1
0

main.py 38 KB

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