From 8aefa3b9a613adb6a2f91b28caf40f82415c3151 Mon Sep 17 00:00:00 2001
From: mark9064 <30447455+mark9064@users.noreply.github.com>
Date: Mon, 11 Nov 2024 00:53:43 +0000
Subject: [PATCH] Ignore old GoToRunning messages

---
 src/displayapp/DisplayApp.cpp | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/src/displayapp/DisplayApp.cpp b/src/displayapp/DisplayApp.cpp
index 4b168c43..b1594f19 100644
--- a/src/displayapp/DisplayApp.cpp
+++ b/src/displayapp/DisplayApp.cpp
@@ -292,7 +292,13 @@ void DisplayApp::Refresh() {
     switch (msg) {
       case Messages::GoToSleep:
       case Messages::GoToAOD:
-        if (state != States::Running) {
+        // Checking if SystemTask is sleeping is purely an optimisation.
+        // If it's no longer sleeping since it sent GoToSleep, it has
+        // cancelled the sleep and transitioned directly from
+        // GoingToSleep->Running, so we are about to receive GoToRunning
+        // and can ignore this message. If it wasn't ignored, DisplayApp
+        // would go to sleep and then immediately re-wake
+        if (state != States::Running || !systemTask->IsSleeping()) {
           break;
         }
         while (brightnessController.Level() != Controllers::BrightnessController::Levels::Low) {
@@ -334,7 +340,10 @@ void DisplayApp::Refresh() {
         lv_disp_trig_activity(nullptr);
         break;
       case Messages::GoToRunning:
-        if (state == States::Running) {
+        // If SystemTask is sleeping, the GoToRunning message is old
+        // and must be ignored. Otherwise DisplayApp will use SPI
+        // that is powered down and cause bad behaviour
+        if (state == States::Running || systemTask->IsSleeping()) {
           break;
         }
         if (state == States::AOD) {