diff --git a/include/payload.h b/include/payload.h index b41bb113..8ae86e6e 100644 --- a/include/payload.h +++ b/include/payload.h @@ -55,6 +55,7 @@ public: void addButton(uint8_t value); void addSensor(uint8_t[]); void addTime(time_t value); + void addTimeDiff(int32_t value); #if (PAYLOAD_ENCODER == 1) // format plain diff --git a/src/payload.cpp b/src/payload.cpp index 8afd0b3b..ac310c55 100644 --- a/src/payload.cpp +++ b/src/payload.cpp @@ -16,7 +16,14 @@ uint8_t *PayloadConvert::getBuffer(void) { return buffer; } /* ---------------- plain format without special encoding ---------- */ -#if (PAYLOAD_ENCODER == 1) +void PayloadConvert::addTimeDiff(int32_t value) { + buffer[cursor++] = (byte)((value & 0xFF000000) >> 24); + buffer[cursor++] = (byte)((value & 0x00FF0000) >> 16); + buffer[cursor++] = (byte)((value & 0x0000FF00) >> 8); + buffer[cursor++] = (byte)((value & 0x000000FF)); +} + +#if PAYLOAD_ENCODER == 1 void PayloadConvert::addByte(uint8_t value) { buffer[cursor++] = (value); } @@ -308,8 +315,8 @@ void PayloadConvert::writeBitmap(bool a, bool b, bool c, bool d, bool e, bool f, #elif ((PAYLOAD_ENCODER == 3) || (PAYLOAD_ENCODER == 4)) -void PayloadConvert::addByte(uint8_t value) { - /* +void PayloadConvert::addByte(uint8_t value) { + /* not implemented */ } @@ -486,4 +493,4 @@ void PayloadConvert::addTime(time_t value) { #endif } -#endif \ No newline at end of file +#endif diff --git a/src/timesync.cpp b/src/timesync.cpp index ef50041d..2c5b5db0 100644 --- a/src/timesync.cpp +++ b/src/timesync.cpp @@ -240,7 +240,42 @@ void IRAM_ATTR setMyTime(uint32_t t_sec, uint16_t t_msec, CLOCKIRQ(); // fire clock pps, this advances time 1 sec #endif - setTime(time_to_set); // set the time on top of second + struct timeval tv; + struct timezone tz; + if(gettimeofday(&tv, &tz) != 0) { + ESP_LOGI(TAG, "ERROR gettimeofday"); + } + struct timeval before = tv; + + struct timeval now; + now.tv_sec = t_sec; + now.tv_usec = t_msec; + if(settimeofday(&tv, &tz) != 0) { + ESP_LOGE(TAG, "ERROR settimeofday"); + } + + struct timeval diff; + diff.tv_sec = now.tv_sec-before.tv_sec; + diff.tv_usec = now.tv_usec-before.tv_usec; + + // sum up diff_s and diff_ms to one ms value + int32_t diff_s = diff.tv_sec; + int32_t diff_ms = diff.tv_usec/1000; + int32_t diff_ms_remain = diff_ms / 1000; + diff_s += diff_ms_remain; + diff_ms += -1000*diff_ms_remain; + if(diff_ms < 0) { + diff_s --; + diff_ms += 1000; + } + // cap diff at 24h (= 86,400s) + diff_s = diff_s % 86400; + int32_t timediff_ms = diff_s * 1000 + diff_ms; + + // send diffTime + payload.reset(); + payload.addTimeDiff(timediff_ms); + SendPayload(TIMEDIFFPORT, prio_high); timeSource = mytimesource; // set global variable timesyncer.attach(TIME_SYNC_INTERVAL * 60, timeSync); @@ -264,4 +299,4 @@ void timesync_init() { 1); // CPU core } -#endif \ No newline at end of file +#endif