🛠 Publier et s'abonner en MQTT avec PubSubClient

ESP8266 (ESP-12E module) · intermediaire · Schéma : IMG-esp8266-esp-12e-intermediaire-3-esp8266-mqtt-pubsub.svg — Module ESP8266-ESP-12E connecté via Wi-Fi à un broker MQTT sur le réseau local, échanges sur les sujets esp12e/rssi et esp12e/led, LED sur GPIO2.

Objectives

Connect the ESP8266-ESP-12E to an MQTT broker (the king protocol of home automation, very lightweight and perfectly suited for the chip) using the PubSubClient library. The module publishes its RSSI every 5 seconds on the topic "esp12e/rssi" and controls the onboard LED by subscribing to "esp12e/led" (ON/OFF messages). You will learn how to maintain the connection (keepalive via mqtt.loop called regularly), manual reconnection when the broker disappears, and how to use the reception callback. The broker can be Mosquitto on a Raspberry Pi or a NAS on the local network.

Hardware

Complete code

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* SSID = "mon-reseau";
const char* PASS = "mot-de-passe";
const char* BROKER = "192.168.1.50";   // IP du broker Mosquitto
const uint8_t LED = 2;                 // active-LOW

WiFiClient net;
PubSubClient mqtt(net);
unsigned long dernierePub = 0;

void callback(char* topic, byte* payload, unsigned int len) {
  String msg = String((char*)payload).substring(0, len);
  msg.toUpperCase;
  if (String(topic) == "esp12e/led") {
    digitalWrite(LED, msg == "ON" ? LOW : HIGH);   // LOW = allumee
    Serial.printf("LED -> %s\n", msg.c_str);
  }
}

void connexion {
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASS);
  while (WiFi.status != WL_CONNECTED) { delay(250); Serial.print("."); yield; }
  while (!mqtt.connected) {
    Serial.print("Connexion MQTT...");
    if (mqtt.connect("esp12e-01")) {          // client id unique sur le broker
      Serial.println(" ok");
      mqtt.subscribe("esp12e/led");
    } else {
      Serial.printf("echec rc=%d, retry 2s\n", mqtt.state);
      delay(2000);
    }
  }
}

void setup {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  mqtt.setServer(BROKER, 1883);
  mqtt.setCallback(callback);
  connexion;
}

void loop {
  if (WiFi.status != WL_CONNECTED || !mqtt.connected) connexion;
  mqtt.loop;                                 // keepalive + réception, indispensable
  if (millis - dernierePub > 5000) {
    dernierePub = millis;
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", WiFi.RSSI);
    mqtt.publish("esp12e/rssi", buf);
  }
  delay(10);
}

Expected verification

Start the broker then the module: the console displays the Wi-Fi connection then "MQTT connection... ok". On the broker side, mosquitto_sub -t 'esp12e/#' should display an RSSI every 5 seconds. Send mosquitto_pub -t esp12e/led -m ON: the module's LED turns on immediately; "OFF" turns it off. Stop the broker: the module displays failures then reconnects on its own when the broker comes back.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials