main.py 33 KB

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