MQTT and IoT Platforms
Why MQTT
HTTP works for occasional uploads. For many devices sending frequent small messages, and for controlling devices remotely, MQTT is lighter: devices publish and subscribe to topics through a broker.
greenhouse/1/temperature ← device publishes 22.4
greenhouse/1/pump/set → device subscribes; dashboard publishes "on"
Brokers
- Mosquitto (self-hosted, lightweight, runs on a Raspberry Pi).
- Hosted brokers from cloud IoT services.
Secure them: username/password or certificates per device, TLS encryption (port 8883), and access-control lists so each device can only use its own topics.
ESP32 with an MQTT library
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
WiFiClientSecure net;
PubSubClient mqtt(net);
void onMessage(char* topic, byte* payload, unsigned int len) {
String msg; for (unsigned i = 0; i < len; i++) msg += (char)payload[i];
if (String(topic) == "greenhouse/1/pump/set") setPump(msg == "on");
}
void setup() {
// connect Wi-Fi first...
net.setCACert(ROOT_CA_PEM);
mqtt.setServer(MQTT_HOST, 8883);
mqtt.setCallback(onMessage);
}
void loop() {
if (!mqtt.connected()) {
mqtt.connect("greenhouse-1", MQTT_USER, MQTT_PASS);
mqtt.subscribe("greenhouse/1/pump/set");
}
mqtt.loop();
// publish readings on a millis() timer:
// mqtt.publish("greenhouse/1/temperature", String(t, 1).c_str());
}
Dashboards and automation
- Home Assistant integrates MQTT devices into dashboards and automations ("if soil is dry for 10 minutes, run the pump for 30 seconds").
- ESPHome lets you define ESP32 devices in YAML and integrates them with Home Assistant without writing C++.
- Node-RED wires flows visually.
- Time-series storage and charts: InfluxDB or PostgreSQL with Grafana.
Exercise
Run Mosquitto with authentication and TLS, connect your ESP32 to publish readings and accept pump commands, and build a Home Assistant (or Node-RED) dashboard with an automation.
Check yourself
- What are topics, publishers and subscribers?
- How should an MQTT broker be secured?
- What does ESPHome simplify?
Ваш прогресс сохраняется только в этом браузере.
Отправить на проверку (10 баллов)