feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view

- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts
This commit is contained in:
Lago committed 2026-10-18 22:25:38 +02:00
1 parent 04f3f55b78
commit c980effddc
55 files changed
+7406 -29

No files matched your search

+55
View File
@@ -16,6 +16,11 @@
"react-dom": "^18.3.1"
},
"devDependencies": {
"@fontsource/arimo": "^5.3.0",
"@fontsource/cousine": "^5.3.0",
"@fontsource/gelasio": "^5.3.0",
"@fontsource/open-sans": "^5.3.0",
"@fontsource/tinos": "^5.3.0",
"@types/canvas-confetti": "1.6.4",
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
@@ -697,6 +702,56 @@
"node": ">=12"
}
},
"node_modules/@fontsource/arimo": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/arimo/-/arimo-5.3.0.tgz",
"integrity": "sha512-nhxZ2sTVZYX8DJBgLuyX360B5vE4mxqpmjlKTRfucIqfcWRVx9vOYzWBc1IgEX0ist48VMC10PRKbFyH+4QFvQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/cousine": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/cousine/-/cousine-5.3.0.tgz",
"integrity": "sha512-EhVes1KpHrmPwGVCoVxYpdiIi/L2LRGxbAuv07m3TdY76f9Vmwyhd/TNqi2RC0NOvMCNt2FtYPJcAfFfkK9DoQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/gelasio": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/gelasio/-/gelasio-5.3.0.tgz",
"integrity": "sha512-V95Jr9GxtSCkigiWKEDTIqajefhJHk8251aQYrMBmrdSeYnjgbKRYxLjGpr3/NjpOAf2bejIiZPwtzJ9Bcpsgw==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/open-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/open-sans/-/open-sans-5.3.0.tgz",
"integrity": "sha512-V1bdMlGNyZrJwzrdusshMOw2YR0aqYDL7kOo9dkxUEKl8dFv66A9HLckOOXl572sG/7ohhDQrCrTFGSn9LZcSw==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/tinos": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/tinos/-/tinos-5.3.0.tgz",
"integrity": "sha512-VVDyyZdbcsLKxo/W7rClAvacD/7DsGc7J5xzzp51Tndib8kDkEe/0bqbb3Xb3iH6+IUjt07aRsvtQ9MGeGGi4w==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+6
View File
@@ -6,6 +6,7 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"build:print": "vite build --config vite.print.config.ts",
"preview": "vite preview"
},
"dependencies": {
@@ -17,6 +18,11 @@
"react-dom": "^18.3.1"
},
"devDependencies": {
"@fontsource/arimo": "^5.3.0",
"@fontsource/cousine": "^5.3.0",
"@fontsource/gelasio": "^5.3.0",
"@fontsource/open-sans": "^5.3.0",
"@fontsource/tinos": "^5.3.0",
"@types/canvas-confetti": "1.6.4",
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Convivo badge print renderer</title>
<style>
/* Tiny reset: the screenshot must be the pure badge, no editor chrome. */
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body, #badge-root { background: #fff; }
#badge-root .badge-page { box-shadow: none !important; border: 0 !important; border-radius: 0 !important; }
</style>
</head>
<body>
<div id="badge-root"></div>
<script type="module" src="/src/print/main.tsx"></script>
</body>
</html>
+10
View File
@@ -10,12 +10,15 @@ import { Schedule } from './views/Schedule';
import { Activity } from './views/Activity';
import { Raffle } from './views/Raffle';
import { BadgeEditor } from './views/BadgeEditor';
import { Printing } from './views/Printing';
import { Events } from './views/Events';
import { Interfaces } from './views/Interfaces';
import { Reports } from './views/Reports';
import { Settings } from './views/Settings';
import { Settings as SettingsIcon } from 'lucide-react';
import { Spinner } from './components/ui';
import { PrinterStatusPill } from './components/PrinterStatusPill';
import { PrintStatusProvider } from './lib/printStatus';
export type View =
| 'dashboard'
@@ -26,6 +29,7 @@ export type View =
| 'activity'
| 'raffle'
| 'badges'
| 'printing'
| 'events'
| 'interfaces'
| 'reports'
@@ -40,6 +44,7 @@ const NAV: { id: View; label: string; ico: string }[] = [
{ id: 'activity', label: 'Activity', ico: '⚡' },
{ id: 'raffle', label: 'Raffle', ico: '🎯' },
{ id: 'badges', label: 'Badges', ico: '🎫' },
{ id: 'printing', label: 'Printing', ico: '🖨️' },
{ id: 'events', label: 'Events', ico: '📅' },
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
{ id: 'reports', label: 'Reports', ico: '📤' },
@@ -61,6 +66,7 @@ function Shell() {
if (!contact) return <Login />;
return (
<PrintStatusProvider>
<div className="app">
<aside className="sidebar">
<div className="brand">
@@ -82,6 +88,8 @@ function Shell() {
</button>
))}
</nav>
{/* Outside .sidebar-foot so it also shows on mobile (the Pi has no screen). */}
<PrinterStatusPill onNavigate={setView} />
<div className="sidebar-foot">
<div className="admin-card">
<span className="avatar" style={{ width: 36, height: 36, fontSize: 13, background: '#d50000' }}>
@@ -112,12 +120,14 @@ function Shell() {
{view === 'activity' && <Activity />}
{view === 'raffle' && <Raffle />}
{view === 'badges' && <BadgeEditor />}
{view === 'printing' && <Printing />}
{view === 'events' && <Events />}
{view === 'interfaces' && <Interfaces />}
{view === 'reports' && <Reports />}
{view === 'settings' && <Settings />}
</main>
</div>
</PrintStatusProvider>
);
}
+2 -1
View File
@@ -1,5 +1,6 @@
import { QRCodeSVG } from 'qrcode.react';
import type { BadgeElement, BadgeQrElement, BadgeSample, BadgeTextElement } from '../lib/types';
import './badge-render.css';
// CSS 96 dpi: 1mm = 3.7795px. Shared by the editor canvas and read-only previews.
export const MM = 3.7795275591;
@@ -45,7 +46,7 @@ export function resolveText(el: BadgeTextElement, sample: BadgeSample): string {
export function resolveQr(el: BadgeQrElement, sample: BadgeSample): string {
switch (el.value) {
case 'qr_token': return sample.qr_token || 'CONVIVO-QR';
case 'checkin_url': return `${window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
case 'checkin_url': return `${sample.checkin_origin ?? window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`;
case 'email': return sample.email || '[email protected]';
case 'attendee_name': return sample.full_name || 'Attendee';
default: return el.static_value || 'https://example.com';
@@ -0,0 +1,54 @@
import type { View } from '../App';
import { Tooltip } from './ui';
import { activeStations, aggregateState, printerHint, timeAgo, shortError, usePrintStatus, worstStation } from '../lib/printStatus';
import type { PrintStation, PrintStationState } from '../lib/types';
// Pill label per aggregated state; the worst station refines error/offline text.
function pillText(state: PrintStationState | 'none', station: PrintStation | null): string {
if (state === 'none') return 'No printer';
if (state === 'ready') return 'Printer ready';
if (state === 'printing') return 'Printing…';
if (state === 'offline') return `Printer offline · ${timeAgo(station?.last_seen_at)}`;
const err = station?.last_status?.printer?.errors?.[0];
return err ? `Printer: ${shortError(err)}` : 'Printer error';
}
function tooltipContent(stations: PrintStation[]): string {
return stations
.map((s) => {
const st = s.last_status;
const roll = st?.printer?.label_id ?? 'unknown roll';
const net = st?.network;
const netText = net?.ssid ? `${net.ssid}${net.ip ? ` · ${net.ip}` : ''}` : net?.state ?? 'unknown';
const hint = printerHint(s);
return `${s.name} (${s.state}) — roll: ${roll} · network: ${netText} · last seen: ${timeAgo(s.last_seen_at)}${hint ? ` · ${hint}` : ''}`;
})
.join('\n');
}
/**
* Always-visible printer status for the sidebar (desktop and mobile). The Pi
* has no screen, so staff must see the printer state from every admin view.
*/
export function PrinterStatusPill({ onNavigate }: { onNavigate: (view: View) => void }) {
const { overview } = usePrintStatus();
const stations = activeStations(overview);
const state = aggregateState(stations);
const station = worstStation(stations);
const label = pillText(state, station);
return (
<Tooltip title="Printer status" content={<span style={{ whiteSpace: 'pre-line' }}>{tooltipContent(stations)}</span>}>
<button
type="button"
className={`printer-pill ${state}`}
data-testid="printer-pill"
data-state={state}
onClick={() => onNavigate('printing')}
>
<span className="printer-pill-dot" aria-hidden="true" />
{label}
</button>
</Tooltip>
);
}
+586
View File
@@ -0,0 +1,586 @@
/*
* Badge rendering: the read-only badge rules shared by the admin preview and the
* standalone print renderer (apps/admin/print.html). Imported by BadgeRender.tsx,
* so the admin app loads this before styles.css.
*/
/* Bundled fonts. The editor family names below are the ones BadgeEditor offers;
each maps to an open-licensed metric-compatible face so rendering never depends
on the fonts installed on the viewer's OS (admin laptop vs. the Pi). */
/* Open Sans latin 400 normal (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 400 normal (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 700 normal (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 700 normal (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 400 italic (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 400 italic (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 700 italic (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 700 italic (editor family "Open Sans") */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 400 normal (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 400 normal (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 700 normal (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 700 normal (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 400 italic (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 400 italic (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 700 italic (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 700 italic (editor family "Helvetica") */
@font-face {
font-family: 'Helvetica';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 400 normal (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 400 normal (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 700 normal (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 700 normal (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 400 italic (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 400 italic (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Arimo latin 700 italic (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Arimo latin-ext 700 italic (editor family "Arial") */
@font-face {
font-family: 'Arial';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/arimo/files/arimo-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Gelasio latin 400 normal (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Gelasio latin-ext 400 normal (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Gelasio latin 700 normal (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Gelasio latin-ext 700 normal (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Gelasio latin 400 italic (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Gelasio latin-ext 400 italic (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Gelasio latin 700 italic (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Gelasio latin-ext 700 italic (editor family "Georgia") */
@font-face {
font-family: 'Georgia';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/gelasio/files/gelasio-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Tinos latin 400 normal (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Tinos latin-ext 400 normal (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Tinos latin 700 normal (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Tinos latin-ext 700 normal (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Tinos latin 400 italic (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Tinos latin-ext 400 italic (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Tinos latin 700 italic (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Tinos latin-ext 700 italic (editor family "Times New Roman") */
@font-face {
font-family: 'Times New Roman';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/tinos/files/tinos-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Cousine latin 400 normal (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Cousine latin-ext 400 normal (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Cousine latin 700 normal (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Cousine latin-ext 700 normal (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Cousine latin 400 italic (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Cousine latin-ext 400 italic (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Cousine latin 700 italic (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Cousine latin-ext 700 italic (editor family "Courier New") */
@font-face {
font-family: 'Courier New';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/cousine/files/cousine-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 400 normal (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-400-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 400 normal (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: normal;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 700 normal (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-700-normal.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 700 normal (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: normal;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-normal.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 400 italic (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-400-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 400 italic (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: italic;
font-weight: 400;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-400-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Open Sans latin 700 italic (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-700-italic.woff2) format('woff2');
unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Open Sans latin-ext 700 italic (editor family "system-ui") */
@font-face {
font-family: 'system-ui';
font-style: italic;
font-weight: 700;
font-display: block;
src: url(@fontsource/open-sans/files/open-sans-latin-ext-700-italic.woff2) format('woff2');
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* ---------- badge page (read-only rendering) ---------- */
.badge-page {
position: relative; background: #fff; flex: none;
touch-action: none;
}
.badge-page-static { flex: none; }
.badge-el { position: absolute; overflow: visible; }
.badge-text-body { width: 100%; height: 100%; display: flex; overflow: hidden; }
.badge-text-body > span { width: 100%; overflow-wrap: anywhere; }
.badge-el-placeholder { color: #cbd5e1; font-style: italic; }
.badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
.badge-qr-body svg { width: 100%; height: 100%; }
.badge-image-body { width: 100%; height: 100%; display: block; }
.badge-image-empty {
display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px;
border: 1px dashed #cbd5e1; background: #f8fafc;
}
+32
View File
@@ -16,6 +16,7 @@ import type {
PointsLogRow,
PretixOptions,
PretixSyncResult,
PrintOverview,
RafflePoolEntry,
RaffleWinner,
Registration,
@@ -491,3 +492,34 @@ export const generateFeedbackSummary = (eventId: string, sessionId?: string) =>
method: 'POST',
body: JSON.stringify({ event_id: eventId, scope: sessionId ? 'session' : 'event', ...(sessionId ? { session_id: sessionId } : {}) }),
});
// ---- Badge printing (queue + printer stations) -------------------------------
/** Admin dashboard snapshot: stations, queue counters, recent jobs, dead letters. */
export const getPrintOverview = () => rpc<PrintOverview>('get_print_overview', {});
/** Queue one attendee's badge for printing; resolves with the queue msg id. */
export const enqueueBadgePrint = (registrationId: string) =>
rpc<number>('enqueue_badge_print', { p_registration_id: registrationId });
/** Register a printer station. The token is returned only here, never again. */
export async function createPrintStation(name: string): Promise<{ id: string; token: string }> {
// create_print_station returns a one-row table (a JSON array of one object).
const rows = await rpc<{ id: string; token: string }[]>('create_print_station', { p_name: name });
if (!rows[0]) throw new ApiError('Station creation returned no token');
return rows[0];
}
/** Retire a station; its token stops working immediately. */
export const revokePrintStation = (id: string) => rpc<void>('revoke_print_station', { p_id: id });
/** Rename a station (revoked ones included); the Pi adopts the new name. */
export const renamePrintStation = (id: string, name: string) =>
rpc<void>('rename_print_station', { p_id: id, p_name: name });
/** Push a dead letter back onto the live queue; resolves with the new msg id. */
export const requeueDeadBadgePrint = (msgId: number) =>
rpc<number>('requeue_dead_badge_print', { p_msg_id: msgId });
/** Drop a dead letter without retrying it. */
export const discardDeadBadgePrint = (msgId: number) => rpc<void>('discard_dead_badge_print', { p_msg_id: msgId });
+136
View File
@@ -0,0 +1,136 @@
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import { getPrintOverview } from './api';
import type { PrintOverview, PrintStation, PrintStationState } from './types';
const POLL_MS = 5000;
interface PrintStatusState {
overview: PrintOverview | null;
error: string | null;
refresh: () => Promise<void>;
}
const PrintStatusContext = createContext<PrintStatusState | null>(null);
/**
* Single shared poller for the badge-print overview, mounted once for the
* authenticated admin shell. Polls every 5 s while the document is visible,
* pauses when hidden and refreshes immediately on visibilitychange. A failing
* poll keeps the last overview and only exposes the error.
*/
export function PrintStatusProvider({ children }: { children: ReactNode }) {
const [overview, setOverview] = useState<PrintOverview | null>(null);
const [error, setError] = useState<string | null>(null);
const inflight = useRef(false);
const refresh = useCallback(async () => {
if (inflight.current) return;
inflight.current = true;
try {
const data = await getPrintOverview();
setOverview(data);
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : 'Printer status unavailable');
} finally {
inflight.current = false;
}
}, []);
useEffect(() => {
let cancelled = false;
const tick = () => {
if (!cancelled && document.visibilityState === 'visible') void refresh();
};
tick();
const timer = window.setInterval(tick, POLL_MS);
const onVisible = () => {
if (document.visibilityState === 'visible') void refresh();
};
document.addEventListener('visibilitychange', onVisible);
return () => {
cancelled = true;
window.clearInterval(timer);
document.removeEventListener('visibilitychange', onVisible);
};
}, [refresh]);
return <PrintStatusContext.Provider value={{ overview, error, refresh }}>{children}</PrintStatusContext.Provider>;
}
export function usePrintStatus(): PrintStatusState {
const ctx = useContext(PrintStatusContext);
if (!ctx) throw new Error('usePrintStatus must be used within PrintStatusProvider');
return ctx;
}
// ---- Pure helpers (shared by the pill, the Printing view and Registrations) --
/** Stations that can still print; revoked ones are ignored everywhere. */
export function activeStations(overview: PrintOverview | null): PrintStation[] {
return (overview?.stations ?? []).filter((s) => s.state !== 'revoked' && !s.revoked_at);
}
// Worst-state wins for the aggregated pill: error > offline > printing > ready.
const SEVERITY: PrintStationState[] = ['error', 'offline', 'printing', 'ready'];
export function aggregateState(stations: PrintStation[]): PrintStationState | 'none' {
for (const state of SEVERITY) if (stations.some((s) => s.state === state)) return state;
return 'none';
}
/** The station whose state drives the pill. */
export function worstStation(stations: PrintStation[]): PrintStation | null {
const state = aggregateState(stations);
return stations.find((s) => s.state === state) ?? null;
}
/** Compact age for last_seen_at: "45 s", "2 min", "3 h", "1 d". */
export function timeAgo(iso: string | null | undefined): string {
if (!iso) return 'never';
const secs = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000));
if (secs < 60) return `${secs} s`;
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins} min`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours} h`;
return `${Math.floor(hours / 24)} d`;
}
/** Trim Brother error strings to their core: 'No media when printing' → 'No media'. */
export function shortError(err: string): string {
return err.replace(/\s+when\s+printing/i, '').replace(/\s*\(.*\)\s*$/, '').trim();
}
/**
* Staff-facing instruction for a station's current problem ('' when fine).
* The Pi has no screen, so this text is the only channel to the operator.
*/
export function printerHint(station: PrintStation): string {
const st = station.last_status;
const wifiHint = () => {
const ssid = st?.network?.ssid?.trim();
const network = ssid ? `“${ssid}”` : '“Convivo-Printer-XXXX”';
return `The printer is not reachable. If it moved to a new Wi-Fi network, connect a phone to the open Wi-Fi ${network} and open http://10.41.0.1 to choose the network. Otherwise check the Raspberry Pi power.`;
};
if (station.state === 'offline') return wifiHint();
if (station.state === 'error') {
const printer = st?.printer;
if (printer && printer.connected === false) {
return 'Printer not detected — check the USB cable and that the printer is switched on.';
}
const errors = printer?.errors ?? [];
for (const err of errors) {
if (/wrong roll/i.test(err)) return err;
if (/cover open/i.test(err)) return 'Close the printer cover.';
if (/media/i.test(err)) return 'Load a new label roll.';
if (/cutter jam/i.test(err)) return 'Clear the cutter jam.';
}
if (errors.length > 0) return errors.join(' · ');
if (st?.last_error) return st.last_error;
return 'The printer reports a problem — check the station card below.';
}
// HOTSPOT on a live heartbeat means the Pi just lost its network.
if (st?.network?.state === 'HOTSPOT') return wifiHint();
return '';
}
+100
View File
@@ -431,4 +431,104 @@ export interface BadgeSample {
qr_token: string;
event_name: string;
company: string;
/** Origin used to build check-in URLs; defaults to the current page origin. */
checkin_origin?: string;
}
/** The payload handed to the standalone print renderer (`window.renderBadge`). */
export interface BadgePrintPayload {
schema: 'convivo.badge-print/v1';
kind: 'checkin' | 'reprint';
requested_at: string;
requested_by: string | null;
event: { id: string; name: string; company: string | null };
registration: { id: string; email: string; type: string };
sample: BadgeSample;
layout: {
id: string;
name: string;
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
};
}
// ---- Badge printing (queue + stations, `get_print_overview`) ----------------
/** Derived station state (`get_print_overview` computes it server-side). */
export type PrintStationState = 'ready' | 'printing' | 'error' | 'offline' | 'revoked';
/** The `last_status` heartbeat the Raspberry Pi worker writes every 10 s. */
export interface PrintStationStatus {
version?: string;
station_name?: string;
worker?: 'starting' | 'idle' | 'printing' | 'paused';
job_msg_id?: number | null;
printer?: {
connected?: boolean;
model?: string | null;
ready?: boolean;
media_type?: 'die-cut' | 'continuous' | null;
label_id?: string | null;
media_width_mm?: number | null;
media_length_mm?: number | null;
errors?: string[];
};
network?: {
state?: 'CONNECTED' | 'CONNECTING' | 'HOTSPOT' | 'UNKNOWN';
ssid?: string | null;
ip?: string | null;
};
label?: string | null;
last_error?: string | null;
uptime_s?: number;
}
export interface PrintStation {
id: string;
name: string;
created_at: string;
revoked_at: string | null;
last_seen_at: string | null;
last_status: PrintStationStatus | null;
state: PrintStationState;
}
export interface PrintQueueCounts {
pending: number;
in_flight: number;
dead_letter: number;
completed: number;
}
/** A completed (archived) badge job, newest first. */
export interface PrintRecentJob {
msg_id: number;
archived_at: string;
kind: 'checkin' | 'reprint' | string;
full_name: string | null;
email: string | null;
event_name: string | null;
registration_id: string | null;
}
/** A job that kept failing and was moved to the dead letter queue. */
export interface PrintDeadLetter {
msg_id: number;
enqueued_at: string;
failed_at: string | null;
error: string | null;
attempts: string | number | null;
kind: 'checkin' | 'reprint' | string;
full_name: string | null;
email: string | null;
event_name: string | null;
registration_id: string | null;
}
export interface PrintOverview {
stations: PrintStation[];
queue: PrintQueueCounts;
recent: PrintRecentJob[];
dead_letters: PrintDeadLetter[];
}
+77
View File
@@ -0,0 +1,77 @@
import { flushSync } from 'react-dom';
import { createRoot, type Root } from 'react-dom/client';
import { BadgePagePreview, MM } from '../components/BadgeRender';
import type { BadgePrintPayload } from '../lib/types';
declare global {
interface Window {
/** Render one badge; resolves with its size in CSS pixels. */
renderBadge: (
payload: BadgePrintPayload,
options?: { checkinOrigin?: string },
) => Promise<{ width_px: number; height_px: number }>;
__badgeReady: boolean;
__badgeError: string | null;
}
}
const SCHEMA = 'convivo.badge-print/v1';
let root: Root | null = null;
function nextFrame(): Promise<void> {
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
}
/** Wait until every image inside the badge is decoded (rejects on a broken src). */
async function waitForImages(host: HTMLElement): Promise<void> {
const images = Array.from(host.querySelectorAll('img'));
for (const img of images) {
try {
await img.decode();
} catch {
throw new Error(`image failed to load: ${img.src || img.getAttribute('src') || ''}`);
}
}
}
async function renderBadge(
payload: BadgePrintPayload,
options?: { checkinOrigin?: string },
): Promise<{ width_px: number; height_px: number }> {
window.__badgeReady = false;
window.__badgeError = null;
try {
if (!payload || payload.schema !== SCHEMA) {
throw new Error(`unsupported print payload schema: ${payload?.schema}`);
}
const host = document.getElementById('badge-root');
if (!host) throw new Error('badge-root element not found');
if (!root) root = createRoot(host);
flushSync(() => {
root?.render(
<BadgePagePreview
layout={payload.layout}
sample={{ ...payload.sample, checkin_origin: options?.checkinOrigin }}
pxPerMm={MM}
/>,
);
});
await document.fonts.ready;
await waitForImages(host);
await nextFrame();
await nextFrame();
const page = host.querySelector<HTMLElement>('.badge-page');
if (!page) throw new Error('badge page did not render');
const box = page.getBoundingClientRect();
window.__badgeReady = true;
return { width_px: box.width, height_px: box.height };
} catch (err) {
window.__badgeError = err instanceof Error ? err.message : String(err);
throw err;
}
}
window.renderBadge = renderBadge;
window.__badgeReady = false;
window.__badgeError = null;
+49 -16
View File
@@ -462,33 +462,20 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
overflow: auto; background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px;
padding: 28px; display: flex; justify-content: center; align-items: flex-start; min-height: 360px;
}
.badge-page {
position: relative; background: #fff; box-shadow: 0 10px 30px rgba(0,0,0,.12); flex: none;
touch-action: none;
}
/* Editor-only look; the shared read-only badge rules live in components/badge-render.css. */
.badge-page { box-shadow: 0 10px 30px rgba(0,0,0,.12); }
.badge-page-empty {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
color: #94a3b8; font-size: 13px; text-align: center; padding: 20px; pointer-events: none;
}
.badge-el { position: absolute; overflow: visible; cursor: move; }
.badge-el { cursor: move; }
.badge-el.selected { outline: 1.5px solid var(--accent); }
.badge-text-body { width: 100%; height: 100%; display: flex; overflow: hidden; }
.badge-text-body > span { width: 100%; overflow-wrap: anywhere; }
.badge-el-placeholder { color: #cbd5e1; font-style: italic; }
.badge-align-group { margin-top: 8px; }
.badge-align-group-label { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
.badge-preview-stage {
display: flex; justify-content: center; align-items: center; padding: 16px;
background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; min-height: 180px;
}
.badge-page-static { flex: none; }
.badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
.badge-qr-body svg { width: 100%; height: 100%; }
.badge-image-body { width: 100%; height: 100%; display: block; }
.badge-image-empty {
display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px;
border: 1px dashed #cbd5e1; background: #f8fafc;
}
.badge-handle {
position: absolute; width: 9px; height: 9px; background: #fff; border: 1.5px solid var(--accent);
border-radius: 2px; transform: translate(-50%, -50%); z-index: 2;
@@ -534,3 +521,49 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.badge-guide-v { width: 0; border-left: 1px dashed #ff2d95; }
.badge-guide-h { height: 0; border-top: 1px dashed #ff2d95; }
.badge-guide-space { border-color: #0ea5e9; }
/* Printing */
.printer-pill {
display: flex; align-items: center; gap: 8px; width: 100%; margin-top: 14px;
padding: 9px 12px; border-radius: 12px; border: 1px solid rgba(255,255,255,.16);
background: var(--sidebar-2); color: rgba(255,255,255,.85);
font-size: 12.5px; font-weight: 700; font-family: inherit; cursor: pointer;
white-space: nowrap; flex-shrink: 0; text-align: left; transition: background .12s;
}
.printer-pill:hover { background: rgba(255,255,255,.1); color: #fff; }
.printer-pill-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--muted); flex-shrink: 0; }
.printer-pill.ready { border-color: rgba(5,150,105,.55); }
.printer-pill.ready .printer-pill-dot { background: #10b981; box-shadow: 0 0 8px rgba(16,185,129,.7); }
.printer-pill.printing { border-color: rgba(14,165,233,.55); }
.printer-pill.printing .printer-pill-dot { background: #0ea5e9; box-shadow: 0 0 8px rgba(14,165,233,.7); animation: printer-pulse 1.1s ease-in-out infinite; }
.printer-pill.error { border-color: rgba(213,0,0,.6); }
.printer-pill.error .printer-pill-dot { background: var(--red); box-shadow: 0 0 8px rgba(213,0,0,.7); }
.printer-pill.offline .printer-pill-dot, .printer-pill.none .printer-pill-dot { background: #6b7280; }
@keyframes printer-pulse { 50% { opacity: .35; } }
@media (prefers-reduced-motion: reduce) {
.printer-pill.printing .printer-pill-dot { animation: none; }
}
@media (max-width: 760px) {
/* First in the scrolling top bar, so it never hides behind the wide nav.
The Tooltip wrapper (span.tip-anchor) is the real flex child. */
.sidebar > .tip-anchor:has(.printer-pill) { order: -1; flex-shrink: 0; }
.printer-pill { width: auto; margin-top: 0; padding: 8px 12px; }
}
.printing { display: grid; gap: 16px; align-content: start; }
.print-counters { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
.print-counter { text-align: center; padding: 14px 10px; }
.print-counter .n { font-size: 24px; font-weight: 800; }
.print-counter .l { color: var(--muted); font-size: 12.5px; font-weight: 600; }
.print-station { display: grid; gap: 12px; }
.print-station.revoked { opacity: .65; }
.print-hint {
padding: 10px 12px; border-radius: 12px; font-size: 13.5px; line-height: 1.5;
background: rgba(213,0,0,.07); border: 1px solid rgba(213,0,0,.3); color: var(--red);
}
.print-details { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 8px 16px; margin: 0; }
.print-details dt { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
.print-details dd { font-size: 13.5px; overflow-wrap: anywhere; margin: 0; }
.print-last-error { color: var(--red); }
@media (max-width: 760px) {
.print-counters { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
+425
View File
@@ -0,0 +1,425 @@
import { useState } from 'react';
import {
createPrintStation,
discardDeadBadgePrint,
enqueueBadgePrint,
renamePrintStation,
requeueDeadBadgePrint,
revokePrintStation,
} from '../lib/api';
import type { PrintDeadLetter, PrintRecentJob, PrintStation, PrintStationState } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Modal, Spinner } from '../components/ui';
import { activeStations, printerHint, timeAgo, usePrintStatus } from '../lib/printStatus';
const STATE_LABEL: Record<PrintStationState, string> = {
ready: 'ready',
printing: 'printing',
error: 'error',
offline: 'offline',
revoked: 'revoked',
};
const STATE_PILL: Record<PrintStationState, string> = {
ready: 'green',
printing: 'session',
error: 'red',
offline: 'attendee',
revoked: 'attendee',
};
const kindLabel = (kind: string) => (kind === 'checkin' ? 'check-in' : kind === 'reprint' ? 'reprint' : kind);
function fmtUptime(secs: number | undefined): string {
if (secs == null || !Number.isFinite(secs)) return '—';
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
return h > 0 ? `${h}h ${m}m` : `${m}m`;
}
function fmtTime(iso: string | null): string {
if (!iso) return '—';
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString();
}
export function Printing() {
const { push } = useToast();
const { overview, error, refresh } = usePrintStatus();
const [adding, setAdding] = useState(false);
const [stationName, setStationName] = useState('');
const [creating, setCreating] = useState(false);
const [issuedToken, setIssuedToken] = useState<{ name: string; token: string } | null>(null);
const [copied, setCopied] = useState(false);
const [busyId, setBusyId] = useState<string | number | null>(null);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState('');
const [renaming, setRenaming] = useState(false);
if (error && !overview) {
return <Empty icon="⚠️" text={error} />;
}
if (!overview) {
return (
<div className="loading-screen">
<Spinner />
</div>
);
}
const stations = overview.stations;
const live = activeStations(overview);
const { queue } = overview;
async function addStation() {
const name = stationName.trim();
if (!name || creating) return;
setCreating(true);
try {
const { token } = await createPrintStation(name);
setIssuedToken({ name, token });
setStationName('');
setAdding(false);
await refresh();
} catch (e) {
push('error', e instanceof Error ? e.message : 'Could not create the station');
} finally {
setCreating(false);
}
}
async function revoke(station: PrintStation) {
if (!confirm(`Revoke "${station.name}"? Its token stops working immediately and the Raspberry Pi can no longer print.`)) return;
setBusyId(station.id);
try {
await revokePrintStation(station.id);
await refresh();
push('success', `Station "${station.name}" revoked`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Revoke failed');
} finally {
setBusyId(null);
}
}
function startRename(station: PrintStation) {
setRenamingId(station.id);
setRenameValue(station.name);
}
function cancelRename() {
setRenamingId(null);
setRenameValue('');
}
async function saveRename(station: PrintStation) {
const name = renameValue.trim();
if (!name || renaming) return;
setRenaming(true);
try {
await renamePrintStation(station.id, name);
await refresh();
push('success', `Station renamed to "${name}"`);
cancelRename();
} catch (e) {
push('error', e instanceof Error ? e.message : 'Rename failed');
} finally {
setRenaming(false);
}
}
async function requeue(dl: PrintDeadLetter) {
setBusyId(dl.msg_id);
try {
await requeueDeadBadgePrint(dl.msg_id);
await refresh();
push('success', 'Job requeued — the station will pick it up');
} catch (e) {
push('error', e instanceof Error ? e.message : 'Requeue failed');
} finally {
setBusyId(null);
}
}
async function discard(dl: PrintDeadLetter) {
if (!confirm(`Discard this dead job${dl.full_name ? ` for ${dl.full_name}` : ''}? It will not be printed.`)) return;
setBusyId(dl.msg_id);
try {
await discardDeadBadgePrint(dl.msg_id);
await refresh();
push('success', 'Dead job discarded');
} catch (e) {
push('error', e instanceof Error ? e.message : 'Discard failed');
} finally {
setBusyId(null);
}
}
async function reprint(job: PrintRecentJob) {
if (!job.registration_id) {
push('error', 'This job has no registration to reprint');
return;
}
setBusyId(job.msg_id);
try {
await enqueueBadgePrint(job.registration_id);
await refresh();
push('success', `Reprint queued for ${job.full_name ?? job.email ?? 'attendee'}`);
} catch (e) {
push('error', e instanceof Error ? e.message : 'Reprint failed');
} finally {
setBusyId(null);
}
}
async function copyToken() {
if (!issuedToken) return;
try {
await navigator.clipboard.writeText(issuedToken.token);
setCopied(true);
} catch {
push('error', 'Copy failed — select the token and copy it manually');
}
}
return (
<div className="printing">
<div className="page-head">
<div>
<h1>Printing</h1>
<div className="sub">Badge queue and printer stations. {error ? <span className="feedback-error">Status update failed: {error}</span> : null}</div>
</div>
<div className="row" style={{ gap: 10 }}>
{adding ? (
<>
<input
className="input"
style={{ maxWidth: 220 }}
placeholder="Station name…"
value={stationName}
autoFocus
onChange={(e) => setStationName(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addStation()}
/>
<button className="btn primary small" disabled={!stationName.trim() || creating} onClick={addStation}>
{creating ? 'Creating…' : 'Create'}
</button>
<button className="btn small" onClick={() => { setAdding(false); setStationName(''); }}>
Cancel
</button>
</>
) : (
<button className="btn" onClick={() => setAdding(true)}>+ Add station</button>
)}
</div>
</div>
<div className="print-counters">
<div className="card print-counter"><div className="n">{queue.pending}</div><div className="l">pending</div></div>
<div className="card print-counter"><div className="n">{queue.in_flight}</div><div className="l">in progress</div></div>
<div className="card print-counter"><div className="n">{queue.completed}</div><div className="l">done</div></div>
<div className="card print-counter"><div className="n">{queue.dead_letter}</div><div className="l">dead letter</div></div>
</div>
<div className="section-head"><h2 className="h2">Stations</h2></div>
{live.length === 0 && stations.length === 0 && (
<div className="card">
<Empty icon="🖨️" text='No printer stations yet. Add one, then put its token on the Raspberry Pi.' />
</div>
)}
{live.length === 0 && stations.length > 0 && (
<div className="card"><Empty icon="🖨️" text='All stations are revoked. Add a station to print again.' /></div>
)}
{live.map((s) => {
const st = s.last_status;
const hint = printerHint(s);
const printer = st?.printer;
const roll = printer?.label_id
? `${printer.label_id}${printer.media_type ? ` · ${printer.media_type}` : ''}${
printer.media_width_mm ? ` · ${printer.media_width_mm}×${printer.media_length_mm ?? '∞'} mm` : ''
}`
: '—';
return (
<div className="card print-station" key={s.id} data-testid={`station-${s.id}`}>
<div className="row between" style={{ flexWrap: 'wrap', gap: 8 }}>
<div className="row" style={{ gap: 10 }}>
{renamingId === s.id ? (
<span className="row" style={{ gap: 8 }}>
<input
className="input"
style={{ maxWidth: 220 }}
aria-label="Station name"
value={renameValue}
autoFocus
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void saveRename(s);
if (e.key === 'Escape') cancelRename();
}}
/>
<button className="btn primary small" disabled={!renameValue.trim() || renaming} onClick={() => void saveRename(s)}>
{renaming ? 'Saving…' : 'Save'}
</button>
<button className="btn small" disabled={renaming} onClick={cancelRename}>
Cancel
</button>
</span>
) : (
<>
<strong>{s.name}</strong>
<span className={`pill ${STATE_PILL[s.state]}`}>{STATE_LABEL[s.state]}</span>
</>
)}
</div>
<div className="row" style={{ gap: 10 }}>
<span className="muted small">last seen {timeAgo(s.last_seen_at)} ago</span>
{renamingId !== s.id && (
<button className="btn small" disabled={busyId === s.id || renaming} onClick={() => startRename(s)}>
Rename
</button>
)}
<button className="btn danger small" disabled={busyId === s.id} onClick={() => revoke(s)}>
Revoke
</button>
</div>
</div>
{hint && <div className="print-hint" role="note">{hint}</div>}
<dl className="print-details">
<div><dt>Worker</dt><dd>{st?.worker ?? '—'}</dd></div>
<div><dt>Current job</dt><dd>{st?.job_msg_id ? `#${st.job_msg_id}` : '—'}</dd></div>
<div><dt>Printer</dt><dd>{printer?.model ?? '—'}</dd></div>
<div><dt>Roll</dt><dd>{roll}</dd></div>
<div>
<dt>Errors</dt>
<dd>{printer?.errors?.length ? printer.errors.join(' · ') : '—'}</dd>
</div>
<div>
<dt>Network</dt>
<dd>{st?.network ? `${st.network.state ?? '—'}${st.network.ssid ? ` · ${st.network.ssid}` : ''}${st.network.ip ? ` · ${st.network.ip}` : ''}` : '—'}</dd>
</div>
<div><dt>Version</dt><dd>{st?.version ?? '—'}</dd></div>
<div><dt>Uptime</dt><dd>{fmtUptime(st?.uptime_s)}</dd></div>
<div><dt>Last error</dt><dd className="print-last-error">{st?.last_error ?? '—'}</dd></div>
</dl>
</div>
);
})}
{stations.filter((s) => s.state === 'revoked').map((s) => (
<div className="card print-station revoked" key={s.id}>
<div className="row between">
<div className="row" style={{ gap: 10 }}>
<strong>{s.name}</strong>
<span className="pill attendee">revoked</span>
</div>
<span className="muted small">revoked {fmtTime(s.revoked_at)}</span>
</div>
</div>
))}
<div className="section-head"><h2 className="h2">Dead letters</h2></div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>Event</th>
<th>Error</th>
<th>Attempts</th>
<th>Failed at</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{overview.dead_letters.map((dl) => (
<tr key={dl.msg_id}>
<td>
<div className="cell-person">
<div>
<div className="n">{dl.full_name ?? '—'}</div>
<div className="e">{dl.email ?? ''}</div>
</div>
</div>
</td>
<td>{dl.event_name ?? '—'}</td>
<td className="small">{dl.error ?? '—'}</td>
<td>{dl.attempts ?? '—'}</td>
<td className="muted small">{fmtTime(dl.failed_at)}</td>
<td style={{ textAlign: 'right' }}>
<div className="row" style={{ gap: 8, justifyContent: 'flex-end' }}>
<button className="btn small" disabled={busyId === dl.msg_id} onClick={() => requeue(dl)}>
Requeue
</button>
<button className="btn danger small" disabled={busyId === dl.msg_id} onClick={() => discard(dl)}>
Discard
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{overview.dead_letters.length === 0 && (
<div style={{ padding: 16 }}><Empty icon="✅" text="No failed jobs — everything printed or is still queued." /></div>
)}
</div>
<div className="section-head"><h2 className="h2">Recently printed</h2></div>
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Attendee</th>
<th>Kind</th>
<th>Time</th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
<tbody>
{overview.recent.map((job) => (
<tr key={job.msg_id}>
<td>
<div className="cell-person">
<div>
<div className="n">{job.full_name ?? '—'}</div>
<div className="e">{job.email ?? ''}</div>
</div>
</div>
</td>
<td><span className="pill">{kindLabel(job.kind)}</span></td>
<td className="muted small">{fmtTime(job.archived_at)}</td>
<td style={{ textAlign: 'right' }}>
<button className="btn small" disabled={busyId === job.msg_id || !job.registration_id} onClick={() => reprint(job)}>
Reprint
</button>
</td>
</tr>
))}
</tbody>
</table>
{overview.recent.length === 0 && (
<div style={{ padding: 16 }}><Empty icon="🖨️" text="Nothing has been printed yet." /></div>
)}
</div>
{issuedToken && (
<Modal
open
title={`Station token — ${issuedToken.name}`}
onClose={() => { setIssuedToken(null); setCopied(false); }}
footer={
<button className="btn primary" onClick={() => { setIssuedToken(null); setCopied(false); }}>
Done
</button>
}
>
<p className="feedback-error" style={{ fontWeight: 700 }}>
Store it in the Raspberry Pi setup now — it cannot be shown again.
</p>
<div className="row" style={{ gap: 8 }}>
<input className="input mono" readOnly value={issuedToken.token} onFocus={(e) => e.target.select()} aria-label="Station token" />
<button className="btn" onClick={copyToken}>{copied ? 'Copied' : 'Copy'}</button>
</div>
</Modal>
)}
</div>
);
}
+36
View File
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import {
createRegistration,
deleteContacts,
enqueueBadgePrint,
getBadgeLayouts,
getAllContacts,
getAllEvents,
@@ -18,6 +19,7 @@ import { useToast } from '../context/ToastContext';
import { useAuth } from '../context/AuthContext';
import { Avatar, ColumnFilter, Empty, Modal, QrImage, Spinner, Toggle, Tooltip, TypeBadge, type ColumnFilterOption } from '../components/ui';
import { BadgePagePreview, fitScale } from '../components/BadgeRender';
import { activeStations, aggregateState, usePrintStatus } from '../lib/printStatus';
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
// Multi-select column filters are Excel-style: an empty selection means "all".
@@ -44,6 +46,10 @@ export function Registrations() {
const [mergeFor, setMergeFor] = useState<Registration | null>(null);
const [badgeFor, setBadgeFor] = useState<Registration | null>(null);
const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
const [printingIds, setPrintingIds] = useState<Set<string>>(new Set());
const { overview: printOverview } = usePrintStatus();
// Aggregated printer state, used only to phrase the enqueue toast honestly.
const printerState = aggregateState(activeStations(printOverview));
const [fType, setFType] = useState<string[]>([]);
const [fTicket, setFTicket] = useState<string[]>([]);
const [fCheckedIn, setFCheckedIn] = useState<string[]>([]);
@@ -201,6 +207,25 @@ export function Registrations() {
}
}
// Queue this attendee's badge. Works while the printer is offline/error —
// the job simply prints once the station is back.
async function printBadge(r: Registration) {
if (printingIds.has(r.id)) return;
setPrintingIds((ids) => new Set(ids).add(r.id));
try {
await enqueueBadgePrint(r.id);
push('success', printerState === 'offline' || printerState === 'error' ? `Queued — printer is ${printerState}` : 'Sent to printer');
} catch (e) {
push('error', e instanceof Error ? e.message : 'Print failed');
} finally {
setPrintingIds((ids) => {
const next = new Set(ids);
next.delete(r.id);
return next;
});
}
}
if (error) return <Empty icon="⚠️" text={error} />;
if (!loaded)
return (
@@ -327,6 +352,17 @@ export function Registrations() {
</button>
</Tooltip>
)}
{badgeConfigured ? (
<button className="btn small" disabled={printingIds.has(r.id)} onClick={() => printBadge(r)} title="Send this attendee's badge to the printer">
{printingIds.has(r.id) ? 'Printing…' : 'Print'}
</button>
) : (
<Tooltip title="No badge yet" content="A badge needs to be configured for this event first. Design one in the Badges view.">
<button className="btn small" disabled>
Print
</button>
</Tooltip>
)}
{!r.qr_token?.trim() && r.import_source === 'sessionize' && (
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
Merge tickets
+1 -1
View File
@@ -9,5 +9,5 @@
"strict": true,
"noEmit": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "vite.print.config.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Standalone print renderer bundle (print.html -> dist-print). No dev proxy:
// the Pi serves the static files itself and drives it through window.renderBadge.
export default defineConfig({
plugins: [react()],
base: './',
build: {
outDir: 'dist-print',
emptyOutDir: true,
rollupOptions: { input: 'print.html' },
},
});
+337
View File
@@ -0,0 +1,337 @@
# 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 … <pw>`), 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 <private-0600-file>)" 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-<nnnn>` (`<nnnn>` 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://<dev-machine-LAN-IP>: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\":\"<admin @appe.at 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('<registration-id>');` (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-<nnnn>` → 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.
+36
View File
@@ -0,0 +1,36 @@
# Convivo badge-printer worker.
# Build context = REPO ROOT:
# docker buildx build --platform linux/arm64 -f apps/printer/Dockerfile -t convivo-printer:latest .
# --- badge print renderer (built on the native build platform for speed) ------
FROM --platform=$BUILDPLATFORM node:20-bookworm-slim AS renderer
WORKDIR /build
COPY apps/admin/package.json apps/admin/package-lock.json ./
RUN npm ci
COPY apps/admin/ ./
RUN npx vite build --config vite.print.config.ts
# --- runtime: Playwright Chromium + brother_ql + worker ------------------------
FROM mcr.microsoft.com/playwright/python:v1.55.0-noble
ARG APP_VERSION=dev
RUN apt-get update \
&& apt-get install -y --no-install-recommends libusb-1.0-0 fonts-dejavu-core \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY apps/printer/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
COPY apps/printer/worker/ /app/worker/
COPY --from=renderer /build/dist-print /app/renderer/
ENV PYTHONUNBUFFERED=1 \
APP_VERSION=${APP_VERSION}
# Root on purpose: raw USB access for the Brother printer (no privileged mode).
# The image's Chromium runs with --no-sandbox (set in render.py).
HEALTHCHECK --interval=30s --timeout=5s --start-period=120s \
CMD find /tmp/heartbeat-ok -mmin -1 | grep -q . || exit 1
CMD ["python", "-m", "worker"]
+19
View File
@@ -0,0 +1,19 @@
# Per-Dockerfile ignore (BuildKit: <Dockerfile>.dockerignore). Context = repo root.
.git
**/.git
**/node_modules
**/dist
**/dist-print
**/test-results
assets
docs
e2e
mockup
packages
src
supabase
apps/convivo
apps/printer/pi
apps/printer/tests
*.md
docker-compose.yml
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# Copy setup (+ worker image when present) to the Pi and run it as root.
# Usage: apps/printer/pi/install.sh [ssh-target] (default: convivo-pi)
# Env: PI_SUDO_PASSWORD (prompted if unset), STAGE_APP / STAGE_WIFI_PORTAL / REBOOT forwarded to setup.sh.
# SKIP_BUILD=1 reuses an existing image tar instead of rebuilding it.
# SKIP_IMAGE=1 does not upload the image tar (reuse the image already on the Pi).
set -euo pipefail
TARGET="${1:-convivo-pi}"
DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$DIR/../../.." && pwd)"
SETUP="$DIR/setup.local.sh"
[[ -f $SETUP ]] || SETUP="$DIR/setup.sh"
PORTAL="$ROOT/apps/printer/portal/portal.py"
IMAGE="$DIR/convivo-printer-image.tar.gz"
# /tmp is a small RAM tmpfs on the Pi; the image tarball needs disk.
REMOTE=/var/tmp/convivo-setup
if [[ "${SKIP_BUILD:-0}" != 1 && "${SKIP_IMAGE:-0}" != 1 ]]; then
# SKIP_IMAGE reuses the Pi's image, so a local build would only be discarded.
# Cross-build the arm64 image from the repo root (default docker builder).
if ! docker buildx inspect default 2>/dev/null | grep -q linux/arm64; then
echo "linux/arm64 not in buildx default builder — installing QEMU binfmt" >&2
docker run --privileged --rm tonistiigi/binfmt --install arm64
fi
echo "Building convivo-printer image (arm64) → $IMAGE"
(
cd "$ROOT"
docker buildx build --platform linux/arm64 \
-f apps/printer/Dockerfile \
--build-arg "APP_VERSION=$(git rev-parse --short HEAD)-$(date +%Y%m%d%H%M)" \
-t convivo-printer:latest \
--output "type=docker,dest=-" . | gzip > "$IMAGE"
)
fi
ssh "$TARGET" "mkdir -p $REMOTE"
scp -q "$SETUP" "$TARGET:$REMOTE/setup.sh"
scp -q "$PORTAL" "$TARGET:$REMOTE/portal.py"
if [[ "${SKIP_IMAGE:-0}" == 1 ]]; then
# Reuse the image already loaded on the Pi; drop any stale tar so setup.sh does not load it.
ssh "$TARGET" "rm -f $REMOTE/convivo-printer-image.tar.gz"
else
[[ -f $IMAGE ]] && scp -q "$IMAGE" "$TARGET:$REMOTE/convivo-printer-image.tar.gz"
fi
if [[ -z "${PI_SUDO_PASSWORD:-}" ]]; then
read -rsp "sudo password for $TARGET: " PI_SUDO_PASSWORD
echo
fi
STAGE_ENV=()
for v in STAGE_APP STAGE_WIFI_PORTAL REBOOT; do
[[ -n "${!v:-}" ]] && STAGE_ENV+=("$v=${!v}")
done
printf '%s\n' "$PI_SUDO_PASSWORD" | ssh "$TARGET" "sudo -S -p '' env ${STAGE_ENV[*]:-} bash $REMOTE/setup.sh"
+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env bash
# Convivo badge printer — Raspberry Pi 4 provisioning (Raspberry Pi OS / Debian trixie, arm64).
# Usage (on the Pi): sudo bash setup.sh
# Idempotent: safe to re-run for updates. Fill a copy as setup.local.sh (git-ignored); never commit the token.
set -euo pipefail
# ---- Configuration -----------------------------------------------------------
# Empty CONVIVO_URL / CONVIVO_ANON_KEY / PRINTER_STATION_TOKEN keep the values already
# in $INSTALL_DIR/.env (e.g. configured through the portal), so re-runs never reset them.
: "${CONVIVO_URL:=}"
# Public anon key (same value baked into the web apps); not a secret.
: "${CONVIVO_ANON_KEY:=}"
# Station token from Admin → Printing → "Add station" (shown once). Required once, via this
# variable or the portal.
: "${PRINTER_STATION_TOKEN:=}"
: "${STATION_NAME:=Welcome desk}"
: "${BADGE_CHECKIN_ORIGIN:=https://admin.appe.at}"
: "${BROTHER_MODEL:=QL-1110NWB}"
: "${BROTHER_LABEL:=auto}"
: "${PRINTER_IDENTIFIER:=usb://0x04f9:0x20a8}"
# 1 = print "ready" / "no network" labels on the printer (costs media).
: "${STATUS_LABELS:=0}"
: "${PI_HOSTNAME:=convivo-printer}"
: "${TIMEZONE:=Europe/Vienna}"
# comitup replaces <nnnn> with a persistent per-device number.
: "${AP_NAME:=Convivo-Printer-<nnnn>}"
: "${IMAGE_TAR:=$(dirname "$(readlink -f "$0")")/convivo-printer-image.tar.gz}"
: "${INSTALL_DIR:=/opt/convivo-printer}"
# Stages: 1 = run, 0 = skip.
: "${STAGE_WIFI_PORTAL:=1}"
: "${STAGE_APP:=1}"
: "${REBOOT:=0}"
log() { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }
warn() { printf '\033[1;33m[warn] %s\033[0m\n' "$*" >&2; }
die() { printf '\033[1;31m[fail] %s\033[0m\n' "$*" >&2; exit 1; }
export DEBIAN_FRONTEND=noninteractive
APT_OPTS=(-y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
preflight() {
log "Preflight"
[[ $EUID -eq 0 ]] || die "run as root: sudo bash $0"
[[ "$(uname -m)" == "aarch64" ]] || die "expected aarch64, got $(uname -m)"
. /etc/os-release
[[ "${ID:-}" == "debian" || "${ID_LIKE:-}" == *debian* ]] || die "unsupported OS: ${PRETTY_NAME:-unknown}"
echo "OS: $PRETTY_NAME · $(tr -d '\0' </proc/device-tree/model 2>/dev/null || true)"
curl -fsS --max-time 10 -o /dev/null https://deb.debian.org/ || die "no internet access (needed for apt/Docker)"
}
base_system() {
log "Base system"
if [[ "$(hostname)" != "$PI_HOSTNAME" ]]; then
hostnamectl set-hostname "$PI_HOSTNAME"
sed -i "s/^127\.0\.1\.1.*/127.0.1.1\t$PI_HOSTNAME/" /etc/hosts
grep -q "^127\.0\.1\.1" /etc/hosts || printf '127.0.1.1\t%s\n' "$PI_HOSTNAME" >>/etc/hosts
fi
timedatectl set-timezone "$TIMEZONE"
# No RTC on the Pi 4: TLS to Convivo fails until the clock is synced.
systemctl enable --now systemd-timesyncd
apt-get update
apt-get "${APT_OPTS[@]}" full-upgrade
apt-get "${APT_OPTS[@]}" install ca-certificates curl gnupg jq usbutils iw
}
reliability() {
log "Reliability (watchdog, Wi-Fi power save, logs, no auto-upgrades)"
install -d /etc/systemd/system.conf.d /etc/systemd/journald.conf.d /etc/NetworkManager/conf.d
local before
before=$(sha256sum /etc/systemd/system.conf.d/convivo-watchdog.conf 2>/dev/null || true)
cat >/etc/systemd/system.conf.d/convivo-watchdog.conf <<'EOF'
[Manager]
RuntimeWatchdogSec=15s
RebootWatchdogSec=2min
EOF
cat >/etc/systemd/journald.conf.d/convivo.conf <<'EOF'
[Journal]
SystemMaxUse=100M
EOF
cat >/etc/NetworkManager/conf.d/convivo-wifi-powersave.conf <<'EOF'
[connection]
wifi.powersave = 2
EOF
if [[ "$before" != "$(sha256sum /etc/systemd/system.conf.d/convivo-watchdog.conf)" ]]; then
systemctl daemon-reexec
# comitup keeps a D-Bus proxy to the old systemd; without a restart its hotspot never starts DHCP.
systemctl try-restart comitup.service
fi
systemctl restart systemd-journald
# Avoid surprise upgrades/reboots during an event; re-run this script to update.
systemctl disable --now apt-daily.timer apt-daily-upgrade.timer 2>/dev/null || true
}
install_docker() {
log "Docker Engine"
if ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
. /etc/os-release
cat >/etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/debian
Suites: ${VERSION_CODENAME}
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
apt-get update
apt-get "${APT_OPTS[@]}" install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
fi
install -d /etc/docker
local before
before=$(sha256sum /etc/docker/daemon.json 2>/dev/null || true)
cat >/etc/docker/daemon.json <<'EOF'
{
"log-driver": "json-file",
"log-opts": { "max-size": "10m", "max-file": "3" }
}
EOF
systemctl enable docker
# A restart bounces the running worker on its old image, so only restart on config changes.
if [[ "$before" != "$(sha256sum /etc/docker/daemon.json)" ]]; then
systemctl restart docker
fi
if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != root ]]; then
usermod -aG docker "$SUDO_USER"
fi
}
usb_printer() {
log "USB printer access"
# brother_ql talks raw USB via libusb; the kernel printer driver would hold the device.
echo "blacklist usblp" >/etc/modprobe.d/convivo-no-usblp.conf
modprobe -r usblp 2>/dev/null || true
# ipp-usb claims the QL-1110NWB's IPP-over-USB interfaces (libusb then fails with "Resource busy").
if systemctl list-unit-files ipp-usb.service >/dev/null 2>&1; then
systemctl disable --now ipp-usb.service 2>/dev/null || true
systemctl mask ipp-usb.service
fi
if lsusb -d 04f9: >/dev/null; then
lsusb -d 04f9:
else
warn "no Brother printer detected on USB (connect it and power it on)"
fi
}
env_get() { # env_get KEY FILE -> value of the last KEY=... line (empty if absent)
awk -F= -v k="$1" '$1 == k { sub(/^[^=]*=/, ""); v=$0 } END { print v }' "$2" 2>/dev/null || true
}
install_app() {
log "Convivo printer worker"
if [[ $STAGE_APP != 1 ]]; then echo "skipped (STAGE_APP=0)"; return; fi
install -d -m 0755 "$INSTALL_DIR"
local envf="$INSTALL_DIR/.env" old=""
[[ -f $envf ]] && old=$(cat "$envf")
# Empty setup variables keep what the portal (or an earlier run) already stored.
if [[ -n $old ]]; then
[[ -n $CONVIVO_URL ]] || CONVIVO_URL=$(env_get CONVIVO_URL "$envf")
[[ -n $CONVIVO_ANON_KEY ]] || CONVIVO_ANON_KEY=$(env_get CONVIVO_ANON_KEY "$envf")
[[ -n $PRINTER_STATION_TOKEN ]] || PRINTER_STATION_TOKEN=$(env_get PRINTER_STATION_TOKEN "$envf")
fi
: "${CONVIVO_URL:=https://convivo.appe.at}"
if [[ -f $IMAGE_TAR && -z $PRINTER_STATION_TOKEN ]]; then
die "PRINTER_STATION_TOKEN is empty (create a station in Admin → Printing, or use the portal)"
fi
[[ -n $CONVIVO_ANON_KEY ]] || warn "CONVIVO_ANON_KEY is empty — set it in the portal or the worker cannot reach Convivo"
umask 077
cat >"$envf" <<EOF
CONVIVO_URL=$CONVIVO_URL
CONVIVO_ANON_KEY=$CONVIVO_ANON_KEY
PRINTER_STATION_TOKEN=$PRINTER_STATION_TOKEN
STATION_NAME=$STATION_NAME
BADGE_CHECKIN_ORIGIN=$BADGE_CHECKIN_ORIGIN
BROTHER_MODEL=$BROTHER_MODEL
BROTHER_LABEL=$BROTHER_LABEL
PRINTER_IDENTIFIER=$PRINTER_IDENTIFIER
STATUS_LABELS=$STATUS_LABELS
EOF
umask 022
cat >"$INSTALL_DIR/docker-compose.yml" <<'EOF'
services:
printer:
image: convivo-printer:latest
container_name: convivo-printer
restart: always
network_mode: host
env_file: .env
devices:
- /dev/bus/usb:/dev/bus/usb
# USB char devices (major 189) so a replugged printer is reachable without a restart.
device_cgroup_rules:
- "c 189:* rmw"
volumes:
- /run/convivo:/run/convivo:ro
tmpfs:
- /tmp
shm_size: 256m
logging:
driver: json-file
options: { max-size: "10m", max-file: "3" }
EOF
local loaded
if [[ -f $IMAGE_TAR ]]; then
loaded=$(docker load -i "$IMAGE_TAR" | awk -F': ' '/Loaded image/ {print $2; exit}')
[[ -n $loaded ]] || die "docker load did not report an image"
[[ $loaded == convivo-printer:latest ]] || docker tag "$loaded" convivo-printer:latest
docker image prune -f >/dev/null
elif docker image inspect convivo-printer:latest >/dev/null 2>&1; then
warn "image tar not found — reusing convivo-printer:latest already on the Pi"
else
warn "no image tar and no convivo-printer:latest on the Pi — wrote .env/compose, worker not started"
return
fi
# Compose recreates the container only when the config or image actually changed.
docker compose -f "$INSTALL_DIR/docker-compose.yml" up -d --remove-orphans
}
wifi_portal() {
log "Wi-Fi provisioning portal (comitup)"
if [[ $STAGE_WIFI_PORTAL != 1 ]]; then echo "skipped (STAGE_WIFI_PORTAL=0)"; return; fi
apt-get "${APT_OPTS[@]}" install comitup
install -d /usr/local/lib/convivo
cat >/usr/local/lib/convivo/netstate.sh <<'EOF'
#!/bin/sh
# comitup external_callback ($1 = HOTSPOT|CONNECTING|CONNECTED): publish network state for the worker.
state="${1:-UNKNOWN}"
dir=/run/convivo
mkdir -p "$dir"
ssid=$(iw dev wlan0 info 2>/dev/null | awk '/ssid/ {sub(/^[ \t]*ssid /, ""); print; exit}')
ip=$(ip -4 -o addr show scope global 2>/dev/null | awk '{split($4, a, "/"); print a[1]; exit}')
jq -n --arg state "$state" --arg ssid "$ssid" --arg ip "$ip" --arg at "$(date -Is)" \
'{state: $state, ssid: $ssid, ip: $ip, updated_at: $at}' >"$dir/network.json.tmp"
mv "$dir/network.json.tmp" "$dir/network.json"
EOF
chmod 0755 /usr/local/lib/convivo/netstate.sh
echo "d /run/convivo 0755 root root -" >/etc/tmpfiles.d/convivo.conf
systemd-tmpfiles --create /etc/tmpfiles.d/convivo.conf
# The Convivo portal replaces comitup-web while in HOTSPOT. install.sh copies portal.py
# next to this script; fail clearly if it is missing rather than leave the stock portal.
local portal_src="$(dirname "$(readlink -f "$0")")/portal.py"
[[ -f $portal_src ]] || die "portal.py not found next to setup.sh ($portal_src) — copy it alongside (install.sh does this)"
install -m 0755 -o root -g root "$portal_src" /usr/local/lib/convivo/portal.py
local dropin_dir=/etc/systemd/system/comitup-web.service.d dropin="$dropin_dir/convivo.conf"
install -d -m 0755 "$dropin_dir"
local dropin_before
dropin_before=$(sha256sum "$dropin" 2>/dev/null || true)
cat >"$dropin" <<'EOF'
# Managed by Convivo setup.sh — serve the Convivo portal instead of comitup-web.
[Service]
ExecStart=
ExecStart=/usr/bin/python3 /usr/local/lib/convivo/portal.py
EOF
# A changed drop-in only needs a reload; comitup-web is started on demand in HOTSPOT.
[[ "$dropin_before" != "$(sha256sum "$dropin")" ]] && systemctl daemon-reload
local before
before=$(sha256sum /etc/comitup.conf 2>/dev/null || true)
cat >/etc/comitup.conf <<EOF
# Managed by Convivo setup.sh
ap_name: $AP_NAME
external_callback: /usr/local/lib/convivo/netstate.sh
enable_appliance_mode: false
verbose: 0
EOF
systemctl enable comitup
# A restart re-negotiates Wi-Fi, so only do it when something changed.
if [[ "$before" != "$(sha256sum /etc/comitup.conf)" ]] || ! systemctl is-active --quiet comitup; then
systemctl restart comitup
fi
}
verify() {
log "Verification"
docker --version
docker compose version
systemctl is-active systemd-timesyncd docker >/dev/null && echo "timesyncd + docker active"
[[ -e /dev/watchdog ]] && echo "hardware watchdog present"
lsusb -d 04f9: || warn "Brother printer not detected"
[[ $STAGE_WIFI_PORTAL == 1 ]] && { systemctl is-active comitup || warn "comitup not active"; }
if docker ps --format '{{.Names}}' | grep -qx convivo-printer; then
docker ps --filter name=convivo-printer --format 'worker: {{.Status}}'
fi
if [[ -f /var/run/reboot-required ]]; then
warn "reboot required (kernel/firmware update)"
[[ $REBOOT == 1 ]] && { log "Rebooting"; systemctl reboot; }
fi
}
preflight
base_system
reliability
install_docker
usb_printer
install_app
wifi_portal
verify
log "Done"
+585
View File
@@ -0,0 +1,585 @@
#!/usr/bin/env python3
"""Convivo provisioning portal served in place of comitup-web while the Pi is in HOTSPOT.
Wi-Fi picker (comitup D-Bus) plus optional Convivo URL / anon key / station token,
which are written to /opt/convivo-printer/.env and applied with docker compose.
Only the standard library plus python3-dbus (already required by comitup) is used;
dbus is imported lazily so the pure helpers stay unit-testable.
"""
from __future__ import annotations
import html
import json
import os
import re
import secrets
import subprocess
import sys
import threading
import time
import urllib.parse
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ENV_FILE = os.environ.get("PORTAL_ENV_FILE", "/opt/convivo-printer/.env")
PORT = int(os.environ.get("PORTAL_PORT", "80"))
DRY_RUN = os.environ.get("PORTAL_DRY_RUN", "0") == "1"
COMPOSE_FILE = "/opt/convivo-printer/docker-compose.yml"
AP_ADDR = "10.41.0.1"
MAX_BODY_BYTES = 8192
TOKEN_PREFIX = "cvp_"
TOKEN_LENGTH = 68
# The only keys the portal may write; anything else is rejected.
ENV_KEY_WHITELIST = ("CONVIVO_URL", "CONVIVO_ANON_KEY", "PRINTER_STATION_TOKEN")
DBUS_NAME = "com.github.davesteele.comitup"
DBUS_PATH = "/com/github/davesteele/comitup"
FAKE_NETWORKS = [
{"ssid": "FakeOffice", "strength": "82", "security": "encrypted"},
{"ssid": "FakeOpen", "strength": "40", "security": "unencrypted"},
]
# ---------------------------------------------------------------------------
# Pure helpers (unit-tested, no dbus / no root)
# ---------------------------------------------------------------------------
def parse_env(text: str) -> dict[str, str]:
result: dict[str, str] = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
result[key.strip()] = value.strip()
return result
def update_env(text: str, updates: dict[str, str]) -> str:
"""Rewrite env text with `updates`; unknown lines are preserved as-is."""
for key in updates:
if key not in ENV_KEY_WHITELIST:
raise ValueError(f"key not allowed: {key}")
value = updates[key]
if "=" in value or any(c in value for c in "\r\n"):
raise ValueError(f"value for {key} must not contain newlines or '='")
lines = text.splitlines()
seen: set[str] = set()
out: list[str] = []
for line in lines:
stripped = line.strip()
if stripped and not stripped.startswith("#") and "=" in stripped:
key = stripped.partition("=")[0].strip()
if key in updates:
out.append(f"{key}={updates[key]}")
seen.add(key)
continue
out.append(line)
for key in updates:
if key not in seen:
out.append(f"{key}={updates[key]}")
return "\n".join(out) + "\n"
def write_env(path: str, text: str) -> None:
"""Atomically replace `path` with owner-only mode 0600."""
tmp = f"{path}.tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
os.chmod(tmp, 0o600)
os.replace(tmp, path)
def mask_token(token: str) -> str:
if not token:
return ""
return f"{TOKEN_PREFIX}…{token[-4:]}" if len(token) > 8 else f"{TOKEN_PREFIX}…"
def _is_private_host(host: str) -> bool:
host = host.strip("[]").lower()
if host in ("localhost", "localhost.localdomain") or host.endswith(".local"):
return True
m = re.fullmatch(r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})", host)
if not m:
return False
a, b = int(m.group(1)), int(m.group(2))
return a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or a == 127
def validate_url(value: str) -> tuple[str | None, str | None]:
"""Return (error, warning) for a Convivo URL; warning set for plaintext http on a LAN host."""
try:
parsed = urllib.parse.urlsplit(value)
except ValueError as exc:
return f"URL is not valid: {exc}", None
host = (parsed.hostname or "").lower()
if parsed.scheme == "https" and host:
return None, None
if parsed.scheme == "http" and host and _is_private_host(host):
return None, ("http:// works only on the local network — it sends the station "
"token unencrypted; prefer https://.")
return "URL must start with https:// (http:// only for a local/LAN address).", None
def validate_anon_key(value: str) -> str | None:
parts = value.split(".")
if len(parts) != 3 or not all(parts):
return "Anon key must look like a JWT: three base64url parts separated by dots."
if not all(re.fullmatch(r"[A-Za-z0-9_\-]+", p) for p in parts):
return "Anon key must look like a JWT: three base64url parts separated by dots."
return None
def validate_token(value: str) -> str | None:
if not value.startswith(TOKEN_PREFIX):
return f"Station token must start with {TOKEN_PREFIX}."
if len(value) != TOKEN_LENGTH:
return f"Station token must be exactly {TOKEN_LENGTH} characters."
return None
def sort_aps(aps: list[dict]) -> list[dict]:
def strength(ap: dict) -> float:
try:
return float(ap.get("strength", 0))
except (TypeError, ValueError):
return 0.0
return sorted(aps, key=strength, reverse=True)
def parse_connect(form: dict) -> tuple[str, str, dict[str, str], list[str], list[str]]:
"""Validate portal form fields. Returns (ssid, password, env-updates, errors, warnings)."""
errors: list[str] = []
warnings: list[str] = []
ssid = (form.get("hidden_ssid") if form.get("hidden") else form.get("ssid")) or ""
ssid = ssid.strip()
if len(ssid.encode("utf-8")) > 32 or any(c in ssid for c in "\r\n"):
errors.append("Network name is too long or contains invalid characters.")
ssid = ""
password = form.get("password") or ""
if not ssid and not errors:
errors.append("Please choose a Wi-Fi network (or enter a hidden network name).")
if any(c in password for c in "\r\n"):
errors.append("Password contains invalid characters.")
if len(password) > 128:
errors.append("Password is too long.")
updates: dict[str, str] = {}
url = (form.get("convivo_url") or "").strip()
if url:
err, warn = validate_url(url)
if err:
errors.append(err)
else:
if warn:
warnings.append(warn)
updates["CONVIVO_URL"] = url
anon = (form.get("anon_key") or "").strip()
if anon:
err = validate_anon_key(anon)
if err:
errors.append(err)
else:
updates["CONVIVO_ANON_KEY"] = anon
token = (form.get("station_token") or "").strip()
if token:
err = validate_token(token)
if err:
errors.append(err)
else:
updates["PRINTER_STATION_TOKEN"] = token
return ssid, password, updates, errors, warnings
# ---------------------------------------------------------------------------
# comitup D-Bus client (verified against comitup/statemgr.py)
# ---------------------------------------------------------------------------
_dbus_proxy = None
_dbus_lock = threading.Lock()
def _comitup_proxy():
global _dbus_proxy
with _dbus_lock:
if _dbus_proxy is None:
import dbus # lazy: unit tests never need python3-dbus
bus = dbus.SystemBus()
_dbus_proxy = bus.get_object(DBUS_NAME, DBUS_PATH)
return _dbus_proxy
def comitup_access_points() -> list[dict]:
"""access_points() -> aa{ss}: dicts with ssid, strength (0-100 %), security."""
raw = _comitup_proxy().access_points(dbus_interface=DBUS_NAME)
return [
{
"ssid": str(ap.get("ssid", "")),
"strength": str(ap.get("strength", "")),
"security": str(ap.get("security", "")),
}
for ap in raw
]
def comitup_state() -> tuple[str, str]:
"""state() -> ss: (HOTSPOT|CONNECTING|CONNECTED, connection)."""
state, connection = _comitup_proxy().state(dbus_interface=DBUS_NAME)
return str(state), str(connection)
def comitup_connect(ssid: str, password: str) -> None:
"""connect(ss, ss): activate/create a NM profile for the SSID and drop the AP."""
_comitup_proxy().connect(ssid, password, dbus_interface=DBUS_NAME)
def list_networks() -> list[dict]:
if DRY_RUN:
return sort_aps(list(FAKE_NETWORKS))
return sort_aps(comitup_access_points())
# ---------------------------------------------------------------------------
# HTML rendering (inline CSS only — no internet in hotspot mode)
# ---------------------------------------------------------------------------
BASE_CSS = """
*{box-sizing:border-box}
body{margin:0;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;
background:#f2f4f7;color:#1c1e21}
.wrap{max-width:480px;margin:0 auto;padding:20px 16px 40px}
header{display:flex;align-items:center;gap:10px;margin-bottom:16px}
header .dot{width:12px;height:12px;border-radius:50%;background:#e8590c}
header h1{font-size:19px;margin:0;font-weight:700}
header p{margin:0;font-size:12.5px;color:#6b7280}
.card{background:#fff;border-radius:14px;padding:16px;margin-bottom:14px;
box-shadow:0 1px 3px rgba(0,0,0,.08)}
h2{font-size:13px;margin:0 0 12px;text-transform:uppercase;letter-spacing:.04em;color:#6b7280}
label{display:block;font-size:13.5px;font-weight:600;margin:12px 0 4px}
input,select{width:100%;padding:12px;font-size:16px;border:1px solid #d1d5db;
border-radius:10px;background:#fff}
input[type=checkbox]{width:auto}
.row{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:14px}
.row label{margin:0;font-weight:500}
button{width:100%;margin-top:18px;padding:14px;font-size:16px;font-weight:700;color:#fff;
background:#0b57d0;border:0;border-radius:12px}
button:active{transform:scale(.99)}
.note{font-size:12.5px;color:#6b7280;margin:6px 0 0}
.err{background:#fdecea;border:1px solid #f5c2c0;color:#8a1f11;border-radius:10px;
padding:10px 12px;font-size:14px;margin-bottom:12px}
.err ul{margin:0;padding-left:18px}
.warn{background:#fff8e1;border:1px solid #ffe08a;color:#7a5b00;border-radius:10px;
padding:10px 12px;font-size:13.5px;margin-bottom:12px}
.warn ul{margin:0;padding-left:18px}
.current{font-size:13.5px;color:#374151;margin:0 0 6px;word-break:break-all}
details summary{cursor:pointer;font-size:13px;text-transform:uppercase;
letter-spacing:.04em;color:#6b7280;font-weight:700}
details[open] summary{margin-bottom:10px}
.ok{background:#e6f4ea;border:1px solid #b7dfc0;color:#1e4620;border-radius:10px;
padding:10px 12px;font-size:14px;margin-bottom:12px}
.spin{width:34px;height:34px;margin:0 auto 14px;border:4px solid #d1d5db;
border-top-color:#0b57d0;border-radius:50%;animation:s 1s linear infinite}
@keyframes s{to{transform:rotate(360deg)}}
.center{text-align:center}
"""
HIDDEN_JS = """
var cb=document.getElementById('hidden-cb'),sel=document.getElementById('ssid'),
hid=document.getElementById('hidden-ssid');
function sync(){sel.disabled=cb.checked;hid.style.display=cb.checked?'block':'none';
if(cb.checked)hid.focus();}
cb.addEventListener('change',sync);sync();
"""
def _e(value: object) -> str:
return html.escape(str(value), quote=True)
def _network_options(aps: list[dict]) -> str:
options = ['<option value="" disabled selected>Choose a network…</option>']
for ap in aps:
enc = "encrypted" if ap.get("security") == "encrypted" else "open"
options.append(
f'<option value="{_e(ap["ssid"])}">{_e(ap["ssid"])} — {enc}, '
f'signal {_e(ap.get("strength", "?"))}%</option>'
)
return "\n".join(options)
def render_page(title: str, body: str) -> bytes:
doc = (
"<!doctype html><html lang=en><head>"
"<meta charset=utf-8>"
"<meta name=viewport content='width=device-width,initial-scale=1'>"
f"<title>{_e(title)}</title><style>{BASE_CSS}</style></head>"
f"<body><div class=wrap><header><span class=dot></span><div>"
"<h1>Convivo Printer</h1><p>Wi-Fi setup · 10.41.0.1</p></div></header>"
f"{body}</div></body></html>"
)
return doc.encode("utf-8")
def render_form(aps: list[dict], current: dict, errors: list[str],
warnings: list[str], csrf: str) -> bytes:
parts: list[str] = []
if errors:
parts.append('<div class=err><ul>' + "".join(f"<li>{_e(e)}</li>" for e in errors) + "</ul></div>")
if warnings:
parts.append('<div class=warn><ul>' + "".join(f"<li>{_e(w)}</li>" for w in warnings) + "</ul></div>")
if not aps:
parts.append('<div class=warn>No networks found right now — use “hidden network”, '
"or press refresh after a moment.</div>")
url = current.get("CONVIVO_URL", "")
station = current.get("STATION_NAME", "")
token_mask = mask_token(current.get("PRINTER_STATION_TOKEN", ""))
_, url_warn = validate_url(url) if url else (None, None)
parts.append(
"<form method=POST action=/connect>"
f"<input type=hidden name=csrf value=\"{_e(csrf)}\">"
'<div class=card><h2>1 · Wi-Fi network</h2>'
f'<label for=ssid>Network</label><select id=ssid name=ssid>{_network_options(aps)}</select>'
'<div class=row><input type=checkbox id=hidden-cb name=hidden value=1>'
"<label for=hidden-cb>My network is hidden</label></div>"
'<input id=hidden-ssid name=hidden_ssid type=text maxlength=32 style=display:none '
'placeholder="Hidden network name (SSID)" autocomplete=off>'
'<label for=password>Password</label>'
'<input id=password name=password type=password maxlength=128 autocomplete=off '
'placeholder="Leave empty for an open network">'
'<p class=note>The printer keeps any network it already knows and always '
"prefers internet access.</p>"
"</div>"
'<div class=card><h2>2 · Convivo connection (optional)</h2>'
f'<p class=current>Current URL: <strong>{_e(url) or "—"}</strong></p>'
f'<p class=current>Station name: <strong>{_e(station) or "—"}</strong></p>'
f'<p class=current>Station token: <strong>{_e(token_mask) or "not set"}</strong></p>'
+ (f'<div class=warn><ul><li>{_e(url_warn)}</li></ul></div>' if url_warn else "")
+ '<label for=convivo_url>Convivo URL</label>'
'<input id=convivo_url name=convivo_url type=url inputmode=url autocomplete=off '
'placeholder="https://admin.appe.at — empty keeps current">'
'<label for=anon_key>Anon key</label>'
'<input id=anon_key name=anon_key type=text autocomplete=off '
'placeholder="eyJ… JWT — empty keeps current">'
'<label for=station_token>Station token</label>'
'<input id=station_token name=station_token type=password autocomplete=off '
'placeholder="cvp_… — empty keeps current">'
'<p class=note>Blank fields keep the current values; tokens are never shown in full.</p>'
"</div>"
"<button type=submit>Connect</button>"
"</form>"
"<p class=center><a href=/networks.json class=note>Refresh network list</a></p>"
f"<script>{HIDDEN_JS}</script>"
)
return render_page("Convivo Printer — Wi-Fi setup", "".join(parts))
def render_switching(ssid: str, applied: list[str]) -> bytes:
applied_text = (
" · ".join(_e(k) for k in applied) if applied else "no changes — current settings kept"
)
body = (
'<div class="card center">'
'<div class=spin id=spin></div>'
"<h2 style=text-transform:none>Switching networks…</h2>"
f"<p>The printer is leaving this hotspot and joining <strong>{_e(ssid)}</strong>.</p>"
f'<p class=note>Convivo settings: {applied_text}</p>'
'<p class=note>This page will update when the Pi leaves the hotspot.</p>'
"</div>"
'<div class=card id=done style=display:none><div class=ok><strong>Network applied.</strong></div>'
"<p class=note>The open <em>Convivo-Printer</em> hotspot is gone — reconnect your phone "
"to your own Wi-Fi.</p></div>"
'<div class=card><p class=note>In the Convivo admin console the printer pill turns '
"<strong>green</strong> as soon as the station is online. If it stays grey for more "
"than a minute, the Wi-Fi credentials or the Convivo URL/token may be wrong — power "
"the printer off and on again to get the hotspot back.</p></div>"
"<script>var done=false;function poll(){fetch('/status').then(function(r){return r.json()})"
".then(function(j){if(!done&&j.state!=='HOTSPOT'){done=true;"
"document.getElementById('spin').style.display='none';"
"document.getElementById('done').style.display='block';}}).catch(function(){});}"
"setInterval(poll,2000);poll();</script>"
'<meta http-equiv="refresh" content="6">'
)
return render_page("Switching networks…", body)
# ---------------------------------------------------------------------------
# HTTP server
# ---------------------------------------------------------------------------
class PortalHandler(BaseHTTPRequestHandler):
server_version = "ConvivoPortal/1.0"
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args): # keep stdout quiet on the Pi
pass
# -- helpers ------------------------------------------------------------
def _cookies(self) -> SimpleCookie:
cookie = SimpleCookie()
raw = self.headers.get("Cookie")
if raw:
cookie.load(raw)
return cookie
def _respond(self, code: int, body: bytes, content_type: str,
extra_headers: list[tuple[str, str]] | None = None) -> None:
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
for key, value in extra_headers or []:
self.send_header(key, value)
self.end_headers()
self.wfile.write(body)
def _redirect_to_portal(self) -> None:
# Captive-portal probes (captive.apple.com, connectivity-check, …) land here.
self._respond(302, b"", "text/plain; charset=utf-8",
[("Location", f"http://{AP_ADDR}/")])
# -- routes -------------------------------------------------------------
def do_GET(self) -> None: # noqa: N802
path = urllib.parse.urlsplit(self.path).path
if path == "/":
try:
aps = list_networks()
except Exception:
aps = []
try:
with open(ENV_FILE, encoding="utf-8") as fh:
current = parse_env(fh.read())
except OSError:
current = {}
csrf = secrets.token_hex(16)
body = render_form(aps, current, [], [], csrf)
self._respond(200, body, "text/html; charset=utf-8",
[("Set-Cookie", f"portal_csrf={csrf}; Path=/; Max-Age=3600")])
elif path == "/networks.json":
try:
aps = list_networks()
except Exception as exc:
self._respond(503, json.dumps({"error": str(exc)}).encode(),
"application/json")
return
self._respond(200, json.dumps({"networks": aps}).encode(), "application/json")
elif path == "/status":
try:
state, connection = ("HOTSPOT", "") if DRY_RUN else comitup_state()
except Exception:
state, connection = "UNKNOWN", ""
self._respond(200, json.dumps({"state": state, "connection": connection}).encode(),
"application/json")
else:
self._redirect_to_portal()
def do_POST(self) -> None: # noqa: N802
path = urllib.parse.urlsplit(self.path).path
if path != "/connect":
self.close_connection = True # the body is not read
self._respond(405, b"", "text/plain; charset=utf-8")
return
try:
length = int(self.headers.get("Content-Length") or 0)
except ValueError:
length = -1
if length < 0 or length > MAX_BODY_BYTES:
# The unread body would corrupt a kept-alive connection.
self.close_connection = True
self._respond(431, b"", "text/plain; charset=utf-8")
return
body = self.rfile.read(length).decode("utf-8", "replace")
form = {k: v for k, v in urllib.parse.parse_qsl(body, keep_blank_values=True)}
cookie = self._cookies().get("portal_csrf")
expected = cookie.value if cookie else ""
def show_form(errors: list[str], warnings: list[str]) -> None:
try:
aps = list_networks()
except Exception:
aps = []
try:
with open(ENV_FILE, encoding="utf-8") as fh:
current = parse_env(fh.read())
except OSError:
current = {}
csrf = secrets.token_hex(16)
body_bytes = render_form(aps, current, errors, warnings, csrf)
self._respond(400, body_bytes, "text/html; charset=utf-8",
[("Set-Cookie", f"portal_csrf={csrf}; Path=/; Max-Age=3600")])
if not expected or not secrets.compare_digest(form.get("csrf", ""), expected):
show_form(["The form expired — please try again."], [])
return
ssid, password, updates, errors, warnings = parse_connect(form)
if errors:
show_form(errors, warnings)
return
if updates:
try:
with open(ENV_FILE, encoding="utf-8") as fh:
old = fh.read()
except OSError:
old = ""
try:
write_env(ENV_FILE, update_env(old, updates))
except ValueError as exc:
show_form([str(exc)], warnings)
return
if ssid:
if DRY_RUN:
sys.stderr.write(f"[dry-run] would comitup connect to {ssid!r}\n")
else:
worker = threading.Thread(
target=self._connect_worker, args=(ssid, password, bool(updates)),
daemon=True,
)
worker.start()
body_bytes = render_switching(ssid or "(no network change)", sorted(updates))
self._respond(200, body_bytes, "text/html; charset=utf-8")
def _connect_worker(self, ssid: str, password: str, env_changed: bool) -> None:
# Let the HTTP response flush before the AP disappears / docker bounces.
time.sleep(1.0)
if env_changed:
try:
subprocess.run(
["docker", "compose", "-f", COMPOSE_FILE, "up", "-d", "--force-recreate"],
check=False, timeout=180,
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT,
)
except Exception as exc:
sys.stderr.write(f"portal: docker compose failed: {exc}\n")
time.sleep(0.5)
try:
comitup_connect(ssid, password)
except Exception as exc:
sys.stderr.write(f"portal: comitup connect failed: {exc}\n")
def main() -> None:
server = ThreadingHTTPServer(("0.0.0.0", PORT), PortalHandler)
sys.stderr.write(f"convivo portal listening on :{PORT} (env={ENV_FILE}, dry_run={DRY_RUN})\n")
try:
server.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
pytest==9.1.1
+4
View File
@@ -0,0 +1,4 @@
brother_ql_next==0.12.0
pillow==13.0.0
httpx==0.28.1
playwright==1.55.0
+110
View File
@@ -0,0 +1,110 @@
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import pytest # noqa: E402
from PIL import Image # noqa: E402
from worker.config import Config # noqa: E402
@pytest.fixture
def cfg() -> Config:
return Config(
convivo_url="http://localhost:54321",
convivo_anon_key="anon-key",
station_token="cvp_test_token",
station_name="Test desk",
dry_run=True,
status_labels=True,
wait_seconds=0,
network_state_file="/nonexistent/network.json",
app_version="test",
)
class FakePrinter:
def __init__(self, ready=True, label_id="103x164", errors=None):
self.ready = ready
self.label_id = label_id
self.errors = errors or []
self.printed: list[tuple[Image.Image, str]] = []
self.print_result = {"did_print": True, "outcome": "printed"}
def get_status(self):
return {
"connected": True,
"model": "QL-1100NWB",
"ready": self.ready and not self.errors,
"media_type": "die-cut",
"label_id": self.label_id,
"media_width_mm": 104,
"media_length_mm": 164,
"errors": list(self.errors),
}
def print_image(self, img, label_id):
self.printed.append((img, label_id))
return dict(self.print_result)
class FakeRenderer:
def __init__(self, image=None, error=None):
self.image = image or Image.new("RGB", (1181, 827), "white")
self.error = error
self.calls: list[tuple[dict, str]] = []
self.closed = False
def render(self, payload, checkin_origin):
self.calls.append((payload, checkin_origin))
if self.error:
raise self.error
return self.image
def close(self):
self.closed = True
class FakeRpc:
def __init__(self, claim_rows=None, claim_error=None, complete_error=None, heartbeat_name="Test desk"):
self.claim_rows = list(claim_rows or [])
self.claim_error = claim_error
self.complete_error = complete_error
self.heartbeat_name = heartbeat_name
self.claims = 0
self.completed: list[int] = []
self.failed: list[tuple[int, str, bool]] = []
self.heartbeats: list[dict] = []
self.heartbeat_error = None
def claim(self, wait_seconds):
self.claims += 1
if self.claim_error:
err, self.claim_error = self.claim_error, None
raise err
return list(self.claim_rows)
def complete(self, msg_id):
if self.complete_error:
err, self.complete_error = self.complete_error, None
raise err
self.completed.append(msg_id)
return True
def fail(self, msg_id, error, retryable=False):
self.failed.append((msg_id, error, retryable))
return "retry" if retryable else "dead_letter"
def heartbeat(self, status):
if self.heartbeat_error:
raise self.heartbeat_error
self.heartbeats.append(status)
return {"station_id": "x", "name": self.heartbeat_name}
def close(self):
pass
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import pytest
from PIL import Image
from worker.label import LayoutTooLarge, compose, find_label
DIE_CUT = find_label("103x164")
ENDLESS = find_label("103")
def mm(px: int) -> float:
return px * 25.4 / 300
def badge_mm(w_mm: float, h_mm: float) -> Image.Image:
return Image.new("RGB", (round(w_mm * 300 / 25.4), round(h_mm * 300 / 25.4)), "red")
def test_label_specs():
assert (DIE_CUT.width_px, DIE_CUT.height_px, DIE_CUT.die_cut) == (1200, 1822, True)
assert (ENDLESS.width_px, ENDLESS.height_px, ENDLESS.die_cut) == (1200, 0, False)
with pytest.raises(KeyError):
find_label("nope")
def test_die_cut_centers_badge():
badge = badge_mm(100, 70)
assert (badge.width, badge.height) == (1181, 827)
out = compose(badge, DIE_CUT)
assert out.size == (1200, 1822)
assert out.getpixel((9, 497)) == (255, 0, 0)
assert out.getpixel((0, 0)) == (255, 255, 255)
assert out.getpixel((1199, 1821)) == (255, 255, 255)
def test_endless_uses_badge_height():
out = compose(badge_mm(100, 70), ENDLESS)
assert out.size == (1200, 827)
assert out.getpixel((9, 0)) == (255, 0, 0)
assert out.getpixel((0, 0)) == (255, 255, 255)
def test_rotated_when_it_only_fits_rotated():
badge = badge_mm(150, 90)
assert badge.width > DIE_CUT.width_px
out = compose(badge, DIE_CUT)
assert out.size == (1200, 1822)
# Rotated 1063x1772 content is centered: margins 68/25 px.
assert out.getpixel((600, 25)) == (255, 0, 0)
assert out.getpixel((600, 0)) == (255, 255, 255)
def test_too_large_raises():
with pytest.raises(LayoutTooLarge) as err:
compose(badge_mm(120, 200), DIE_CUT)
message = str(err.value)
assert "120x200 mm" in message and "103x164" in message
def test_overshoot_is_cropped():
out = compose(Image.new("RGB", (1203, 1822), "red"), DIE_CUT)
assert out.size == (1200, 1822)
def test_grayscale_input_converted():
out = compose(Image.new("L", (1181, 827), 0), DIE_CUT)
assert out.mode == "RGB"
def test_compose_accepts_identifier_string():
out = compose(badge_mm(100, 70), "103")
assert mm(out.width) == pytest.approx(101.6, abs=0.1)
assert out.height == 827
+312
View File
@@ -0,0 +1,312 @@
from __future__ import annotations
import json
import pytest
from PIL import Image
from conftest import FakePrinter, FakeRenderer, FakeRpc
from worker.label import LayoutTooLarge
from worker.main import Worker
from worker.render import RenderError
from worker.rpc import InvalidToken, RpcUnavailable
PAYLOAD = {"schema": "convivo.badge-print/v1", "kind": "checkin", "sample": {}, "layout": {}}
ROW = {"msg_id": 42, "read_ct": 1, "payload": PAYLOAD}
def make(cfg, rpc=None, printer=None, renderer=None, sleeps=None):
if sleeps is None:
sleeps = []
return Worker(
cfg,
rpc or FakeRpc(),
printer or FakePrinter(),
renderer or FakeRenderer(),
sleep=sleeps.append,
)
def test_success_completes(cfg):
rpc, printer, renderer = FakeRpc([ROW]), FakePrinter(), FakeRenderer()
make(cfg, rpc, printer, renderer).handle_job(ROW)
assert rpc.completed == [42] and not rpc.failed
assert len(printer.printed) == 1
assert printer.printed[0][0].size == (1200, 1822)
assert renderer.calls[0][1] == cfg.checkin_origin
def test_not_printed_fails_non_retryable(cfg):
rpc, printer = FakeRpc(), FakePrinter()
printer.print_result = {"did_print": False, "outcome": "error"}
make(cfg, rpc, printer, FakeRenderer()).handle_job(ROW)
assert rpc.failed == [(42, "printer: error", False)] and not rpc.completed
def test_error_after_successful_print_still_completes(cfg):
rpc, printer = FakeRpc(), FakePrinter()
printer.errors = ["Tape end"]
make(cfg, rpc, printer, FakeRenderer()).handle_job(ROW)
assert rpc.completed == [42] and not rpc.failed
def test_printer_state_errors_explain_failed_print(cfg):
rpc, printer = FakeRpc(), FakePrinter()
printer.print_result = {"did_print": False, "outcome": "error", "printer_state": {"errors": ["Cover open while printing"]}}
make(cfg, rpc, printer, FakeRenderer()).handle_job(ROW)
assert rpc.failed == [(42, "printer: Cover open while printing", False)]
def test_layout_too_large_fails_non_retryable(cfg):
rpc, renderer = FakeRpc(), FakeRenderer(image=Image.new("RGB", (1417, 2362), "red"))
make(cfg, rpc, FakePrinter(), renderer).handle_job(ROW)
assert rpc.failed and rpc.failed[0][0] == 42 and rpc.failed[0][2] is False
assert "does not fit label 103x164" in rpc.failed[0][1]
def test_render_error_fails_non_retryable(cfg):
rpc = FakeRpc()
make(cfg, rpc, FakePrinter(), FakeRenderer(error=RenderError("image failed to load"))).handle_job(ROW)
assert rpc.failed == [(42, "render: image failed to load", False)]
def test_bad_schema_fails_without_rendering(cfg):
rpc, renderer = FakeRpc(), FakeRenderer()
row = {"msg_id": 7, "read_ct": 1, "payload": {"schema": "other/v2"}}
make(cfg, rpc, FakePrinter(), renderer).handle_job(row)
assert rpc.failed == [(7, "unsupported payload schema: other/v2", False)]
assert renderer.calls == []
def test_unexpected_error_fails_retryable(cfg):
class Boom(FakeRenderer):
def render(self, payload, checkin_origin):
raise RuntimeError("kaboom")
rpc = FakeRpc()
make(cfg, rpc, FakePrinter(), Boom()).handle_job(ROW)
assert rpc.failed == [(42, "worker: RuntimeError: kaboom", True)]
def test_no_label_id_fails_retryable(cfg):
rpc = FakeRpc()
make(cfg, rpc, FakePrinter(label_id=None), FakeRenderer()).handle_job(ROW)
assert rpc.failed == [(42, "printer: no label detected", True)]
def test_complete_unavailable_retries_then_succeeds(cfg):
rpc = FakeRpc(complete_error=RpcUnavailable("claim: ConnectError"))
sleeps: list[float] = []
make(cfg, rpc, FakePrinter(), FakeRenderer(), sleeps).handle_job(ROW)
assert rpc.completed == [42]
assert sleeps and sleeps[0] == 2.0
def test_complete_gives_up_after_limit(cfg):
class AlwaysDown(FakeRpc):
def complete(self, msg_id):
raise RpcUnavailable("down")
sleeps: list[float] = []
make(cfg, AlwaysDown(), FakePrinter(), FakeRenderer(), sleeps).handle_job(ROW)
assert sum(sleeps) <= 60 + 32
assert not sleeps or sum(sleeps[:-1]) <= 60
def test_tick_skips_claim_when_not_ready(cfg):
rpc, printer = FakeRpc([ROW]), FakePrinter(ready=False, errors=["Tape end"])
worker = make(cfg, rpc, printer, FakeRenderer(), [])
worker.tick()
assert rpc.claims == 0
assert worker.worker == "paused"
assert worker.last_error == "Tape end"
def test_tick_claims_and_processes_when_ready(cfg):
rpc = FakeRpc([ROW])
worker = make(cfg, rpc, FakePrinter(), FakeRenderer(), [])
worker.tick()
assert rpc.claims == 1 and rpc.completed == [42]
assert worker.worker == "idle"
def test_tick_claim_invalid_token_keeps_running(cfg):
rpc = FakeRpc(claim_error=InvalidToken("bad"))
worker = make(cfg, rpc, FakePrinter(), FakeRenderer(), [])
worker.tick() # must not raise
assert worker.worker == "idle"
def test_heartbeat_body_shape(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
cfg.network_state_file = str(net)
rpc = FakeRpc()
worker = make(cfg, rpc, FakePrinter(), FakeRenderer())
worker.beat()
body = rpc.heartbeats[0]
assert body["version"] == "test"
assert body["station_name"] == "Test desk"
assert body["worker"] == "starting"
assert body["job_msg_id"] is None
assert body["printer"]["ready"] is True
assert body["network"]["ssid"] == "office"
assert body["label"] == "103x164"
assert body["last_error"] is None
assert isinstance(body["uptime_s"], int)
assert (tmp_path / "heartbeat-ok").exists()
def test_heartbeat_invalid_token_does_not_raise(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
rpc = FakeRpc()
rpc.heartbeat_error = InvalidToken("nope")
worker = make(cfg, rpc, FakePrinter(), FakeRenderer())
worker.beat() # must not raise
assert rpc.heartbeats == []
assert not (tmp_path / "heartbeat-ok").exists()
def test_need_wifi_printed_once_per_hotspot_episode(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
rpc, printer = FakeRpc(), FakePrinter()
worker = make(cfg, rpc, printer, FakeRenderer(), [])
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "Convivo-Printer-0042"}))
worker.beat()
worker.tick()
worker.tick()
assert len(printer.printed) == 1 # once per episode, not per tick
assert rpc.claims == 2 # both ticks keep claiming after the info label
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.5"}))
worker.beat()
worker.tick()
assert len(printer.printed) == 2 # ready label on the new network, no second need-wifi
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "Convivo-Printer-0042"}))
worker.beat()
worker.tick()
assert len(printer.printed) == 3 # a new hotspot episode prints again
def test_need_wifi_skipped_when_printer_not_ready(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "ap"}))
rpc, printer = FakeRpc(), FakePrinter(ready=False, errors=["Tape end"])
worker = make(cfg, rpc, printer, FakeRenderer(), [])
worker.beat()
worker.tick()
assert printer.printed == []
assert worker._need_wifi_pending # still queued for when the printer recovers
def test_ready_label_once_per_network_key(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
rpc, printer = FakeRpc(), FakePrinter()
worker = make(cfg, rpc, printer, FakeRenderer(), [])
worker.beat()
worker.tick()
assert len(printer.printed) == 1 # ready label after first heartbeat
worker.tick()
worker.tick()
assert len(printer.printed) == 1 # not repeated for the same (ssid, ip)
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "other", "ip": "10.0.1.2"}))
worker.beat()
worker.tick()
assert len(printer.printed) == 2 # new network key → new ready label
def test_status_labels_off_print_nothing(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
cfg.status_labels = False
rpc, printer = FakeRpc(), FakePrinter()
worker = make(cfg, rpc, printer, FakeRenderer(), [])
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
worker.beat()
worker.tick()
net.write_text(json.dumps({"state": "HOTSPOT", "ssid": "Convivo-Printer-1", "ip": "10.41.0.1"}))
worker.beat()
worker.tick()
assert printer.printed == []
def test_failing_info_label_does_not_block_jobs(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
def broken_label(*_args):
raise TypeError("boom")
monkeypatch.setattr("worker.main.ready_label", broken_label)
rpc, printer = FakeRpc([ROW]), FakePrinter()
worker = make(cfg, rpc, printer, FakeRenderer(), [])
worker.beat()
worker.tick()
assert rpc.completed == [42]
def test_heartbeat_name_overrides_env_station_name(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
rpc, printer = FakeRpc(heartbeat_name="Front desk 2"), FakePrinter()
worker = make(cfg, rpc, printer, FakeRenderer(), [])
assert worker.station_name == "Test desk" # env fallback before any heartbeat
worker.beat()
assert worker.station_name == "Front desk 2"
worker.beat()
assert rpc.heartbeats[1]["station_name"] == "Front desk 2"
import worker.main as worker_main
real_ready_label = worker_main.ready_label
labels: list[str] = []
def spy_ready_label(spec, station, network, version, now):
labels.append(station)
return real_ready_label(spec, station, network, version, now)
monkeypatch.setattr(worker_main, "ready_label", spy_ready_label)
worker.tick()
assert len(printer.printed) == 1 # ready label printed with the server name
assert labels == ["Front desk 2"]
def test_blank_heartbeat_name_keeps_previous(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
rpc = FakeRpc(heartbeat_name=" ")
worker = make(cfg, rpc, FakePrinter(), FakeRenderer())
worker.beat()
assert worker.station_name == "Test desk"
def test_ready_label_only_after_successful_heartbeat(cfg, monkeypatch, tmp_path):
monkeypatch.setattr("worker.main.HEARTBEAT_TOUCH", str(tmp_path / "heartbeat-ok"))
net = tmp_path / "network.json"
cfg.network_state_file = str(net)
net.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9"}))
rpc, printer = FakeRpc(), FakePrinter()
rpc.heartbeat_error = RpcUnavailable("down")
worker = make(cfg, rpc, printer, FakeRenderer(), [])
worker.beat()
worker.tick()
assert printer.printed == [] # no heartbeat yet → no ready label
rpc.heartbeat_error = None
worker.beat()
worker.tick()
assert len(printer.printed) == 1
+36
View File
@@ -0,0 +1,36 @@
from __future__ import annotations
import json
from worker.network import read_network
def test_missing_file_falls_back(tmp_path):
result = read_network(str(tmp_path / "absent.json"))
assert result["state"] == "UNKNOWN"
assert result["ssid"] is None
assert "ip" in result
def test_reads_state(tmp_path):
path = tmp_path / "network.json"
path.write_text(json.dumps({"state": "CONNECTED", "ssid": "office", "ip": "10.0.0.9", "updated_at": "x"}))
result = read_network(str(path))
assert result["state"] == "CONNECTED"
assert result["ssid"] == "office"
assert result["ip"] == "10.0.0.9"
def test_corrupt_file_falls_back(tmp_path):
path = tmp_path / "network.json"
path.write_text("{not json")
assert read_network(str(path))["state"] == "UNKNOWN"
def test_empty_strings_become_none(tmp_path):
path = tmp_path / "network.json"
path.write_text(json.dumps({"state": "HOTSPOT", "ssid": "", "ip": ""}))
result = read_network(str(path))
assert result["state"] == "HOTSPOT"
assert result["ssid"] is None
assert result["ip"] is None
+263
View File
@@ -0,0 +1,263 @@
from __future__ import annotations
import json
import threading
import urllib.error
import urllib.parse
import urllib.request
from http.server import ThreadingHTTPServer
import pytest
from portal import portal
JWT = "eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiYW5vbiJ9.sig-__"
TOKEN = "cvp_" + "a" * 64
# ---- pure helpers ----------------------------------------------------------
def test_parse_env_basic():
parsed = portal.parse_env("# comment\n\nA=1\nB = two words \nBAD\n")
assert parsed == {"A": "1", "B": "two words"}
def test_update_env_replaces_in_place_preserves_others_appends_missing():
old = (
"# header\n"
"CONVIVO_URL=https://old.example\n"
"STATION_NAME=Desk\n"
"PRINTER_IDENTIFIER=usb://0x04f9:0x20a8\n"
)
new = portal.update_env(old, {"CONVIVO_URL": "https://new.example", "CONVIVO_ANON_KEY": JWT})
lines = new.splitlines()
assert lines[0] == "# header"
assert lines[1] == "CONVIVO_URL=https://new.example"
assert "STATION_NAME=Desk" in lines
assert "PRINTER_IDENTIFIER=usb://0x04f9:0x20a8" in lines
assert lines[-1] == f"CONVIVO_ANON_KEY={JWT}"
assert new.endswith("\n")
def test_update_env_rejects_non_whitelisted_key():
with pytest.raises(ValueError):
portal.update_env("", {"PATH": "/evil"})
def test_update_env_rejects_injection_in_values():
with pytest.raises(ValueError):
portal.update_env("", {"CONVIVO_URL": "https://x\nEVIL=1"})
with pytest.raises(ValueError):
portal.update_env("", {"CONVIVO_ANON_KEY": "a=b"})
def test_write_env_atomic_and_mode(tmp_path):
path = tmp_path / ".env"
portal.write_env(str(path), "CONVIVO_URL=https://x\n")
assert path.read_text() == "CONVIVO_URL=https://x\n"
assert path.stat().st_mode & 0o777 == 0o600
assert not (tmp_path / ".env.tmp").exists()
def test_mask_token():
assert portal.mask_token(TOKEN) == "cvp_…" + TOKEN[-4:]
assert portal.mask_token("") == ""
assert portal.mask_token("cvp_sh") == "cvp_…"
assert "a" * 64 not in portal.mask_token(TOKEN)
def test_validate_url():
assert portal.validate_url("https://admin.appe.at")[0] is None
assert portal.validate_url("https://x")[0] is None
assert portal.validate_url("http://192.168.178.4:54321")[1] is not None
assert portal.validate_url("http://192.168.178.4:54321")[0] is None
assert portal.validate_url("http://localhost:54321")[0] is None
assert portal.validate_url("http://127.0.0.1:8000")[0] is None
assert portal.validate_url("http://printer.local")[0] is None
assert portal.validate_url("http://10.0.0.5")[0] is None
assert portal.validate_url("http://172.20.0.1")[0] is None
assert portal.validate_url("http://evil.example")[0] is not None
assert portal.validate_url("http://8.8.8.8")[0] is not None
assert portal.validate_url("ftp://host")[0] is not None
assert portal.validate_url("https://")[0] is not None
assert portal.validate_url("not a url")[0] is not None
def test_validate_anon_key():
assert portal.validate_anon_key(JWT) is None
assert portal.validate_anon_key("a.b") is not None
assert portal.validate_anon_key("a.b.c.d") is not None
assert portal.validate_anon_key("a.b.!bad") is not None
assert portal.validate_anon_key("a..c") is not None
def test_validate_token():
assert portal.validate_token(TOKEN) is None
assert portal.validate_token("x" * 68) is not None
assert portal.validate_token("cvp_short") is not None
assert portal.validate_token(TOKEN[:-1]) is not None
def test_sort_aps_by_strength_desc_and_bad_values():
aps = [
{"ssid": "a", "strength": "20"},
{"ssid": "b", "strength": "bad"},
{"ssid": "c", "strength": "90"},
]
assert [ap["ssid"] for ap in portal.sort_aps(aps)] == ["c", "a", "b"]
def test_parse_connect_ok_with_warning():
form = {
"ssid": "Office",
"password": "secret",
"convivo_url": "http://192.168.1.5:54321",
"anon_key": JWT,
"station_token": TOKEN,
}
ssid, password, updates, errors, warnings = portal.parse_connect(form)
assert (ssid, password) == ("Office", "secret")
assert updates == {
"CONVIVO_URL": "http://192.168.1.5:54321",
"CONVIVO_ANON_KEY": JWT,
"PRINTER_STATION_TOKEN": TOKEN,
}
assert errors == []
assert warnings
def test_parse_connect_hidden_network():
form = {"hidden": "1", "hidden_ssid": "SecretNet", "password": "pw"}
ssid, password, updates, errors, warnings = portal.parse_connect(form)
assert (ssid, password) == ("SecretNet", "pw")
assert updates == {} and errors == [] and warnings == []
def test_parse_connect_errors():
_, _, updates, errors, _ = portal.parse_connect({})
assert errors and not updates
_, _, updates, errors, _ = portal.parse_connect(
{"ssid": "x" * 40, "convivo_url": "http://evil.example", "station_token": "nope"}
)
assert len(errors) == 3 and not updates
# ---- HTTP server (dry-run, fake env file) ----------------------------------
@pytest.fixture
def portal_server(tmp_path, monkeypatch):
env = tmp_path / ".env"
env.write_text(
"CONVIVO_URL=https://old.example\n"
"CONVIVO_ANON_KEY=old.anon.key\n"
"PRINTER_STATION_TOKEN=cvp_" + "b" * 64 + "\n"
"STATION_NAME=Desk\n"
)
monkeypatch.setattr(portal, "ENV_FILE", str(env))
monkeypatch.setattr(portal, "DRY_RUN", True)
server = ThreadingHTTPServer(("127.0.0.1", 0), portal.PortalHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield f"http://127.0.0.1:{server.server_address[1]}", env
server.shutdown()
server.server_close()
def _get(url: str):
with urllib.request.urlopen(url, timeout=5) as resp:
return resp.status, resp.read().decode()
def test_get_root_lists_networks_and_masks_token(portal_server):
base, env = portal_server
status, page = _get(base + "/")
assert status == 200
assert "FakeOffice" in page and "FakeOpen" in page
assert "https://old.example" in page # current URL is shown
assert "cvp_" + "b" * 64 not in page # token only masked
assert "bbbb" in page # last four shown
def _get_with_cookie(url: str):
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=5) as resp:
page = resp.read().decode()
raw_cookie = resp.headers.get("Set-Cookie", "")
csrf_cookie = raw_cookie.split(";")[0] # portal_csrf=...
return page, csrf_cookie
def test_catchall_redirects_to_portal(portal_server):
base, _ = portal_server
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
opener = urllib.request.build_opener(NoRedirect)
for probe in ("/generate_204", "/hotspot-detect.html", "/ncsi.txt", "/connecttest.txt"):
try:
opener.open(base + probe, timeout=5)
pytest.fail(f"{probe} should not return 200")
except urllib.error.HTTPError as exc:
assert exc.code == 302, probe
assert exc.headers.get("Location") == "http://10.41.0.1/", probe
def test_networks_json_and_status(portal_server):
base, _ = portal_server
status, payload = _get(base + "/networks.json")
assert status == 200
networks = json.loads(payload)["networks"]
assert [n["ssid"] for n in networks] == ["FakeOffice", "FakeOpen"]
status, payload = _get(base + "/status")
assert status == 200 and json.loads(payload)["state"] == "HOTSPOT"
def test_post_connect_rewrites_env_without_echoing_secrets(portal_server):
base, env = portal_server
page, csrf_cookie = _get_with_cookie(base + "/")
csrf = page.split('name=csrf value="')[1].split('"')[0]
form = urllib.parse.urlencode(
{
"csrf": csrf,
"ssid": "FakeOffice",
"password": "hunter2",
"convivo_url": "https://admin.appe.at",
"anon_key": "",
"station_token": TOKEN,
}
).encode()
req = urllib.request.Request(base + "/connect", data=form,
headers={"Cookie": csrf_cookie})
with urllib.request.urlopen(req, timeout=5) as resp:
status, page = resp.status, resp.read().decode()
assert status == 200
assert "FakeOffice" in page
assert TOKEN not in page and JWT not in page
written = env.read_text()
assert "CONVIVO_URL=https://admin.appe.at" in written
assert f"PRINTER_STATION_TOKEN={TOKEN}" in written
assert "CONVIVO_ANON_KEY=old.anon.key" in written # blank field keeps current
assert "STATION_NAME=Desk" in written # untouched keys preserved
assert env.stat().st_mode & 0o777 == 0o600
def test_post_connect_rejects_bad_csrf(portal_server):
base, env = portal_server
before = env.read_text()
form = urllib.parse.urlencode({"csrf": "nope", "ssid": "FakeOffice"}).encode()
with pytest.raises(urllib.error.HTTPError) as exc:
urllib.request.urlopen(urllib.request.Request(base + "/connect", data=form), timeout=5)
assert exc.value.code == 400
assert env.read_text() == before
def test_post_connect_rejects_oversized_body(portal_server):
base, _ = portal_server
form = b"csrf=x&ssid=" + b"A" * (portal.MAX_BODY_BYTES + 1)
with pytest.raises(urllib.error.HTTPError) as exc:
urllib.request.urlopen(urllib.request.Request(base + "/connect", data=form), timeout=5)
assert exc.value.code == 431
+103
View File
@@ -0,0 +1,103 @@
from __future__ import annotations
import pytest
from PIL import Image
from worker.printer import Printer, map_status
from worker.config import Config
# Verbatim status dict reported by the real QL-1110NWB with DK-22246 loaded.
REAL_STATUS = {
"status_type": "Reply to status request",
"phase_type": "Waiting to receive",
"model_name": "QL-1100NWB",
"media_type": "Die-cut labels",
"media_width": 104,
"media_length": 164,
"identified_media": type(
"Label",
(),
{"identifier": "103x164", "dots_printable": (1200, 1822), "form_factor": 1},
)(),
"errors": [],
}
def cfg(label: str = "auto") -> Config:
return Config(
convivo_url="http://x",
convivo_anon_key="k",
station_token="t",
brother_label=label,
dry_run=True,
)
def test_maps_real_status():
st = map_status(REAL_STATUS, "auto")
assert st == {
"connected": True,
"model": "QL-1100NWB",
"ready": True,
"media_type": "die-cut",
"label_id": "103x164",
"media_width_mm": 104,
"media_length_mm": 164,
"errors": [],
}
def test_continuous_media_type():
raw = dict(REAL_STATUS, media_type="Continuous length tape")
st = map_status(raw, "auto")
assert st["media_type"] == "continuous" and st["ready"]
def test_errors_block_ready():
raw = dict(REAL_STATUS, errors=["Tape end"])
st = map_status(raw, "auto")
assert st["errors"] == ["Tape end"] and not st["ready"] and st["connected"]
def test_wrong_roll_mismatch():
st = map_status(REAL_STATUS, "103")
assert not st["ready"]
assert st["errors"] == ["wrong roll: loaded 103x164, expected 103"]
def test_matching_expected_label_ok():
assert map_status(REAL_STATUS, "103x164")["ready"]
def test_not_waiting_phase():
raw = dict(REAL_STATUS, phase_type="Printing data to receive buffer")
st = map_status(raw, "auto")
assert st["connected"] and not st["ready"]
def test_no_media():
raw = dict(REAL_STATUS, media_type="No media", identified_media=None)
st = map_status(raw, "auto")
assert st["media_type"] is None and st["label_id"] is None
assert "no media loaded" in st["errors"] and not st["ready"]
def test_unidentified_media_not_ready():
raw = dict(REAL_STATUS, identified_media=None)
st = map_status(raw, "auto")
assert not st["ready"]
def test_dry_run_status_and_print(tmp_path, monkeypatch):
monkeypatch.setattr("worker.printer.DRYRUN_DIR", tmp_path)
printer = Printer(cfg())
st = printer.get_status()
assert st["ready"] and st["label_id"] == "103x164"
result = printer.print_image(Image.new("RGB", (10, 10)), "103x164")
assert result["did_print"] is True
assert list(tmp_path.glob("dryrun-*.png"))
def test_dry_run_honours_expected_label():
st = Printer(cfg("103")).get_status()
assert st["label_id"] == "103" and st["media_type"] == "continuous"
+75
View File
@@ -0,0 +1,75 @@
from __future__ import annotations
import httpx
import pytest
from conftest import FakePrinter, FakeRenderer, FakeRpc # noqa: F401 (path setup)
from worker.config import Config
from worker.main import Worker
from worker.rpc import InvalidToken, Rpc, RpcError, RpcUnavailable
CFG = Config(convivo_url="http://x", convivo_anon_key="k", station_token="t")
def make_rpc(handler) -> Rpc:
client = httpx.Client(transport=httpx.MockTransport(handler), headers={"apikey": "k"})
return Rpc(CFG, client=client)
def test_claim_rows_and_timeout():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/rest/v1/rpc/printer_claim_badge_job"
return httpx.Response(200, json=[{"msg_id": 1, "read_ct": 1, "payload": {}}])
rows = make_rpc(handler).claim(10)
assert rows[0]["msg_id"] == 1
def test_claim_empty_returns_list():
rpc = make_rpc(lambda r: httpx.Response(200, json=[]))
assert rpc.claim(0) == []
def test_invalid_token_401():
rpc = make_rpc(lambda r: httpx.Response(401, json={"code": "28000"}))
with pytest.raises(InvalidToken):
rpc.complete(1)
def test_invalid_token_via_body_code():
rpc = make_rpc(lambda r: httpx.Response(400, json={"code": "28000", "message": "invalid printer token"}))
with pytest.raises(InvalidToken):
rpc.heartbeat({})
def test_5xx_is_unavailable():
rpc = make_rpc(lambda r: httpx.Response(503, text="nope"))
with pytest.raises(RpcUnavailable):
rpc.complete(1)
def test_connect_error_is_unavailable():
def handler(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("boom", request=request)
rpc = make_rpc(handler)
with pytest.raises(RpcUnavailable):
rpc.claim(0)
def test_other_4xx_is_rpc_error():
rpc = make_rpc(lambda r: httpx.Response(400, json={"code": "P0001", "message": "job not found"}))
with pytest.raises(RpcError):
rpc.fail(1, "x")
def test_token_never_in_repr():
cfg = Config(convivo_url="http://x", convivo_anon_key="k", station_token="cvp_secret123")
rpc = Rpc(cfg, client=httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json=[]))))
assert "cvp_secret123" not in repr(cfg)
assert "cvp_secret123" not in repr(rpc)
def test_fail_returns_outcome_string():
rpc = make_rpc(lambda r: httpx.Response(200, json="dead_letter"))
assert rpc.fail(1, "err", retryable=False) == "dead_letter"
+18
View File
@@ -0,0 +1,18 @@
from datetime import datetime
import pytest
from worker.label import find_label
from worker.status_labels import need_wifi_label, ready_label
@pytest.mark.parametrize("label_id", ["103", "103x164", "62"])
def test_status_labels_render_for_any_roll(label_id):
spec = find_label(label_id)
network = {"state": "CONNECTED", "ssid": "Venue", "ip": "10.0.0.5"}
for img in (
ready_label(spec, "Welcome desk", network, "v1", datetime(2026, 10, 18, 9, 0)),
need_wifi_label(spec, "Convivo-Printer-6372"),
):
assert img.width == spec.width_px
assert img.height > 0 and isinstance(img.height, int)
+1
View File
@@ -0,0 +1 @@
"""Convivo badge-printer worker package."""
+3
View File
@@ -0,0 +1,3 @@
from .main import main
raise SystemExit(main())
+81
View File
@@ -0,0 +1,81 @@
"""Environment-driven configuration for the badge-printer worker."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
def _int(name: str, default: int) -> int:
raw = os.environ.get(name, "").strip()
try:
return int(raw) if raw else default
except ValueError:
return default
def _flag(name: str, default: str = "0") -> bool:
return os.environ.get(name, default).strip().lower() in ("1", "true", "yes", "on")
@dataclass
class Config:
convivo_url: str
convivo_anon_key: str
station_name: str = "Welcome desk"
checkin_origin: str = "https://admin.appe.at"
brother_model: str = "QL-1110NWB"
brother_label: str = "auto"
printer_identifier: str = "usb://0x04f9:0x20a8"
dry_run: bool = False
# Ready / no-network labels cost media; the admin status pill is the default channel.
status_labels: bool = False
heartbeat_seconds: int = 10
vt_seconds: int = 120
wait_seconds: int = 2
network_state_file: str = "/run/convivo/network.json"
renderer_dir: str = "/app/renderer"
threshold: int = 70
dither: bool = False
app_version: str = "dev"
# Token kept out of repr so it can never reach a log line.
station_token: str = field(default="", repr=False)
@classmethod
def from_env(cls) -> "Config":
url = os.environ.get("CONVIVO_URL", "").strip().rstrip("/")
anon = os.environ.get("CONVIVO_ANON_KEY", "").strip()
token = os.environ.get("PRINTER_STATION_TOKEN", "").strip()
missing = [
name
for name, value in (
("CONVIVO_URL", url),
("CONVIVO_ANON_KEY", anon),
("PRINTER_STATION_TOKEN", token),
)
if not value
]
if missing:
raise RuntimeError(f"missing required env: {', '.join(missing)}")
return cls(
convivo_url=url,
convivo_anon_key=anon,
station_token=token,
station_name=os.environ.get("STATION_NAME", "Welcome desk").strip()
or "Welcome desk",
checkin_origin=os.environ.get("BADGE_CHECKIN_ORIGIN", "https://admin.appe.at")
.strip()
.rstrip("/"),
brother_model=os.environ.get("BROTHER_MODEL", "QL-1110NWB").strip(),
brother_label=os.environ.get("BROTHER_LABEL", "auto").strip() or "auto",
printer_identifier=os.environ.get("PRINTER_IDENTIFIER", "usb://0x04f9:0x20a8").strip(),
dry_run=_flag("DRY_RUN"),
status_labels=_flag("STATUS_LABELS"),
heartbeat_seconds=_int("HEARTBEAT_SECONDS", 10),
vt_seconds=_int("VT_SECONDS", 120),
wait_seconds=_int("WAIT_SECONDS", 2),
network_state_file=os.environ.get("NETWORK_STATE_FILE", "/run/convivo/network.json"),
renderer_dir=os.environ.get("RENDERER_DIR", "/app/renderer"),
threshold=_int("THRESHOLD", 70),
dither=_flag("DITHER"),
app_version=os.environ.get("APP_VERSION", "dev").strip() or "dev",
)
+90
View File
@@ -0,0 +1,90 @@
"""Fit a rendered badge image onto a printer label (pure Pillow, no hardware)."""
from __future__ import annotations
from dataclasses import dataclass
from PIL import Image
from brother_ql.labels import ALL_LABELS, FormFactor, Label
PRINT_DPI = 300
# Small rounding differences between the renderer and the label spec are cropped.
OVERSHOOT_TOLERANCE_PX = 3
class LayoutTooLarge(Exception):
"""The badge cannot be printed on the loaded label, even rotated."""
@dataclass
class LabelSpec:
identifier: str
width_px: int
height_px: int # 0 for endless/continuous labels
die_cut: bool
def find_label(identifier: str) -> LabelSpec:
for label in ALL_LABELS:
if label.identifier == identifier:
width, height = label.dots_printable
return LabelSpec(
identifier=label.identifier,
width_px=int(width),
height_px=int(height),
die_cut=label.form_factor == FormFactor.DIE_CUT,
)
raise KeyError(f"unknown label identifier: {identifier}")
def _mm(px: int) -> int:
return round(px * 25.4 / PRINT_DPI)
def _too_large(badge: Image.Image, spec: LabelSpec) -> LayoutTooLarge:
return LayoutTooLarge(
f"layout {_mm(badge.width)}x{_mm(badge.height)} mm does not fit label {spec.identifier}"
)
def _fits(w: int, h: int, spec: LabelSpec) -> bool:
if w > spec.width_px + OVERSHOOT_TOLERANCE_PX:
return False
if spec.die_cut and h > spec.height_px + OVERSHOOT_TOLERANCE_PX:
return False
return True
def _crop_to(w: int, h: int, spec: LabelSpec) -> tuple[int, int]:
return (
min(w, spec.width_px),
min(h, spec.height_px) if spec.die_cut else h,
)
def compose(badge: Image.Image, label: LabelSpec | str) -> Image.Image:
"""Return a bitmap sized for `label`, ready for brother_ql convert()."""
spec = find_label(label) if isinstance(label, str) else label
if badge.mode != "RGB":
badge = badge.convert("RGB")
if not _fits(badge.width, badge.height, spec):
rotated = badge.transpose(Image.Transpose.ROTATE_270)
if not _fits(rotated.width, rotated.height, spec):
raise _too_large(badge, spec)
badge = rotated
if spec.die_cut:
canvas = Image.new("RGB", (spec.width_px, spec.height_px), "white")
target = _crop_to(badge.width, badge.height, spec)
if (badge.width, badge.height) != target:
badge = badge.crop((0, 0, target[0], target[1]))
canvas.paste(badge, ((spec.width_px - badge.width) // 2, (spec.height_px - badge.height) // 2))
return canvas
# Endless: fixed width, length follows the badge.
target_w = min(badge.width, spec.width_px)
if badge.width != target_w:
badge = badge.crop((0, 0, target_w, badge.height))
canvas = Image.new("RGB", (spec.width_px, badge.height), "white")
canvas.paste(badge, ((spec.width_px - badge.width) // 2, 0))
return canvas
+349
View File
@@ -0,0 +1,349 @@
"""Worker loop: heartbeat beacon, informational labels and badge jobs."""
from __future__ import annotations
import logging
import signal
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Callable
from PIL import Image
from .config import Config
from .label import LayoutTooLarge, compose, find_label
from .network import read_network
from .render import RenderError, Renderer
from .rpc import InvalidToken, Rpc, RpcError, RpcUnavailable
from .status_labels import need_wifi_label, ready_label
log = logging.getLogger("worker")
SCHEMA = "convivo.badge-print/v1"
HEARTBEAT_TOUCH = "/tmp/heartbeat-ok"
COMPLETE_RETRY_LIMIT_SECONDS = 60
class Worker:
def __init__(
self,
cfg: Config,
rpc: Rpc,
printer: Any,
renderer: Any,
*,
sleep: Callable[[float], None] = time.sleep,
monotonic: Callable[[], float] = time.monotonic,
):
self.cfg = cfg
self._rpc = rpc
self._printer = printer
self._renderer = renderer
self._sleep = sleep
self._started = monotonic()
self._monotonic = monotonic
self._stop = threading.Event()
self._state_lock = threading.Lock()
self.worker = "starting"
self.job_msg_id: int | None = None
self.last_error: str | None = None
# Replaced by the server name once the first heartbeat succeeds.
self._station_name = cfg.station_name
self._printer_status: dict[str, Any] = printer.get_status()
self._network: dict[str, Any] = read_network(cfg.network_state_file)
self._heartbeat_thread: threading.Thread | None = None
self._last_invalid_token_log = 0.0
self._last_rpc_log = 0.0
# Informational-label bookkeeping.
self._was_hotspot = False
self._need_wifi_pending = False
self._ready_pending_key: tuple[str | None, str | None] | None = None
self._ready_printed_key: tuple[str | None, str | None] | None = None
# ------------------------------------------------------------------ helpers
@property
def printer_status(self) -> dict[str, Any]:
with self._state_lock:
return dict(self._printer_status)
def _set_printer_status(self, status: dict[str, Any]) -> None:
with self._state_lock:
self._printer_status = status
def _set_worker(self, value: str, msg_id: int | None = None, error: str | None = None) -> None:
with self._state_lock:
self.worker = value
self.job_msg_id = msg_id
self.last_error = error
@property
def station_name(self) -> str:
with self._state_lock:
return self._station_name
def _net_key(self) -> tuple[str | None, str | None]:
return (self._network.get("ssid"), self._network.get("ip"))
def _status_body(self) -> dict[str, Any]:
with self._state_lock:
printer = dict(self._printer_status)
body = {
"version": self.cfg.app_version,
"station_name": self._station_name,
"worker": self.worker,
"job_msg_id": self.job_msg_id,
"printer": printer,
"network": dict(self._network),
"label": printer.get("label_id"),
"last_error": self.last_error,
"uptime_s": int(self._monotonic() - self._started),
}
return body
# -------------------------------------------------------------- heartbeat
def start_heartbeat(self) -> None:
self._heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
self._heartbeat_thread.start()
def _heartbeat_loop(self) -> None:
interval = max(2, self.cfg.heartbeat_seconds)
while not self._stop.is_set():
self.beat()
self._stop.wait(interval)
def beat(self) -> None:
"""One heartbeat: read network state, then beacon it (never raises)."""
self._network = read_network(self.cfg.network_state_file)
if self._network.get("state") == "HOTSPOT":
if not self._was_hotspot:
self._need_wifi_pending = True
self._was_hotspot = True
else:
self._was_hotspot = False
try:
result = self._rpc.heartbeat(self._status_body())
self._apply_station_name(result)
except InvalidToken:
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
except RpcUnavailable as err:
self._log_rate_limited("_last_rpc_log", f"heartbeat unavailable: {err}")
except RpcError as err:
self._log_rate_limited("_last_rpc_log", f"heartbeat failed: {err}")
else:
self._touch_heartbeat()
# A ready label only makes sense on a real network, not in hotspot mode.
key = self._net_key()
if self._network.get("state") != "HOTSPOT" and key != self._ready_printed_key:
self._ready_pending_key = key
def _apply_station_name(self, result: Any) -> None:
"""Adopt the name the server reports for this station."""
if not isinstance(result, dict):
return
name = result.get("name")
if isinstance(name, str) and name.strip():
with self._state_lock:
self._station_name = name.strip()
def _touch_heartbeat(self) -> None:
try:
Path(HEARTBEAT_TOUCH).touch()
except OSError:
pass
def _log_rate_limited(self, attr: str, message: str, interval: float = 60.0) -> None:
now = self._monotonic()
if now - getattr(self, attr) >= interval:
setattr(self, attr, now)
log.warning(message)
# ------------------------------------------------- informational labels
def _print_local(self, img: Image.Image) -> bool:
label_id = self.printer_status.get("label_id") or "103x164"
try:
result = self._printer.print_image(img, label_id)
except Exception as err: # noqa: BLE001
log.warning("info label failed: %s", err)
return False
if not result.get("did_print"):
log.warning("info label not printed: %s", result.get("outcome"))
return False
log.info("printed info label on %s", label_id)
return True
def _maybe_print_info_labels(self) -> bool:
"""Print a pending ready/need-Wi-Fi label. True if the loop should continue."""
if not self.cfg.status_labels:
return False
if not (self._need_wifi_pending or self._ready_pending_key):
return False
status = self.printer_status
if not status.get("ready"):
return False
spec_id = status.get("label_id")
if not spec_id:
return False
spec = find_label(spec_id)
try:
if self._need_wifi_pending:
if self._print_local(need_wifi_label(spec, self._network.get("ssid") or "Convivo-Printer")):
self._need_wifi_pending = False
return True
key = self._ready_pending_key
assert key is not None
if self._print_local(ready_label(spec, self.station_name, self._network, self.cfg.app_version, datetime.now())):
self._ready_printed_key = key
self._ready_pending_key = None
except Exception: # noqa: BLE001 — a status label must never block badge jobs
log.exception("info label failed; dropping it")
self._need_wifi_pending = False
self._ready_printed_key, self._ready_pending_key = self._ready_pending_key, None
return True
# ------------------------------------------------------------------- jobs
def _fail(self, msg_id: int, error: str, retryable: bool) -> None:
log.warning("job %s failed (%s): %s", msg_id, "retry" if retryable else "dead-letter", error)
try:
outcome = self._rpc.fail(msg_id, error, retryable)
log.info("job %s → %s", msg_id, outcome)
except InvalidToken:
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
except (RpcUnavailable, RpcError) as err:
log.warning("could not report failure for job %s: %s", msg_id, err)
def _complete(self, msg_id: int) -> None:
delay = 2.0
waited = 0.0
while True:
try:
self._rpc.complete(msg_id)
log.info("job %s completed", msg_id)
return
except InvalidToken:
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
return
except RpcUnavailable as err:
if waited + delay > COMPLETE_RETRY_LIMIT_SECONDS:
# The job stays in flight; redelivery may print a duplicate.
log.error("complete for job %s still failing after %ds: %s", msg_id, int(waited), err)
return
log.warning("complete for job %s unavailable, retrying in %.0fs", msg_id, delay)
self._sleep(delay)
waited += delay
delay = min(delay * 2, 32.0)
except RpcError as err:
log.error("complete for job %s rejected: %s", msg_id, err)
return
def handle_job(self, row: dict[str, Any]) -> None:
msg_id = int(row.get("msg_id", 0))
payload = row.get("payload")
self._set_worker("printing", msg_id)
try:
if not isinstance(payload, dict) or payload.get("schema") != SCHEMA:
got = payload.get("schema") if isinstance(payload, dict) else type(payload).__name__
self._fail(msg_id, f"unsupported payload schema: {got}", retryable=False)
return
label_id = self.printer_status.get("label_id")
if not label_id:
self._fail(msg_id, "printer: no label detected", retryable=True)
return
try:
badge = self._renderer.render(payload, self.cfg.checkin_origin)
composed = compose_or_raise(badge, label_id)
except LayoutTooLarge as err:
self._fail(msg_id, str(err), retryable=False)
return
except RenderError as err:
self._fail(msg_id, f"render: {err}", retryable=False)
return
result = self._printer.print_image(composed, label_id)
status = self._printer.get_status()
self._set_printer_status(status)
# A post-print error (e.g. roll just ran out) must not dead-letter a badge that did print.
if result.get("did_print"):
self._complete(msg_id)
return
errors = (result.get("printer_state") or {}).get("errors") or status.get("errors") or []
detail = "; ".join(str(e) for e in errors) or result.get("outcome", "unknown")
self._fail(msg_id, f"printer: {detail}", retryable=False)
except Exception as err: # noqa: BLE001 — never lose a job silently
log.exception("unexpected error on job %s", msg_id)
self._fail(msg_id, f"worker: {type(err).__name__}: {err}", retryable=True)
finally:
self._set_worker("idle")
# ------------------------------------------------------------------- loop
def tick(self) -> None:
status = self._printer.get_status()
self._set_printer_status(status)
if self._maybe_print_info_labels():
status = self._printer.get_status()
self._set_printer_status(status)
if not status.get("ready"):
self._set_worker("paused", error="; ".join(status.get("errors") or []) or "printer not ready")
self._sleep(3)
return
self._set_worker("idle")
try:
rows = self._rpc.claim(self.cfg.wait_seconds)
except InvalidToken:
self._log_rate_limited("_last_invalid_token_log", "station token rejected — fix it in Admin → Printing")
self._sleep(5)
return
except RpcUnavailable as err:
self._log_rate_limited("_last_rpc_log", f"claim unavailable: {err}")
self._sleep(5)
return
except RpcError as err:
log.warning("claim failed: %s", err)
self._sleep(5)
return
if not rows:
return
self.handle_job(rows[0])
def run(self) -> None:
self.start_heartbeat()
while not self._stop.is_set():
try:
self.tick()
except Exception: # noqa: BLE001 — the loop must survive anything
log.exception("loop iteration failed")
self._sleep(3)
log.info("worker stopping")
self._renderer.close()
self._rpc.close()
def stop(self) -> None:
self._stop.set()
def compose_or_raise(badge: Image.Image, label_id: str) -> Image.Image:
return compose(badge, find_label(label_id))
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
try:
cfg = Config.from_env()
except RuntimeError as err:
log.error("%s", err)
return 2
log.info("convivo printer worker %s starting (station=%s, dry_run=%s)", cfg.app_version, cfg.station_name, cfg.dry_run)
rpc = Rpc(cfg)
from .printer import Printer
printer = Printer(cfg)
renderer = Renderer(cfg.renderer_dir)
worker = Worker(cfg, rpc, printer, renderer)
def _handle_signal(_sig: int, _frame: Any) -> None:
log.info("signal received, finishing current job")
worker.stop()
signal.signal(signal.SIGTERM, _handle_signal)
signal.signal(signal.SIGINT, _handle_signal)
worker.run()
return 0
+39
View File
@@ -0,0 +1,39 @@
"""Read the comitup network state file written by the host."""
from __future__ import annotations
import json
import socket
from pathlib import Path
UNKNOWN = {"state": "UNKNOWN", "ssid": None, "ip": None}
def _detect_ip() -> str | None:
# UDP connect trick: picks the source address of the default route, no traffic sent.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("8.8.8.8", 53))
return str(sock.getsockname()[0])
except OSError:
return None
finally:
sock.close()
def read_network(path: str) -> dict:
try:
raw = json.loads(Path(path).read_text())
except (OSError, ValueError):
result = dict(UNKNOWN)
result["ip"] = _detect_ip()
return result
if not isinstance(raw, dict):
result = dict(UNKNOWN)
result["ip"] = _detect_ip()
return result
return {
"state": str(raw.get("state") or "UNKNOWN"),
"ssid": raw.get("ssid") or None,
"ip": raw.get("ip") or None,
"updated_at": raw.get("updated_at"),
}
+136
View File
@@ -0,0 +1,136 @@
"""Brother QL printer access through brother_ql (pyusb backend), serialized by a lock."""
from __future__ import annotations
import logging
import threading
from pathlib import Path
from typing import Any
from PIL import Image
from brother_ql.backends.helpers import send as bq_send
from brother_ql.backends.helpers import status as bq_status
from brother_ql.conversion import convert
from brother_ql.raster import BrotherQLRaster
from .config import Config
from .label import find_label
log = logging.getLogger("worker.printer")
DIE_CUT_MEDIA = "Die-cut labels"
CONTINUOUS_MEDIA = "Continuous length tape"
DRYRUN_DIR = Path("/tmp/dryrun")
def map_status(raw: dict[str, Any], expected_label: str) -> dict[str, Any]:
"""Translate a brother_ql status dict into the heartbeat printer block."""
errors = [str(e) for e in (raw.get("errors") or [])]
identified = raw.get("identified_media")
label_id = getattr(identified, "identifier", None)
media_type = raw.get("media_type")
media = {"Die-cut labels": "die-cut", "Continuous length tape": "continuous"}.get(
str(media_type)
)
if media is None and str(media_type) == "No media":
errors.append("no media loaded")
if expected_label not in ("auto", "") and label_id and label_id != expected_label:
errors.append(f"wrong roll: loaded {label_id}, expected {expected_label}")
connected = str(raw.get("status_type", "")) == "Reply to status request"
phase_ok = str(raw.get("phase_type", "")) == "Waiting to receive"
ready = connected and phase_ok and not errors and label_id is not None
return {
"connected": connected,
"model": raw.get("model_name"),
"ready": ready,
"media_type": media,
"label_id": label_id,
"media_width_mm": raw.get("media_width"),
"media_length_mm": raw.get("media_length"),
"errors": errors,
}
class Printer:
def __init__(self, cfg: Config):
self._model = cfg.brother_model
self._identifier = cfg.printer_identifier
self._expected_label = cfg.brother_label
self._threshold = cfg.threshold
self._dither = cfg.dither
self._dry_run = cfg.dry_run
self._lock = threading.Lock()
if self._dry_run:
log.warning("DRY_RUN active: nothing is sent to the printer")
def get_status(self) -> dict[str, Any]:
if self._dry_run:
label_id = None if self._expected_label == "auto" else self._expected_label
label_id = label_id or "103x164"
spec = find_label(label_id)
return {
"connected": True,
"model": f"{self._model} (dry-run)",
"ready": True,
"media_type": "die-cut" if spec.die_cut else "continuous",
"label_id": label_id,
"media_width_mm": int(spec.width_px * 25.4 // 300),
"media_length_mm": int(spec.height_px * 25.4 // 300) if spec.die_cut else 0,
"errors": [],
}
try:
with self._lock:
st, _raw = bq_status(
printer_model=self._model,
printer_identifier=self._identifier,
backend_identifier="pyusb",
)
except Exception as err: # noqa: BLE001 — USB stack raises many types
log.debug("status failed: %r", err)
return {
"connected": False,
"model": None,
"ready": False,
"media_type": None,
"label_id": None,
"media_width_mm": None,
"media_length_mm": None,
"errors": [f"printer unreachable: {type(err).__name__}"],
}
return map_status(st if isinstance(st, dict) else {}, self._expected_label)
def print_image(self, img: Image.Image, label_id: str) -> dict[str, Any]:
if self._dry_run:
out = DRYRUN_DIR
out.mkdir(parents=True, exist_ok=True)
path = out / f"dryrun-{threading.get_ident()}.png"
img.save(path)
log.info("dry-run: saved %s (%dx%d)", path, img.width, img.height)
return {
"instructions_sent": True,
"outcome": "printed",
"did_print": True,
"ready_for_next_job": True,
}
qlr = BrotherQLRaster(self._model)
qlr.exception_on_warning = True
instructions = convert(
qlr,
[img],
label_id,
rotate="0",
threshold=self._threshold,
dither=self._dither,
cut=True,
)
with self._lock:
result = bq_send(
instructions,
self._identifier,
backend_identifier="pyusb",
blocking=True,
)
return result if isinstance(result, dict) else {"outcome": "unknown"}
+122
View File
@@ -0,0 +1,122 @@
"""Headless-Chromium badge renderer: serves dist-print and screenshots the badge page."""
from __future__ import annotations
import functools
import http.server
import io
import logging
import threading
from typing import Any
from PIL import Image
log = logging.getLogger("worker.render")
PRINT_DPI = 300
CSS_DPI = 96
RENDER_TIMEOUT_MS = 30_000
class RenderError(Exception):
"""The badge could not be rendered."""
class _QuietHandler(http.server.SimpleHTTPRequestHandler):
def log_message(self, *_args: Any) -> None: # keep worker stdout clean
pass
class Renderer:
"""One Chromium instance reused for every badge; relaunches itself after a crash."""
def __init__(self, renderer_dir: str):
self._dir = renderer_dir
self._server: http.server.ThreadingHTTPServer | None = None
self._thread: threading.Thread | None = None
self._browser = None
self._page = None
self._lock = threading.Lock()
def _ensure_http(self) -> str:
if self._server is not None:
return f"http://127.0.0.1:{self._server.server_address[1]}/print.html"
handler = functools.partial(_QuietHandler, directory=self._dir)
self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start()
port = self._server.server_address[1]
log.info("renderer http server on 127.0.0.1:%s", port)
return f"http://127.0.0.1:{port}/print.html"
def _ensure_browser(self) -> None:
if self._page is not None:
return
# Lazy import so the pure modules stay testable without playwright installed.
from playwright.sync_api import sync_playwright
self._pw = sync_playwright().start()
self._browser = self._pw.chromium.launch(args=["--no-sandbox"])
context = self._browser.new_context(
device_scale_factor=PRINT_DPI / CSS_DPI, viewport={"width": 1800, "height": 1800}
)
self._page = context.new_page()
self._page.set_default_timeout(RENDER_TIMEOUT_MS)
url = self._ensure_http()
self._page.goto(url, wait_until="load", timeout=RENDER_TIMEOUT_MS)
# The module defines renderBadge on load; the ready/error flags only
# change once renderBadge is actually called.
self._page.wait_for_function("typeof window.renderBadge === 'function'", timeout=RENDER_TIMEOUT_MS)
log.info("renderer chromium ready (%s)", url)
def _shutdown_browser(self) -> None:
for closer in ("_page", "_browser", "_pw"):
obj = getattr(self, closer, None)
if obj is None:
continue
try:
(obj.stop if closer == "_pw" else obj.close)()
except Exception: # noqa: BLE001
pass
setattr(self, closer, None)
def render(self, payload: dict[str, Any], checkin_origin: str) -> Image.Image:
with self._lock:
try:
self._ensure_browser()
return self._render_locked(payload, checkin_origin)
except RenderError:
raise
except Exception as err: # noqa: BLE001 — browser crash: relaunch once
log.warning("renderer error (%s), relaunching chromium", type(err).__name__)
self._shutdown_browser()
try:
self._ensure_browser()
return self._render_locked(payload, checkin_origin)
except RenderError:
raise
except Exception as err2: # noqa: BLE001
raise RenderError(f"render failed: {err2}") from err2
def _render_locked(self, payload: dict[str, Any], checkin_origin: str) -> Image.Image:
page = self._page
assert page is not None
try:
page.evaluate(
"([p, o]) => window.renderBadge(p, o)",
[payload, {"checkinOrigin": checkin_origin}],
)
except Exception as err: # noqa: BLE001 — renderBadge rejects on bad payload
raise RenderError(str(err).splitlines()[0][:300]) from err
png = page.locator("#badge-root .badge-page").screenshot(timeout=RENDER_TIMEOUT_MS)
return Image.open(io.BytesIO(png))
def close(self) -> None:
with self._lock:
self._shutdown_browser()
if self._server is not None:
self._server.shutdown()
self._server.server_close()
self._server = None
if self._thread is not None:
self._thread.join(timeout=5)
self._thread = None
+91
View File
@@ -0,0 +1,91 @@
"""PostgREST RPC client for the token-gated printer functions."""
from __future__ import annotations
import logging
from typing import Any
import httpx
from .config import Config
log = logging.getLogger("worker.rpc")
# SQLSTATE raised by _print_station_from_token for invalid/revoked tokens.
INVALID_TOKEN_CODE = "28000"
class RpcError(Exception):
"""RPC returned an unexpected response."""
class InvalidToken(RpcError):
"""The station token is invalid or revoked (HTTP 401/403 or SQLSTATE 28000)."""
class RpcUnavailable(RpcError):
"""Network failure, timeout or 5xx — the backend may come back."""
class Rpc:
def __init__(self, cfg: Config, client: httpx.Client | None = None):
self._token = cfg.station_token
self._base = f"{cfg.convivo_url}/rest/v1/rpc"
self._vt = cfg.vt_seconds
self._client = client or httpx.Client(
headers={
"apikey": cfg.convivo_anon_key,
"Authorization": f"Bearer {cfg.convivo_anon_key}",
"Content-Type": "application/json",
},
timeout=httpx.Timeout(30.0),
)
def close(self) -> None:
self._client.close()
def _call(self, fn: str, params: dict[str, Any], timeout: float) -> Any:
try:
resp = self._client.post(f"{self._base}/{fn}", json=params, timeout=timeout)
except httpx.HTTPError as err:
raise RpcUnavailable(f"{fn}: {type(err).__name__}") from err
if resp.status_code in (401, 403):
raise InvalidToken(f"{fn}: rejected ({resp.status_code})")
if resp.status_code >= 500:
raise RpcUnavailable(f"{fn}: HTTP {resp.status_code}")
if resp.status_code >= 400:
try:
body = resp.json()
except ValueError:
body = {}
if str(body.get("code", "")) == INVALID_TOKEN_CODE:
raise InvalidToken(f"{fn}: invalid station token")
detail = str(body.get("message", ""))[:200]
raise RpcError(f"{fn}: HTTP {resp.status_code} {detail}".strip())
try:
return resp.json()
except ValueError as err:
raise RpcError(f"{fn}: non-JSON response") from err
def claim(self, wait_seconds: int) -> list[dict[str, Any]]:
# Long-poll: the server waits up to wait_seconds before answering.
rows = self._call(
"printer_claim_badge_job",
{"p_token": self._token, "p_vt": self._vt, "p_wait_seconds": wait_seconds},
timeout=wait_seconds + 15,
)
return rows if isinstance(rows, list) else []
def complete(self, msg_id: int) -> bool:
return bool(self._call("printer_complete_badge_job", {"p_token": self._token, "p_msg_id": msg_id}, 20))
def fail(self, msg_id: int, error: str, retryable: bool = False) -> str:
result = self._call(
"printer_fail_badge_job",
{"p_token": self._token, "p_msg_id": msg_id, "p_error": error, "p_retryable": retryable},
20,
)
return str(result)
def heartbeat(self, status: dict[str, Any]) -> dict[str, Any]:
result = self._call("printer_heartbeat", {"p_token": self._token, "p_status": status}, 15)
return result if isinstance(result, dict) else {}
+79
View File
@@ -0,0 +1,79 @@
"""Locally-printed informational labels (ready / need Wi-Fi), drawn with Pillow."""
from __future__ import annotations
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont
from .label import LabelSpec
FONT_DIRS = (
"/usr/share/fonts/truetype/dejavu",
"/usr/share/fonts/dejavu",
"/System/Library/Fonts",
)
def _font(size: int, bold: bool = False) -> ImageFont.ImageFont:
name = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf"
for base in FONT_DIRS:
try:
return ImageFont.truetype(f"{base}/{name}", size)
except OSError:
continue
return ImageFont.load_default(size)
def _size(font: ImageFont.ImageFont) -> int:
return int(getattr(font, "size", 16) or 16)
def _fit(text: str, max_width: int, size: int, bold: bool) -> ImageFont.ImageFont:
font = _font(size, bold)
while size > 14 and font.getlength(text) > max_width:
size -= 4
font = _font(size, bold)
return font
def _render_lines(spec: LabelSpec, headline: str, lines: list[str]) -> Image.Image:
if spec.die_cut:
width, height = spec.width_px, spec.height_px
else:
width = spec.width_px
# ~60 mm of endless tape, but never shorter than half the label width.
height = max(int(60 * 300 / 25.4), width // 2)
img = Image.new("RGB", (width, height), "white")
draw = ImageDraw.Draw(img)
margin = width // 20
text_width = width - 2 * margin
y = margin
font = _fit(headline, text_width, width // 9, True)
draw.text((margin, y), headline, fill="black", font=font)
y += int(_size(font) * 1.6)
for line in lines:
font = _fit(line, text_width, width // 16, False)
draw.text((margin, y), line, fill="black", font=font)
y += int(_size(font) * 1.6)
return img
def ready_label(spec: LabelSpec, station: str, network: dict, version: str, now: datetime) -> Image.Image:
lines = [f"Station: {station}"]
if network.get("ssid"):
lines.append(f"Wi-Fi: {network['ssid']}")
if network.get("ip"):
lines.append(f"IP: {network['ip']}")
lines.append(now.strftime("%Y-%m-%d %H:%M"))
lines.append(f"v{version}")
return _render_lines(spec, "Convivo printer ready", lines)
def need_wifi_label(spec: LabelSpec, ap_ssid: str) -> Image.Image:
return _render_lines(
spec,
"No network",
["Connect a phone to the open Wi-Fi", ap_ssid, "then open http://10.41.0.1"],
)