def test(use_priority=True): global after, after_ms, lp_version, loop target_delay = 10 # Nominal delay in priority task (ms) processing_delay = 2 # Processing time in low priority task (ms) if use_priority and not lp_version: print('To test priority mechanism you must use asyncio_priority.py') else: ntasks = max(num_coros) + 4 if use_priority: loop = asyncio.get_event_loop(ntasks, ntasks, ntasks) after = asyncio.after after_ms = asyncio.after_ms else: lp_version = False after = asyncio.sleep after_ms = asyncio.sleep_ms loop = asyncio.get_event_loop(ntasks, ntasks) s = 'Testing accuracy of {}ms nominal delay with coros blocking for {}ms.' print(s.format(target_delay, processing_delay)) if lp_version: print('Using priority mechanism.') else: print('Not using priority mechanism.') loop.create_task(run_test(processing_delay, target_delay)) loop.run_until_complete(report(target_delay))
def __init__(self, pin): self.pin = pin # Should be initialised for input with pullup self._open_func = False self._close_func = False self.switchstate = self.pin.value() # Get initial state loop = asyncio.get_event_loop() loop.create_task(self.switchcheck()) # Thread runs forever
def trigger(self, duration): # Update end time loop = asyncio.get_event_loop() self.tstop = time.ticks_add(loop.time(), duration) if not self._running: # Start a task which stops the delay after its period has elapsed loop.create_task(self.killer()) self._running = True
async def buttoncheck(self): loop = asyncio.get_event_loop() if self._long_func: longdelay = Delay_ms(self._long_func, self._long_args) if self._double_func: doubledelay = Delay_ms() while True: state = self.rawstate() # State has changed: act on it now. if state != self.buttonstate: self.buttonstate = state if state: # Button is pressed if self._long_func and not longdelay.running(): # Start long press delay longdelay.trigger(Pushbutton.long_press_ms) if self._double_func: if doubledelay.running(): launch(self._double_func, self._double_args) else: # First click: start doubleclick timer doubledelay.trigger(Pushbutton.double_click_ms) if self._true_func: launch(self._true_func, self._true_args) else: # Button release if self._long_func and longdelay.running(): # Avoid interpreting a second click as a long push longdelay.stop() if self._false_func: launch(self._false_func, self._false_args) # Ignore state changes until switch has settled await asyncio.sleep_ms(Pushbutton.debounce_ms)
def __init__(self, gatherables): ncoros = len(gatherables) self.barrier = Barrier(ncoros + 1) self.results = [None] * ncoros loop = asyncio.get_event_loop() for n, gatherable in enumerate(gatherables): loop.create_task(self.wrap(gatherable, n)())
def _cancel(cls, task_no): # pend_throw() does nothing if the task does not exist # (because it has terminated). task = cls.tasks[task_no][0] prev = task.pend_throw(StopTask()) # Instantiate exception if prev is False: loop = asyncio.get_event_loop() loop.call_soon(task)
def __init__(self, func=None, args=(), can_alloc=True): self.func = func self.args = args self.can_alloc = can_alloc self.tstop = None # Not running self.loop = asyncio.get_event_loop() if not can_alloc: self.loop.create_task(self._run())
async def run_test(): loop = asyncio.get_event_loop() loop.call_after(1, cb, 'One second has elapsed.') # Test args loop.call_after_ms(500, cb, ('500ms has elapsed.', )) print('Callbacks scheduled.') while True: loop.call_after(0, callback, pyb.rng()) # demo use of args yield 20 # 20ms
def __init__(self, pin): self.pin = pin # Initialise for input self._true_func = False self._false_func = False self._double_func = False self._long_func = False self.sense = pin.value() # Convert from electrical to logical value self.buttonstate = self.rawstate() # Initial state loop = asyncio.get_event_loop() loop.create_task(self.buttoncheck()) # Thread runs forever
async def killer(self): loop = asyncio.get_event_loop() twait = time.ticks_diff(self.tstop, loop.time()) while twait > 0 and self._running: # Return if stop() called during wait # Must loop here: might be retriggered await asyncio.sleep_ms(twait) twait = time.ticks_diff(self.tstop, loop.time()) if self._running and self.func is not None: launch(self.func, self.args) # Execute callback self._running = False
async def run_cancel_test(): loop = asyncio.get_event_loop() await asyn.NamedTask('foo 0', foo, 0) loop.create_task(asyn.NamedTask('foo 1', foo, 1)()) loop.create_task(bar()) await asyncio.sleep(5) await asyn.NamedTask('foo 2', foo, 2) await asyn.NamedTask('foo 4', foo, 4) loop.create_task(asyn.NamedTask('foo 3', foo, 3)()) await asyncio.sleep(5)
async def run_cancel_test(): loop = asyncio.get_event_loop() await NamedTask(foo(0), 'foo 0') loop.create_task(NamedTask(foo(1), 'foo 1').task) loop.create_task(bar()) await asyncio.sleep(5) await NamedTask(foo(2), 'foo 2') await foo(5) loop.create_task(NamedTask(foo(3), 'foo 3').task) await asyncio.sleep(5)
def test_swcb(): print('Test of switch executing callbacks.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) sw = Switch(pin) # Register a coro to launch on contact close sw.close_func(toggle, (red,)) sw.open_func(toggle, (green,)) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def test(duration): loop = asyncio.get_event_loop() duration = int(duration) if duration > 0: print("Flash LED's for {:3d} seconds".format(duration)) leds = [pyb.LED(x) for x in range(1, 5)] # Initialise all four on board LED's for x, led in enumerate(leds): # Create a coroutine for each LED t = int((0.2 + x / 2) * 1000) loop.create_task(toggle(leds[x], t)) loop.run_until_complete(killer(duration)) loop.close()
def pend_throw(cls, taskname, ClsException): if taskname in cls.tasks: # pend_throw() does nothing if the task does not exist # (because it has terminated). # Enable throwing arbitrary exceptions loop = asyncio.get_event_loop() task = cls.tasks.pop(taskname) prev = task.pend_throw(ClsException()) # Instantiate exception if prev is False: loop.call_soon(task) return True return False
def test_sw(): print('Test of switch scheduling coroutines.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) sw = Switch(pin) # Register coros to launch on contact close and open sw.close_func(pulse, (green, 1000)) sw.open_func(pulse, (red, 1000)) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
async def switchcheck(self): loop = asyncio.get_event_loop() while True: state = self.pin.value() if state != self.switchstate: # State has changed: act on it now. self.switchstate = state if state == 0 and self.close_func: launch(self._close_func, self._close_args) elif state == 1 and self._open_func: launch(self._open_func, self._open_args) # Ignore further state changes until switch has settled await asyncio.sleep_ms(Switch.debounce_ms)
async def accel_coro(timeout=2000): loop = asyncio.get_event_loop() accelhw = pyb.Accel() # Instantiate accelerometer hardware await asyncio.sleep_ms(30) # Allow it to settle accel = Accelerometer(accelhw, timeout) while True: result = accel.poll() if result == 0: # Value has changed x, y, z = accel.vector() print("Value x:{:3d} y:{:3d} z:{:3d}".format(x, y, z)) elif accel.timed_out(): # Report every 2 secs print("Timeout waiting for accelerometer change") await asyncio.sleep_ms(100) # Poll every 100ms
def test_btn(): print('Test of pushbutton scheduling coroutines.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) yellow = LED(3) blue = LED(4) pb = Pushbutton(pin) pb.press_func(pulse, (red, 1000)) pb.release_func(pulse, (green, 1000)) pb.double_func(pulse, (yellow, 1000)) pb.long_func(pulse, (blue, 1000)) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def test_btncb(): print('Test of pushbutton executing callbacks.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) yellow = LED(3) blue = LED(4) pb = Pushbutton(pin) pb.press_func(toggle, (red,)) pb.release_func(toggle, (green,)) pb.double_func(toggle, (yellow,)) pb.long_func(toggle, (blue,)) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def test(): printexp( '''Starting foo 0 foo 0 ran to completion. Starting foo 1 foo 0 was not cancellable. foo 1 will be cancelled when next scheduled foo 3 was not cancellable. foo 1 was cancelled. Starting foo 2 foo 2 ran to completion. Starting foo 4 foo 4 ran to completion. Starting foo 3 foo 3 ran to completion. ''', 14) loop = asyncio.get_event_loop() loop.run_until_complete(run_cancel_test())
try: import asyncio_priority as asyncio except ImportError: import uasyncio as asyncio count = 0 period = 5 async def foo(n): global count while True: # yield await asyncio.sleep_ms(0) count += 1 print('Foo', n) async def main(delay): print('Testing for {} seconds'.format(period)) await asyncio.sleep(delay) loop = asyncio.get_event_loop() loop.create_task(foo(1)) loop.create_task(foo(2)) loop.create_task(foo(3)) loop.run_until_complete(main(period)) print('Coro executions per sec =', count / period)
for x, n in enumerate(num_coros): print('Coros {:4d} Iterations/sec {:5d} Duration {:3d}us'.format( n, int(iterations[x] / duration), int(duration * 1000000 / iterations[x]))) async def foo(): global count while True: yield count += 1 async def test(): global count, done old_n = 0 for n, n_coros in enumerate(num_coros): print('Testing {} coros for {}secs'.format(n_coros, duration)) count = 0 for _ in range(n_coros - old_n): loop.create_task(foo()) old_n = n_coros await asyncio.sleep(duration) iterations[n] = count done = True loop = asyncio.get_event_loop(max(num_coros) + 2) loop.create_task(test()) loop.run_until_complete(report())
def launch(func, tup_args): res = func(*tup_args) if isinstance(res, type_coro): loop = asyncio.get_event_loop() loop.create_task(res)
def __init__(self, accelhw, timeout): self.loop = asyncio.get_event_loop() self.accelhw = accelhw self.timeout = timeout self.last_change = self.loop.time() self.coords = [accelhw.x(), accelhw.y(), accelhw.z()]
print('Coros {:4d} Iterations/sec {:5d} Duration {:3d}us'.format( n, int(iterations[x] / duration), int(duration * 1000000 / iterations[x]))) async def foo(): global count while True: yield count += 1 async def test(): global count, done old_n = 0 for n, n_coros in enumerate(num_coros): print('Testing {} coros for {}secs'.format(n_coros, duration)) count = 0 for _ in range(n_coros - old_n): loop.create_task(foo()) old_n = n_coros await asyncio.sleep(duration) iterations[n] = count done = True ntasks = max(num_coros) + 3 loop = asyncio.get_event_loop(ntasks, ntasks) loop.create_task(test()) loop.run_until_complete(report())
global tmax, tmin device = DummyDeviceDriver() while True: await asyncio.sleep_ms(100) gc.collect() # For precise timing tstart = time.ticks_us() await device # Measure the latency delta = time.ticks_diff(time.ticks_us(), tstart) tmax = max(tmax, delta) tmin = min(tmin, delta) # Ensure coros are running before we start the timer and measurement. async def report(): await asyncio.sleep_ms(100) tim.init(freq=10) tim.callback(trig) await asyncio.sleep(2) print('Max latency of urgent tasks: {}us'.format(max_latency)) print('Latency of normal tasks: {:6.2f}ms max {:6.2f}ms min.'.format(tmax / 1000, tmin / 1000)) tim.deinit() print('Test runs for two seconds.') loop = asyncio.get_event_loop(hpqlen = n_hp_tasks) #loop.allocate_hpq(n_hp_tasks) # Allocate a (small) high priority queue loop.create_task(norm_latency()) # Measure latency of a normal task for _ in range(n_tasks): loop.create_task(normal_task(1)) # Hog CPU for 1ms for n in range(n_hp_tasks): loop.create_task(urgent(n)) loop.run_until_complete(report())