#include <WiFi.h>
#include <HTTPClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h> // For parsing JSON
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "mqtt.eclipseprojects.io"; // MQTT broker
const int mqttPort = 1883;
const char* mqttTopic = "weather/data";// Topic to publish data
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT broker
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT broker");
// Optionally subscribe to topics here if needed
} else {
Serial.print("Failed to connect to MQTT broker. Retrying...");
delay(5000);
}
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("https://api.openweathermap.org/data/2.5/weather?q=Cape%20Town&appid=0897ec6053fd70b586341d0cc5e0d88a&units=metric");
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println(payload); // Print the JSON response
// Parse the JSON response to extract temperature
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
float temperature = doc["main"]["temp"];
// Create a message to send to Node-RED
String message = "Temperature: " + String(temperature) + "°C";
// Send the message to the MQTT broker
client.publish(mqttTopic, message.c_str());
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
client.loop(); // Keep the MQTT connection alive
delay(60000); // Fetch weather data every 60 seconds
}