@@ -182,11 +182,28 @@ void SystemTask::Work() {
182182 measureBatteryTimer = xTimerCreate (" measureBattery" , batteryMeasurementPeriod, pdTRUE, this , MeasureBatteryTimerCallback);
183183 xTimerStart (measureBatteryTimer, portMAX_DELAY);
184184
185+ constexpr TickType_t stateUpdatePeriod = pdMS_TO_TICKS (100 );
186+ // Stores when the state (motion, watchdog, time persistence etc) was last updated
187+ // If there are many events being received by the message queue, this prevents
188+ // having to update motion etc after every single event, which is bad
189+ // for efficiency and for motion wake algorithms which expect motion readings
190+ // to be 100ms apart
191+ TickType_t lastStateUpdate = xTaskGetTickCount () - stateUpdatePeriod; // Force immediate run
192+ TickType_t elapsed;
193+
185194#pragma clang diagnostic push
186195#pragma ide diagnostic ignored "EndlessLoop"
187196 while (true ) {
188197 Messages msg;
189- if (xQueueReceive (systemTasksMsgQueue, &msg, 100 ) == pdTRUE) {
198+
199+ elapsed = xTaskGetTickCount () - lastStateUpdate;
200+ TickType_t waitTime;
201+ if (elapsed >= stateUpdatePeriod) {
202+ waitTime = 0 ;
203+ } else {
204+ waitTime = stateUpdatePeriod - elapsed;
205+ }
206+ if (xQueueReceive (systemTasksMsgQueue, &msg, waitTime) == pdTRUE) {
190207 switch (msg) {
191208 case Messages::EnableSleeping:
192209 wakeLocksHeld--;
@@ -359,23 +376,25 @@ void SystemTask::Work() {
359376 break ;
360377 }
361378 }
362-
363- UpdateMotion ();
364- if (isBleDiscoveryTimerRunning) {
365- if (bleDiscoveryTimer == 0 ) {
366- isBleDiscoveryTimerRunning = false ;
367- // Services discovery is deferred from 3 seconds to avoid the conflicts between the host communicating with the
368- // target and vice-versa. I'm not sure if this is the right way to handle this...
369- nimbleController.StartDiscovery ();
370- } else {
371- bleDiscoveryTimer--;
379+ elapsed = xTaskGetTickCount () - lastStateUpdate;
380+ if (elapsed >= stateUpdatePeriod) {
381+ UpdateMotion ();
382+ if (isBleDiscoveryTimerRunning) {
383+ if (bleDiscoveryTimer == 0 ) {
384+ isBleDiscoveryTimerRunning = false ;
385+ // Services discovery is deferred from 3 seconds to avoid the conflicts between the host communicating with the
386+ // target and vice-versa. I'm not sure if this is the right way to handle this...
387+ nimbleController.StartDiscovery ();
388+ } else {
389+ bleDiscoveryTimer--;
390+ }
372391 }
373- }
374-
375- monitor. Process ();
376- NoInit_BackUpTime = dateTimeController. CurrentDateTime ();
377- if ( nrf_gpio_pin_read (PinMap::Button) == 0 ) {
378- watchdog. Reload ();
392+ monitor. Process ();
393+ NoInit_BackUpTime = dateTimeController. CurrentDateTime ();
394+ if ( nrf_gpio_pin_read (PinMap::Button) == 0 ) {
395+ watchdog. Reload ();
396+ }
397+ lastStateUpdate = xTaskGetTickCount ();
379398 }
380399 }
381400#pragma clang diagnostic pop
0 commit comments