time_util.cpp 1.53 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "time_util.h"
#include "sensor_console.h"
#include "config.h"
#include <WiFiUdp.h> // required for NTP
#include "src/lib/NTPClient-master/NTPClient.h" // NTP

namespace config {
  const char *ntp_server = NTP_SERVER;
  const long utc_offset_in_seconds = UTC_OFFSET_IN_SECONDS; // UTC+1
}

//NOTE: ESP32 sometimes couldn't access the NTP server, and every loop would take +1000ms
// ifdefs could be used to define functions specific to ESP32, e.g. with configTime
namespace ntp {
  WiFiUDP ntpUDP;
  NTPClient timeClient(ntpUDP, config::ntp_server, config::utc_offset_in_seconds, 60000UL);
  bool connected_at_least_once = false;
  void setLocalTime(int32_t unix_seconds);

  void initialize() {
    timeClient.begin();
    sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F("1618829570 (Sets time to the given UNIX time)"));
  }

  void update() {
    connected_at_least_once |= timeClient.update();
  }

  void getLocalTime(char *timestamp) {
    timeClient.getFormattedDate(timestamp);
  }

  void setLocalTime(int32_t unix_seconds) {
    char time[23];
    timeClient.getFormattedDate(time);
    Serial.print(F("Current time : "));
    Serial.println(time);
    if (connected_at_least_once) {
      Serial.println(F("NTP update already happened. Not changing anything."));
      return;
    }
    Serial.print(F("Setting UNIX time to : "));
    Serial.println(unix_seconds);
    timeClient.setEpochTime(unix_seconds - seconds());
    timeClient.getFormattedDate(time);
    Serial.print(F("Current time : "));
    Serial.println(time);
  }
}