feat: make command parameter optional in set_alarm mutation

This commit is contained in:
Markus Graf
2026-05-11 15:05:29 +02:00
parent 5b5b845e41
commit ff79224560
10 changed files with 152 additions and 98 deletions
Binary file not shown.
+2 -1
View File
@@ -74,15 +74,16 @@ query {
``` ```
**Set an alarm:** **Set an alarm:**
*(Note: `command` is optional. If omitted, the API will automatically figure out the correct command to start `wecker.py`)*
```graphql ```graphql
mutation { mutation {
setAlarm( setAlarm(
cronExpression: "45 6 * * 1-5", cronExpression: "45 6 * * 1-5",
command: "cd /home/pi/workspace/wecker && /usr/bin/python3 wecker.py > wecker.log 2>&1",
isEnabled: true isEnabled: true
) { ) {
id id
cronExpression cronExpression
command
} }
} }
``` ```
+1
View File
@@ -0,0 +1 @@
17958
+13 -4
View File
@@ -1,6 +1,7 @@
import uuid import uuid
from crontab import CronTab from crontab import CronTab
class CrontabManager: class CrontabManager:
COMMENT_PREFIX = "wecker-alarm:" COMMENT_PREFIX = "wecker-alarm:"
@@ -21,15 +22,23 @@ class CrontabManager:
if job.comment.startswith(self.COMMENT_PREFIX): if job.comment.startswith(self.COMMENT_PREFIX):
alarm_id = job.comment.split(self.COMMENT_PREFIX)[1].strip() alarm_id = job.comment.split(self.COMMENT_PREFIX)[1].strip()
# job.slices is a valid cron slice object, str(job.slices) gives the expression # job.slices is a valid cron slice object, str(job.slices) gives the expression
alarms.append({ alarms.append(
{
"id": alarm_id, "id": alarm_id,
"cron_expression": str(job.slices), "cron_expression": str(job.slices),
"command": job.command, "command": job.command,
"is_enabled": job.is_enabled() "is_enabled": job.is_enabled(),
}) }
)
return alarms return alarms
def set_alarm(self, alarm_id: str | None, cron_expression: str, command: str, is_enabled: bool = True): def set_alarm(
self,
alarm_id: str | None,
cron_expression: str,
command: str,
is_enabled: bool = True,
):
if not alarm_id: if not alarm_id:
alarm_id = str(uuid.uuid4()) alarm_id = str(uuid.uuid4())
+3
View File
@@ -11,6 +11,7 @@ load_dotenv()
API_KEY_NAME = "X-API-Key" API_KEY_NAME = "X-API-Key"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False) api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
def get_api_key(api_key_header: str = Security(api_key_header)): def get_api_key(api_key_header: str = Security(api_key_header)):
expected_api_key = os.getenv("API_KEY") expected_api_key = os.getenv("API_KEY")
if not expected_api_key: if not expected_api_key:
@@ -21,6 +22,7 @@ def get_api_key(api_key_header: str = Security(api_key_header)):
return api_key_header return api_key_header
raise HTTPException(status_code=401, detail="Invalid or missing API Key") raise HTTPException(status_code=401, detail="Invalid or missing API Key")
graphql_app = GraphQLRouter(schema) graphql_app = GraphQLRouter(schema)
app = FastAPI(title="Wecker API") app = FastAPI(title="Wecker API")
@@ -28,6 +30,7 @@ app = FastAPI(title="Wecker API")
# Add auth dependency to the graphql route # Add auth dependency to the graphql route
app.include_router(graphql_app, prefix="/graphql", dependencies=[Depends(get_api_key)]) app.include_router(graphql_app, prefix="/graphql", dependencies=[Depends(get_api_key)])
@app.get("/health") @app.get("/health")
def health_check(): def health_check():
return {"status": "ok"} return {"status": "ok"}
+16 -4
View File
@@ -1,12 +1,16 @@
import strawberry import strawberry
from typing import List, Optional from typing import List, Optional
import os import os
import sys
from pathlib import Path
from api.crontab_manager import CrontabManager from api.crontab_manager import CrontabManager
def get_manager(): def get_manager():
tabfile = os.getenv("TABFILE") tabfile = os.getenv("TABFILE")
return CrontabManager(tabfile=tabfile) return CrontabManager(tabfile=tabfile)
@strawberry.type @strawberry.type
class Alarm: class Alarm:
id: str id: str
@@ -14,6 +18,7 @@ class Alarm:
command: str command: str
is_enabled: bool is_enabled: bool
@strawberry.type @strawberry.type
class Query: class Query:
@strawberry.field @strawberry.field
@@ -30,28 +35,34 @@ class Query:
return Alarm(**a) return Alarm(**a)
return None return None
@strawberry.type @strawberry.type
class Mutation: class Mutation:
@strawberry.field @strawberry.field
def set_alarm( def set_alarm(
self, self,
cron_expression: str, cron_expression: str,
command: str, command: Optional[str] = None,
is_enabled: bool = True, is_enabled: bool = True,
id: Optional[str] = None id: Optional[str] = None,
) -> Alarm: ) -> Alarm:
if command is None:
project_root = Path(__file__).parent.parent.absolute()
python_exec = sys.executable
command = f"cd {project_root} && {python_exec} wecker.py > wecker.log 2>&1"
manager = get_manager() manager = get_manager()
new_id = manager.set_alarm( new_id = manager.set_alarm(
alarm_id=id, alarm_id=id,
cron_expression=cron_expression, cron_expression=cron_expression,
command=command, command=command,
is_enabled=is_enabled is_enabled=is_enabled,
) )
return Alarm( return Alarm(
id=new_id, id=new_id,
cron_expression=cron_expression, cron_expression=cron_expression,
command=command, command=command,
is_enabled=is_enabled is_enabled=is_enabled,
) )
@strawberry.field @strawberry.field
@@ -65,4 +76,5 @@ class Mutation:
return True return True
return False return False
schema = strawberry.Schema(query=Query, mutation=Mutation) schema = strawberry.Schema(query=Query, mutation=Mutation)
+6 -1
View File
@@ -13,6 +13,7 @@ from api.main import app # noqa: E402
client = TestClient(app) client = TestClient(app)
def test_auth_missing(): def test_auth_missing():
query = """ query = """
query { query {
@@ -24,6 +25,7 @@ def test_auth_missing():
response = client.post("/graphql", json={"query": query}) response = client.post("/graphql", json={"query": query})
assert response.status_code == 401 assert response.status_code == 401
def test_auth_invalid(): def test_auth_invalid():
query = """ query = """
query { query {
@@ -32,9 +34,12 @@ def test_auth_invalid():
} }
} }
""" """
response = client.post("/graphql", json={"query": query}, headers={"X-API-Key": "wrong"}) response = client.post(
"/graphql", json={"query": query}, headers={"X-API-Key": "wrong"}
)
assert response.status_code == 401 assert response.status_code == 401
def test_graphql_workflow(): def test_graphql_workflow():
headers = {"X-API-Key": "test-secret"} headers = {"X-API-Key": "test-secret"}
+9 -4
View File
@@ -3,16 +3,19 @@ import tempfile
import uuid import uuid
from api.crontab_manager import CrontabManager from api.crontab_manager import CrontabManager
@pytest.fixture @pytest.fixture
def crontab_file(): def crontab_file():
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as f: with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f:
pass pass
yield f.name yield f.name
def test_crontab_manager_empty(crontab_file): def test_crontab_manager_empty(crontab_file):
manager = CrontabManager(tabfile=crontab_file) manager = CrontabManager(tabfile=crontab_file)
assert manager.get_alarms() == [] assert manager.get_alarms() == []
def test_add_and_list_alarm(crontab_file): def test_add_and_list_alarm(crontab_file):
manager = CrontabManager(tabfile=crontab_file) manager = CrontabManager(tabfile=crontab_file)
alarm_id = str(uuid.uuid4()) alarm_id = str(uuid.uuid4())
@@ -20,7 +23,7 @@ def test_add_and_list_alarm(crontab_file):
alarm_id=alarm_id, alarm_id=alarm_id,
cron_expression="30 7 * * *", cron_expression="30 7 * * *",
command="python wecker.py", command="python wecker.py",
is_enabled=True is_enabled=True,
) )
alarms = manager.get_alarms() alarms = manager.get_alarms()
@@ -30,6 +33,7 @@ def test_add_and_list_alarm(crontab_file):
assert alarms[0]["command"] == "python wecker.py" assert alarms[0]["command"] == "python wecker.py"
assert alarms[0]["is_enabled"] is True assert alarms[0]["is_enabled"] is True
def test_update_alarm(crontab_file): def test_update_alarm(crontab_file):
manager = CrontabManager(tabfile=crontab_file) manager = CrontabManager(tabfile=crontab_file)
alarm_id = "test-id" alarm_id = "test-id"
@@ -37,14 +41,14 @@ def test_update_alarm(crontab_file):
alarm_id=alarm_id, alarm_id=alarm_id,
cron_expression="30 7 * * *", cron_expression="30 7 * * *",
command="python wecker.py", command="python wecker.py",
is_enabled=True is_enabled=True,
) )
manager.set_alarm( manager.set_alarm(
alarm_id=alarm_id, alarm_id=alarm_id,
cron_expression="0 8 * * *", cron_expression="0 8 * * *",
command="python wecker.py --loud", command="python wecker.py --loud",
is_enabled=False is_enabled=False,
) )
alarms = manager.get_alarms() alarms = manager.get_alarms()
@@ -53,6 +57,7 @@ def test_update_alarm(crontab_file):
assert alarms[0]["command"] == "python wecker.py --loud" assert alarms[0]["command"] == "python wecker.py --loud"
assert alarms[0]["is_enabled"] is False assert alarms[0]["is_enabled"] is False
def test_delete_alarm(crontab_file): def test_delete_alarm(crontab_file):
manager = CrontabManager(tabfile=crontab_file) manager = CrontabManager(tabfile=crontab_file)
alarm_id = "test-id-2" alarm_id = "test-id-2"
+18 -11
View File
@@ -3,24 +3,27 @@ import sys
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
# Mock RPi.GPIO and pygame before importing wecker # Mock RPi.GPIO and pygame before importing wecker
sys.modules['RPi'] = MagicMock() sys.modules["RPi"] = MagicMock()
sys.modules['RPi.GPIO'] = MagicMock() sys.modules["RPi.GPIO"] = MagicMock()
sys.modules['pygame'] = MagicMock() sys.modules["pygame"] = MagicMock()
import wecker # noqa: E402 import wecker # noqa: E402
@pytest.fixture @pytest.fixture
def mock_gpio(): def mock_gpio():
with patch.object(wecker, 'GPIO') as mock: with patch.object(wecker, "GPIO") as mock:
mock.LOW = 0 mock.LOW = 0
mock.HIGH = 1 mock.HIGH = 1
yield mock yield mock
@pytest.fixture @pytest.fixture
def mock_pygame(): def mock_pygame():
with patch.object(wecker, 'pygame') as mock: with patch.object(wecker, "pygame") as mock:
yield mock yield mock
def test_set_led(mock_gpio): def test_set_led(mock_gpio):
wecker.set_led(True) wecker.set_led(True)
mock_gpio.output.assert_called_with(wecker.LED_PIN, mock_gpio.LOW) mock_gpio.output.assert_called_with(wecker.LED_PIN, mock_gpio.LOW)
@@ -28,7 +31,8 @@ def test_set_led(mock_gpio):
wecker.set_led(False) wecker.set_led(False)
mock_gpio.output.assert_called_with(wecker.LED_PIN, mock_gpio.HIGH) mock_gpio.output.assert_called_with(wecker.LED_PIN, mock_gpio.HIGH)
@patch('wecker.time.sleep')
@patch("wecker.time.sleep")
def test_blink_led(mock_sleep, mock_gpio): def test_blink_led(mock_sleep, mock_gpio):
wecker.blink_led(2) wecker.blink_led(2)
# 2 blinks = 4 sleep calls, 2 set_led(True), 2 set_led(False) # 2 blinks = 4 sleep calls, 2 set_led(True), 2 set_led(False)
@@ -36,7 +40,8 @@ def test_blink_led(mock_sleep, mock_gpio):
# GPIO output called 4 times total (on, off, on, off) # GPIO output called 4 times total (on, off, on, off)
assert mock_gpio.output.call_count == 4 assert mock_gpio.output.call_count == 4
@patch('wecker.time.time')
@patch("wecker.time.time")
def test_run_alarm_start_to_wait(mock_time, mock_gpio, mock_pygame): def test_run_alarm_start_to_wait(mock_time, mock_gpio, mock_pygame):
# Mock pygame.mixer.get_init() to return True so music plays # Mock pygame.mixer.get_init() to return True so music plays
mock_pygame.mixer.get_init.return_value = True mock_pygame.mixer.get_init.return_value = True
@@ -45,6 +50,7 @@ def test_run_alarm_start_to_wait(mock_time, mock_gpio, mock_pygame):
wecker.run_alarm(test_mode=True) wecker.run_alarm(test_mode=True)
assert mock_pygame.mixer.music.play.called assert mock_pygame.mixer.music.play.called
def test_state_machine_evaluation(mock_gpio, mock_pygame): def test_state_machine_evaluation(mock_gpio, mock_pygame):
clock = wecker.AlarmClock() clock = wecker.AlarmClock()
@@ -53,11 +59,11 @@ def test_state_machine_evaluation(mock_gpio, mock_pygame):
assert clock.state == wecker.STATE_WAIT_BEFORE_BLINK assert clock.state == wecker.STATE_WAIT_BEFORE_BLINK
# Wait 3 seconds -> blinking # Wait 3 seconds -> blinking
with patch('wecker.blink_led'): with patch("wecker.blink_led"):
clock.update(103.1, False) clock.update(103.1, False)
assert clock.state == wecker.STATE_BLINKING assert clock.state == wecker.STATE_BLINKING
with patch('wecker.blink_led'): with patch("wecker.blink_led"):
clock.update(103.2, False) clock.update(103.2, False)
assert clock.state == wecker.STATE_WAIT_FOR_INPUT assert clock.state == wecker.STATE_WAIT_FOR_INPUT
assert clock.target_blinks >= 1 assert clock.target_blinks >= 1
@@ -85,6 +91,7 @@ def test_state_machine_evaluation(mock_gpio, mock_pygame):
assert clock.state == wecker.STATE_EVALUATING assert clock.state == wecker.STATE_EVALUATING
assert not keep_running assert not keep_running
def test_state_machine_incorrect(mock_gpio, mock_pygame): def test_state_machine_incorrect(mock_gpio, mock_pygame):
clock = wecker.AlarmClock() clock = wecker.AlarmClock()
clock.state = wecker.STATE_WAIT_FOR_INPUT clock.state = wecker.STATE_WAIT_FOR_INPUT
@@ -104,7 +111,7 @@ def test_state_machine_incorrect(mock_gpio, mock_pygame):
assert clock.state == wecker.STATE_WAIT_BEFORE_RETRY assert clock.state == wecker.STATE_WAIT_BEFORE_RETRY
@patch('wecker.time.time') @patch("wecker.time.time")
def test_blinking_updates_time_correctly(mock_time, mock_gpio, mock_pygame): def test_blinking_updates_time_correctly(mock_time, mock_gpio, mock_pygame):
clock = wecker.AlarmClock() clock = wecker.AlarmClock()
clock.state = wecker.STATE_BLINKING clock.state = wecker.STATE_BLINKING
@@ -112,7 +119,7 @@ def test_blinking_updates_time_correctly(mock_time, mock_gpio, mock_pygame):
mock_time.return_value = 200.0 mock_time.return_value = 200.0
with patch('wecker.blink_led'): with patch("wecker.blink_led"):
clock.update(100.0, False) clock.update(100.0, False)
assert clock.state == wecker.STATE_WAIT_FOR_INPUT assert clock.state == wecker.STATE_WAIT_FOR_INPUT
+28 -17
View File
@@ -8,11 +8,8 @@ import sys
# Configure logging # Configure logging
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
format='%(asctime)s - %(message)s', format="%(asctime)s - %(message)s",
handlers=[ handlers=[logging.FileHandler("wecker.log"), logging.StreamHandler()],
logging.FileHandler("wecker.log"),
logging.StreamHandler()
]
) )
# GPIO Setup # GPIO Setup
@@ -33,7 +30,7 @@ try:
except Exception as e: except Exception as e:
logging.error(f"Error loading audio file: {e}") logging.error(f"Error loading audio file: {e}")
# Don't exit in test mode # Don't exit in test mode
if 'pytest' not in sys.modules: if "pytest" not in sys.modules:
sys.exit(1) sys.exit(1)
# State Machine states for the flow # State Machine states for the flow
@@ -50,14 +47,16 @@ user_presses = 0
last_interaction_time = 0 last_interaction_time = 0
button_was_pressed = False button_was_pressed = False
def set_led(on): def set_led(on):
"""Turns the LED on or off (LOW = ON, HIGH = OFF)""" """Turns the LED on or off (LOW = ON, HIGH = OFF)"""
if 'GPIO' in globals() and hasattr(GPIO, 'output'): if "GPIO" in globals() and hasattr(GPIO, "output"):
if on: if on:
GPIO.output(LED_PIN, GPIO.LOW) GPIO.output(LED_PIN, GPIO.LOW)
else: else:
GPIO.output(LED_PIN, GPIO.HIGH) GPIO.output(LED_PIN, GPIO.HIGH)
def blink_led(times): def blink_led(times):
"""Blinks the LED a specific number of times (blocking)""" """Blinks the LED a specific number of times (blocking)"""
for _ in range(times): for _ in range(times):
@@ -66,6 +65,7 @@ def blink_led(times):
set_led(False) set_led(False)
time.sleep(0.3) # LED off for 300ms time.sleep(0.3) # LED off for 300ms
class AlarmClock: class AlarmClock:
def __init__(self): def __init__(self):
self.state = STATE_RINGING self.state = STATE_RINGING
@@ -84,7 +84,9 @@ class AlarmClock:
if self.state == STATE_RINGING: if self.state == STATE_RINGING:
if button_just_pressed: if button_just_pressed:
logging.info("Alarm button pressed! Puzzle started. Waiting 3 seconds...") logging.info(
"Alarm button pressed! Puzzle started. Waiting 3 seconds..."
)
self.state = STATE_WAIT_BEFORE_BLINK self.state = STATE_WAIT_BEFORE_BLINK
self.last_interaction_time = now self.last_interaction_time = now
@@ -101,10 +103,11 @@ class AlarmClock:
logging.info("Blinking finished. Waiting for input...") logging.info("Blinking finished. Waiting for input...")
self.state = STATE_WAIT_FOR_INPUT self.state = STATE_WAIT_FOR_INPUT
self.user_presses = 0 self.user_presses = 0
self.last_interaction_time = time.time() # Use time.time() to account for blocking blink_led self.last_interaction_time = (
if 'GPIO' in globals() and hasattr(GPIO, 'input'): time.time()
self.button_was_pressed = (GPIO.input(BUTTON_PIN) == GPIO.LOW) ) # 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
elif self.state == STATE_WAIT_FOR_INPUT: elif self.state == STATE_WAIT_FOR_INPUT:
set_led(is_pressed) set_led(is_pressed)
@@ -120,10 +123,16 @@ class AlarmClock:
self.state = STATE_EVALUATING self.state = STATE_EVALUATING
elif self.state == STATE_EVALUATING: elif self.state == STATE_EVALUATING:
logging.info(f"Evaluation: Target={self.target_blinks}, Entered={self.user_presses}") logging.info(
f"Evaluation: Target={self.target_blinks}, Entered={self.user_presses}"
)
if self.user_presses == self.target_blinks: if self.user_presses == self.target_blinks:
logging.info("Puzzle solved correctly! Alarm clock is stopping.") logging.info("Puzzle solved correctly! Alarm clock is stopping.")
if 'pygame' in globals() and hasattr(pygame, 'mixer') and pygame.mixer.get_init(): if (
"pygame" in globals()
and hasattr(pygame, "mixer")
and pygame.mixer.get_init()
):
pygame.mixer.music.stop() pygame.mixer.music.stop()
set_led(False) set_led(False)
return False # Indicate we should stop running return False # Indicate we should stop running
@@ -141,9 +150,10 @@ class AlarmClock:
return True # Keep running return True # Keep running
def run_alarm(test_mode=False): def run_alarm(test_mode=False):
logging.info("Alarm clock started. Music is playing in an endless loop.") 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(): if "pygame" in globals() and hasattr(pygame, "mixer") and pygame.mixer.get_init():
pygame.mixer.music.play(-1) pygame.mixer.music.play(-1)
set_led(False) # LED off at start set_led(False) # LED off at start
@@ -154,8 +164,8 @@ def run_alarm(test_mode=False):
while True: while True:
now = time.time() now = time.time()
if 'GPIO' in globals() and hasattr(GPIO, 'input'): if "GPIO" in globals() and hasattr(GPIO, "input"):
is_pressed = (GPIO.input(BUTTON_PIN) == GPIO.LOW) is_pressed = GPIO.input(BUTTON_PIN) == GPIO.LOW
else: else:
is_pressed = False is_pressed = False
@@ -169,6 +179,7 @@ def run_alarm(test_mode=False):
except KeyboardInterrupt: except KeyboardInterrupt:
logging.info("Manually aborted (CTRL+C).") logging.info("Manually aborted (CTRL+C).")
if __name__ == "__main__": if __name__ == "__main__":
try: try:
run_alarm() run_alarm()