Docs

Chapter 05

Software

From a tap in the app to a door springing open: the unlock sequence, the MQTT topics between the backend and the cabinet, the RS485 frames sent to the lock boards, and a starting point for the controller service.

Unlock sequence

  1. The customer taps “Open compartment 57”. The app sends the request with its session token over HTTPS.
  2. The backend checks the token and that compartment 57 is assigned to this customer. It then signs a short-lived command.
  3. The backend publishes it to cabinet/cab-001/cmd/open.
  4. The Pi verifies the signature and expiry, then maps 57 to board 2, channel 9.
  5. The Pi writes the RS485 frame. The board pulses 12 V on channel 9 and the door springs open.
  6. The Pi reads the door sensor and publishes the event. The app shows “Compartment 57 open” and the backend logs it.

MQTT topics

TopicDirectionPayload
cabinet/{id}/cmd/openBackend → Pi{"locker":57,"requestId":"…","exp":1763466000,"sig":"…"}
cabinet/{id}/event/unlockPi → Backend{"locker":57,"requestId":"…","ok":true,"ts":…}
cabinet/{id}/event/doorPi → Backend{"locker":57,"state":"closed","ts":…}
cabinet/{id}/statusPi → Backend (retained)online / offline (last will)

RS485 frame format

This is the format commonly used by these lock control boards: 9600 baud, 8N1. The checksum (BCC) is the XOR of all the preceding bytes.

CommandFrameExample
Unlock one lock8A addr ch 11 BCC8A 02 09 11 90 = compartment 57
Read status80 addr 00 33 BCC80 02 00 33 B1
Check the exact frame format, channel numbering and reply layout against the protocol sheet of the boards you buy. They vary between models.

Cabinet controller service (Python sketch)

locker_service.py
# locker_service.py - Raspberry Pi cabinet controller (sketch)
import hashlib, hmac, json, time
import serial                      # pip install pyserial
import paho.mqtt.client as mqtt    # pip install paho-mqtt (v2)

CABINET_ID = "cab-001"
BROKER = "mqtt.example.com"
PORT = "/dev/ttyUSB0"              # USB-RS485 converter
LOCKS_PER_BOARD = 48
LOCKER_COUNT = 100
SECRET = open("/etc/locker/secret", "rb").read().strip()

bus = serial.Serial(PORT, 9600, timeout=0.3)
seen = set()                       # used requestIds (replay protection)


def bcc(data):
    x = 0
    for b in data:
        x ^= b
    return x


def locate(locker):
    board = (locker - 1) // LOCKS_PER_BOARD + 1
    channel = (locker - 1) % LOCKS_PER_BOARD + 1
    return board, channel


def send(frame, reply_len):
    bus.reset_input_buffer()
    bus.write(frame + bytes([bcc(frame)]))
    return bus.read(reply_len)


def unlock(locker):
    board, ch = locate(locker)
    return send(bytes([0x8A, board, ch, 0x11]), 5)


def verify(cmd):
    body = f'{cmd["locker"]}|{cmd["requestId"]}|{cmd["exp"]}'.encode()
    sig = hmac.new(SECRET, body, hashlib.sha256).hexdigest()
    return (hmac.compare_digest(sig, cmd.get("sig", ""))
            and cmd["exp"] > time.time()
            and cmd["requestId"] not in seen
            and 1 <= int(cmd["locker"]) <= LOCKER_COUNT)


def on_connect(client, userdata, flags, reason_code, properties):
    client.publish(f"cabinet/{CABINET_ID}/status", "online", qos=1, retain=True)
    client.subscribe(f"cabinet/{CABINET_ID}/cmd/open", qos=1)


def on_message(client, userdata, msg):
    try:
        cmd = json.loads(msg.payload)
        if not verify(cmd):
            return
        seen.add(cmd["requestId"])
        reply = unlock(int(cmd["locker"]))
        client.publish(f"cabinet/{CABINET_ID}/event/unlock", json.dumps({
            "locker": cmd["locker"], "requestId": cmd["requestId"],
            "ok": len(reply) > 0, "ts": int(time.time())}), qos=1)
    except (ValueError, KeyError):
        pass                       # malformed command: ignore and log


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=CABINET_ID)
client.tls_set(ca_certs="/etc/locker/ca.pem",
               certfile=f"/etc/locker/{CABINET_ID}.crt",
               keyfile=f"/etc/locker/{CABINET_ID}.key")
client.will_set(f"cabinet/{CABINET_ID}/status", "offline", qos=1, retain=True)
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER, 8883)
client.loop_forever()

Dependencies: pip install paho-mqtt pyserial. Run it as a systemd service with automatic restart. This is a starting point, not production code: add a reply parser, retries, a door-state poller and local logging. Download locker_service.py