Python uasyncio.sleep() Examples
The following are 30
code examples of uasyncio.sleep().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
uasyncio
, or try the search function
.
Example #1
Source File: pbmqtt.py From micropython-mqtt with MIT License | 7 votes |
def _do_rtc(self): lnk = self._lnk lnk.vbprint('Start RTC synchroniser') self._time_valid = not self._rtc_last_syn == 0 # Valid on restart while True: while not self._time_valid: lnk.channel.send(TIME) # Give 5s time for response await asyn.sleep(5) if not self._time_valid: # WiFi may be down. Delay 1 min before retry. await asyn.sleep(60) else: # Valid time received or restart if self._rtc_interval < 0: break # One resync only: done tend = self._rtc_last_syn + self._rtc_interval twait = max(tend - time(), 5) # Prolonged outage await asyn.sleep(twait) self._time_valid = False
Example #2
Source File: webcam.py From esp32-micropython-webcam with Apache License 2.0 | 6 votes |
def index(req, resp): # parse query string req.parse_qs() flash = req.form.get('flash', 'false') if flash == 'true': led.on() camera.init() # wait for sensor to start and focus before capturing image await asyncio.sleep(2) buf = camera.capture() led.off() camera.deinit() if len(buf) > 0: yield from picoweb.start_response(resp, "image/jpeg") yield from resp.awrite(buf) else: picoweb.http_error(resp, 503)
Example #3
Source File: mqtt_as.py From micropython-mqtt with MIT License | 6 votes |
def wan_ok(self, packet=b'$\x1a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'): if not self.isconnected(): # WiFi is down return False length = 32 # DNS query and response packet size s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setblocking(False) s.connect(('8.8.8.8', 53)) await asyncio.sleep(1) try: await self._as_write(packet, sock=s) await asyncio.sleep(2) res = await self._as_read(length, s) if len(res) == length: return True # DNS response size OK except OSError: # Timeout on read: no connectivity. return False finally: s.close() return False
Example #4
Source File: pbmqtt.py From micropython-mqtt with MIT License | 6 votes |
def heartbeat(): led = pyb.LED(1) while True: await asyncio.sleep_ms(500) led.toggle() # Replace to handle status changes. In the case of fatal status values the # ESP8266 will be rebooted on return. You may want to pause for remedial # action before the reboot. Information statuses can be ignored with rapid # return. Cases which may require attention: # SPECNET return 1 to try specified network or 0 to reboot ESP. Code below # tries specified LAN (if default LAN fails) on first run only to limit # flash wear. # BROKER_FAIL Pause for server fix? Return (and so reboot) after delay? # Pauses must be implemented with the following to ensure task quits on fail # if not await self.exit_gate.sleep(delay_in_secs): # return
Example #5
Source File: server.py From micropython-iot with MIT License | 6 votes |
def write(self, line, qos=True, wait=True): if qos and wait: while self._acks_pend: await asyncio.sleep(TIM_TINY) fstr = '{:02x}{}' if line.endswith('\n') else '{:02x}{}\n' mid = next(self._getmid) self._acks_pend.add(mid) # ACK will be removed from ._acks_pend by ._read line = fstr.format(mid, line) # Local copy await self._vwrite(line) # Write verbatim if not qos: # Don't care about ACK. All done. return # qos: pause until ACK received while True: await self._status_coro() # Wait for outage to clear if await self._waitack(mid): return # Got ack, removed from ._acks_pend, all done # Either timed out or an outage started await self._vwrite(line) # Waits for outage to clear self._verbose and print('Repeat', line[2:], 'to server app') # When ._read receives an ACK it is discarded from ._acks_pend. Wait for # this to occur (or an outage to start). Currently use system timeout.
Example #6
Source File: client_r.py From micropython-samples with MIT License | 6 votes |
def run(): global success ok = True try: while ok: res = poller.ipoll(10) for sock, ev in res: if ev & select.POLLIN: r = sock.readline() print(ev, r) # A server outage prints 1, b'' forever on ESP8266 or Unix. # If killer closes socket on ESP8266 ev is always 1, # on Unix get ev == 32 # Never see 9 or 17 (base 10) which are the error responses expected by uasyncio # (POLLIN & POLLERR or POLLIN & POLLHUP) else: # The only way I can make it work (on Unix) is to quit on 32 print('Terminating event:', ev) # What is 32?? ok = False break await asyncio.sleep(0) except OSError: print('Got OSError') # Never happens success = True # Detected socket closure or error by OSError or event
Example #7
Source File: client_w.py From micropython-samples with MIT License | 6 votes |
def run(): global success ok = True try: while ok: res = poller.ipoll(10) for sock, ev in res: if ev & select.POLLOUT: r = sock.send(b'0123456789\n') print(ev, r) # On ESP8266 if another task closes the socket the poll object # never triggers. uasyncio expects it to trigger with POLLHUP or # (POLLOUT & POLLERR or POLLOUT & POLLHUP) # If server fails gets OSError on both platforms. else: # But on Unix socket closure produces ev == 32 print('Terminating event:', ev) # What is 32?? ok = False break await asyncio.sleep(1) await asyncio.sleep(0) except OSError: print('Got OSError') # Happens on ESP8266 if server fails success = True # Detected socket closure or error by OSError or event
Example #8
Source File: server.py From micropython-iot with MIT License | 6 votes |
def _vwrite(self, line): ok = False while not ok: if self._verbose and not self(): print('Writer Client:', self._cl_id, 'awaiting OK status') await self._status_coro() if line is None: line = '\n' # Keepalive. Send now: don't care about loss else: # Aawait client ready after initial or subsequent connection while self._wr_pause: await asyncio.sleep(self._tim_short) async with self._wlock: # >1 writing task? ok = await self._send(line) # Fail clears status # Send a string. Return True on apparent success, False on failure.
Example #9
Source File: asyntest.py From micropython-samples with MIT License | 6 votes |
def run_ack(): message = Message() ack1 = Message() ack2 = Message() count = 0 while True: asyncio.create_task(message_wait(message, ack1, 1)) asyncio.create_task(message_wait(message, ack2, 2)) message.set(count) count += 1 print('message was set') await ack1 ack1.clear() print('Cleared ack1') await ack2 ack2.clear() print('Cleared ack2') message.clear() print('Cleared message') await asyncio.sleep(1)
Example #10
Source File: range_ex.py From micropython-mqtt with MIT License | 6 votes |
def main(client): try: await client.connect() except OSError: print('Connection failed.') return n = 0 s = '{} repubs: {} outages: {} rssi: {}dB free: {}bytes' while True: await asyncio.sleep(5) gc.collect() m = gc.mem_free() print('publish', n) # If WiFi is down the following will pause for the duration. await client.publish(TOPIC, s.format(n, client.REPUB_COUNT, outages, rssi, m), qos = 1) n += 1 # Define configuration
Example #11
Source File: range_ex.py From micropython-mqtt with MIT License | 6 votes |
def get_rssi(): global rssi s = network.WLAN() ssid = config['ssid'].encode('UTF8') while True: try: rssi = [x[3] for x in s.scan() if x[0] == ssid][0] except IndexError: # ssid not found. rssi = -199 await asyncio.sleep(30)
Example #12
Source File: asyn.py From micropython-mqtt with MIT License | 6 votes |
def sleep(t, granularity=100): # 100ms default if granularity <= 0: raise ValueError('sleep granularity must be > 0') t = int(t * 1000) # ms if t <= granularity: await asyncio.sleep_ms(t) else: n, rem = divmod(t, granularity) for _ in range(n): await asyncio.sleep_ms(granularity) await asyncio.sleep_ms(rem) # Anonymous cancellable tasks. These are members of a group which is identified # by a user supplied name/number (default 0). Class method cancel_all() cancels # all tasks in a group and awaits confirmation. Confirmation of ending (whether # normally or by cancellation) is signalled by a task calling the _stopped() # class method. Handled by the @cancellable decorator.
Example #13
Source File: s_app_cp.py From micropython-iot with MIT License | 5 votes |
def writer(self): print('Started writer') count = 0 while True: self.data[0] = count count += 1 print('Sent', self.data, 'to remote', self.client_id, '\n') # .write() behaves as per .readline() await self.conn.write(json.dumps(self.data)) await asyncio.sleep(5)
Example #14
Source File: test_fast_scheduling.py From micropython-samples with MIT License | 5 votes |
def dummy(self): while True: await asyncio.sleep(0) self.dummy_count += 1 utime.sleep_ms(10) # Emulate time consuming user code
Example #15
Source File: asyntest.py From micropython-samples with MIT License | 5 votes |
def ack_coro(delay): print('Started ack coro with delay', delay) await asyncio.sleep(delay) print("I've seen attack ships burn on the shoulder of Orion...") print("Time to die...")
Example #16
Source File: server.py From micropython-iot with MIT License | 5 votes |
def _waitack(self, mid): tstart = time.time() # Wait for ACK while mid in self._acks_pend: await asyncio.sleep(TIM_TINY) if not self() or ((time.time() - tstart) > self._to_secs): self._verbose and print('waitack timeout', mid) return False # Outage or ACK not received in time return True # Verbatim write: add no message ID.
Example #17
Source File: asyntest.py From micropython-samples with MIT License | 5 votes |
def messageset(message): print('Waiting 5 secs before setting message') await asyncio.sleep(5) message.set() print('message was set')
Example #18
Source File: asyntest.py From micropython-samples with MIT License | 5 votes |
def run_lock(n, lock): print('run_lock {} waiting for lock'.format(n)) await lock.acquire() print('run_lock {} acquired lock'.format(n)) await asyncio.sleep(1) # Delay to demo other coros waiting for lock lock.release() print('run_lock {} released lock'.format(n))
Example #19
Source File: asyntest.py From micropython-samples with MIT License | 5 votes |
def killer(duration): await asyncio.sleep(duration)
Example #20
Source File: s_qos_fast.py From micropython-iot with MIT License | 5 votes |
def writer(self): print('Started writer') count = 0 while True: for _ in range(4): data = [self.tx_msg_id, count] self.tx_msg_id += 1 count += 1 await self.conn # Only launch write if link is up print('Sent {} to remote {}\n'.format(data, self.client_id)) asyncio.create_task(self.conn.write(json.dumps(data), wait=False)) await asyncio.sleep(3.95)
Example #21
Source File: server.py From micropython-iot with MIT License | 5 votes |
def _keepalive(self): while True: await self._vwrite(None) await asyncio.sleep(self._tim_ka)
Example #22
Source File: server.py From micropython-iot with MIT License | 5 votes |
def _status_coro(self): while not self(): await asyncio.sleep(self._tim_short)
Example #23
Source File: server.py From micropython-iot with MIT License | 5 votes |
def _client_active(self): await asyncio.sleep(0.2) # Let ESP get out of bed. self._wr_pause = False
Example #24
Source File: server.py From micropython-iot with MIT License | 5 votes |
def wait_all(cls, client_id=None, peers=None): conn = None if client_id is not None: conn = await client_conn(client_id) if peers is None: # Wait for all expected clients while cls._expected: await asyncio.sleep(0.5) else: while not set(cls._conns.keys()).issuperset(peers): await asyncio.sleep(0.5) return conn
Example #25
Source File: server.py From micropython-iot with MIT License | 5 votes |
def client_conn(cls, client_id): while True: if client_id in cls._conns: c = cls._conns[client_id] # await c # works but under CPython produces runtime warnings. So do: await c._status_coro() return c await asyncio.sleep(0.5) # App waits for all expected clients to connect.
Example #26
Source File: server.py From micropython-iot with MIT License | 5 votes |
def run(expected, verbose=False, port=8123, timeout=2000): addr = socket.getaddrinfo('0.0.0.0', port, 0, socket.SOCK_STREAM)[0][-1] s_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # server socket s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s_sock.bind(addr) s_sock.listen(len(expected) + 2) verbose and print('Awaiting connection.', port) poller = select.poll() poller.register(s_sock, select.POLLIN) to_secs = timeout / 1000 # ms -> secs while True: res = poller.poll(1) # 1ms block if res: # Only s_sock is polled c_sock, _ = s_sock.accept() # get client socket c_sock.setblocking(False) try: data = await _readid(c_sock, to_secs) except OSError: c_sock.close() else: Connection.go(to_secs, data, verbose, c_sock, s_sock, expected) await asyncio.sleep(0.2) # A Connection persists even if client dies (minimise object creation). # If client dies Connection is closed: ._close() flags this state by closing its # socket and setting .sock to None (.status() == False).
Example #27
Source File: asi2c_i.py From micropython-iot with MIT License | 5 votes |
def _run(self): while True: # If hardware link exists reboot Responder await self.reboot() self.txbyt = b'' self.rxbyt = b'' await self._sync() await asyncio.sleep(1) # Ensure Responder is ready if self.cr_go: asyncio.create_task(self.cr_go(*self.go_args)) while True: gc.collect() try: tstart = utime.ticks_us() self._sendrx() t = utime.ticks_diff(utime.ticks_us(), tstart) except OSError: # Reboot remote. break await asyncio.sleep_ms(Initiator.t_poll) self.block_max = max(self.block_max, t) # self measurement self.block_cnt += 1 self.block_sum += t self.nboots += 1 if self.cr_fail: await self.cr_fail(*self.f_args) if self.reset is None: # No means of recovery raise OSError('Responder fail.')
Example #28
Source File: s_app.py From micropython-iot with MIT License | 5 votes |
def writer(self): print('Started writer') count = 0 while True: self.data[0] = count count += 1 print('Sent', self.data, 'to remote', self.client_id, '\n') # .write() behaves as per .readline() await self.conn.write(json.dumps(self.data)) await asyncio.sleep(5)
Example #29
Source File: asi2c.py From micropython-iot with MIT License | 5 votes |
def _sync(self): self.verbose and print('Synchronising') self.own(0) while self.rem(): await asyncio.sleep_ms(100) # Both pins are now low await asyncio.sleep(0) self.verbose and print('Synchronised') self.synchronised = True
Example #30
Source File: app_base.py From micropython-iot with MIT License | 5 votes |
def server_ok(self, up): await asyncio.sleep(0) print('Server is {}'.format('up' if up else 'down'))