diff options
| -rwxr-xr-x | agent-lamp | 270 |
1 files changed, 270 insertions, 0 deletions
@@ -29,8 +29,17 @@ colours. When nothing is left the bulb goes back to how it was. Unknown state words do nothing, so hook callers never break. Without a paired gateway or without coap-client, every command does nothing. """ +import colorsys +import contextlib +import fcntl import json +import os +import secrets +import shutil +import subprocess import sys +import time +from pathlib import Path # Colours are tuned on the real bulb; only the hue survives the saturation # floor, so they are effectively hue picks. @@ -48,6 +57,21 @@ DIM = 60 ESCALATE = 120 # a wait this long starts to breathe BREATHE = 2 # each half of a breath CYCLE = 4 # each colour of a multi-colour cycle +TICK = 1 # renderer loop period +FADE = 20 # transition, tenths of a second +TIMEOUT = 5 # per gateway request + +CONFIG = Path.home() / ".config/agent-lamp/tradfri.json" +RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") +DIR = RUNTIME / "agent-lamp" +# quickshell's statusctl mode file; read directly so the shell need not run. +NOLAMP = RUNTIME / "status.nolamp" + +# IPSO object ids the gateway uses: 15001 devices, 3311 light control, +# 5850 on/off, 5851 brightness, 5707 hue, 5708 saturation, 5709/5710 colour +# xy, 5712 transition. Hue and saturation run 0..65279. +DEVICES, LIGHT = "15001", "3311" +HUE_MAX = 65279 def word(w): @@ -101,6 +125,195 @@ def frame(sessions, now): return COLOURS[state], BRIGHT +def coap(method, url, ident, key, payload=None): + """The response body of one coaps request, or None on any failure.""" + cmd = ["coap-client", "-m", method, "-u", ident, "-k", key, "-B", str(TIMEOUT)] + if payload is not None: + cmd += ["-e", json.dumps(payload, separators=(",", ":"))] + try: + out = subprocess.run(cmd + [url], capture_output=True, text=True, + timeout=TIMEOUT + 2, check=True).stdout + except (subprocess.SubprocessError, OSError): + return None + return out.strip() + + +def put(url, auth, state): + return coap("put", url, *auth, {LIGHT: [state]}) is not None + + +def colour_state(colour): + """The 3311 state fading to #rrggbb. Pastels wash out to white on the + bulb, so saturation is floored to full and only the hue counts.""" + h, _, _ = colorsys.rgb_to_hsv(*(int(colour[i:i + 2], 16) / 255 for i in (1, 3, 5))) + return {"5707": round(h * HUE_MAX), "5708": HUE_MAX, "5712": FADE} + + +def show(urls, auth, target, shown): + """Move the bulbs from `shown` to `target`; the new shown state. + + The gateway drops part of a request setting colour and brightness at + once, so they go separately, colour first, and only what changed is sent. + On a failed request the old state is returned, so the next tick retries. + """ + colour, level = target + ok = True + for url in urls: + if colour != shown[0]: + ok &= put(url, auth, colour_state(colour)) + if level != shown[1]: + ok &= put(url, auth, {"5850": 1, "5851": level, "5712": FADE}) + return target if ok else shown + + +def snapshot(urls, auth): + """Each bulb's on/off, brightness and colour, or None if one is silent.""" + snap = [] + for url in urls: + try: + light = json.loads(coap("get", url, *auth))[LIGHT][0] + snap.append({k: light[k] for k in ("5850", "5851", "5709", "5710")}) + except (TypeError, ValueError, KeyError, IndexError): + return None + return snap + + +def restore(urls, auth, snap): + """Put the bulbs back as snapshot. Any colour change switches a bulb on, + so an off bulb gets its colour first and is switched off after.""" + for url, s in zip(urls, snap): + put(url, auth, {"5709": s["5709"], "5710": s["5710"], "5712": FADE}) + put(url, auth, {"5850": 1, "5851": s["5851"], "5712": FADE} if s["5850"] + else {"5850": 0}) + + +def configured(): + """The gateway config, or None when there is nothing to drive.""" + try: + cfg = json.loads(CONFIG.read_text()) + except (OSError, ValueError): + return None + if not cfg.get("bulbs") or not shutil.which("coap-client"): + return None + return cfg + + +@contextlib.contextmanager +def locked(): + """Hold the state lock: every read-modify-write of the state is inside.""" + DIR.mkdir(parents=True, exist_ok=True) + with open(DIR / "state.lock", "w") as f: + fcntl.flock(f, fcntl.LOCK_EX) + yield + + +def load(): + try: + return json.loads((DIR / "state.json").read_text()) + except (OSError, ValueError): + return {} + + +def save(sessions): + tmp = DIR / "state.json.tmp" + tmp.write_text(json.dumps(sessions)) + tmp.replace(DIR / "state.json") + + +def nolamp(): + try: + return NOLAMP.read_text().strip() == "1" + except OSError: + return False + + +def update(session, state): + """Record one event and wake the renderer if the state changed.""" + if not configured(): + return + with locked(): + sessions = load() + changed = apply(sessions, session, state, time.time()) + if changed: + save(sessions) + if changed and state != "reset": + subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--run"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + + +def wait_renderer(seconds): + """Return once no renderer holds the run lock, or after `seconds`. + + `reset` runs right before logout, suspend or poweroff; waiting lets the + renderer restore the bulb before the network goes. + """ + DIR.mkdir(parents=True, exist_ok=True) + end = time.monotonic() + seconds + with open(DIR / "run.lock", "w") as f: + while time.monotonic() < end: + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except BlockingIOError: + time.sleep(0.2) + + +def run(): + """The renderer: one at a time, by the run lock; a late one waits its + turn and exits at once if nothing is left by then. The exit decision and + the restore happen under the state lock, so no event slips between them. + """ + cfg = configured() + if not cfg: + return + auth = cfg["identity"], cfg["key"] + urls = [f"coaps://{cfg['host']}:5684/{DEVICES}/{b}" for b in cfg["bulbs"]] + DIR.mkdir(parents=True, exist_ok=True) + with open(DIR / "run.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + snap, shown = None, (None, None) + while True: + with locked(): + target = frame(load(), time.time()) + paused = nolamp() + if (target is None or paused) and snap: + restore(urls, auth, snap) + snap, shown = None, (None, None) + if target is None: + return + if not paused: + # ponytail: a silent gateway (just after resume) is retried + # every tick, no backoff; add one if it ever floods the log. + if snap is None: + snap = snapshot(urls, auth) + if snap is not None: + shown = show(urls, auth, target, shown) + time.sleep(TICK) + + +def pair(host, code): + ident = "agent-lamp-" + secrets.token_hex(4) + base = f"coaps://{host}:5684" + reply = coap("post", f"{base}/15011/9063", "Client_identity", code, {"9090": ident}) + try: + key = json.loads(reply)["9091"] + except (TypeError, ValueError, KeyError): + sys.exit(f"agent-lamp: pairing with {host} failed: {reply or 'no reply'}") + bulbs = [] + for dev in json.loads(coap("get", f"{base}/{DEVICES}", ident, key) or "[]"): + info = json.loads(coap("get", f"{base}/{DEVICES}/{dev}", ident, key) or "{}") + # Colour bulbs report a hue; white-spectrum ones only a colour temperature. + if "5707" in (info.get(LIGHT) or [{}])[0]: + bulbs.append(str(dev)) + print(f"{dev}: {info.get('9001', '?')}") + CONFIG.parent.mkdir(parents=True, exist_ok=True) + CONFIG.write_text(json.dumps({"host": host, "identity": ident, "key": key, + "bulbs": bulbs})) + CONFIG.chmod(0o600) + print(f"{len(bulbs)} colour bulb(s) recorded in {CONFIG}") + + def selftest(): assert word("permission") == "permission" assert word("complete") == "complete" @@ -155,6 +368,43 @@ def selftest(): assert frame(two, CYCLE) == (COLOURS["error"], BRIGHT) assert frame(two, 2 * CYCLE) == (COLOURS["permission"], BRIGHT) assert frame(two, dim_at)[1] == BRIGHT + # colour_state: hue from #rrggbb, saturation floored to full. + assert colour_state("#ff0000") == {"5707": 0, "5708": HUE_MAX, "5712": FADE} + pale = colour_state("#8080ff") + assert (pale["5707"], pale["5708"]) == (round(HUE_MAX * 2 / 3), HUE_MAX) + + # show and restore against a fake gateway that records every request. + global coap + real, sent = coap, [] + + def fake(method, url, ident, key, payload=None): + sent.append((method, url, payload)) + return json.dumps({LIGHT: [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}]}) + coap = fake + try: + auth, urls = ("i", "k"), ["u1"] + shown = show(urls, auth, ("#ff0000", BRIGHT), (None, None)) + assert shown == ("#ff0000", BRIGHT) + # Colour first, brightness after, in requests of their own. + assert [p[LIGHT][0] for _, _, p in sent] == [ + colour_state("#ff0000"), {"5850": 1, "5851": BRIGHT, "5712": FADE}] + sent.clear() + assert show(urls, auth, ("#ff0000", BRIGHT), shown) == shown and sent == [] + show(urls, auth, ("#ff0000", DIM), shown) + assert [p[LIGHT][0] for _, _, p in sent] == [{"5850": 1, "5851": DIM, "5712": FADE}] + sent.clear() + snap = snapshot(urls, auth) + assert snap == [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}] + sent.clear() + restore(urls, auth, snap) + # An off bulb gets its colour back, then is switched off. + assert [p[LIGHT][0] for _, _, p in sent] == [ + {"5709": 1, "5710": 2, "5712": FADE}, {"5850": 0}] + coap = lambda *a, **k: None + assert snapshot(urls, auth) is None + assert show(urls, auth, ("#ff0000", BRIGHT), (None, None)) == (None, None) + finally: + coap = real print("ok") @@ -162,6 +412,26 @@ def main(): args = sys.argv[1:] if args == ["--selftest"]: return selftest() + if args == ["--run"]: + return run() + if len(args) == 3 and args[0] == "--pair": + return pair(*args[1:]) + if args == ["reset"]: + update(None, "reset") + return wait_renderer(15) + if args == ["claude"]: + try: + event = from_claude(json.load(sys.stdin)) + except ValueError: + return + if event: + update(event[1], event[0]) + return + if len(args) == 2: + state = word(args[0]) + if state: + update(args[1], state) + return sys.exit(__doc__.split("\n\n")[1]) |
