time_sntp.cpp 7.8 KB

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