main.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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. from concurrent.futures import ProcessPoolExecutor
  31. import multiprocessing
  32. # Get log level from environment variable, default to INFO
  33. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  34. log_level = getattr(logging, log_level_str, logging.INFO)
  35. # Create a process pool for CPU-intensive tasks
  36. # Limit to reasonable number of workers for embedded systems
  37. cpu_count = multiprocessing.cpu_count()
  38. # Maximum 3 workers (leaving 1 for motion), minimum 1
  39. process_pool_size = min(3, max(1, cpu_count - 1))
  40. process_pool = None # Will be initialized in lifespan
  41. logging.basicConfig(
  42. level=log_level,
  43. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  44. handlers=[
  45. logging.StreamHandler(),
  46. ]
  47. )
  48. logger = logging.getLogger(__name__)
  49. def normalize_file_path(file_path: str) -> str:
  50. """Normalize file path separators for consistent cross-platform handling."""
  51. if not file_path:
  52. return ''
  53. # First normalize path separators
  54. normalized = file_path.replace('\\', '/')
  55. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  56. if normalized.startswith('./patterns/'):
  57. normalized = normalized[11:]
  58. elif normalized.startswith('patterns/'):
  59. normalized = normalized[9:]
  60. return normalized
  61. @asynccontextmanager
  62. async def lifespan(app: FastAPI):
  63. # Startup
  64. logger.info("Starting Dune Weaver application...")
  65. # Register signal handlers
  66. signal.signal(signal.SIGINT, signal_handler)
  67. signal.signal(signal.SIGTERM, signal_handler)
  68. # Initialize process pool for CPU-intensive tasks
  69. global process_pool
  70. process_pool = ProcessPoolExecutor(max_workers=process_pool_size)
  71. logger.info(f"Initialized process pool with {process_pool_size} workers (detected {cpu_count} cores total)")
  72. try:
  73. connection_manager.connect_device()
  74. except Exception as e:
  75. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  76. # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
  77. if state.auto_play_enabled and state.auto_play_playlist:
  78. logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
  79. try:
  80. # Check if we have a valid connection before starting playlist
  81. if state.conn and hasattr(state.conn, 'is_connected') and state.conn.is_connected():
  82. logger.info(f"Connection available, starting auto-play playlist: {state.auto_play_playlist} with options: run_mode={state.auto_play_run_mode}, pause_time={state.auto_play_pause_time}, clear_pattern={state.auto_play_clear_pattern}, shuffle={state.auto_play_shuffle}")
  83. asyncio.create_task(playlist_manager.run_playlist(
  84. state.auto_play_playlist,
  85. pause_time=state.auto_play_pause_time,
  86. clear_pattern=state.auto_play_clear_pattern,
  87. run_mode=state.auto_play_run_mode,
  88. shuffle=state.auto_play_shuffle
  89. ))
  90. else:
  91. logger.warning("No hardware connection available, skipping auto_play mode auto-play")
  92. except Exception as e:
  93. logger.error(f"Failed to auto-play auto_play playlist: {str(e)}")
  94. try:
  95. mqtt_handler = mqtt.init_mqtt()
  96. except Exception as e:
  97. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  98. # Schedule cache generation check for later (non-blocking startup)
  99. async def delayed_cache_check():
  100. """Check and generate cache in background."""
  101. try:
  102. logger.info("Starting cache check...")
  103. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  104. if await is_cache_generation_needed_async():
  105. logger.info("Cache generation needed, starting background task...")
  106. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  107. else:
  108. logger.info("Cache is up to date, skipping generation")
  109. except Exception as e:
  110. logger.warning(f"Failed during cache generation: {str(e)}")
  111. # Start cache check in background immediately
  112. asyncio.create_task(delayed_cache_check())
  113. yield # This separates startup from shutdown code
  114. # Shutdown
  115. logger.info("Shutting down Dune Weaver application...")
  116. # Shutdown process pool
  117. if process_pool:
  118. process_pool.shutdown(wait=True)
  119. logger.info("Process pool shutdown complete")
  120. app = FastAPI(lifespan=lifespan)
  121. templates = Jinja2Templates(directory="templates")
  122. app.mount("/static", StaticFiles(directory="static"), name="static")
  123. # Pydantic models for request/response validation
  124. class ConnectRequest(BaseModel):
  125. port: Optional[str] = None
  126. class auto_playModeRequest(BaseModel):
  127. enabled: bool
  128. playlist: Optional[str] = None
  129. run_mode: Optional[str] = "loop"
  130. pause_time: Optional[float] = 5.0
  131. clear_pattern: Optional[str] = "adaptive"
  132. shuffle: Optional[bool] = False
  133. class CoordinateRequest(BaseModel):
  134. theta: float
  135. rho: float
  136. class PlaylistRequest(BaseModel):
  137. playlist_name: str
  138. files: List[str] = []
  139. pause_time: float = 0
  140. clear_pattern: Optional[str] = None
  141. run_mode: str = "single"
  142. shuffle: bool = False
  143. class PlaylistRunRequest(BaseModel):
  144. playlist_name: str
  145. pause_time: Optional[float] = 0
  146. clear_pattern: Optional[str] = None
  147. run_mode: Optional[str] = "single"
  148. shuffle: Optional[bool] = False
  149. start_time: Optional[str] = None
  150. end_time: Optional[str] = None
  151. class SpeedRequest(BaseModel):
  152. speed: float
  153. class WLEDRequest(BaseModel):
  154. wled_ip: Optional[str] = None
  155. class DeletePlaylistRequest(BaseModel):
  156. playlist_name: str
  157. class ThetaRhoRequest(BaseModel):
  158. file_name: str
  159. pre_execution: Optional[str] = "none"
  160. class GetCoordinatesRequest(BaseModel):
  161. file_name: str
  162. # Store active WebSocket connections
  163. active_status_connections = set()
  164. active_cache_progress_connections = set()
  165. @app.websocket("/ws/status")
  166. async def websocket_status_endpoint(websocket: WebSocket):
  167. await websocket.accept()
  168. active_status_connections.add(websocket)
  169. try:
  170. while True:
  171. status = pattern_manager.get_status()
  172. try:
  173. await websocket.send_json({
  174. "type": "status_update",
  175. "data": status
  176. })
  177. except RuntimeError as e:
  178. if "close message has been sent" in str(e):
  179. break
  180. raise
  181. await asyncio.sleep(1)
  182. except WebSocketDisconnect:
  183. pass
  184. finally:
  185. active_status_connections.discard(websocket)
  186. try:
  187. await websocket.close()
  188. except RuntimeError:
  189. pass
  190. async def broadcast_status_update(status: dict):
  191. """Broadcast status update to all connected clients."""
  192. disconnected = set()
  193. for websocket in active_status_connections:
  194. try:
  195. await websocket.send_json({
  196. "type": "status_update",
  197. "data": status
  198. })
  199. except WebSocketDisconnect:
  200. disconnected.add(websocket)
  201. except RuntimeError:
  202. disconnected.add(websocket)
  203. active_status_connections.difference_update(disconnected)
  204. @app.websocket("/ws/cache-progress")
  205. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  206. from modules.core.cache_manager import get_cache_progress
  207. await websocket.accept()
  208. active_cache_progress_connections.add(websocket)
  209. try:
  210. while True:
  211. progress = get_cache_progress()
  212. try:
  213. await websocket.send_json({
  214. "type": "cache_progress",
  215. "data": progress
  216. })
  217. except RuntimeError as e:
  218. if "close message has been sent" in str(e):
  219. break
  220. raise
  221. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  222. except WebSocketDisconnect:
  223. pass
  224. finally:
  225. active_cache_progress_connections.discard(websocket)
  226. try:
  227. await websocket.close()
  228. except RuntimeError:
  229. pass
  230. # FastAPI routes
  231. @app.get("/")
  232. async def index(request: Request):
  233. return templates.TemplateResponse("index.html", {"request": request, "app_name": state.app_name})
  234. @app.get("/settings")
  235. async def settings(request: Request):
  236. return templates.TemplateResponse("settings.html", {"request": request, "app_name": state.app_name})
  237. @app.get("/api/auto_play-mode")
  238. async def get_auto_play_mode():
  239. """Get current auto_play mode settings."""
  240. return {
  241. "enabled": state.auto_play_enabled,
  242. "playlist": state.auto_play_playlist,
  243. "run_mode": state.auto_play_run_mode,
  244. "pause_time": state.auto_play_pause_time,
  245. "clear_pattern": state.auto_play_clear_pattern,
  246. "shuffle": state.auto_play_shuffle
  247. }
  248. @app.post("/api/auto_play-mode")
  249. async def set_auto_play_mode(request: auto_playModeRequest):
  250. """Update auto_play mode settings."""
  251. state.auto_play_enabled = request.enabled
  252. if request.playlist is not None:
  253. state.auto_play_playlist = request.playlist
  254. if request.run_mode is not None:
  255. state.auto_play_run_mode = request.run_mode
  256. if request.pause_time is not None:
  257. state.auto_play_pause_time = request.pause_time
  258. if request.clear_pattern is not None:
  259. state.auto_play_clear_pattern = request.clear_pattern
  260. if request.shuffle is not None:
  261. state.auto_play_shuffle = request.shuffle
  262. state.save()
  263. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  264. return {"success": True, "message": "auto_play mode settings updated"}
  265. @app.get("/list_serial_ports")
  266. async def list_ports():
  267. logger.debug("Listing available serial ports")
  268. return connection_manager.list_serial_ports()
  269. @app.post("/connect")
  270. async def connect(request: ConnectRequest):
  271. if not request.port:
  272. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  273. connection_manager.device_init()
  274. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  275. return {"success": True}
  276. try:
  277. state.conn = connection_manager.SerialConnection(request.port)
  278. connection_manager.device_init()
  279. logger.info(f'Successfully connected to serial port {request.port}')
  280. return {"success": True}
  281. except Exception as e:
  282. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  283. raise HTTPException(status_code=500, detail=str(e))
  284. @app.post("/disconnect")
  285. async def disconnect():
  286. try:
  287. state.conn.close()
  288. logger.info('Successfully disconnected from serial port')
  289. return {"success": True}
  290. except Exception as e:
  291. logger.error(f'Failed to disconnect serial: {str(e)}')
  292. raise HTTPException(status_code=500, detail=str(e))
  293. @app.post("/restart_connection")
  294. async def restart(request: ConnectRequest):
  295. if not request.port:
  296. logger.warning("Restart serial request received without port")
  297. raise HTTPException(status_code=400, detail="No port provided")
  298. try:
  299. logger.info(f"Restarting connection on port {request.port}")
  300. connection_manager.restart_connection()
  301. return {"success": True}
  302. except Exception as e:
  303. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  304. raise HTTPException(status_code=500, detail=str(e))
  305. @app.get("/list_theta_rho_files")
  306. async def list_theta_rho_files():
  307. logger.debug("Listing theta-rho files")
  308. # Run the blocking file system operation in a thread pool
  309. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  310. return sorted(files)
  311. @app.get("/list_theta_rho_files_with_metadata")
  312. async def list_theta_rho_files_with_metadata():
  313. """Get list of theta-rho files with metadata for sorting and filtering.
  314. Optimized to process files asynchronously and support request cancellation.
  315. """
  316. from modules.core.cache_manager import get_pattern_metadata
  317. import asyncio
  318. from concurrent.futures import ThreadPoolExecutor
  319. # Run the blocking file listing in a thread
  320. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  321. files_with_metadata = []
  322. # Use ThreadPoolExecutor for I/O-bound operations
  323. executor = ThreadPoolExecutor(max_workers=4)
  324. def process_file(file_path):
  325. """Process a single file and return its metadata."""
  326. try:
  327. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  328. # Get file stats
  329. file_stat = os.stat(full_path)
  330. # Get cached metadata (this should be fast if cached)
  331. metadata = get_pattern_metadata(file_path)
  332. # Extract full folder path from file path
  333. path_parts = file_path.split('/')
  334. if len(path_parts) > 1:
  335. # Get everything except the filename (join all folder parts)
  336. category = '/'.join(path_parts[:-1])
  337. else:
  338. category = 'root'
  339. # Get file name without extension
  340. file_name = os.path.splitext(os.path.basename(file_path))[0]
  341. # Use modification time (mtime) for "date modified"
  342. date_modified = file_stat.st_mtime
  343. return {
  344. 'path': file_path,
  345. 'name': file_name,
  346. 'category': category,
  347. 'date_modified': date_modified,
  348. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  349. }
  350. except Exception as e:
  351. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  352. # Include file with minimal info if metadata fails
  353. path_parts = file_path.split('/')
  354. if len(path_parts) > 1:
  355. category = '/'.join(path_parts[:-1])
  356. else:
  357. category = 'root'
  358. return {
  359. 'path': file_path,
  360. 'name': os.path.splitext(os.path.basename(file_path))[0],
  361. 'category': category,
  362. 'date_modified': 0,
  363. 'coordinates_count': 0
  364. }
  365. # Process files in parallel using asyncio
  366. loop = asyncio.get_event_loop()
  367. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  368. # Process results as they complete
  369. for task in asyncio.as_completed(tasks):
  370. try:
  371. result = await task
  372. files_with_metadata.append(result)
  373. except Exception as e:
  374. logger.error(f"Error processing file: {str(e)}")
  375. return files_with_metadata
  376. @app.post("/upload_theta_rho")
  377. async def upload_theta_rho(file: UploadFile = File(...)):
  378. """Upload a theta-rho file."""
  379. try:
  380. # Save the file
  381. # Ensure custom_patterns directory exists
  382. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  383. os.makedirs(custom_patterns_dir, exist_ok=True)
  384. # Use forward slashes for internal path representation to maintain consistency
  385. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  386. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  387. # Save the uploaded file with proper encoding for Windows compatibility
  388. file_content = await file.read()
  389. try:
  390. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  391. text_content = file_content.decode('utf-8')
  392. with open(full_file_path, "w", encoding='utf-8') as f:
  393. f.write(text_content)
  394. except UnicodeDecodeError:
  395. # If UTF-8 decoding fails, save as binary (fallback)
  396. with open(full_file_path, "wb") as f:
  397. f.write(file_content)
  398. logger.info(f"File {file.filename} saved successfully")
  399. # Generate image preview for the new file with retry logic
  400. max_retries = 3
  401. for attempt in range(max_retries):
  402. try:
  403. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  404. success = await generate_image_preview(file_path_in_patterns_dir)
  405. if success:
  406. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  407. break
  408. else:
  409. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  410. if attempt < max_retries - 1:
  411. await asyncio.sleep(0.5) # Small delay before retry
  412. except Exception as e:
  413. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  414. if attempt < max_retries - 1:
  415. await asyncio.sleep(0.5) # Small delay before retry
  416. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  417. except Exception as e:
  418. logger.error(f"Error uploading file: {str(e)}")
  419. raise HTTPException(status_code=500, detail=str(e))
  420. @app.post("/get_theta_rho_coordinates")
  421. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  422. """Get theta-rho coordinates for animated preview."""
  423. try:
  424. # Normalize file path for cross-platform compatibility and remove prefixes
  425. file_name = normalize_file_path(request.file_name)
  426. file_path = os.path.join(THETA_RHO_DIR, file_name)
  427. # Check file existence asynchronously
  428. exists = await asyncio.to_thread(os.path.exists, file_path)
  429. if not exists:
  430. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  431. # Parse the theta-rho file in a separate process for CPU-intensive work
  432. # This prevents blocking the motion control thread
  433. loop = asyncio.get_event_loop()
  434. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, file_path)
  435. if not coordinates:
  436. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  437. return {
  438. "success": True,
  439. "coordinates": coordinates,
  440. "total_points": len(coordinates)
  441. }
  442. except Exception as e:
  443. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  444. raise HTTPException(status_code=500, detail=str(e))
  445. @app.post("/run_theta_rho")
  446. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  447. if not request.file_name:
  448. logger.warning('Run theta-rho request received without file name')
  449. raise HTTPException(status_code=400, detail="No file name provided")
  450. file_path = None
  451. if 'clear' in request.file_name:
  452. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  453. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  454. logger.info(f'Clear pattern file: {file_path}')
  455. if not file_path:
  456. # Normalize file path for cross-platform compatibility
  457. normalized_file_name = normalize_file_path(request.file_name)
  458. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  459. if not os.path.exists(file_path):
  460. logger.error(f'Theta-rho file not found: {file_path}')
  461. raise HTTPException(status_code=404, detail="File not found")
  462. try:
  463. if not (state.conn.is_connected() if state.conn else False):
  464. logger.warning("Attempted to run a pattern without a connection")
  465. raise HTTPException(status_code=400, detail="Connection not established")
  466. if pattern_manager.pattern_lock.locked():
  467. logger.warning("Attempted to run a pattern while another is already running")
  468. raise HTTPException(status_code=409, detail="Another pattern is already running")
  469. files_to_run = [file_path]
  470. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  471. # Only include clear_pattern if it's not "none"
  472. kwargs = {}
  473. if request.pre_execution != "none":
  474. kwargs['clear_pattern'] = request.pre_execution
  475. # Pass arguments properly
  476. background_tasks.add_task(
  477. pattern_manager.run_theta_rho_files,
  478. files_to_run, # First positional argument
  479. **kwargs # Spread keyword arguments
  480. )
  481. return {"success": True}
  482. except HTTPException as http_exc:
  483. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  484. raise http_exc
  485. except Exception as e:
  486. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  487. raise HTTPException(status_code=500, detail=str(e))
  488. @app.post("/stop_execution")
  489. async def stop_execution():
  490. if not (state.conn.is_connected() if state.conn else False):
  491. logger.warning("Attempted to stop without a connection")
  492. raise HTTPException(status_code=400, detail="Connection not established")
  493. await pattern_manager.stop_actions()
  494. return {"success": True}
  495. @app.post("/send_home")
  496. async def send_home():
  497. try:
  498. if not (state.conn.is_connected() if state.conn else False):
  499. logger.warning("Attempted to move to home without a connection")
  500. raise HTTPException(status_code=400, detail="Connection not established")
  501. # Run homing with 15 second timeout
  502. success = await asyncio.to_thread(connection_manager.home)
  503. if not success:
  504. logger.error("Homing failed or timed out")
  505. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  506. return {"success": True}
  507. except HTTPException:
  508. raise
  509. except Exception as e:
  510. logger.error(f"Failed to send home command: {str(e)}")
  511. raise HTTPException(status_code=500, detail=str(e))
  512. @app.post("/run_theta_rho_file/{file_name}")
  513. async def run_specific_theta_rho_file(file_name: str):
  514. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  515. if not os.path.exists(file_path):
  516. raise HTTPException(status_code=404, detail="File not found")
  517. if not (state.conn.is_connected() if state.conn else False):
  518. logger.warning("Attempted to run a pattern without a connection")
  519. raise HTTPException(status_code=400, detail="Connection not established")
  520. pattern_manager.run_theta_rho_file(file_path)
  521. return {"success": True}
  522. class DeleteFileRequest(BaseModel):
  523. file_name: str
  524. @app.post("/delete_theta_rho_file")
  525. async def delete_theta_rho_file(request: DeleteFileRequest):
  526. if not request.file_name:
  527. logger.warning("Delete theta-rho file request received without filename")
  528. raise HTTPException(status_code=400, detail="No file name provided")
  529. # Normalize file path for cross-platform compatibility
  530. normalized_file_name = normalize_file_path(request.file_name)
  531. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  532. # Check file existence asynchronously
  533. exists = await asyncio.to_thread(os.path.exists, file_path)
  534. if not exists:
  535. logger.error(f"Attempted to delete non-existent file: {file_path}")
  536. raise HTTPException(status_code=404, detail="File not found")
  537. try:
  538. # Delete the pattern file asynchronously
  539. await asyncio.to_thread(os.remove, file_path)
  540. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  541. # Clean up cached preview image and metadata asynchronously
  542. from modules.core.cache_manager import delete_pattern_cache
  543. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  544. if cache_cleanup_success:
  545. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  546. else:
  547. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  548. return {"success": True, "cache_cleanup": cache_cleanup_success}
  549. except Exception as e:
  550. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  551. raise HTTPException(status_code=500, detail=str(e))
  552. @app.post("/move_to_center")
  553. async def move_to_center():
  554. try:
  555. if not (state.conn.is_connected() if state.conn else False):
  556. logger.warning("Attempted to move to center without a connection")
  557. raise HTTPException(status_code=400, detail="Connection not established")
  558. logger.info("Moving device to center position")
  559. await pattern_manager.reset_theta()
  560. await pattern_manager.move_polar(0, 0)
  561. return {"success": True}
  562. except Exception as e:
  563. logger.error(f"Failed to move to center: {str(e)}")
  564. raise HTTPException(status_code=500, detail=str(e))
  565. @app.post("/move_to_perimeter")
  566. async def move_to_perimeter():
  567. try:
  568. if not (state.conn.is_connected() if state.conn else False):
  569. logger.warning("Attempted to move to perimeter without a connection")
  570. raise HTTPException(status_code=400, detail="Connection not established")
  571. await pattern_manager.reset_theta()
  572. await pattern_manager.move_polar(0, 1)
  573. return {"success": True}
  574. except Exception as e:
  575. logger.error(f"Failed to move to perimeter: {str(e)}")
  576. raise HTTPException(status_code=500, detail=str(e))
  577. @app.post("/preview_thr")
  578. async def preview_thr(request: DeleteFileRequest):
  579. if not request.file_name:
  580. logger.warning("Preview theta-rho request received without filename")
  581. raise HTTPException(status_code=400, detail="No file name provided")
  582. # Normalize file path for cross-platform compatibility
  583. normalized_file_name = normalize_file_path(request.file_name)
  584. # Construct the full path to the pattern file to check existence
  585. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  586. # Check file existence asynchronously
  587. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  588. if not exists:
  589. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  590. raise HTTPException(status_code=404, detail="Pattern file not found")
  591. try:
  592. cache_path = get_cache_path(normalized_file_name)
  593. # Check cache existence asynchronously
  594. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  595. if not cache_exists:
  596. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  597. # Attempt to generate the preview if it's missing
  598. success = await generate_image_preview(normalized_file_name)
  599. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  600. if not success or not cache_exists_after:
  601. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  602. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  603. # Try to get coordinates from metadata cache first
  604. metadata = get_pattern_metadata(normalized_file_name)
  605. if metadata:
  606. first_coord_obj = metadata.get('first_coordinate')
  607. last_coord_obj = metadata.get('last_coordinate')
  608. else:
  609. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  610. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  611. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  612. first_coord = coordinates[0] if coordinates else None
  613. last_coord = coordinates[-1] if coordinates else None
  614. # Format coordinates as objects with x and y properties
  615. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  616. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  617. # Return JSON with preview URL and coordinates
  618. # URL encode the file_name for the preview URL
  619. # Handle both forward slashes and backslashes for cross-platform compatibility
  620. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  621. return {
  622. "preview_url": f"/preview/{encoded_filename}",
  623. "first_coordinate": first_coord_obj,
  624. "last_coordinate": last_coord_obj
  625. }
  626. except HTTPException:
  627. raise
  628. except Exception as e:
  629. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  630. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  631. @app.get("/preview/{encoded_filename}")
  632. async def serve_preview(encoded_filename: str):
  633. """Serve a preview image for a pattern file."""
  634. # Decode the filename by replacing -- with the original path separators
  635. # First try forward slash (most common case), then backslash if needed
  636. file_name = encoded_filename.replace('--', '/')
  637. # Apply normalization to handle any remaining path prefixes
  638. file_name = normalize_file_path(file_name)
  639. # Check if the decoded path exists, if not try backslash decoding
  640. cache_path = get_cache_path(file_name)
  641. if not os.path.exists(cache_path):
  642. # Try with backslash for Windows paths
  643. file_name_backslash = encoded_filename.replace('--', '\\')
  644. file_name_backslash = normalize_file_path(file_name_backslash)
  645. cache_path_backslash = get_cache_path(file_name_backslash)
  646. if os.path.exists(cache_path_backslash):
  647. file_name = file_name_backslash
  648. cache_path = cache_path_backslash
  649. # cache_path is already determined above in the decoding logic
  650. if not os.path.exists(cache_path):
  651. logger.error(f"Preview image not found for {file_name}")
  652. raise HTTPException(status_code=404, detail="Preview image not found")
  653. # Add caching headers
  654. headers = {
  655. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  656. "Content-Type": "image/webp",
  657. "Accept-Ranges": "bytes"
  658. }
  659. return FileResponse(
  660. cache_path,
  661. media_type="image/webp",
  662. headers=headers
  663. )
  664. @app.post("/send_coordinate")
  665. async def send_coordinate(request: CoordinateRequest):
  666. if not (state.conn.is_connected() if state.conn else False):
  667. logger.warning("Attempted to send coordinate without a connection")
  668. raise HTTPException(status_code=400, detail="Connection not established")
  669. try:
  670. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  671. await pattern_manager.move_polar(request.theta, request.rho)
  672. return {"success": True}
  673. except Exception as e:
  674. logger.error(f"Failed to send coordinate: {str(e)}")
  675. raise HTTPException(status_code=500, detail=str(e))
  676. @app.get("/download/{filename}")
  677. async def download_file(filename: str):
  678. return FileResponse(
  679. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  680. filename=filename
  681. )
  682. @app.get("/serial_status")
  683. async def serial_status():
  684. connected = state.conn.is_connected() if state.conn else False
  685. port = state.port
  686. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  687. return {
  688. "connected": connected,
  689. "port": port
  690. }
  691. @app.post("/pause_execution")
  692. async def pause_execution():
  693. if pattern_manager.pause_execution():
  694. return {"success": True, "message": "Execution paused"}
  695. raise HTTPException(status_code=500, detail="Failed to pause execution")
  696. @app.post("/resume_execution")
  697. async def resume_execution():
  698. if pattern_manager.resume_execution():
  699. return {"success": True, "message": "Execution resumed"}
  700. raise HTTPException(status_code=500, detail="Failed to resume execution")
  701. # Playlist endpoints
  702. @app.get("/list_all_playlists")
  703. async def list_all_playlists():
  704. playlist_names = playlist_manager.list_all_playlists()
  705. return playlist_names
  706. @app.get("/get_playlist")
  707. async def get_playlist(name: str):
  708. if not name:
  709. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  710. playlist = playlist_manager.get_playlist(name)
  711. if not playlist:
  712. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  713. return playlist
  714. @app.post("/create_playlist")
  715. async def create_playlist(request: PlaylistRequest):
  716. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  717. return {
  718. "success": success,
  719. "message": f"Playlist '{request.playlist_name}' created/updated"
  720. }
  721. @app.post("/modify_playlist")
  722. async def modify_playlist(request: PlaylistRequest):
  723. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  724. return {
  725. "success": success,
  726. "message": f"Playlist '{request.playlist_name}' updated"
  727. }
  728. @app.delete("/delete_playlist")
  729. async def delete_playlist(request: DeletePlaylistRequest):
  730. success = playlist_manager.delete_playlist(request.playlist_name)
  731. if not success:
  732. raise HTTPException(
  733. status_code=404,
  734. detail=f"Playlist '{request.playlist_name}' not found"
  735. )
  736. return {
  737. "success": True,
  738. "message": f"Playlist '{request.playlist_name}' deleted"
  739. }
  740. class AddToPlaylistRequest(BaseModel):
  741. playlist_name: str
  742. pattern: str
  743. @app.post("/add_to_playlist")
  744. async def add_to_playlist(request: AddToPlaylistRequest):
  745. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  746. if not success:
  747. raise HTTPException(status_code=404, detail="Playlist not found")
  748. return {"success": True}
  749. @app.post("/run_playlist")
  750. async def run_playlist_endpoint(request: PlaylistRequest):
  751. """Run a playlist with specified parameters."""
  752. try:
  753. if not (state.conn.is_connected() if state.conn else False):
  754. logger.warning("Attempted to run a playlist without a connection")
  755. raise HTTPException(status_code=400, detail="Connection not established")
  756. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  757. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  758. # Start the playlist execution
  759. success, message = await playlist_manager.run_playlist(
  760. request.playlist_name,
  761. pause_time=request.pause_time,
  762. clear_pattern=request.clear_pattern,
  763. run_mode=request.run_mode,
  764. shuffle=request.shuffle
  765. )
  766. if not success:
  767. raise HTTPException(status_code=409, detail=message)
  768. return {"message": f"Started playlist: {request.playlist_name}"}
  769. except Exception as e:
  770. logger.error(f"Error running playlist: {e}")
  771. raise HTTPException(status_code=500, detail=str(e))
  772. @app.post("/set_speed")
  773. async def set_speed(request: SpeedRequest):
  774. try:
  775. if not (state.conn.is_connected() if state.conn else False):
  776. logger.warning("Attempted to change speed without a connection")
  777. raise HTTPException(status_code=400, detail="Connection not established")
  778. if request.speed <= 0:
  779. logger.warning(f"Invalid speed value received: {request.speed}")
  780. raise HTTPException(status_code=400, detail="Invalid speed value")
  781. state.speed = request.speed
  782. return {"success": True, "speed": request.speed}
  783. except Exception as e:
  784. logger.error(f"Failed to set speed: {str(e)}")
  785. raise HTTPException(status_code=500, detail=str(e))
  786. @app.get("/check_software_update")
  787. async def check_updates():
  788. update_info = update_manager.check_git_updates()
  789. return update_info
  790. @app.post("/update_software")
  791. async def update_software():
  792. logger.info("Starting software update process")
  793. success, error_message, error_log = update_manager.update_software()
  794. if success:
  795. logger.info("Software update completed successfully")
  796. return {"success": True}
  797. else:
  798. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  799. raise HTTPException(
  800. status_code=500,
  801. detail={
  802. "error": error_message,
  803. "details": error_log
  804. }
  805. )
  806. @app.post("/set_wled_ip")
  807. async def set_wled_ip(request: WLEDRequest):
  808. state.wled_ip = request.wled_ip
  809. state.led_controller = LEDController(request.wled_ip)
  810. effect_idle(state.led_controller)
  811. state.save()
  812. logger.info(f"WLED IP updated: {request.wled_ip}")
  813. return {"success": True, "wled_ip": state.wled_ip}
  814. @app.get("/get_wled_ip")
  815. async def get_wled_ip():
  816. if not state.wled_ip:
  817. raise HTTPException(status_code=404, detail="No WLED IP set")
  818. return {"success": True, "wled_ip": state.wled_ip}
  819. @app.post("/skip_pattern")
  820. async def skip_pattern():
  821. if not state.current_playlist:
  822. raise HTTPException(status_code=400, detail="No playlist is currently running")
  823. state.skip_requested = True
  824. return {"success": True}
  825. @app.get("/api/custom_clear_patterns")
  826. async def get_custom_clear_patterns():
  827. """Get the currently configured custom clear patterns."""
  828. return {
  829. "success": True,
  830. "custom_clear_from_in": state.custom_clear_from_in,
  831. "custom_clear_from_out": state.custom_clear_from_out
  832. }
  833. @app.post("/api/custom_clear_patterns")
  834. async def set_custom_clear_patterns(request: dict):
  835. """Set custom clear patterns for clear_from_in and clear_from_out."""
  836. try:
  837. # Validate that the patterns exist if they're provided
  838. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  839. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  840. if not os.path.exists(pattern_path):
  841. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  842. state.custom_clear_from_in = request["custom_clear_from_in"]
  843. elif "custom_clear_from_in" in request:
  844. state.custom_clear_from_in = None
  845. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  846. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  847. if not os.path.exists(pattern_path):
  848. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  849. state.custom_clear_from_out = request["custom_clear_from_out"]
  850. elif "custom_clear_from_out" in request:
  851. state.custom_clear_from_out = None
  852. state.save()
  853. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  854. return {
  855. "success": True,
  856. "custom_clear_from_in": state.custom_clear_from_in,
  857. "custom_clear_from_out": state.custom_clear_from_out
  858. }
  859. except Exception as e:
  860. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  861. raise HTTPException(status_code=500, detail=str(e))
  862. @app.get("/api/clear_pattern_speed")
  863. async def get_clear_pattern_speed():
  864. """Get the current clearing pattern speed setting."""
  865. return {
  866. "success": True,
  867. "clear_pattern_speed": state.clear_pattern_speed,
  868. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  869. }
  870. @app.post("/api/clear_pattern_speed")
  871. async def set_clear_pattern_speed(request: dict):
  872. """Set the clearing pattern speed."""
  873. try:
  874. # If speed is None or "none", use default behavior (state.speed)
  875. speed_value = request.get("clear_pattern_speed")
  876. if speed_value is None or speed_value == "none" or speed_value == "":
  877. speed = None
  878. else:
  879. speed = int(speed_value)
  880. # Validate speed range (same as regular speed limits) only if speed is not None
  881. if speed is not None and not (50 <= speed <= 2000):
  882. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  883. state.clear_pattern_speed = speed
  884. state.save()
  885. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  886. return {
  887. "success": True,
  888. "clear_pattern_speed": state.clear_pattern_speed,
  889. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  890. }
  891. except ValueError:
  892. raise HTTPException(status_code=400, detail="Invalid speed value")
  893. except Exception as e:
  894. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  895. raise HTTPException(status_code=500, detail=str(e))
  896. @app.get("/api/app-name")
  897. async def get_app_name():
  898. """Get current application name."""
  899. return {"app_name": state.app_name}
  900. @app.post("/api/app-name")
  901. async def set_app_name(request: dict):
  902. """Update application name."""
  903. app_name = request.get("app_name", "").strip()
  904. if not app_name:
  905. app_name = "Dune Weaver" # Reset to default if empty
  906. state.app_name = app_name
  907. state.save()
  908. logger.info(f"Application name updated to: {app_name}")
  909. return {"success": True, "app_name": app_name}
  910. @app.post("/preview_thr_batch")
  911. async def preview_thr_batch(request: dict):
  912. start = time.time()
  913. if not request.get("file_names"):
  914. logger.warning("Batch preview request received without filenames")
  915. raise HTTPException(status_code=400, detail="No file names provided")
  916. file_names = request["file_names"]
  917. if not isinstance(file_names, list):
  918. raise HTTPException(status_code=400, detail="file_names must be a list")
  919. headers = {
  920. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  921. "Content-Type": "application/json"
  922. }
  923. async def process_single_file(file_name):
  924. """Process a single file and return its preview data."""
  925. t1 = time.time()
  926. try:
  927. # Normalize file path for cross-platform compatibility
  928. normalized_file_name = normalize_file_path(file_name)
  929. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  930. # Check file existence asynchronously
  931. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  932. if not exists:
  933. logger.warning(f"Pattern file not found: {pattern_file_path}")
  934. return file_name, {"error": "Pattern file not found"}
  935. cache_path = get_cache_path(normalized_file_name)
  936. # Check cache existence asynchronously
  937. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  938. if not cache_exists:
  939. logger.info(f"Cache miss for {file_name}. Generating preview...")
  940. success = await generate_image_preview(normalized_file_name)
  941. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  942. if not success or not cache_exists_after:
  943. logger.error(f"Failed to generate or find preview for {file_name}")
  944. return file_name, {"error": "Failed to generate preview"}
  945. metadata = get_pattern_metadata(normalized_file_name)
  946. if metadata:
  947. first_coord_obj = metadata.get('first_coordinate')
  948. last_coord_obj = metadata.get('last_coordinate')
  949. else:
  950. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  951. # Use process pool for CPU-intensive parsing
  952. loop = asyncio.get_event_loop()
  953. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, pattern_file_path)
  954. first_coord = coordinates[0] if coordinates else None
  955. last_coord = coordinates[-1] if coordinates else None
  956. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  957. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  958. # Read image file asynchronously
  959. image_data = await asyncio.to_thread(lambda: open(cache_path, 'rb').read())
  960. image_b64 = base64.b64encode(image_data).decode('utf-8')
  961. result = {
  962. "image_data": f"data:image/webp;base64,{image_b64}",
  963. "first_coordinate": first_coord_obj,
  964. "last_coordinate": last_coord_obj
  965. }
  966. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  967. return file_name, result
  968. except Exception as e:
  969. logger.error(f"Error processing {file_name}: {str(e)}")
  970. return file_name, {"error": str(e)}
  971. # Process all files concurrently
  972. tasks = [process_single_file(file_name) for file_name in file_names]
  973. file_results = await asyncio.gather(*tasks)
  974. # Convert results to dictionary
  975. results = dict(file_results)
  976. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  977. return JSONResponse(content=results, headers=headers)
  978. @app.get("/playlists")
  979. async def playlists(request: Request):
  980. logger.debug("Rendering playlists page")
  981. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name})
  982. @app.get("/image2sand")
  983. async def image2sand(request: Request):
  984. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name})
  985. @app.get("/wled")
  986. async def wled(request: Request):
  987. return templates.TemplateResponse("wled.html", {"request": request, "app_name": state.app_name})
  988. @app.get("/table_control")
  989. async def table_control(request: Request):
  990. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name})
  991. @app.get("/cache-progress")
  992. async def get_cache_progress_endpoint():
  993. """Get the current cache generation progress."""
  994. from modules.core.cache_manager import get_cache_progress
  995. return get_cache_progress()
  996. @app.post("/rebuild_cache")
  997. async def rebuild_cache_endpoint():
  998. """Trigger a rebuild of the pattern cache."""
  999. try:
  1000. from modules.core.cache_manager import rebuild_cache
  1001. await rebuild_cache()
  1002. return {"success": True, "message": "Cache rebuild completed successfully"}
  1003. except Exception as e:
  1004. logger.error(f"Failed to rebuild cache: {str(e)}")
  1005. raise HTTPException(status_code=500, detail=str(e))
  1006. def signal_handler(signum, frame):
  1007. """Handle shutdown signals gracefully but forcefully."""
  1008. logger.info("Received shutdown signal, cleaning up...")
  1009. try:
  1010. if state.led_controller:
  1011. state.led_controller.set_power(0)
  1012. # Run cleanup operations - need to handle async in sync context
  1013. try:
  1014. # Try to run in existing loop if available
  1015. import asyncio
  1016. loop = asyncio.get_running_loop()
  1017. # If we're in an event loop, schedule the coroutine
  1018. import concurrent.futures
  1019. with concurrent.futures.ThreadPoolExecutor() as executor:
  1020. future = executor.submit(asyncio.run, pattern_manager.stop_actions())
  1021. future.result(timeout=5.0) # Wait up to 5 seconds
  1022. except RuntimeError:
  1023. # No running loop, create a new one
  1024. import asyncio
  1025. asyncio.run(pattern_manager.stop_actions())
  1026. except Exception as cleanup_err:
  1027. logger.error(f"Error in async cleanup: {cleanup_err}")
  1028. state.save()
  1029. logger.info("Cleanup completed")
  1030. except Exception as e:
  1031. logger.error(f"Error during cleanup: {str(e)}")
  1032. finally:
  1033. logger.info("Exiting application...")
  1034. os._exit(0) # Force exit regardless of other threads
  1035. @app.get("/api/version")
  1036. async def get_version_info():
  1037. """Get current and latest version information"""
  1038. try:
  1039. version_info = await version_manager.get_version_info()
  1040. return JSONResponse(content=version_info)
  1041. except Exception as e:
  1042. logger.error(f"Error getting version info: {e}")
  1043. return JSONResponse(
  1044. content={
  1045. "current": version_manager.get_current_version(),
  1046. "latest": version_manager.get_current_version(),
  1047. "update_available": False,
  1048. "error": "Unable to check for updates"
  1049. },
  1050. status_code=200
  1051. )
  1052. @app.post("/api/update")
  1053. async def trigger_update():
  1054. """Trigger software update (placeholder for future implementation)"""
  1055. try:
  1056. # For now, just return the GitHub release URL
  1057. version_info = await version_manager.get_version_info()
  1058. if version_info.get("latest_release"):
  1059. return JSONResponse(content={
  1060. "success": False,
  1061. "message": "Automatic updates not implemented yet",
  1062. "manual_update_url": version_info["latest_release"].get("html_url"),
  1063. "instructions": "Please visit the GitHub release page to download and install the update manually"
  1064. })
  1065. else:
  1066. return JSONResponse(content={
  1067. "success": False,
  1068. "message": "No updates available"
  1069. })
  1070. except Exception as e:
  1071. logger.error(f"Error triggering update: {e}")
  1072. return JSONResponse(
  1073. content={"success": False, "message": "Failed to check for updates"},
  1074. status_code=500
  1075. )
  1076. def entrypoint():
  1077. import uvicorn
  1078. logger.info("Starting FastAPI server on port 8080...")
  1079. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  1080. if __name__ == "__main__":
  1081. entrypoint()