81 lines
2 KiB
Python
81 lines
2 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from datetime import datetime
|
|
import requests
|
|
from matrix import MatrixDisplay
|
|
import asyncio
|
|
|
|
app = FastAPI()
|
|
|
|
matrix_display = MatrixDisplay()
|
|
should_run_time_loop = True
|
|
|
|
|
|
async def display_time():
|
|
while should_run_time_loop:
|
|
try:
|
|
matrix_display.show_current_time()
|
|
except requests.exceptions.RequestException as e:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=f"Failed to display time on the matrix display: {e}",
|
|
)
|
|
|
|
seconds_until_next_minute = 60 - datetime.now().second
|
|
await asyncio.sleep(seconds_until_next_minute)
|
|
|
|
|
|
|
|
asyncio.create_task(display_time())
|
|
|
|
|
|
|
|
@app.post("/time")
|
|
async def start_time_loop():
|
|
global should_run_time_loop
|
|
should_run_time_loop = True
|
|
asyncio.create_task(display_time())
|
|
return {"message": "Time loop started"}
|
|
|
|
|
|
@app.post("/off")
|
|
async def turn_off():
|
|
global should_run_time_loop
|
|
should_run_time_loop = False
|
|
matrix_display.turn_off()
|
|
return {"message": "Display turned off"}
|
|
|
|
|
|
@app.post("/flash")
|
|
async def flash(count: int = 1):
|
|
global should_run_time_loop
|
|
was_clock_runnign = should_run_time_loop
|
|
should_run_time_loop = False
|
|
|
|
matrix_display.flash(count)
|
|
|
|
if was_clock_runnign:
|
|
should_run_time_loop = True
|
|
asyncio.create_task(display_time())
|
|
return {"message": "Display flashed"}
|
|
|
|
|
|
@app.post("/message")
|
|
async def display_message(body: dict):
|
|
global should_run_time_loop
|
|
should_run_time_loop = False
|
|
message_text = body.get("message")
|
|
try:
|
|
matrix_display.show_text(message_text)
|
|
except requests.exceptions.RequestException as e:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=f"Failed to display message on the matrix display: {e}",
|
|
)
|
|
return {"message": "Message displayed"}
|
|
|
|
|
|
@app.post("/stop")
|
|
async def stop_time_loop():
|
|
global should_run_time_loop
|
|
should_run_time_loop = False
|
|
return {"message": "Time loop stopped"}
|