update simulator rtc counter improvements to match real hardware

This commit is contained in:
redraw
2026-01-22 10:29:52 -03:00
parent 7d4a80a29d
commit a3664b0789
+6 -22
View File
@@ -39,7 +39,6 @@ static uint32_t counter_interval;
static uint32_t counter; static uint32_t counter;
static uint32_t reference_timestamp; static uint32_t reference_timestamp;
static double next_tick_time; static double next_tick_time;
static double rtc_start_time;
#define WATCH_RTC_N_COMP_CB 8 #define WATCH_RTC_N_COMP_CB 8
@@ -111,18 +110,7 @@ unix_timestamp_t watch_rtc_get_unix_time(void) {
} }
rtc_counter_t watch_rtc_get_counter(void) { rtc_counter_t watch_rtc_get_counter(void) {
if (!counter_interval) { return counter;
return counter; // RTC not running
}
// Calculate current counter from high-precision time
double now = EM_ASM_DOUBLE({ return performance.now(); });
double elapsed_ms = now - rtc_start_time;
// Convert elapsed time to RTC ticks (RTC_CNT_HZ = 128 Hz)
double elapsed_ticks = (elapsed_ms * RTC_CNT_HZ) / 1000.0;
return (rtc_counter_t)elapsed_ticks;
} }
uint32_t watch_rtc_get_frequency(void) { uint32_t watch_rtc_get_frequency(void) {
@@ -183,7 +171,6 @@ static void _watch_schedule_next_tick(void) {
if (!counter_interval) return; if (!counter_interval) return;
double now = EM_ASM_DOUBLE({ return performance.now(); }); double now = EM_ASM_DOUBLE({ return performance.now(); });
double drift = now - next_tick_time;
// Target interval in ms // Target interval in ms
double ms = 1000.0 / (double)RTC_CNT_HZ; double ms = 1000.0 / (double)RTC_CNT_HZ;
@@ -192,13 +179,12 @@ static void _watch_schedule_next_tick(void) {
next_tick_time += ms; next_tick_time += ms;
double delay = next_tick_time - now; double delay = next_tick_time - now;
// Ensure we don't schedule negative or zero delays // If we're behind, schedule immediately
if (delay < 0.1) { if (delay < 0) {
delay = 0.1; delay = 0;
next_tick_time = now + delay;
} }
emscripten_async_call(_watch_increase_counter, NULL, (int)delay); emscripten_async_call(_watch_increase_counter, NULL, delay);
} }
static void _watch_increase_counter(void *userData) { static void _watch_increase_counter(void *userData) {
@@ -385,9 +371,7 @@ void watch_rtc_enable(bool en)
if (en) { if (en) {
// Use drift-correcting timer instead of fixed setInterval // Use drift-correcting timer instead of fixed setInterval
counter_interval = 1; // Non-zero to indicate enabled counter_interval = 1; // Non-zero to indicate enabled
rtc_start_time = EM_ASM_DOUBLE({ return performance.now(); }); next_tick_time = EM_ASM_DOUBLE({ return performance.now(); });
next_tick_time = rtc_start_time;
counter = 0;
_watch_schedule_next_tick(); _watch_schedule_next_tick();
} else { } else {
counter_interval = 0; counter_interval = 0;