Skip to content

Provisioning

Internals of the Provisioning domain. For the public API, see Provisioning API.

The domain lives in CoreAPI/domain/provisioning. It pairs display devices (LG webOS, Samsung Tizen, Android SignageBoard) through a 6-digit code, tracks them through heartbeats and MQTT status reports, and controls them by publishing MQTT commands. On top of that loop it owns broadcast to a space, composite rendering, test playback, the playout (linear-TV) channel-group read, approvals and direct assignments.

How it works

Physical screen                              CoreAPI
┌─────────────┐
│   Display   │── 1. POST /devices/generate-code ──▶ provisioning_codes (10-minute TTL)
│  (webOS /   │◀─ shows the 6-digit code
│  Tizen /    │
│  Android)   │   2. a user claims the code (POST /displays/:ws/claim-code) ──▶ devices row created
│             │── 3. GET /devices/check-claim/:provisioningId ──▶ deviceToken (JWT, 365 days)
│             │── 4. POST /devices/heartbeat-public ──▶ devices.last_seen_at
│             │◀─ MQTT tellyboard/devices/{id}/play, /player/command, /volume, /power, ...
│             │── MQTT tellyboard/devices/{id}/status, /player/event, /heartbeat ... ──▶ CoreAPI subscribers
└─────────────┘
Device status = 'Online' if last_seen_at > NOW() - 5 minutes

Two route families run the same handlers:

