devices
Status: implemented (services/devices, contract: docs/dev/phase4-contracts.md, Devices service; specs:
features.md "Integration with machines"). Runs in the apps profile of docker-compose.yml on port 8094
(metrics 9194, :9090 in compose) and is reached through the gateway route /v1/devices.
Role: registry of the machines of every site and their integrations. External devices only talk to the HTTP API through the gateway with a device API key; Kafka stays internal.
Kind (kind) | Integration |
|---|---|
label_printer | Agent (heartbeat + jobs); prints the inventory label jobs (mock driver for now) |
printer_3d | Moonraker polling (status, history), manual print attribution, filament stock out |
cutter (Cricut), embroidery | Design file library (files service) + manual job logs with consumables |
raspberry_pi | Agent with generic jobs (free-form JSON payload) |
other | Agent with generic jobs and manual job logs |
Flow
Device credentials
- Registration (
POST /v1/devices,devices.device.createon the site) issues an authz API key owned by the device (owner kinddevice) throughPOST /internal/v1/devices/{id}/api-keyswith thedevicesservice principal. authz accepts device keys only from that principal and refuses any grant on them. - The raw key is returned once (
api_key); onlykey_prefixis kept.POST /v1/devices/{id}/credentials/rotatereplaces the secret (a new key is issued if the old one was revoked), deletion revokes every key of the device. - The gateway rejects device keys outside
/v1/devices/agent/*(403); the devices service also checks that the key owner is a live device whose active key is the caller, and rejects disabled devices (device_disabled).
Agent API
| Endpoint | Purpose |
|---|---|
POST /v1/devices/agent/heartbeat | status (online or error) and metadata → device summary and poll_wait_s |
GET /v1/devices/agent/jobs?wait=&limit= | Long poll (≤ 30 s): queued jobs of the device, marked delivered |
POST /v1/devices/agent/jobs/{id}/ack | delivered → running |
POST /v1/devices/agent/jobs/{id}/done | Optional result object (≤ 16 KiB) |
POST /v1/devices/agent/jobs/{id}/fail | error message (≤ 500 characters, no personal data) |
GET /v1/devices/agent/jobs/{id}/label.svg | SVG of a label job, rendered by inventory with the service principal |
Long polls wait on an in-process notifier and re-read MongoDB every 2 s, so jobs created on another replica are
delivered too. Job statuses: queued → delivered → running → done | failed, plus cancelled. The maintenance job
(lease devices-maintenance, every DEVICES_MAINTENANCE_INTERVAL) requeues delivered jobs not acknowledged within
DEVICES_JOB_ACK_TIMEOUT (failing them with not_acknowledged after DEVICES_JOB_MAX_ATTEMPTS deliveries), fails
running jobs older than DEVICES_JOB_RUN_TIMEOUT (timeout) and marks devices offline after
DEVICES_OFFLINE_AFTER without contact.
Label printing
inventory.label.print_requested (topic inventory.label.v1, group devices) creates one label job per event
(the event ID is a unique key: redeliveries are ignored). Routing: the requested printer_id when it is an online
label printer of the item's site, otherwise the next online label printer of the site (round robin counter per
site); with none online the job stays unassigned and the first label printer of the site that polls claims it.
Queued jobs of printers that went offline are released for the others. Payload: item_id, short_code,
qr_url, copies, template, label_url (the agent endpoint above, used instead of a presigned URL so that the device key
is the only credential). The template is forwarded to inventory when rendering the SVG. Older jobs without
it use medium (62 × 29 mm). The web label queue (/app/devices/labels) lists, cancels and retries them.
3D printers (Moonraker)
PUT /v1/devices/{id}/moonraker stores url, enabled, the Moonraker API key (write-only, sealed with the
keyring, subject = device ID, crypto-shredded on deletion), filament_item_id (inventory consumable in m, g
or kg) and grams_per_meter (default 2.98, 1.75 mm PLA). The poller (lease devices-moonraker, every
DEVICES_MOONRAKER_INTERVAL, or POST /v1/devices/{id}/sync) calls, with X-Api-Key:
GET /printer/objects/query?print_stats=state,filename&display_status=progress&extruder=temperature,target&heater_bed=temperature,target→printerstate, deviceonline(errorwhen Klipper reportserror/shutdown);GET /server/history/list?limit=50&order=desc→ prints upserted by(device_id, moonraker_job_id);GET /server/history/job?uid=for in-progress prints that left the latest page.
Failures store a code on the device (moonraker.last_error: unreachable, unauthorized, invalid_answer,
not_found), never the answer. HTTP calls use DEVICES_HTTP_TIMEOUT and 2 retries with backoff on network
errors, 429 and 5xx.
Mainsail has no user notion: PUT /v1/devices/prints/{id}/attribution sets user_id / project_id
(devices.job.submit, project parent; attributing to another member also needs devices.device.update). With
consume_filament, a finished print of a mapped printer gets a stock line (item, quantity,
reference devices:print:<id>, status): stored pending, posted as an inventory out movement with the caller principal
(inventory checks inventory.stock.adjust), then done or failed (forbidden, rejected, not_found).
Transient failures stay pending and the maintenance job retries them with the service principal after checking
the latest 200 movements of the item for the reference (inventory movements are not idempotent by themselves).
POST /v1/devices/prints/{id}/consume retries a failed line as the caller.
Design libraries and manual logs
Cricut and embroidery designs are files service attachments owned by atl:devices:<site>:device/<id> (purpose
design) or by a project ARN (project designs, projects.file.*). For device files, files derives
devices.device.read|update; when denied it asks the devices delegate (FILES_DELEGATES has
devices=http://devices:8094): read = devices.device.read, write = devices.file.manage on
atl:devices:<site>:file/<device id> with the site and the uploader's project parent (so project roles may hold it).
POST /v1/devices/{id}/logs (cutter, embroidery, other) records a manual job (done) with project, design file,
notes, times and up to 20 consumables, each posted as a stock out line (devices:job:<id>:<n>) with the same
pending/retry rules; POST /v1/devices/jobs/{id}/consume retries failed lines.
Embroidery remote storage (theoretical design)
Not implemented (features.md: "TODO later"). The Maison Broderie MIRROR should browse the designs of the current project from the intranet instead of a USB stick. Intended design:
- Bridge: the machine cannot hold an API key nor speak HTTPS to the gateway, so a Raspberry Pi agent next to it exposes the storage protocol the machine supports (network share, typically SMB/WebDAV, to be confirmed with the machine documentation) on the workshop network only.
- Current project: a member selects the project on the device page; this becomes a
genericjob{action: "mount_project", project_id}for the agent (and a device settingcurrent_project_id). - Library sync: the agent lists the project's
designfiles (and the device library) through a new agent endpointGET /v1/devices/agent/librarythat returns file IDs, names, iterations and short-lived presigned URLs fetched by devices with the service principal; it mirrors them read-only into the share, keeping only the latest iterations to keep the library concise. - Jobs: stitching is still launched manually on the machine; members log the run afterwards (
manualjob with thread/stabiliser consumables), optionally pre-filled from the file the agent saw opened if the protocol allows it. - Security: the share is read-only, LAN-only, and holds no personal data; the agent wipes it when the project is unmounted or the device disabled.
Raspberry Pi agent
services/devices/cmd/devices-agent is the reference agent (same Go module). It sends a heartbeat every
DEVICES_AGENT_HEARTBEAT (30 s) with its version, long-polls jobs (DEVICES_AGENT_WAIT, ≤ 30 s), acknowledges
each job, runs it with the driver and reports done/fail. Only the mock driver exists: it writes one JSON line
per job (labels include the downloaded SVG) to DEVICES_AGENT_OUTPUT (- = stdout).
# Build for a Raspberry Pi (64-bit OS; GOARCH=arm GOARM=7 for 32-bit)
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -ldflags "-X main.version=$(git describe --always)" \
-o devices-agent ./services/devices/cmd/devices-agent
scp devices-agent pi@printer-pi:/usr/local/bin/
On the Pi, store the key shown at registration in /etc/atelier/devices-agent.key (mode 600) and create
/etc/systemd/system/devices-agent.service:
[Unit]
Description=Atelier devices agent
After=network-online.target
Wants=network-online.target
[Service]
Environment=DEVICES_API_URL=https://api.atelier-maker.fr
Environment=DEVICES_API_KEY_FILE=/etc/atelier/devices-agent.key
Environment=DEVICES_AGENT_DRIVER=mock
Environment=DEVICES_AGENT_OUTPUT=/var/log/devices-agent/jobs.log
ExecStart=/usr/local/bin/devices-agent
DynamicUser=yes
LogsDirectory=devices-agent
Restart=always
[Install]
WantedBy=multi-user.target
systemctl enable --now devices-agent, then check the device turns online in the intranet. Locally, run it
against the gateway with DEVICES_API_URL=http://localhost:8080.
Configuration
| Variable | Default | Purpose |
|---|---|---|
HTTP_ADDR / METRICS_ADDR | :8094 / :9194 | Listeners |
MONGO_URI, MONGO_DATABASE | local, devices | Store (devices, jobs, prints, counters, outbox, keyring) |
AUTHZ_URL, INVENTORY_URL | http://localhost:8081, :8085 | Dependencies |
PRINCIPAL_PUBLIC_KEY, PRINCIPAL_SIGNING_KEY | required | Verify callers, sign the service principal |
CRYPTO_KEK_SOURCE, CRYPTO_KEK | Keyring (Moonraker keys) | |
DEVICES_OFFLINE_AFTER | 2m | Presence timeout |
DEVICES_MAINTENANCE_INTERVAL | 30s | Presence, redelivery, stock retries |
DEVICES_MOONRAKER_INTERVAL | 30s | Moonraker poll period |
DEVICES_HTTP_TIMEOUT | 10s | Moonraker, authz and inventory calls |
DEVICES_JOB_ACK_TIMEOUT, DEVICES_JOB_MAX_ATTEMPTS, DEVICES_JOB_RUN_TIMEOUT | 2m, 5, 1h | Job delivery |
Authorization, events, audit
devices.device.read|create|update|delete(global) onatl:devices:<site>:device/<id>with the site parent; lists use the Lookup scope ofdevices.device.read, unreadable devices, jobs and prints answer 404.devices.job.submit(project scoped) onatl:devices:<site>:job/<id>with the site and project parents: generic jobs, manual logs, attributions and stock retries.devices.file.manage: device library uploads.- Events (outbox):
devices.device.v1(registered,updated,status_changed,credentials_rotated,deleted),devices.job.v1(queued,done,failed,cancelled; generic payloads are not published),devices.print.v1(recordedonce a print ends,attributed). - Audit: every user write, agent
ack/done/fail, status changes and print records. Heartbeats without status change and deliveries are not audited (telemetry, every few seconds). - Erasure:
members.member.erasedremoves the member from print attributions.