bkelldog a89565b478
web / test (push) Failing after 1s
web / image (push) Skipped
Add deploy workflow.
2026-11-06 11:57:51 -05:00
2026-11-06 11:57:51 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00
2026-11-06 11:42:34 -05:00

Mamadachi web: device API, dashboard and database

One small Python service does three jobs:

 Mamadachi (ESP32-C6)                       Parent's phone / laptop
        │  POST /api/v1/device/sync                 │  https://…/   (dashboard)
        │  (presses + battery, once per wake)       │  /api/v1/…    (JSON API, CSV export)
        ▼                                           ▼
 ┌──────────────────────────── FastAPI app (app/) ───────────────────────────┐
 │ device_api.py ─ ingest.py ─┐                 pages.py / admin.py ─ HTML   │
 │                            ├─ events.py, stats.py (the shared logic)      │
 │ api.py (JSON) ─────────────┘                                              │
 └──────────────────────────────────┬────────────────────────────────────────┘
                                    ▼
                    Postgres in production (Neon / Supabase)
                    SQLite file on your computer (web/mamadachi.db)
  • Dashboard (mobile-first, dark mode for night feeds, can be added to the home screen):
    • Today: time since the last feed, which side next, asleep/awake, today's counts against the 7-day average, one-tap logging, and today's timeline.
    • Log: every event by day. Add, edit, delete and undo.
    • Trends: a daily-rhythm chart and per-day feeds, sleep and diapers.
    • Device: battery curve, signal, clock, the sync log and tokens.
    • Settings: baby profile, timezone, what each of the 8 buttons means, event types, and export.
  • Device API: one request per wake. It uploads the queued presses and telemetry, and gets back the button labels, the time and what to draw on the e-paper.
  • Database: 7 tables, versioned with Alembic migrations. They work the same on SQLite and Postgres.

Run it on your computer

From this web/ folder, in PowerShell:

python -m venv .venv
.venv\Scripts\pip install -r requirements-dev.txt
.venv\Scripts\python -m app.cli seed-demo --days 21     # optional: 3 weeks of fake newborn data
.venv\Scripts\python -m uvicorn app.main:app --reload

On Linux or macOS, use python3 -m venv .venv, then the same commands with .venv/bin/ in place of .venv\Scripts\.

Open http://127.0.0.1:8000. No password is set locally. The interactive API reference is at http://127.0.0.1:8000/docs.

  • python -m app.cli reset --yes deletes the demo data and keeps your settings.
  • python -m app.cli create-device "Proto 1" prints a device token. The Device page can do the same.
  • .venv\Scripts\python -m pytest runs the test suite (49 tests, a few seconds) on SQLite. Run it before every deploy.
  • To run the same tests on real Postgres, the database production uses, start a throwaway one with Docker. Never point TEST_DATABASE_URL at real data: every test empties the tables.
    docker run -d --rm --name pg-test -e POSTGRES_PASSWORD=test -p 55432:5432 postgres:17-alpine
    $env:TEST_DATABASE_URL = "postgresql://postgres:test@127.0.0.1:55432/postgres"; .venv\Scripts\python -m pytest
    

Try the device API without hardware

tools/fake_device.py behaves like the firmware should. It queues presses in a local file and only deletes them after an HTTP 200:

.venv\Scripts\python tools\fake_device.py press 6              # sleep starts
.venv\Scripts\python tools\fake_device.py press 4 --ago 10     # wet diaper 10 min ago
.venv\Scripts\python tools\fake_device.py --token mmd_xxx sync
.venv\Scripts\python tools\fake_device.py --token mmd_xxx sync --clock-off 3600   # RTC an hour slow

Use --url https://your-app.onrender.com to point it at the deployed server.

The device protocol (what the firmware needs to do)

POST /api/v1/device/sync
Authorization: Bearer mmd_…            (the device token, in secrets.h)
Content-Type: application/json         (required)

