"""The box's LED: on while the mics are open, blinking while the agent thinks, double-flashing while it looks. run() draws it from the state, so looking can show over thinking, and give way. """ from contextlib import contextmanager BLINK_S = 0.25 # thinking: on and off, twice a second LOOK_FLASHES = ((0.0, 0.1), (0.2, 0.3)) # looking: two quick flashes... LOOK_PERIOD_S = 0.8 # ...each 0.8 s def led_at(mics, thinking, looking, t): """Whether the LED is lit at time t (seconds): looking outranks thinking, which outranks the mics. Looking double-flashes: >>> [led_at(False, False, True, t / 10) for t in range(8)] [True, False, True, False, False, False, False, False] Thinking blinks twice a second; otherwise the LED shows whether the mics are open: >>> [led_at(True, True, False, t / 4) for t in range(4)] [True, False, True, False] >>> led_at(True, False, False, 7.3), led_at(False, False, False, 7.3) (True, False) """ if looking: phase = t % LOOK_PERIOD_S return any(start <= phase < stop for start, stop in LOOK_FLASHES) if thinking: return int(t / BLINK_S) % 2 == 0 return mics class Light: """The LED's state; run() draws it, on the event loop. >>> light = Light(set_led=print, monotonic=lambda: 0.0, sleep=None) >>> light.lit() False >>> light.mics(True) >>> light.lit() True >>> with light.looking(): ... light.looking_now() True >>> light.looking_now() False """ def __init__(self, set_led, monotonic, sleep): self.__set, self.__monotonic, self.__sleep = set_led, monotonic, sleep self.__mics = self.__thinking = False self.__looks = 0 def mics(self, on): self.__mics = on def thinking(self, on): self.__thinking = on @contextmanager def looking(self): self.__looks += 1 try: yield finally: self.__looks -= 1 def looking_now(self): return self.__looks > 0 def lit(self): return led_at(self.__mics, self.__thinking, self.looking_now(), self.__monotonic()) async def run(self): shown = None while True: want = self.lit() if want != shown: self.__set(want) shown = want await self.__sleep(0.02)