check / check (push) Canceled after 0s
The box within reach of the couch: a Raspberry Pi 3B with the AIY Voice HAT, from the first household's configuration, made generic. - box/body: the button service, in Python: press and talk, turns by voice, a press interrupts; the look signal - box/*.js: the ir and look capabilities, behind gates, for the brain; the ask client, the box's side of a conversation - box/module.nix: the services, each confined to the devices and addresses it needs; the private network as an option (a tailnet by default); the Pico found by its USB IDs, as /dev/pdtv26-ir - box/voicehat.nix: the Voice HAT's device tree overlay and ALSA setup - lib.mkBox: a box's whole system from its name, the home server's, the Wi-Fi network's, and who looks after it - checks: box-js, box-py (doctests and pyflakes), and box-system (an example box's system evaluates) Generated-by: Claude Opus 5.5
92 lines
3.2 KiB
Python
92 lines
3.2 KiB
Python
"""The box's reports to a status page: ready, each conversation, each look, and a heartbeat.
|
|
|
|
Reports wait in a queue, so a slow status server never holds the box up. A failure is logged when it
|
|
starts, and again when reports get through.
|
|
"""
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
from urllib.parse import urlsplit
|
|
|
|
HEARTBEAT_S = 60
|
|
|
|
|
|
def poster(open_connection, url):
|
|
"""post(path, body): POST body, as JSON, to path on url's server, and no other.
|
|
|
|
open_connection is asyncio.open_connection, or a fake:
|
|
|
|
>>> class Writer:
|
|
... def write(self, data): pass
|
|
... async def drain(self): pass
|
|
... def close(self): pass
|
|
... async def wait_closed(self): pass
|
|
>>> def server(status):
|
|
... class Reader:
|
|
... async def readline(self): return status
|
|
... async def connect(host, port): return Reader(), Writer()
|
|
... return connect
|
|
|
|
Any 2xx is success; the rest raise:
|
|
|
|
>>> asyncio.run(poster(server(b"HTTP/1.1 204 No Content\\r\\n"), "http://home:8027")("/heartbeat", {}))
|
|
>>> post = poster(server(b"HTTP/1.1 400 Bad Request\\r\\n"), "http://home:8027")
|
|
>>> asyncio.run(post("/event", {"kind": "look"}))
|
|
Traceback (most recent call last):
|
|
...
|
|
OSError: /event: HTTP/1.1 400 Bad Request
|
|
"""
|
|
parts = urlsplit(url)
|
|
host, port, base = parts.hostname, parts.port or 80, parts.path.rstrip("/")
|
|
|
|
async def post(path, body):
|
|
data = json.dumps(body).encode()
|
|
reader, writer = await asyncio.wait_for(open_connection(host, port), 10)
|
|
try:
|
|
writer.write(f"POST {base}{path} HTTP/1.1\r\nHost: {host}\r\n"
|
|
f"Content-Type: application/json\r\nContent-Length: {len(data)}\r\n"
|
|
"Connection: close\r\n\r\n".encode() + data)
|
|
await writer.drain()
|
|
status = (await asyncio.wait_for(reader.readline(), 10)).decode().strip()
|
|
finally:
|
|
writer.close()
|
|
await writer.wait_closed()
|
|
code = status.split(" ")[1:2]
|
|
if not (code and code[0].startswith("2")):
|
|
raise OSError(f"{path}: {status}")
|
|
return post
|
|
|
|
|
|
def ignore(kind, **data):
|
|
"""note(kind, ...) for a box with no status page: it goes nowhere."""
|
|
|
|
|
|
class Status:
|
|
"""note(kind, ...) queues an event; run() sends what's queued; heartbeat() queues one a minute."""
|
|
|
|
def __init__(self, post, sleep):
|
|
self.__post, self.__sleep = post, sleep
|
|
self.__q = asyncio.Queue()
|
|
|
|
def note(self, kind, **data):
|
|
self.__q.put_nowait(("/event", {"kind": kind, "source": "pdtv26-button", **data}))
|
|
|
|
async def heartbeat(self):
|
|
while True:
|
|
self.__q.put_nowait(("/heartbeat", {}))
|
|
await self.__sleep(HEARTBEAT_S)
|
|
|
|
async def run(self):
|
|
failing = False
|
|
while True:
|
|
path, body = await self.__q.get()
|
|
try:
|
|
await self.__post(path, body)
|
|
if failing:
|
|
logging.info("status: reports get through again")
|
|
failing = False
|
|
except (OSError, asyncio.TimeoutError) as err:
|
|
if not failing:
|
|
logging.info(f"status: report failed: {err}")
|
|
failing = True
|