This is my first Arduino / ESP32 project and I am working off this Random Nerd Tutorial and have everything working as laid out on this website.
I added additional code to also pull in data from my Davis Weather station via MQTT. I have successfully connected too my MQTT broker and have the following data/format being updated to a global variable named "davisdata".
{"time":"12:20:57","windspeed":9,"winddir":60,"press":29.82}
How do I extract and place just the windspeed into a variable for use elsewhere in my code?
I assume I can do this within the Callback function?
Below is my full sketch, any recommendations for my code will be very well received!
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
#include <PubSubClient.h>
WiFiClient WifiClient;
PubSubClient mqttClient(WifiClient);
char* mqttServer = "*.*.*.*";
int mqttPort = 1883;
char davisdata[1000];
void callback(char* topic, byte* payload, unsigned int length) {
for (int i = 0; i < length; i++) {
davisdata[i]=char(payload[i]);
}
}
void setupMQTT() {
mqttClient.setServer(mqttServer, mqttPort);
mqttClient.setCallback(callback);
}
// Replace with your network credentials
const char* ssid = "**********";
const char* password = "********";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create an Event Source on /events
AsyncEventSource events("/events");
// Json Variable to Hold Sensor Readings
JSONVar readings;
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
// Create a sensor object
Adafruit_BME280 bme; // BME280 connect to ESP32 I2C (GPIO 21 = SDA, GPIO 22 = SCL)
// Init BME280
void initBME(){
if (!bme.begin(0x77)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
}
// Get Sensor Readings and return JSON object
String getSensorReadings(){
readings["temperature"] = String(1.8*bme.readTemperature()+32);
readings["humidity"] = String(bme.readHumidity()+3.1);
readings["pressure"] = String(bme.readPressure()/3312.50);
//readings["windspeed"] = String("10");// Need to bring reading from MQTT topic
String jsonString = JSON.stringify(readings);
return jsonString;
}
// Initialize SPIFFS // Files to build the webpage
void initSPIFFS() {
if (!SPIFFS.begin()) {
Serial.println("An error has occurred while mounting SPIFFS");
}
Serial.println("SPIFFS mounted, ESP32 Booting...");
}
// Connect to WiFi
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
}
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
initSPIFFS();
setupMQTT();
initBME();
initWiFi();
// Connect to MQTT Broker
while (!mqttClient.connected()) {
if (mqttClient.connect("ESP32")){
mqttClient.subscribe("my MQTT topic");
}
else {
Serial.print("Connection failed ");
Serial.print(mqttClient.state());
}
}
// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html", "text/html");
});
server.serveStatic("/", SPIFFS, "/");
// Request for the latest sensor readings
server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){
String json = getSensorReadings();
request->send(200, "application/json", json);
json = String();
});
events.onConnect([](AsyncEventSourceClient *client){
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
}
// send event with message "hello!", id current millis
// and set reconnect delay to 1 second
client->send("hello!", NULL, millis(), 1000);
});
server.addHandler(&events);
// Start server
server.begin();
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Send Events to the client with the Sensor Readings Every 10 seconds
events.send("ping",NULL,millis());
events.send(getSensorReadings().c_str(),"new_readings" ,millis());
lastTime = millis();
}
mqttClient.loop();
}