time_sntp.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #include "time_sntp.h"
  2. #include <string>
  3. #include <time.h>
  4. #include <sys/time.h>
  5. #include "freertos/FreeRTOS.h"
  6. #include "freertos/task.h"
  7. #include "freertos/event_groups.h"
  8. #include "esp_system.h"
  9. #include "esp_log.h"
  10. #include "esp_attr.h"
  11. #include "esp_sleep.h"
  12. #include "esp_netif_sntp.h"
  13. #include "../../include/defines.h"
  14. #include "ClassLogFile.h"
  15. #include "configFile.h"
  16. #include "Helper.h"
  17. static const char *TAG = "SNTP";
  18. static std::string timeZone = "";
  19. static std::string timeServer = "undefined";
  20. static bool useNtp = true;
  21. static bool timeWasNotSetAtBoot = false;
  22. static bool timeWasNotSetAtBoot_PrintStartBlock = false;
  23. std::string getNtpStatusText(sntp_sync_status_t status);
  24. static void setTimeZone(std::string _tzstring);
  25. static std::string getServerName(void);
  26. int LocalTimeToUTCOffsetSeconds;
  27. std::string ConvertTimeToString(time_t _time, const char * frm)
  28. {
  29. struct tm timeinfo;
  30. char strftime_buf[64];
  31. localtime_r(&_time, &timeinfo);
  32. strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
  33. std::string result(strftime_buf);
  34. return result;
  35. }
  36. std::string getCurrentTimeString(const char * frm)
  37. {
  38. time_t now;
  39. struct tm timeinfo;
  40. time(&now);
  41. char strftime_buf[64];
  42. localtime_r(&now, &timeinfo);
  43. strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
  44. std::string result(strftime_buf);
  45. return result;
  46. }
  47. void time_sync_notification_cb(struct timeval *tv)
  48. {
  49. if (timeWasNotSetAtBoot_PrintStartBlock) {
  50. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  51. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "==================== Start ======================");
  52. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "== Logs before time sync -> log_1970-01-01.txt ==");
  53. timeWasNotSetAtBoot_PrintStartBlock = false;
  54. }
  55. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is synced with NTP Server " +
  56. getServerName() + ": " + getCurrentTimeString("%Y-%m-%d %H:%M:%S"));
  57. }
  58. bool time_manual_reset_sync(void)
  59. {
  60. sntp_restart();
  61. // sntp_init();
  62. int retry = 0;
  63. const int retry_count = 10;
  64. while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
  65. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Waiting for system time to be set... " + std::to_string(retry) + "/" + std::to_string(retry_count));
  66. vTaskDelay(2000 / portTICK_PERIOD_MS);
  67. }
  68. if (retry >= retry_count)
  69. return false;
  70. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Waiting for system time successfull with " + std::to_string(retry) + "/" + std::to_string(retry_count));
  71. return true;
  72. }
  73. int getUTCOffsetSeconds(std::string &zeitzone)
  74. {
  75. int offset = 0;
  76. int vorzeichen = 1;
  77. int minuten = 0;
  78. int stunden = 0;
  79. time_t now;
  80. struct tm timeinfo;
  81. time (&now);
  82. localtime_r(&now, &timeinfo);
  83. char buffer[80];
  84. strftime(buffer, 80, "%z", &timeinfo);
  85. zeitzone = std::string(buffer);
  86. if (zeitzone.length() == 5)
  87. {
  88. if (zeitzone[0] == '-')
  89. vorzeichen = -1;
  90. stunden = stoi(zeitzone.substr(1, 2));
  91. minuten = stoi(zeitzone.substr(3, 2));
  92. offset = ((stunden * 60) + minuten) * 60;
  93. }
  94. return offset;
  95. }
  96. void setTimeZone(std::string _tzstring)
  97. {
  98. setenv("TZ", _tzstring.c_str(), 1);
  99. tzset();
  100. _tzstring = "Time zone set to " + _tzstring;
  101. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _tzstring);
  102. std::string zeitzone;
  103. LocalTimeToUTCOffsetSeconds = getUTCOffsetSeconds(zeitzone);
  104. // std::string zw = std::to_string(LocalTimeToUTCOffsetSeconds);
  105. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "time zone: " + zeitzone + " Delta to UTC: " + std::to_string(LocalTimeToUTCOffsetSeconds) + " seconds");
  106. }
  107. std::string getNtpStatusText(sntp_sync_status_t status) {
  108. if (status == SNTP_SYNC_STATUS_COMPLETED) {
  109. return "Synchronized";
  110. }
  111. else if (status == SNTP_SYNC_STATUS_IN_PROGRESS) {
  112. return "In Progress";
  113. }
  114. else { // SNTP_SYNC_STATUS_RESET
  115. return "Reset";
  116. }
  117. }
  118. bool getTimeIsSet(void) {
  119. time_t now;
  120. struct tm timeinfo;
  121. time(&now);
  122. localtime_r(&now, &timeinfo);
  123. // Is time set? If not, tm_year will be (1970 - 1900).
  124. if ((timeinfo.tm_year < (2022 - 1900))) {
  125. return false;
  126. }
  127. else {
  128. return true;
  129. }
  130. }
  131. /*void restartNtpClient(void) {
  132. // sntp_restart();
  133. // obtain_time();
  134. }*/
  135. bool getUseNtp(void) {
  136. return useNtp;
  137. }
  138. bool getTimeWasNotSetAtBoot(void)
  139. {
  140. return timeWasNotSetAtBoot;
  141. }
  142. std::string getServerName(void) {
  143. char buf[100];
  144. if (sntp_getservername(0)){
  145. snprintf(buf, sizeof(buf), "%s", sntp_getservername(0));
  146. return std::string(buf);
  147. }
  148. else { // we have either IPv4 or IPv6 address
  149. ip_addr_t const *ip = sntp_getserver(0);
  150. if (ipaddr_ntoa_r(ip, buf, sizeof(buf)) != NULL) {
  151. return std::string(buf);
  152. }
  153. }
  154. return "";
  155. }
  156. /**
  157. * Load the TimeZone and TimeServer from the config file and initialize the NTP client
  158. */
  159. bool setupTime() {
  160. time_t now;
  161. struct tm timeinfo;
  162. char strftime_buf[64];
  163. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  164. if (!configFile.ConfigFileExists()){
  165. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setupTime()!");
  166. return false;
  167. }
  168. std::vector<std::string> splitted;
  169. std::string line = "";
  170. bool disabledLine = false;
  171. bool eof = false;
  172. /* Load config from config file */
  173. while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
  174. (line.compare("[System]") != 0)) && !eof) {}
  175. if (eof) {
  176. return false;
  177. }
  178. if (disabledLine) {
  179. return false;
  180. }
  181. while (configFile.getNextLine(&line, disabledLine, eof) &&
  182. !configFile.isNewParagraph(line)) {
  183. splitted = ZerlegeZeile(line, "=");
  184. if (toUpper(splitted[0]) == "TIMEZONE") {
  185. if (splitted.size() <= 1) { // parameter part is empty
  186. timeZone = "";
  187. }
  188. else {
  189. timeZone = splitted[1];
  190. }
  191. }
  192. if (toUpper(splitted[0]) == "TIMESERVER") {
  193. if (splitted.size() <= 1) { // Key has no value => we use this to show it as disabled
  194. timeServer = "";
  195. }
  196. else {
  197. timeServer = splitted[1];
  198. }
  199. }
  200. }
  201. /* Setup NTP Server and Timezone */
  202. if (timeServer == "undefined") {
  203. timeServer = "pool.ntp.org";
  204. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer not defined, using default: " + timeServer);
  205. }
  206. else if (timeServer == "") {
  207. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer config empty, disabling NTP");
  208. useNtp = false;
  209. }
  210. else {
  211. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer: " + timeServer);
  212. }
  213. if (timeZone == "") {
  214. timeZone = "CET-1CEST,M3.5.0,M10.5.0/3";
  215. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeZone not set, using default: " + timeZone);
  216. }
  217. if (useNtp) {
  218. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Configuring NTP Client...");
  219. esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(timeServer.c_str());
  220. config.sync_cb = time_sync_notification_cb;
  221. esp_netif_sntp_init(&config);
  222. setTimeZone(timeZone);
  223. }
  224. /* The RTC keeps the time after a restart (Except on Power On or Pin Reset)
  225. * There should only be a minor correction through NTP */
  226. // Get current time from RTC
  227. time(&now);
  228. localtime_r(&now, &timeinfo);
  229. strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
  230. if (getTimeIsSet()) {
  231. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is already set: " + std::string(strftime_buf));
  232. }
  233. else {
  234. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "The local time is unknown, starting with " + std::string(strftime_buf));
  235. if (useNtp) {
  236. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Once the NTP server provides a time, we will switch to that one");
  237. timeWasNotSetAtBoot = true;
  238. timeWasNotSetAtBoot_PrintStartBlock = true;
  239. }
  240. }
  241. return true;
  242. }