"""The box's button: presses, queued as they come, whatever the box is doing.""" import asyncio PRESSED = "pressed" # what race() returns when the button wins class Presses: """Turn (falling?, t_ns) edges into ("down", t_ns) and ("up", held_s) events. Repeated edges in one direction (bounce that outlasts the debounce) are ignored, as is a release before any press. >>> p = Presses() >>> [p.edge(*e) for e in [(False, 0), (True, 10), (True, 11), (False, 2_510_000_000)]] [None, ('down', 10), None, ('up', 2.51)] """ def __init__(self): self.down_at = None def edge(self, falling, t_ns): if falling and self.down_at is None: self.down_at = t_ns return ("down", t_ns) if not falling and self.down_at is not None: held = round((t_ns - self.down_at) / 1e9, 2) self.down_at = None return ("up", held) return None class Button: """feed(edges) queues presses; wait() awaits one; pressed() doesn't wait; race(aw) awaits aw unless the button is pressed first. >>> async def demo(): ... b = Button() ... b.feed([(True, 1), (False, 2)]) ... first = await b.race(asyncio.sleep(9, "slept")) ... second = await b.race(asyncio.sleep(0, "slept")) ... return first, second, b.pressed() >>> asyncio.run(demo()) ('pressed', 'slept', False) """ def __init__(self): self.__presses = Presses() self.__q = asyncio.Queue() def feed(self, edges): for edge in edges: if (self.__presses.edge(*edge) or ("",))[0] == "down": self.__q.put_nowait(True) async def wait(self): await self.__q.get() def pressed(self): """Whether there were any presses since last asked; forgets them.""" hit = False while not self.__q.empty(): self.__q.get_nowait() hit = True return hit async def race(self, aw, timeout=None): """aw's result; or PRESSED if the button is pressed first; TimeoutError after timeout s.""" work = asyncio.ensure_future(aw) if self.pressed(): work.cancel() return PRESSED press = asyncio.ensure_future(self.__q.get()) done, pending = await asyncio.wait({work, press}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED) for p in pending: p.cancel() if press in done: return PRESSED if work in done: return work.result() raise TimeoutError(f"nothing in {timeout} s")