diff options
| -rw-r--r-- | AGENTS.md | 3 | ||||
| -rw-r--r-- | deckit/modules/tablet.py | 108 | ||||
| -rw-r--r-- | static/deck.css | 2 | ||||
| -rw-r--r-- | static/modules/tablet.js | 77 | ||||
| -rw-r--r-- | tests/test_tablet.py | 61 |
5 files changed, 251 insertions, 0 deletions
@@ -49,6 +49,9 @@ Keep the server dependency-free apart from that one package. is the emergency stop, a press-and-hold button on the tab. While the printer is off it backs off 10s between tries. The camera snapshot and the slicer thumbnail are loaded by the tablet straight from the printer. +- `tablet` reads the tablet's battery (`dumpsys battery`) and Wi-Fi (`cmd wifi + status`, Android 11+) over adb, from the device whose reverse carries the + dashboard socket; reads are cached 10s. - The page holds a Screen Wake Lock while visible, so the tablet never sleeps over the dashboard; nothing on the tablet's settings is changed. - Launchers are `[launch] apps`, desktop ids run with `gtk-launch`; label and diff --git a/deckit/modules/tablet.py b/deckit/modules/tablet.py new file mode 100644 index 0000000..3f4b0d9 --- /dev/null +++ b/deckit/modules/tablet.py @@ -0,0 +1,108 @@ +# deck-it - tablet module +# Copyright (C) 2026 Danilo M. <danix@danix.xyz> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +"""The tablet's own battery and Wi-Fi, read over adb. + +The tablet is the device whose adb reverse carries the dashboard socket, the +same test `deck-it status` uses, so a USB/Wi-Fi switch is followed. +""" + +import re +import subprocess +import threading +import time + +from ..module import Module + +STATUS = {"2": "charging", "3": "discharging", "4": "not charging", "5": "full"} +TTL = 10 # seconds; each read is two adb round trips + + +def _adb(*args, timeout=5): + return subprocess.run(["adb", *args], capture_output=True, text=True, + timeout=timeout, check=True).stdout + + +def _find_tablet(): + for line in _adb("devices").splitlines()[1:]: + f = line.split() + if len(f) == 2 and f[1] == "device": + try: + if "deck-it/http.sock" in _adb("-s", f[0], "reverse", "--list", timeout=3): + return f[0] + except (subprocess.SubprocessError, OSError): + continue + return None + + +def parse_battery(text): + kv = dict(re.findall(r"^\s*([\w ]+): (.+)$", text, re.M)) + plug = next((k.split()[0] for k in ("AC powered", "USB powered", "Wireless powered") + if kv.get(k) == "true"), None) + scale = int(kv.get("scale", 100)) or 100 + temp = kv.get("temperature") + return { + "level": round(100 * int(kv.get("level", 0)) / scale), + "status": STATUS.get(kv.get("status"), "unknown"), + "plug": plug, + "temp": int(temp) / 10 if temp else None, + } + + +def parse_wifi(text): + """`cmd wifi status` (Android 11+): a 'connected to "SSID"' line plus WifiInfo.""" + m = re.search(r'connected to "(.*?)"', text) + if not m: + return {"connected": False} + rssi = re.search(r"RSSI: (-?\d+)", text) + speed = re.search(r"Link speed: (\d+)", text) + freq = re.search(r"Frequency: (\d+)", text) + return { + "connected": True, + "ssid": m[1], + "rssi": int(rssi[1]) if rssi else None, + "speed": int(speed[1]) if speed else None, + "band": f"{int(freq[1]) / 1000:.1f} GHz" if freq else None, + } + + +def make(cfg: dict) -> Module: + lock = threading.Lock() + cache = {"t": 0, "v": None, "serial": None} + + def read(): + serial = cache["serial"] or _find_tablet() + if not serial: + return {"connected": False, "error": "no tablet with the dashboard tunnel"} + try: + batt = _adb("-s", serial, "shell", "dumpsys", "battery") + wifi = _adb("-s", serial, "shell", "cmd", "wifi", "status") + except (subprocess.SubprocessError, OSError) as e: + cache["serial"] = None # look again next time; it may have moved USB <-> Wi-Fi + return {"connected": False, "error": str(e) or type(e).__name__} + cache["serial"] = serial + return {"connected": True, "link": "Wi-Fi" if ":" in serial else "USB", + "battery": parse_battery(batt), "wifi": parse_wifi(wifi)} + + def state(): + # ponytail: one shared cache, so several open pages cost one adb read per TTL. + with lock: + if time.monotonic() - cache["t"] >= TTL: + cache["v"] = read() + cache["t"] = time.monotonic() + return cache["v"] + + return Module(name="tablet", title="Tablet", state=state) diff --git a/static/deck.css b/static/deck.css index ee8bc37..0b9a0dd 100644 --- a/static/deck.css +++ b/static/deck.css @@ -281,6 +281,8 @@ select { text-overflow: ellipsis; } .msub { font-size: 0.857rem; color: var(--udt-subtext0); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.tablet .bars { height: 0.8em; margin-left: 6px; vertical-align: baseline; fill: var(--udt-surface2); } +.tablet .bars .lit { fill: var(--udt-accent); } .mfoot { margin-top: 10px; font-size: 0.857rem; color: var(--udt-overlay0); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .windows { display: flex; flex-direction: column; gap: 14px; } diff --git a/static/modules/tablet.js b/static/modules/tablet.js new file mode 100644 index 0000000..cb38416 --- /dev/null +++ b/static/modules/tablet.js @@ -0,0 +1,77 @@ +// deck-it - tablet panel +// Copyright (C) 2026 Danilo M. <danix@danix.xyz> +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License version 2 as +// published by the Free Software Foundation. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +// The tablet's battery and Wi-Fi, in the System card's tile style. + +import { offline } from "../offline.js"; + +function tile(label, value, sub, cls = "", badge = "") { + const d = document.createElement("div"); + d.className = "mtile"; + d.innerHTML = `<span class="mlabel"></span><span class="mvalue num ${cls}"></span><span class="msub"></span>`; + d.children[0].textContent = label; + d.children[0].insertAdjacentHTML("beforeend", badge); + d.children[1].textContent = value; + d.children[2].textContent = sub || ""; + return d; +} + +// Four bars in the label, lit by Android's thresholds: -55 dBm and up is full. +function bars(rssi) { + const n = rssi == null ? 0 : rssi >= -55 ? 4 : rssi >= -66 ? 3 : rssi >= -77 ? 2 : 1; + const rects = [0, 1, 2, 3].map((i) => + `<rect x="${i * 4}" y="${9 - i * 3}" width="3" height="${3 + i * 3}" rx="1"${i < n ? ' class="lit"' : ""}/>`); + return `<svg class="bars" viewBox="0 0 15 12" aria-hidden="true">${rects.join("")}</svg>`; +} + +export default { + title: "Tablet", + interval: 10, + + mount(el) { + el.innerHTML = `<div class="tablet"><div class="stats"></div></div>`; + }, + + update(st, el) { + const box = el.querySelector(".stats"); + if (!st.connected) { + offline(box, { + icon: "/icons/smartphone.svg", + title: "Tablet not reachable over adb", + detail: "Its battery and Wi-Fi show here once deck-it's tunnel is up.", + reason: st.error, + }); + return; + } + box.textContent = ""; + const b = st.battery; + const w = st.wifi; + const low = b.level <= 20 && b.status !== "charging"; + box.append( + tile("Battery", `${b.level}%`, + [b.status, b.plug, b.temp != null ? `${b.temp}°C` : ""].filter(Boolean).join(" · "), + low ? "bad" : b.status === "charging" ? "good" : ""), + w.connected + ? tile("Wi-Fi", `${w.rssi ?? "?"} dBm`, + [w.ssid, w.band, w.speed ? `${w.speed} Mbps` : ""].filter(Boolean).join(" · "), "", bars(w.rssi)) + : tile("Wi-Fi", "off", "not connected", "warn"), + ); + const foot = document.createElement("div"); + foot.className = "mfoot"; + foot.textContent = `linked over ${st.link}`; + box.append(foot); + }, +}; diff --git a/tests/test_tablet.py b/tests/test_tablet.py new file mode 100644 index 0000000..f2bbed6 --- /dev/null +++ b/tests/test_tablet.py @@ -0,0 +1,61 @@ +# deck-it - tests for tablet +# Copyright (C) 2026 Danilo M. <danix@danix.xyz> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import unittest + +from deckit.modules import tablet + +BATTERY = """Current Battery Service state: + AC powered: false + USB powered: true + Wireless powered: false + status: 2 + health: 2 + present: true + level: 85 + scale: 100 + voltage: 4200 + temperature: 312 +""" + +WIFI = """Wifi is enabled +Wifi scanning is always available +==== Primary ClientModeManager instance ==== +Wifi is connected to "ExampleNet" +WifiInfo: SSID: "ExampleNet", BSSID: 02:00:00:00:00:00, RSSI: -58, Link speed: 866Mbps, Frequency: 5180MHz +""" + + +class Parse(unittest.TestCase): + def test_battery(self): + self.assertEqual(tablet.parse_battery(BATTERY), + {"level": 85, "status": "charging", "plug": "USB", "temp": 31.2}) + + def test_wifi(self): + self.assertEqual(tablet.parse_wifi(WIFI), + {"connected": True, "ssid": "ExampleNet", "rssi": -58, "speed": 866, "band": "5.2 GHz"}) + + def test_wifi_off(self): + self.assertEqual(tablet.parse_wifi("Wifi is disabled\n"), {"connected": False}) + + +if __name__ == "__main__": + unittest.main() |
