diff options
| -rwxr-xr-x | agent-lamp | 91 |
1 files changed, 66 insertions, 25 deletions
@@ -60,9 +60,11 @@ 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 +RESTORE_TRIES = 10 # ticks a failing restore is retried before giving up CONFIG = Path.home() / ".config/agent-lamp/tradfri.json" -RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") +# No XDG_RUNTIME_DIR, no lamp: a shared /tmp fallback could be squatted. +RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or "/nonexistent") DIR = RUNTIME / "agent-lamp" # quickshell's statusctl mode file; read directly so the shell need not run. NOLAMP = RUNTIME / "status.nolamp" @@ -73,6 +75,10 @@ NOLAMP = RUNTIME / "status.nolamp" DEVICES, LIGHT = "15001", "3311" HUE_MAX = 65279 +# When the last brightness fade started (monotonic). The gateway drops a +# colour sent while a brightness fade runs, so colour waits for it to end. +level_at = 0.0 + def word(w): """The state a CLI or opencode-notifier event word means, or None.""" @@ -83,7 +89,8 @@ def word(w): def from_claude(payload): """(state, session) for a Claude Code hook payload, or None to ignore.""" - if not isinstance(payload, dict) or not payload.get("session_id"): + if not isinstance(payload, dict) or not isinstance(payload.get("session_id"), str) \ + or not payload["session_id"]: return None event = payload.get("hook_event_name") if event == "Notification": @@ -154,15 +161,22 @@ def show(urls, auth, target, shown): 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. + A colour waits out a running brightness fade, which would drop it. On a + failed or deferred request the old state is returned, so the next tick + retries. """ + global level_at colour, level = target + if colour != shown[0] and time.monotonic() < level_at + FADE / 10: + return shown 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}) + if level != shown[1]: + level_at = time.monotonic() return target if ok else shown @@ -180,15 +194,21 @@ def snapshot(urls, auth): 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.""" + so an off bulb gets its colour first and is switched off after. True if + every request went through.""" + time.sleep(max(0.0, level_at + FADE / 10 - time.monotonic())) + ok = True 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}) + ok &= put(url, auth, {"5709": s["5709"], "5710": s["5710"], "5712": FADE}) + ok &= put(url, auth, {"5850": 1, "5851": s["5851"], "5712": FADE} if s["5850"] + else {"5850": 0}) + return ok def configured(): """The gateway config, or None when there is nothing to drive.""" + if not RUNTIME.is_dir(): + return None try: cfg = json.loads(CONFIG.read_text()) except (OSError, ValueError): @@ -209,9 +229,10 @@ def locked(): def load(): try: - return json.loads((DIR / "state.json").read_text()) + sessions = json.loads((DIR / "state.json").read_text()) except (OSError, ValueError): return {} + return sessions if isinstance(sessions, dict) else {} def save(sessions): @@ -231,11 +252,14 @@ 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) + try: + with locked(): + sessions = load() + changed = apply(sessions, session, state, time.time()) + if changed: + save(sessions) + except OSError: + return # hook callers must never break if changed and state != "reset": subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--run"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, @@ -248,6 +272,8 @@ def wait_renderer(seconds): `reset` runs right before logout, suspend or poweroff; waiting lets the renderer restore the bulb before the network goes. """ + if not configured(): + return DIR.mkdir(parents=True, exist_ok=True) end = time.monotonic() + seconds with open(DIR / "run.lock", "w") as f: @@ -260,9 +286,10 @@ def wait_renderer(seconds): 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. + """The renderer: one at a time, by the run lock. A second one exits at + once. No event is lost: writers spawn after releasing the state lock, and + the renderer decides to exit and drops the run lock under that same lock, + so either it sees the new state or the run lock is already free. """ cfg = configured() if not cfg: @@ -271,18 +298,25 @@ def run(): 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) + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return + snap, shown, fails = None, (None, None), 0 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: + # A failed restore keeps the snapshot and retries, so a + # slow gateway does not strand the bulb in an agent colour. + fails += 1 + if restore(urls, auth, snap) or fails >= RESTORE_TRIES: + snap, shown, fails = None, (None, None), 0 + if target is None and not snap: + fcntl.flock(lock, fcntl.LOCK_UN) return - if not paused: + if target is not None and 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: @@ -336,6 +370,7 @@ def selftest(): assert hook("SubagentStop") is None assert from_claude({"hook_event_name": "Stop"}) is None assert from_claude([]) is None + assert from_claude({"hook_event_name": "Stop", "session_id": 1}) is None # apply: a session holds one state; the same state again keeps its # start time, so repeated notifications do not reset the escalation. s = {} @@ -374,7 +409,7 @@ def selftest(): 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 + global coap, level_at real, sent = coap, [] def fake(method, url, ident, key, payload=None): @@ -390,18 +425,24 @@ def selftest(): 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) + dimmed = show(urls, auth, ("#ff0000", DIM), shown) assert [p[LIGHT][0] for _, _, p in sent] == [{"5850": 1, "5851": DIM, "5712": FADE}] sent.clear() + # A colour change waits out the brightness fade just started. + assert show(urls, auth, ("#00ff00", DIM), dimmed) == dimmed and sent == [] + level_at = 0.0 + assert show(urls, auth, ("#00ff00", DIM), dimmed) == ("#00ff00", DIM) + sent.clear() snap = snapshot(urls, auth) assert snap == [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}] sent.clear() - restore(urls, auth, snap) + assert 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 not restore(urls, auth, snap) assert show(urls, auth, ("#ff0000", BRIGHT), (None, None)) == (None, None) finally: coap = real |
