#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
// change next line to use with another board/shield
//#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
long randNumber;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverUrl = "http://206.189.0.204:8080/api/v1/thermalsense";
char str[10];
#define MAX_UID 10 /* Change to whatever length you need */
WiFiUDP ntpUDP;
// By default 'pool.ntp.org' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP,"pool.ntp.org", 3 * 3600);
const char * generateUID() {
/* Change to allowable characters */
const char possible[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static char uid[MAX_UID + 1];
for (int p = 0, i = 0; i < MAX_UID; i++) {
int r = random(0, strlen(possible));
uid[p++] = possible[r];
}
uid[MAX_UID] = '\0';
return uid;
}
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
//Serial.println("Connected to WiFi");
// Perform HTTP POST
//timeClient.setTimeOffset(10800);
timeClient.begin();
//postData();
//getEpoch();
}
void loop() {
randNumber = random(20, 35);
Serial.println(randNumber);
timeClient.update();
Serial.println(timeClient.getEpochTime());
postData();
delay(10000);
// The formattedDate comes with the following format:
// 2018-05-28T16:00:13Z
// We need to extract date and time
//formattedDate = timeClient.getFormattedTime();
//Serial.println(formattedDate);
}
void postData() {
StaticJsonDocument<128> doc;
doc["messageCode"] = generateUID();
doc["probeID"] = "TMP002";
doc["param"] = randNumber;
doc["timeStamp"] = timeClient.getEpochTime();
// serializeJson(doc, output);
// Create JSON object
// StaticJsonDocument<200> doc;
// JsonObject data = doc.createNestedObject("data");
// data["celcius"] = 25;
// data["fahrenheit"] = 77;
// doc["name"] = "temperature_sensor";
// Serialize JSON to string
String jsonStr;
serializeJson(doc, jsonStr);
// Send HTTP POST request
HTTPClient http;
http.begin(serverUrl);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(jsonStr);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println(jsonStr);
String response = http.getString();
Serial.println(response);
} else {
Serial.print("Error in HTTP POST request: ");
Serial.println(httpResponseCode);
}
http.end();
}