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>
76
docs/app.md
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
# The phone app
|
||||
|
||||
Flutter, Android. It keeps its own copy of the data, works offline and syncs through your server
|
||||
([server.md](server.md)) about every 5 minutes while open and about hourly in the background.
|
||||
|
||||
## Build
|
||||
|
||||
You need Flutter with Dart 3.12 or newer (the app is built with Flutter 3.44) and the Android SDK.
|
||||
|
||||
```bash
|
||||
cd app
|
||||
flutter pub get
|
||||
flutter test
|
||||
flutter build apk --release
|
||||
```
|
||||
|
||||
Install `build/app/outputs/flutter-apk/app-release.apk` on the phone.
|
||||
|
||||
### Signing
|
||||
|
||||
A release build without a key is signed with the debug key. That APK installs, but your later builds can't
|
||||
update it, and it can't update a properly signed install. Make a key once and keep it safe, outside the
|
||||
repo:
|
||||
|
||||
```bash
|
||||
keytool -genkey -v -keystore ~/keys/dashpi-upload.jks -keyalg RSA -keysize 4096 -validity 10000 -alias dashpi
|
||||
```
|
||||
|
||||
`app/android/key.properties` (git ignores it):
|
||||
|
||||
```
|
||||
storeFile=/home/you/keys/dashpi-upload.jks
|
||||
storePassword=…
|
||||
keyAlias=dashpi
|
||||
keyPassword=…
|
||||
```
|
||||
|
||||
### Your own defaults (optional)
|
||||
|
||||
These can be built in with `--dart-define` so the app starts with them; all of them can also be set in the app:
|
||||
|
||||
| Define | What | In the app |
|
||||
|---|---|---|
|
||||
| `DEV_SERVER` | The server the connect screen suggests, e.g. `https://sync.example.com` | Connect screen |
|
||||
| `PI_URL` | The dashboard on your home network, e.g. `http://192.168.1.50:8080`, for "sync now" | Sync page ▸ Dashboard on the home network |
|
||||
| `HOME_PLACES` | Weather places, home first: `Home, XX\|47.17\|24.06;Town, XX\|46.77\|23.60` | Weather ▸ Add a place |
|
||||
|
||||
## Connect
|
||||
|
||||
1. Set up sync on the dashboard first (Settings ▸ General ▸ Sync, [dashboard.md](dashboard.md)).
|
||||
2. There: **Devices ▸ Add a device** → a QR code.
|
||||
3. In the app: **Scan the code from the dashboard**, then type the passphrase (or use the recovery key).
|
||||
Without a camera, type the server and token shown under the code.
|
||||
|
||||
The token and the data key are kept in Android's keystore-backed secure storage. The app's database is
|
||||
excluded from Android backups; the dashboard keeps the data anyway.
|
||||
|
||||
**Sync now:** with the dashboard's address set (Sync page), the app asks the dashboard on the home network
|
||||
to process new band data right away. The request is sealed with the data key. Away from home nothing happens.
|
||||
|
||||
**Gadgetbridge:** Sync page ▸ Band (Gadgetbridge): pick Gadgetbridge's database export (Gadgetbridge ▸ Settings ▸ Auto
|
||||
export). The app relays new rows to the dashboard, which works out the sleep, heart and activity summaries.
|
||||
|
||||
## Updates over the air (optional)
|
||||
|
||||
The app can update itself from your sync server. `tool/publish.sh` builds the next build number, signs it
|
||||
and uploads `app.json` + the APK to the server's `app/` folder over SSH. Phones then offer it on the Sync page.
|
||||
|
||||
```bash
|
||||
cp tool/publish.env.example tool/publish.env # your server, SSH login, defines
|
||||
# write a "## x.y.z — date" entry in CHANGELOG.md for the pubspec version
|
||||
tool/publish.sh
|
||||
```
|
||||
|
||||
The primary dashboard mirrors the newest build at `http://<dashboard>:8080/app` for a first install on the
|
||||
home network.
|
||||
58
docs/architecture.md
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# How it fits together
|
||||
|
||||
```
|
||||
3.5" SPI screen ◄── dash.py (Pillow → RGB565 → /dev/fb0) ──┐
|
||||
touch (evdev) ──► │ one Python process:
|
||||
│ workers fill a shared Store,
|
||||
browser / TV ◄── web.py (Flask, :8080) ─────────────────┤ the screen and the web pages
|
||||
│ read it
|
||||
plugins/<name>/ (pages, workers, data in dash_data/<name>/*.db)
|
||||
│
|
||||
syncdb.py stamps every change; sync.py sends / receives
|
||||
│ XChaCha20-Poly1305, key never leaves the devices
|
||||
▼
|
||||
server/ (PHP + SQLite): encrypted batches, in order
|
||||
▲
|
||||
app/ (Flutter): its own SQLite copy, same merge rules
|
||||
```
|
||||
|
||||
## The dashboard (`dashboard/`)
|
||||
|
||||
- **No X, no Wayland.** Each tick `screens.render()` draws a 480×320 PIL image, `panel.to_rgb565()` packs it,
|
||||
and it's written to the panel's framebuffer
|
||||
(found by itself: `panel.find_screen`; none = web pages only). Redraws about once a second and on touch.
|
||||
- **Store** (`store.py`): the shared state the workers fill (weather, calendar, sensors) and the screen and
|
||||
pages read.
|
||||
- **Plugins** (`pluginhost.py`): every feature beyond the clock is a package in `plugins/<name>/` with a `META`
|
||||
and `register(ctx)`. `ctx` is the whole API: a blueprint for pages, Home regions, 3.5" screens,
|
||||
workers, settings fields, cached pages, sync specs. A plugin keeps its data in `dash_data/<name>/`.
|
||||
Turning one on or off needs no restart.
|
||||
- **Web** (`web.py`): Jinja pages that fill a landscape screen without scrolling and stack on phones. They
|
||||
refresh every minute and reload after a deploy.
|
||||
- **Users** (`auth.py`): admin, members (a subset of sections), and the household (no login, read only;
|
||||
also what the 3.5" screen shows).
|
||||
- **Settings** (`settings.py`): `dash_config.json`, validated, applied live where possible.
|
||||
|
||||
Import direction is one way: `config` ← `store` ← `panel` ← screen modules ← `dash`. The plugins only use `ctx`
|
||||
(the built-in weather, calendar and stations plugins also use the Store and the drawing helpers).
|
||||
|
||||
## Sync
|
||||
|
||||
Every device keeps a full copy. Changes go through the server, which only stores encrypted batches.
|
||||
|
||||
- `syncdb.py` adds `_uid`, `_hlc` (hybrid logical clock, ms) and `_dev` to every synced table, and triggers that
|
||||
stamp each insert/update and turn deletes into tombstones. Plugin code doesn't change.
|
||||
- Which tables sync is each plugin's `META["sync"]`. Foreign keys travel as the target's `_uid`.
|
||||
- Merge: the last change wins by (`_hlc`, `_dev`); a tombstone beats older changes. Notes are documents with
|
||||
revisions, and two edits made at the same time keep both, as a conflicted copy.
|
||||
- Keys: one random data key, wrapped on the server with Argon2id(passphrase). The recovery key is the data key
|
||||
in base32.
|
||||
|
||||
The full protocol, which the app follows to the letter: [server/PROTOCOL.md](../server/PROTOCOL.md).
|
||||
|
||||
## The app (`app/`)
|
||||
|
||||
Flutter, Android. `lib/sync/` is the protocol (store, crypto, client). `lib/health`, `lib/work`, `lib/notes`
|
||||
and `lib/weather` are the pages. They are ports of the dashboard's views, and their numbers must match.
|
||||
Health summaries from the band (sleep, heart rate, energy) are worked out on the primary dashboard and
|
||||
synced to the app one way.
|
||||
139
docs/dashboard.md
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
# The dashboard
|
||||
|
||||
## What you need
|
||||
|
||||
- **With the screen:** a Raspberry Pi (a Pi 3 is enough) on Raspberry Pi OS Bookworm or newer, and a 3.5"
|
||||
480×320 SPI TFT on the GPIO header. The common ILI9486 + XPT2046 "piscreen" boards work.
|
||||
- **Without a screen:** any Linux machine (Debian/Ubuntu for the install script). With no small screen found it runs
|
||||
the web pages and background workers only; `--headless` forces that.
|
||||
|
||||
## The screen (skip for headless)
|
||||
|
||||
In `/boot/firmware/config.txt`:
|
||||
|
||||
```
|
||||
dtparam=spi=on
|
||||
dtoverlay=piscreen,speed=16000000,rotate=270
|
||||
```
|
||||
|
||||
Reboot. The panel should appear as `/dev/fb0` (RGB565, 480×320) and touch as an `ads7846` input device.
|
||||
To keep the console from blanking the panel, add ` consoleblank=0` to the single line in
|
||||
`/boot/firmware/cmdline.txt`. The first start runs a 5-point touch calibration; `dash.py --calibrate`
|
||||
redoes it.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
git clone https://git.hackman.club/HackmanClub/dashboard.git dashpi
|
||||
cd dashpi
|
||||
sudo ./dashboard/install.sh # with the screen, runs as you
|
||||
sudo ./dashboard/install.sh --headless # without
|
||||
```
|
||||
|
||||
The script installs the apt packages, copies `dashboard/` to `/opt/dashboard` and writes
|
||||
`/opt/dashboard/dash_config.json` from the example if there isn't one. It then installs and starts the
|
||||
`dashboard` systemd service. Options: `--dir`, `--user <name>` (creates a system user if missing),
|
||||
`--no-apt`, `--no-service`.
|
||||
|
||||
**Update:** `git pull`, then run the same command again. Your `dash_config.json`, `dash_data/` and the
|
||||
other state files in `/opt/dashboard` are never touched.
|
||||
|
||||
Without the script (another distro, a virtualenv): install the packages from
|
||||
[`dashboard/requirements.txt`](../dashboard/requirements.txt) plus the DejaVu fonts (and Symbola for emoji
|
||||
on the screen). Copy `dash_config.example.json` to `dash_config.json` and run `python3 dash.py [--headless]`.
|
||||
|
||||
## First start (everything else is in the browser)
|
||||
|
||||
1. Open `http://<the machine>:8080/settings`.
|
||||
2. **Settings ▸ Users:** create the admin account. It asks for the **setup code** printed in the log:
|
||||
`journalctl -u dashboard | grep 'setup code'`. From the machine itself (`localhost`) no code is needed.
|
||||
3. **Settings ▸ Users ▸ Household view:** choose what people see without a login (the 3.5" screen too).
|
||||
By default that's weather and sensors, with no calendars.
|
||||
4. **Weather:** search your town; add more places for the weather page. The phone app gets the same places.
|
||||
**Calendar:** any ICS feeds (Google's "secret address in iCal format", Outlook, holidays), and if you have
|
||||
one, Nextcloud / CalDAV (URL, user name, an app password: Nextcloud ▸ Settings ▸ Security). The dashboard's
|
||||
own Local calendar works with neither.
|
||||
5. **Sensors:** **+ Add sensor source**, pick the kind, **Test** it, then **+ Add** the readings you want (below).
|
||||
6. **Plugins:** switch on the ones you want. Each has its own settings tab.
|
||||
|
||||
## Configuration
|
||||
|
||||
Everything is in the Settings page and stored in `dash_config.json` (chmod 600, it holds the passwords). The only
|
||||
key without a page is `web.enabled` (`false` by default, `true` in the example the installer copies).
|
||||
|
||||
**Settings ▸ General** (besides units, the plugins and Sync):
|
||||
- **Web pages:** who can open them (everyone on the network / only this computer), the port, and extra host
|
||||
names it answers to. IP addresses, `localhost` and this machine's name (+ `.local` / `.lan` / `.home`) always work.
|
||||
- **Screen:** where to draw. "Find it" uses a small SPI panel and never a desktop's own display; or pick one, or none.
|
||||
It also recalibrates the touch screen.
|
||||
- **Backup:** download one, or restore one (also to move to a new machine).
|
||||
|
||||
For the command-line tools only: `FOOD_COUNTRIES` (`plugins/food/off.py`: whose shop products go into the
|
||||
food database, e.g. `romania,slovakia`) and `DASH_TZ` (the Health time zone for `plugins/health/mi.py`; on
|
||||
the dashboard it's Settings ▸ Health; left empty, the phone app's time zone, sent with the band's data, else the
|
||||
machine's).
|
||||
|
||||
## Plugins
|
||||
|
||||
| Plugin | On by default | Needs |
|
||||
|---|---|---|
|
||||
| Weather | yes | Nothing (Open-Meteo, no key) |
|
||||
| Calendar | yes | A CalDAV server and/or ICS links |
|
||||
| Measurement stations | yes | A sensor source (below); hidden until configured |
|
||||
| Workload tracker | no | |
|
||||
| Health | no | Optional: a Gadgetbridge database export folder (e.g. synced with Syncthing) |
|
||||
| Food diary | no | Optional: an Ollama-style model URL for the "describe what you ate" box |
|
||||
| Cycle tracker | no | |
|
||||
| Notes | no | |
|
||||
| Activity | no | [ActivityWatch](https://activitywatch.net) on each computer, listening on the LAN (`aw-server.toml`: `host = "0.0.0.0"`) |
|
||||
|
||||
Each plugin is a folder in `dashboard/plugins/<name>/` with a `META` and a `register(ctx)`. See the docstring
|
||||
of `dashboard/pluginhost.py` for writing your own.
|
||||
|
||||
### Sensors (Measurement stations)
|
||||
|
||||
**Settings ▸ Sensors**: **+ Add sensor source** and pick the kind (the table below), press **Test** to see what it
|
||||
has, and **+ Add** the readings to show.
|
||||
Name them, put each indoor / outdoor / hidden, order them, and tick **Main** on the one shown as the big temperature
|
||||
on Home (any indoor or outdoor one; by default the first indoor one). Up to 3 outdoor ones sit next to the weather.
|
||||
Saving applies at once.
|
||||
|
||||
| Source | What to give it | What a sensor reads |
|
||||
|---|---|---|
|
||||
| **Home Assistant** | Its URL + a long-lived access token (your profile ▸ Security) | An entity (`sensor.kitchen_temperature`); humidity from a second entity |
|
||||
| **MQTT** | Broker, port, optional login / TLS (needs `python3-paho-mqtt`) | A topic (`tasmota/attic/temp`) or a JSON field of one (`zigbee2mqtt/garage\|temperature`) |
|
||||
| **JSON URL** | Any URL that answers JSON (ESPHome's web server, Tasmota, your own script), an optional header | A path in the answer (`sensors.0.temp`) |
|
||||
| **DS18B20 (1-wire)** | Nothing: wire it to GPIO 4 and add `dtoverlay=w1-gpio` to `/boot/firmware/config.txt` | The sensor's id (`28-…`) |
|
||||
| **termix** | The `stm32.php` URL, API key and device ids | A device id (temperature + humidity) |
|
||||
|
||||
Temperatures can be in °F (a tick per source); they're kept in °C. Readings are kept as 5-minute rows forever, for
|
||||
the graphs on `/stations` and in the app.
|
||||
|
||||
## Sync, the phone app, more dashboards
|
||||
|
||||
Set up the server first ([server.md](server.md)); it prints this dashboard's token. Then **Settings ▸ General ▸ Sync**:
|
||||
|
||||
1. Server address + token → **Next**. The account's first device chooses the **sync passphrase** and is shown
|
||||
the **recovery key** once. Write it down: without the passphrase or the recovery key, the synced data
|
||||
can't be read.
|
||||
2. **Devices ▸ Add a device** ("phone") shows a QR code. In the app: **Scan the code from the dashboard**,
|
||||
then type the passphrase. Another dashboard: add a device for it, paste its token into that dashboard's
|
||||
Settings ▸ General ▸ Sync, and join with the passphrase. Untick **Primary dashboard** there.
|
||||
3. The same tab: sync now, revoke a lost device, change the passphrase, disconnect.
|
||||
|
||||
The command line does the same: `python3 sync.py setup|join|now|status|passphrase`.
|
||||
|
||||
## Files
|
||||
|
||||
| Path (in `/opt/dashboard`) | What |
|
||||
|---|---|
|
||||
| `dash_config.json` | Settings + secrets (600) |
|
||||
| `dash_data/<plugin>/` | Each plugin's SQLite data (600); `dash_data/auth/users.db` the users, `dash_data/sync/state.json` the sync key |
|
||||
| `dash_calib.json`, `dash_history.json`, `dash_weather.json` | Touch calibration, 24 h sensor history, last weather |
|
||||
|
||||
**Back up** with Settings ▸ General ▸ Backup (or copy `dash_data/` + `dash_config.json`). Everything
|
||||
else comes from git. **Move to a new machine:** install there, create an admin, Settings ▸ General ▸ Restore,
|
||||
then switch the old one off.
|
||||
|
||||
Logs: `journalctl -u dashboard -f`. Don't run `dash.py` by hand while the service runs: both would write
|
||||
the screen.
|
||||
BIN
docs/screenshots/activity.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/screenshots/app-body.png
Normal file
|
After Width: | Height: | Size: 149 KiB |
BIN
docs/screenshots/app-connect.png
Normal file
|
After Width: | Height: | Size: 141 KiB |
BIN
docs/screenshots/app-cycle.png
Normal file
|
After Width: | Height: | Size: 159 KiB |
BIN
docs/screenshots/app-food.png
Normal file
|
After Width: | Height: | Size: 200 KiB |
BIN
docs/screenshots/app-health.png
Normal file
|
After Width: | Height: | Size: 207 KiB |
BIN
docs/screenshots/app-notes.png
Normal file
|
After Width: | Height: | Size: 175 KiB |
BIN
docs/screenshots/app-sleep.png
Normal file
|
After Width: | Height: | Size: 179 KiB |
BIN
docs/screenshots/app-weather.png
Normal file
|
After Width: | Height: | Size: 198 KiB |
BIN
docs/screenshots/app-work.png
Normal file
|
After Width: | Height: | Size: 132 KiB |
164
docs/screenshots/app.py
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
#!/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(" ", "\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()
|
||||
BIN
docs/screenshots/food.png
Normal file
|
After Width: | Height: | Size: 134 KiB |
BIN
docs/screenshots/health.png
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
docs/screenshots/home.png
Normal file
|
After Width: | Height: | Size: 159 KiB |
435
docs/screenshots/make.py
Normal 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()
|
||||
BIN
docs/screenshots/notes.png
Normal file
|
After Width: | Height: | Size: 76 KiB |
BIN
docs/screenshots/phone-food.png
Normal file
|
After Width: | Height: | Size: 50 KiB |
BIN
docs/screenshots/phone-home.png
Normal file
|
After Width: | Height: | Size: 46 KiB |
BIN
docs/screenshots/screen-cal.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
docs/screenshots/screen-home.png
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
docs/screenshots/screen-temp.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
docs/screenshots/screen-weather.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
docs/screenshots/settings-sensors.png
Normal file
|
After Width: | Height: | Size: 85 KiB |
BIN
docs/screenshots/settings.png
Normal file
|
After Width: | Height: | Size: 128 KiB |
BIN
docs/screenshots/sleep.png
Normal file
|
After Width: | Height: | Size: 162 KiB |
BIN
docs/screenshots/stations.png
Normal file
|
After Width: | Height: | Size: 148 KiB |
BIN
docs/screenshots/weather.png
Normal file
|
After Width: | Height: | Size: 115 KiB |
BIN
docs/screenshots/week.png
Normal file
|
After Width: | Height: | Size: 52 KiB |
BIN
docs/screenshots/work.png
Normal file
|
After Width: | Height: | Size: 90 KiB |
101
docs/server.md
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
# The sync server
|
||||
|
||||
A mailbox: devices send it encrypted batches of changes and read each other's. It stores them in order and
|
||||
can't read them, because the key never leaves the devices. Plain PHP + SQLite, no daemon. The protocol is
|
||||
in [server/PROTOCOL.md](../server/PROTOCOL.md).
|
||||
|
||||
```
|
||||
server/public/index.php the API (the only thing the web server serves)
|
||||
server/public/.htaccess Apache rewrite
|
||||
server/src/db.php storage (one SQLite file)
|
||||
server/src/food.php the optional food search
|
||||
server/bin/admin.php accounts + device tokens (command line)
|
||||
server/bin/setup-server.sh one-time setup for Apache + certbot
|
||||
server/config.example.php → config.php
|
||||
```
|
||||
|
||||
**Needs:** PHP 8.1+ with `pdo_sqlite` (Debian: `php-sqlite3`), HTTPS, and its own (sub)domain, which is
|
||||
simplest.
|
||||
|
||||
## Quick setup (Debian/Ubuntu + Apache + certbot)
|
||||
|
||||
```bash
|
||||
sudo apt install apache2 libapache2-mod-php php-sqlite3 certbot python3-certbot-apache rsync
|
||||
sudo rsync -a server/ /srv/dash-sync/ # anywhere, but NOT inside another site's folder
|
||||
sudo bash /srv/dash-sync/bin/setup-server.sh sync.example.com me
|
||||
```
|
||||
|
||||
It creates `data/` (owned by the web server, mode 700), turns on Apache's `mod_rewrite`, an Apache site for `sync.example.com` with
|
||||
`DocumentRoot /srv/dash-sync/public`, and a Let's Encrypt certificate. Then it creates the account `me` and
|
||||
its first device, `dashboard`, and prints that device's **token once**. Paste it into the dashboard's
|
||||
Settings ▸ General ▸ Sync. That's all the server needs: phones and other dashboards get their tokens from the
|
||||
dashboard (Settings ▸ General ▸ Devices ▸ Add a device, as a QR code). Running the script again is safe.
|
||||
|
||||
> Keep the folder out of other sites' document roots. Only `public/` may be reachable from the web.
|
||||
> `data/sync.db` holds the token hashes and the wrapped key.
|
||||
|
||||
## By hand (nginx, another layout)
|
||||
|
||||
1. Copy `server/` anywhere, e.g. `/srv/dash-sync`.
|
||||
2. `cp config.example.php config.php`, then `mkdir data && sudo chown www-data: data && chmod 700 data`.
|
||||
3. Web server, with the document root at `public/`:
|
||||
```nginx
|
||||
server {
|
||||
server_name sync.example.com;
|
||||
root /srv/dash-sync/public;
|
||||
client_max_body_size 9m;
|
||||
location / { try_files $uri /index.php$is_args$args; }
|
||||
location = /index.php {
|
||||
include snippets/fastcgi-php.conf;
|
||||
fastcgi_pass unix:/run/php/php8.2-fpm.sock; # your PHP version
|
||||
}
|
||||
# + the TLS lines certbot adds
|
||||
}
|
||||
```
|
||||
Under a path instead of a subdomain: set `'base_path' => '/dash-sync'` in `config.php`.
|
||||
4. The account and its first device (as the web server's user, so it owns the database):
|
||||
```bash
|
||||
sudo -u www-data php bin/admin.php add-account me
|
||||
sudo -u www-data php bin/admin.php add-device me dashboard # prints its token once
|
||||
```
|
||||
The rest come from the dashboard's Settings ▸ General ▸ Devices.
|
||||
5. Check: `curl -H "Authorization: Bearer <token>" https://sync.example.com/v1/hello`.
|
||||
|
||||
## config.php
|
||||
|
||||
| Key | Default | What |
|
||||
|---|---|---|
|
||||
| `db` | `data/sync.db` | The database |
|
||||
| `base_path` | `''` | URL prefix when not at the root |
|
||||
| `max_batch_bytes` | 8 MB | One batch (also mind PHP's `post_max_size`) |
|
||||
| `max_account_bytes` | 1 GB | All of an account's batches (`0` = no limit) → `507` when full |
|
||||
| `max_answer_bytes` | 32 MB | Batches per download answer; clients just ask again |
|
||||
| `key_replace_any` | `false` | `true`: any device may change the passphrase, not only the one that set the key |
|
||||
| `app_dir` | `app/` | The phone app's published builds ([app.md](app.md)) |
|
||||
| `food_db` | `food/off-archive.db` | The food search archive (below) |
|
||||
| `food_home` | `[]` | Food search: these countries' products rank first, e.g. `['germany', 'austria']` |
|
||||
|
||||
## Day to day
|
||||
|
||||
- Devices: the dashboard that set up the key manages them in Settings ▸ General ▸ Devices (add, revoke). The
|
||||
same on the server: `php bin/admin.php list`, `revoke me phone`. For a stolen, unlocked phone, also change
|
||||
the passphrase (Settings ▸ General ▸ Sync on that dashboard).
|
||||
- `php bin/admin.php stats`: batches and size per account.
|
||||
- **Back up** `data/sync.db`. It's useless without the key, and every device has all the data anyway.
|
||||
- Batches aren't pruned yet. Normal use stays in the tens of MB a year.
|
||||
|
||||
## Optional: the food search archive
|
||||
|
||||
`GET /v1/food/search` searches every Open Food Facts product. Build the archive on any computer from
|
||||
[the OFF export](https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz) (~1 GB, ~10 min)
|
||||
and upload it:
|
||||
|
||||
```bash
|
||||
cd dashboard
|
||||
FOOD_COUNTRIES=germany python3 plugins/food/off.py --archive en.openfoodfacts.org.products.csv.gz /tmp/off-archive.db
|
||||
rsync -t /tmp/off-archive.db you@host:/srv/dash-sync/food/off-archive.db.new
|
||||
ssh you@host 'mv /srv/dash-sync/food/off-archive.db.new /srv/dash-sync/food/off-archive.db'
|
||||
```
|
||||
|
||||
The data is under the ODbL ([NOTICE.md](../NOTICE.md)). Serving it to your own devices is fine. If you open
|
||||
the search to others, credit Open Food Facts.
|
||||
31
docs/testing.md
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
# Testing
|
||||
|
||||
What there is, and what to run before a release. The dashboard has no unit tests yet (see the issues);
|
||||
these are end-to-end checks against clean machines, plus the app's tests.
|
||||
|
||||
| Check | Command | Needs | Takes |
|
||||
|---|---|---|---|
|
||||
| Dashboard from scratch on Debian 12 and 13: `install.sh`, every plugin on, every page answers, the food search works, a foreign `Host` is refused, no tracebacks | `tests/clean-install.sh` | Docker | ~3 min |
|
||||
| Sync server from scratch: `bin/setup-server.sh` with Apache, the printed token works, no token → 401, `data/` not reachable; 88 requests at once (uploads, new devices, reads) all succeed and are all kept | `tests/server-setup.sh` (`--keep` leaves it running on :18080) | Docker | ~1 min |
|
||||
| The phone app: unit and widget tests, static analysis | `cd app && flutter test && flutter analyze` | Flutter 3.44 | ~1 min |
|
||||
| Python, PHP and JS at least parse | `python3 -m compileall -q dashboard && php -l server/public/index.php && for f in dashboard/static/*.js dashboard/plugins/*/static/*.js; do node --check "$f"; done` | PHP, Node | seconds |
|
||||
| The README's screenshots, from a demo dashboard full of made-up data: a quick look at every page | `python3 docs/screenshots/make.py` (`--keep` leaves the demo running on :8199) | Playwright | ~2 min |
|
||||
| The app's screenshots, which also exercise the whole chain: demo dashboard → server → a fresh app connecting, syncing and showing every section | `tests/server-setup.sh --keep`, `make.py --keep`, then `python3 docs/screenshots/app.py --token <the server's token>` | an Android emulator (a Pixel-sized AVD), Flutter | ~5 min |
|
||||
|
||||
## By hand, before a release
|
||||
|
||||
- **Sync end to end:** `tests/server-setup.sh --keep`, then a dashboard (e.g. `make.py --keep`, or one
|
||||
started from `dashboard/`) ▸ Settings ▸ General ▸ Sync: server `http://127.0.0.1:18080`, the printed
|
||||
token, a passphrase. Note the recovery key, then Devices ▸ Add a device ▸ a phone. A second dashboard
|
||||
joins with another device token and the passphrase; a change on one shows on the other after "Sync now".
|
||||
- **The 3.5" screen:** on a Pi with the panel, the service log's `screen:` line names it
|
||||
(`journalctl -u dashboard | grep screen`). Without one, Settings ▸ General ▸ Screen shows what it would
|
||||
draw (`/api/screen.png?n=Home`).
|
||||
- **The app:** a release APK on a phone. Connect by QR, sync, weather with and without places.
|
||||
|
||||
## Not covered
|
||||
|
||||
- The dashboard's Python logic in isolation (the sync merge, auth, settings validation): no unit tests.
|
||||
- ARM: the checks run on x86-64 Debian. The Pi's Raspberry Pi OS is the same Debian with the same
|
||||
packages, but it isn't run here.
|
||||
- iOS: the app is Android only.
|
||||