"""What the box hears, and the brain: each a client bound to its one server. The clients take their keys from systemd's credentials, not argv. """ import json import logging from button import PRESSED ANSWER_S = 150 # the channel gives up at 120 s class Hear: """transcribe(wav): the speech capability (hear-client, bound to its URL).""" def __init__(self, hear_client): self.__client = hear_client async def transcribe(self, wav): return (await self.__client.run(stdin=wav)).decode() def answer(line): """One line from ask-client, as converse takes it. >>> answer(b'{"say": "Let me try."}') ('say', 'Let me try.') >>> answer(b'{"reply": "Bye!", "end": true}') ('reply', 'Bye!', True) """ event = json.loads(line) if "say" in event: return ("say", event["say"]) return ("reply", event["reply"], bool(event.get("end"))) class Brain: """ask(text, convo) yields ("say", text)s, then ("reply", text, end); or ("press",). end(convo) tells the brain the conversation is over. ask_client is a Command for ask-client, bound to the brain's ask capability. """ def __init__(self, ask_client, button): self.__client, self.__button = ask_client, button async def ask(self, text, convo): proc = await self.__client.spawn(convo) proc.stdin.write(text.encode()) await proc.stdin.drain() proc.stdin.close() try: while True: line = await self.__button.race(proc.stdout.readline(), timeout=ANSWER_S) if line is PRESSED: yield ("press",) return if not line: await proc.wait() err = (await proc.stderr.read()).decode().strip() raise IOError(f"ask-client exit {proc.returncode}: {err}") event = answer(line) yield event if event[0] == "reply": return finally: if proc.returncode is None: proc.kill() await proc.wait() async def end(self, convo): try: await self.__client.run(convo, "end", timeout=15) except Exception as err: logging.info(f"{convo}: telling the brain it ended failed: {err}")