Skip to main content

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_printerAgent (heartbeat + jobs); prints the inventory label jobs (mock driver for now)
printer_3dMoonraker polling (status, history), manual print attribution, filament stock out
cutter (Cricut), embroideryDesign file library (files service) + manual job logs with consumables
raspberry_piAgent with generic jobs (free-form JSON payload)
otherAgent with generic jobs and manual job logs

Flow​

Device credentials​

  • Registration (POST /v1/devices, devices.device.create on the site) issues an authz API key owned by the device (owner kind device) through POST /internal/v1/devices/{id}/api-keys with the devices service principal. authz accepts device keys only from that principal and refuses any grant on them.
  • The raw key is returned once (api_key); only key_prefix is kept. POST /v1/devices/{id}/credentials/rotate replaces 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​

EndpointPurpose
POST /v1/devices/agent/heartbeatstatus (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}/ackdelivered → running
POST /v1/devices/agent/jobs/{id}/doneOptional result object (≤ 16 KiB)
POST /v1/devices/agent/jobs/{id}/failerror message (≤ 500 characters, no personal data)
GET /v1/devices/agent/jobs/{id}/label.svgSVG 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 → printer state, device online (error when Klipper reports error/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:

  1. 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.
  2. Current project: a member selects the project on the device page; this becomes a generic job {action: "mount_project", project_id} for the agent (and a device setting current_project_id).
  3. Library sync: the agent lists the project's design files (and the device library) through a new agent endpoint GET /v1/devices/agent/library that 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.
  4. Jobs: stitching is still launched manually on the machine; members log the run afterwards (manual job with thread/stabiliser consumables), optionally pre-filled from the file the agent saw opened if the protocol allows it.
  5. 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​

VariableDefaultPurpose
HTTP_ADDR / METRICS_ADDR:8094 / :9194Listeners
MONGO_URI, MONGO_DATABASElocal, devicesStore (devices, jobs, prints, counters, outbox, keyring)
AUTHZ_URL, INVENTORY_URLhttp://localhost:8081, :8085Dependencies
PRINCIPAL_PUBLIC_KEY, PRINCIPAL_SIGNING_KEYrequiredVerify callers, sign the service principal
CRYPTO_KEK_SOURCE, CRYPTO_KEKKeyring (Moonraker keys)
DEVICES_OFFLINE_AFTER2mPresence timeout
DEVICES_MAINTENANCE_INTERVAL30sPresence, redelivery, stock retries
DEVICES_MOONRAKER_INTERVAL30sMoonraker poll period
DEVICES_HTTP_TIMEOUT10sMoonraker, authz and inventory calls
DEVICES_JOB_ACK_TIMEOUT, DEVICES_JOB_MAX_ATTEMPTS, DEVICES_JOB_RUN_TIMEOUT2m, 5, 1hJob delivery

Authorization, events, audit​

  • devices.device.read|create|update|delete (global) on atl:devices:<site>:device/<id> with the site parent; lists use the Lookup scope of devices.device.read, unreadable devices, jobs and prints answer 404.
  • devices.job.submit (project scoped) on atl: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 (recorded once 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.erased removes the member from print attributions.