{"device_time": 1760630400,            RTC now, UNIX seconds UTC
 "firmware": "0.1.0", "battery_mv": 3987, "charging": false, "rssi": -61,
 "boot_count": 42, "queue_len": 0,
 "events": [{"seq": 101, "time": 1760620000, "button": 6}, …]}    ≤ 500 per request

The one rule: HTTP 200 means every event you sent is stored, so delete them all. Any other result means keep them and retry later. Retries are safe, because the server recognises a press it already has (same seq and time) and skips it. A 401 means the token is wrong or revoked. A 422 is a firmware bug, and the server logs what was wrong with the request.

What the firmware has to keep:

  • seq: a per-press counter in NVS. If it resets, nothing breaks: the press time is part of the identity.
  • time: read from the RV-3028's UNIX-time register when the button is pressed.
  • Wrong clock? The server compares device_time with its own clock. If they differ by more than 2 minutes, it shifts the event times and marks them as corrected. The response's server_time lets you set the RTC.

What comes back (abridged):

{"ok": true, "server_time": 1760630402, "ack_seq": 102, "stored": 2, "duplicates": 0,
 "clock_skew_s": 2, "clock_corrected": false, "tz_offset_s": -14400, "sync_interval_s": 3600,
 "config_version": "a1b2c3d4",
 "buttons": [{"button": 1, "kind": "nurse_left", "short": "Nurse L", "mode": "instant"}, …],
 "status": {"baby_name": "Mia", "last_feed": {"kind": "nurse_left", "short": "Nurse L", "time": 1760620000},
            "next_side": "R", "last_diaper": {…}, "open": [{"kind": "sleep", "short": "Sleep", "since": 1760627000}],
            "today": {"feeds": 6, "wet": 5, "dirty": 2, "sleep_min": 540}}}

Every time in the response is a UNIX timestamp. The device works out "Fed 2h 10m ago" from its own RTC, so the e-paper stays correct while the device sleeps. tz_offset_s is the offset for displaying local time. Re-draw the button labels only when config_version changes.

How presses become events. Each button maps to an event type in Settings. A "single press" type (a diaper) logs one event per press. A "start / stop" type (sleep) starts on the first press and ends on the next. If the start is older than the type's auto-close limit (12 h for sleep), the next press starts a new session instead. A forgotten stop is flagged on the dashboard. Unassigned buttons are logged as "Other" rather than dropped.

Firmware tips for battery and reliability

  • Use HTTPS with ESP-IDF's certificate bundle (esp_crt_bundle_attach). All the hosts below serve publicly trusted certificates. Set a 10–15 s HTTP timeout.
  • Make one request per wake, then sleep. Don't sync on every press: with deep sleep, an hourly sync costs far less than a Wi-Fi join per press. A quick sync after a press, if the device was already awake, is fine.
  • After a failure, back off (1 min, 5 min, 30 min…). Never drop the queue. Keep it in flash, not RTC RAM, so a brown-out doesn't lose presses.
  • Follow sync_interval_s. You can then change the interval in Settings without reflashing.

Where to host it

You need two things: somewhere to run the app and a Postgres database. Keep them in the same region. My recommendation for this stage:

Service Cost Why
App Render, web service, 0.5c-512mb instance ~$7/mo Push to GitHub and it deploys. HTTPS, logs and environment variables are in a web UI. It never sleeps.
Database Neon, Free plan $0 Real Postgres that never gets paused. It scales to zero when idle and wakes in under a second. It has 0.5 GB storage (years of presses) and 6 h point-in-time restore.

Avoid Render's Free web plan for this. It sleeps after 15 minutes without traffic and takes about a minute to wake. The device would wait that minute with its radio on, which drains the battery, or time out and retry. The paid instance removes that problem. Render's free Postgres is also deleted after 30 days.

Supabase works as the database too: change the connection string and nothing else. Its table editor is nicer than Neon's, and Supabase Auth is a good option once you add real accounts. The catch is that free Supabase projects pause after 7 days without activity. If the device is offline for a week (say, a trip), the next sync fails until someone clicks "restore" in the Supabase dashboard. Use the Session pooler connection string (port 5432), because Supabase's direct connection is IPv6-only and many hosts can't reach it. Pro is $25/mo and removes the pause.

