ESP32 Learn

MQTT Basics: Pub/Sub & Keepalive

2025-09-18 路 ~1 min read
Table of contents
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <WiFi.h>

#include <PubSubClient.h>

WiFiClient espClient;
PubSubClient mqtt(espClient);
void cb(char * t, byte * p, unsigned int l) {
  /* handle msg */ }
void reconnect() {
  while (!mqtt.connected()) {
    mqtt.connect("esp32");
    mqtt.subscribe("home/cmd");
  }
}
void setup() {
  /* WiFi */
  mqtt.setServer("broker.hivemq.com", 1883);
  mqtt.setCallback(cb);
}
void loop() {
  if (!mqtt.connected()) reconnect();
  mqtt.loop();
  mqtt.publish("home/status", "ok");
  delay(2000);
}

馃敄 #mqtt #pubsub #iot