| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279 |
- #include "time_sntp.h"
- #include <string>
- #include <time.h>
- #include <sys/time.h>
- #include "freertos/FreeRTOS.h"
- #include "freertos/task.h"
- #include "freertos/event_groups.h"
- #include "esp_system.h"
- #include "esp_log.h"
- #include "esp_attr.h"
- #include "esp_sleep.h"
- #include "esp_sntp.h"
- #include "../../include/defines.h"
- #include "websocket.h"
- #include "ClassLogFile.h"
- #include "configFile.h"
- #include "Helper.h"
- static const char *TAG = "SNTP";
- static std::string timeZone = "";
- static std::string timeServer = "undefined";
- static bool useNtp = true;
- static bool timeWasNotSetAtBoot = false;
- static bool timeWasNotSetAtBoot_PrintStartBlock = false;
- std::string getNtpStatusText(sntp_sync_status_t status);
- static void setTimeZone(std::string _tzstring);
- static std::string getServerName(void);
- std::string ConvertTimeToString(time_t _time, const char * frm)
- {
- struct tm timeinfo;
- char strftime_buf[64];
- localtime_r(&_time, &timeinfo);
- strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
- std::string result(strftime_buf);
- return result;
- }
- std::string getCurrentTimeString(const char * frm)
- {
- time_t now;
- struct tm timeinfo;
- time(&now);
- char strftime_buf[64];
- localtime_r(&now, &timeinfo);
- strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
- std::string result(strftime_buf);
- return result;
- }
- void time_sync_notification_cb(struct timeval *tv)
- {
- if (timeWasNotSetAtBoot_PrintStartBlock) {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "==================== Start ======================");
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "== Logs before time sync -> log_1970-01-01.txt ==");
- timeWasNotSetAtBoot_PrintStartBlock = false;
- }
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is synced with NTP Server " +
- getServerName() + ": " + getCurrentTimeString("%Y-%m-%d %H:%M:%S"));
-
- schedule_websocket_message("{\"ntp\": \"synchronized\"}");
- }
- bool time_manual_reset_sync(void)
- {
- sntp_restart();
- // sntp_init();
- int retry = 0;
- const int retry_count = 10;
- while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
- LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Waiting for system time to be set... " + std::to_string(retry) + "/" + std::to_string(retry_count));
- vTaskDelay(2000 / portTICK_PERIOD_MS);
- }
- if (retry >= retry_count)
- return false;
- LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Waiting for system time successfull with " + std::to_string(retry) + "/" + std::to_string(retry_count));
- return true;
- }
- void setTimeZone(std::string _tzstring)
- {
- setenv("TZ", _tzstring.c_str(), 1);
- tzset();
- _tzstring = "Time zone set to " + _tzstring;
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, _tzstring);
- }
- std::string getNtpStatusText(sntp_sync_status_t status) {
- if (status == SNTP_SYNC_STATUS_COMPLETED) {
- return "Synchronized";
- }
- else if (status == SNTP_SYNC_STATUS_IN_PROGRESS) {
- return "In Progress";
- }
- else { // SNTP_SYNC_STATUS_RESET
- return "Reset";
- }
- }
- bool getTimeIsSet(void) {
- time_t now;
- struct tm timeinfo;
- time(&now);
- localtime_r(&now, &timeinfo);
- // Is time set? If not, tm_year will be (1970 - 1900).
- if ((timeinfo.tm_year < (2022 - 1900))) {
- return false;
- }
- else {
- return true;
- }
- }
- /*void restartNtpClient(void) {
- // sntp_restart();
- // obtain_time();
- }*/
- bool getUseNtp(void) {
- return useNtp;
- }
- bool getTimeWasNotSetAtBoot(void)
- {
- return timeWasNotSetAtBoot;
- }
- std::string getServerName(void) {
- char buf[100];
- if (sntp_getservername(0)){
- snprintf(buf, sizeof(buf), "%s", sntp_getservername(0));
- return std::string(buf);
- }
- else { // we have either IPv4 or IPv6 address
- ip_addr_t const *ip = sntp_getserver(0);
- if (ipaddr_ntoa_r(ip, buf, sizeof(buf)) != NULL) {
- return std::string(buf);
- }
- }
- return "";
- }
- /**
- * Load the TimeZone and TimeServer from the config file and initialize the NTP client
- */
- bool setupTime() {
- time_t now;
- struct tm timeinfo;
- char strftime_buf[64];
- ConfigFile configFile = ConfigFile(CONFIG_FILE);
- if (!configFile.ConfigFileExists()){
- LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setupTime()!");
- return false;
- }
- std::vector<std::string> splitted;
- std::string line = "";
- bool disabledLine = false;
- bool eof = false;
- /* Load config from config file */
- while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
- (line.compare("[System]") != 0)) && !eof) {}
- if (eof) {
- return false;
- }
- if (disabledLine) {
- return false;
- }
- while (configFile.getNextLine(&line, disabledLine, eof) &&
- !configFile.isNewParagraph(line)) {
- splitted = ZerlegeZeile(line, "=");
- if (toUpper(splitted[0]) == "TIMEZONE") {
- if (splitted.size() <= 1) { // parameter part is empty
- timeZone = "";
- }
- else {
- timeZone = splitted[1];
- }
- }
- if (toUpper(splitted[0]) == "TIMESERVER") {
- if (splitted.size() <= 1) { // Key has no value => we use this to show it as disabled
- timeServer = "";
- }
- else {
- timeServer = splitted[1];
- }
- }
- }
- /* Setup NTP Server and Timezone */
- if (timeServer == "undefined") {
- timeServer = "pool.ntp.org";
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer not defined, using default: " + timeServer);
- }
- else if (timeServer == "") {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer config empty, disabling NTP");
- useNtp = false;
- }
- else {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer: " + timeServer);
- }
-
- if (timeZone == "") {
- timeZone = "CET-1CEST,M3.5.0,M10.5.0/3";
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeZone not set, using default: " + timeZone);
- }
- if (useNtp) {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Configuring NTP Client...");
- sntp_setoperatingmode(SNTP_OPMODE_POLL);
- sntp_setservername(0, timeServer.c_str());
- sntp_set_time_sync_notification_cb(time_sync_notification_cb);
- setTimeZone(timeZone);
- sntp_init();
- /*
- if (!wait_for_timesync())
- {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Timesync at startup failed.");
- }
- */
- }
- /* The RTC keeps the time after a restart (Except on Power On or Pin Reset)
- * There should only be a minor correction through NTP */
- // Get current time from RTC
- time(&now);
- localtime_r(&now, &timeinfo);
- strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
- if (getTimeIsSet()) {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is already set: " + std::string(strftime_buf));
- }
- else {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "The local time is unknown, starting with " + std::string(strftime_buf));
- if (useNtp) {
- LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Once the NTP server provides a time, we will switch to that one");
- timeWasNotSetAtBoot = true;
- timeWasNotSetAtBoot_PrintStartBlock = true;
- }
- }
- return true;
- }
|