Python uasyncio.CancelledError() Examples
The following are 18
code examples of uasyncio.CancelledError().
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: lock.py From micropython-samples with MIT License | 6 votes |
def acquire(self): if self._locked or self._awt: # Lock set or just released but has tasks waiting on it, # put the calling task on the Lock's waiting queue and yield self.save_current() try: yield except uasyncio.CancelledError: if self._awt is uasyncio.cur_task: # Task that was going to acquire got cancelled after being scheduled. # Schedule next waiting task self._locked = True self.release() raise self._locked = True return True
Example #2
Source File: rfpump.py From pysmartnode with MIT License | 6 votes |
def _wait_off(self): print("wait_off started") st = time.ticks_ms() try: while time.ticks_ms() - st < self._on_time * 1000: await asyncio.sleep(1) except asyncio.CancelledError: self._log.debug("_wait_off canceled", local_only=True) print("wait_off canceled") return except Exception as e: await self._log.asyncLog("error", "wait_off error: {!s}".format(e)) return False finally: print("wait_off exited") await super().on_message(self._topic, "OFF", False)
Example #3
Source File: rfpump.py From pysmartnode with MIT License | 6 votes |
def _repeating(self): print("repeating started") self._repeating_mode = True try: while True: st = time.ticks_ms() await super().on_message(self._topic, "ON", False) while time.ticks_ms() - st < self._on_time * 1000: await asyncio.sleep(1) await super().on_message(self._topic, "OFF", False) st = time.ticks_ms() while time.ticks_ms() - st < self._off_time * 1000: await asyncio.sleep(1) except asyncio.CancelledError: print("repeating canceled") self._log.debug("_repeating canceled", local_only=True) except Exception as e: await self._log.asyncLog("error", "_repeating error: {!s}".format(e)) finally: await super().on_message(self._topic, "OFF", False) self._repeating_mode = False print("repeating exited")
Example #4
Source File: mqtt.py From pysmartnode with MIT License | 6 votes |
def _connected_handler(self, client): try: await self.publish(self.getDeviceTopic(config.MQTT_AVAILABILITY_SUBTOPIC), "online", qos=1, retain=True) # if it hangs here because connection is lost, it will get canceled when reconnected. if self.__first_connect is True: # only log on first connection, not on reconnect as nothing has changed here await _log.asyncLog("info", str(os.name if platform == "linux" else os.uname())) await _log.asyncLog("info", "Client version: {!s}".format(config.VERSION)) self.__first_connect = False elif self.__first_connect is False: await _log.asyncLog("debug", "Reconnected") # resubscribe topics because clean session is used if self._sub_coro is not None: asyncio.cancel(self._sub_coro) self._sub_coro = self._subscribeTopics() asyncio.get_event_loop().create_task(self._sub_coro) for cb in self._reconnected_subs: res = cb(client) if type(res) == type_gen: await res self._connected_coro = None except asyncio.CancelledError: if self._sub_coro is not None: asyncio.cancel(self._sub_coro)
Example #5
Source File: repeating.py From pysmartnode with MIT License | 6 votes |
def _repeating(self, component_on, component_off): print("repeating started") try: while True: st = time.ticks_ms() await component_on() while time.ticks_diff(time.ticks_ms(), st) < self._on_time * 1000: await asyncio.sleep(0.2) await component_off() st = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), st) < self._off_time * 1000: await asyncio.sleep(0.2) except asyncio.CancelledError: print("repeating canceled") finally: await component_off() self._coro = None print("repeating exited")
Example #6
Source File: safety_off.py From pysmartnode with MIT License | 5 votes |
def _wait_off(self, component_off): print("wait_off started") st = time.ticks_ms() try: while time.ticks_diff(time.ticks_ms(), st) < self._on_time * 1000: await asyncio.sleep(0.2) except asyncio.CancelledError: print("wait_off canceled") finally: self._coro = None # prevents cancelling the cancelled coro await component_off() print("wait_off exited")
Example #7
Source File: fast_can_test.py From micropython-async with MIT License | 5 votes |
def lpfoo(t): try: print('lpfoo started') await asyncio.after(t) print('lpfoo ended', t) except asyncio.CancelledError: print('lpfoo cancelled', t)
Example #8
Source File: iorw_can.py From micropython-async with MIT License | 5 votes |
def sender(myiow): swriter = asyncio.StreamWriter(myiow, {}) await asyncio.sleep(1) count = 0 try: # Trap in outermost scope to catch cancellation of .sleep while True: count += 1 tosend = 'Wrote Hello MyIO {}\n'.format(count) await swriter.awrite(tosend.encode('UTF8')) await asyncio.sleep(2) except asyncio.CancelledError: print('Sender cancelled')
Example #9
Source File: iorw_can.py From micropython-async with MIT License | 5 votes |
def receiver(myior): sreader = asyncio.StreamReader(myior) try: while True: res = await sreader.readline() print('Received', res) except asyncio.CancelledError: print('Receiver cancelled')
Example #10
Source File: gather.py From micropython-async with MIT License | 5 votes |
def bar(n): print('Start cancellable bar()') try: while True: await asyncio.sleep(1) n += 1 except asyncio.CancelledError: # Demo of trapping print('Trapped bar cancellation.') raise return n
Example #11
Source File: gather.py From micropython-async with MIT License | 5 votes |
def foo(n): print('Start timeout coro foo()') try: while True: await asyncio.sleep(1) n += 1 except asyncio.CancelledError: print('Trapped foo timeout.') raise return n
Example #12
Source File: asyntest.py From micropython-async with MIT License | 5 votes |
def my_coro(text): try: await asyncio.sleep_ms(0) while True: await asyncio.sleep(1) print(text) except asyncio.CancelledError: print('my_coro was cancelled.')
Example #13
Source File: remoteConfig.py From pysmartnode with MIT License | 5 votes |
def _watcher(self): mqtt = _mqtt mqtt.subscribeSync(self._topic, self.on_message, self) try: while True: while mqtt.isconnected() is False: await asyncio.sleep(1) if await mqtt.awaitSubscriptionsDone(await_connection=False): _log.debug("waiting for config", local_only=True) await _mqtt.publish( "{!s}/login/{!s}/set".format(mqtt.mqtt_home, mqtt.client_id), [config.VERSION, platform, WAIT]) gc.collect() else: await asyncio.sleep(20) continue for _ in range(120): if mqtt.isconnected() is False: break await asyncio.sleep(1) # so that it can be cancelled properly every second except asyncio.CancelledError: if config.DEBUG is True: _log.debug("_watcher cancelled", local_only=True) except Exception as e: await _log.asyncLog("error", "Error watching remoteConfig:", e) finally: await mqtt.unsubscribe(self._topic, self) self._done = True
Example #14
Source File: asnano_sync.py From micropython-nano-gui with MIT License | 5 votes |
def flash(n, t): led = pyb.LED(n) try: while True: led.toggle() await asyncio.sleep_ms(t) except asyncio.CancelledError: led.off() # Demo tidying up on cancellation.
Example #15
Source File: mqtt.py From pysmartnode with MIT License | 5 votes |
def _preprocessor(self, coroutine, *args, timeout=None, await_connection=True): coro = None start = time.ticks_ms() i = 0 if len(args) == 4 else 1 # 0: publish, 1:(un)sub try: while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout * 1000: if not await_connection and not self._isconnected: return False if self._ops_coros[i] is coro is None: coro = self._operationTimeout(coroutine, *args, i=i) asyncio.get_event_loop().create_task(coro) self._ops_coros[i] = coro elif coro: if self._ops_coros[i] != coro: return True # published await asyncio.sleep_ms(20) _log.debug("timeout on", "(un)sub" if i else "publish", args, local_only=True) self.__timedout += 1 except asyncio.CancelledError: raise # the caller should be cancelled too finally: if coro and self._ops_coros[i] == coro: async with self.lock: asyncio.cancel(coro) return False # else: returns value during process return False
Example #16
Source File: mqtt.py From pysmartnode with MIT License | 5 votes |
def _operationTimeout(self, coro, *args, i): try: await coro(*args) except asyncio.CancelledError: raise # in case the calling function need to handle Cancellation too finally: self._ops_coros[i] = None
Example #17
Source File: test_can.py From micropython-samples with MIT License | 5 votes |
def foo(n): try: while True: await asyncio.sleep(0) print(n) except asyncio.CancelledError: print('Task {} canned.'.format(n)) raise
Example #18
Source File: server.py From tinyweb with MIT License | 5 votes |
def _tcp_server(self, host, port, backlog): """TCP Server implementation. Opens socket for accepting connection and creates task for every new accepted connection """ addr = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0][-1] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(False) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(addr) sock.listen(backlog) try: while True: yield asyncio.IORead(sock) csock, caddr = sock.accept() csock.setblocking(False) # Start handler / keep it in the map - to be able to # shutdown gracefully - by close all connections self.processed_connections += 1 hid = id(csock) handler = self._handler(asyncio.StreamReader(csock), asyncio.StreamWriter(csock, {})) self.conns[hid] = handler self.loop.create_task(handler) # In case of max concurrency reached - temporary pause server: # 1. backlog must be greater than max_concurrency, otherwise # client will got "Connection Reset" # 2. Server task will be resumed whenever one active connection finished if len(self.conns) == self.max_concurrency: # Pause yield False except asyncio.CancelledError: return finally: sock.close()