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>
This commit is contained in:
Bashy 2026-10-24 09:35:12 +02:00
commit fb3c01cdd7
333 changed files with 45151 additions and 0 deletions

435
docs/screenshots/make.py Normal file
View file

@ -0,0 +1,435 @@
#!/usr/bin/env python3
"""The README's screenshots, made from a demo dashboard full of made-up data (never anyone's real data).
python3 docs/screenshots/make.py → docs/screenshots/*.png
python3 docs/screenshots/make.py --keep … and leave the demo running at http://127.0.0.1:8199 (Ctrl+C)
What it does: copies dashboard/ into a temporary folder; writes a demo config (Vienna, every plugin on, four
room sensors from a small fake JSON source served here); fills it the way real data arrives — the pages' own
API (calendar, measurements, food, cycle, work, notes), a generated Gadgetbridge export through the real
import (sleep, heart rate, steps, workouts), sensor history and ActivityWatch-style events through the
plugins' storage; then photographs the web pages with Playwright and the 3.5" screens with /api/screen.png.
Needs: the dashboard's packages (dashboard/requirements.txt), and for the web pages Playwright
(pip install playwright && playwright install chromium). The weather is live (Open-Meteo), so it changes.
"""
import argparse
import http.cookiejar
import http.server
import json
import math
import os
import random
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
from datetime import date, datetime, timedelta
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
PORT = 8199
BASE = f"http://127.0.0.1:{PORT}"
ADMIN = ("demo", "demo-password-1")
random.seed(7) # the same "random" data every run
TODAY = date.today()
NOW = datetime.now()
# ---- the fake sensors: a JSON source like an ESPHome / own-script one ------------------------------------
def sensor_values():
h = NOW.hour + NOW.minute / 60
out = 9 + 5 * math.sin((h - 9) / 24 * 2 * math.pi)
return {"living": {"temperature": 21.8, "humidity": 46}, "bedroom": {"temperature": 19.6, "humidity": 52},
"office": {"temperature": 22.9, "humidity": 41}, "garden": {"temperature": round(out, 1), "humidity": 78}}
class SensorJSON(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = json.dumps(sensor_values()).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
SENSORS = [ # id, name, place, JSON path → the history below and the config
(1000, "Living room", "indoor", "living"), (1001, "Bedroom", "indoor", "bedroom"),
(1002, "Office", "indoor", "office"), (1003, "Garden", "outdoor", "garden"),
]
def config(sensor_port, gb_file):
with open(os.path.join(REPO, "dashboard", "dash_config.example.json")) as f:
c = json.load(f)
c.update(location_name="Vienna, AT", lat=48.2082, lon=16.3738, units="metric",
weather_locations=[{"name": "Lisbon, PT", "lat": 38.7223, "lon": -9.1393},
{"name": "Oslo, NO", "lat": 59.9139, "lon": 10.7522}])
c["web"] = dict(c.get("web") or {}, enabled=True, host="127.0.0.1", port=PORT)
c.pop("termix", None)
c["calendar"] = dict(c.get("calendar") or {}, enabled=False, caldav_url="", card_calendars=["Local"],
sleep={"on": True, "start": "23:00", "end": "07:00"},
lunch_break={"on": True, "start": "12:30", "end": "13:15"})
c["sensors"] = {"sources": [{"id": "s1", "type": "json", "label": "Room sensors",
"url": f"http://127.0.0.1:{sensor_port}/sensors.json"}],
"list": [{"id": i, "source": "s1", "temp": f"{p}.temperature", "hum": f"{p}.humidity",
"name": n, "place": place} for i, n, place, p in SENSORS],
"main": 1000}
plugins = c.setdefault("plugins", {})
for name in ("calendar", "weather", "stations", "health", "food", "cycle", "workload", "activity", "notes"):
plugins.setdefault(name, {})["enabled"] = True
plugins["health"].update(sex="male", birth_date="1988-04-12", height=181, sleep_goal=8, gb_export=gb_file)
plugins["workload"].update(currency="EUR", default_rate=60, week_target=40)
return c
# ---- data that comes in through imports / workers ----------------------------------------------------------
def sensor_history(d):
"""35 days of 5-minute rows for the four sensors (the Stations graphs)."""
sys.path.insert(0, d)
from plugins.stations import db as sdb
path = os.path.join(d, "dash_data", "stations", "readings.db")
os.makedirs(os.path.dirname(path), exist_ok=True)
con = sdb.connect(path)
rows, end = [], int(time.time()) // 300 * 300
days = 36
swing = [random.uniform(2, 8) for _ in range(days + 1)] # how much each day warms up
front = [random.uniform(-4, 4) for _ in range(days + 1)] # colder / warmer spells
for did, _, place, p in SENSORS:
base, walk = sensor_values()[p]["temperature"], 0.0
for t in range(end - 35 * 86400, end, 300):
h = datetime.fromtimestamp(t).hour + datetime.fromtimestamp(t).minute / 60
k = (t - (end - 35 * 86400)) / 86400
mood = front[int(k)] + (front[int(k) + 1] - front[int(k)]) * (k % 1)
if place == "outdoor":
walk = max(-1.5, min(1.5, walk + random.uniform(-.08, .08)))
v = 7 + mood + swing[int(k)] * math.sin((h - 9) / 24 * 2 * math.pi) + walk
hum = 92 - 3.5 * (v - 2) + random.uniform(-2, 2)
else:
heating = 0.0 if 6 <= h < 22 else -1.1 # cooler at night
walk = max(-.4, min(.4, walk + random.uniform(-.03, .03)))
v = base + heating + 0.12 * mood + 0.5 * math.sin((h - 16) / 24 * 2 * math.pi) + walk
hum = sensor_values()[p]["humidity"] + 4 * math.sin(k / 3) + random.uniform(-1, 1)
rows.append((did, t, round(v, 2), round(v - .15, 2), round(v + .15, 2), round(max(20, min(98, hum)), 1), 5))
sdb.store_buckets(con, rows)
con.commit()
con.close()
def activity_events(d):
"""Two weeks of a working computer in ActivityWatch's shape (window, AFK and browser buckets)."""
from plugins.activity import db as adb
path = os.path.join(d, "dash_data", "activity", "activity.db")
os.makedirs(os.path.dirname(path), exist_ok=True)
con = adb.connect(path)
adb.source_seen(con, "laptop", "http://127.0.0.1:5600", hostname="laptop", last_ok=int(time.time()))
win = adb.bucket_row(con, "laptop", "aw-watcher-window_laptop", {"type": "currentwindow", "hostname": "laptop"})["id"]
afk = adb.bucket_row(con, "laptop", "aw-watcher-afk_laptop", {"type": "afkstatus", "hostname": "laptop"})["id"]
web = adb.bucket_row(con, "laptop", "aw-watcher-web-firefox", {"type": "web.tab.current", "hostname": "laptop"})["id"]
apps = [("code", "dashboard — web.py — Visual Studio Code", 30), ("code", "sync.py — Visual Studio Code", 20),
("gnome-terminal-server", "pytest — Terminal", 10), ("firefox", "Pull request #42 — GitHub — Firefox", 10),
("thunderbird", "Inbox — Thunderbird", 7), ("slack", "Slack — #team", 8),
("libreoffice-writer", "Quarterly report.odt — LibreOffice Writer", 8),
("firefox", "YouTube — Firefox", 4), ("firefox", "Hacker News — Firefox", 3)]
pages = {"Pull request #42 — GitHub — Firefox": "https://github.com/example/dashboard/pull/42",
"YouTube — Firefox": "https://www.youtube.com/", "Hacker News — Firefox": "https://news.ycombinator.com/"}
w_ev, a_ev, b_ev = [], [], []
for back in range(14, -1, -1):
day = TODAY - timedelta(days=back)
if day.weekday() >= 5:
continue
t = datetime.combine(day, datetime.min.time()).replace(hour=8, minute=random.randint(30, 59))
stop = t.replace(hour=17, minute=random.randint(0, 40))
if back == 0:
stop = min(stop, NOW)
while t < stop:
if t.hour == 12 and t.minute < 40: # lunch away
a_ev.append((int(t.timestamp() * 1000), 45 * 60, {"status": "afk"}))
t += timedelta(minutes=45)
continue
app, title, weight = random.choices(apps, weights=[a[2] for a in apps])[0]
dur = random.randint(3, 25) * 60
ms = int(t.timestamp() * 1000)
w_ev.append((ms, dur, {"app": app, "title": title}))
a_ev.append((ms, dur, {"status": "not-afk"}))
if title in pages:
b_ev.append((ms, dur, {"url": pages[title], "title": title.rsplit(" — ", 1)[0]}))
t += timedelta(seconds=dur)
adb.store_events(con, win, w_ev)
adb.store_events(con, afk, a_ev)
adb.store_events(con, web, b_ev)
con.commit()
con.close()
def gadgetbridge_export(path):
"""A Gadgetbridge database export (the tables the import reads): 30 days of a band."""
from plugins.health import gb
con = sqlite3.connect(path)
con.executescript(gb.RELAY_SCHEMA)
ms = lambda dt: int(dt.timestamp() * 1000)
samples = []
for back in range(30, -1, -1):
day = TODAY - timedelta(days=back)
mid = datetime.combine(day, datetime.min.time())
bed = mid - timedelta(hours=1, minutes=random.randint(-20, 50)) # around 23:00 the evening before
wake = mid + timedelta(hours=6, minutes=random.randint(35, 80))
if wake > NOW:
wake = None
rest = random.randint(54, 59)
walk = mid + timedelta(hours=random.choice([7, 12, 18]), minutes=random.randint(0, 40))
run = mid + timedelta(hours=18, minutes=30) if day.weekday() in (1, 3, 6) else None
end = min(mid + timedelta(days=1), NOW)
t = mid
while t < end:
asleep = t < (wake or NOW) or t >= mid + timedelta(hours=23)
moving = walk <= t < walk + timedelta(minutes=35) or (run and run <= t < run + timedelta(minutes=40))
if moving:
hr, st = (random.randint(135, 160), random.randint(150, 170)) if run and run <= t else (random.randint(95, 112), random.randint(95, 115))
elif asleep:
hr, st = rest + random.randint(-3, 4), 0
else:
hr, st = random.randint(66, 84), random.choice([0, 0, 0, 3, 12, 25])
samples.append((int(t.timestamp()), hr if t.minute % 2 == 0 else 0, st, st * 70))
t += timedelta(minutes=1)
con.execute("INSERT INTO XIAOMI_DAILY_SUMMARY_SAMPLE VALUES (?, ?)", (ms(mid), rest))
if wake:
con.execute("INSERT INTO XIAOMI_SLEEP_TIME_SAMPLE VALUES (?, ?)", (ms(bed), ms(wake)))
t, i = bed, 0
cycle = [(3, 20), (2, 35), (3, 25), (4, 20)] # (stage, minutes) — 2 deep, 3 light, 4 REM
while t < wake:
stage, mins = cycle[i % 4]
if i and i % 9 == 0:
stage, mins = 5, 6 # awake a moment
con.execute("INSERT OR REPLACE INTO XIAOMI_SLEEP_STAGE_SAMPLE VALUES (?, ?)", (ms(t), stage))
t += timedelta(minutes=mins + random.randint(-6, 8))
i += 1
if walk + timedelta(minutes=35) < NOW:
con.execute("INSERT INTO BASE_ACTIVITY_SUMMARY VALUES (?, ?, ?, NULL)",
(ms(walk), ms(walk + timedelta(minutes=35)), 0x20))
if run and run + timedelta(minutes=40) < NOW:
con.execute("INSERT INTO BASE_ACTIVITY_SUMMARY VALUES (?, ?, ?, NULL)", (ms(run), ms(run + timedelta(minutes=40)), 0x10))
con.execute("INSERT OR REPLACE INTO XIAOMI_MANUAL_SAMPLE VALUES (?, 18, ?)",
(ms(mid + timedelta(hours=9)), random.randint(96, 99)))
con.executemany("INSERT OR REPLACE INTO XIAOMI_ACTIVITY_SAMPLE VALUES (?, ?, ?, ?)", samples)
con.commit()
con.close()
# ---- data typed in: through the dashboard's own API -------------------------------------------------------
class Client:
def __init__(self):
self.op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
def call(self, path, body=None, ok=(200,)):
req = urllib.request.Request(BASE + path, data=None if body is None else json.dumps(body).encode(),
headers={"Content-Type": "application/json", "Origin": BASE})
try:
with self.op.open(req, timeout=60) as r:
raw = r.read()
return json.loads(raw) if r.headers.get_content_type() == "application/json" else raw
except urllib.error.HTTPError as e:
if e.code in ok:
return json.loads(e.read() or b"{}")
raise SystemExit(f"{path}: {e.code} {e.read()[:300]!r}")
def fill(c):
day = lambda n: (TODAY + timedelta(days=n)).isoformat()
# calendar (the dashboard's own Local calendar)
for _ in range(60): # the calendar worker's first round lists it
cals = c.call("/api/calendars")
cal = next((t["id"] for t in cals if t["name"] == "Local"), None)
if cal:
break
time.sleep(1)
else:
raise SystemExit(f"no Local calendar to write to: {cals}")
monday = -TODAY.weekday()
week = [(0, "09:30", "09:45", "Stand-up", ""), (0, "11:00", "12:00", "Design review", "Room 2"),
(1, "10:00", "11:30", "Sprint planning", ""), (1, "19:00", "21:00", "Climbing", "Boulder hall"),
(2, "13:00", "14:00", "Lunch talk: SQLite", ""), (3, "14:00", "15:00", "1:1 with Sam", ""),
(4, "15:00", "16:00", "Retro", ""), (4, "18:30", "22:00", "Dinner at Marta's", "")]
events = [(monday + 7 * w + n, a, b, t, p) for w in (0, 1) for n, a, b, t, p in week]
events += [(0, "08:15", "08:45", "Call with Ana", ""), (0, "16:00", "16:45", "Dentist", "Main St 14")]
for n, a, b, title, where in events:
c.call("/api/events", {"cal": cal, "date": day(n), "start": a, "end": b, "title": title, "location": where})
for n, title in ((5, "Mia's birthday"), (9, "Trip to Lisbon"), (16, "Concert")):
c.call("/api/events", {"cal": cal, "date": day(n), "all_day": True, "title": title})
# body measurements: a slow trend, a tape measure now and then, blood pressure
for back in range(90, -1, -1):
if back % 3 and back > 7:
continue
w = 84.2 - (90 - back) * 0.035 + random.uniform(-.35, .35)
m = {"day": day(-back), "weight": round(w, 1)}
if back % 14 == 0:
m.update(waist=round(92 - (90 - back) * 0.03, 1), neck=39, hip=99)
c.call("/health/api/measure", m)
for back in (20, 13, 6, 1):
c.call("/health/api/vital", {"kind": "bp", "day": day(-back), "time": "08:10",
"sys": random.randint(116, 124), "dia": random.randint(74, 80)})
# food: three days of meals from the food database
def food(q):
r = c.call("/food/api/foods?q=" + urllib.request.quote(q))["db"]
return f"usda:{r[0]['id']}" if r else None
menu = [("breakfast", "07:30", [("oatmeal", 250), ("banana", 120), ("coffee brewed", 250)]),
("lunch", "12:45", [("chicken breast", 150), ("rice cooked", 200), ("broccoli", 120)]),
("snack", "16:00", [("apple", 180), ("almonds", 25)]),
("dinner", "19:15", [("salmon", 140), ("boiled potatoes", 220), ("mixed salad greens", 100)])]
for back in (2, 1, 0):
for meal, at, items in menu:
if back == 0 and meal == "dinner":
continue
for q, g in items:
ref = food(q)
if ref:
c.call("/food/api/entry", {"day": day(-back), "time": at, "meal": meal, "food": ref,
"amount": round(g * random.uniform(.9, 1.1)), "unit": "g", "note": ""})
# cycle: three periods
for start in (-58, -30, -2):
for i in range(5):
if start + i <= 0:
c.call("/cycle/api/day", {"day": day(start + i), "period": True, "flow": [3, 4, 3, 2, 1][i]})
# work: two customers, projects, a week of entries
node = lambda d: c.call("/work/api/node", d)["id"]
acme = node({"kind": "client", "name": "Acme Corp", "billable": True, "currency": "EUR"})
shop = node({"kind": "project", "name": "Web shop", "parent_id": acme})
api = node({"kind": "project", "name": "Mobile API", "parent_id": acme})
north = node({"kind": "client", "name": "Northwind", "billable": True})
audit = node({"kind": "project", "name": "Security audit", "parent_id": north})
own = node({"kind": "client", "name": "Internal", "billable": False})
for n in range(monday, 1):
if n < 0 or n == 0:
plan = [(shop, "08:30", "12:00"), (api, "13:00", "15:30"), (audit, "15:45", "17:30")] if n % 2 else \
[(audit, "09:00", "11:30"), (own, "11:30", "12:15"), (shop, "13:00", "17:00")]
for nid, a, b in plan:
if n == 0 and int(b[:2]) > NOW.hour:
continue
c.call("/work/api/entry", {"node_id": nid, "date": day(n), "start": a, "end": b,
"billable": nid != own, "note": ""})
# notes
for folder, text, pinned in [
("", "# Shopping\n- [x] milk\n- [ ] coffee beans\n- [ ] olive oil\n- [ ] #home light bulbs", True),
("Work", "# Sprint 14 ideas\nSync the weather places to the app. Faster cold start. #ideas", False),
("Work", "# Release checklist\n1. Tests green\n2. Changelog\n3. Tag + publish the APK #release", False),
("Home", "# Wi-Fi for guests\nNetwork: *guests* — the password is on the fridge.", False),
("", "# Books to read\n- The Pragmatic Programmer\n- Designing Data-Intensive Applications #books", False)]:
c.call("/notes/api/save", {"body": text, "folder": folder, "pinned": pinned})
# ---- the pictures ---------------------------------------------------------------------------------------
PAGES = [ # file, path, width, height, what to click first (a selector) or None, full page?
("home", "/", 1920, 1080, None, False),
("week", "/week", 1600, 1000, None, False),
("weather", "/weather", 1440, 1000, None, True),
("stations", "/stations?r=7d", 1440, 900, None, True),
("health", "/health", 1440, 1000, None, True),
("sleep", "/health/sleep", 1440, 1000, None, True),
("food", "/food", 1440, 1000, None, True),
("work", "/work", 1600, 1000, None, False),
("activity", "/activity?d=" + (TODAY - timedelta(days=max(0, TODAY.weekday() - 4))).isoformat(), 1440, 1000, None, True),
("notes", "/notes", 1440, 900, "text=Release checklist", False),
("settings", "/settings#general", 1440, 1000, None, False),
("settings-sensors", "/settings#sensors", 1440, 900, None, False),
("phone-home", "/", 390, 844, None, False),
("phone-food", "/food", 390, 844, None, False),
]
SCREENS = ["Home", "Temp", "Weather", "Cal"]
def shoot(c, out):
for name in SCREENS: # the 3.5" panel: no browser needed
with open(os.path.join(out, f"screen-{name.lower()}.png"), "wb") as f:
f.write(c.call(f"/api/screen.png?n={name}"))
try:
from playwright.sync_api import sync_playwright
except ImportError:
print("Playwright isn't installed: only the 3.5\" screens were made "
"(pip install playwright && playwright install chromium)")
return
with sync_playwright() as p:
b = p.chromium.launch()
ctx = b.new_context(device_scale_factor=1)
page = ctx.new_page()
page.goto(BASE + "/login")
page.locator("input[name=name]").fill(ADMIN[0])
page.locator("input[type=password]").fill(ADMIN[1])
page.keyboard.press("Enter")
page.wait_for_url(lambda u: "/login" not in u)
for name, path, w, h, click, full in PAGES:
page.set_viewport_size({"width": w, "height": h})
page.goto(BASE + path)
page.wait_for_load_state("networkidle")
if click:
page.click(click)
page.wait_for_timeout(1500)
page.add_style_tag(content=".sound-off { display: none !important; }")
page.screenshot(path=os.path.join(out, f"{name}.png"), full_page=full)
print(" ", name)
b.close()
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--keep", action="store_true", help="leave the demo running afterwards")
ap.add_argument("--out", default=HERE, help="where the pictures go (default: next to this script)")
a = ap.parse_args()
tmp = tempfile.mkdtemp(prefix="dash-demo-")
d = os.path.join(tmp, "dashboard")
shutil.copytree(os.path.join(REPO, "dashboard"), d, ignore=shutil.ignore_patterns("__pycache__", "dash_data",
"dash_config.json", "dash_*.json"))
os.makedirs(os.path.join(d, "dash_data", "food"))
shutil.copyfile(os.path.join(REPO, "app", "assets", "foods.db"), os.path.join(d, "dash_data", "food", "foods.db"))
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SensorJSON)
threading.Thread(target=srv.serve_forever, daemon=True).start()
gb_file = os.path.join(tmp, "Gadgetbridge.db")
with open(os.path.join(d, "dash_config.json"), "w") as f:
json.dump(config(srv.server_address[1], gb_file), f, indent=1)
os.chdir(d)
sensor_history(d)
activity_events(d)
gadgetbridge_export(gb_file)
print(f"demo dashboard: {d}")
log = open(os.path.join(tmp, "dash.log"), "w")
proc = subprocess.Popen([sys.executable, "dash.py", "--headless"], cwd=d, stdout=log, stderr=subprocess.STDOUT)
try:
c = Client()
for _ in range(60):
try:
urllib.request.urlopen(BASE + "/login", timeout=2)
break
except OSError:
time.sleep(0.5)
c.call("/api/users/save", {"name": ADMIN[0], "password": ADMIN[1], "role": "admin"}) # the first: logged in
fill(c)
print("band import:", c.call("/health/api/gb/import", {}).get("result"))
time.sleep(35) # the sensors' first poll, the weather, the summaries
os.makedirs(a.out, exist_ok=True)
shoot(c, a.out)
print(f"pictures in {a.out}")
if a.keep:
print(f"the demo runs at {BASE} — log in as {ADMIN[0]} / {ADMIN[1]}; Ctrl+C stops it")
proc.wait()
except KeyboardInterrupt:
pass
finally:
proc.terminate()
proc.wait()
srv.shutdown()
if not a.keep:
shutil.rmtree(tmp, ignore_errors=True)
if __name__ == "__main__":
main()