time_sntp.cpp 7.4 KB

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