main.py 71 KB

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