IoT devices need efficient communication protocols. MQTT provides lightweight messaging designed specifically for connected devices. This guide shows how to connect various IoT devices using MQTT.
Why IoT Needs Special Protocols
Traditional web protocols weren't designed for IoT. HTTP requires significant overhead per request. Opening and closing connections drains batteries quickly.
Consider a temperature sensor that reports every minute. With HTTP, each reading requires a new connection with hundreds of bytes of overhead. The sensor battery dies quickly.
MQTT solves these problems. Connections stay open, reusing the same channel. Message overhead is minimal. Devices send data efficiently.
Connecting a Raspberry Pi
The Raspberry Pi works great with MQTT. It runs Python and has built-in networking.
Install the MQTT library:
pip install paho-mqtt
Create a sensor script:
import paho.mqtt.client as mqtt
import json
import time
import random
from gpiozero import TemperatureSensor
# Initialize sensor
sensor = TemperatureSensor()
# MQTT connection
client = mqtt.Client(client_id="raspberry-pi-01")
client.username_pw_set("api-key", password="")
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
else:
print(f"Connection failed with code {rc}")
client.on_connect = on_connect
# Connect to broker
client.connect("mqtt://broker.petstoreapi.com", 1883, 60)
# Main loop
client.loop_start()
while True:
# Read temperature
temp = sensor.temperature
payload = {
"device": "raspberry-pi-01",
"type": "temperature",
"value": round(temp, 2),
"unit": "celsius",
"timestamp": int(time.time())
}
# Publish
client.publish(
"petstore/sensors/environment/temperature",
json.dumps(payload),
qos=1
)
print(f"Published: {payload}")
time.sleep(60)
The Pi publishes temperature readings every minute. The broker forwards these to any subscribers.
Connecting ESP32/ESP8266
Microcontrollers like ESP32 and ESP8266 work well with MQTT. These devices have WiFi and run efficiently on battery power.
Using Arduino IDE:
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi credentials
const char* ssid = "your-network";
const char* password = "your-password";
// MQTT broker
const char* mqtt_server = "mqtt://broker.petstoreapi.com";
const char* mqtt_username = "your-api-key";
const char* mqtt_password = "";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32Client", mqtt_username, mqtt_password)) {
Serial.println("MQTT connected");
} else {
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Read sensor and publish
float temperature = readTemperature();
char payload[100];
snprintf(payload, sizeof(payload),
"{\"device\":\"esp32-01\",\"temp\":%.2f,\"timestamp\":%lu}",
temperature, millis());
client.publish("petstore/sensors/esp32/temperature", payload, 1);
delay(60000);
}
This code runs on battery-powered devices. It wakes up, reads sensors, publishes data, and sleeps again.
Connecting Mobile Apps
Mobile apps can both publish and subscribe. Use MQTT for efficient real-time updates.
// Using MQTT.js in a mobile app
import MQTT from 'mqtt';
const client = MQTT.connect('mqtt://broker.petstoreapi.com', {
clientId: 'petstore-iot-device-001'
clientId: 'mobile-app-' + Date.now(),
username: 'api-key',
clean: true,
reconnectPeriod: 5000
});
client.on('connect', () => {
console.log('Connected to MQTT');
// Subscribe to order updates
client.subscribe('petstore/orders/#', { qos: 1 });
// Subscribe to alerts
client.subscribe('petstore/alerts/#', { qos: 1 });
});
client.on('message', (topic, message) => {
const data = JSON.parse(message.toString());
if (topic.startsWith('petstore/orders/')) {
showOrderNotification(data);
} else if (topic.startsWith('petstore/alerts/')) {
showAlert(data);
}
});
// Publish device location
function publishLocation(lat, lon) {
client.publish(
'petstore/devices/mobile/location',
JSON.stringify({
deviceId: getDeviceId(),
lat,
lon,
timestamp: Date.now()
}),
{ qos: 0 }
);
}
Mobile apps receive instant updates without polling. Location data publishes efficiently in the background.
Cloud Integration
Forward MQTT messages to cloud services for storage and analysis:
// Forward to cloud storage
const mqtt = require('mqtt');
const { Kafka } = require('kafkajs');
const mqttClient = mqtt.connect('mqtt://localhost:1883');
const kafka = new Kafka({ brokers: ['kafka:9092'] });
const producer = kafka.producer();
mqttClient.on('message', (topic, message) => {
// Forward to Kafka
producer.send({
topic: 'iot-data',
messages: [{ value: message.toString() }]
});
});
Store data in time-series databases, trigger functions based on thresholds, visualize in dashboards.
Handling Disconnections
IoT devices lose connectivity. Your code must handle this gracefully.
import paho.mqtt.client as mqtt
import json
def on_disconnect(client, userdata, rc):
if rc != 0:
print(f"Unexpected disconnection. Reconnecting...")
while True:
try:
client.reconnect()
print("Reconnected")
break
except:
time.sleep(5)
client = mqtt.Client()
client.on_disconnect = on_disconnect
Reconnection logic ensures devices resume operation automatically when networks restore.
Security Best Practices
Secure your MQTT deployments:
Use TLS encryption: Connect to port 8883 for encrypted communication.
Implement authentication: Use API keys or certificates for device authentication.
Restrict topics: Limit what each device can publish and subscribe to.
Validate data: Check message sizes and formats before processing.
Monitor connections: Track connection attempts and disconnect patterns.
Pet Store API MQTT Setup
The Pet Store API provides a managed MQTT broker for your IoT devices.
Connect devices using these settings:
- Broker:
mqtt://broker.petstoreapi.comormqtts://broker.petstoreapi.com:8883 - Authentication: Use your API key as username
- Topics: Follow the naming convention in docs.petstoreapi.com
Publish sensor data to track inventory conditions. Subscribe to topics for order and inventory updates.
MQTT makes IoT integration straightforward. Devices communicate efficiently. Data flows automatically. Your systems stay connected.