time_sntp.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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_sntp.h"
  13. #include "../../include/defines.h"
  14. #include "websocket.h"
  15. #include "ClassLogFile.h"
  16. #include "configFile.h"
  17. #include "Helper.h"
  18. static const char *TAG = "SNTP";
  19. static std::string timeZone = "";
  20. static std::string timeServer = "undefined";
  21. static bool useNtp = true;
  22. static bool timeWasNotSetAtBoot = false;
  23. static bool timeWasNotSetAtBoot_PrintStartBlock = false;
  24. std::string getNtpStatusText(sntp_sync_status_t status);
  25. static void setTimeZone(std::string _tzstring);
  26. static std::string getServerName(void);
  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. schedule_websocket_message("{\"ntp\": \"synchronized\"}");
  58. }
  59. bool time_manual_reset_sync(void)
  60. {
  61. sntp_restart();
  62. // sntp_init();
  63. int retry = 0;
  64. const int retry_count = 10;
  65. while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
  66. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Waiting for system time to be set... " + std::to_string(retry) + "/" + std::to_string(retry_count));
  67. vTaskDelay(2000 / portTICK_PERIOD_MS);
  68. }
  69. if (retry >= retry_count)
  70. return false;
  71. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Waiting for system time successfull with " + std::to_string(retry) + "/" + std::to_string(retry_count));
  72. return true;
  73. }
  74. void setTimeZone(std::string _tzstring)
  75. {
  76. setenv("TZ", _tzstring.c_str(), 1);
  77. tzset();
  78. _tzstring = "Time zone set to " + _tzstring;
  79. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _tzstring);
  80. }
  81. std::string getNtpStatusText(sntp_sync_status_t status) {
  82. if (status == SNTP_SYNC_STATUS_COMPLETED) {
  83. return "Synchronized";
  84. }
  85. else if (status == SNTP_SYNC_STATUS_IN_PROGRESS) {
  86. return "In Progress";
  87. }
  88. else { // SNTP_SYNC_STATUS_RESET
  89. return "Reset";
  90. }
  91. }
  92. bool getTimeIsSet(void) {
  93. time_t now;
  94. struct tm timeinfo;
  95. time(&now);
  96. localtime_r(&now, &timeinfo);
  97. // Is time set? If not, tm_year will be (1970 - 1900).
  98. if ((timeinfo.tm_year < (2022 - 1900))) {
  99. return false;
  100. }
  101. else {
  102. return true;
  103. }
  104. }
  105. /*void restartNtpClient(void) {
  106. // sntp_restart();
  107. // obtain_time();
  108. }*/
  109. bool getUseNtp(void) {
  110. return useNtp;
  111. }
  112. bool getTimeWasNotSetAtBoot(void)
  113. {
  114. return timeWasNotSetAtBoot;
  115. }
  116. std::string getServerName(void) {
  117. char buf[100];
  118. if (sntp_getservername(0)){
  119. snprintf(buf, sizeof(buf), "%s", sntp_getservername(0));
  120. return std::string(buf);
  121. }
  122. else { // we have either IPv4 or IPv6 address
  123. ip_addr_t const *ip = sntp_getserver(0);
  124. if (ipaddr_ntoa_r(ip, buf, sizeof(buf)) != NULL) {
  125. return std::string(buf);
  126. }
  127. }
  128. return "";
  129. }
  130. /**
  131. * Load the TimeZone and TimeServer from the config file and initialize the NTP client
  132. */
  133. bool setupTime() {
  134. time_t now;
  135. struct tm timeinfo;
  136. char strftime_buf[64];
  137. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  138. if (!configFile.ConfigFileExists()){
  139. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setupTime()!");
  140. return false;
  141. }
  142. std::vector<std::string> splitted;
  143. std::string line = "";
  144. bool disabledLine = false;
  145. bool eof = false;
  146. /* Load config from config file */
  147. while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
  148. (line.compare("[System]") != 0)) && !eof) {}
  149. if (eof) {
  150. return false;
  151. }
  152. if (disabledLine) {
  153. return false;
  154. }
  155. while (configFile.getNextLine(&line, disabledLine, eof) &&
  156. !configFile.isNewParagraph(line)) {
  157. splitted = ZerlegeZeile(line, "=");
  158. if (toUpper(splitted[0]) == "TIMEZONE") {
  159. if (splitted.size() <= 1) { // parameter part is empty
  160. timeZone = "";
  161. }
  162. else {
  163. timeZone = splitted[1];
  164. }
  165. }
  166. if (toUpper(splitted[0]) == "TIMESERVER") {
  167. if (splitted.size() <= 1) { // Key has no value => we use this to show it as disabled
  168. timeServer = "";
  169. }
  170. else {
  171. timeServer = splitted[1];
  172. }
  173. }
  174. }
  175. /* Setup NTP Server and Timezone */
  176. if (timeServer == "undefined") {
  177. timeServer = "pool.ntp.org";
  178. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer not defined, using default: " + timeServer);
  179. }
  180. else if (timeServer == "") {
  181. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer config empty, disabling NTP");
  182. useNtp = false;
  183. }
  184. else {
  185. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer: " + timeServer);
  186. }
  187. if (timeZone == "") {
  188. timeZone = "CET-1CEST,M3.5.0,M10.5.0/3";
  189. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeZone not set, using default: " + timeZone);
  190. }
  191. if (useNtp) {
  192. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Configuring NTP Client...");
  193. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  194. sntp_setservername(0, timeServer.c_str());
  195. sntp_set_time_sync_notification_cb(time_sync_notification_cb);
  196. setTimeZone(timeZone);
  197. sntp_init();
  198. /*
  199. if (!wait_for_timesync())
  200. {
  201. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Timesync at startup failed.");
  202. }
  203. */
  204. }
  205. /* The RTC keeps the time after a restart (Except on Power On or Pin Reset)
  206. * There should only be a minor correction through NTP */
  207. // Get current time from RTC
  208. time(&now);
  209. localtime_r(&now, &timeinfo);
  210. strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
  211. if (getTimeIsSet()) {
  212. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is already set: " + std::string(strftime_buf));
  213. }
  214. else {
  215. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "The local time is unknown, starting with " + std::string(strftime_buf));
  216. if (useNtp) {
  217. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Once the NTP server provides a time, we will switch to that one");
  218. timeWasNotSetAtBoot = true;
  219. timeWasNotSetAtBoot_PrintStartBlock = true;
  220. }
  221. }
  222. return true;
  223. }