# 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()
