aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/tablet.py
blob: 08f12face89f1a12e24c10534535030eafdca5fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# 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 pathlib import Path

from ..module import Module, ModuleError

STATUS = {"2": "charging", "3": "discharging", "4": "not charging", "5": "full"}
TTL = 10  # seconds; each read is two adb round trips
# The settings from before a dim, kept on disk so a server that died or a PC
# that rebooted while the tablet was dim can still put them back.
DIM_FILE = Path.home() / ".cache" / "deck-it" / "dim"


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"]

    tcfg = cfg.get("tablet", {})
    dim_after = max(0, int(tcfg.get("dim_after", 120)))
    level = min(255, max(0, int(tcfg.get("dim_brightness", 8))))
    clock = {"clock_font": bool(tcfg.get("clock_font")), "clock_font_date": bool(tcfg.get("clock_font_date", True))}
    saved = {}   # mode and brightness from before a dim; empty while bright
    try:
        saved["mode"], saved["level"] = DIM_FILE.read_text().split()
    except (OSError, ValueError):
        saved.clear()

    def shell(cmd):
        serial = cache["serial"] or _find_tablet()
        if not serial:
            raise ModuleError("no tablet with the dashboard tunnel")
        try:
            return _adb("-s", serial, "shell", cmd).strip()
        except (subprocess.SubprocessError, OSError) as e:
            raise ModuleError(str(e) or type(e).__name__)

    # The backlight is what drains an LCD, so a dim page alone saves little.
    # Auto brightness is switched off while dimmed, else it raises it again.
    def dim(_=None):
        with lock:
            if not saved:
                saved["mode"] = shell("settings get system screen_brightness_mode")
                saved["level"] = shell("settings get system screen_brightness")
                DIM_FILE.parent.mkdir(parents=True, exist_ok=True)
                DIM_FILE.write_text(f"{saved['mode']} {saved['level']}\n")
                shell(f"settings put system screen_brightness_mode 0;"
                      f" settings put system screen_brightness {level}")

    def undim(_=None):
        with lock:
            if saved:
                shell(f"settings put system screen_brightness {int(saved['level'])};"
                      f" settings put system screen_brightness_mode {int(saved['mode'])}")
                saved.clear()
                DIM_FILE.unlink(missing_ok=True)

    def stop():
        try:
            undim()
        except ModuleError:
            pass

    return Module(name="tablet", title="Tablet",
                  state=lambda: {**state(), "dim_after": dim_after, **clock},
                  actions={"dim": dim, "undim": undim}, stop=stop)