main.py 49 KB

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