test: add tests and refactor wecker.py state machine for testability

This commit is contained in:
Markus Graf
2026-05-09 22:31:28 +02:00
parent 1a9bcd7158
commit a7c4febd67
4 changed files with 214 additions and 68 deletions
+94 -68
View File
@@ -32,7 +32,9 @@ try:
pygame.mixer.music.set_volume(1.0)
except Exception as e:
logging.error(f"Error loading audio file: {e}")
sys.exit(1)
# Don't exit in test mode
if 'pytest' not in sys.modules:
sys.exit(1)
# State Machine states for the flow
STATE_RINGING = 0
@@ -50,10 +52,11 @@ button_was_pressed = False
def set_led(on):
"""Turns the LED on or off (LOW = ON, HIGH = OFF)"""
if on:
GPIO.output(LED_PIN, GPIO.LOW)
else:
GPIO.output(LED_PIN, GPIO.HIGH)
if 'GPIO' in globals() and hasattr(GPIO, 'output'):
if on:
GPIO.output(LED_PIN, GPIO.LOW)
else:
GPIO.output(LED_PIN, GPIO.HIGH)
def blink_led(times):
"""Blinks the LED a specific number of times (blocking)"""
@@ -63,90 +66,113 @@ def blink_led(times):
set_led(False)
time.sleep(0.3) # LED off for 300ms
logging.info("Alarm clock started. Music is playing in an endless loop.")
# -1 means the song is played in an endless loop
pygame.mixer.music.play(-1)
class AlarmClock:
def __init__(self):
self.state = STATE_RINGING
self.target_blinks = 0
self.user_presses = 0
self.last_interaction_time = 0
self.button_was_pressed = False
set_led(False) # LED off at start
try:
while True:
now = time.time()
# Read button state (LOW = pressed, due to Pull-Up)
is_pressed = (GPIO.input(BUTTON_PIN) == GPIO.LOW)
def update(self, now, is_pressed):
button_just_pressed = False
if is_pressed and not button_was_pressed:
button_was_pressed = True
if is_pressed and not self.button_was_pressed:
self.button_was_pressed = True
button_just_pressed = True
elif not is_pressed and button_was_pressed:
button_was_pressed = False
elif not is_pressed and self.button_was_pressed:
self.button_was_pressed = False
# --- State Machine ---
if state == STATE_RINGING:
if self.state == STATE_RINGING:
if button_just_pressed:
logging.info("Alarm button pressed! Puzzle started. Waiting 3 seconds...")
state = STATE_WAIT_BEFORE_BLINK
last_interaction_time = now
self.state = STATE_WAIT_BEFORE_BLINK
self.last_interaction_time = now
elif state == STATE_WAIT_BEFORE_BLINK:
if now - last_interaction_time >= 3.0:
target_blinks = random.randint(1, 7)
logging.info(f"Blinking {target_blinks} times...")
state = STATE_BLINKING
elif self.state == STATE_WAIT_BEFORE_BLINK:
if now - self.last_interaction_time >= 3.0:
self.target_blinks = random.randint(1, 7)
logging.info(f"Blinking {self.target_blinks} times...")
self.state = STATE_BLINKING
elif state == STATE_BLINKING:
blink_led(target_blinks)
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...")
state = STATE_WAIT_FOR_INPUT
user_presses = 0
last_interaction_time = time.time()
# Update the button state after the blocking blink
button_was_pressed = (GPIO.input(BUTTON_PIN) == GPIO.LOW)
self.state = STATE_WAIT_FOR_INPUT
self.user_presses = 0
self.last_interaction_time = now # Use the current update time!
if 'GPIO' in globals() and hasattr(GPIO, 'input'):
self.button_was_pressed = (GPIO.input(BUTTON_PIN) == GPIO.LOW)
elif state == STATE_WAIT_FOR_INPUT:
# LED lights up as confirmation when the button is pressed
elif self.state == STATE_WAIT_FOR_INPUT:
set_led(is_pressed)
if button_just_pressed:
user_presses += 1
logging.info(f"Button pressed: {user_presses} times")
self.user_presses += 1
logging.info(f"Button pressed: {self.user_presses} times")
if is_pressed:
# As long as the button is held down, we keep resetting the timeout
last_interaction_time = now
self.last_interaction_time = now
# If the button was released and 3 seconds have passed without action -> Evaluation
if not is_pressed and (now - last_interaction_time >= 3.0):
state = STATE_EVALUATING
if not is_pressed and (now - self.last_interaction_time >= 3.0):
self.state = STATE_EVALUATING
elif state == STATE_EVALUATING:
logging.info(f"Evaluation: Target={target_blinks}, Entered={user_presses}")
if user_presses == target_blinks:
elif self.state == STATE_EVALUATING:
logging.info(f"Evaluation: Target={self.target_blinks}, Entered={self.user_presses}")
if self.user_presses == self.target_blinks:
logging.info("Puzzle solved correctly! Alarm clock is stopping.")
pygame.mixer.music.stop()
if 'pygame' in globals() and hasattr(pygame, 'mixer') and pygame.mixer.get_init():
pygame.mixer.music.stop()
set_led(False)
break # Exits the while loop and thus the program
return False # Indicate we should stop running
else:
logging.info("Incorrect input! Waiting 3 seconds before retrying...")
state = STATE_WAIT_BEFORE_RETRY
last_interaction_time = time.time()
self.state = STATE_WAIT_BEFORE_RETRY
self.last_interaction_time = time.time()
set_led(False)
elif state == STATE_WAIT_BEFORE_RETRY:
if now - last_interaction_time >= 5.0:
# Puzzle is repeated with a new random blink count
target_blinks = random.randint(1, 7)
logging.info(f"New attempt! Blinking {target_blinks} times...")
state = STATE_BLINKING
elif self.state == STATE_WAIT_BEFORE_RETRY:
if now - self.last_interaction_time >= 5.0:
self.target_blinks = random.randint(1, 7)
logging.info(f"New attempt! Blinking {self.target_blinks} times...")
self.state = STATE_BLINKING
return True # Keep running
time.sleep(0.02) # Short polling interval to save CPU and ensure good responsiveness (20ms)
except KeyboardInterrupt:
logging.info("Manually aborted (CTRL+C).")
finally:
pygame.mixer.quit()
GPIO.cleanup()
logging.info("Program finished.")
def run_alarm(test_mode=False):
logging.info("Alarm clock started. Music is playing in an endless loop.")
if 'pygame' in globals() and hasattr(pygame, 'mixer') and pygame.mixer.get_init():
pygame.mixer.music.play(-1)
set_led(False) # LED off at start
clock = AlarmClock()
try:
while True:
now = time.time()
if 'GPIO' in globals() and hasattr(GPIO, 'input'):
is_pressed = (GPIO.input(BUTTON_PIN) == GPIO.LOW)
else:
is_pressed = False
keep_running = clock.update(now, is_pressed)
if not keep_running or test_mode:
break
time.sleep(0.02)
except KeyboardInterrupt:
logging.info("Manually aborted (CTRL+C).")
if __name__ == "__main__":
try:
run_alarm()
finally:
pygame.mixer.quit()
GPIO.cleanup()
logging.info("Program finished.")