dashboard/docs/screenshots/app.py
bashynx fb3c01cdd7 dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:56:19 +02:00

164 lines
8.1 KiB
Python

#!/usr/bin/env python3
"""The phone app's screenshots, from the demo dashboard's made-up data, on an Android emulator.
tests/server-setup.sh --keep a sync server on :18080 (prints its token)
python3 docs/screenshots/make.py --keep & the demo dashboard on :8199
<an emulator running> e.g. emulator -avd <a Pixel-sized AVD> -no-window
python3 docs/screenshots/app.py --token <the server's token> → docs/screenshots/app-*.png
It connects the demo dashboard to the server (passphrase "correct horse battery"), adds a phone, installs
a debug build of the app (a debug build accepts the test server's plain http), connects it the way a phone
without a camera does (server + token typed in), lets it sync, and photographs each section. Buttons are
found by their labels (uiautomator), not by position. The status bar is put in Android's demo mode.
"""
import argparse
import http.cookiejar
import json
import os
import re
import shutil
import subprocess
import time
import urllib.parse
import urllib.request
from datetime import date, timedelta
HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(os.path.dirname(os.path.dirname(HERE)), "app")
DEMO = "http://127.0.0.1:8199"
PASSPHRASE = "correct horse battery"
PACKAGE = "dev.bashynx.dash_app"
def adb_path():
for d in (os.environ.get("ANDROID_HOME"), os.environ.get("ANDROID_SDK_ROOT")):
if d and os.path.exists(os.path.join(d, "platform-tools", "adb")):
return os.path.join(d, "platform-tools", "adb")
return shutil.which("adb") or "adb"
class Phone:
def __init__(self, adb):
self.adb = adb
def sh(self, *args, out=False):
r = subprocess.run([self.adb, *args], capture_output=True, check=True)
return r.stdout if out else None
def nodes(self):
"""What's on screen: [(label, (x, y) of its centre)] — text or content-desc."""
self.sh("shell", "uiautomator", "dump", "/sdcard/ui.xml")
xml = self.sh("exec-out", "cat", "/sdcard/ui.xml", out=True).decode()
out = []
for n in re.findall(r"<node [^>]*>", xml):
label = (re.search(r'text="([^"]*)"', n).group(1) or re.search(r'content-desc="([^"]*)"', n).group(1))
x1, y1, x2, y2 = map(int, re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', n).groups())
cls = re.search(r'class="([^"]*)"', n).group(1)
out.append((label.replace("&#10;", "\n"), ((x1 + x2) // 2, (y1 + y2) // 2), cls))
return out
def find(self, start, wait=20, exact=False):
"""The centre of the first thing whose label starts with `start` (or is it: exact); waits for it."""
t = time.time()
while time.time() - t < wait:
nodes = self.nodes()
if any("isn't responding" in label for label, _, _ in nodes): # a just-booted emulator's System UI
self.sh("shell", "input", "tap", *map(str, next(xy for label, xy, _ in nodes if label == "Wait")))
time.sleep(2)
continue
for label, xy, _ in nodes:
if label == start if exact else label.startswith(start):
return xy
time.sleep(1)
raise SystemExit(f"not on screen: {start!r}")
def tap(self, start, wait=20, exact=False):
x, y = self.find(start, wait, exact)
self.sh("shell", "input", "tap", str(x), str(y))
def shot(self, path, settle=3):
time.sleep(settle)
with open(path, "wb") as f:
f.write(self.sh("exec-out", "screencap", "-p", out=True))
print(" ", os.path.basename(path))
def demo_phone_token(server, token):
"""Connect the demo dashboard to the server, push its data, add the device "phone" → its token."""
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
op.open(urllib.request.Request(DEMO + "/login", data=urllib.parse.urlencode(
{"name": "demo", "password": "demo-password-1", "next": "/"}).encode(), headers={"Origin": DEMO}))
def post(path, body):
req = urllib.request.Request(DEMO + path, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "Origin": DEMO})
try:
return json.loads(op.open(req, timeout=120).read())
except urllib.error.HTTPError as e:
raise SystemExit(f"{path}: {e.code} {e.read()[:300]!r}")
if not json.loads(op.open(DEMO + "/api/sync").read()).get("account"): # not connected yet
post("/api/sync/connect", {"server": server, "token": token, "passphrase": PASSPHRASE})
try: # a rerun: the old "phone" makes way
post("/api/sync/revoke", {"name": "phone"})
except SystemExit:
pass # there was none
phone = post("/api/sync/add", {"name": "phone"})
print("demo dashboard:", post("/api/sync/now", {}))
return phone["token"]
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--token", required=True, help="the sync server's token for the device 'dashboard'")
ap.add_argument("--server", default="http://127.0.0.1:18080", help="the server, as this computer reaches it")
ap.add_argument("--from-phone", default="http://10.0.2.2:18080", help="the server, as the emulator reaches it")
ap.add_argument("--apk", help="an APK to install (default: build a debug one)")
ap.add_argument("--out", default=HERE)
a = ap.parse_args()
phone_token = demo_phone_token(a.server, a.token)
apk = a.apk
if not apk:
flutter = shutil.which("flutter") or "flutter"
subprocess.run([flutter, "build", "apk", "--debug"], cwd=APP, check=True)
apk = os.path.join(APP, "build", "app", "outputs", "flutter-apk", "app-debug.apk")
p = Phone(adb_path())
p.sh("install", "-r", apk)
p.sh("shell", "pm", "clear", PACKAGE) # a phone that has never connected
p.sh("shell", "settings", "put", "global", "sysui_demo_allowed", "1")
for cmd in (["enter"], ["clock", "-e", "hhmm", "0930"], ["battery", "-e", "level", "100", "-e", "plugged", "false"],
["network", "-e", "wifi", "show", "-e", "level", "4", "-e", "fully", "true", "-e", "mobile", "hide"],
["notifications", "-e", "visible", "false"]):
p.sh("shell", "am", "broadcast", "-a", "com.android.systemui.demo", "-e", "command", *cmd)
p.sh("shell", "monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
p.find("Connect to your dashboard", wait=60)
out = lambda n: os.path.join(a.out, f"app-{n}.png")
p.shot(out("connect"))
fields = [xy for _, xy, cls in p.nodes() if cls.endswith("EditText")]
for xy, text in zip(fields, (a.from_phone, phone_token, PASSPHRASE)):
p.sh("shell", "input", "tap", *map(str, xy))
time.sleep(1) # the field has the focus before typing
p.sh("shell", "input", "text", text.replace(" ", "%s"))
p.sh("shell", "input", "keyevent", "4") # the keyboard away
time.sleep(1)
p.tap("Connect", exact=True) # the button, not "Connect to your dashboard"
p.find("Health\nTab 1", wait=180) # connected; the first sync runs
time.sleep(20)
p.shot(out("health"))
for tab in ("Sleep", "Body", "Cycle"):
p.tap(tab)
p.shot(out(tab.lower()))
p.tap("Food\nTab 2")
p.shot(out("food"), 4)
p.tap("Work\nTab 3")
last_weekday = date.today() - timedelta(days=max(0, date.today().weekday() - 4))
p.tap(last_weekday.strftime("%a")[:2] + f" {last_weekday.day}") # the day bar: a weekday has entries
p.shot(out("work"), 4)
p.tap("Notes\nTab 4")
p.shot(out("notes"), 4)
p.tap("Weather\nTab 5")
p.shot(out("weather"), 8)
p.sh("shell", "am", "broadcast", "-a", "com.android.systemui.demo", "-e", "command", "exit")
print("pictures in", a.out)
if __name__ == "__main__":
main()