Skip to content

Commit 1cc133b

Browse files
committed
Allow setting RTC clock backwards and fix elapsed-time underflow
Remove the "clock cannot go backwards" restriction from all set-time paths (CLI `time`, `clock sync`, companion radio CMD_SET_DEVICE_TIME, and simple_secure_chat). The ESP32-S3 RTC drifts 5-10% during deep sleep, making backwards correction necessary after even a few days. Add safeElapsedSecs() helper in ArduinoHelpers.h that clamps elapsed time to 0 when a stored timestamp appears to be in the future after a clock correction. Applied to: - Neighbor "heard X ago" displays in simple_repeater - UI time displays in companion_radio - TimeSeriesData calculations in simple_sensor Switch BaseChatMesh connection expiry from RTC timestamps to monotonic millis(), making it immune to RTC adjustments from GPS, NTP, or manual sync. Rename last_activity to last_activity_ms to reflect the change.
1 parent f7e92a7 commit 1cc133b

9 files changed

Lines changed: 39 additions & 46 deletions

File tree

examples/companion_radio/MyMesh.cpp

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,13 +1065,8 @@ void MyMesh::handleCmdFrame(size_t len) {
10651065
} else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) {
10661066
uint32_t secs;
10671067
memcpy(&secs, &cmd_frame[1], 4);
1068-
uint32_t curr = getRTCClock()->getCurrentTime();
1069-
if (secs >= curr) {
1070-
getRTCClock()->setCurrentTime(secs);
1071-
writeOKFrame();
1072-
} else {
1073-
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
1074-
}
1068+
getRTCClock()->setCurrentTime(secs);
1069+
writeOKFrame();
10751070
} else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
10761071
mesh::Packet* pkt;
10771072
if (_prefs.advert_loc_policy == ADVERT_LOC_NONE) {

examples/companion_radio/ui-new/UITask.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ class HomeScreen : public UIScreen {
225225
for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) {
226226
auto a = &recent[i];
227227
if (a->name[0] == 0) continue; // empty slot
228-
int secs = _rtc->getCurrentTime() - a->recv_timestamp;
228+
uint32_t secs = safeElapsedSecs(_rtc->getCurrentTime(), a->recv_timestamp);
229229
if (secs < 60) {
230230
sprintf(tmp, "%ds", secs);
231231
} else if (secs < 60*60) {
@@ -488,7 +488,7 @@ class MsgPreviewScreen : public UIScreen {
488488

489489
auto p = &unread[head];
490490

491-
int secs = _rtc->getCurrentTime() - p->timestamp;
491+
uint32_t secs = safeElapsedSecs(_rtc->getCurrentTime(), p->timestamp);
492492
if (secs < 60) {
493493
sprintf(tmp, "%ds", secs);
494494
} else if (secs < 60*60) {

examples/simple_repeater/MyMesh.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
343343

344344
// add next neighbour to results
345345
auto neighbour = sorted_neighbours[index + offset];
346-
uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
346+
uint32_t heard_seconds_ago = safeElapsedSecs(getRTCClock()->getCurrentTime(), neighbour->heard_timestamp);
347347
memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
348348
memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
349349
memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
@@ -934,7 +934,7 @@ void MyMesh::formatNeighborsReply(char *reply) {
934934
mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
935935

936936
// add next neighbour
937-
uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
937+
uint32_t secs_ago = safeElapsedSecs(getRTCClock()->getCurrentTime(), neighbour->heard_timestamp);
938938
sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
939939
while (*dp)
940940
dp++; // find end of string

examples/simple_secure_chat/main.cpp

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,13 +158,8 @@ class MyMesh : public BaseChatMesh, ContactVisitor {
158158
}
159159

160160
void setClock(uint32_t timestamp) {
161-
uint32_t curr = getRTCClock()->getCurrentTime();
162-
if (timestamp > curr) {
163-
getRTCClock()->setCurrentTime(timestamp);
164-
Serial.println(" (OK - clock set!)");
165-
} else {
166-
Serial.println(" (ERR: clock cannot go backwards)");
167-
}
161+
getRTCClock()->setCurrentTime(timestamp);
162+
Serial.println(" (OK - clock set!)");
168163
}
169164

170165
void importCard(const char* command) {

examples/simple_sensor/TimeSeriesData.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "TimeSeriesData.h"
2+
#include <helpers/ArduinoHelpers.h>
23

34
void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) {
45
uint32_t now = clock->getCurrentTime();
@@ -12,7 +13,7 @@ void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) {
1213

1314
void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const {
1415
int i = next, n = num_slots;
15-
uint32_t ago = clock->getCurrentTime() - last_timestamp;
16+
uint32_t ago = safeElapsedSecs(clock->getCurrentTime(), last_timestamp);
1617
int num_values = 0;
1718
float total = 0.0f;
1819

src/helpers/ArduinoHelpers.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@
33
#include <Mesh.h>
44
#include <Arduino.h>
55

6+
// Safe elapsed time calculation that handles clock corrections (when RTC is set backwards).
7+
// Returns 0 if recorded_timestamp is in the "future" relative to current_time.
8+
inline uint32_t safeElapsedSecs(uint32_t current_time, uint32_t recorded_timestamp) {
9+
if (recorded_timestamp > current_time) {
10+
return 0; // Clock was corrected backwards; treat as "just now"
11+
}
12+
return current_time - recorded_timestamp;
13+
}
14+
615
class VolatileRTCClock : public mesh::RTCClock {
716
uint32_t base_time;
817
uint64_t accumulator;

src/helpers/BaseChatMesh.cpp

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ bool BaseChatMesh::startConnection(const ContactInfo& contact, uint16_t keep_ali
609609
uint32_t interval = connections[use_idx].keep_alive_millis = ((uint32_t)keep_alive_secs)*1000;
610610
connections[use_idx].next_ping = futureMillis(interval);
611611
connections[use_idx].expected_ack = 0;
612-
connections[use_idx].last_activity = getRTCClock()->getCurrentTime();
612+
connections[use_idx].last_activity_ms = _ms->getMillis();
613613
return true; // success
614614
}
615615

@@ -619,7 +619,7 @@ void BaseChatMesh::stopConnection(const uint8_t* pub_key) {
619619
connections[i].keep_alive_millis = 0; // mark slot as now free
620620
connections[i].next_ping = 0;
621621
connections[i].expected_ack = 0;
622-
connections[i].last_activity = 0;
622+
connections[i].last_activity_ms = 0;
623623
break;
624624
}
625625
}
@@ -635,7 +635,7 @@ bool BaseChatMesh::hasConnectionTo(const uint8_t* pub_key) {
635635
void BaseChatMesh::markConnectionActive(const ContactInfo& contact) {
636636
for (int i = 0; i < MAX_CONNECTIONS; i++) {
637637
if (connections[i].keep_alive_millis > 0 && connections[i].server_id.matches(contact.id)) {
638-
connections[i].last_activity = getRTCClock()->getCurrentTime();
638+
connections[i].last_activity_ms = _ms->getMillis();
639639

640640
// re-schedule next KEEP_ALIVE, now that we have heard from server
641641
connections[i].next_ping = futureMillis(connections[i].keep_alive_millis);
@@ -649,7 +649,7 @@ ContactInfo* BaseChatMesh::checkConnectionsAck(const uint8_t* data) {
649649
if (connections[i].keep_alive_millis > 0 && memcmp(&connections[i].expected_ack, data, 4) == 0) {
650650
// yes, got an ack for our keep_alive request!
651651
connections[i].expected_ack = 0;
652-
connections[i].last_activity = getRTCClock()->getCurrentTime();
652+
connections[i].last_activity_ms = _ms->getMillis();
653653

654654
// re-schedule next KEEP_ALIVE, now that we have heard from server
655655
connections[i].next_ping = futureMillis(connections[i].keep_alive_millis);
@@ -666,14 +666,17 @@ void BaseChatMesh::checkConnections() {
666666
for (int i = 0; i < MAX_CONNECTIONS; i++) {
667667
if (connections[i].keep_alive_millis == 0) continue; // unused slot
668668

669-
uint32_t now = getRTCClock()->getCurrentTime();
670-
uint32_t expire_secs = (connections[i].keep_alive_millis / 1000) * 5 / 2; // 2.5 x keep_alive interval
671-
if (now >= connections[i].last_activity + expire_secs) {
669+
// Monotonic time is immune to RTC clock changes (GPS, NTP, manual sync).
670+
// Assumes light sleep (millis() keeps incrementing). Deep sleep resets millis(),
671+
// but BaseChatMesh is only used by companion_radio which uses light sleep.
672+
unsigned long now = _ms->getMillis();
673+
unsigned long expire_millis = (connections[i].keep_alive_millis * 5UL) / 2; // 2.5 x keep_alive interval
674+
if ((now - connections[i].last_activity_ms) >= expire_millis) {
672675
// connection now lost
673676
connections[i].keep_alive_millis = 0;
674677
connections[i].next_ping = 0;
675678
connections[i].expected_ack = 0;
676-
connections[i].last_activity = 0;
679+
connections[i].last_activity_ms = 0;
677680
continue;
678681
}
679682

src/helpers/BaseChatMesh.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ class ContactsIterator {
4444
struct ConnectionInfo {
4545
mesh::Identity server_id;
4646
unsigned long next_ping;
47-
uint32_t last_activity;
47+
unsigned long last_activity_ms; // monotonic millis() for connection expiry
4848
uint32_t keep_alive_millis;
4949
uint32_t expected_ack;
5050
};

src/helpers/CommonCLI.cpp

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -205,15 +205,10 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
205205
_callbacks->sendSelfAdvertisement(1500, true); // longer delay, give CLI response time to be sent first
206206
strcpy(reply, "OK - Advert sent");
207207
} else if (memcmp(command, "clock sync", 10) == 0) {
208-
uint32_t curr = getRTCClock()->getCurrentTime();
209-
if (sender_timestamp > curr) {
210-
getRTCClock()->setCurrentTime(sender_timestamp + 1);
211-
uint32_t now = getRTCClock()->getCurrentTime();
212-
DateTime dt = DateTime(now);
213-
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
214-
} else {
215-
strcpy(reply, "ERR: clock cannot go backwards");
216-
}
208+
getRTCClock()->setCurrentTime(sender_timestamp + 1);
209+
uint32_t now = getRTCClock()->getCurrentTime();
210+
DateTime dt = DateTime(now);
211+
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
217212
} else if (memcmp(command, "start ota", 9) == 0) {
218213
if (!_board->startOTAUpdate(_prefs->node_name, reply)) {
219214
strcpy(reply, "Error");
@@ -224,15 +219,10 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
224219
sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
225220
} else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
226221
uint32_t secs = _atoi(&command[5]);
227-
uint32_t curr = getRTCClock()->getCurrentTime();
228-
if (secs > curr) {
229-
getRTCClock()->setCurrentTime(secs);
230-
uint32_t now = getRTCClock()->getCurrentTime();
231-
DateTime dt = DateTime(now);
232-
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
233-
} else {
234-
strcpy(reply, "(ERR: clock cannot go backwards)");
235-
}
222+
getRTCClock()->setCurrentTime(secs);
223+
uint32_t now = getRTCClock()->getCurrentTime();
224+
DateTime dt = DateTime(now);
225+
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
236226
} else if (memcmp(command, "neighbors", 9) == 0) {
237227
_callbacks->formatNeighborsReply(reply);
238228
} else if (memcmp(command, "neighbor.remove ", 16) == 0) {

0 commit comments

Comments
 (0)