#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* azureIoTHubConnectionString = "nexford--test.azure-devices.net";
const char* endpoint = "devices/lovee";
WiFiServer server(80);
const int ledPin = 2; // Pin connected to the LED
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
// We specify the WiFi channel number (6) when calling WiFi.begin().
// This skips the WiFi scanning phase and saves about 4 seconds
// when connecting to the WiFi.
WiFi.begin(ssid, password, 6);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.print(WiFi.localIP());
Serial.println("");
}
void loop() {
// Simulate sending telemetry data to Azure IoT Hub
sendTelemetryToAzure("Temperature", "25.5");
digitalWrite(ledPin, HIGH);
delay(5000); // Simulate sending data every 5 seconds
}
void sendTelemetryToAzure(const char* metric, const char* value) {
// Simulate sending telemetry data to Azure IoT Hub
Serial.printf("Sending telemetry to Azure: %s=%s\n", metric, value);
// Create an HTTP client
HTTPClient http;
String url = String("https://") + azureIoTHubConnectionString + String("/") + endpoint + String("/messages/events?api-version=2020-03-13");
String payload = String("{\"") + metric + "\":\"" + value + "\"}";
String authorizationHeader = "SharedAccessSignature sr=Nexford--test.azure-devices.net%2Fdevices%2Flovee&sig=WYQMwWOv79upa3fXxID%2Bov%2BfdpOciXmxsEX9kdEvMFk%3D&se=1698632698";
http.begin(url);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", authorizationHeader);
// Send the POST request with the payload
int httpResponseCode = http.POST(payload);
// Check for a successful request
if (httpResponseCode > 0) {
digitalWrite(ledPin, !digitalRead(ledPin));
delay(500);
digitalWrite(ledPin, !digitalRead(ledPin));
delay(500);
Serial.printf("HTTP Response Code: %d\n", httpResponseCode);
} else {
Serial.printf("HTTP Request failed: %s\n", http.errorToString(httpResponseCode).c_str());
}
// Close the connection
http.end();
}