Hopefully this will be a quick one, I am using a ESP32 to read values from a MQTT server over Wi-Fi.
The topic is in this format:
{"time":"15:19:49","windspeed":3,"windgust":10,"wgustTM":16,"YearGustH":39,"winddir":133,"press":29.95,"presstrend":"Rising slowly","temp":42.2,"temptrendtext":"Rising","tempTH":42.5,"tempTL":37.0,"dew":39.2,"heatindex":42.2,"wchill":40.1,"feelslike":40.1,"tempH":96.7,"tempL":-10.6,"outhum":89,"raintoday":0.26,"rainrate":0.00,"rmonth":1.00,"ryear":30.38,"IsRaining":0,"moonphase":"Waning Crescent",}
My code successfully connects and can publish to the MQTT server; however, I can’t figure out how to extract the values for say, "temp":42.2,"
I think I am close but could use some help to get this working!
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const size_t capacity = JSON_OBJECT_SIZE(2) + JSON_ARRAY_SIZE(2) + 60; // Example capacity
StaticJsonDocument<capacity> doc;
// WiFi
const char *ssid = "";
const char *password = "";
// MQTT Broker
const char *mqtt_broker = "";
const char *topic = "TEST";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// Connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the Wi-Fi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
if (client.connect(client_id.c_str())) {
Serial.println("Connected to the MQTT Broker");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// Publish and subscribe
//Client.publish(topic, "Hi, I'm ESP32 ^^");
client.subscribe("CumulusMX/DataUpdate");
}
void callback(char *topic, byte *payload, unsigned int length) {
char jsonString[length + 1];
memcpy(jsonString, payload, length);
jsonString[length] = '\0';
DeserializationError error = deserializeJson(doc, jsonString);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
int windspeed = doc["windspeed"];
int winddir = doc["winddir"];
float press = doc["press"];
Serial.println(windspeed);
Serial.println(winddir);
}
void loop() {
client.loop();
}