87 lines
1.9 KiB
C++
87 lines
1.9 KiB
C++
#include "net.h"
|
|
|
|
#include <WiFi.h>
|
|
#include <esp_sntp.h>
|
|
#include <sys/time.h>
|
|
|
|
#include "heaplog.h"
|
|
#include "settings.h"
|
|
|
|
namespace {
|
|
|
|
bool synced = false;
|
|
bool wasConnected = false;
|
|
|
|
time_t buildTime() {
|
|
static const char months[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
|
|
char month[4] = {__DATE__[0], __DATE__[1], __DATE__[2], '\0'};
|
|
const char* found = strstr(months, month);
|
|
struct tm parts = {};
|
|
parts.tm_mon = found ? (found - months) / 3 : 0;
|
|
parts.tm_mday = atoi(__DATE__ + 4);
|
|
parts.tm_year = atoi(__DATE__ + 7) - 1900;
|
|
parts.tm_hour = atoi(__TIME__);
|
|
parts.tm_min = atoi(__TIME__ + 3);
|
|
parts.tm_sec = atoi(__TIME__ + 6);
|
|
return mktime(&parts);
|
|
}
|
|
|
|
void onTimeSync(struct timeval*) {
|
|
const bool first = !synced;
|
|
synced = true;
|
|
Serial.printf("[net] clock synced: %lu\n", (unsigned long)time(nullptr));
|
|
}
|
|
|
|
} // namespace
|
|
|
|
void net::applyTimezone() {
|
|
setenv("TZ", settings.timezone.c_str(), 1);
|
|
tzset();
|
|
}
|
|
|
|
void net::begin() {
|
|
// Apply Timezone
|
|
applyTimezone();
|
|
|
|
// Floor to Build
|
|
time_t floor = buildTime();
|
|
if (time(nullptr) < floor) {
|
|
struct timeval seed = {.tv_sec = floor, .tv_usec = 0};
|
|
settimeofday(&seed, nullptr);
|
|
}
|
|
|
|
// Latch
|
|
sntp_set_time_sync_notification_cb(onTimeSync);
|
|
}
|
|
|
|
void net::stopWifi() {
|
|
if (WiFi.getMode() == WIFI_MODE_NULL)
|
|
return;
|
|
|
|
// Stop WiFi
|
|
esp_sntp_stop();
|
|
WiFi.mode(WIFI_OFF);
|
|
wasConnected = false;
|
|
logHeap("wifi-off");
|
|
}
|
|
|
|
void net::loop() {
|
|
if (WiFi.getMode() == WIFI_MODE_NULL)
|
|
return;
|
|
|
|
// Store Connection
|
|
bool connected = WiFi.status() == WL_CONNECTED;
|
|
if (connected == wasConnected)
|
|
return;
|
|
wasConnected = connected;
|
|
if (!connected)
|
|
return;
|
|
|
|
// SNMP Sync
|
|
sntp_servermode_dhcp(1);
|
|
configTzTime(settings.timezone.c_str(), "pool.ntp.org", "time.nist.gov");
|
|
Serial.println("[net] wifi up, sntp started");
|
|
}
|
|
|
|
bool net::clockSynced() { return synced; }
|