#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <time.h>
#include "secrets.h"
void connectToWifi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
Serial.println();
connectToWifi();
}
void loop() {
WiFiClientSecure *client = new WiFiClientSecure;
if (client) {
client->setCACert(rootCACertificate);
HTTPClient https;
Serial.print("[HTTPS] begin...\n");
if (https.begin(*client, "https://arpy8-drishti-api.hf.space/update-data")) { // HTTPS
Serial.print("[HTTPS] POST...\n");
https.addHeader("Content-Type", "application/json");
https.addHeader("Drishti-Auth-Key", "2907");
float tc = random(33, 35);
float hu = random(28, 31);
int mt = map(random(350, 370), 0, 1023, 0, 100);
time_t now;
time(&now);
String httpRequestData = "{\"time\":\"" + String(now) + "\",\"humidity\":\"" + String(hu) + "\",\"temperature\":\"" + String(tc) + "\",\"soil_moisture\":\"" + String(mt) + "\",\"uuid\":\"" + UUID + "\"}";
int httpCode = https.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(String(httpCode) + ": " + httpRequestData);
if (httpCode > 0) {
Serial.printf("[HTTPS] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = https.getString();
Serial.println(payload);
}
}
else {
Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
}
https.end();
}
else {
Serial.println("[HTTPS] Unable to begin connection");
}
delete client;
}
else {
Serial.printf("[HTTPS] Unable to create client\n");
}
Serial.println();
Serial.println("Waiting 5sec before the next round...");
delay(5000);
}