Application Layer Protocol

This article introduces the MQTT protocol for IoT applications and demonstrates how to use an ESP32 to connect to an MQTT server, publish messages, and control a light through subscribed messages. It also provides example code for WiFi setup, MQTT configuration, and message handling.

Application Layer Protocol

Example: MQTT — Publish and Subscribe

Connect to a public MQTT server, publish a "hello world" message to the "outTopic" every 2 seconds, and have the client listen to the "inTopic" to control a light based on the payload content.

Hardware Required:

Example Code: Modify the WiFi SSID and password in the code below to your own WiFi SSID and password, then upload the program to the mainboard.

#include <WiFi.h>
#include <PubSubClient.h>

#define LED  15  // LED control pin (adjust according to actual hardware connections)

/* Network configuration parameters (need user modification) */
const char* ssid = "your_ssid";         // WiFi network name
const char* password = "your_password"; // WiFi password
const char* mqtt_server = "broker.mqtt-dashboard.com"; // MQTT server address

WiFiClient espClient;                   // WiFi client instance
PubSubClient client(espClient);         // MQTT client instance
long lastMsg = 0;                       // Last message timestamp
char msg[50];                           // Message buffer
int value = 0;                          // Test counter

/* WiFi connection initialization */
void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);           // Start WiFi connection

  // Wait for successful connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());                 // Initialize random seed

  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());       // Display obtained IP address
}

/* MQTT message callback function */
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);                  // Display message topic
  Serial.print("] ");
  
  // Print message content
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Control LED based on the first character of the message
  if ((char)payload[0] == '0') {
    digitalWrite(LED, LOW);    // Turn off LED when receiving '0' (low level active)
  } else {
    digitalWrite(LED, HIGH);   // Turn on LED for non-'0' messages
  }
}

/* MQTT reconnection mechanism */
void reconnect() {
  while (!client.connected()) {         // Keep attempting to connect
    Serial.print("Attempting MQTT connection...");
    
    // Generate random client ID (to avoid duplication)
    String clientId = "FireBeetleClient-";
    clientId += String(random(0xffff), HEX);
    
    if (client.connect(clientId.c_str())) {  // Connection attempt
      Serial.println("connected");
      client.publish("outTopic", "hello world"); // Publish initial message
      client.subscribe("inTopic");              // Subscribe to input topic
    } else {
      Serial.print("failed, rc=");      // Display error status code
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

/* Initialization setup */
void setup() {
  pinMode(LED, OUTPUT);              // Initialize LED pin as output
  Serial.begin(115200);              // Start serial communication
  setup_wifi();                      // Connect to WiFi network
  client.setServer(mqtt_server, 1883); // Configure MQTT server
  client.setCallback(callback);      // Set message callback function
}

/* Main loop */
void loop() {
  if (!client.connected()) {         // Maintain MQTT connection
    reconnect();
  }
  client.loop();                     // Process MQTT messages

  // Publish test message every 2 seconds
  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf(msg, 75, "hello world #%ld", value); // Generate message content
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);  // Publish to specified topic
  }
}

Results: The serial output is as follows.

Was this article helpful?

TOP