Fly.io is the cheaper alternative for the app, at about $2/mo for an always-on 256 MB machine. It's driven from the command line, it can deploy straight from this folder without GitHub, and fly.toml is ready. Fly has had no free allowance for new accounts since late 2024.

Deploy: Neon + Render, step by step

  1. Put the project on GitHub. The Mamadachi folder isn't a git repository yet. Run git init at the top level, commit, and push to a private GitHub repo. web/.gitignore already keeps out .venv, .env and the local database.
  2. Create the database. Sign up at neon.com and create a project in AWS US East 2 (Ohio). Copy the connection string. It looks like postgresql://user:pass@ep-xxx.us-east-2.aws.neon.tech/neondb?sslmode=require.
  3. Create the app. In Render, choose New → Blueprint, pick the repo and set the blueprint path to web/render.yaml. When asked, paste DATABASE_URL (from step 2) and pick a DASHBOARD_PASSWORD. Render generates SECRET_KEY itself.
  4. Wait for the first deploy. The app creates its tables on start. Open https://mamadachi-xxxx.onrender.com and log in.
  5. Settings: set the baby's name, birth date and timezone. On the Device page, create a token and put it and the URL in the firmware's secrets.h.
  6. Check it from your computer: python tools\fake_device.py --url https://… --token mmd_… status.

From then on, git push deploys. Render runs the new version, waits for /healthz to answer, then switches traffic, so a broken build never replaces a working one.

Safety checks built in: in production the app refuses to start if DATABASE_URL is missing. Otherwise it would quietly write to a SQLite file that the host deletes on every deploy. It also refuses to start if a password is set without a SECRET_KEY, and it shows a red banner if there's no dashboard password.

CI and the image registry (Gitea)

.gitea/workflows/web.yml, at the top of the repo, runs the tests on SQLite and on Postgres for every push and pull request that touches web/. If they pass, it builds the Docker image and pushes it to your Gitea's container registry:

You push Image tags
a commit to main gitea.yourdomain.com/<owner>/mamadachi-web:sha-1a2b3c4
a tag v0.2.0 the same sha-… tag, plus :0.2.0
a pull request none (tests only)

There's deliberately no :latest. Your deployment names an exact tag, so you always know what's running and can roll back.

One-time setup:

  1. Turn on Actions. Set [actions] ENABLED = true in Gitea's app.ini (it's on by default from 1.21), then tick Actions in the repo's Settings.
  2. Run a runner. Start an act_runner container, for example on the NAS, and register it with a token from Site Administration → Actions → Runners. Keep its default ubuntu-latest label. Leave container.docker_host empty in its config, so jobs can use the host's Docker to build the image. That gives the runner root-level access to the host, which is fine for your own repos only.
  3. Make a token. Under User settings → Applications, create an access token with package: read and write. Add it to the repo under Settings → Actions → Secrets as REGISTRY_TOKEN.
  4. Check Gitea's ROOT_URL. It must be the public HTTPS name, for example https://gitea.yourdomain.com/, because the workflow takes the registry host from it. Otherwise, set a repo variable REGISTRY to the right host. If the token belongs to someone other than whoever pushes, set a variable REGISTRY_USER to the token's owner.
  5. Raise the proxy's upload limit. On the proxy in front of Gitea (NPMPlus), add client_max_body_size 0; under the proxy host's Advanced tab. Otherwise pushing an image layer fails with 413.

Releasing: git tag v0.2.0 && git push --tags. Wait for the workflow, change the image tag in the server's compose file, snapshot the data, then redeploy. To roll back, set the previous tag. If the release included a database migration, also restore the snapshot.

Pulling on the server: run docker login gitea.yourdomain.com once, with a token that can read packages. Private packages need it.

