app.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect, Request
  2. from fastapi.responses import JSONResponse, FileResponse, Response
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi.templating import Jinja2Templates
  5. from pydantic import BaseModel
  6. from typing import List, Optional, Tuple, Dict, Any, Union
  7. import atexit
  8. import os
  9. import logging
  10. from datetime import datetime, time
  11. from modules.connection import connection_manager
  12. from modules.core import pattern_manager
  13. from modules.core.pattern_manager import parse_theta_rho_file, THETA_RHO_DIR
  14. from modules.core import playlist_manager
  15. from modules.update import update_manager
  16. from modules.core.state import state
  17. from modules import mqtt
  18. import signal
  19. import sys
  20. import asyncio
  21. from contextlib import asynccontextmanager
  22. from modules.led.led_controller import LEDController, effect_idle
  23. import math
  24. from modules.core.cache_manager import generate_all_image_previews, get_cache_path, generate_image_preview, get_pattern_metadata
  25. import json
  26. import base64
  27. import time
  28. import argparse
  29. # Get log level from environment variable, default to INFO
  30. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  31. log_level = getattr(logging, log_level_str, logging.INFO)
  32. logging.basicConfig(
  33. level=log_level,
  34. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  35. handlers=[
  36. logging.StreamHandler(),
  37. ]
  38. )
  39. logger = logging.getLogger(__name__)
  40. @asynccontextmanager
  41. async def lifespan(app: FastAPI):
  42. # Startup
  43. logger.info("Starting Dune Weaver application...")
  44. # Register signal handlers
  45. signal.signal(signal.SIGINT, signal_handler)
  46. signal.signal(signal.SIGTERM, signal_handler)
  47. try:
  48. connection_manager.connect_device()
  49. except Exception as e:
  50. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  51. try:
  52. mqtt_handler = mqtt.init_mqtt()
  53. except Exception as e:
  54. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  55. # Generate metadata cache and image previews for all patterns
  56. try:
  57. logger.info("Starting cache generation...")
  58. from modules.core.cache_manager import generate_metadata_cache, generate_all_image_previews
  59. await generate_metadata_cache()
  60. await generate_all_image_previews()
  61. logger.info("Cache generation completed successfully")
  62. except Exception as e:
  63. logger.warning(f"Failed to generate cache: {str(e)}")
  64. yield # This separates startup from shutdown code
  65. app = FastAPI(lifespan=lifespan)
  66. templates = Jinja2Templates(directory="templates")
  67. app.mount("/static", StaticFiles(directory="static"), name="static")
  68. # Pydantic models for request/response validation
  69. class ConnectRequest(BaseModel):
  70. port: Optional[str] = None
  71. class CoordinateRequest(BaseModel):
  72. theta: float
  73. rho: float
  74. class PlaylistRequest(BaseModel):
  75. playlist_name: str
  76. files: List[str] = []
  77. pause_time: float = 0
  78. clear_pattern: Optional[str] = None
  79. run_mode: str = "single"
  80. shuffle: bool = False
  81. class PlaylistRunRequest(BaseModel):
  82. playlist_name: str
  83. pause_time: Optional[float] = 0
  84. clear_pattern: Optional[str] = None
  85. run_mode: Optional[str] = "single"
  86. shuffle: Optional[bool] = False
  87. start_time: Optional[str] = None
  88. end_time: Optional[str] = None
  89. class SpeedRequest(BaseModel):
  90. speed: float
  91. class WLEDRequest(BaseModel):
  92. wled_ip: Optional[str] = None
  93. class DeletePlaylistRequest(BaseModel):
  94. playlist_name: str
  95. class ThetaRhoRequest(BaseModel):
  96. file_name: str
  97. pre_execution: Optional[str] = "none"
  98. class GetCoordinatesRequest(BaseModel):
  99. file_name: str
  100. # Store active WebSocket connections
  101. active_status_connections = set()
  102. @app.websocket("/ws/status")
  103. async def websocket_status_endpoint(websocket: WebSocket):
  104. await websocket.accept()
  105. active_status_connections.add(websocket)
  106. try:
  107. while True:
  108. status = pattern_manager.get_status()
  109. try:
  110. await websocket.send_json({
  111. "type": "status_update",
  112. "data": status
  113. })
  114. except RuntimeError as e:
  115. if "close message has been sent" in str(e):
  116. break
  117. raise
  118. await asyncio.sleep(1)
  119. except WebSocketDisconnect:
  120. pass
  121. finally:
  122. active_status_connections.discard(websocket)
  123. try:
  124. await websocket.close()
  125. except RuntimeError:
  126. pass
  127. async def broadcast_status_update(status: dict):
  128. """Broadcast status update to all connected clients."""
  129. disconnected = set()
  130. for websocket in active_status_connections:
  131. try:
  132. await websocket.send_json({
  133. "type": "status_update",
  134. "data": status
  135. })
  136. except WebSocketDisconnect:
  137. disconnected.add(websocket)
  138. except RuntimeError:
  139. disconnected.add(websocket)
  140. active_status_connections.difference_update(disconnected)
  141. # FastAPI routes
  142. @app.get("/")
  143. async def index(request: Request):
  144. return templates.TemplateResponse("index.html", {"request": request})
  145. @app.get("/settings")
  146. async def settings(request: Request):
  147. return templates.TemplateResponse("settings.html", {"request": request})
  148. @app.get("/list_serial_ports")
  149. async def list_ports():
  150. logger.debug("Listing available serial ports")
  151. return connection_manager.list_serial_ports()
  152. @app.post("/connect")
  153. async def connect(request: ConnectRequest):
  154. if not request.port:
  155. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  156. connection_manager.device_init()
  157. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  158. return {"success": True}
  159. try:
  160. state.conn = connection_manager.SerialConnection(request.port)
  161. connection_manager.device_init()
  162. logger.info(f'Successfully connected to serial port {request.port}')
  163. return {"success": True}
  164. except Exception as e:
  165. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  166. raise HTTPException(status_code=500, detail=str(e))
  167. @app.post("/disconnect")
  168. async def disconnect():
  169. try:
  170. state.conn.close()
  171. logger.info('Successfully disconnected from serial port')
  172. return {"success": True}
  173. except Exception as e:
  174. logger.error(f'Failed to disconnect serial: {str(e)}')
  175. raise HTTPException(status_code=500, detail=str(e))
  176. @app.post("/restart_connection")
  177. async def restart(request: ConnectRequest):
  178. if not request.port:
  179. logger.warning("Restart serial request received without port")
  180. raise HTTPException(status_code=400, detail="No port provided")
  181. try:
  182. logger.info(f"Restarting connection on port {request.port}")
  183. connection_manager.restart_connection()
  184. return {"success": True}
  185. except Exception as e:
  186. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  187. raise HTTPException(status_code=500, detail=str(e))
  188. @app.get("/list_theta_rho_files")
  189. async def list_theta_rho_files():
  190. logger.debug("Listing theta-rho files")
  191. files = pattern_manager.list_theta_rho_files()
  192. return sorted(files)
  193. @app.post("/upload_theta_rho")
  194. async def upload_theta_rho(file: UploadFile = File(...)):
  195. """Upload a theta-rho file."""
  196. try:
  197. # Save the file
  198. # Ensure custom_patterns directory exists
  199. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  200. os.makedirs(custom_patterns_dir, exist_ok=True)
  201. file_path_in_patterns_dir = os.path.join("custom_patterns", file.filename)
  202. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  203. # Save the uploaded file
  204. with open(full_file_path, "wb") as f:
  205. f.write(await file.read())
  206. logger.info(f"File {file.filename} saved successfully")
  207. # Generate image preview for the new file with retry logic
  208. max_retries = 3
  209. for attempt in range(max_retries):
  210. try:
  211. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  212. success = await generate_image_preview(file_path_in_patterns_dir)
  213. if success:
  214. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  215. break
  216. else:
  217. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  218. if attempt < max_retries - 1:
  219. await asyncio.sleep(0.5) # Small delay before retry
  220. except Exception as e:
  221. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  222. if attempt < max_retries - 1:
  223. await asyncio.sleep(0.5) # Small delay before retry
  224. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  225. except Exception as e:
  226. logger.error(f"Error uploading file: {str(e)}")
  227. raise HTTPException(status_code=500, detail=str(e))
  228. @app.post("/get_theta_rho_coordinates")
  229. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  230. """Get theta-rho coordinates for animated preview."""
  231. try:
  232. # Handle file paths that may include the patterns directory prefix
  233. file_name = request.file_name
  234. if file_name.startswith('./patterns/'):
  235. file_name = file_name[11:] # Remove './patterns/' prefix
  236. elif file_name.startswith('patterns/'):
  237. file_name = file_name[9:] # Remove 'patterns/' prefix
  238. file_path = os.path.join(THETA_RHO_DIR, file_name)
  239. if not os.path.exists(file_path):
  240. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  241. # Parse the theta-rho file
  242. coordinates = parse_theta_rho_file(file_path)
  243. if not coordinates:
  244. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  245. return {
  246. "success": True,
  247. "coordinates": coordinates,
  248. "total_points": len(coordinates)
  249. }
  250. except Exception as e:
  251. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  252. raise HTTPException(status_code=500, detail=str(e))
  253. @app.post("/run_theta_rho")
  254. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  255. if not request.file_name:
  256. logger.warning('Run theta-rho request received without file name')
  257. raise HTTPException(status_code=400, detail="No file name provided")
  258. file_path = None
  259. if 'clear' in request.file_name:
  260. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  261. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  262. logger.info(f'Clear pattern file: {file_path}')
  263. if not file_path:
  264. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  265. if not os.path.exists(file_path):
  266. logger.error(f'Theta-rho file not found: {file_path}')
  267. raise HTTPException(status_code=404, detail="File not found")
  268. try:
  269. if not (state.conn.is_connected() if state.conn else False):
  270. logger.warning("Attempted to run a pattern without a connection")
  271. raise HTTPException(status_code=400, detail="Connection not established")
  272. if pattern_manager.pattern_lock.locked():
  273. logger.warning("Attempted to run a pattern while another is already running")
  274. raise HTTPException(status_code=409, detail="Another pattern is already running")
  275. files_to_run = [file_path]
  276. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  277. # Only include clear_pattern if it's not "none"
  278. kwargs = {}
  279. if request.pre_execution != "none":
  280. kwargs['clear_pattern'] = request.pre_execution
  281. # Pass arguments properly
  282. background_tasks.add_task(
  283. pattern_manager.run_theta_rho_files,
  284. files_to_run, # First positional argument
  285. **kwargs # Spread keyword arguments
  286. )
  287. return {"success": True}
  288. except HTTPException as http_exc:
  289. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  290. raise http_exc
  291. except Exception as e:
  292. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  293. raise HTTPException(status_code=500, detail=str(e))
  294. @app.post("/stop_execution")
  295. async def stop_execution():
  296. if not (state.conn.is_connected() if state.conn else False):
  297. logger.warning("Attempted to stop without a connection")
  298. raise HTTPException(status_code=400, detail="Connection not established")
  299. pattern_manager.stop_actions()
  300. return {"success": True}
  301. @app.post("/send_home")
  302. async def send_home():
  303. try:
  304. if not (state.conn.is_connected() if state.conn else False):
  305. logger.warning("Attempted to move to home without a connection")
  306. raise HTTPException(status_code=400, detail="Connection not established")
  307. connection_manager.home()
  308. return {"success": True}
  309. except Exception as e:
  310. logger.error(f"Failed to send home command: {str(e)}")
  311. raise HTTPException(status_code=500, detail=str(e))
  312. @app.post("/run_theta_rho_file/{file_name}")
  313. async def run_specific_theta_rho_file(file_name: str):
  314. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  315. if not os.path.exists(file_path):
  316. raise HTTPException(status_code=404, detail="File not found")
  317. if not (state.conn.is_connected() if state.conn else False):
  318. logger.warning("Attempted to run a pattern without a connection")
  319. raise HTTPException(status_code=400, detail="Connection not established")
  320. pattern_manager.run_theta_rho_file(file_path)
  321. return {"success": True}
  322. class DeleteFileRequest(BaseModel):
  323. file_name: str
  324. @app.post("/delete_theta_rho_file")
  325. async def delete_theta_rho_file(request: DeleteFileRequest):
  326. if not request.file_name:
  327. logger.warning("Delete theta-rho file request received without filename")
  328. raise HTTPException(status_code=400, detail="No file name provided")
  329. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  330. if not os.path.exists(file_path):
  331. logger.error(f"Attempted to delete non-existent file: {file_path}")
  332. raise HTTPException(status_code=404, detail="File not found")
  333. try:
  334. os.remove(file_path)
  335. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  336. return {"success": True}
  337. except Exception as e:
  338. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  339. raise HTTPException(status_code=500, detail=str(e))
  340. @app.post("/move_to_center")
  341. async def move_to_center():
  342. try:
  343. if not (state.conn.is_connected() if state.conn else False):
  344. logger.warning("Attempted to move to center without a connection")
  345. raise HTTPException(status_code=400, detail="Connection not established")
  346. logger.info("Moving device to center position")
  347. pattern_manager.reset_theta()
  348. pattern_manager.move_polar(0, 0)
  349. return {"success": True}
  350. except Exception as e:
  351. logger.error(f"Failed to move to center: {str(e)}")
  352. raise HTTPException(status_code=500, detail=str(e))
  353. @app.post("/move_to_perimeter")
  354. async def move_to_perimeter():
  355. try:
  356. if not (state.conn.is_connected() if state.conn else False):
  357. logger.warning("Attempted to move to perimeter without a connection")
  358. raise HTTPException(status_code=400, detail="Connection not established")
  359. pattern_manager.reset_theta()
  360. pattern_manager.move_polar(0, 1)
  361. return {"success": True}
  362. except Exception as e:
  363. logger.error(f"Failed to move to perimeter: {str(e)}")
  364. raise HTTPException(status_code=500, detail=str(e))
  365. @app.post("/preview_thr")
  366. async def preview_thr(request: DeleteFileRequest):
  367. if not request.file_name:
  368. logger.warning("Preview theta-rho request received without filename")
  369. raise HTTPException(status_code=400, detail="No file name provided")
  370. # Construct the full path to the pattern file to check existence
  371. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  372. if not os.path.exists(pattern_file_path):
  373. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  374. raise HTTPException(status_code=404, detail="Pattern file not found")
  375. try:
  376. cache_path = get_cache_path(request.file_name)
  377. if not os.path.exists(cache_path):
  378. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  379. # Attempt to generate the preview if it's missing
  380. success = await generate_image_preview(request.file_name)
  381. if not success or not os.path.exists(cache_path):
  382. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  383. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  384. # Try to get coordinates from metadata cache first
  385. metadata = get_pattern_metadata(request.file_name)
  386. if metadata:
  387. first_coord_obj = metadata.get('first_coordinate')
  388. last_coord_obj = metadata.get('last_coordinate')
  389. else:
  390. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  391. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  392. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  393. first_coord = coordinates[0] if coordinates else None
  394. last_coord = coordinates[-1] if coordinates else None
  395. # Format coordinates as objects with x and y properties
  396. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  397. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  398. # Return JSON with preview URL and coordinates
  399. # URL encode the file_name for the preview URL
  400. encoded_filename = request.file_name.replace('/', '--')
  401. return {
  402. "preview_url": f"/preview/{encoded_filename}",
  403. "first_coordinate": first_coord_obj,
  404. "last_coordinate": last_coord_obj
  405. }
  406. except HTTPException:
  407. raise
  408. except Exception as e:
  409. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  410. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  411. @app.get("/preview/{encoded_filename}")
  412. async def serve_preview(encoded_filename: str):
  413. """Serve a preview image for a pattern file."""
  414. # Decode the filename by replacing -- with /
  415. file_name = encoded_filename.replace('--', '/')
  416. cache_path = get_cache_path(file_name)
  417. if not os.path.exists(cache_path):
  418. logger.error(f"Preview image not found for {file_name}")
  419. raise HTTPException(status_code=404, detail="Preview image not found")
  420. # Add caching headers
  421. headers = {
  422. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  423. "Content-Type": "image/webp",
  424. "Accept-Ranges": "bytes"
  425. }
  426. return FileResponse(
  427. cache_path,
  428. media_type="image/webp",
  429. headers=headers
  430. )
  431. @app.post("/send_coordinate")
  432. async def send_coordinate(request: CoordinateRequest):
  433. if not (state.conn.is_connected() if state.conn else False):
  434. logger.warning("Attempted to send coordinate without a connection")
  435. raise HTTPException(status_code=400, detail="Connection not established")
  436. try:
  437. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  438. pattern_manager.move_polar(request.theta, request.rho)
  439. return {"success": True}
  440. except Exception as e:
  441. logger.error(f"Failed to send coordinate: {str(e)}")
  442. raise HTTPException(status_code=500, detail=str(e))
  443. @app.get("/download/{filename}")
  444. async def download_file(filename: str):
  445. return FileResponse(
  446. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  447. filename=filename
  448. )
  449. @app.get("/serial_status")
  450. async def serial_status():
  451. connected = state.conn.is_connected() if state.conn else False
  452. port = state.port
  453. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  454. return {
  455. "connected": connected,
  456. "port": port
  457. }
  458. @app.post("/pause_execution")
  459. async def pause_execution():
  460. if pattern_manager.pause_execution():
  461. return {"success": True, "message": "Execution paused"}
  462. raise HTTPException(status_code=500, detail="Failed to pause execution")
  463. @app.post("/resume_execution")
  464. async def resume_execution():
  465. if pattern_manager.resume_execution():
  466. return {"success": True, "message": "Execution resumed"}
  467. raise HTTPException(status_code=500, detail="Failed to resume execution")
  468. # Playlist endpoints
  469. @app.get("/list_all_playlists")
  470. async def list_all_playlists():
  471. playlist_names = playlist_manager.list_all_playlists()
  472. return playlist_names
  473. @app.get("/get_playlist")
  474. async def get_playlist(name: str):
  475. if not name:
  476. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  477. playlist = playlist_manager.get_playlist(name)
  478. if not playlist:
  479. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  480. return playlist
  481. @app.post("/create_playlist")
  482. async def create_playlist(request: PlaylistRequest):
  483. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  484. return {
  485. "success": success,
  486. "message": f"Playlist '{request.playlist_name}' created/updated"
  487. }
  488. @app.post("/modify_playlist")
  489. async def modify_playlist(request: PlaylistRequest):
  490. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  491. return {
  492. "success": success,
  493. "message": f"Playlist '{request.playlist_name}' updated"
  494. }
  495. @app.delete("/delete_playlist")
  496. async def delete_playlist(request: DeletePlaylistRequest):
  497. success = playlist_manager.delete_playlist(request.playlist_name)
  498. if not success:
  499. raise HTTPException(
  500. status_code=404,
  501. detail=f"Playlist '{request.playlist_name}' not found"
  502. )
  503. return {
  504. "success": True,
  505. "message": f"Playlist '{request.playlist_name}' deleted"
  506. }
  507. class AddToPlaylistRequest(BaseModel):
  508. playlist_name: str
  509. pattern: str
  510. @app.post("/add_to_playlist")
  511. async def add_to_playlist(request: AddToPlaylistRequest):
  512. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  513. if not success:
  514. raise HTTPException(status_code=404, detail="Playlist not found")
  515. return {"success": True}
  516. @app.post("/run_playlist")
  517. async def run_playlist_endpoint(request: PlaylistRequest):
  518. """Run a playlist with specified parameters."""
  519. try:
  520. if not (state.conn.is_connected() if state.conn else False):
  521. logger.warning("Attempted to run a playlist without a connection")
  522. raise HTTPException(status_code=400, detail="Connection not established")
  523. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  524. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  525. # Start the playlist execution
  526. success, message = await playlist_manager.run_playlist(
  527. request.playlist_name,
  528. pause_time=request.pause_time,
  529. clear_pattern=request.clear_pattern,
  530. run_mode=request.run_mode,
  531. shuffle=request.shuffle
  532. )
  533. if not success:
  534. raise HTTPException(status_code=409, detail=message)
  535. return {"message": f"Started playlist: {request.playlist_name}"}
  536. except Exception as e:
  537. logger.error(f"Error running playlist: {e}")
  538. raise HTTPException(status_code=500, detail=str(e))
  539. @app.post("/set_speed")
  540. async def set_speed(request: SpeedRequest):
  541. try:
  542. if not (state.conn.is_connected() if state.conn else False):
  543. logger.warning("Attempted to change speed without a connection")
  544. raise HTTPException(status_code=400, detail="Connection not established")
  545. if request.speed <= 0:
  546. logger.warning(f"Invalid speed value received: {request.speed}")
  547. raise HTTPException(status_code=400, detail="Invalid speed value")
  548. state.speed = request.speed
  549. return {"success": True, "speed": request.speed}
  550. except Exception as e:
  551. logger.error(f"Failed to set speed: {str(e)}")
  552. raise HTTPException(status_code=500, detail=str(e))
  553. @app.get("/check_software_update")
  554. async def check_updates():
  555. update_info = update_manager.check_git_updates()
  556. return update_info
  557. @app.post("/update_software")
  558. async def update_software():
  559. logger.info("Starting software update process")
  560. success, error_message, error_log = update_manager.update_software()
  561. if success:
  562. logger.info("Software update completed successfully")
  563. return {"success": True}
  564. else:
  565. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  566. raise HTTPException(
  567. status_code=500,
  568. detail={
  569. "error": error_message,
  570. "details": error_log
  571. }
  572. )
  573. @app.post("/set_wled_ip")
  574. async def set_wled_ip(request: WLEDRequest):
  575. state.wled_ip = request.wled_ip
  576. state.led_controller = LEDController(request.wled_ip)
  577. effect_idle(state.led_controller)
  578. state.save()
  579. logger.info(f"WLED IP updated: {request.wled_ip}")
  580. return {"success": True, "wled_ip": state.wled_ip}
  581. @app.get("/get_wled_ip")
  582. async def get_wled_ip():
  583. if not state.wled_ip:
  584. raise HTTPException(status_code=404, detail="No WLED IP set")
  585. return {"success": True, "wled_ip": state.wled_ip}
  586. @app.post("/skip_pattern")
  587. async def skip_pattern():
  588. if not state.current_playlist:
  589. raise HTTPException(status_code=400, detail="No playlist is currently running")
  590. state.skip_requested = True
  591. return {"success": True}
  592. @app.post("/preview_thr_batch")
  593. async def preview_thr_batch(request: dict):
  594. start = time.time()
  595. if not request.get("file_names"):
  596. logger.warning("Batch preview request received without filenames")
  597. raise HTTPException(status_code=400, detail="No file names provided")
  598. file_names = request["file_names"]
  599. if not isinstance(file_names, list):
  600. raise HTTPException(status_code=400, detail="file_names must be a list")
  601. headers = {
  602. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  603. "Content-Type": "application/json"
  604. }
  605. results = {}
  606. for file_name in file_names:
  607. t1 = time.time()
  608. try:
  609. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  610. if not os.path.exists(pattern_file_path):
  611. logger.warning(f"Pattern file not found: {pattern_file_path}")
  612. results[file_name] = {"error": "Pattern file not found"}
  613. continue
  614. cache_path = get_cache_path(file_name)
  615. if not os.path.exists(cache_path):
  616. logger.info(f"Cache miss for {file_name}. Generating preview...")
  617. success = await generate_image_preview(file_name)
  618. if not success or not os.path.exists(cache_path):
  619. logger.error(f"Failed to generate or find preview for {file_name}")
  620. results[file_name] = {"error": "Failed to generate preview"}
  621. continue
  622. metadata = get_pattern_metadata(file_name)
  623. if metadata:
  624. first_coord_obj = metadata.get('first_coordinate')
  625. last_coord_obj = metadata.get('last_coordinate')
  626. else:
  627. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  628. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  629. first_coord = coordinates[0] if coordinates else None
  630. last_coord = coordinates[-1] if coordinates else None
  631. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  632. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  633. with open(cache_path, 'rb') as f:
  634. image_data = f.read()
  635. image_b64 = base64.b64encode(image_data).decode('utf-8')
  636. results[file_name] = {
  637. "image_data": f"data:image/webp;base64,{image_b64}",
  638. "first_coordinate": first_coord_obj,
  639. "last_coordinate": last_coord_obj
  640. }
  641. except Exception as e:
  642. logger.error(f"Error processing {file_name}: {str(e)}")
  643. results[file_name] = {"error": str(e)}
  644. finally:
  645. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  646. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  647. return JSONResponse(content=results, headers=headers)
  648. @app.get("/playlists")
  649. async def playlists(request: Request):
  650. logger.debug("Rendering playlists page")
  651. return templates.TemplateResponse("playlists.html", {"request": request})
  652. @app.get("/image2sand")
  653. async def image2sand(request: Request):
  654. return templates.TemplateResponse("image2sand.html", {"request": request})
  655. @app.get("/wled")
  656. async def wled(request: Request):
  657. return templates.TemplateResponse("wled.html", {"request": request})
  658. @app.get("/table_control")
  659. async def table_control(request: Request):
  660. return templates.TemplateResponse("table_control.html", {"request": request})
  661. @app.post("/rebuild_cache")
  662. async def rebuild_cache_endpoint():
  663. """Trigger a rebuild of the pattern cache."""
  664. try:
  665. from modules.core.cache_manager import rebuild_cache
  666. await rebuild_cache()
  667. return {"success": True, "message": "Cache rebuild completed successfully"}
  668. except Exception as e:
  669. logger.error(f"Failed to rebuild cache: {str(e)}")
  670. raise HTTPException(status_code=500, detail=str(e))
  671. def signal_handler(signum, frame):
  672. """Handle shutdown signals gracefully but forcefully."""
  673. logger.info("Received shutdown signal, cleaning up...")
  674. try:
  675. if state.led_controller:
  676. state.led_controller.set_power(0)
  677. # Run cleanup operations synchronously to ensure completion
  678. pattern_manager.stop_actions()
  679. state.save()
  680. logger.info("Cleanup completed")
  681. except Exception as e:
  682. logger.error(f"Error during cleanup: {str(e)}")
  683. finally:
  684. logger.info("Exiting application...")
  685. os._exit(0) # Force exit regardless of other threads
  686. def entrypoint():
  687. import uvicorn
  688. logger.info("Starting FastAPI server on port 8080...")
  689. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  690. if __name__ == "__main__":
  691. entrypoint()