← Back to Academy
IoT Protocol · Networking

MQTT & Secure IoT Communication

⏱ ~2 hours 🛠️ Hands-on Beginner

Why MQTT for IoT?

HTTP — the protocol of the web — requires a full request-response cycle for every message. For a temperature sensor that needs to send a reading every 30 seconds, HTTP would require the device to initiate a new connection, send headers, wait for a response, and close the connection. On a battery-powered device with 64KB of RAM and a 2G connection, this is unacceptably expensive.

MQTT was designed for exactly this situation. It uses a persistent TCP connection, tiny packet overhead (as little as 2 bytes of header), and an efficient pub/sub routing model. A sensor can stay connected and publish readings with minimal power draw and bandwidth.

📡 HTTP vs MQTT

HTTP: each message opens a connection, sends headers (hundreds of bytes), waits for response, closes. MQTT: one persistent connection, 2-byte minimum header, no response needed.

🔋 Power Efficiency

MQTT's keepalive mechanism lets devices sleep between messages. The broker holds messages for offline devices and delivers them when they reconnect.

📊 Bandwidth

MQTT fixed header is 2 bytes. HTTP minimum is ~500 bytes. For 10,000 daily readings, MQTT uses ~20KB vs HTTP's ~5MB — a 250x reduction.

🕐 Latency

One-way message delivery with no acknowledgement overhead at QoS 0. Device-to-subscriber delivery in single-digit milliseconds on a local network.

The Publish/Subscribe Model

MQTT uses a publish/subscribe (pub/sub) model — fundamentally different from HTTP's request/response. There are three roles:

1

Broker

The central message router. Receives all published messages and routes them to subscribed clients. The FidesInnova Node includes a built-in broker — you do not need a separate Mosquitto or EMQX installation.

2

Publisher

A client (your IoT device) that sends messages to the broker on a named topic. The publisher does not know who is subscribed — it just sends to the topic.

3

Subscriber

A client (FidesInnova Node, another device, a dashboard) that tells the broker which topics it cares about. The broker delivers any matching published messages immediately.

This decoupling is powerful: publishers and subscribers never need to know about each other. A new subscriber can start receiving data from existing devices without modifying the device firmware at all.

Topics & Wildcards

MQTT topics are hierarchical strings using / as separators. FidesInnova recommends a consistent naming convention:

# Recommended FidesInnova topic structure
{nodeId}/{deviceId}/sensor/{reading_type} # sensor data
{nodeId}/{deviceId}/status # online/offline
{nodeId}/{deviceId}/proof # ZKP proof data
{nodeId}/{deviceId}/command # commands to device

# Wildcard subscriptions
node001/+/sensor/temperature # + = one level: all devices, temperature only
node001/# # # = all levels: everything on this node
+/device007/# # device007 across all nodes

Single-level wildcard (+) matches exactly one topic level. Multi-level wildcard (#) matches any number of levels and must appear at the end of a subscription.

Quality of Service Levels

MQTT offers three QoS levels. Choose based on the consequences of message loss or duplication:

QoS 0 — At Most Once

Fire and forget. No acknowledgement. Use for high-frequency sensor readings (temperature every second) where occasional loss is acceptable and retransmission would cause outdated data anyway.

QoS 1 — At Least Once

Broker acknowledges receipt. Message retransmitted until acknowledged — duplicates possible. Use for alerts and events where loss is unacceptable but duplicate processing is tolerable.

QoS 2 — Exactly Once

Four-way handshake. No loss, no duplicates. Use for ZKP proof submission, billing events, and actuator commands where exactly-once semantics are critical.

🏆 FidesInnova Recommendation

Use QoS 0 for raw sensor streams, QoS 1 for status updates, QoS 2 for proof submissions to the blockchain queue.

Connecting a Device to the FidesInnova Node

The FidesInnova Node broker listens on port 1883 (plain) and 8883 (TLS). Devices connect with a client ID, username (device ID), and password (device token generated by the Node dashboard).

#include <WiFiClientSecure.h>
#include <PubSubClient.h>

const char* broker = "your-node.fidesinnova.io";
const int port = 8883; // TLS port
const char* deviceId = "device-001";
const char* token = "your-device-token";

WiFiClientSecure net; PubSubClient client(net);

void connectMQTT() {
  net.setCACert(rootCA); // node TLS certificate
  client.setServer(broker, port);
  while (!client.connected()) {
    if (client.connect(deviceId, deviceId, token)) {
      client.subscribe("node001/device-001/command");
    } else { delay(5000); } // retry
  }
}

MQTTS & TLS Security

Never use plain MQTT (port 1883) in production. Without TLS, all device credentials and sensor data are transmitted in cleartext — readable by anyone on the network path.

MQTTS (MQTT over TLS, port 8883) provides encryption and server authentication. The FidesInnova Node generates a TLS certificate during setup. Obtain it from your Node dashboard and embed it in device firmware.

For the highest security, enable mutual TLS (mTLS) — each device has its own certificate that the broker uses to authenticate it, eliminating the need for password-based authentication entirely.

Certificate rotation: Device certificates should be rotated periodically. FidesInnova's Node dashboard supports per-device certificate management and revocation without device reflashing — new certificates can be delivered via the command topic and stored in device flash.

Last Will and Testament (LWT)

LWT is an MQTT feature where a client pre-registers a message with the broker. If the client disconnects ungracefully (power loss, crash, network failure), the broker publishes the LWT message automatically. This is essential for device health monitoring in FidesInnova deployments.

// Register LWT before connecting
client.setWill(
  "node001/device-001/status", // topic
  "offline", // payload
  1, // QoS 1
  true // retained
);

// On successful connect, publish online status
client.publish("node001/device-001/status", "online", true);

Integration with FidesInnova Service Contracts

Service Contracts on the FidesInnova Node subscribe to device topics automatically based on the device's registered configuration. A simple Service Contract that reacts to temperature readings:

// Service Contract: temperature watchdog
function onMessage(topic, payload) {
  const data = JSON.parse(payload);
  const proof = node.generateProof(data);
  node.submitToBlockchain(proof);

  if (data.temperature > 35) {
    node.sendNotification("HIGH TEMP: " + data.temperature);
    node.publishMQTT("node001/hvac/command", "cool_on");
  }
}

What You Will Learn

  • Understand the pub/sub model and how MQTT differs from HTTP
  • Configure topics, QoS levels, and retained messages
  • Set up MQTTS with TLS for production security
  • Connect an ESP32 device to the FidesInnova Node broker
  • Use Last Will and Testament for device health monitoring
  • Write a Service Contract that reacts to MQTT device data
🤖
AI Learning Assistant

Ask any question about this course topic

Ask AI ↗