util.cpp 2.22 KB
Newer Older
1
2
3
4
5
6
7
#include "util.h"

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

Eric Duminil's avatar
Eric Duminil committed
8
9
10
11
12
13
14
15
#if defined(ESP8266)
const char *current_board = "ESP8266";
#elif defined(ESP32)
const char *current_board = "ESP32";
#else
const char *current_board = "UNKNOWN";
#endif

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Get last 3 bytes of ESP MAC (worldwide unique)
String macToID() {
  uint8_t mac[6];
  WiFi.macAddress(mac);
  String result;
  for (int i = 3; i < 6; i++) {
    if (mac[i] < 16)
      result += '0';
    result += String(mac[i], HEX);
  }
  result.toLowerCase();
  return result;
}

//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);
35
  bool connected_at_least_once = false;
36
37
38
39
40
41

  void initialize() {
    timeClient.begin();
  }

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

45
46
  void getLocalTime(char *timestamp) {
    timeClient.getFormattedDate(timestamp);
47
  }
48
49
50
51

  void setLocalTime(int32_t unix_seconds) {
    char time[23];
    timeClient.getFormattedDate(time);
Eric Duminil's avatar
Eric Duminil committed
52
    Serial.print(F("Current time : "));
53
    Serial.println(time);
54
55
56
    if (connected_at_least_once) {
      Serial.println(F("NTP update already happened. Not changing anything."));
    }
Eric Duminil's avatar
Eric Duminil committed
57
    Serial.print(F("Setting UNIX time to : "));
58
59
60
    Serial.println(unix_seconds);
    timeClient.setEpochTime(unix_seconds - seconds());
    timeClient.getFormattedDate(time);
Eric Duminil's avatar
Eric Duminil committed
61
    Serial.print(F("Current time : "));
62
63
64
65
    Serial.println(time);
  }
}

Eric Duminil's avatar
Eric Duminil committed
66
67
68
69
70
71
void Ampel::showFreeSpace() {
  Serial.print(F("Free heap space : "));
  Serial.print(get_free_heap_size());
  Serial.println(F(" bytes."));
}

72
Ampel::Ampel() :
Eric Duminil's avatar
Eric Duminil committed
73
    board(current_board), sensorId("ESP" + macToID()), max_loop_duration(0) {
74
75
  sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F(" 1618829570 (Sets time to the given UNIX time)"));
  sensor_console::defineCommand("free", Ampel::showFreeSpace, F(" (Displays available heap space)"));
Eric Duminil's avatar
Eric Duminil committed
76
77
  sensor_console::defineCommand("reset", []() {
    ESP.restart();
78
  }, F(" (Restarts the sensor)"));
79
80
}

Eric Duminil's avatar
Eric Duminil committed
81
Ampel ampel;