#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST"; // Change this to your WiFi SSID
const char* password = ""; // Change this to your WiFi password
const char* device_id = "DHT001";
char* h_sensor_id = "HUM1";
char* t_sensor_id = "TEMP1";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
connectWifi();
}
void loop() {
// put your main code here, to run repeatedly:
float temp = 30;
float hum = 80;
sendDataToWaziCloud(t_sensor_id, temp);
delay(16000); // this speeds up the simulation
sendDataToWaziCloud(h_sensor_id, hum);
delay(16000); // this speeds up the simulation
}
void sendDataToWaziCloud(char* sensor_id, float value) {
// We cancel the send process if our board is not yet connectedd to the internet, and try reconnecting to wifi again.
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi not connected.");
connectWifi();
return;
}
Serial.println("Sending Data ....");
HTTPClient http;
// Initialize the API endpoint to send data. This endpoint is responsible for receiving the data we send
String endpoint = "https://api.waziup.io/api/v2/devices/" + String(device_id) + "/sensors/" + String(sensor_id) + "/value";
http.begin(endpoint);
// Header content for the data to send
http.addHeader("Content-Type", "application/json;charset=utf-8");
http.addHeader("accept", "application/json;charset=utf-8");
// Data to send
String data = "{ \"value\": " + String(value) + " }";
int httpResponseCode = http.POST(data);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("HTTP Response code: " + String(httpResponseCode));
Serial.println("Response: " + response);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
void connectWifi(){
WiFi.begin(ssid, password); //Initiate the wifi connection here with the credentials earlier preset
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print("Connecting to WiFi...: ");
Serial.println(ssid);
}
Serial.println("Connected to WiFi");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
return;
}