refactor: make blink_led non-blocking in the state machine

This commit is contained in:
2026-06-18 17:09:10 +02:00
parent dfc9f0cd94
commit 4d9f08f21f
2 changed files with 72 additions and 56 deletions
+34 -25
View File
@@ -96,11 +96,7 @@ STATE_WAIT_FOR_INPUT = 3
STATE_EVALUATING = 4
STATE_WAIT_BEFORE_RETRY = 5
state = STATE_RINGING
target_blinks = 0
user_presses = 0
last_interaction_time = 0
button_was_pressed = False
BLINK_INTERVAL = 0.3
def set_led(on):
@@ -112,15 +108,6 @@ def set_led(on):
GPIO.output(LED_PIN, GPIO.HIGH)
def blink_led(times):
"""Blinks the LED a specific number of times (blocking)"""
for _ in range(times):
set_led(True)
time.sleep(0.3) # LED on for 300ms
set_led(False)
time.sleep(0.3) # LED off for 300ms
class AlarmClock:
def __init__(self):
self.state = STATE_RINGING
@@ -128,6 +115,9 @@ class AlarmClock:
self.user_presses = 0
self.last_interaction_time = 0
self.button_was_pressed = False
self._blink_phase: int = 0
self._blink_phases: int = 0
self._blink_next_toggle: float | None = None
def update(self, now, is_pressed):
button_just_pressed = False
@@ -150,19 +140,38 @@ class AlarmClock:
self.target_blinks = random.randint(1, 7)
logging.info(f"Blinking {self.target_blinks} times...")
self.state = STATE_BLINKING
self._blink_phase = 0
self._blink_phases = self.target_blinks * 2
self._blink_next_toggle = now + BLINK_INTERVAL
set_led(True)
elif self.state == STATE_BLINKING:
# Move the blink_led out of the update loop for testability,
# or just call it directly. Here we call it.
blink_led(self.target_blinks)
logging.info("Blinking finished. Waiting for input...")
self.state = STATE_WAIT_FOR_INPUT
self.user_presses = 0
self.last_interaction_time = (
time.time()
) # Use time.time() to account for blocking blink_led
if "GPIO" in globals() and hasattr(GPIO, "input"):
self.button_was_pressed = GPIO.input(BUTTON_PIN) == GPIO.LOW
# Non-blocking blink: toggle the LED at fixed intervals so the main
# loop keeps sampling the button and can be interrupted.
if self._blink_next_toggle is None:
# Safety for direct state assignment (e.g. tests).
self._blink_phase = 0
self._blink_phases = self.target_blinks * 2
self._blink_next_toggle = now + BLINK_INTERVAL
set_led(True)
while now >= self._blink_next_toggle:
self._blink_phase += 1
self._blink_next_toggle += BLINK_INTERVAL
if self._blink_phase >= self._blink_phases:
set_led(False)
self._blink_phase = 0
self._blink_phases = 0
self._blink_next_toggle = None
logging.info("Blinking finished. Waiting for input...")
self.state = STATE_WAIT_FOR_INPUT
self.user_presses = 0
self.last_interaction_time = now
if "GPIO" in globals() and hasattr(GPIO, "input"):
self.button_was_pressed = GPIO.input(BUTTON_PIN) == GPIO.LOW
break
else:
set_led(self._blink_phase % 2 == 0)
elif self.state == STATE_WAIT_FOR_INPUT:
set_led(is_pressed)