diff --git a/packages/omamobile-shell/bin/omamobile-nfc-open b/packages/omamobile-shell/bin/omamobile-nfc-open index 734ea024f..193f9ee4a 100644 --- a/packages/omamobile-shell/bin/omamobile-nfc-open +++ b/packages/omamobile-shell/bin/omamobile-nfc-open @@ -15,6 +15,11 @@ told when the kernel blocks the radio, so on a block the adapter is powered off through neard (on a kernel that already did, neard's view stays stale), and on an unblock neard is restarted: it finds the adapter again, powers it (DefaultPowered), and a new poll loop starts. + +And it polls only while the screen is lit, as stock Android does: with every +display connector off (DPMS) for SCREEN_OFF_SECONDS, the poll loop stops, +and it starts again when the screen comes on. A poll loop is the radio +searching for cards, which costs the Pixel 9a about 60 mA. """ import glob import subprocess @@ -30,6 +35,7 @@ NEARD = "org.neard" RECORD = "org.neard.Record" ADAPTER = "org.neard.Adapter" REPEAT_SECONDS = 3.0 +SCREEN_OFF_SECONDS = 4 last = {"uri": None, "time": 0.0} @@ -96,7 +102,9 @@ def start_polling(bus): bus.call_sync(NEARD, path, "org.freedesktop.DBus.Properties", "Set", GLib.Variant("(ssv)", (ADAPTER, "Powered", GLib.Variant("b", True))), None, Gio.DBusCallFlags.NONE, -1, None) - if not adapter.get("Polling"): + if not adapter.get("Polling") and not screen["lit"]: + log(f"screen off: {path} powered, polling waits for the screen") + elif not adapter.get("Polling"): try: bus.call_sync(NEARD, path, ADAPTER, "StartPollLoop", GLib.Variant("(s)", ("Initiator",)), None, @@ -141,6 +149,63 @@ def set_powered(bus, powered): rfkill = {"blocked": None} +screen = {"lit": True, "dark_for": 0} + + +def screen_lit(drm="/sys/class/drm"): + """True unless every connected display connector reports DPMS off.""" + states = [] + for path in glob.glob(f"{drm}/card*-*"): + try: + with open(f"{path}/status") as f: + if f.read().strip() != "connected": + continue + with open(f"{path}/dpms") as f: + states.append(f.read().strip()) + except OSError: + continue + return not states or any(state == "On" for state in states) + + +def stop_polling(bus): + try: + objects = bus.call_sync(NEARD, "/", "org.freedesktop.DBus.ObjectManager", + "GetManagedObjects", None, None, + Gio.DBusCallFlags.NONE, -1, None).unpack()[0] + except GLib.Error: + return + for path, interfaces in objects.items(): + adapter = interfaces.get(ADAPTER) + if adapter is None or not adapter.get("Polling"): + continue + try: + bus.call_sync(NEARD, path, ADAPTER, "StopPollLoop", None, None, + Gio.DBusCallFlags.NONE, -1, None) + log(f"screen off: polling stopped on {path}") + except GLib.Error as error: + log(f"could not stop polling on {path}: {error.message}") + + +def follow_screen(bus): + """Every 2 s: once the screen has been off for a while, stop any poll loop + (each time, so one that neard, a restart or the sleep hook started while + the screen was dark stops too); start it again when the screen lights + (unless NFC is switched off).""" + lit = screen_lit() + if lit: + screen["dark_for"] = 0 + if not screen["lit"]: + screen["lit"] = True + if not rfkill["blocked"]: + log("screen on: polling again") + start_polling(bus) + return True + screen["dark_for"] += 2 + if screen["dark_for"] >= SCREEN_OFF_SECONDS: + screen["lit"] = False + if not rfkill["blocked"]: + stop_polling(bus) + return True def follow_rfkill(bus): @@ -172,6 +237,7 @@ def main(): # earlier run of it): start from a fresh neard. restart_neard(bus) GLib.timeout_add_seconds(2, follow_rfkill, bus) + GLib.timeout_add_seconds(2, follow_screen, bus) GLib.MainLoop().run() diff --git a/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml b/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml index 1b241627b..cd283e662 100644 --- a/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml +++ b/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml @@ -151,16 +151,23 @@ QtObject { if (kind === "media") { fromCommand("playerctl metadata --format " + JSON.stringify(Phone.MEDIA_FORMAT) + " 2>/dev/null", Phone.mediaFrom); return } if (kind === "modes") { fromCommand("brightnessctl --device=white:torch get 2>/dev/null || echo; makoctl mode 2>/dev/null", Phone.modesFrom); return } if (kind === "system") { - fromCommand("cat /proc/meminfo; echo '@@'; cat /proc/uptime; echo '@@'; uname -r; echo '@@'; df -B1 --output=size,used / | tail -1", function(t) { - const parts = t.split("@@\n") - return Phone.systemFrom(parts[0], parts[1], parts[2], parts[3]) + fromCommand("cat /proc/meminfo; echo '@@'; cat /proc/uptime; echo '@@'; uname -r; echo '@@'; df -B1 --output=size,used / | tail -1; echo '@@@'; " + Phone.DEVICE_COMMAND, function(t) { + const halves = t.split("@@@\n") + const parts = halves[0].split("@@\n") + return Phone.systemFrom(parts[0], parts[1], parts[2], parts[3], Phone.boardFrom(halves[1])) }) return } if (kind === "battery") { fromCommand(Phone.BATTERY_COMMAND, Phone.batteryFrom); return } if (kind === "alarm") { done({ value: { set: false, time: null, app: null } }); return } if (kind === "notifications") { done({ value: { available: false, count: 0, items: [] } }); return } - if (kind === "device") { done({ value: { model: "Pixel 7 Pro", maker: "Google", android: null, sdk: null, soc: "gs201" } }); return } + if (kind === "device") { + fromCommand(Phone.DEVICE_COMMAND, function(t) { + const b = Phone.boardFrom(t) + return { model: b.model, maker: b.maker, android: null, sdk: null, soc: b.soc } + }) + return + } done({ value: null }) } diff --git a/packages/omamobile-shell/plugins/omamobile.home/owl/phone.js b/packages/omamobile-shell/plugins/omamobile.home/owl/phone.js index bde108adb..a75b07634 100644 --- a/packages/omamobile-shell/plugins/omamobile.home/owl/phone.js +++ b/packages/omamobile-shell/plugins/omamobile.home/owl/phone.js @@ -305,14 +305,37 @@ function batteryFrom(text) { temp: null, voltage: null, health: null, plugged: null, technology: null, cycles: null } } -// /proc/meminfo, /proc/uptime, uname and df -> android.system. -function systemFrom(meminfo, uptime, kernel, df) { +// The board from the device tree: "model" and the "compatible" list, read by +// DEVICE_COMMAND as "\n@@\n". +var DEVICE_COMMAND = "tr -d '\\0' < /proc/device-tree/model 2>/dev/null; echo; echo '@@'; tr '\\0' '\\n' < /proc/device-tree/compatible 2>/dev/null" +// What the device tree doesn't say, for the boards Omarchy Mobile runs on: +// the panel's size, density and top refresh rate (what it can do, not the +// rate it runs at now). +var BOARDS = { + cheetah: { model: "Pixel 7 Pro", soc: "gs201", display: { width: 1440, height: 3120, hz: 120, dpi: 512 } }, + tegu: { model: "Pixel 9a", soc: "zumapro", display: { width: 1080, height: 2424, hz: 120, dpi: 422 } } +} +// "google,gs201-cheetah" or "google,zumapro-tegu" -> codename and SoC. +function boardFrom(text) { + var parts = String(text || "").split("@@\n") + var model = String(parts[0] || "").trim() + var compat = String(parts[1] || "").split("\n").map(function(c) { return c.trim() }).filter(function(c) { return c }) + var m = /^[^,]+,([^-]+)-(.+)$/.exec(compat[0] || "") + var codename = m ? m[2] : null + var known = (codename && BOARDS[codename]) || {} + return { model: known.model || model.replace(/^Google\s+/, "") || null, maker: /^Google\b/.test(model) || /^google,/.test(compat[0] || "") ? "Google" : null, + codename: codename, soc: known.soc || (m ? m[1] : null), display: known.display || null } +} + +// /proc/meminfo, /proc/uptime, uname and df (and the board) -> android.system. +function systemFrom(meminfo, uptime, kernel, df, board) { + var b = board || {} var kb = function(name) { var m = new RegExp("^" + name + ":\\s+(\\d+)", "m").exec(meminfo || ""); return m ? parseInt(m[1], 10) * 1024 : null } var total = kb("MemTotal"), available = kb("MemAvailable") return { kernel: String(kernel || "").trim() || null, uptime: Math.floor(parseFloat(uptime) || 0), memory: { total: total, used: total !== null && available !== null ? total - available : null, available: available }, - storage: storageFrom(df), cpu: { soc: "gs201", maker: "Google", hardware: null, cores: 8, abi: "arm64-v8a", maxMhz: null }, - display: { width: 1440, height: 3120, hz: 120, dpi: 512 }, build: null, codename: "cheetah", patch: null, + storage: storageFrom(df), cpu: { soc: b.soc || null, maker: b.maker || null, hardware: null, cores: 8, abi: "arm64-v8a", maxMhz: null }, + display: b.display || null, build: null, codename: b.codename || null, patch: null, locale: null, timezone: null, launcher: "omamobile", theme: null, apps: 0 } } @@ -366,6 +389,7 @@ if (typeof module !== "undefined") { actionArgv: actionArgv, volumeFrom: volumeFrom, mediaFrom: mediaFrom, MEDIA_FORMAT: MEDIA_FORMAT, modesFrom: modesFrom, systemFrom: systemFrom, storageFrom: storageFrom, batteryFrom: batteryFrom, BATTERY_COMMAND: BATTERY_COMMAND, panelOff: panelOff, DEVICE_ACTIONS: DEVICE_ACTIONS, + boardFrom: boardFrom, DEVICE_COMMAND: DEVICE_COMMAND, BOARDS: BOARDS, CLOCK: CLOCK, frameInterval: frameInterval, frameSlow: frameSlow, frameSkipped: frameSkipped, tickDelay: tickDelay } } diff --git a/packages/omamobile-shell/test/all b/packages/omamobile-shell/test/all index bc9f6533a..b0253eb06 100755 --- a/packages/omamobile-shell/test/all +++ b/packages/omamobile-shell/test/all @@ -469,6 +469,10 @@ grep -c 'Quickshell.execDetached(HomeModel.urlLaunchArgv(text))' plugins/omamobi grep -c 'HomeModel.commandLaunchArgv(\["sh", "-c", tap\])' plugins/omamobile.home/CommandWidget.qml >/dev/null || fail "the text widget's tap goes through omamobile-launch" grep -c '"omamobile-launch", "url", uri' bin/omamobile-nfc-open >/dev/null || fail "NFC links open through omamobile-launch" grep -c 'GLib.timeout_add_seconds(2, follow_rfkill, bus)' bin/omamobile-nfc-open >/dev/null || fail "the NFC service follows the rfkill switch" +grep -c 'GLib.timeout_add_seconds(2, follow_screen, bus)' bin/omamobile-nfc-open >/dev/null || fail "the NFC service stops polling with the screen off" +python3 -B test/nfc-screen.py >/dev/null || { python3 -B test/nfc-screen.py | grep -v '^ok'; fail "screen_lit reads the connectors"; } +grep -c 'polling waits for the screen' bin/omamobile-nfc-open >/dev/null || fail "start_polling leaves the loop off while the screen is dark" +grep -c 'timeout_add_seconds(4' bin/omamobile-nfc-open >/dev/null && fail "the one-shot stop is gone: the screen check stops polling every time" grep -c '"systemctl", "restart", "neard"' bin/omamobile-nfc-open >/dev/null || fail "an NFC unblock restarts neard" grep -c '^Requires=neard' systemd/omamobile-nfc-open.service >/dev/null && fail "omamobile-nfc-open restarts neard, so it must not Require= it (the restart would loop)" grep -c '"omamobile-launch", "empty"' bin/omamobile-widget >/dev/null || fail "the widget agent's terminal gets an empty workspace" diff --git a/packages/omamobile-shell/test/nfc-screen.py b/packages/omamobile-shell/test/nfc-screen.py new file mode 100644 index 000000000..0c0f63010 --- /dev/null +++ b/packages/omamobile-shell/test/nfc-screen.py @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: MIT +# omamobile-nfc-open's screen_lit() against temporary sysfs trees: connected +# and disconnected connectors, DPMS On and Off, and no connectors at all. +import importlib.machinery, importlib.util, os, sys, tempfile, types +sys.dont_write_bytecode = True # never a __pycache__ next to bin/omamobile-nfc-open + +gi = types.ModuleType("gi"); gi.require_version = lambda *a: None +repo = types.ModuleType("gi.repository"); repo.Gio = repo.GLib = types.SimpleNamespace() +sys.modules.update({"gi": gi, "gi.repository": repo}) +loader = importlib.machinery.SourceFileLoader("nfc_open", os.path.join(os.path.dirname(__file__), "..", "bin", "omamobile-nfc-open")) +nfc = importlib.util.module_from_spec(importlib.util.spec_from_loader("nfc_open", loader)); loader.exec_module(nfc) + +fails = 0 +def case(name, connectors, want): + global fails + with tempfile.TemporaryDirectory() as drm: + for conn, (status, dpms) in connectors.items(): + os.makedirs(f"{drm}/{conn}") + open(f"{drm}/{conn}/status", "w").write(status + "\n") + open(f"{drm}/{conn}/dpms", "w").write(dpms + "\n") + got = nfc.screen_lit(drm) + print(("ok" if got == want else "not ok") + f" - {name}") + fails += got != want + +case("panel on", {"card1-DSI-1": ("connected", "On")}, True) +case("panel off", {"card1-DSI-1": ("connected", "Off")}, False) +case("panel off, a disconnected output on", {"card1-DSI-1": ("connected", "Off"), "card1-DP-1": ("disconnected", "On")}, False) +case("two connected, one on", {"card1-DSI-1": ("connected", "Off"), "card1-HDMI-A-1": ("connected", "On")}, True) +case("only a disconnected output", {"card1-DP-1": ("disconnected", "Off")}, True) +case("no connectors at all", {}, True) +sys.exit(1 if fails else 0) diff --git a/packages/omamobile-shell/test/owl-core.js b/packages/omamobile-shell/test/owl-core.js index 8018a612e..0e595f031 100644 --- a/packages/omamobile-shell/test/owl-core.js +++ b/packages/omamobile-shell/test/owl-core.js @@ -341,6 +341,17 @@ test("phone actions and android.* answers, with mocks", () => { eq([sys.kernel, sys.uptime, sys.memory], ["7.3.0", 123, { total: 8192000, used: 5120000, available: 3072000 }]) eq(P.systemFrom("", "1", "7.3.0\n", " 116041613312 16160268288\n").storage, { total: 116041613312, used: 16160268288, available: 99881345024 }) eq([sys.storage, P.storageFrom("Size Used"), P.storageFrom("0 0")], [null, null, null]) + // the board comes from the device tree, not a fixed Pixel 7 Pro + const tegu = P.boardFrom("Google Pixel 9a\n@@\ngoogle,zumapro-tegu\ngoogle,zumapro\n") + eq([tegu.model, tegu.maker, tegu.codename, tegu.soc, tegu.display.width], ["Pixel 9a", "Google", "tegu", "zumapro", 1080]) + const cheetah = P.boardFrom("Google Pixel 7 Pro\n@@\ngoogle,gs201-cheetah\ngoogle,gs201\n") + eq([cheetah.model, cheetah.codename, cheetah.soc, cheetah.display.height], ["Pixel 7 Pro", "cheetah", "gs201", 3120]) + const other = P.boardFrom("OnePlus 13\n@@\noneplus,sm8750-dodge\nqcom,sm8750\n") + eq([other.model, other.maker, other.codename, other.soc, other.display], ["OnePlus 13", null, "dodge", "sm8750", null]) + eq([P.boardFrom("").model, P.boardFrom("").codename], [null, null]) + const s9 = P.systemFrom("", "1", "7.3.0\n", "", tegu) + eq([s9.codename, s9.cpu.soc, s9.display.dpi], ["tegu", "zumapro", 422]) + eq([P.systemFrom("", "1", "7.3.0\n").codename, P.systemFrom("", "1", "7.3.0\n").display], [null, null]) eq([P.batteryFrom("97\nCharging\n").level, P.batteryFrom("97\nCharging\n").charging, P.batteryFrom("97\nCharging\n").status], [97, true, "charging"]) eq([P.batteryFrom("").level, P.batteryFrom("").status], [null, null]) eq([P.panelOff("0\n"), P.panelOff("4\n"), P.panelOff("")], [false, true, false]) diff --git a/packages/omamobile-shell/version b/packages/omamobile-shell/version index 16c9e92a2..f5ab2b1dd 100644 --- a/packages/omamobile-shell/version +++ b/packages/omamobile-shell/version @@ -1 +1 @@ -0.2.45 +0.2.49