# Convivo Badge Printer — Pi Operating Manual Operating instructions for an AI agent (or human) who must **change, deploy or troubleshoot** the Convivo Raspberry Pi badge printer. Everything here was verified against the code and on real hardware (2026-10-18). Parts marked *in progress* are being built by a concurrent agent — **verify against the code before relying on them.** Backend architecture contract: [docs/backend/printing.md](../../docs/backend/printing.md) (link only, don't duplicate). Repo-wide rules: [root AGENT.MD](../../AGENT.MD). ## 1. Purpose & architecture Staff check in an attendee → the DB transaction enqueues a self-contained badge document (`convivo.badge-print/v1`) on a pgmq queue → a headless Raspberry Pi station claims it, renders the badge with the admin's own React renderer inside headless Chromium, composes it onto the loaded roll and prints on a Brother QL-1110NWB over raw USB. Admins watch a status pill + Printing view in the admin console. ```mermaid flowchart LR SCAN[Welcome check-in / admin Print] -->|pgmq.send| Q[(badge_print queue)] Q -->|printer_claim_badge_job RPC| W[worker: apps/printer/worker] W -->|renderBadge in Chromium| R[dist-print renderer] W -->|brother_ql_next pyusb| P[Brother QL-1110NWB] W -->|printer_heartbeat| S[(print_stations)] S -->|get_print_overview 5s poll| A[Admin pill + Printing view] C[comitup + portal] -->|/run/convivo/network.json| W ``` Delivery is **at-least-once**: if `complete` keeps failing (>60 s) the job may be redelivered and print a duplicate. That is by design — don't "fix" it silently. ## 2. Repo map | Path | Role | |---|---| | `apps/printer/worker/` | Python worker: `main.py` loop, `rpc.py` PostgREST client, `printer.py` brother_ql USB, `render.py` Chromium, `label.py` Pillow compose, `network.py` comitup state, `status_labels.py`, `config.py` env | | `apps/printer/tests/` | pytest unit tests (fakes — no hardware, no DB) | | `apps/printer/Dockerfile` | arm64 image; **build context = repo root**; node renderer stage on `BUILDPLATFORM`, runtime = `mcr.microsoft.com/playwright/python:v1.55.0-noble` | | `apps/printer/Dockerfile.dockerignore` | per-Dockerfile ignore (supabase/, e2e/, docs/, pi/, tests excluded from context) | | `apps/printer/pi/install.sh` | dev-machine side: buildx build → tar.gz → scp → run setup.sh over SSH | | `apps/printer/pi/setup.sh` | Pi provisioning, idempotent, runs as root on the Pi | | `apps/printer/pi/setup.local.sh` | filled copy with URL + station token — **git-ignored, secret-bearing, never open/print/commit** | | `apps/printer/pi/convivo-printer-image.tar.gz` | exported image (~950 MB gz) — git-ignored | | `apps/printer/portal/portal.py` | captive-portal config page — *in progress by another agent*, see §8 | | `supabase/migrations/20261018170000_badge_print_queue.sql` | queues, `print_stations`, all RPCs (idempotent/re-runnable) | | `supabase/tests/badge_print_tests.sql` | rollback-only regression suite (~101 asserts); run command in its header | | `apps/admin/print.html`, `src/print/main.tsx` | standalone renderer page; exposes `window.renderBadge(payload, opts)` | | `apps/admin/vite.print.config.ts` | builds `print.html` → `apps/admin/dist-print/` (`npm run build:print`) | | `apps/admin/src/components/BadgeRender.tsx` | shared badge layout renderer (editor preview + print page) | | `apps/admin/src/views/Printing.tsx` | stations, queue counts, dead letters (Requeue/Discard), recent (Reprint), Add/Rename/Revoke station | | `apps/admin/src/lib/printStatus.tsx` | 5 s poller of `get_print_overview()` + `printerHint()` operator text | | `e2e/tests/printing.spec.ts` | Playwright: pill states, token-once, rename, requeue/discard, reprint (RPCs mocked) | ## 3. Hardware facts (verified on the real Pi) | Item | Value | |---|---| | Board | Raspberry Pi 4 (2 GB), Raspberry Pi OS / Debian 13 trixie, aarch64 | | Printer | Brother QL-1110NWB(c), USB id `04f9:20a8`, identifier `usb://0x04f9:0x20a8`, pyusb backend | | Model string | `QL-1110NWB` (brother_ql_next 0.12.0); device self-reports `QL-1100NWB` — normal | | Die-cut roll | `103x164` (1200×1822 px @300 dpi). **Die-cut labels cannot be cut shorter** than the pitch | | Continuous roll | DK-22246 → id `103` (1200 px wide), cut to layout length | | `BROTHER_LABEL` | `auto` (default): print on whatever roll is detected | | Print speed | ≈ 8 s/label. `/tmp` on the Pi is a ≈923 MB tmpfs — never stage the image there | ## 4. Golden rules 1. **Never write or print secrets.** No passwords in files, commands, logs, or memory — refer to "the Pi sudo password, ask the operator". No station tokens, no server credentials, ever. The Supabase anon key is public (not a secret) but don't paste it anywhere new: it comes from `apps/printer/pi/setup.sh` (default `CONVIVO_ANON_KEY`, same value baked into the web apps). 2. **sudo on the Pi needs a password.** Pipe it on stdin only: `printf '%s\n' "$PI_SUDO_PASSWORD" | ssh convivo-pi "sudo -S -p '' …"`, with `PI_SUDO_PASSWORD` read from a private 0600 file outside the repo (or exported by the operator). Never on a command line (`sudo … `), never in the repo. 3. **SSH access**: alias `convivo-pi` in `~/.ssh/config` (key `~/.ssh/convivo_pi`, `StrictHostKeyChecking yes`). The Pi's LAN IP changes at venues — always use the alias. 4. **Idempotency**: `setup.sh` must stay safe to re-run on a working station. It restarts services **only when their config changed** (§6). Violating this caused two real incidents (bounced worker printed a label mid-deploy; hotspot without DHCP). 5. **Risky network change over Wi-Fi SSH? Arm a rollback first** (§7). 6. **Never log tokens or `qr_token` payload values.** `Config` keeps `station_token` out of `repr` — keep it that way. 7. **Ask before destructive or production actions** (revoke station, DB writes on prod, rebooting a station mid-event). Prod deploys follow [docs/deployment.md](../../docs/deployment.md): backup, drift guard, build-before-up, never touch prod data/secrets. 8. **Sub-agents must not run local docker builds** — docker veth churn can kill the session (ERR_NETWORK_CHANGED). The supervisor runs builds, in async terminals. Also: `pkill -f` patterns can match your own shell — avoid them. ## 5. Changing the code ### Worker (`apps/printer/worker/`) - Loop: `tick()` → printer ready? → `claim(wait_seconds)` → `handle_job()` → render → compose → `print_image` → `complete`/`fail`. Errors never escape the loop. - A post-print error (roll ran out mid-job) must **not** dead-letter a badge that did print (`did_print` wins). Retryable failures re-claim up to 3 reads, then dead-letter. - Env knobs live in `config.py` (`CONVIVO_URL`, `CONVIVO_ANON_KEY`, `PRINTER_STATION_TOKEN`, `STATION_NAME`, `BROTHER_*`, `WAIT_SECONDS`, `HEARTBEAT_SECONDS`, `VT_SECONDS`, `STATUS_LABELS`, `DRY_RUN`, `THRESHOLD`, `DITHER`). - `DRY_RUN=1` writes PNGs to `/tmp/dryrun` instead of printing — use it for bench tests. Tests (pure fakes, no hardware/DB): ```bash cd apps/printer && python -m venv /tmp/convivo-printer-venv /tmp/convivo-printer-venv/bin/pip install -r requirements-dev.txt brother_ql_next==0.12.0 pillow httpx /tmp/convivo-printer-venv/bin/python -m pytest -q ``` ### Renderer (`apps/admin`) The badge look is `BadgeRender.tsx` shared with the editor; the print page is `src/print/main.tsx` (`window.renderBadge`). Change layout code there, then: ```bash npm run build:print --prefix apps/admin # produces dist-print/ (what the Pi image embeds) npm run build --prefix apps/admin # the admin app itself must still build CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- printing.spec.ts ``` (the e2e spec needs the admin dev server on 127.0.0.1:3001; RPCs are mocked in the spec). The Dockerfile renderer stage rebuilds `dist-print` inside the image — a stale local `dist-print/` never leaks in (it's docker-ignored). ### Database (`supabase/`) Edit the migration `20261018170000_badge_print_queue.sql` (it is idempotent/re-runnable) and extend `supabase/tests/badge_print_tests.sql`. RPC surface: `welcome_checkin` (enqueues on first check-in; no layout → no job), `enqueue_badge_print` (admin reprint), `create_print_station` / `rename_print_station` / `revoke_print_station`, `get_print_overview`, `requeue_dead_badge_print`, `discard_dead_badge_print`, and the four token-gated `printer_*` RPCs (claim/complete/fail/heartbeat). Run the rollback suite (works before AND after apply; nothing persists): ```bash (echo 'begin;'; \ cat supabase/migrations/20261018170000_badge_print_queue.sql; \ sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \ | docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -v ON_ERROR_STOP=1 ``` Hard constraint: the anon role has `statement_timeout = 3 s` — every anon RPC must finish under that. The claim long-poll is clamped server-side to `p_wait_seconds ≤ 2` (worker default `WAIT_SECONDS=2`). A 10 s poll → HTTP 500 `57014`. ### Image `apps/printer/Dockerfile`: build context is the **repo root**; the node renderer stage runs on `--platform=$BUILDPLATFORM` (native, fast) while the runtime stage is arm64. Runtime deps are pinned in `requirements.txt` (brother_ql_next, pillow, httpx, playwright). Container runs as root on purpose (raw USB, Chromium `--no-sandbox`). Healthcheck = `/tmp/heartbeat-ok` touched every heartbeat, 120 s start-period. ## 6. Deploy to a Pi ### First install on a fresh Pi 1. Flash Raspberry Pi OS (64-bit, trixie) with **Raspberry Pi Imager → OS customisation: enable SSH (key auth), set hostname `convivo-printer`**. Connect **Ethernet** if at all possible for the first deploy (Wi-Fi over-SSH deploys need the rollback dance, §7). 2. Add the ssh alias (`convivo-pi`) with key `~/.ssh/convivo_pi`, `StrictHostKeyChecking yes`; copy your key to the Pi; have the operator supply the sudo password when needed. 3. Create the station in **Admin → Printing → Add station** — the token (`cvp_…`) is shown **once** (only its SHA-256 is stored). Lost it → revoke + re-add. 4. Create `apps/printer/pi/setup.local.sh` (git-ignored, mode 0600): `cp apps/printer/pi/setup.sh apps/printer/pi/setup.local.sh` then set the defaults — either edit the `: "${VAR:=…}"` lines or `sed` them: `CONVIVO_URL`, `PRINTER_STATION_TOKEN`, `STATION_NAME`. Never commit or print this file. 5. Run the installer (supervisor's terminal, expect: build a few minutes, upload minutes, `docker load` on the SD card several minutes): ```bash PI_SUDO_PASSWORD="$(cat )" bash apps/printer/pi/install.sh # default target convivo-pi PI_SUDO_PASSWORD=… bash apps/printer/pi/install.sh user@other-pi # any other Pi ``` `install.sh` flags: `SKIP_BUILD=1` (reuse the existing tar), `SKIP_IMAGE=1` (env-only change — don't even upload the tar; *being added, verify against the code*), `STAGE_APP=0` / `STAGE_WIFI_PORTAL=0` (skip stages), `REBOOT=1` (reboot if kernel update pending). It builds arm64 with buildx (installs QEMU binfmt if missing), gzips to `apps/printer/pi/convivo-printer-image.tar.gz`, scp's setup (prefers `setup.local.sh`) + image to **`/var/tmp/convivo-setup`** (NOT `/tmp` — 923 MB tmpfs), then runs setup.sh as root via `sudo -S`. ### `setup.sh` stages and idempotency rules (do not break these) - **base_system / reliability**: hostname, timezone, apt, hardware watchdog, journald cap, Wi-Fi powersave off, auto-upgrade timers disabled. `daemon-reexec` **only when the watchdog conf changed**, and then comitup is restarted too — a re-exec without that restart leaves comitup with a stale D-Bus proxy → hotspot up but **no DHCP/portal**. - **docker**: installed from docker.com repo; restart **only when `daemon.json` changed** — a restart bounces the worker on its old image (it would re-claim and print). - **usb**: blacklist `usblp`; **mask `ipp-usb`** (it grabs the printer's interfaces → "Resource busy"). - **app**: writes `/opt/convivo-printer/.env` (0600) + `docker-compose.yml`, `docker load`, tags whatever load reports as `convivo-printer:latest`, `compose up -d`, image prune. Compose: host network, `/dev/bus/usb` + `device_cgroup_rules: c 189:* rmw` (replugged printer works without restart), `/run/convivo:ro`, tmpfs `/tmp`, `restart: always`. *In progress:* setup.sh will always rewrite `.env` while **preserving portal-set values** — verify against the code. - **comitup**: restart **only when `/etc/comitup.conf` changed** (a restart renegotiates Wi-Fi and can drop your SSH mid-script). ### Updates Code change → re-run `install.sh` (rebuild + upload + setup). Env-only change → edit `setup.local.sh` (or `.env` on the Pi + `docker compose up -d`), with `SKIP_BUILD=1 SKIP_IMAGE=1` if supported. Then verify (§10 checklist). ## 7. Risky network changes over Wi-Fi SSH Arm a rollback **before** the change, run the work detached, cancel the timer after: ```bash # 1. snapshot the current profile, then arm a timer (e.g. 8 min): ssh convivo-pi "sudo -S systemd-run --on-active=8min --unit=convivo-net-rollback \ sh -c 'cp /tmp/net-backup.yaml /etc/netplan/ && netplan generate && nmcli connection reload && systemctl restart comitup'" # 2. long steps detached so an SSH drop can't kill them: ssh convivo-pi "sudo -S systemd-run --unit=convivo-setup --collect bash /var/tmp/convivo-setup/setup.sh" # 3. verify connectivity (comitup-cli i shows CONNECTED), then: ssh convivo-pi "sudo -S systemctl stop convivo-net-rollback" ``` If SSH drops, the timer restores the old config automatically. ## 8. Wi-Fi provisioning & captive portal - comitup 1.43 (Debian trixie package). With no known network the Pi broadcasts the **open** AP `Convivo-Printer-` (`` persistent per device; this Pi: `Convivo-Printer-6372`). Connect a phone, open **http://10.41.0.1**, pick a network. Comitup remembers any number of networks and reuses existing NM/netplan profiles. **Open AP = anyone nearby can reconfigure the station — accepted risk.** - `external_callback = /usr/local/lib/convivo/netstate.sh` writes `/run/convivo/network.json` (`HOTSPOT|CONNECTING|CONNECTED` + ssid/ip) → mounted read-only into the worker → heartbeats → the admin pill knows the network state. - **Config portal (in progress, another agent):** `apps/printer/portal/portal.py` will replace the comitup web UI by overriding `comitup-web.service` `ExecStart` through a systemd drop-in. Staff will be able to pick **any** Wi-Fi and optionally set `CONVIVO_URL` / `CONVIVO_ANON_KEY` / `PRINTER_STATION_TOKEN` — the portal rewrites `/opt/convivo-printer/.env` and recreates the container. Companion changes: `install.sh SKIP_IMAGE=1`, and `setup.sh` always rewriting `.env` while preserving portal-set values. **Verify all of this against the code before documenting or relying on it.** `STAGE_WIFI_PORTAL=0` skips the comitup/portal stage (wired bench). ## 9. Configuring: local test vs production | | Local test | Production | |---|---|---| | `CONVIVO_URL` | `http://:54321` (Kong; reachable from the Pi on the same LAN — verified: `192.168.178.x`) | `https://admin.appe.at` (same-origin PostgREST proxy) | | Station token | create via SQL on the local DB (below) | Admin → Printing → Add station (shown once) | | Migrations/admin | local `supabase_db_Convivo` | per docs/deployment.md (backup, drift guard, build-before-up) | Local station via SQL (token to a 0600 file, **never print it**): ```bash docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -tA -c \ "select set_config('request.jwt.claims','{\"email\":\"\",\"role\":\"authenticated\"}', false); select token from public.create_print_station('Welcome desk (local test)');" > /tmp/.local-station-token chmod 600 /tmp/.local-station-token ``` Queue a test badge: `select public.enqueue_badge_print('');` (admin only) or the admin Print button on Registrations (works while the printer is offline — the job waits). The event needs a badge layout whose page fits the loaded roll (die-cut 103×164 or continuous 103 mm wide). ## 10. Operating at an event - **Roll change**: swap physically; `BROTHER_LABEL=auto` picks up the new media on the next status poll. Worker pauses (no claims) while the printer reports errors — queue waits. Want short badges (e.g. 101×30)? You need the **continuous DK-22246** roll; a die-cut roll always prints the full 164 mm label. - **Wi-Fi change**: phone → open AP `Convivo-Printer-` → http://10.41.0.1 → pick the venue network (or the new portal page once it lands, §8). Watch the pill come back. - **Admin pill states** (worst-state wins across active stations, polls every 5 s): - `ready` — heartbeat <45 s old, printer ready, no errors. - `printing` — worker currently on a job. - `error` — printer disconnected / errors (no media, cover open, cutter jam, wrong roll) — hover text comes from `printerHint()`, written for operators. - `offline` — no heartbeat for >45 s (Pi off, Wi-Fi lost, wrong `CONVIVO_URL`). - `revoked` stations are excluded from the pill. - Queue counts, dead letters (Requeue/Discard) and Recent jobs (Reprint) live in **Admin → Printing**. Rename a station there (inline); the worker adopts the new name from the heartbeat response. - Status labels ("ready" / "need Wi-Fi" printed on the printer) are **off by default** (`STATUS_LABELS=1` enables; costs media). The pill is the default channel. ## 11. Troubleshooting | Symptom | Cause | Fix | |---|---|---| | USB open "Resource busy" | `ipp-usb` (or `usblp`) claimed the printer | `sudo systemctl mask --now ipp-usb`; replug USB; setup.sh enforces both | | Claims HTTP 500 `57014` | anon `statement_timeout` 3 s exceeded | keep `p_wait_seconds ≤ 2`; nobody raised `WAIT_SECONDS` | | Hotspot up, clients get no IP | comitup stale D-Bus proxy after `daemon-reexec` | `sudo systemctl restart comitup` | | DLQ "layout … does not fit label" | badge bigger than loaded roll (both rotations) | load 103 mm roll / shrink layout / Requeue after fix | | Short badge wastes a full die-cut label | die-cut can't cut shorter | load continuous DK-22246 (`103`) | | Pill **offline** | Pi powered off / Wi-Fi lost / wrong `CONVIVO_URL` | power, `comitup-cli i`, `cat /run/convivo/network.json`, re-provision Wi-Fi | | RPC 401 / SQLSTATE `28000`, log "station token rejected" | token revoked/wrong | Add station again (new token, once), update `.env` via portal or redeploy | | Pill error "wrong roll" | `BROTHER_LABEL` pinned, different roll loaded | swap roll or set `BROTHER_LABEL=auto` | | Duplicate badge after worker restart | `complete` failed >60 s earlier | expected at-least-once; fix network to DB | | Container unhealthy | `/tmp/heartbeat-ok` stale >1 min | `docker logs --since 10m convivo-printer`; usually DB unreachable | | Printer not detected (USB gone) | cable/power/replug | check printer power; `lsusb -d 04f9:`; cgroup rule means no container restart needed | | Pi unreachable by IP | venue changed the network | use `convivo-pi` alias / mDNS; re-provision via portal/AP | Log & state commands (read-only, safe during an event): ```bash ssh convivo-pi "sudo -n docker logs --since 10m convivo-printer" ssh convivo-pi "sudo -n docker ps --filter name=convivo-printer" # Status: healthy ssh convivo-pi "comitup-cli i" ssh convivo-pi "cat /run/convivo/network.json" docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres -c \ "select name, last_seen_at, last_status->'printer'->>'ready' as ready from public.print_stations" ``` ## 12. Checklists **Pre-deploy** - [ ] `cd apps/printer && python -m pytest -q` green. - [ ] SQL rollback suite green (command in §5) if DB touched. - [ ] `npm run build --prefix apps/admin && npm run build:print --prefix apps/admin` green if renderer/admin touched. - [ ] `printing.spec.ts` green if admin UI touched. - [ ] `git status` shows no secret files staged (`setup.local.sh`, `*.tar.gz` are git-ignored — keep it that way). - [ ] Station exists (Admin → Printing) and its token is in `setup.local.sh` / portal, not in any log. **Post-deploy verification** - [ ] `docker ps` → `convivo-printer` **healthy** (allow 120 s start-period). - [ ] Logs show heartbeats / `worker idle`, no token errors. - [ ] Admin pill shows the station **ready** with the right name and roll. - [ ] Physical: check in an unchecked attendee → badge prints ≤ ~15 s → job in Recent (archived). - [ ] Reprint from Printing view works. - [ ] (If network work was done) rollback timer cancelled: `systemctl is-active convivo-net-rollback` → inactive. **Production (first real deployment — not done yet as of 2026-10-18)** - [ ] Verify `pgmq` is installable on prod Postgres (local: works as `postgres` role; prod unverified). - [ ] Apply the migration via docs/deployment.md (backup, single transaction, migration ledger). - [ ] Build + deploy admin app (Printing view, pill). The renderer ships **inside the Pi image**, not the web app. - [ ] Add station (prod) → one-time token → `setup.local.sh` with `CONVIVO_URL=https://admin.appe.at`. - [ ] `install.sh` against the prod Pi; run the post-deploy checklist with a real check-in.