Docs

Chapter 07

Cabinet API

How your backend drives a Nook Locker cabinet: the MQTT topics, how to sign an unlock command, the events the cabinet reports, and the Bluetooth tokens that keep it working offline.

The cabinet has no HTTP API and opens no port on the site network. Your backend talks to it over MQTT with TLS: it publishes signed commands, and the cabinet publishes results and events. This page describes that interface as implemented by the cabinet controller, version 1.0.0. The app and your own systems (bookings, online shop, CRM) never talk to the cabinet: they use the App API, and the backend relays to the cabinet.

Connection

SettingValue
ProtocolMQTT over TLS, port 8883
AuthenticationOne client certificate per cabinet, revocable from the backend. The MQTT client id is the cabinet id, for example cab-001.
Topic prefixcabinet/{id}/. The broker ACLs restrict each cabinet to its own topics.
HeartbeatA retained status message every 30 s
Last Will{"state":"offline"} on status, retained
Shared secret32 or more random bytes per cabinet, stored in /etc/nook/secret on the cabinet and registered in your backend. It signs commands and offline tokens.

Topics

TopicDirectionPurpose
cmd/openBackend → cabinetUnlock one compartment (signed command)
cmd/syncBackend → cabinetAsk for a fresh state. Any payload. The cabinet answers on doors and status.
event/unlockCabinet → backendResult of every unlock attempt, accepted or refused
event/doorCabinet → backendA door opened, closed, was forced or was left open
event/faultCabinet → backendLock boards stopped or started answering
event/powerCabinet → backendMains lost or restored, low battery, shutdown
doorsCabinet → backendState of every door, in reply to cmd/sync
statusCabinet → backend, retainedHeartbeat and health summary

Unlock a compartment: cmd/open

JSON
{
  "locker": 17,
  "requestId": "6f1c2a9e-3b7d-4c55-9a1e-0d2f8b7c4e11",
  "exp": 1767225600,
  "member": "m-42",
  "sig": "9b0e…c41a"
}
FieldTypeRules
lockerintegerCompartment number, from 1 to the cabinet's capacity (48, 100 or 144)
requestIdstring8 to 64 characters, unique. A UUID works. It is used once: a replay is refused.
expintegerExpiry, Unix time in seconds. At most 60 s in the future.
memberstring, optionalYour customer reference. Not signed, echoed back in event/unlock for your logs.
sigstringHex HMAC-SHA256(secret, "{cabinet}|{locker}|{requestId}|{exp}")

The cabinet id is part of the signed string, so a command signed for one cabinet can never open another. The cabinet tolerates 5 s of clock difference, and each compartment can be unlocked at most once every 2 s.

Signing a command

The cabinet uses the same definition. Python and Node.js versions:

Python
import hashlib, hmac, time, uuid

def sign_command(secret: bytes, cabinet: str, locker: int, member: str | None = None, ttl: int = 30) -> dict:
    request_id = str(uuid.uuid4())
    exp = int(time.time()) + ttl
    body = f"{cabinet}|{locker}|{request_id}|{exp}".encode()
    cmd = {"locker": locker, "requestId": request_id, "exp": exp,
           "sig": hmac.new(secret, body, hashlib.sha256).hexdigest()}
    if member:
        cmd["member"] = member
    return cmd

# publish json.dumps(cmd) on cabinet/cab-001/cmd/open, QoS 1
Node.js
import { createHmac, randomUUID } from 'node:crypto';

export function signCommand(secret, cabinet, locker, member, ttl = 30) {
  const requestId = randomUUID();
  const exp = Math.floor(Date.now() / 1000) + ttl;
  const sig = createHmac('sha256', secret).update(`${cabinet}|${locker}|${requestId}|${exp}`).digest('hex');
  return { locker, requestId, exp, sig, ...(member ? { member } : {}) };
}

Events from the cabinet

Every event carries ts, the Unix time at which it happened on the cabinet. Events are written to a local journal first and published in order. If the link drops, they are kept and sent when it returns, with their original ts.

event/unlock

JSON
{"locker": 17, "ok": true, "doorOpen": true, "source": "app",
 "requestId": "6f1c2a9e-…", "member": "m-42", "ts": 1767225571}
