Turn a ~$5 AliExpress clock into a physical AI usage dashboard (Claude, Codex, multi-account). No firmware flashing.
Harden SmallTV-Ultra support and refuse mismatched backups
click6067-ship-itac62d079abfc
diff --git a/docs/hardware-compatibility.md b/docs/hardware-compatibility.mdindex 2ed508d..ccc0ea7 100644--- a/docs/hardware-compatibility.md+++ b/docs/hardware-compatibility.md@@ -8,14 +8,21 @@ not "probably fine".| Clock | Firmware web UI | What TokenTV uses | Checked || --- | --- | --- | --- || The author's 240×240 GeekMagic SmallTV-style Wi-Fi clock (receipt: ₩5,650 on a Korean AliExpress discount; prices vary by region) | Stock firmware with the **SD_PRO** web UI and a photo album | `/theme/list`, `/photo/list`, `/photo/upload`, photo theme id `2` | One unit, Linux host |+| GeekMagic **SmallTV-Ultra** | Stock firmware `Ultra-V9.0.54` (`/v.json` reports `SmallTV-Ultra`) | `/app.json`, `/album.json`, `/doUpload?dir=/image/`, `/set?img=`, Photo Album theme `3` | The contributor's unit ([#7](https://github.com/click6067-ship-it/token-tv/pull/7)). The author has no Ultra and has not checked it on a real clock |TokenTV never flashes firmware and never deletes your photos. It uploads one picture, switches theclock to its photo theme, and `token-tv run --restore-display` puts the original theme back.+On the SmallTV-Ultra, TokenTV also turns the album's autoplay off while it is showing. Restoring puts+the theme and autoplay back, but there is no known way to read which photo was selected before, so+TokenTV's picture can stay in the album. Delete `tokentv.jpg` / `tokentv.gif` on the clock's image page+if you want them gone.+## Not verified- Other GeekMagic models, SmallTV Pro, and clones that look the same. A similar case is not evidenceof the same firmware.+- SmallTV-Ultra on firmware other than `Ultra-V9.0.54`, and animated (GIF) faces on the Ultra.- Firmware without the photo album page or with different photo API paths.- macOS and Windows hosts.diff --git a/tests/test_device.py b/tests/test_device.pyindex 988cb20..5cfadf7 100644--- a/tests/test_device.py+++ b/tests/test_device.py@@ -1,10 +1,18 @@+import email+import email.policyimport json+import socket+import tempfileimport threadingimport unittest+from contextlib import contextmanagerfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from unittest.mock import patchfrom urllib.parse import parse_qs, urlparse-from token_tv.device import PhotoDisplay+from token_tv import live+from token_tv.device import BackupMismatch, PhotoDisplay, UltraDisplay, open_displayclass DisplayTests(unittest.TestCase):@@ -83,5 +91,193 @@ class DisplayTests(unittest.TestCase):thread.join()+@contextmanager+def serve(handler):+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)+ thread = threading.Thread(target=server.serve_forever)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++def answering(status, body):+ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ return+ def do_GET(self):+ self.send_response(status)+ self.end_headers()+ self.wfile.write(body)+ return Handler+++def ultra_clock(state, calls):+ """SmallTV-Ultra stock web API as recorded by the contributor and adrienbrault/geekmagic-hacs."""+ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ return+ def reply(self, data, status=200):+ body = json.dumps(data).encode()+ self.send_response(status)+ self.end_headers()+ self.wfile.write(body)+ def do_GET(self):+ calls.append(("GET", self.path))+ url = urlparse(self.path)+ if url.path == "/v.json":+ return self.reply({"m": "SmallTV-Ultra", "v": "Ultra-V9.0.54"})+ if url.path == "/app.json":+ return self.reply({"theme": state["theme"]})+ if url.path == "/album.json":+ return self.reply({"autoplay": state["autoplay"], "i_i": state["i_i"]})+ if url.path == "/set":+ for key, values in parse_qs(url.query).items():+ state[key] = values[0] if key == "img" else int(values[0])+ return self.reply("OK")+ self.reply({}, 404)+ def do_POST(self):+ calls.append(("POST", self.path))+ body = self.rfile.read(int(self.headers["Content-Length"]))+ form = email.message_from_bytes(b"Content-Type: " + self.headers["Content-Type"].encode() + b"\r\n\r\n" + body,+ policy=email.policy.HTTP)+ for part in form.iter_parts():+ state["parts"].append((part.get_param("name", header="content-disposition"), part.get_filename(),+ part.get_content_type(), part.get_payload(decode=True)))+ if self.path == "/doUpload?dir=/image/" and part.get_param("name", header="content-disposition") == "file":+ state["files"][part.get_filename()] = part.get_payload(decode=True)+ self.reply("OK")+ return Handler+++SD_PRO_BACKUP = {"themes": [{"id": 0, "enabled": True}, {"id": 2, "enabled": False}], "theme_interval": 10,+ "files": [{"name": "original.jpg", "enabled": True}], "photo_interval": 10}+ULTRA_BACKUP = {"model": "ultra", "theme": 1, "autoplay": 1, "i_i": 5}+++class UltraTests(unittest.TestCase):+ def setUp(self):+ self.state = {"theme": 1, "autoplay": 1, "i_i": 5, "img": "/image/cat.jpg", "files": {"cat.jpg": b"CAT"}, "parts": []}+ self.calls = []++ def test_only_a_smalltv_ultra_answer_selects_the_ultra_api(self):+ answers = [(200, b'{"m": "SmallTV-Ultra", "v": "Ultra-V9.0.54"}', UltraDisplay),+ (404, b"", PhotoDisplay), (200, b'{"m": null}', PhotoDisplay), (200, b'{"m": 5}', PhotoDisplay),+ (200, b'["SmallTV-Ultra"]', PhotoDisplay), (200, b"<html></html>", PhotoDisplay),+ (200, b"\xff", PhotoDisplay), (200, b'{"m": "SmallTV-PRO"}', PhotoDisplay),+ (200, b'{"m": "NotUltraAtAll"}', PhotoDisplay)]+ for status, body, expected in answers:+ with self.subTest(body=body), serve(answering(status, body)) as url:+ self.assertIs(type(open_display(url)), expected)++ def test_unreachable_or_broken_clock_keeps_the_sd_pro_path(self):+ class Garbled(BaseHTTPRequestHandler):+ def log_message(self, *args):+ return+ def do_GET(self):+ self.wfile.write(b"not an http status line\r\n\r\n")+ with serve(Garbled) as url:+ self.assertIs(type(open_display(url)), PhotoDisplay)+ with socket.socket() as closed:+ closed.bind(("127.0.0.1", 0))+ port = closed.getsockname()[1]+ self.assertIs(type(open_display(f"http://127.0.0.1:{port}")), PhotoDisplay)++ def test_ultra_contract_backup_upload_show_and_restore(self):+ with serve(ultra_clock(self.state, self.calls)) as url:+ display = open_display(url)+ self.assertIsInstance(display, UltraDisplay)+ self.assertEqual(self.calls, [("GET", "/v.json")])+ original = display.capture()+ self.assertEqual(original, ULTRA_BACKUP)+ self.assertEqual(self.calls[1:], [("GET", "/app.json"), ("GET", "/album.json")])++ start = len(self.calls)+ display.upload("tokentv.jpg", b"EXACT-JPEG")+ display.upload("tokentv.gif", b"GIF89a-EXACT")+ for name, image in (("other.jpg", b"JPEG"), ("tokentv.jpg", b""), ("tokentv.jpg", b"x" * 60001)):+ with self.assertRaises(ValueError):+ display.upload(name, image)+ self.assertEqual(self.calls[start:], [("POST", "/doUpload?dir=/image/")] * 2)+ self.assertEqual(self.state["parts"], [("file", "tokentv.jpg", "image/jpeg", b"EXACT-JPEG"),+ ("file", "tokentv.gif", "image/gif", b"GIF89a-EXACT")])++ # Stop the slideshow, switch to the Photo Album theme, then point it at our image.+ start = len(self.calls)+ display.activate(original)+ self.assertEqual(self.calls[start:], [("GET", "/app.json"), ("GET", "/album.json"), ("GET", "/set?i_i=5&autoplay=0"),+ ("GET", "/set?theme=3"), ("GET", "/set?img=%2Fimage%2Ftokentv.jpg")])+ self.assertEqual((self.state["theme"], self.state["autoplay"], self.state["img"]), (3, 0, "/image/tokentv.jpg"))+ # Already in the album with autoplay off: only the image changes.+ start = len(self.calls)+ display.activate(original, "tokentv.gif")+ self.assertEqual(self.calls[start:], [("GET", "/app.json"), ("GET", "/album.json"), ("GET", "/set?img=%2Fimage%2Ftokentv.gif")])++ start = len(self.calls)+ display.restore(original)+ self.assertEqual(self.calls[start:], [("GET", "/set?i_i=5&autoplay=1"), ("GET", "/set?theme=1")])+ self.assertEqual((self.state["theme"], self.state["autoplay"], self.state["i_i"]), (1, 1, 5))+ self.assertEqual(self.state["files"], {"cat.jpg": b"CAT", "tokentv.jpg": b"EXACT-JPEG", "tokentv.gif": b"GIF89a-EXACT"})+ paths = [c[1] for c in self.calls]+ self.assertFalse(any(word in p for p in paths for word in ("delete", "clear", "reset", "reboot", "update")))++ def test_ultra_activate_does_not_copy_clock_values_into_the_query(self):+ self.state["i_i"] = "5&theme=0"+ with serve(ultra_clock(self.state, self.calls)) as url:+ with self.assertRaises(ValueError):+ UltraDisplay(url).activate(ULTRA_BACKUP)+ self.assertFalse(any(path.startswith("/set") for _, path in self.calls))+ self.assertEqual(self.state["theme"], 1)++ def test_backup_from_another_kind_of_clock_is_refused(self):+ sd_pro, ultra = PhotoDisplay("http://127.0.0.1:9"), UltraDisplay("http://127.0.0.1:9")+ sd_pro.check_backup(SD_PRO_BACKUP)+ ultra.check_backup(ULTRA_BACKUP)+ for display, backup in ((ultra, SD_PRO_BACKUP), (sd_pro, ULTRA_BACKUP), (ultra, ["not", "a", "backup"])):+ with self.subTest(display=type(display).__name__, backup=backup), self.assertRaises(BackupMismatch):+ display.check_backup(backup)++ def test_mismatched_backup_is_kept_and_the_clock_is_not_touched(self):+ with tempfile.TemporaryDirectory() as folder, serve(ultra_clock(self.state, self.calls)) as url:+ backup = Path(folder) / "display-original.json"+ backup.write_text(json.dumps(SD_PRO_BACKUP))+ saved = backup.read_bytes()+ display = open_display(url)+ # Live cycle: refuse before any capture, upload or new backup.+ with self.assertRaises(BackupMismatch):+ live.load_original(display, backup)+ # --restore-display: a clear message instead of a KeyError traceback.+ config = Path(folder) / "config.json"+ config.write_text(json.dumps({"device_url": url, "accounts": [+ {"key": "claude", "alias": "Claude", "provider": "claude", "email": "[email protected]"}]}))+ with patch("sys.argv", ["token-tv", "--config", str(config), "--state-dir", folder, "--restore-display"]):+ with self.assertRaises(SystemExit) as stop:+ live.main()+ self.assertIn("SD_PRO", str(stop.exception.code))+ self.assertIn("Nothing was changed on the clock", str(stop.exception.code))+ self.assertEqual(backup.read_bytes(), saved)+ self.assertEqual(sorted(p.name for p in Path(folder).iterdir()), ["config.json", "display-original.json"])+ self.assertEqual(self.calls, [("GET", "/v.json")] * 2)+ self.assertEqual(self.state["theme"], 1)++ def test_backup_is_saved_once_and_reused_for_the_same_kind_of_clock(self):+ with tempfile.TemporaryDirectory() as folder, serve(ultra_clock(self.state, self.calls)) as url:+ backup = Path(folder) / "display-original.json"+ display = open_display(url)+ self.assertEqual(live.load_original(display, backup), ULTRA_BACKUP)+ self.assertEqual(json.loads(backup.read_text()), ULTRA_BACKUP)+ self.state["theme"] = 3+ start = len(self.calls)+ self.assertEqual(live.load_original(display, backup), ULTRA_BACKUP)+ self.assertEqual(self.calls[start:], [])+ # SD_PRO backups have no model key and keep working unchanged.+ backup.write_text(json.dumps(SD_PRO_BACKUP))+ self.assertEqual(live.load_original(PhotoDisplay(url), backup), SD_PRO_BACKUP)+ self.assertEqual(self.calls[start:], [])++if __name__ == "__main__":unittest.main()diff --git a/token_tv/device.py b/token_tv/device.pyindex d2b64d8..0143619 100644--- a/token_tv/device.py+++ b/token_tv/device.py@@ -1,6 +1,7 @@"""Confirmed SD_PRO photo API, plus the SmallTV-Ultra image API. Never flash or delete existing photographs."""import jsonimport uuid+from http.client import HTTPExceptionfrom urllib.parse import quote, urlencode, urlparsefrom urllib.request import Request, urlopen@@ -9,9 +10,16 @@ FILES = ("tokentv.jpg", "tokentv.gif")# The album page accepts GIFs up to 240×240; keep both well under the free space.LIMITS = {"tokentv.jpg": (60000, "image/jpeg"), "tokentv.gif": (400000, "image/gif")}LEGACY_FILES = ("tokentv-c.jpg", "tokentv-m.jpg")+MODEL_NAMES = {"sdpro": "an SD_PRO", "ultra": "a SmallTV-Ultra"}+++class BackupMismatch(ValueError):+ """The saved original state belongs to a different kind of clock."""class PhotoDisplay:+ MODEL = "sdpro"+def __init__(self, base_url):parsed = urlparse(base_url)if parsed.scheme != "http" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.path not in ("", "/"):@@ -23,6 +31,13 @@ class PhotoDisplay:body = response.read()return response.status, body+ def check_backup(self, original):+ # SD_PRO backups predate the model key, so a missing key means SD_PRO.+ saved = original.get("model", "sdpro") if isinstance(original, dict) else None+ if saved != self.MODEL:+ raise BackupMismatch(f"The saved display backup is for {MODEL_NAMES.get(saved, 'an unknown')} clock, "+ f"but this clock was detected as {MODEL_NAMES[self.MODEL]}.")+def capture(self):_, raw = self.request("/theme/list")themes = json.loads(raw)@@ -83,6 +98,7 @@ class PhotoDisplay:class UltraDisplay(PhotoDisplay):"""SmallTV-Ultra (Ultra-V9) image API, read from the clock's own image.html and settings.html."""+ MODEL = "ultra"PHOTO_THEME = 3def capture(self):@@ -90,7 +106,7 @@ class UltraDisplay(PhotoDisplay):theme = json.loads(raw)["theme"]_, raw = self.request("/album.json")album = json.loads(raw)- return {"model": "ultra", "theme": theme, "autoplay": album["autoplay"], "i_i": album["i_i"]}+ return {"model": self.MODEL, "theme": theme, "autoplay": album["autoplay"], "i_i": album["i_i"]}def upload(self, name, image):limit, mime = LIMITS.get(name, (0, ""))@@ -104,15 +120,17 @@ class UltraDisplay(PhotoDisplay):return {"file": name, "status": status, "bytes": len(image)}def activate(self, original, name=FILES[0]):- # Stop the slideshow so the user's own photos never rotate in, show ours, select the album theme.+ # Stop the slideshow so the user's own photos never rotate in, select the album theme, show ours.+ # The image is chosen after the theme, as geekmagic-hacs does on the same firmware.current = self.capture()if current["autoplay"]:- self.request(f"/set?i_i={current['i_i']}&autoplay=0")- self.request("/set?img=" + quote("/image/" + name, safe=""))+ self.request(f"/set?i_i={int(current['i_i'])}&autoplay=0")if current["theme"] != self.PHOTO_THEME:self.request(f"/set?theme={self.PHOTO_THEME}")+ self.request("/set?img=" + quote("/image/" + name, safe=""))def restore(self, original):+ # There is no known way to read the previously shown image, so only the album settings and theme return.self.request(f"/set?i_i={int(original['i_i'])}&autoplay={int(original['autoplay'])}")self.request(f"/set?theme={int(original['theme'])}")@@ -121,8 +139,7 @@ def open_display(base_url):display = PhotoDisplay(base_url)try:_, raw = display.request("/v.json")- if "Ultra" in json.loads(raw).get("m", ""):- return UltraDisplay(base_url)- except (OSError, ValueError, AttributeError):- pass # ponytail: model checked once at start; an Ultra offline at launch falls back to SD_PRO until restart- return display+ model = json.loads(raw).get("m")+ except (OSError, ValueError, AttributeError, HTTPException):+ return display # model checked once at start; an Ultra offline at launch falls back to SD_PRO until restart+ return UltraDisplay(base_url) if isinstance(model, str) and model.startswith("SmallTV-Ultra") else displaydiff --git a/token_tv/live.py b/token_tv/live.pyindex e8d55da..c31612c 100644--- a/token_tv/live.py+++ b/token_tv/live.py@@ -9,7 +9,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom urllib.parse import parse_qs, urlparse-from token_tv.device import FILES, open_display+from token_tv.device import FILES, BackupMismatch, open_displayfrom token_tv.catalog import payload as theme_payloadfrom token_tv.display import STYLES, render_pagefrom token_tv.web_assets import HTML, ASSETS, asset@@ -26,6 +26,23 @@ def write_json(path, data):temporary.replace(path)+def load_original(device, backup_path):+ """Return the clock's original state; save it first only if no backup exists yet."""+ if backup_path.is_file():+ original = json.loads(backup_path.read_text())+ device.check_backup(original) # a backup from another kind of clock is kept and nothing is sent+ return original+ original = device.capture()+ write_json(backup_path, original)+ return original+++def mismatch_message(error, backup_path):+ return (f"{error} Nothing was changed on the clock and {backup_path} was kept. If the clock was offline "+ "when TokenTV started, start TokenTV again. If you replaced the clock, put the old one back to "+ "restore it, or move that file away so TokenTV saves a new backup.")++class DisplayPreferences:def __init__(self, config_path, config):self.path = Path(config_path)@@ -155,7 +172,12 @@ def main():if args.restore_display:if not device or not backup_path.is_file():parser.error("A display and its original state backup are required")- device.restore(json.loads(backup_path.read_text()))+ original = json.loads(backup_path.read_text())+ try:+ device.check_backup(original)+ except BackupMismatch as error:+ raise SystemExit(mismatch_message(error, backup_path))+ device.restore(original)print("Original display selection restored.")returnstore = UsageStore(config["accounts"])@@ -177,9 +199,7 @@ def main():phase = "backup"try:if original is None:- original = json.loads(backup_path.read_text()) if backup_path.is_file() else device.capture()- if not backup_path.is_file():- write_json(backup_path, original)+ original = load_original(device, backup_path)phase = "upload"image = render_page(snapshot, 0, style)name = FILES[1] if image[:4] == b"GIF8" else FILES[0]@@ -195,6 +215,8 @@ def main():write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "uploads": receipts})preferences.delivered(style, True)except (OSError, ValueError, KeyError) as error:+ if isinstance(error, BackupMismatch):+ print(mismatch_message(error, backup_path), flush=True)write_json(state_dir / "display-receipt.json", {"at": int(time.time()), "style": style, "status": "error", "phase": phase,"uploads": receipts, "http_status": getattr(error, "code", None)})preferences.delivered(style, False)