Skip to content

Proposal for maintaining relative time during deep sleep on ESP32 #839

Open
@cmidgley

Description

@cmidgley

Moving from a gitter.im discussion...

When an ESP32 runs in light sleep, both Date() (time of day) and Time() (milliseconds since boot) are able track time. However, in deep sleep, only Date() has the correct time upon wakeup. You can not just use Date() for tracking milliseconds, as operations such as timesync change the time and it is no longer relative to system boot.

To address this, rather than a prior proposal to track time spent asleep, I propose we always use the system clock (gettimeofday) for time (time of day, and time since boot) but then track time change requests as an offset to be used for relative time.

We would introduce a static time offset variable, millisecondsOffset in this example, that would be saved in RTC slow memory (default at 0) so that it is retained across deep and light sleeps. The modMilliseconds macro, which currently uses esp_timer_get_time, would be changed to use a function that consumes gettimeofday to get milliseconds and add the offset, such as:

#define modMilliseconds() modMillisecondsRTCOffset()

uint32_t RTC_SLOW_ATTR millisecondsOffset = 0;

uint32_t modMillisecondsRTCOffset() {
   struct timeval tv_now;
   gettimeofday(&tv_now, NULL);
   return tv_now.tv_sec - millisecondsOffset;
}

A similar approach would be taken for a modification to 'modSetTime' , to compute the delta between the requested time and the current time, and store that in the offset (millisecondsOffset).

This approach eliminates the need to know if we go to sleep or not, eliminates induced drift, doesn't need to execute before the VM starts or worry about fastest-time-to-execution and is totally contained within the host implementation (I believe everything is located in xsHost) and exposes no new APIs for developers to consume. Thanks to ESP-IDF, the gettimeofday uses the high accuracy clock and only downshifts to the low accuracy during sleep, so there should be no loss of accuracy.

The only downside I've thought of so far is perhaps there is a small performance penalty, but that would really depend on the implementation details of esp_timer_get_time and gettimeofday, and likewise on modSetTime.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions