1
0

main.py 35 KB

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