We continue with the entries intended for communication with ESP8266 or ESP32 seeing how to send a message in Json format via MQTT.
In the previous entry, we saw how to use MQTT asynchronously thanks to the AsyncMqttClient library. On the other hand, we also saw how to use the Json format in both Ajax calls and Websockets.
Now it’s our turn to combine MQTT and Json. The good news is that both combine perfectly. In fact, it is very common for the message we send by MQTT to be in Json format.
So let’s see how to use Json and MQTT in a simple example. As usual, we will start from the previous example, so if you haven’t already done so, it’s worth taking a look.
Remember that in the previous example we used an ESP32 to send a data, which in this case was simply the value millis()
. The same device received the message and displayed it by serial. In this way, we avoid using two devices to test the communication.
Now we are going to do the same, but this time we are going to send the MQTT message in Json format.
The main program remains essentially identical to the previous example. The only difference is that we have added the dependency on the ArduinoJson library.
#include <WiFi.h>
#include <AsyncMqttClient.h>
#include <ArduinoJson.h>
#include "config.h" // Replace with your network data
#include "MQTT.hpp"
#include "ESP32_Utils.hpp"
#include "ESP32_Utils_MQTT_Async.hpp"
void setup(void)
{
Serial.begin(115200);
delay(500);
WiFi.onEvent(WiFiEvent);
InitMqtt();
ConnectWiFi_STA();
}
void loop()
{
PublishMqtt();
delay(1000);
}
What has changed, logically, is the MQTT.hpp file. Remember that in this file we have grouped the specific functionality of our project in terms of MQTT.
As we can see, instead of sending a simple piece of data as in the previous example, where we sent the value of millis(), this time we are sending a text string encoded as Json.
In this Json, we are encoding a ‘data’ field with the value of millis(). Obviously, the Json could be anything else. But, to show the use and test the communication, it is sufficient.
On the other hand, in the OnMqttReceived callback function, we are receiving the MQTT message, decoding the Json, and displaying the ‘data’ field, which contains the value of the sent millis(), by serial port.
#pragma once
const IPAddress MQTT_HOST(192, 168, 1, 150);
const int MQTT_PORT = 1883;
AsyncMqttClient mqttClient;
String GetPayloadContent(char* data, size_t len)
{
String content = "";
for(size_t i = 0; i < len; i++)
{
content.concat(data[i]);
}
return content;
}
void SuscribeMqtt()
{
uint16_t packetIdSub = mqttClient.subscribe("hello/world", 0);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
}
void PublishMqtt()
{
String payload = "";
StaticJsonDocument<300> jsonDoc;
jsonDoc["data"] = millis();
serializeJson(jsonDoc, payload);
mqttClient.publish("hello/world", 0, true, (char*)payload.c_str());
}
void OnMqttReceived(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total)
{
Serial.print("Received on ");
Serial.print(topic);
Serial.print(": ");
String content = GetPayloadContent(payload, len);
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, content);
if(error) return;
unsigned long data = doc["data"];
Serial.print("Millis:");
Serial.println(data);
}
Result
Quite simple. Now we upload everything to our ESP32 and we will see the value of Millis() by serial port, which the same device has sent.
If we use a generic MQTT client like MQTT Explorer, we will see that the messages are indeed sent through the broker. And, if we had more devices, they would all receive the message at the same time.
Basically, we have already seen everything there is in MQTT communication in the backend, that is, between devices. We could give it as many twists as we want but, essentially, there is nothing more to do. Wasn’t it difficult, right? Well, we will not tire of saying that one of the advantages of MQTT is that it is very simple and robust to use.
What we have left to see is how to consume MQTT from the front end. But that will be in the next entry, where we will see how to consume this Json from a web page served by the ESP32 itself. Until next time!
Download the code
All the code from this post is available for download on Github.
Version for ESP8266: https://github.com/luisllamasbinaburo/ESP8266-Examples
Version for ESP32: https://github.com/luisllamasbinaburo/ESP32-Examples