I have a problem: I am receiving a .json message from Firebase through Node-red and send it via mqtt to ESP32. I can receive the message when something is changed in Firebase due to the callback function of the "ArduinoMqttClient" library, but I would like to get the data as soon as I load the sketch in ESP32.
Currently, when I upload the sketch, the topic is signed but I only get the message if I change something in Firebase.
I don't have much experience with mqtt, I don't know if I can get the message of the topic when loading the program to the ESP32.
Here is the complete code and attached (for curiosity) the flow in node-red:
#include <ArduinoMqttClient.h>
#include <WiFi.h>
#include <ArduinoJson.h>
char ssid[] = "wifi";
char pass[] = "password123";
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const String ORG = "abcde";
const String DEVICE_TYPE = "ESP32";
const String DEVICE_ID = "008";
#define DEVICE_TOKEN "SD78963214!@#$"
const String CLIENT_ID = "d:" + ORG + ":" + DEVICE_TYPE + ":" + DEVICE_ID;
const char broker[] = "abcde.messaging.internetofthings.ibmcloud.com";
int port = 1883;
const char topic[] = "iot-2/cmd/firebaseData/fmt/json";
String json;
void setup() {
Serial.begin(115200);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
Serial.print(".");
delay(5000);
}
mqttClient.setId(CLIENT_ID);
mqttClient.setUsernamePassword("use-token-auth", DEVICE_TOKEN);
if (!mqttClient.connect(broker, port)) {
Serial.println(mqttClient.connectError());
while (1);
}
mqttClient.onMessage(onMqttMessage);
mqttClient.subscribe(topic);
mqttClient.messageTopic();
while (mqttClient.available()) {
char j = mqttClient.read();
json += j;
}
Serial.println("JSON: ");
Serial.println(json);
}
void loop() {
mqttClient.poll();
}
void onMqttMessage(int messageSize)
{
json = "";
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
while (mqttClient.available()) {
char j = mqttClient.read();
json += j;
}
Serial.println("JSON");
Serial.println(json);
}
Thank you!