Running it

  • Changing the database schema: edit app/models.py, then run .venv\Scripts\alembic revision --autogenerate -m "what changed". Read the generated file in migrations/versions/ and commit it. The app applies new migrations on its next start. A test fails if you forget the migration.
  • Backups: Neon keeps 6 hours of history on the free plan. For more, download Settings → Full backup (JSON) now and then. The more automatic option is a weekly pg_dump from a scheduled GitHub Action. Settings → spreadsheet (CSV) is the export to hand to a pediatrician or to open in Google Sheets.
  • Logs: Render → service → Logs. Every sync logs one line, for example sync device=1 received=3 stored=3 dup=0 skew=2s battery=3987mV rssi=-61. A bad request from the firmware logs a 422 line with the reason.
  • Health: /healthz shows the process is up. /readyz also checks the database. Point a free uptime monitor (UptimeRobot or Better Stack) at /readyz to get an email when it's down.

What's deliberately simple, and the road to robust

Built in now: per-device secret tokens (only hashes are stored), a dashboard password with a signed 90-day cookie, HTTPS-only cookies in production, cross-site form protection, idempotent syncs, soft-delete with undo, clock-skew correction, input validation with size limits, health checks, pinned dependencies and tests.

Before anyone outside your family uses it, roughly in this order:

  1. Version control and CI. Use git now. Then add a GitHub Action that runs pytest on every push, so Render only deploys code that passes.
  2. Monitoring. An uptime check on /readyz, plus error tracking (Sentry's free tier is 5 lines in main.py) so you hear about crashes before a parent does.
  3. Backups you've restored at least once. A backup you've never restored is a hope, not a backup.
  4. Real accounts and families. Add a families table with a family_id on profile, devices, kinds, buttons and events, and filter every query by it. Then add login with email links or passwords: Supabase Auth, Clerk, or FastAPI-Users. That replaces the single DASHBOARD_PASSWORD. Add password reset and inviting a partner.
  5. Device claiming. Typing tokens into secrets.h doesn't scale. At manufacture, give each unit a unique ID and secret. The e-paper shows a short pairing code, the parent types it into the website, and the server links the device to their family. For the home Wi-Fi password, use ESP-IDF's Wi-Fi provisioning over BLE.
  6. Abuse protection. Rate-limit /login and /api/v1/device/sync (for example with slowapi), add CSRF tokens on forms, and lock the CORS policy.
  7. Privacy and law. This is data about a child's health and routine. Write a privacy policy, let families export and delete everything (export already exists), keep EU users' data in an EU region if you sell there (GDPR), and check the rules for selling a radio device (the external-antenna FCC/CE note in the hardware README).
  8. Over-the-air firmware updates. Add firmware_url and firmware_version to the sync response. The device already reports its version, so the server can tell it when to update (ESP-IDF esp_https_ota).
  9. Integrations. The project README mentions Google Sheets. The CSV export and /api/v1/events are the starting point. A nightly job could push new rows to a sheet the parent connects with Google OAuth.

Layout

web/
├── app/
│   ├── main.py            app setup, middleware, health checks, startup migrations
│   ├── config.py          settings from environment variables
│   ├── db.py, models.py   database connection and tables
│   ├── schemas.py         JSON shapes for the APIs (validated, documented at /docs)
│   ├── services/
│   │   ├── ingest.py      device sync: dedupe, clock correction, tokens, response
│   │   ├── events.py      press → event rules (start/stop pairing), edits, queries
│   │   ├── stats.py       feeds, sleep totals, daily stats, rhythm chart, alerts
│   │   └── catalog.py     default event types, button layout, battery curve
│   ├── routes/            device_api, api (JSON), pages + admin (HTML), auth
│   ├── charts.py          chart geometry (no JS chart library)
│   ├── templates/, static/ HTML, CSS and a little JS
│   ├── demo.py, cli.py    demo data and command-line helpers
├── migrations/            Alembic schema history
├── tests/                 pytest: sync rules, stats, pages, auth, migrations
├── tools/fake_device.py   device simulator
├── Dockerfile, render.yaml, fly.toml, .env.example
S
Description
Web Backend
Readme
118 KiB
0 Stars 1 Watchers 0 Forks
Languages
Python 68.5%
HTML 16.6%
CSS 11.1%
JavaScript 3%
Dockerfile 0.5%
Other 0.3%