Family Mounted by Auth Who calls it
Scoped /api/v1/displays/:ws/... RegisterScopedDeviceRoutes (scoped_routes.go) ProtectedRS256 + VerifiedWorkspaceScope (org from the token, workspace from the path, permission check; overwrites X-Organization-ID, X-Workspace-ID, X-User-ID with verified values) PlayoutAdmin, partners. This is the documented API.
Flat /api/v1/devices/*, /spaces/*, /approvals, /direct-assignments, /schedules, /channels/:id/activities RegisterDeviceRoutes and friends (routes.go, routes_platform.go) Header-trusting: the handlers read X-Organization-ID / X-Workspace-ID / X-User-ID as sent. The legacy scope guard sits in front (below). TellyboardAdmin, and the TV itself for the five open device routes

requireDeviceInWorkspace guards every scoped /:deviceId route: a device of another workspace or org is a 404 (Device not found in this workspace), so IDs can't be probed across workspaces. requireTargetLocationInWorkspace guards PATCH .../location because the legacy handler only checks the device's org, not the target location's.

Legacy scope guard

pkg/middleware/legacy_scope.go covers the flat prefixes (/devices, /spaces, /approvals, /direct-assignments, /schedules, /channels and the other flat groups). Mode comes from COREAPI_LEGACY_SCOPE:

Mode Behaviour
off Nothing happens.
log (default) Each request is classified and counted; the ones enforce mode would refuse are logged. Counters at GET /api/v1/internal/legacy-scope (PSK).
enforce No valid token, or headers that disagree with the token: 401 / 403. A good request has its headers overwritten with the verified values.

Routes a device calls without a user login always pass (legacyOpenRoutes): GET /devices/:deviceId/channels/groups, GET /devices/:deviceId/channels/categories, POST /devices/generate-code, GET /devices/check-claim/:provisioningId, POST /devices/heartbeat-public, GET /devices/status/ws (authenticates itself).

MQTT topics

All topics are tellyboard/devices/{deviceId}/<suffix>.

Suffix Direction Trigger / payload
play CoreAPI → device POST .../play, .../composite, .../test-play, POST /spaces/:id/broadcast. { command: "PLAY", ... }: items, zones + layout, or one composited video
player/command CoreAPI → device STOP (stop, test-play stop with no bound channel); {command: "SET_CHANNEL_GROUPS", groups} (playout publish); {command: "RESET_DEVICE"} (retained, on delete); CAPTURE_SCREEN; the allow-listed player_command values of POST .../command
executePowerCommand, power, volume, getDeviceInfo CoreAPI → device POST .../command types reboot, power, volume, getDeviceInfo
config/bandwidth-limit CoreAPI → device Retained, so a device that was offline learns its cap on reconnect (the shared player/command topic must never be retained)
status device → CoreAPI device_info_report, screenshot_report, play_report, usage, power, md5, upgrade reports
player/event device → CoreAPI Playback events, ACTION_RESULT, volume changes
report/storage, report/download, log device → CoreAPI Subscribed per device only while someone watches it on /displays/:ws/:id/stream

Command publishes from the scoped POST .../command are QoS 1, not retained, with a 5-second timeout (mqttPublishTimeout). The older play/stop handlers publish QoS 0 and Wait() without a timeout.

Real-time streams

  • GET /api/v1/devices/status/ws: WebSocket, ProtectedRS256 (cookie fallback, since a browser upgrade can't send custom headers). Org comes from the token. On connect it sends a snapshot of every device's merged state from Valkey (device:status:<org>:<device>), then live updates fanned out through NATS subject device.status. The state per device is merged (deviceStatusState: connectivity, display, last info, volume), not just the last event.
  • GET /api/v1/displays/:ws/:deviceId/stream: WebSocket, scoped like the other device routes. Relays that one device's MQTT replies in Tellyboard's own shape ({topic, payload}), plus {"type":"ready"}, a {"type":"ping"} every 25 s, and {"type":"error","code":"expired"|"too_many_streams"|"unavailable"}. At most 25 listeners per device; a stream is cut after 30 minutes (the login is only checked at upgrade), and the client reconnects. Every CoreAPI replica has its own MQTT subscription, so no NATS hop is needed.

Neither stream is in the partner reference: the message shapes carry raw MQTT topics and are tied to our admin apps.

Data model

devices

Field Type Notes
id UUID
organizationId string Tenant scope
workspaceId *string Set at claim from the path workspace. POST /displays/:ws/unassigned/:id/assign is the only way to set it later
name, description string
serialNumber string SN-{code} on claim; unique index. PUT with a serial used by another device keeps the old one (logged)
status string Computed on read (Online if last_seen_at is within 5 minutes). HandleUpdateDevice can still write the column and HandleRelinkDevice sets it to Online; the read overrides it
lastSeenAt *time Heartbeat and MQTT heartbeat/status
currentPlaylistId *string Last direct playlist pushed; cleared on stop
locationId *string Spatial locations.id (a space)
volume int 100 on claim; updated from device reports
orientation, timezone string landscape, UTC on claim
isRemoteControlEnabled, isPanelControlEnabled bool true on claim
wolEnabled, dpmEnabled, dpmSignalType Wake-on-LAN, display power management
ipAddress, macAddress, manufacturer, model, playerVersion, firmwareVersion, osVersion, platformName, platformVersion From device_info_report
storageUsedBytes, storageTotalBytes, cpuPct, memPct From device reports
downloadBandwidthLimitMbps *float null = unlimited
warrantyEndDate, expectedRefreshDate *date Lifecycle
continent, country, countryCode, regionName, city, isp string Filled by POST .../geo (ip-api.com). Private IPs (127.x, 192.168.x, 10.x) query without an IP, so the server's own IP is used
latitude, longitude *float Not filled by /geo
deviceType string signage default
approvalStatus string pending on manual create; read falls back to approved
appMode string tellyboard (default) or playout; DB CHECK accepts only those two lowercase values, so HandleClaimDeviceCode lower-cases the client's value
playoutChannelGroupId *int Set by a successful publish/push of a playout channel group
display_on, display_changed_at From display_on / display_off reports
playbackGroupId, policyGroupId, operationGroupId *string On the model; no handler reads or writes them

Computed on read: locationName, locationPath (venue > building > floor > space > endpoint), locationCountryCode, endpointId, endpointName, groups (target-group names), nowPlaying, displayScheduledOff (online but outside the feed's operation hours). nowPlaying.source is resolved in priority order: emergency → campaign → direct → timeblock → feed → none.

Other tables

Table Use
provisioning_codes id (the provisioningId), code (6 digits), expires_at (+10 min), device_id (NULL until claimed or relinked), organization_id
device_activity_log Activity entries (kind, title, detail); also read by power adherence (kind='power') and status?refresh=1 (kind='device_info')
device_placement_history One row per location change, with the resolved path and a note
device_power_schedule One row per weekday (day_of_week 0-6, on_time, off_time HH:MM, 24:00 allowed for off)
device_screenshots Last screenshot (or last capture error) per device
device_play_logs Proof of play from play_report; a play with the same device, start time and creative is stored once. At most 200 plays per report, at most 6 h per play
approval_requests Approvals (below)

Key flows

Pairing

  1. The screen calls POST /devices/generate-code → {provisioningId, code, expiresAt}; code stored with a 10-minute TTL.
  2. A user claims it: scoped POST /displays/:ws/claim-code (or legacy POST /devices/claim-code with X-Organization-ID). Body {code, name, mode?, spaceId?}. Creates the device in one transaction and links the code. spaceId must be a space of the org (400 otherwise); it becomes location_id, so the TV's room (and its stay) resolves even with no endpoint bound.
  3. The screen polls GET /devices/check-claim/:provisioningId: {status:"pending"}, 410 {status:"expired"}, or {status:"claimed", deviceId, deviceToken, deviceName, appMode, workspaceId}.

Claim does not check expiry

HandleClaimDeviceCode looks the code up by value and refuses it only when already claimed (409). It does not check expires_at, so an expired, unclaimed code can still be claimed; the screen's own poll returns 410 by then. Relink does check expiry.

Heartbeat

POST /devices/heartbeat-public {deviceId} sets last_seen_at = NOW(). After more than 60 s offline it triggers catalogue.ResyncDeviceOnReconnect. The response carries workspaceId (so a launcher claimed before workspaces existed learns it) and, when the device's endpoint has a feed with operation hours, operatingHours {start, end, timezone, channelId}; the timezone is catalogue.OperationTimezone. runDeviceOfflineScheduler marks stale devices offline and broadcasts OFFLINE.

Play and stop

POST .../play normalises the body (id/mediaId, type/mediaType), resolves a channel (channelId, or the channel whose zone uses playlist id), attaches the layout and the active time block's zones (Asia/Bangkok time), then either publishes the payload or renders a composite (below). It records current_playlist_id for a plain playlist and logs MQTT_PUBLISH to the channel's activity. A body whose url contains composite is sent as a single-item play. POST .../stop clears current_playlist_id and publishes STOP.

Composite rendering

A device that can't render multi-zone layouts gets one merged MP4 (FFmpeg overlay/concat).

  • Manual, legacy POST /devices/:id/composite {channelId, screenW=1920, screenH=1080, totalSec=30, zones:[{zoneId, filePath, widthPx, heightPx, xPx, yPx, duration}]}. filePath values are local server paths. Writes ./media-assets/uploads/composite/composite_{deviceId}_{ts}.mp4, never deleted. 500 {"error":"FFmpeg failed"} on encode failure.
  • Automatic, inside play when the channel has a multi-zone layout:
Mode When Behaviour
none No valid zone content 400 {"error":"No valid content"}
single One valid zone That zone's items as a flat play
direct A zone has .mpd content, or no PDFs mixed in {command:"PLAY", layout, zones}; the device renders
composite Several video zones, or PDFs mixed with other content Download remote media, loop shorter zones, render, play the merged file

Composite mode de-duplicates by a SHA-256 of layout + zones (composite-unchanged), skips a second concurrent render for the same device (composite-skipped), deletes the file 30 s after publishing, and logs FFMPEG_START/SUCCESS/ERROR, DOWNLOAD_START/SUCCESS, COMPOSITE_GENERATED to the channel activity (GET /channels/:channelId/activities?limit=&before=).

Test playback

POST .../test-play {playlistId, minutes 1-240} publishes the playlist as an override (id: test-{ts}) and schedules an in-memory revert timer. Reverting re-runs the device's own play path with its bound channel. A restart during the window loses the timer: the device stays on the test playlist until .../test-play/stop or another play.

Commands

POST /displays/:ws/:id/command {type, payload}. The route needs workspace:devices:view; the handler then requires the tier of the command:

Tier Permission Commands
view workspace:devices:view getDeviceInfo; player commands GET_SYSTEM_USAGE, GET_DPM_STATUS, GET_USAGE_DATA, GET_POWER_STATUS, GET_VERSION_INFO, GET_MD5, CAPTURE_SCREEN
edit workspace:devices:edit reboot, power (ON/OFF), volume (0-100); REBOOT, REBOOT_APP, SYNC_STORAGE, CLEAR_CACHE, SET_PORTRAIT, SET_CONTENT_ROTATION, TOGGLE_CLOCK, SET_WOL, SET_DPM_WAKEUP, SET_TIMEZONE_AND_TIME, CHANGE_LOGO, STOP, PAUSE, RESUME, SWITCH_TO_PLAYOUT, SWITCH_TO_TELLYBOARD
delete workspace:devices:delete DELETE_FILE, DELETE_BULK, DOWNLOAD_FIRMWARE, UPGRADE_FIRMWARE, UPGRADE_APP, UPDATE_COMPONENT, SET_SERVER

Max body 256 KB. A url field in a player command must be http(s). Responses: 202 {status:"sent", command}, 503 broker down, 504 publish timeout, 502 other publish error. This replaced the browser publishing to MQTT itself.

Status, capture and screenshot

Request/response wrappers over MQTT for SignageBoard (Android) and the Tizen launcher. The call publishes, then polls the database every 400 ms for the device's report: status?refresh=1 waits up to wait (default 8 s) for a device_info activity row; capture waits up to wait (default 20, max 40 s) for a new device_screenshots row. A capture timeout answers 504 with a hint (an app screen that doesn't capture, or a Samsung TV without the partner privilege). Screenshots are at most 8 MB.

Playout channel groups (linear-TV mode)

A device with appMode: "playout" plays a channel group instead of signage. GET /devices/:id/channels/groups reads the device's playoutChannelGroupId straight from the database and maps it to PlayoutGroup; it returns [] when none is assigned, the group is gone, or the group isn't published (unless PLAYOUT_ALLOW_DRAFT=1). The read looks the group up by ID alone (no org check), as before, so existing Tellyboard devices keep working. Artwork comes from the channel's brand assets; the legacy playout_channel_meta table is only a fallback on the Tellyboard routes.

categories per channel = CategoriesFor(primaryGenre, genres): main genre then sub genres, lower-cased, de-duplicated. (The struct comment in models_playout.go still says "one item"; the function is the rule.) facets is computed before any filter. urlHls is set only for an external relay origin.

Who can call what:

Route Login Used by
GET /devices/:id/channels/groups, .../categories No (published group only) TV app, guide client
GET /playback/:ws/channel-groups/:id/payload, .../categories workspace:channels:view Guide UI development, PlayoutAdmin preview
POST /playback/:ws/channel-groups/:id/push workspace:channels:manage PlayoutAdmin. Only this org's playout devices; the group must be published; records the assignment only when the broker acknowledges
Legacy POST /devices/:id/channels/publish/:groupId, POST /spaces/:id/channels/publish/:groupId No Tellyboard only. No org check, no published check: anyone who can reach the API can repoint a device

See also Playout workspace auth.

Building a guide client (team workflow):

  1. No backend: serve Quickstart/docs/samples/tvguide-groups.placeholders.json and tvguide-categories.json with any static server (npx http-server Quickstart/docs/samples -p 4010 --cors). Same shape as the real response.
  2. Real data, no device: as a workspace member, GET /api/v1/playback/:ws/channel-groups/:id/payload (works for drafts). Browser calls need an allowed CORS origin.
  3. Production path: GET /api/v1/devices/:id/channels/groups; [] until the group is published and pushed.
  4. Live thumbnails come from a backend worker, off unless LIVE_THUMBS_ENABLED=true.

Broadcast to a space (legacy only)

POST /spaces/:spaceId/broadcast {items:[{mediaId,name,type,url,storageKey,duration}], isOverride, playAt?} pushes the same content to every device bound to the space through endpoints, bypassing scheduling. Registered in routes_platform.go, not routes.go. It checks the space is a space location of the org (404), resolves item URLs (storage key → proxy URL, dev/local hosts rewritten), publishes concurrently with a 5 s timeout per device and returns {success, sentCount, total}. 404 "no devices found in this space", 503 "mqtt broker not connected, please retry". This is TellyboardAdmin's "Publish Direct". TellyboardAdmin checks ws:playlist:publish client-side; without it the UI calls POST /approvals instead. The API itself enforces nothing.

Approvals and direct assignments (legacy only)

stateDiagram-v2
    [*] --> pending: POST /approvals
    pending --> approved: PATCH /approvals/:id {status: "approved"}
    pending --> rejected: PATCH /approvals/:id {status: "rejected"}
    approved --> [*]
    rejected --> [*]
  • POST /approvals (X-Organization-ID) {kind, targetId, targetName, requestedById, requestedBy, scope, summary, payload}; kind and targetId required → 201 {id, status:"pending"}.
  • GET /approvals?status= → newest first.
  • PATCH /approvals/:requestId (X-Organization-ID, X-User-ID) {status: "approved"|"rejected"}; 404 when missing or no longer pending. reviewedById comes from X-User-ID; decidedBy and reviewerFeedback in the body are accepted and ignored. On approve, payload.items is replayed fire-and-forget to every payload.spaceIds (broadcast logic) and payload.endpointIds.
  • /direct-assignments (POST, GET, PATCH /:id/cancel) and /schedules (playlist-override scheduling, CRUD) back TellyboardAdmin's Schedule calendar and the Content & Storage tab.

Legacy route list

Every flat route, header-trusting. Scoped equivalents exist for the ones marked ✓.

Method Path Scoped equivalent
GET / POST /devices ✓ (GET /displays/:ws); create has none (devices are created by claiming)
POST /devices/claim-code, /devices/relink ✓
POST /devices/generate-code, /devices/heartbeat-public; GET /devices/check-claim/:id Open device routes (documented)
GET / PUT / DELETE /devices/:deviceId ✓
POST /devices/:id/play, /stop, /geo, /test-play, /test-play/stop, /refresh-info, /capture ✓
POST /devices/:id/composite none
PATCH /devices/:id/location, /bandwidth-limit, /lifecycle ✓
GET /devices/:id/status, /screenshot, /proof-of-play, /activity, /placement-history, /content-sources, /power-schedule, /power-adherence ✓
PUT /devices/:id/power-schedule ✓
GET /devices/:id/channels/groups, /channels/categories Open device routes (documented)
POST /devices/:id/channels/publish/:groupId, /spaces/:id/channels/publish/:groupId POST /playback/:ws/channel-groups/:id/push
POST /spaces/:spaceId/broadcast none
GET /channels/:channelId/activities none
POST / GET / PATCH /approvals, /approvals/:requestId none
POST / GET / PATCH /direct-assignments, /direct-assignments/:id/cancel none
GET / POST / GET / PUT / DELETE /schedules, /schedules/:id none
GET /devices/status/ws (WebSocket, RS256) n/a

Environment variables

Variable Effect
COREAPI_LEGACY_SCOPE off / log (default) / enforce for the flat routes
PLAYOUT_ALLOW_DRAFT 1 serves draft channel groups on the device read
LIVE_THUMBS_ENABLED true runs the live-thumbnail worker; otherwise thumbnail is the EPG thumbnail

Change history

Date Change
2026-11-13 Status, capture and last screenshot as request/response routes; proof of play (play_report, GET .../proof-of-play); device_screenshots and device_play_logs registered for migration.
2026-10-21 Reply relay GET /displays/:ws/:id/stream, scoped relink, PAUSE/RESUME/SWITCH_TO_* on the command allow-list, placement fields on the single-device read, scoped playlist reads.
2026-10-15 Authenticated workspace-scoped device routes (/displays/:ws).
2026-10-01 Playout group read comes from the database (filters, /channels/categories, extended payload with brand assets and guide metadata); legacy publish routes kept; authenticated push added in the Playback domain. See Playout workspace auth.
2026-08-07 Documented broadcast to a space, composite rendering, test playback, playout channel groups (appMode) and approvals.
2026-06-17 First description, architecture, data model and flows.
2026-06-16 First OpenAPI file.