#include <Arduino.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <WiFi.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define ENDPOINT_URL "https://iot-rasec.free.beeceptor.com/api/v1/data-records"
HTTPClient httpClient;
#define CONTENT_TYPE_HEADER "Content-Type"
#define APPLICATION_JSON "application/json"
#define DEVICE_ID "HC2971"
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.println("ConnecTED: ");
Serial.println(WiFi.localIP());
httpClient.begin(ENDPOINT_URL);
JsonDocument dataRecord;
dataRecord["deviceId"] = DEVICE_ID;
dataRecord["DISTANCE"] = 250;
String dataRecordResource;
serializeJson(dataRecord, dataRecordResource);
httpClient.addHeader(CONTENT_TYPE_HEADER, APPLICATION_JSON);
httpClient.POST(dataRecordResource);
JsonDocument response;
String responseResource;
responseResource = httpClient.getString();
deserializeJson(response, responseResource);
serializeJsonPretty(response, Serial);
Serial.println();
Serial.println("Distance: ");
Serial.println(response["distance"].as<long>());
httpClient.end();
httpClient.begin(ENDPOINT_URL);
int httpResponseCode = httpClient.GET();
Serial.print("Response Code: ");
Serial.println(httpResponseCode);
responseResource = httpClient.getString();
deserializeJson(response, responseResource);
serializeJsonPretty(response, Serial);
Serial.println("About to show IDs");
JsonArray dataRecords = response.as<JsonArray>();
if(dataRecords != NULL) {
for(JsonVariant dataRecord : dataRecords) {
Serial.print("ID: ");
Serial.println(dataRecord["id"].as<String>());
}
}
httpClient.end();
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}