The KeyAccess system allows authorized users to unlock physical key boxes using their phone's NFC capabilities. The flow is secured via Supabase for authorization and HiveMQ (MQTT) for low-latency communication with the ESP32 hardware.
sequenceDiagram
participant User
participant App as Mobile App
participant DB as Supabase DB
participant Bridge as MQTT Bridge
participant MQTT as HiveMQ
participant DEV as ESP32 Lock
User->>App: Taps "Unlock" (NFC Scan)
App->>App: Reads NFC Tag (Box UUID)
App->>DB: RPC request_unlock(box_uuid)
DB->>DB: Authorize Booking
DB->>DB: Insert "unlock" into box_commands
DB-->>App: Return command_id
App->>DB: Subscribe Realtime(box_commands, id)
DB->>Bridge: Realtime INSERT Event
Bridge->>Bridge: Parse command
Bridge->>MQTT: Publish "keyaccess/boxes/<uuid>/cmd"
MQTT->>DEV: Deliver Message
DEV->>DEV: Validate & Unlock Servo
DEV->>MQTT: Publish "keyaccess/boxes/<uuid>/status" (unlocked)
MQTT->>Bridge: Deliver Status
Bridge->>DB: Update box_commands (status='executed')
DB->>App: Realtime UPDATE Event (executed)
App->>User: Show "Access Granted"
Topic: keyaccess/boxes/<BOX_UUID>/cmd
Payload:
{
"type": "command",
"command": "unlock",
"commandId": "550e8400-e29b...",
"ts": 1702550000000
}Topic: keyaccess/boxes/<BOX_UUID>/status
Payload:
{
"type": "status",
"boxId": "<BOX_UUID>",
"status": "unlocked", // or "locked", "online", "offline"
"result": "ok", // or "failed"
"commandId": "...", // correlated from command
"ts": 1702550005000
}Run the script scripts/init_mqtt_flow.sql to create the necessary tables, types, and RPC functions.
Located in services/mqttBridge.
Environment Variables (.env):
SUPABASE_URL=...
SUPABASE_SERVICE_ROLE_KEY=...
MQTT_URL=mqtts://...
MQTT_USERNAME=...
MQTT_PASSWORD=...
TOPIC_PREFIX=keyaccess
MQTT_TLS_INSECURE=false # Set true only for dev if neededLocated in ../test.ino (or firmware/).
Configuration:
- Update
WIFI_SSIDandWIFI_PASSin the code (or use WiFiManager). - Update
MQTT_BROKER,User,Pass. - CRITICAL: Set
DEVICE_IDto match the UUID of the box in your database.
Flashing:
- Install Arduino IDE or PlatformIO.
- Install libraries:
PubSubClient,ArduinoJson,ESP32Servo,Adafruit_NeoPixel. - Select Board: "ESP32 Dev Module".
- Upload.
- Secrets: Do not commit
secrets.hor.envfiles. - TLS: The bridge and ESP32 are configured for TLS (MQTTS). For production, ensure CA certificates are pinned on the ESP32 instead of using
setInsecure().