main.py 49 KB

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