FieldMeaning
oktrue when the lock board accepted the command
doorOpentrue when the door actually moved. ok:true, doorOpen:false means the board answered but the door did not open: a jammed lock or a door held shut.
sourceapp for an online command, ble for a Bluetooth offline token
requestId / nonceThe command's requestId (online) or the token's nonce (Bluetooth)
reasonPresent when the attempt was refused or failed. See the reasons below.

event/door

JSON
{"locker": 17, "event": "opened", "ts": 1767225571}
{"locker": 17, "event": "left_open", "after": 120, "ts": 1767225691}

event/fault, event/power, doors, status

JSON
// event/fault: board 3 stopped answering (an empty list means everything is back)
{"failedBoards": [3], "ts": 1767225600}

// event/power: on_battery, mains_restored, low_battery or shutdown
{"event": "on_battery", "mains": false, "battery": 96, "ts": 1767225600}

// doors: reply to cmd/sync, true means open
{"doors": {"1": false, "2": false, "17": true, "…": false}, "failedBoards": [], "ts": 1767225600}

// status: retained heartbeat
{"state": "online", "version": "1.0.0", "uptime": 86400,
 "power": {"mains": true, "battery": 100},
 "boards": {"total": 3, "failed": []},
 "openDoors": [17], "pendingEvents": 0, "ts": 1767225600}

low_battery is sent once when the battery drops to 20 % on battery power. shutdown is sent just before a clean shutdown at 5 %. battery is null when no battery monitor is fitted.

Refusal and failure reasons

A refused attempt is never silent: it produces an event/unlock with ok:false and one of these reasons.

ReasonCause
not JSON, not an objectThe payload could not be read as a JSON object
bad lockerMissing, not an integer, or outside 1 to the cabinet's capacity
bad requestId, bad exp, missing sigA required field is missing or malformed
bad signatureWrong secret, wrong cabinet id or a modified field
expiredexp is in the past
expiry too far aheadexp is more than 60 s in the future
replayedThis requestId was already used
too many requestsThe same compartment was unlocked less than 2 s ago
board N did not answerThe lock board did not reply on the RS485 bus
bad token, bad token format, bad token encoding, bad payloadBluetooth only: the token is malformed
token for another cabinetBluetooth only: the token names another cabinet
not valid yet, validity window too long, already usedBluetooth only: the token is outside its window, valid for more than 7 days, or was already used

Offline tokens over Bluetooth

When the cabinet has no internet, the member's app opens the compartment over Bluetooth with a token issued in advance by your backend. Issue a few tokens while the app is online and store them in the app.

Format
v1.<base64url(payload)>.<base64url(HMAC-SHA256(offline_key, payload))>

payload       = {"cab":"cab-001","exp":1767830400,"locker":17,"member":"m-42","nbf":1767225600,"nonce":"9f2c4e7a"}
                (compact JSON, keys sorted)
offline_key   = HMAC-SHA256(secret, "nook-offline-v1")

Bluetooth GATT service

The cabinet advertises as Nook-{cabinet id}.

CharacteristicUUIDUse
Service6e6f6f6b-0001-4c6f-636b-657200000000
Unlock6e6f6f6b-0002-4c6f-636b-657200000000Write the token as UTF-8
Result6e6f6f6b-0003-4c6f-636b-657200000000Read or notify: {"ok":true,"locker":17,"doorOpen":true}

Unlocks made over Bluetooth are journaled with source:"ble" and reach your backend as soon as the cabinet is back online.

Test without hardware

The controller ships with a simulator that runs the same code as the cabinet, with simulated boards, power and Bluetooth. It needs Python 3.11 or newer.

Shell
python -m nook sim                          # dashboard on http://127.0.0.1:8080
python -m nook sim --mqtt localhost:1883    # against a real broker

# helpers for your backend tests, using the cabinet's configuration
python -m nook sign-command 17 --member m-42 -c /etc/nook/config.toml
python -m nook issue-token 17 --member m-42 --hours 24 -c /etc/nook/config.toml

From the dashboard you can cut the internet or the mains, unplug a board, jam a lock or force a door, and watch the events your backend would receive.