main.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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. from modules.led.led_interface import LEDInterface
  24. import math
  25. from modules.core.cache_manager import generate_all_image_previews, get_cache_path, generate_image_preview, get_pattern_metadata
  26. from modules.core.version_manager import version_manager
  27. import json
  28. import base64
  29. import time
  30. import argparse
  31. from concurrent.futures import ProcessPoolExecutor
  32. import multiprocessing
  33. # Get log level from environment variable, default to INFO
  34. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  35. log_level = getattr(logging, log_level_str, logging.INFO)
  36. # Create a process pool for CPU-intensive tasks
  37. # Limit to reasonable number of workers for embedded systems
  38. cpu_count = multiprocessing.cpu_count()
  39. # Maximum 3 workers (leaving 1 for motion), minimum 1
  40. process_pool_size = min(3, max(1, cpu_count - 1))
  41. process_pool = None # Will be initialized in lifespan
  42. logging.basicConfig(
  43. level=log_level,
  44. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  45. handlers=[
  46. logging.StreamHandler(),
  47. ]
  48. )
  49. logger = logging.getLogger(__name__)
  50. def normalize_file_path(file_path: str) -> str:
  51. """Normalize file path separators for consistent cross-platform handling."""
  52. if not file_path:
  53. return ''
  54. # First normalize path separators
  55. normalized = file_path.replace('\\', '/')
  56. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  57. if normalized.startswith('./patterns/'):
  58. normalized = normalized[11:]
  59. elif normalized.startswith('patterns/'):
  60. normalized = normalized[9:]
  61. return normalized
  62. @asynccontextmanager
  63. async def lifespan(app: FastAPI):
  64. # Startup
  65. logger.info("Starting Dune Weaver application...")
  66. # Register signal handlers
  67. signal.signal(signal.SIGINT, signal_handler)
  68. signal.signal(signal.SIGTERM, signal_handler)
  69. # Initialize process pool for CPU-intensive tasks
  70. global process_pool
  71. process_pool = ProcessPoolExecutor(max_workers=process_pool_size)
  72. logger.info(f"Initialized process pool with {process_pool_size} workers (detected {cpu_count} cores total)")
  73. try:
  74. connection_manager.connect_device()
  75. except Exception as e:
  76. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  77. # Initialize LED controller based on saved configuration
  78. try:
  79. # Auto-detect provider for backward compatibility with existing installations
  80. if not state.led_provider or state.led_provider == "none":
  81. if state.wled_ip:
  82. state.led_provider = "wled"
  83. logger.info("Auto-detected WLED provider from existing configuration")
  84. elif state.hyperion_ip:
  85. state.led_provider = "hyperion"
  86. logger.info("Auto-detected Hyperion provider from existing configuration")
  87. # Initialize the appropriate controller
  88. if state.led_provider == "wled" and state.wled_ip:
  89. state.led_controller = LEDInterface("wled", state.wled_ip)
  90. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  91. elif state.led_provider == "hyperion" and state.hyperion_ip:
  92. state.led_controller = LEDInterface("hyperion", state.hyperion_ip, state.hyperion_port)
  93. logger.info(f"LED controller initialized: Hyperion at {state.hyperion_ip}:{state.hyperion_port}")
  94. else:
  95. state.led_controller = None
  96. logger.info("LED controller not configured")
  97. # Save if provider was auto-detected
  98. if state.led_provider and (state.wled_ip or state.hyperion_ip):
  99. state.save()
  100. except Exception as e:
  101. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  102. state.led_controller = None
  103. # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
  104. if state.auto_play_enabled and state.auto_play_playlist:
  105. logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
  106. try:
  107. # Check if we have a valid connection before starting playlist
  108. if state.conn and hasattr(state.conn, 'is_connected') and state.conn.is_connected():
  109. 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}")
  110. asyncio.create_task(playlist_manager.run_playlist(
  111. state.auto_play_playlist,
  112. pause_time=state.auto_play_pause_time,
  113. clear_pattern=state.auto_play_clear_pattern,
  114. run_mode=state.auto_play_run_mode,
  115. shuffle=state.auto_play_shuffle
  116. ))
  117. else:
  118. logger.warning("No hardware connection available, skipping auto_play mode auto-play")
  119. except Exception as e:
  120. logger.error(f"Failed to auto-play auto_play playlist: {str(e)}")
  121. try:
  122. mqtt_handler = mqtt.init_mqtt()
  123. except Exception as e:
  124. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  125. # Schedule cache generation check for later (non-blocking startup)
  126. async def delayed_cache_check():
  127. """Check and generate cache in background."""
  128. try:
  129. logger.info("Starting cache check...")
  130. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  131. if await is_cache_generation_needed_async():
  132. logger.info("Cache generation needed, starting background task...")
  133. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  134. else:
  135. logger.info("Cache is up to date, skipping generation")
  136. except Exception as e:
  137. logger.warning(f"Failed during cache generation: {str(e)}")
  138. # Start cache check in background immediately
  139. asyncio.create_task(delayed_cache_check())
  140. yield # This separates startup from shutdown code
  141. # Shutdown
  142. logger.info("Shutting down Dune Weaver application...")
  143. # Shutdown process pool
  144. if process_pool:
  145. process_pool.shutdown(wait=True)
  146. logger.info("Process pool shutdown complete")
  147. app = FastAPI(lifespan=lifespan)
  148. templates = Jinja2Templates(directory="templates")
  149. app.mount("/static", StaticFiles(directory="static"), name="static")
  150. # Pydantic models for request/response validation
  151. class ConnectRequest(BaseModel):
  152. port: Optional[str] = None
  153. class auto_playModeRequest(BaseModel):
  154. enabled: bool
  155. playlist: Optional[str] = None
  156. run_mode: Optional[str] = "loop"
  157. pause_time: Optional[float] = 5.0
  158. clear_pattern: Optional[str] = "adaptive"
  159. shuffle: Optional[bool] = False
  160. class TimeSlot(BaseModel):
  161. start_time: str # HH:MM format
  162. end_time: str # HH:MM format
  163. days: str # "daily", "weekdays", "weekends", or "custom"
  164. custom_days: Optional[List[str]] = [] # ["monday", "tuesday", etc.]
  165. class ScheduledPauseRequest(BaseModel):
  166. enabled: bool
  167. control_wled: Optional[bool] = False
  168. time_slots: List[TimeSlot] = []
  169. class CoordinateRequest(BaseModel):
  170. theta: float
  171. rho: float
  172. class PlaylistRequest(BaseModel):
  173. playlist_name: str
  174. files: List[str] = []
  175. pause_time: float = 0
  176. clear_pattern: Optional[str] = None
  177. run_mode: str = "single"
  178. shuffle: bool = False
  179. class PlaylistRunRequest(BaseModel):
  180. playlist_name: str
  181. pause_time: Optional[float] = 0
  182. clear_pattern: Optional[str] = None
  183. run_mode: Optional[str] = "single"
  184. shuffle: Optional[bool] = False
  185. start_time: Optional[str] = None
  186. end_time: Optional[str] = None
  187. class SpeedRequest(BaseModel):
  188. speed: float
  189. class WLEDRequest(BaseModel):
  190. wled_ip: Optional[str] = None
  191. class LEDConfigRequest(BaseModel):
  192. provider: str # "wled", "hyperion", or "none"
  193. ip_address: Optional[str] = None
  194. port: Optional[int] = None
  195. class DeletePlaylistRequest(BaseModel):
  196. playlist_name: str
  197. class ThetaRhoRequest(BaseModel):
  198. file_name: str
  199. pre_execution: Optional[str] = "none"
  200. class GetCoordinatesRequest(BaseModel):
  201. file_name: str
  202. # Store active WebSocket connections
  203. active_status_connections = set()
  204. active_cache_progress_connections = set()
  205. @app.websocket("/ws/status")
  206. async def websocket_status_endpoint(websocket: WebSocket):
  207. await websocket.accept()
  208. active_status_connections.add(websocket)
  209. try:
  210. while True:
  211. status = pattern_manager.get_status()
  212. try:
  213. await websocket.send_json({
  214. "type": "status_update",
  215. "data": status
  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)
  222. except WebSocketDisconnect:
  223. pass
  224. finally:
  225. active_status_connections.discard(websocket)
  226. try:
  227. await websocket.close()
  228. except RuntimeError:
  229. pass
  230. async def broadcast_status_update(status: dict):
  231. """Broadcast status update to all connected clients."""
  232. disconnected = set()
  233. for websocket in active_status_connections:
  234. try:
  235. await websocket.send_json({
  236. "type": "status_update",
  237. "data": status
  238. })
  239. except WebSocketDisconnect:
  240. disconnected.add(websocket)
  241. except RuntimeError:
  242. disconnected.add(websocket)
  243. active_status_connections.difference_update(disconnected)
  244. @app.websocket("/ws/cache-progress")
  245. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  246. from modules.core.cache_manager import get_cache_progress
  247. await websocket.accept()
  248. active_cache_progress_connections.add(websocket)
  249. try:
  250. while True:
  251. progress = get_cache_progress()
  252. try:
  253. await websocket.send_json({
  254. "type": "cache_progress",
  255. "data": progress
  256. })
  257. except RuntimeError as e:
  258. if "close message has been sent" in str(e):
  259. break
  260. raise
  261. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  262. except WebSocketDisconnect:
  263. pass
  264. finally:
  265. active_cache_progress_connections.discard(websocket)
  266. try:
  267. await websocket.close()
  268. except RuntimeError:
  269. pass
  270. # FastAPI routes
  271. @app.get("/")
  272. async def index(request: Request):
  273. return templates.TemplateResponse("index.html", {"request": request, "app_name": state.app_name})
  274. @app.get("/settings")
  275. async def settings(request: Request):
  276. return templates.TemplateResponse("settings.html", {"request": request, "app_name": state.app_name})
  277. @app.get("/api/auto_play-mode")
  278. async def get_auto_play_mode():
  279. """Get current auto_play mode settings."""
  280. return {
  281. "enabled": state.auto_play_enabled,
  282. "playlist": state.auto_play_playlist,
  283. "run_mode": state.auto_play_run_mode,
  284. "pause_time": state.auto_play_pause_time,
  285. "clear_pattern": state.auto_play_clear_pattern,
  286. "shuffle": state.auto_play_shuffle
  287. }
  288. @app.post("/api/auto_play-mode")
  289. async def set_auto_play_mode(request: auto_playModeRequest):
  290. """Update auto_play mode settings."""
  291. state.auto_play_enabled = request.enabled
  292. if request.playlist is not None:
  293. state.auto_play_playlist = request.playlist
  294. if request.run_mode is not None:
  295. state.auto_play_run_mode = request.run_mode
  296. if request.pause_time is not None:
  297. state.auto_play_pause_time = request.pause_time
  298. if request.clear_pattern is not None:
  299. state.auto_play_clear_pattern = request.clear_pattern
  300. if request.shuffle is not None:
  301. state.auto_play_shuffle = request.shuffle
  302. state.save()
  303. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  304. return {"success": True, "message": "auto_play mode settings updated"}
  305. @app.get("/api/scheduled-pause")
  306. async def get_scheduled_pause():
  307. """Get current Still Sands settings."""
  308. return {
  309. "enabled": state.scheduled_pause_enabled,
  310. "control_wled": state.scheduled_pause_control_wled,
  311. "time_slots": state.scheduled_pause_time_slots
  312. }
  313. @app.post("/api/scheduled-pause")
  314. async def set_scheduled_pause(request: ScheduledPauseRequest):
  315. """Update Still Sands settings."""
  316. try:
  317. # Validate time slots
  318. for i, slot in enumerate(request.time_slots):
  319. # Validate time format (HH:MM)
  320. try:
  321. start_time = datetime.strptime(slot.start_time, "%H:%M").time()
  322. end_time = datetime.strptime(slot.end_time, "%H:%M").time()
  323. except ValueError:
  324. raise HTTPException(
  325. status_code=400,
  326. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  327. )
  328. # Validate days setting
  329. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  330. raise HTTPException(
  331. status_code=400,
  332. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  333. )
  334. # Validate custom days if applicable
  335. if slot.days == "custom":
  336. if not slot.custom_days or len(slot.custom_days) == 0:
  337. raise HTTPException(
  338. status_code=400,
  339. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  340. )
  341. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  342. for day in slot.custom_days:
  343. if day not in valid_days:
  344. raise HTTPException(
  345. status_code=400,
  346. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  347. )
  348. # Update state
  349. state.scheduled_pause_enabled = request.enabled
  350. state.scheduled_pause_control_wled = request.control_wled
  351. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  352. state.save()
  353. wled_msg = " (with WLED control)" if request.control_wled else ""
  354. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}")
  355. return {"success": True, "message": "Still Sands settings updated"}
  356. except HTTPException:
  357. raise
  358. except Exception as e:
  359. logger.error(f"Error updating Still Sands settings: {str(e)}")
  360. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  361. @app.get("/list_serial_ports")
  362. async def list_ports():
  363. logger.debug("Listing available serial ports")
  364. return await asyncio.to_thread(connection_manager.list_serial_ports)
  365. @app.post("/connect")
  366. async def connect(request: ConnectRequest):
  367. if not request.port:
  368. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  369. connection_manager.device_init()
  370. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  371. return {"success": True}
  372. try:
  373. state.conn = connection_manager.SerialConnection(request.port)
  374. connection_manager.device_init()
  375. logger.info(f'Successfully connected to serial port {request.port}')
  376. return {"success": True}
  377. except Exception as e:
  378. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  379. raise HTTPException(status_code=500, detail=str(e))
  380. @app.post("/disconnect")
  381. async def disconnect():
  382. try:
  383. state.conn.close()
  384. logger.info('Successfully disconnected from serial port')
  385. return {"success": True}
  386. except Exception as e:
  387. logger.error(f'Failed to disconnect serial: {str(e)}')
  388. raise HTTPException(status_code=500, detail=str(e))
  389. @app.post("/restart_connection")
  390. async def restart(request: ConnectRequest):
  391. if not request.port:
  392. logger.warning("Restart serial request received without port")
  393. raise HTTPException(status_code=400, detail="No port provided")
  394. try:
  395. logger.info(f"Restarting connection on port {request.port}")
  396. connection_manager.restart_connection()
  397. return {"success": True}
  398. except Exception as e:
  399. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  400. raise HTTPException(status_code=500, detail=str(e))
  401. @app.get("/list_theta_rho_files")
  402. async def list_theta_rho_files():
  403. logger.debug("Listing theta-rho files")
  404. # Run the blocking file system operation in a thread pool
  405. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  406. return sorted(files)
  407. @app.get("/list_theta_rho_files_with_metadata")
  408. async def list_theta_rho_files_with_metadata():
  409. """Get list of theta-rho files with metadata for sorting and filtering.
  410. Optimized to process files asynchronously and support request cancellation.
  411. """
  412. from modules.core.cache_manager import get_pattern_metadata
  413. import asyncio
  414. from concurrent.futures import ThreadPoolExecutor
  415. # Run the blocking file listing in a thread
  416. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  417. files_with_metadata = []
  418. # Use ThreadPoolExecutor for I/O-bound operations
  419. executor = ThreadPoolExecutor(max_workers=4)
  420. def process_file(file_path):
  421. """Process a single file and return its metadata."""
  422. try:
  423. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  424. # Get file stats
  425. file_stat = os.stat(full_path)
  426. # Get cached metadata (this should be fast if cached)
  427. metadata = get_pattern_metadata(file_path)
  428. # Extract full folder path from file path
  429. path_parts = file_path.split('/')
  430. if len(path_parts) > 1:
  431. # Get everything except the filename (join all folder parts)
  432. category = '/'.join(path_parts[:-1])
  433. else:
  434. category = 'root'
  435. # Get file name without extension
  436. file_name = os.path.splitext(os.path.basename(file_path))[0]
  437. # Use modification time (mtime) for "date modified"
  438. date_modified = file_stat.st_mtime
  439. return {
  440. 'path': file_path,
  441. 'name': file_name,
  442. 'category': category,
  443. 'date_modified': date_modified,
  444. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  445. }
  446. except Exception as e:
  447. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  448. # Include file with minimal info if metadata fails
  449. path_parts = file_path.split('/')
  450. if len(path_parts) > 1:
  451. category = '/'.join(path_parts[:-1])
  452. else:
  453. category = 'root'
  454. return {
  455. 'path': file_path,
  456. 'name': os.path.splitext(os.path.basename(file_path))[0],
  457. 'category': category,
  458. 'date_modified': 0,
  459. 'coordinates_count': 0
  460. }
  461. # Load the entire metadata cache at once (async)
  462. # This is much faster than 1000+ individual metadata lookups
  463. try:
  464. import json
  465. metadata_cache_path = "metadata_cache.json"
  466. # Use async file reading to avoid blocking the event loop
  467. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  468. cache_dict = cache_data.get('data', {})
  469. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  470. # Process all files using cached data only
  471. for file_path in files:
  472. try:
  473. # Extract category from path
  474. path_parts = file_path.split('/')
  475. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  476. # Get file name without extension
  477. file_name = os.path.splitext(os.path.basename(file_path))[0]
  478. # Get metadata from cache
  479. cached_entry = cache_dict.get(file_path, {})
  480. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  481. metadata = cached_entry['metadata']
  482. coords_count = metadata.get('total_coordinates', 0)
  483. date_modified = cached_entry.get('mtime', 0)
  484. else:
  485. coords_count = 0
  486. date_modified = 0
  487. files_with_metadata.append({
  488. 'path': file_path,
  489. 'name': file_name,
  490. 'category': category,
  491. 'date_modified': date_modified,
  492. 'coordinates_count': coords_count
  493. })
  494. except Exception as e:
  495. logger.warning(f"Error processing {file_path}: {e}")
  496. # Include file with minimal info if processing fails
  497. path_parts = file_path.split('/')
  498. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  499. files_with_metadata.append({
  500. 'path': file_path,
  501. 'name': os.path.splitext(os.path.basename(file_path))[0],
  502. 'category': category,
  503. 'date_modified': 0,
  504. 'coordinates_count': 0
  505. })
  506. except Exception as e:
  507. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  508. # Fallback to original method if cache loading fails
  509. # Create tasks only when needed
  510. loop = asyncio.get_event_loop()
  511. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  512. for task in asyncio.as_completed(tasks):
  513. try:
  514. result = await task
  515. files_with_metadata.append(result)
  516. except Exception as task_error:
  517. logger.error(f"Error processing file: {str(task_error)}")
  518. # Clean up executor
  519. executor.shutdown(wait=False)
  520. return files_with_metadata
  521. @app.post("/upload_theta_rho")
  522. async def upload_theta_rho(file: UploadFile = File(...)):
  523. """Upload a theta-rho file."""
  524. try:
  525. # Save the file
  526. # Ensure custom_patterns directory exists
  527. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  528. os.makedirs(custom_patterns_dir, exist_ok=True)
  529. # Use forward slashes for internal path representation to maintain consistency
  530. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  531. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  532. # Save the uploaded file with proper encoding for Windows compatibility
  533. file_content = await file.read()
  534. try:
  535. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  536. text_content = file_content.decode('utf-8')
  537. with open(full_file_path, "w", encoding='utf-8') as f:
  538. f.write(text_content)
  539. except UnicodeDecodeError:
  540. # If UTF-8 decoding fails, save as binary (fallback)
  541. with open(full_file_path, "wb") as f:
  542. f.write(file_content)
  543. logger.info(f"File {file.filename} saved successfully")
  544. # Generate image preview for the new file with retry logic
  545. max_retries = 3
  546. for attempt in range(max_retries):
  547. try:
  548. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  549. success = await generate_image_preview(file_path_in_patterns_dir)
  550. if success:
  551. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  552. break
  553. else:
  554. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  555. if attempt < max_retries - 1:
  556. await asyncio.sleep(0.5) # Small delay before retry
  557. except Exception as e:
  558. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  559. if attempt < max_retries - 1:
  560. await asyncio.sleep(0.5) # Small delay before retry
  561. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  562. except Exception as e:
  563. logger.error(f"Error uploading file: {str(e)}")
  564. raise HTTPException(status_code=500, detail=str(e))
  565. @app.post("/get_theta_rho_coordinates")
  566. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  567. """Get theta-rho coordinates for animated preview."""
  568. try:
  569. # Normalize file path for cross-platform compatibility and remove prefixes
  570. file_name = normalize_file_path(request.file_name)
  571. file_path = os.path.join(THETA_RHO_DIR, file_name)
  572. # Check file existence asynchronously
  573. exists = await asyncio.to_thread(os.path.exists, file_path)
  574. if not exists:
  575. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  576. # Parse the theta-rho file in a separate process for CPU-intensive work
  577. # This prevents blocking the motion control thread
  578. loop = asyncio.get_event_loop()
  579. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, file_path)
  580. if not coordinates:
  581. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  582. return {
  583. "success": True,
  584. "coordinates": coordinates,
  585. "total_points": len(coordinates)
  586. }
  587. except Exception as e:
  588. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  589. raise HTTPException(status_code=500, detail=str(e))
  590. @app.post("/run_theta_rho")
  591. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  592. if not request.file_name:
  593. logger.warning('Run theta-rho request received without file name')
  594. raise HTTPException(status_code=400, detail="No file name provided")
  595. file_path = None
  596. if 'clear' in request.file_name:
  597. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  598. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  599. logger.info(f'Clear pattern file: {file_path}')
  600. if not file_path:
  601. # Normalize file path for cross-platform compatibility
  602. normalized_file_name = normalize_file_path(request.file_name)
  603. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  604. if not os.path.exists(file_path):
  605. logger.error(f'Theta-rho file not found: {file_path}')
  606. raise HTTPException(status_code=404, detail="File not found")
  607. try:
  608. if not (state.conn.is_connected() if state.conn else False):
  609. logger.warning("Attempted to run a pattern without a connection")
  610. raise HTTPException(status_code=400, detail="Connection not established")
  611. if pattern_manager.pattern_lock.locked():
  612. logger.warning("Attempted to run a pattern while another is already running")
  613. raise HTTPException(status_code=409, detail="Another pattern is already running")
  614. files_to_run = [file_path]
  615. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  616. # Only include clear_pattern if it's not "none"
  617. kwargs = {}
  618. if request.pre_execution != "none":
  619. kwargs['clear_pattern'] = request.pre_execution
  620. # Pass arguments properly
  621. background_tasks.add_task(
  622. pattern_manager.run_theta_rho_files,
  623. files_to_run, # First positional argument
  624. **kwargs # Spread keyword arguments
  625. )
  626. return {"success": True}
  627. except HTTPException as http_exc:
  628. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  629. raise http_exc
  630. except Exception as e:
  631. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  632. raise HTTPException(status_code=500, detail=str(e))
  633. @app.post("/stop_execution")
  634. async def stop_execution():
  635. if not (state.conn.is_connected() if state.conn else False):
  636. logger.warning("Attempted to stop without a connection")
  637. raise HTTPException(status_code=400, detail="Connection not established")
  638. await pattern_manager.stop_actions()
  639. return {"success": True}
  640. @app.post("/send_home")
  641. async def send_home():
  642. try:
  643. if not (state.conn.is_connected() if state.conn else False):
  644. logger.warning("Attempted to move to home without a connection")
  645. raise HTTPException(status_code=400, detail="Connection not established")
  646. # Run homing with 15 second timeout
  647. success = await asyncio.to_thread(connection_manager.home)
  648. if not success:
  649. logger.error("Homing failed or timed out")
  650. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  651. return {"success": True}
  652. except HTTPException:
  653. raise
  654. except Exception as e:
  655. logger.error(f"Failed to send home command: {str(e)}")
  656. raise HTTPException(status_code=500, detail=str(e))
  657. @app.post("/run_theta_rho_file/{file_name}")
  658. async def run_specific_theta_rho_file(file_name: str):
  659. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  660. if not os.path.exists(file_path):
  661. raise HTTPException(status_code=404, detail="File not found")
  662. if not (state.conn.is_connected() if state.conn else False):
  663. logger.warning("Attempted to run a pattern without a connection")
  664. raise HTTPException(status_code=400, detail="Connection not established")
  665. pattern_manager.run_theta_rho_file(file_path)
  666. return {"success": True}
  667. class DeleteFileRequest(BaseModel):
  668. file_name: str
  669. @app.post("/delete_theta_rho_file")
  670. async def delete_theta_rho_file(request: DeleteFileRequest):
  671. if not request.file_name:
  672. logger.warning("Delete theta-rho file request received without filename")
  673. raise HTTPException(status_code=400, detail="No file name provided")
  674. # Normalize file path for cross-platform compatibility
  675. normalized_file_name = normalize_file_path(request.file_name)
  676. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  677. # Check file existence asynchronously
  678. exists = await asyncio.to_thread(os.path.exists, file_path)
  679. if not exists:
  680. logger.error(f"Attempted to delete non-existent file: {file_path}")
  681. raise HTTPException(status_code=404, detail="File not found")
  682. try:
  683. # Delete the pattern file asynchronously
  684. await asyncio.to_thread(os.remove, file_path)
  685. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  686. # Clean up cached preview image and metadata asynchronously
  687. from modules.core.cache_manager import delete_pattern_cache
  688. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  689. if cache_cleanup_success:
  690. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  691. else:
  692. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  693. return {"success": True, "cache_cleanup": cache_cleanup_success}
  694. except Exception as e:
  695. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  696. raise HTTPException(status_code=500, detail=str(e))
  697. @app.post("/move_to_center")
  698. async def move_to_center():
  699. try:
  700. if not (state.conn.is_connected() if state.conn else False):
  701. logger.warning("Attempted to move to center without a connection")
  702. raise HTTPException(status_code=400, detail="Connection not established")
  703. logger.info("Moving device to center position")
  704. await pattern_manager.reset_theta()
  705. await pattern_manager.move_polar(0, 0)
  706. return {"success": True}
  707. except Exception as e:
  708. logger.error(f"Failed to move to center: {str(e)}")
  709. raise HTTPException(status_code=500, detail=str(e))
  710. @app.post("/move_to_perimeter")
  711. async def move_to_perimeter():
  712. try:
  713. if not (state.conn.is_connected() if state.conn else False):
  714. logger.warning("Attempted to move to perimeter without a connection")
  715. raise HTTPException(status_code=400, detail="Connection not established")
  716. await pattern_manager.reset_theta()
  717. await pattern_manager.move_polar(0, 1)
  718. return {"success": True}
  719. except Exception as e:
  720. logger.error(f"Failed to move to perimeter: {str(e)}")
  721. raise HTTPException(status_code=500, detail=str(e))
  722. @app.post("/preview_thr")
  723. async def preview_thr(request: DeleteFileRequest):
  724. if not request.file_name:
  725. logger.warning("Preview theta-rho request received without filename")
  726. raise HTTPException(status_code=400, detail="No file name provided")
  727. # Normalize file path for cross-platform compatibility
  728. normalized_file_name = normalize_file_path(request.file_name)
  729. # Construct the full path to the pattern file to check existence
  730. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  731. # Check file existence asynchronously
  732. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  733. if not exists:
  734. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  735. raise HTTPException(status_code=404, detail="Pattern file not found")
  736. try:
  737. cache_path = get_cache_path(normalized_file_name)
  738. # Check cache existence asynchronously
  739. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  740. if not cache_exists:
  741. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  742. # Attempt to generate the preview if it's missing
  743. success = await generate_image_preview(normalized_file_name)
  744. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  745. if not success or not cache_exists_after:
  746. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  747. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  748. # Try to get coordinates from metadata cache first
  749. metadata = get_pattern_metadata(normalized_file_name)
  750. if metadata:
  751. first_coord_obj = metadata.get('first_coordinate')
  752. last_coord_obj = metadata.get('last_coordinate')
  753. else:
  754. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  755. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  756. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  757. first_coord = coordinates[0] if coordinates else None
  758. last_coord = coordinates[-1] if coordinates else None
  759. # Format coordinates as objects with x and y properties
  760. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  761. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  762. # Return JSON with preview URL and coordinates
  763. # URL encode the file_name for the preview URL
  764. # Handle both forward slashes and backslashes for cross-platform compatibility
  765. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  766. return {
  767. "preview_url": f"/preview/{encoded_filename}",
  768. "first_coordinate": first_coord_obj,
  769. "last_coordinate": last_coord_obj
  770. }
  771. except HTTPException:
  772. raise
  773. except Exception as e:
  774. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  775. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  776. @app.get("/preview/{encoded_filename}")
  777. async def serve_preview(encoded_filename: str):
  778. """Serve a preview image for a pattern file."""
  779. # Decode the filename by replacing -- with the original path separators
  780. # First try forward slash (most common case), then backslash if needed
  781. file_name = encoded_filename.replace('--', '/')
  782. # Apply normalization to handle any remaining path prefixes
  783. file_name = normalize_file_path(file_name)
  784. # Check if the decoded path exists, if not try backslash decoding
  785. cache_path = get_cache_path(file_name)
  786. if not os.path.exists(cache_path):
  787. # Try with backslash for Windows paths
  788. file_name_backslash = encoded_filename.replace('--', '\\')
  789. file_name_backslash = normalize_file_path(file_name_backslash)
  790. cache_path_backslash = get_cache_path(file_name_backslash)
  791. if os.path.exists(cache_path_backslash):
  792. file_name = file_name_backslash
  793. cache_path = cache_path_backslash
  794. # cache_path is already determined above in the decoding logic
  795. if not os.path.exists(cache_path):
  796. logger.error(f"Preview image not found for {file_name}")
  797. raise HTTPException(status_code=404, detail="Preview image not found")
  798. # Add caching headers
  799. headers = {
  800. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  801. "Content-Type": "image/webp",
  802. "Accept-Ranges": "bytes"
  803. }
  804. return FileResponse(
  805. cache_path,
  806. media_type="image/webp",
  807. headers=headers
  808. )
  809. @app.post("/send_coordinate")
  810. async def send_coordinate(request: CoordinateRequest):
  811. if not (state.conn.is_connected() if state.conn else False):
  812. logger.warning("Attempted to send coordinate without a connection")
  813. raise HTTPException(status_code=400, detail="Connection not established")
  814. try:
  815. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  816. await pattern_manager.move_polar(request.theta, request.rho)
  817. return {"success": True}
  818. except Exception as e:
  819. logger.error(f"Failed to send coordinate: {str(e)}")
  820. raise HTTPException(status_code=500, detail=str(e))
  821. @app.get("/download/{filename}")
  822. async def download_file(filename: str):
  823. return FileResponse(
  824. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  825. filename=filename
  826. )
  827. @app.get("/serial_status")
  828. async def serial_status():
  829. connected = state.conn.is_connected() if state.conn else False
  830. port = state.port
  831. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  832. return {
  833. "connected": connected,
  834. "port": port
  835. }
  836. @app.post("/pause_execution")
  837. async def pause_execution():
  838. if pattern_manager.pause_execution():
  839. return {"success": True, "message": "Execution paused"}
  840. raise HTTPException(status_code=500, detail="Failed to pause execution")
  841. @app.post("/resume_execution")
  842. async def resume_execution():
  843. if pattern_manager.resume_execution():
  844. return {"success": True, "message": "Execution resumed"}
  845. raise HTTPException(status_code=500, detail="Failed to resume execution")
  846. # Playlist endpoints
  847. @app.get("/list_all_playlists")
  848. async def list_all_playlists():
  849. playlist_names = playlist_manager.list_all_playlists()
  850. return playlist_names
  851. @app.get("/get_playlist")
  852. async def get_playlist(name: str):
  853. if not name:
  854. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  855. playlist = playlist_manager.get_playlist(name)
  856. if not playlist:
  857. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  858. return playlist
  859. @app.post("/create_playlist")
  860. async def create_playlist(request: PlaylistRequest):
  861. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  862. return {
  863. "success": success,
  864. "message": f"Playlist '{request.playlist_name}' created/updated"
  865. }
  866. @app.post("/modify_playlist")
  867. async def modify_playlist(request: PlaylistRequest):
  868. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  869. return {
  870. "success": success,
  871. "message": f"Playlist '{request.playlist_name}' updated"
  872. }
  873. @app.delete("/delete_playlist")
  874. async def delete_playlist(request: DeletePlaylistRequest):
  875. success = playlist_manager.delete_playlist(request.playlist_name)
  876. if not success:
  877. raise HTTPException(
  878. status_code=404,
  879. detail=f"Playlist '{request.playlist_name}' not found"
  880. )
  881. return {
  882. "success": True,
  883. "message": f"Playlist '{request.playlist_name}' deleted"
  884. }
  885. class AddToPlaylistRequest(BaseModel):
  886. playlist_name: str
  887. pattern: str
  888. @app.post("/add_to_playlist")
  889. async def add_to_playlist(request: AddToPlaylistRequest):
  890. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  891. if not success:
  892. raise HTTPException(status_code=404, detail="Playlist not found")
  893. return {"success": True}
  894. @app.post("/run_playlist")
  895. async def run_playlist_endpoint(request: PlaylistRequest):
  896. """Run a playlist with specified parameters."""
  897. try:
  898. if not (state.conn.is_connected() if state.conn else False):
  899. logger.warning("Attempted to run a playlist without a connection")
  900. raise HTTPException(status_code=400, detail="Connection not established")
  901. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  902. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  903. # Start the playlist execution
  904. success, message = await playlist_manager.run_playlist(
  905. request.playlist_name,
  906. pause_time=request.pause_time,
  907. clear_pattern=request.clear_pattern,
  908. run_mode=request.run_mode,
  909. shuffle=request.shuffle
  910. )
  911. if not success:
  912. raise HTTPException(status_code=409, detail=message)
  913. return {"message": f"Started playlist: {request.playlist_name}"}
  914. except Exception as e:
  915. logger.error(f"Error running playlist: {e}")
  916. raise HTTPException(status_code=500, detail=str(e))
  917. @app.post("/set_speed")
  918. async def set_speed(request: SpeedRequest):
  919. try:
  920. if not (state.conn.is_connected() if state.conn else False):
  921. logger.warning("Attempted to change speed without a connection")
  922. raise HTTPException(status_code=400, detail="Connection not established")
  923. if request.speed <= 0:
  924. logger.warning(f"Invalid speed value received: {request.speed}")
  925. raise HTTPException(status_code=400, detail="Invalid speed value")
  926. state.speed = request.speed
  927. return {"success": True, "speed": request.speed}
  928. except Exception as e:
  929. logger.error(f"Failed to set speed: {str(e)}")
  930. raise HTTPException(status_code=500, detail=str(e))
  931. @app.get("/check_software_update")
  932. async def check_updates():
  933. update_info = update_manager.check_git_updates()
  934. return update_info
  935. @app.post("/update_software")
  936. async def update_software():
  937. logger.info("Starting software update process")
  938. success, error_message, error_log = update_manager.update_software()
  939. if success:
  940. logger.info("Software update completed successfully")
  941. return {"success": True}
  942. else:
  943. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  944. raise HTTPException(
  945. status_code=500,
  946. detail={
  947. "error": error_message,
  948. "details": error_log
  949. }
  950. )
  951. @app.post("/set_wled_ip")
  952. async def set_wled_ip(request: WLEDRequest):
  953. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  954. state.wled_ip = request.wled_ip
  955. state.led_provider = "wled" if request.wled_ip else "none"
  956. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  957. if state.led_controller:
  958. state.led_controller.effect_idle()
  959. state.save()
  960. logger.info(f"WLED IP updated: {request.wled_ip}")
  961. return {"success": True, "wled_ip": state.wled_ip}
  962. @app.get("/get_wled_ip")
  963. async def get_wled_ip():
  964. """Legacy endpoint for backward compatibility"""
  965. if not state.wled_ip:
  966. raise HTTPException(status_code=404, detail="No WLED IP set")
  967. return {"success": True, "wled_ip": state.wled_ip}
  968. @app.post("/set_led_config")
  969. async def set_led_config(request: LEDConfigRequest):
  970. """Configure LED provider (WLED, Hyperion, or none)"""
  971. if request.provider not in ["wled", "hyperion", "none"]:
  972. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'wled', 'hyperion', or 'none'")
  973. state.led_provider = request.provider
  974. if request.provider == "wled":
  975. if not request.ip_address:
  976. raise HTTPException(status_code=400, detail="IP address required for WLED")
  977. state.wled_ip = request.ip_address
  978. state.hyperion_ip = None # Clear other provider
  979. state.led_controller = LEDInterface("wled", request.ip_address)
  980. logger.info(f"LED provider set to WLED at {request.ip_address}")
  981. elif request.provider == "hyperion":
  982. if not request.ip_address:
  983. raise HTTPException(status_code=400, detail="IP address required for Hyperion")
  984. state.hyperion_ip = request.ip_address
  985. state.hyperion_port = request.port or 8090
  986. state.wled_ip = None # Clear other provider
  987. state.led_controller = LEDInterface("hyperion", request.ip_address, request.port or 8090)
  988. logger.info(f"LED provider set to Hyperion at {request.ip_address}:{request.port or 8090}")
  989. else: # none
  990. state.wled_ip = None
  991. state.hyperion_ip = None
  992. state.led_controller = None
  993. logger.info("LED provider disabled")
  994. # Show idle effect if controller is configured
  995. if state.led_controller:
  996. state.led_controller.effect_idle()
  997. state.save()
  998. return {
  999. "success": True,
  1000. "provider": state.led_provider,
  1001. "wled_ip": state.wled_ip,
  1002. "hyperion_ip": state.hyperion_ip,
  1003. "hyperion_port": state.hyperion_port
  1004. }
  1005. @app.get("/get_led_config")
  1006. async def get_led_config():
  1007. """Get current LED provider configuration"""
  1008. # Auto-detect provider for backward compatibility with existing installations
  1009. provider = state.led_provider
  1010. if not provider or provider == "none":
  1011. # If no provider set but we have IPs configured, auto-detect
  1012. if state.wled_ip:
  1013. provider = "wled"
  1014. state.led_provider = "wled"
  1015. state.save()
  1016. logger.info("Auto-detected WLED provider from existing configuration")
  1017. elif state.hyperion_ip:
  1018. provider = "hyperion"
  1019. state.led_provider = "hyperion"
  1020. state.save()
  1021. logger.info("Auto-detected Hyperion provider from existing configuration")
  1022. else:
  1023. provider = "none"
  1024. return {
  1025. "success": True,
  1026. "provider": provider,
  1027. "wled_ip": state.wled_ip,
  1028. "hyperion_ip": state.hyperion_ip,
  1029. "hyperion_port": state.hyperion_port,
  1030. "hyperion_idle_effect": state.hyperion_idle_effect,
  1031. "hyperion_playing_effect": state.hyperion_playing_effect
  1032. }
  1033. @app.post("/skip_pattern")
  1034. async def skip_pattern():
  1035. if not state.current_playlist:
  1036. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1037. state.skip_requested = True
  1038. return {"success": True}
  1039. @app.get("/api/custom_clear_patterns")
  1040. async def get_custom_clear_patterns():
  1041. """Get the currently configured custom clear patterns."""
  1042. return {
  1043. "success": True,
  1044. "custom_clear_from_in": state.custom_clear_from_in,
  1045. "custom_clear_from_out": state.custom_clear_from_out
  1046. }
  1047. @app.post("/api/custom_clear_patterns")
  1048. async def set_custom_clear_patterns(request: dict):
  1049. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1050. try:
  1051. # Validate that the patterns exist if they're provided
  1052. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1053. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1054. if not os.path.exists(pattern_path):
  1055. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1056. state.custom_clear_from_in = request["custom_clear_from_in"]
  1057. elif "custom_clear_from_in" in request:
  1058. state.custom_clear_from_in = None
  1059. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1060. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1061. if not os.path.exists(pattern_path):
  1062. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1063. state.custom_clear_from_out = request["custom_clear_from_out"]
  1064. elif "custom_clear_from_out" in request:
  1065. state.custom_clear_from_out = None
  1066. state.save()
  1067. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1068. return {
  1069. "success": True,
  1070. "custom_clear_from_in": state.custom_clear_from_in,
  1071. "custom_clear_from_out": state.custom_clear_from_out
  1072. }
  1073. except Exception as e:
  1074. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  1075. raise HTTPException(status_code=500, detail=str(e))
  1076. @app.get("/api/clear_pattern_speed")
  1077. async def get_clear_pattern_speed():
  1078. """Get the current clearing pattern speed setting."""
  1079. return {
  1080. "success": True,
  1081. "clear_pattern_speed": state.clear_pattern_speed,
  1082. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1083. }
  1084. @app.post("/api/clear_pattern_speed")
  1085. async def set_clear_pattern_speed(request: dict):
  1086. """Set the clearing pattern speed."""
  1087. try:
  1088. # If speed is None or "none", use default behavior (state.speed)
  1089. speed_value = request.get("clear_pattern_speed")
  1090. if speed_value is None or speed_value == "none" or speed_value == "":
  1091. speed = None
  1092. else:
  1093. speed = int(speed_value)
  1094. # Validate speed range (same as regular speed limits) only if speed is not None
  1095. if speed is not None and not (50 <= speed <= 2000):
  1096. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  1097. state.clear_pattern_speed = speed
  1098. state.save()
  1099. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  1100. return {
  1101. "success": True,
  1102. "clear_pattern_speed": state.clear_pattern_speed,
  1103. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1104. }
  1105. except ValueError:
  1106. raise HTTPException(status_code=400, detail="Invalid speed value")
  1107. except Exception as e:
  1108. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  1109. raise HTTPException(status_code=500, detail=str(e))
  1110. @app.get("/api/app-name")
  1111. async def get_app_name():
  1112. """Get current application name."""
  1113. return {"app_name": state.app_name}
  1114. @app.post("/api/app-name")
  1115. async def set_app_name(request: dict):
  1116. """Update application name."""
  1117. app_name = request.get("app_name", "").strip()
  1118. if not app_name:
  1119. app_name = "Dune Weaver" # Reset to default if empty
  1120. state.app_name = app_name
  1121. state.save()
  1122. logger.info(f"Application name updated to: {app_name}")
  1123. return {"success": True, "app_name": app_name}
  1124. @app.post("/preview_thr_batch")
  1125. async def preview_thr_batch(request: dict):
  1126. start = time.time()
  1127. if not request.get("file_names"):
  1128. logger.warning("Batch preview request received without filenames")
  1129. raise HTTPException(status_code=400, detail="No file names provided")
  1130. file_names = request["file_names"]
  1131. if not isinstance(file_names, list):
  1132. raise HTTPException(status_code=400, detail="file_names must be a list")
  1133. headers = {
  1134. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  1135. "Content-Type": "application/json"
  1136. }
  1137. async def process_single_file(file_name):
  1138. """Process a single file and return its preview data."""
  1139. t1 = time.time()
  1140. try:
  1141. # Normalize file path for cross-platform compatibility
  1142. normalized_file_name = normalize_file_path(file_name)
  1143. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1144. # Check file existence asynchronously
  1145. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1146. if not exists:
  1147. logger.warning(f"Pattern file not found: {pattern_file_path}")
  1148. return file_name, {"error": "Pattern file not found"}
  1149. cache_path = get_cache_path(normalized_file_name)
  1150. # Check cache existence asynchronously
  1151. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1152. if not cache_exists:
  1153. logger.info(f"Cache miss for {file_name}. Generating preview...")
  1154. success = await generate_image_preview(normalized_file_name)
  1155. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1156. if not success or not cache_exists_after:
  1157. logger.error(f"Failed to generate or find preview for {file_name}")
  1158. return file_name, {"error": "Failed to generate preview"}
  1159. metadata = get_pattern_metadata(normalized_file_name)
  1160. if metadata:
  1161. first_coord_obj = metadata.get('first_coordinate')
  1162. last_coord_obj = metadata.get('last_coordinate')
  1163. else:
  1164. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  1165. # Use process pool for CPU-intensive parsing
  1166. loop = asyncio.get_event_loop()
  1167. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, pattern_file_path)
  1168. first_coord = coordinates[0] if coordinates else None
  1169. last_coord = coordinates[-1] if coordinates else None
  1170. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1171. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1172. # Read image file asynchronously
  1173. image_data = await asyncio.to_thread(lambda: open(cache_path, 'rb').read())
  1174. image_b64 = base64.b64encode(image_data).decode('utf-8')
  1175. result = {
  1176. "image_data": f"data:image/webp;base64,{image_b64}",
  1177. "first_coordinate": first_coord_obj,
  1178. "last_coordinate": last_coord_obj
  1179. }
  1180. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  1181. return file_name, result
  1182. except Exception as e:
  1183. logger.error(f"Error processing {file_name}: {str(e)}")
  1184. return file_name, {"error": str(e)}
  1185. # Process all files concurrently
  1186. tasks = [process_single_file(file_name) for file_name in file_names]
  1187. file_results = await asyncio.gather(*tasks)
  1188. # Convert results to dictionary
  1189. results = dict(file_results)
  1190. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  1191. return JSONResponse(content=results, headers=headers)
  1192. @app.get("/playlists")
  1193. async def playlists(request: Request):
  1194. logger.debug("Rendering playlists page")
  1195. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name})
  1196. @app.get("/image2sand")
  1197. async def image2sand(request: Request):
  1198. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name})
  1199. @app.get("/wled")
  1200. async def wled(request: Request):
  1201. return templates.TemplateResponse("wled.html", {"request": request, "app_name": state.app_name})
  1202. # Hyperion control endpoints
  1203. @app.get("/api/hyperion/status")
  1204. async def hyperion_status():
  1205. """Get Hyperion connection status"""
  1206. if not state.led_controller or state.led_provider != "hyperion":
  1207. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1208. try:
  1209. status = state.led_controller.check_status()
  1210. return status
  1211. except Exception as e:
  1212. logger.error(f"Failed to check Hyperion status: {str(e)}")
  1213. return {"connected": False, "message": str(e)}
  1214. @app.post("/api/hyperion/power")
  1215. async def hyperion_power(request: dict):
  1216. """Control Hyperion power state"""
  1217. if not state.led_controller or state.led_provider != "hyperion":
  1218. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1219. state_value = request.get("state", 1)
  1220. if state_value not in [0, 1, 2]:
  1221. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  1222. try:
  1223. result = state.led_controller.set_power(state_value)
  1224. return result
  1225. except Exception as e:
  1226. logger.error(f"Failed to set Hyperion power: {str(e)}")
  1227. raise HTTPException(status_code=500, detail=str(e))
  1228. @app.post("/api/hyperion/brightness")
  1229. async def hyperion_brightness(request: dict):
  1230. """Set Hyperion brightness"""
  1231. if not state.led_controller or state.led_provider != "hyperion":
  1232. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1233. value = request.get("value", 100)
  1234. if not 0 <= value <= 100:
  1235. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  1236. try:
  1237. controller = state.led_controller.get_controller()
  1238. result = controller.set_brightness(value)
  1239. return result
  1240. except Exception as e:
  1241. logger.error(f"Failed to set Hyperion brightness: {str(e)}")
  1242. raise HTTPException(status_code=500, detail=str(e))
  1243. @app.post("/api/hyperion/color")
  1244. async def hyperion_color(request: dict):
  1245. """Set Hyperion color"""
  1246. if not state.led_controller or state.led_provider != "hyperion":
  1247. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1248. hex_color = request.get("hex")
  1249. r = request.get("r")
  1250. g = request.get("g")
  1251. b = request.get("b")
  1252. if not hex_color and (r is None or g is None or b is None):
  1253. raise HTTPException(status_code=400, detail="Either hex or RGB values required")
  1254. try:
  1255. controller = state.led_controller.get_controller()
  1256. # Convert hex to RGB if hex was provided
  1257. if hex_color:
  1258. hex_color = hex_color.lstrip('#')
  1259. if len(hex_color) != 6:
  1260. raise HTTPException(status_code=400, detail="Hex color must be 6 characters")
  1261. r = int(hex_color[0:2], 16)
  1262. g = int(hex_color[2:4], 16)
  1263. b = int(hex_color[4:6], 16)
  1264. result = controller.set_color(r=r, g=g, b=b)
  1265. return result
  1266. except ValueError as e:
  1267. logger.error(f"Failed to parse hex color: {str(e)}")
  1268. raise HTTPException(status_code=400, detail="Invalid hex color format")
  1269. except Exception as e:
  1270. logger.error(f"Failed to set Hyperion color: {str(e)}")
  1271. raise HTTPException(status_code=500, detail=str(e))
  1272. @app.post("/api/hyperion/clear")
  1273. async def hyperion_clear(request: dict):
  1274. """Clear Hyperion priority"""
  1275. if not state.led_controller or state.led_provider != "hyperion":
  1276. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1277. try:
  1278. controller = state.led_controller.get_controller()
  1279. result = controller.clear_priority()
  1280. return result
  1281. except Exception as e:
  1282. logger.error(f"Failed to clear Hyperion priority: {str(e)}")
  1283. raise HTTPException(status_code=500, detail=str(e))
  1284. @app.get("/api/hyperion/effects")
  1285. async def hyperion_effects():
  1286. """Get list of available Hyperion effects"""
  1287. if not state.led_controller or state.led_provider != "hyperion":
  1288. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1289. try:
  1290. import requests as req
  1291. response = req.post(
  1292. f"http://{state.hyperion_ip}:{state.hyperion_port}/json-rpc",
  1293. json={"command": "serverinfo"},
  1294. timeout=2
  1295. )
  1296. data = response.json()
  1297. effects = data.get('info', {}).get('effects', [])
  1298. # Return sorted list of effects
  1299. effects_list = [{"name": e.get("name"), "args": e.get("args", {})} for e in effects]
  1300. effects_list.sort(key=lambda x: x["name"])
  1301. return {"success": True, "effects": effects_list}
  1302. except Exception as e:
  1303. logger.error(f"Failed to get Hyperion effects: {str(e)}")
  1304. raise HTTPException(status_code=500, detail=str(e))
  1305. @app.post("/api/hyperion/effect")
  1306. async def hyperion_effect(request: dict):
  1307. """Set Hyperion effect"""
  1308. if not state.led_controller or state.led_provider != "hyperion":
  1309. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1310. effect_name = request.get("effect_name")
  1311. effect_args = request.get("args", {})
  1312. if not effect_name:
  1313. raise HTTPException(status_code=400, detail="effect_name required")
  1314. try:
  1315. controller = state.led_controller.get_controller()
  1316. result = controller.set_effect(effect_name, effect_args)
  1317. return result
  1318. except Exception as e:
  1319. logger.error(f"Failed to set Hyperion effect: {str(e)}")
  1320. raise HTTPException(status_code=500, detail=str(e))
  1321. @app.post("/api/hyperion/set_effects")
  1322. async def hyperion_set_effects(request: dict):
  1323. """Configure idle and playing effects for Hyperion"""
  1324. idle_effect = request.get("idle_effect")
  1325. playing_effect = request.get("playing_effect")
  1326. # Allow None/empty string to clear the setting
  1327. state.hyperion_idle_effect = idle_effect if idle_effect else None
  1328. state.hyperion_playing_effect = playing_effect if playing_effect else None
  1329. state.save()
  1330. logger.info(f"Hyperion effects configured - Idle: {state.hyperion_idle_effect}, Playing: {state.hyperion_playing_effect}")
  1331. return {
  1332. "success": True,
  1333. "idle_effect": state.hyperion_idle_effect,
  1334. "playing_effect": state.hyperion_playing_effect
  1335. }
  1336. @app.get("/table_control")
  1337. async def table_control(request: Request):
  1338. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name})
  1339. @app.get("/cache-progress")
  1340. async def get_cache_progress_endpoint():
  1341. """Get the current cache generation progress."""
  1342. from modules.core.cache_manager import get_cache_progress
  1343. return get_cache_progress()
  1344. @app.post("/rebuild_cache")
  1345. async def rebuild_cache_endpoint():
  1346. """Trigger a rebuild of the pattern cache."""
  1347. try:
  1348. from modules.core.cache_manager import rebuild_cache
  1349. await rebuild_cache()
  1350. return {"success": True, "message": "Cache rebuild completed successfully"}
  1351. except Exception as e:
  1352. logger.error(f"Failed to rebuild cache: {str(e)}")
  1353. raise HTTPException(status_code=500, detail=str(e))
  1354. def signal_handler(signum, frame):
  1355. """Handle shutdown signals gracefully but forcefully."""
  1356. logger.info("Received shutdown signal, cleaning up...")
  1357. try:
  1358. if state.led_controller:
  1359. state.led_controller.set_power(0)
  1360. # Run cleanup operations - need to handle async in sync context
  1361. try:
  1362. # Try to run in existing loop if available
  1363. import asyncio
  1364. loop = asyncio.get_running_loop()
  1365. # If we're in an event loop, schedule the coroutine
  1366. import concurrent.futures
  1367. with concurrent.futures.ThreadPoolExecutor() as executor:
  1368. future = executor.submit(asyncio.run, pattern_manager.stop_actions())
  1369. future.result(timeout=5.0) # Wait up to 5 seconds
  1370. except RuntimeError:
  1371. # No running loop, create a new one
  1372. import asyncio
  1373. asyncio.run(pattern_manager.stop_actions())
  1374. except Exception as cleanup_err:
  1375. logger.error(f"Error in async cleanup: {cleanup_err}")
  1376. state.save()
  1377. logger.info("Cleanup completed")
  1378. except Exception as e:
  1379. logger.error(f"Error during cleanup: {str(e)}")
  1380. finally:
  1381. logger.info("Exiting application...")
  1382. os._exit(0) # Force exit regardless of other threads
  1383. @app.get("/api/version")
  1384. async def get_version_info():
  1385. """Get current and latest version information"""
  1386. try:
  1387. version_info = await version_manager.get_version_info()
  1388. return JSONResponse(content=version_info)
  1389. except Exception as e:
  1390. logger.error(f"Error getting version info: {e}")
  1391. return JSONResponse(
  1392. content={
  1393. "current": version_manager.get_current_version(),
  1394. "latest": version_manager.get_current_version(),
  1395. "update_available": False,
  1396. "error": "Unable to check for updates"
  1397. },
  1398. status_code=200
  1399. )
  1400. @app.post("/api/update")
  1401. async def trigger_update():
  1402. """Trigger software update (placeholder for future implementation)"""
  1403. try:
  1404. # For now, just return the GitHub release URL
  1405. version_info = await version_manager.get_version_info()
  1406. if version_info.get("latest_release"):
  1407. return JSONResponse(content={
  1408. "success": False,
  1409. "message": "Automatic updates not implemented yet",
  1410. "manual_update_url": version_info["latest_release"].get("html_url"),
  1411. "instructions": "Please visit the GitHub release page to download and install the update manually"
  1412. })
  1413. else:
  1414. return JSONResponse(content={
  1415. "success": False,
  1416. "message": "No updates available"
  1417. })
  1418. except Exception as e:
  1419. logger.error(f"Error triggering update: {e}")
  1420. return JSONResponse(
  1421. content={"success": False, "message": "Failed to check for updates"},
  1422. status_code=500
  1423. )
  1424. def entrypoint():
  1425. import uvicorn
  1426. logger.info("Starting FastAPI server on port 8080...")
  1427. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  1428. if __name__ == "__main__":
  1429. entrypoint()