Skip to content

Commit 2db37f6

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 cdd3d5f commit 2db37f6

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
@@ -1103,13 +1103,8 @@ void MyMesh::handleCmdFrame(size_t len) {
11031103
} else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) {
11041104
uint32_t secs;
11051105
memcpy(&secs, &cmd_frame[1], 4);
1106-
uint32_t curr = getRTCClock()->getCurrentTime();
1107-
if (secs >= curr) {
1108-
getRTCClock()->setCurrentTime(secs);
1109-
writeOKFrame();
1110-
} else {
1111-
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
1112-
}
1106+
getRTCClock()->setCurrentTime(secs);
1107+
writeOKFrame();
11131108
} else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
11141109
mesh::Packet* pkt;
11151110
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
@@ -233,7 +233,7 @@ class HomeScreen : public UIScreen {
233233
for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) {
234234
auto a = &recent[i];
235235
if (a->name[0] == 0) continue; // empty slot
236-
int secs = _rtc->getCurrentTime() - a->recv_timestamp;
236+
uint32_t secs = safeElapsedSecs(_rtc->getCurrentTime(), a->recv_timestamp);
237237
if (secs < 60) {
238238
sprintf(tmp, "%ds", secs);
239239
} else if (secs < 60*60) {
@@ -496,7 +496,7 @@ class MsgPreviewScreen : public UIScreen {
496496

497497
auto p = &unread[head];
498498

499-
int secs = _rtc->getCurrentTime() - p->timestamp;
499+
uint32_t secs = safeElapsedSecs(_rtc->getCurrentTime(), p->timestamp);
500500
if (secs < 60) {
501501
sprintf(tmp, "%ds", secs);
502502
} else if (secs < 60*60) {

examples/simple_repeater/MyMesh.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
355355
#if MAX_NEIGHBOURS
356356
// add next neighbour to results
357357
auto neighbour = sorted_neighbours[index + offset];
358-
uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
358+
uint32_t heard_seconds_ago = safeElapsedSecs(getRTCClock()->getCurrentTime(), neighbour->heard_timestamp);
359359
memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
360360
memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
361361
memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
@@ -993,7 +993,7 @@ void MyMesh::formatNeighborsReply(char *reply) {
993993
mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
994994

995995
// add next neighbour
996-
uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
996+
uint32_t secs_ago = safeElapsedSecs(getRTCClock()->getCurrentTime(), neighbour->heard_timestamp);
997997
sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
998998
while (*dp)
999999
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
@@ -618,7 +618,7 @@ bool BaseChatMesh::startConnection(const ContactInfo& contact, uint16_t keep_ali
618618
uint32_t interval = connections[use_idx].keep_alive_millis = ((uint32_t)keep_alive_secs)*1000;
619619
connections[use_idx].next_ping = futureMillis(interval);
620620
connections[use_idx].expected_ack = 0;
621-
connections[use_idx].last_activity = getRTCClock()->getCurrentTime();
621+
connections[use_idx].last_activity_ms = _ms->getMillis();
622622
return true; // success
623623
}
624624

@@ -628,7 +628,7 @@ void BaseChatMesh::stopConnection(const uint8_t* pub_key) {
628628
connections[i].keep_alive_millis = 0; // mark slot as now free
629629
connections[i].next_ping = 0;
630630
connections[i].expected_ack = 0;
631-
connections[i].last_activity = 0;
631+
connections[i].last_activity_ms = 0;
632632
break;
633633
}
634634
}
@@ -644,7 +644,7 @@ bool BaseChatMesh::hasConnectionTo(const uint8_t* pub_key) {
644644
void BaseChatMesh::markConnectionActive(const ContactInfo& contact) {
645645
for (int i = 0; i < MAX_CONNECTIONS; i++) {
646646
if (connections[i].keep_alive_millis > 0 && connections[i].server_id.matches(contact.id)) {
647-
connections[i].last_activity = getRTCClock()->getCurrentTime();
647+
connections[i].last_activity_ms = _ms->getMillis();
648648

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

663663
// re-schedule next KEEP_ALIVE, now that we have heard from server
664664
connections[i].next_ping = futureMillis(connections[i].keep_alive_millis);
@@ -675,14 +675,17 @@ void BaseChatMesh::checkConnections() {
675675
for (int i = 0; i < MAX_CONNECTIONS; i++) {
676676
if (connections[i].keep_alive_millis == 0) continue; // unused slot
677677

678-
uint32_t now = getRTCClock()->getCurrentTime();
679-
uint32_t expire_secs = (connections[i].keep_alive_millis / 1000) * 5 / 2; // 2.5 x keep_alive interval
680-
if (now >= connections[i].last_activity + expire_secs) {
678+
// Monotonic time is immune to RTC clock changes (GPS, NTP, manual sync).
679+
// Assumes light sleep (millis() keeps incrementing). Deep sleep resets millis(),
680+
// but BaseChatMesh is only used by companion_radio which uses light sleep.
681+
unsigned long now = _ms->getMillis();
682+
unsigned long expire_millis = (connections[i].keep_alive_millis * 5UL) / 2; // 2.5 x keep_alive interval
683+
if ((now - connections[i].last_activity_ms) >= expire_millis) {
681684
// connection now lost
682685
connections[i].keep_alive_millis = 0;
683686
connections[i].next_ping = 0;
684687
connections[i].expected_ack = 0;
685-
connections[i].last_activity = 0;
688+
connections[i].last_activity_ms = 0;
686689
continue;
687690
}
688691

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
@@ -208,15 +208,10 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
208208
_callbacks->sendSelfAdvertisement(1500, true); // longer delay, give CLI response time to be sent first
209209
strcpy(reply, "OK - Advert sent");
210210
} else if (memcmp(command, "clock sync", 10) == 0) {
211-
uint32_t curr = getRTCClock()->getCurrentTime();
212-
if (sender_timestamp > curr) {
213-
getRTCClock()->setCurrentTime(sender_timestamp + 1);
214-
uint32_t now = getRTCClock()->getCurrentTime();
215-
DateTime dt = DateTime(now);
216-
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
217-
} else {
218-
strcpy(reply, "ERR: clock cannot go backwards");
219-
}
211+
getRTCClock()->setCurrentTime(sender_timestamp + 1);
212+
uint32_t now = getRTCClock()->getCurrentTime();
213+
DateTime dt = DateTime(now);
214+
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
220215
} else if (memcmp(command, "start ota", 9) == 0) {
221216
if (!_board->startOTAUpdate(_prefs->node_name, reply)) {
222217
strcpy(reply, "Error");
@@ -227,15 +222,10 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
227222
sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
228223
} else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
229224
uint32_t secs = _atoi(&command[5]);
230-
uint32_t curr = getRTCClock()->getCurrentTime();
231-
if (secs > curr) {
232-
getRTCClock()->setCurrentTime(secs);
233-
uint32_t now = getRTCClock()->getCurrentTime();
234-
DateTime dt = DateTime(now);
235-
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
236-
} else {
237-
strcpy(reply, "(ERR: clock cannot go backwards)");
238-
}
225+
getRTCClock()->setCurrentTime(secs);
226+
uint32_t now = getRTCClock()->getCurrentTime();
227+
DateTime dt = DateTime(now);
228+
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
239229
} else if (memcmp(command, "neighbors", 9) == 0) {
240230
_callbacks->formatNeighborsReply(reply);
241231
} else if (memcmp(command, "neighbor.remove ", 16) == 0) {

0 commit comments

Comments
 (0)