Devices and MQTT
Enrol a device with a claim code, connect it to Floor's MQTT broker, and hear it, command it and configure it from a backend.
This page takes a gate controller from first boot to a backend that opens its barrier. You'll make claim codes, approve a device, see the protocol its firmware speaks, and handle its messages, commands and config in Rust. You need a project and a backend (see Your first backend).
Floor gives every device its identity. The device keeps its own private key; Floor stores the public key and hands out one-hour device tokens. Floor's MQTT broker runs inside Floor itself and lets each device use only its own topics.
1. Make claim codes for the labels
A claim code is printed on the device's label. With --auto-approve, a device that presents it is approved at once (each code works once):
floor claim-codes create sac --count 20 --label "Gate controllers, batch 3" --auto-approveThe codes are printed once. Without --auto-approve, or without a code, a claiming device waits in quarantine for an operator. In the console, codes are under Fleet › Devices › Pre-register claim codes.
Devices with a certificate from your factory's CA can join without codes: in Fleet › Provisioning, add the CA (its certificate, PEM) and an enrollment group that trusts it, optionally only for hardware ids starting with a batch's prefix and with a number of slots. A device then sends its certificate chain (certificate_chain, PEM, its own certificate first, with its hardware id as the common name) when it claims, and is in at once. Anything a group doesn't admit waits in quarantine with the reason, where you let it in or reject it; rejecting blocks its key and certificate.
2. Try it with a simulated device
floor devices simulate runs the whole device protocol from your machine: it makes a key, claims, waits for approval, gets a token and connects to MQTT. It speaks plain MQTT, so run it against a Floor on your machine (Dev loop):
floor devices simulate sac --hardware-id GATE-07 --stay 60 --health-every 5--stay 60 keeps it connected for a minute, publishing health and telemetry, answering commands (it fails a command named fail and ignores one named ignore) and applying config. Its source is the reference implementation for firmware.
3. Approve the device
Without an auto-approve code the device shows as waiting. Compare the key fingerprint with the one the device prints (serial console or display), then approve it:
floor devices list --project sac --status pending
floor devices approve sac/GATE-07In the console: Fleet › Devices, under Waiting to join. To shut a device out later:
floor devices revoke sac/GATE-07 # no new tokens; it's disconnected from MQTT at once4. What the firmware does
First boot. Make a P-256 key pair and keep the private key (NVS on an ESP32, a root-only file on Linux). Make a new one only on factory reset. The device also needs its hardware id (1 to 64 letters, digits, ., _ or -; it becomes part of its topics), the project slug, and optionally its claim code.
Claim once, and again after a factory reset:
POST https://usefloor.dev/v1/devices/claim
Content-Type: application/json
{
"project": "sac",
"hardware_id": "GATE-07",
"public_key": { "kty": "EC", "crv": "P-256", "x": "<base64url>", "y": "<base64url>" },
"claim_code": "K4M7-77Q2-X9AB",
"certificate_chain": null,
"kind": "SAC gate controller",
"firmware_version": "3.0.11"
}{ "device_id": "…", "status": "pending", "key_fingerprint": "3B:91:F0:…", "group": null }status is active at once with an auto-approve code, or when an enrollment group admits the device (group names it); a 403 means the project rejected this key or certificate. Claiming again with the same key is harmless. A different key for an active hardware id is refused until an operator revokes the old one, so a cloned id can't take over a device.
Get a device token every hour. Sign a short JWT with the device's key (ES256), exp at most 5 minutes ahead (keep the clock in sync):
header: { "alg": "ES256", "typ": "JWT" }
payload: { "iss": "sac/GATE-07", "aud": "https://usefloor.dev/v1/devices/token",
"iat": <now>, "exp": <now + 120> }POST https://usefloor.dev/v1/devices/token
Content-Type: application/json
{ "assertion": "<jwt>", "firmware_version": "3.0.11" }{
"access_token": "<device token>",
"token_type": "Bearer",
"expires_in": 3600,
"mqtt_username": "sac:GATE-07",
"mqtt_topics": "sac/GATE-07/#",
"media_path": "sac/GATE-07"
}A 403 means the device is still waiting for approval or was revoked: retry every few minutes. A 401 means the assertion was wrong (signature, audience or clock).
Connect to MQTT with username mqtt_username and password access_token:
- MQTT over TLS on port 8883 of Floor's MQTT host;
- or MQTT over WebSocket at
wss://usefloor.dev/mqtt(subprotocolmqtt), for devices that can only reach HTTPS.
The broker closes the connection when the token expires, so fetch a new token a few minutes before expires_in runs out and reconnect with it.
5. Topics
A device may publish and subscribe only under <project>/<hardware id>/. Everything else is denied: a refused publish is dropped, and a refused subscription gets a failure code.
| Topic | Direction | What |
|---|---|---|
sac/GATE-07/health | device → Floor | JSON: rssi_dbm, uptime_s, free_heap_kb, temp_c, any other short fields; once a minute is plenty |
sac/GATE-07/events, telemetry, logs | device → Floor | product data |
sac/GATE-07/config | Floor → device | desired config, retained |
sac/GATE-07/state | device → Floor | the config it runs now, retained |
sac/GATE-07/cmd | Floor → device | commands |
sac/GATE-07/cmd/ack | device → Floor | answers to commands |
sac/GATE-07/app/… | either | anything product-specific |
Firmware needs nothing for online and offline: Floor sees connects and disconnects in the broker itself. A status topic is optional.
The broker speaks MQTT 3.1.1 with QoS 0 and 1, retained messages, last wills and persistent sessions. A packet is at most 256 KiB, and a client may publish 50 messages a second (bursts of 4 times that).
6. Hear the device in the backend
A file in on/ handles MQTT messages. The filter is inside the project's prefix, so +/events means sac/+/events:
// on/mqtt/events.rs
use floor::prelude::*;
#[derive(Deserialize)]
pub struct PlateEvent {
event_id: String,
lane_id: i64,
plate: String,
}
#[mqtt("+/events")]
pub async fn events(cx: Cx, msg: Mqtt<PlateEvent>) -> Result<()> {
// msg.device is "GATE-07", msg.topic is "sac/GATE-07/events", msg.body the parsed JSON.
let e = msg.body;
floor::tracing::info!(device = %msg.device, plate = %e.plate, lane = e.lane_id, "plate read");
Ok(())
}Mqtt<T>parses a JSON payload;MqttRawgives the bytes (payload).- Delivery is at least once. A handler that changes data should notice an event it has seen; SAC's gate keeps each
event_id. Okacks the message. AnErris logged, counted and acked with its message.
Device events (presence, health, config, commands) come to a #[device(…)] handler:
// on/presence.rs
use floor::prelude::*;
#[device(online, offline)]
pub async fn presence(cx: Cx, ev: DeviceEvent) -> Result<()> {
let Some(device) = ev.device else { return Ok(()) };
cx.kv_set_json(&format!("presence:{device}"), &serde_json::json!({ "state": ev.event }), None)
.await
}The events are online, offline, health, config and command; #[device] with no list gets all of them. ev.event is the event's name, ev.device the hardware id when the event names one, and ev.data the whole event as JSON.
7. Send a command and read the answer
let id = cx
.command("GATE-07", "open_gate", &serde_json::json!({ "lane": 2 }))
.await?;cx.command returns the command's id at once; it doesn't wait for the device. Floor publishes it on the device's cmd topic and tracks it:
- The device must be online and approved, or the call fails.
- Arguments are at most 16 KiB of JSON.
- The device has 30 seconds to answer, then the command is marked timed out.
The device receives:
{ "id": "01a1…", "name": "open_gate", "args": { "lane": 2 },
"sent_at": 1794476520, "expires_at": 1794476550 }and answers on cmd/ack with the same id, ignoring commands past expires_at:
{ "id": "01a1…", "ok": true, "result": { "barrier": "up" } }
{ "id": "01a1…", "ok": false, "error": "lane 2 barrier jammed" }The backend hears each change as a command device event. Its data.command has id, device, name, args, status (sent, acked, failed or timed_out), result and error:
// on/commands.rs
use floor::prelude::*;
#[device(command)]
pub async fn answered(cx: Cx, ev: DeviceEvent) -> Result<()> {
let c = &ev.data["command"];
if c["name"] == "open_gate" && c["status"] == "timed_out" {
floor::tracing::warn!(device = %c["device"], "a gate didn't answer");
}
Ok(())
}From a terminal: floor devices command sac/GATE-07 open_gate --args '{"lane":2}' sends one and waits for the answer, and floor devices commands sac/GATE-07 lists recent ones.
8. Change a device's desired config
Floor keeps a desired config per device and publishes it retained on <device>/config, so the device gets it now or when it next connects:
let mut set = serde_json::Map::new();
set.insert("plate_min_confidence".into(), serde_json::json!(0.8));
set.insert("health_interval_s".into(), serde_json::json!(60));
let config = cx.set_device_config("GATE-07", set, &["night_mode"]).await?;
// config.version, config.desired, config.reportedThe settings in set change, the names in the last argument are removed, and the others stay. The device receives:
{ "version": 14, "config": { "plate_min_confidence": 0.8, "health_interval_s": 60 } }It applies what it can and publishes what it now runs on <device>/state, retained: the settings object, or the same {"version", "config"} shape. The console compares the two setting by setting ("In sync" or "Pending"). From a terminal: floor devices config sac/GATE-07 --set plate_min_confidence=0.8.
Use cx.set_device_config rather than publishing on config yourself, so Floor keeps the desired config and its version.
Let devices in from the product
A product's own admin page can do what the console does here: cx.devices(Some("pending")),
cx.approve_device, cx.revoke_device and cx.claim_codes. See
Floor from Cx.
Look a device up
let gate = cx.device_info("GATE-07").await?;
if !gate.online {
return Err(Error::conflict("gate 7's controller is offline"));
}DeviceInfo has hardware_id, name, kind, status, online, last_seen_at, firmware_version, health (what it last published on health) and labels.
Let devices call the backend over HTTP
A route with #[post(device)] takes the project's devices, by their device token as Authorization: Bearer <token>. cx.device() is the caller's hardware id. A device token is refused on every other kind of route.
// api/gates/heartbeat.rs → POST /api/gates/heartbeat
use floor::prelude::*;
#[derive(Deserialize, Type)]
pub struct Heartbeat {
barrier: String,
}
#[post(device)]
pub async fn post(cx: Cx, Json(b): Json<Heartbeat>) -> Result<NoContent> {
let device = cx.device()?;
sqlx::query("update lanes set barrier = $2, heard_at = now() where device = $1")
.bind(device)
.bind(&b.barrier)
.execute(cx.db())
.await?;
Ok(NoContent)
}Use this for what MQTT does badly, such as asking for an upload URL (Files).
Publish to a device's topics yourself
cx.mqtt_publish(topic, payload, retain) publishes inside the project's prefix: cx.mqtt_publish("GATE-07/app/display", "Welcome", false) goes to sac/GATE-07/app/display. Prefer commands when you need to know the device got it.
Testing
floor::testing::TestApp runs MQTT messages and device events through your handlers, and records the commands they send. See Testing.