/*
Set URL in senddata.h
*/
#include <WiFi.h>
#include "wifi-credentials.h"
#include "connection-wifi.h"
#include "gps.h"
#include "dht.h"
#include "senddata.h"
#include "functions.h"
#include "esp_sleep.h" // Include the ESP32 sleep library
const int TIME_TO_SLEEP_IN_SECONDS = 120;
const unsigned long uS_TO_S_FACTOR = 1000000;
const int MAX_RETRY_ATTEMPTS = 10; // Maximum number of retries for WiFi connection
const int RETRY_DELAY_MS = 500; // Delay between retries in milliseconds
bool connectToWiFi() {
Serial.print("Connecting to WiFi");
WiFi.persistent(true); // Retain WiFi credentials across resets
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
int retryCount = 0;
while (WiFi.status() != WL_CONNECTED && retryCount < MAX_RETRY_ATTEMPTS) {
Serial.printf(" (Attempt %d of %d).\n", retryCount + 1, MAX_RETRY_ATTEMPTS); // Output retry count
delay(RETRY_DELAY_MS);
retryCount++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println(" Connected to WiFi");
return true;
} else {
Serial.println(" Failed to connect to WiFi");
return false;
}
}
void gatherDataAndSend() {
Serial.println("Starting data collection");
static char temp[8];
strcpy(temp, readTemperature());
Serial.print("Temperature: ");
Serial.println(temp);
static char latlng[32];
strcpy(latlng, readGPS());
Serial.print("GPS: ");
Serial.println(latlng);
static char data[64];
snprintf(data, sizeof(data), "t=%s&g=%s", temp, latlng);
Serial.print("Data: ");
Serial.println(data);
Serial.println("Sending data");
sendData(data);
Serial.println("Data sent");
}
void sendDataAndSleep() {
gatherDataAndSend();
// Disconnect from WiFi
Serial.println("Disconnecting from WiFi");
WiFi.disconnect(true);
delay(100); // Small delay to ensure WiFi disconnects properly
// Set ESP32 to wake up after defined time
Serial.println("Setting up deep sleep");
Serial.println("Entering deep sleep now...");
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_IN_SECONDS * uS_TO_S_FACTOR);
Serial.flush();
esp_deep_sleep_start();
Serial.println("This line should not be printed"); // This should never be executed
}
void setup() {
Serial.println("Starting...");
Serial.begin(115200);
delay(1000); // Delay to stabilize system after wake-up
if (!connectToWiFi()) {
// Restart ESP32 if unable to connect to WiFi
Serial.println("########## Was unable to connect to WIFI - Restarting ESP32");
ESP.restart();
}
sendDataAndSleep();
}
void loop() {
// Loop should not be called, as the ESP32 is in deep sleep mode
}