@@ -47,7 +47,7 @@ class SnapTime {
4747 }
4848
4949 // / Record the last time difference between client and server
50- void setTimeDifferenceClientServerMs (int diff) { time_diff = diff; }
50+ void setTimeDifferenceClientServerMs (uint32_t diff) { time_diff = diff; }
5151
5252 // / Provides the current server time in ms
5353 uint32_t serverMillis () {
@@ -70,13 +70,13 @@ class SnapTime {
7070 return sec * 1000 + (usec / 1000 );
7171 }
7272
73- bool printLocalTime () {
73+ bool printLocalTime (const char * msg ) {
7474 const timeval val = time ();
7575 auto *tm_result = gmtime (&val.tv_sec );
7676
7777 char str[80 ];
7878 strftime (str, 80 , " %d-%m-%Y %H-%M-%S" , tm_result);
79- ESP_LOGI (TAG, " Time is %s" , str);
79+ ESP_LOGI (TAG, " %s: Time is %s" , msg , str);
8080 return true ;
8181 }
8282
@@ -89,12 +89,21 @@ class SnapTime {
8989 // / updates the actual time
9090 bool setTime (timeval time) {
9191 ESP_LOGI (TAG, " epoch: %lu" , time.tv_sec );
92- #if !CONFIG_SNAPCLIENT_SNTP_ENABLE && CONFIG_SNAPCLIENT_SETTIME_ALLOWD
92+ #if CONFIG_SNAPCLIENT_SET_TIME_ALLOWD
93+ // we do not allow the update when the time is managed via smtp
94+ if (has_sntp_time){
95+ ESP_LOGI (TAG," setTime not relevant because it is managed via sntp" );
96+ return true ;
97+ }
98+ // update epoch
9399 int rc = settimeofday (&time, NULL );
94- printLocalTime ();
100+ if (rc==0 ){
101+ time_diff = time.tv_sec / 1000 ;
102+ }
103+ printLocalTime (" setTime" );
95104 return rc == 0 ;
96105#else
97- ESP_LOGI (TAG, " setTime now allowed/active" );
106+ ESP_LOGI (TAG, " setTime not allowed/active" );
98107 return false ;
99108#endif
100109 }
@@ -113,11 +122,32 @@ class SnapTime {
113122 return delay;
114123 }
115124
125+ void setupSNTPTime () {
126+ #if CONFIG_SNAPCLIENT_SNTP_ENABLE
127+ ESP_LOGD (TAG, " start" );
128+ const char *ntpServer = CONFIG_SNTP_SERVER;
129+ const long gmtOffset_sec = 1 * 60 * 60 ;
130+ const int daylightOffset_sec = 1 * 60 * 60 ;
131+ for (int retry = 0 ; retry < 5 ; retry++) {
132+ configTime (gmtOffset_sec, daylightOffset_sec, ntpServer);
133+ tm time;
134+ if (!getLocalTime (&time)){
135+ continue ;
136+ }
137+ SnapTime::instance ().printLocalTime (" SNTP" );
138+ has_sntp_time = true ;
139+ break ;
140+ }
141+ #endif
142+ }
143+
144+
116145protected:
117- int64_t time_diff = 0 ;
146+ uint32_t time_diff = 0 ;
118147 const char *TAG = " SnapTime" ;
119148 uint32_t server_ms = 0 ;
120149 uint32_t local_ms;
121150 uint16_t message_buffer_delay_ms = 0 ;
122151 timeval server_time;
152+ bool has_sntp_time = false ;
123153};
0 commit comments