main.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. # Run the blocking file system operation in a thread pool
  291. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  292. return sorted(files)
  293. @app.get("/list_theta_rho_files_with_metadata")
  294. async def list_theta_rho_files_with_metadata():
  295. """Get list of theta-rho files with metadata for sorting and filtering.
  296. Optimized to process files asynchronously and support request cancellation.
  297. """
  298. from modules.core.cache_manager import get_pattern_metadata
  299. import asyncio
  300. from concurrent.futures import ThreadPoolExecutor
  301. # Run the blocking file listing in a thread
  302. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  303. files_with_metadata = []
  304. # Use ThreadPoolExecutor for I/O-bound operations
  305. executor = ThreadPoolExecutor(max_workers=4)
  306. def process_file(file_path):
  307. """Process a single file and return its metadata."""
  308. try:
  309. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  310. # Get file stats
  311. file_stat = os.stat(full_path)
  312. # Get cached metadata (this should be fast if cached)
  313. metadata = get_pattern_metadata(file_path)
  314. # Extract full folder path from file path
  315. path_parts = file_path.split('/')
  316. if len(path_parts) > 1:
  317. # Get everything except the filename (join all folder parts)
  318. category = '/'.join(path_parts[:-1])
  319. else:
  320. category = 'root'
  321. # Get file name without extension
  322. file_name = os.path.splitext(os.path.basename(file_path))[0]
  323. # Use modification time (mtime) for "date modified"
  324. date_modified = file_stat.st_mtime
  325. return {
  326. 'path': file_path,
  327. 'name': file_name,
  328. 'category': category,
  329. 'date_modified': date_modified,
  330. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  331. }
  332. except Exception as e:
  333. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  334. # Include file with minimal info if metadata fails
  335. path_parts = file_path.split('/')
  336. if len(path_parts) > 1:
  337. category = '/'.join(path_parts[:-1])
  338. else:
  339. category = 'root'
  340. return {
  341. 'path': file_path,
  342. 'name': os.path.splitext(os.path.basename(file_path))[0],
  343. 'category': category,
  344. 'date_modified': 0,
  345. 'coordinates_count': 0
  346. }
  347. # Process files in parallel using asyncio
  348. loop = asyncio.get_event_loop()
  349. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  350. # Process results as they complete
  351. for task in asyncio.as_completed(tasks):
  352. try:
  353. result = await task
  354. files_with_metadata.append(result)
  355. except Exception as e:
  356. logger.error(f"Error processing file: {str(e)}")
  357. return files_with_metadata
  358. @app.post("/upload_theta_rho")
  359. async def upload_theta_rho(file: UploadFile = File(...)):
  360. """Upload a theta-rho file."""
  361. try:
  362. # Save the file
  363. # Ensure custom_patterns directory exists
  364. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  365. os.makedirs(custom_patterns_dir, exist_ok=True)
  366. # Use forward slashes for internal path representation to maintain consistency
  367. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  368. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  369. # Save the uploaded file with proper encoding for Windows compatibility
  370. file_content = await file.read()
  371. try:
  372. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  373. text_content = file_content.decode('utf-8')
  374. with open(full_file_path, "w", encoding='utf-8') as f:
  375. f.write(text_content)
  376. except UnicodeDecodeError:
  377. # If UTF-8 decoding fails, save as binary (fallback)
  378. with open(full_file_path, "wb") as f:
  379. f.write(file_content)
  380. logger.info(f"File {file.filename} saved successfully")
  381. # Generate image preview for the new file with retry logic
  382. max_retries = 3
  383. for attempt in range(max_retries):
  384. try:
  385. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  386. success = await generate_image_preview(file_path_in_patterns_dir)
  387. if success:
  388. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  389. break
  390. else:
  391. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  392. if attempt < max_retries - 1:
  393. await asyncio.sleep(0.5) # Small delay before retry
  394. except Exception as e:
  395. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  396. if attempt < max_retries - 1:
  397. await asyncio.sleep(0.5) # Small delay before retry
  398. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  399. except Exception as e:
  400. logger.error(f"Error uploading file: {str(e)}")
  401. raise HTTPException(status_code=500, detail=str(e))
  402. @app.post("/get_theta_rho_coordinates")
  403. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  404. """Get theta-rho coordinates for animated preview."""
  405. try:
  406. # Normalize file path for cross-platform compatibility and remove prefixes
  407. file_name = normalize_file_path(request.file_name)
  408. file_path = os.path.join(THETA_RHO_DIR, file_name)
  409. # Check file existence asynchronously
  410. exists = await asyncio.to_thread(os.path.exists, file_path)
  411. if not exists:
  412. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  413. # Parse the theta-rho file asynchronously
  414. coordinates = await asyncio.to_thread(parse_theta_rho_file, file_path)
  415. if not coordinates:
  416. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  417. return {
  418. "success": True,
  419. "coordinates": coordinates,
  420. "total_points": len(coordinates)
  421. }
  422. except Exception as e:
  423. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  424. raise HTTPException(status_code=500, detail=str(e))
  425. @app.post("/run_theta_rho")
  426. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  427. if not request.file_name:
  428. logger.warning('Run theta-rho request received without file name')
  429. raise HTTPException(status_code=400, detail="No file name provided")
  430. file_path = None
  431. if 'clear' in request.file_name:
  432. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  433. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  434. logger.info(f'Clear pattern file: {file_path}')
  435. if not file_path:
  436. # Normalize file path for cross-platform compatibility
  437. normalized_file_name = normalize_file_path(request.file_name)
  438. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  439. if not os.path.exists(file_path):
  440. logger.error(f'Theta-rho file not found: {file_path}')
  441. raise HTTPException(status_code=404, detail="File not found")
  442. try:
  443. if not (state.conn.is_connected() if state.conn else False):
  444. logger.warning("Attempted to run a pattern without a connection")
  445. raise HTTPException(status_code=400, detail="Connection not established")
  446. if pattern_manager.pattern_lock.locked():
  447. logger.warning("Attempted to run a pattern while another is already running")
  448. raise HTTPException(status_code=409, detail="Another pattern is already running")
  449. files_to_run = [file_path]
  450. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  451. # Only include clear_pattern if it's not "none"
  452. kwargs = {}
  453. if request.pre_execution != "none":
  454. kwargs['clear_pattern'] = request.pre_execution
  455. # Pass arguments properly
  456. background_tasks.add_task(
  457. pattern_manager.run_theta_rho_files,
  458. files_to_run, # First positional argument
  459. **kwargs # Spread keyword arguments
  460. )
  461. return {"success": True}
  462. except HTTPException as http_exc:
  463. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  464. raise http_exc
  465. except Exception as e:
  466. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  467. raise HTTPException(status_code=500, detail=str(e))
  468. @app.post("/stop_execution")
  469. async def stop_execution():
  470. if not (state.conn.is_connected() if state.conn else False):
  471. logger.warning("Attempted to stop without a connection")
  472. raise HTTPException(status_code=400, detail="Connection not established")
  473. await pattern_manager.stop_actions()
  474. return {"success": True}
  475. @app.post("/send_home")
  476. async def send_home():
  477. try:
  478. if not (state.conn.is_connected() if state.conn else False):
  479. logger.warning("Attempted to move to home without a connection")
  480. raise HTTPException(status_code=400, detail="Connection not established")
  481. # Run homing with 15 second timeout
  482. success = await asyncio.to_thread(connection_manager.home)
  483. if not success:
  484. logger.error("Homing failed or timed out")
  485. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  486. return {"success": True}
  487. except HTTPException:
  488. raise
  489. except Exception as e:
  490. logger.error(f"Failed to send home command: {str(e)}")
  491. raise HTTPException(status_code=500, detail=str(e))
  492. @app.post("/run_theta_rho_file/{file_name}")
  493. async def run_specific_theta_rho_file(file_name: str):
  494. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  495. if not os.path.exists(file_path):
  496. raise HTTPException(status_code=404, detail="File not found")
  497. if not (state.conn.is_connected() if state.conn else False):
  498. logger.warning("Attempted to run a pattern without a connection")
  499. raise HTTPException(status_code=400, detail="Connection not established")
  500. pattern_manager.run_theta_rho_file(file_path)
  501. return {"success": True}
  502. class DeleteFileRequest(BaseModel):
  503. file_name: str
  504. @app.post("/delete_theta_rho_file")
  505. async def delete_theta_rho_file(request: DeleteFileRequest):
  506. if not request.file_name:
  507. logger.warning("Delete theta-rho file request received without filename")
  508. raise HTTPException(status_code=400, detail="No file name provided")
  509. # Normalize file path for cross-platform compatibility
  510. normalized_file_name = normalize_file_path(request.file_name)
  511. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  512. # Check file existence asynchronously
  513. exists = await asyncio.to_thread(os.path.exists, file_path)
  514. if not exists:
  515. logger.error(f"Attempted to delete non-existent file: {file_path}")
  516. raise HTTPException(status_code=404, detail="File not found")
  517. try:
  518. # Delete the pattern file asynchronously
  519. await asyncio.to_thread(os.remove, file_path)
  520. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  521. # Clean up cached preview image and metadata asynchronously
  522. from modules.core.cache_manager import delete_pattern_cache
  523. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  524. if cache_cleanup_success:
  525. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  526. else:
  527. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  528. return {"success": True, "cache_cleanup": cache_cleanup_success}
  529. except Exception as e:
  530. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  531. raise HTTPException(status_code=500, detail=str(e))
  532. @app.post("/move_to_center")
  533. async def move_to_center():
  534. try:
  535. if not (state.conn.is_connected() if state.conn else False):
  536. logger.warning("Attempted to move to center without a connection")
  537. raise HTTPException(status_code=400, detail="Connection not established")
  538. logger.info("Moving device to center position")
  539. await pattern_manager.reset_theta()
  540. await pattern_manager.move_polar(0, 0)
  541. return {"success": True}
  542. except Exception as e:
  543. logger.error(f"Failed to move to center: {str(e)}")
  544. raise HTTPException(status_code=500, detail=str(e))
  545. @app.post("/move_to_perimeter")
  546. async def move_to_perimeter():
  547. try:
  548. if not (state.conn.is_connected() if state.conn else False):
  549. logger.warning("Attempted to move to perimeter without a connection")
  550. raise HTTPException(status_code=400, detail="Connection not established")
  551. await pattern_manager.reset_theta()
  552. await pattern_manager.move_polar(0, 1)
  553. return {"success": True}
  554. except Exception as e:
  555. logger.error(f"Failed to move to perimeter: {str(e)}")
  556. raise HTTPException(status_code=500, detail=str(e))
  557. @app.post("/preview_thr")
  558. async def preview_thr(request: DeleteFileRequest):
  559. if not request.file_name:
  560. logger.warning("Preview theta-rho request received without filename")
  561. raise HTTPException(status_code=400, detail="No file name provided")
  562. # Normalize file path for cross-platform compatibility
  563. normalized_file_name = normalize_file_path(request.file_name)
  564. # Construct the full path to the pattern file to check existence
  565. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  566. # Check file existence asynchronously
  567. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  568. if not exists:
  569. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  570. raise HTTPException(status_code=404, detail="Pattern file not found")
  571. try:
  572. cache_path = get_cache_path(normalized_file_name)
  573. # Check cache existence asynchronously
  574. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  575. if not cache_exists:
  576. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  577. # Attempt to generate the preview if it's missing
  578. success = await generate_image_preview(normalized_file_name)
  579. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  580. if not success or not cache_exists_after:
  581. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  582. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  583. # Try to get coordinates from metadata cache first
  584. metadata = get_pattern_metadata(normalized_file_name)
  585. if metadata:
  586. first_coord_obj = metadata.get('first_coordinate')
  587. last_coord_obj = metadata.get('last_coordinate')
  588. else:
  589. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  590. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  591. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  592. first_coord = coordinates[0] if coordinates else None
  593. last_coord = coordinates[-1] if coordinates else None
  594. # Format coordinates as objects with x and y properties
  595. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  596. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  597. # Return JSON with preview URL and coordinates
  598. # URL encode the file_name for the preview URL
  599. # Handle both forward slashes and backslashes for cross-platform compatibility
  600. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  601. return {
  602. "preview_url": f"/preview/{encoded_filename}",
  603. "first_coordinate": first_coord_obj,
  604. "last_coordinate": last_coord_obj
  605. }
  606. except HTTPException:
  607. raise
  608. except Exception as e:
  609. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  610. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  611. @app.get("/preview/{encoded_filename}")
  612. async def serve_preview(encoded_filename: str):
  613. """Serve a preview image for a pattern file."""
  614. # Decode the filename by replacing -- with the original path separators
  615. # First try forward slash (most common case), then backslash if needed
  616. file_name = encoded_filename.replace('--', '/')
  617. # Apply normalization to handle any remaining path prefixes
  618. file_name = normalize_file_path(file_name)
  619. # Check if the decoded path exists, if not try backslash decoding
  620. cache_path = get_cache_path(file_name)
  621. if not os.path.exists(cache_path):
  622. # Try with backslash for Windows paths
  623. file_name_backslash = encoded_filename.replace('--', '\\')
  624. file_name_backslash = normalize_file_path(file_name_backslash)
  625. cache_path_backslash = get_cache_path(file_name_backslash)
  626. if os.path.exists(cache_path_backslash):
  627. file_name = file_name_backslash
  628. cache_path = cache_path_backslash
  629. # cache_path is already determined above in the decoding logic
  630. if not os.path.exists(cache_path):
  631. logger.error(f"Preview image not found for {file_name}")
  632. raise HTTPException(status_code=404, detail="Preview image not found")
  633. # Add caching headers
  634. headers = {
  635. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  636. "Content-Type": "image/webp",
  637. "Accept-Ranges": "bytes"
  638. }
  639. return FileResponse(
  640. cache_path,
  641. media_type="image/webp",
  642. headers=headers
  643. )
  644. @app.post("/send_coordinate")
  645. async def send_coordinate(request: CoordinateRequest):
  646. if not (state.conn.is_connected() if state.conn else False):
  647. logger.warning("Attempted to send coordinate without a connection")
  648. raise HTTPException(status_code=400, detail="Connection not established")
  649. try:
  650. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  651. await pattern_manager.move_polar(request.theta, request.rho)
  652. return {"success": True}
  653. except Exception as e:
  654. logger.error(f"Failed to send coordinate: {str(e)}")
  655. raise HTTPException(status_code=500, detail=str(e))
  656. @app.get("/download/{filename}")
  657. async def download_file(filename: str):
  658. return FileResponse(
  659. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  660. filename=filename
  661. )
  662. @app.get("/serial_status")
  663. async def serial_status():
  664. connected = state.conn.is_connected() if state.conn else False
  665. port = state.port
  666. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  667. return {
  668. "connected": connected,
  669. "port": port
  670. }
  671. @app.post("/pause_execution")
  672. async def pause_execution():
  673. if pattern_manager.pause_execution():
  674. return {"success": True, "message": "Execution paused"}
  675. raise HTTPException(status_code=500, detail="Failed to pause execution")
  676. @app.post("/resume_execution")
  677. async def resume_execution():
  678. if pattern_manager.resume_execution():
  679. return {"success": True, "message": "Execution resumed"}
  680. raise HTTPException(status_code=500, detail="Failed to resume execution")
  681. # Playlist endpoints
  682. @app.get("/list_all_playlists")
  683. async def list_all_playlists():
  684. playlist_names = playlist_manager.list_all_playlists()
  685. return playlist_names
  686. @app.get("/get_playlist")
  687. async def get_playlist(name: str):
  688. if not name:
  689. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  690. playlist = playlist_manager.get_playlist(name)
  691. if not playlist:
  692. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  693. return playlist
  694. @app.post("/create_playlist")
  695. async def create_playlist(request: PlaylistRequest):
  696. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  697. return {
  698. "success": success,
  699. "message": f"Playlist '{request.playlist_name}' created/updated"
  700. }
  701. @app.post("/modify_playlist")
  702. async def modify_playlist(request: PlaylistRequest):
  703. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  704. return {
  705. "success": success,
  706. "message": f"Playlist '{request.playlist_name}' updated"
  707. }
  708. @app.delete("/delete_playlist")
  709. async def delete_playlist(request: DeletePlaylistRequest):
  710. success = playlist_manager.delete_playlist(request.playlist_name)
  711. if not success:
  712. raise HTTPException(
  713. status_code=404,
  714. detail=f"Playlist '{request.playlist_name}' not found"
  715. )
  716. return {
  717. "success": True,
  718. "message": f"Playlist '{request.playlist_name}' deleted"
  719. }
  720. class AddToPlaylistRequest(BaseModel):
  721. playlist_name: str
  722. pattern: str
  723. @app.post("/add_to_playlist")
  724. async def add_to_playlist(request: AddToPlaylistRequest):
  725. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  726. if not success:
  727. raise HTTPException(status_code=404, detail="Playlist not found")
  728. return {"success": True}
  729. @app.post("/run_playlist")
  730. async def run_playlist_endpoint(request: PlaylistRequest):
  731. """Run a playlist with specified parameters."""
  732. try:
  733. if not (state.conn.is_connected() if state.conn else False):
  734. logger.warning("Attempted to run a playlist without a connection")
  735. raise HTTPException(status_code=400, detail="Connection not established")
  736. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  737. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  738. # Start the playlist execution
  739. success, message = await playlist_manager.run_playlist(
  740. request.playlist_name,
  741. pause_time=request.pause_time,
  742. clear_pattern=request.clear_pattern,
  743. run_mode=request.run_mode,
  744. shuffle=request.shuffle
  745. )
  746. if not success:
  747. raise HTTPException(status_code=409, detail=message)
  748. return {"message": f"Started playlist: {request.playlist_name}"}
  749. except Exception as e:
  750. logger.error(f"Error running playlist: {e}")
  751. raise HTTPException(status_code=500, detail=str(e))
  752. @app.post("/set_speed")
  753. async def set_speed(request: SpeedRequest):
  754. try:
  755. if not (state.conn.is_connected() if state.conn else False):
  756. logger.warning("Attempted to change speed without a connection")
  757. raise HTTPException(status_code=400, detail="Connection not established")
  758. if request.speed <= 0:
  759. logger.warning(f"Invalid speed value received: {request.speed}")
  760. raise HTTPException(status_code=400, detail="Invalid speed value")
  761. state.speed = request.speed
  762. return {"success": True, "speed": request.speed}
  763. except Exception as e:
  764. logger.error(f"Failed to set speed: {str(e)}")
  765. raise HTTPException(status_code=500, detail=str(e))
  766. @app.get("/check_software_update")
  767. async def check_updates():
  768. update_info = update_manager.check_git_updates()
  769. return update_info
  770. @app.post("/update_software")
  771. async def update_software():
  772. logger.info("Starting software update process")
  773. success, error_message, error_log = update_manager.update_software()
  774. if success:
  775. logger.info("Software update completed successfully")
  776. return {"success": True}
  777. else:
  778. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  779. raise HTTPException(
  780. status_code=500,
  781. detail={
  782. "error": error_message,
  783. "details": error_log
  784. }
  785. )
  786. @app.post("/set_wled_ip")
  787. async def set_wled_ip(request: WLEDRequest):
  788. state.wled_ip = request.wled_ip
  789. state.led_controller = LEDController(request.wled_ip)
  790. effect_idle(state.led_controller)
  791. state.save()
  792. logger.info(f"WLED IP updated: {request.wled_ip}")
  793. return {"success": True, "wled_ip": state.wled_ip}
  794. @app.get("/get_wled_ip")
  795. async def get_wled_ip():
  796. if not state.wled_ip:
  797. raise HTTPException(status_code=404, detail="No WLED IP set")
  798. return {"success": True, "wled_ip": state.wled_ip}
  799. @app.post("/skip_pattern")
  800. async def skip_pattern():
  801. if not state.current_playlist:
  802. raise HTTPException(status_code=400, detail="No playlist is currently running")
  803. state.skip_requested = True
  804. return {"success": True}
  805. @app.get("/api/custom_clear_patterns")
  806. async def get_custom_clear_patterns():
  807. """Get the currently configured custom clear patterns."""
  808. return {
  809. "success": True,
  810. "custom_clear_from_in": state.custom_clear_from_in,
  811. "custom_clear_from_out": state.custom_clear_from_out
  812. }
  813. @app.post("/api/custom_clear_patterns")
  814. async def set_custom_clear_patterns(request: dict):
  815. """Set custom clear patterns for clear_from_in and clear_from_out."""
  816. try:
  817. # Validate that the patterns exist if they're provided
  818. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  819. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  820. if not os.path.exists(pattern_path):
  821. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  822. state.custom_clear_from_in = request["custom_clear_from_in"]
  823. elif "custom_clear_from_in" in request:
  824. state.custom_clear_from_in = None
  825. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  826. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  827. if not os.path.exists(pattern_path):
  828. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  829. state.custom_clear_from_out = request["custom_clear_from_out"]
  830. elif "custom_clear_from_out" in request:
  831. state.custom_clear_from_out = None
  832. state.save()
  833. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  834. return {
  835. "success": True,
  836. "custom_clear_from_in": state.custom_clear_from_in,
  837. "custom_clear_from_out": state.custom_clear_from_out
  838. }
  839. except Exception as e:
  840. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  841. raise HTTPException(status_code=500, detail=str(e))
  842. @app.get("/api/clear_pattern_speed")
  843. async def get_clear_pattern_speed():
  844. """Get the current clearing pattern speed setting."""
  845. return {
  846. "success": True,
  847. "clear_pattern_speed": state.clear_pattern_speed,
  848. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  849. }
  850. @app.post("/api/clear_pattern_speed")
  851. async def set_clear_pattern_speed(request: dict):
  852. """Set the clearing pattern speed."""
  853. try:
  854. # If speed is None or "none", use default behavior (state.speed)
  855. speed_value = request.get("clear_pattern_speed")
  856. if speed_value is None or speed_value == "none" or speed_value == "":
  857. speed = None
  858. else:
  859. speed = int(speed_value)
  860. # Validate speed range (same as regular speed limits) only if speed is not None
  861. if speed is not None and not (50 <= speed <= 2000):
  862. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  863. state.clear_pattern_speed = speed
  864. state.save()
  865. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  866. return {
  867. "success": True,
  868. "clear_pattern_speed": state.clear_pattern_speed,
  869. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  870. }
  871. except ValueError:
  872. raise HTTPException(status_code=400, detail="Invalid speed value")
  873. except Exception as e:
  874. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  875. raise HTTPException(status_code=500, detail=str(e))
  876. @app.get("/api/app-name")
  877. async def get_app_name():
  878. """Get current application name."""
  879. return {"app_name": state.app_name}
  880. @app.post("/api/app-name")
  881. async def set_app_name(request: dict):
  882. """Update application name."""
  883. app_name = request.get("app_name", "").strip()
  884. if not app_name:
  885. app_name = "Dune Weaver" # Reset to default if empty
  886. state.app_name = app_name
  887. state.save()
  888. logger.info(f"Application name updated to: {app_name}")
  889. return {"success": True, "app_name": app_name}
  890. @app.post("/preview_thr_batch")
  891. async def preview_thr_batch(request: dict):
  892. start = time.time()
  893. if not request.get("file_names"):
  894. logger.warning("Batch preview request received without filenames")
  895. raise HTTPException(status_code=400, detail="No file names provided")
  896. file_names = request["file_names"]
  897. if not isinstance(file_names, list):
  898. raise HTTPException(status_code=400, detail="file_names must be a list")
  899. headers = {
  900. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  901. "Content-Type": "application/json"
  902. }
  903. async def process_single_file(file_name):
  904. """Process a single file and return its preview data."""
  905. t1 = time.time()
  906. try:
  907. # Normalize file path for cross-platform compatibility
  908. normalized_file_name = normalize_file_path(file_name)
  909. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  910. # Check file existence asynchronously
  911. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  912. if not exists:
  913. logger.warning(f"Pattern file not found: {pattern_file_path}")
  914. return file_name, {"error": "Pattern file not found"}
  915. cache_path = get_cache_path(normalized_file_name)
  916. # Check cache existence asynchronously
  917. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  918. if not cache_exists:
  919. logger.info(f"Cache miss for {file_name}. Generating preview...")
  920. success = await generate_image_preview(normalized_file_name)
  921. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  922. if not success or not cache_exists_after:
  923. logger.error(f"Failed to generate or find preview for {file_name}")
  924. return file_name, {"error": "Failed to generate preview"}
  925. metadata = get_pattern_metadata(normalized_file_name)
  926. if metadata:
  927. first_coord_obj = metadata.get('first_coordinate')
  928. last_coord_obj = metadata.get('last_coordinate')
  929. else:
  930. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  931. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  932. first_coord = coordinates[0] if coordinates else None
  933. last_coord = coordinates[-1] if coordinates else None
  934. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  935. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  936. # Read image file asynchronously
  937. image_data = await asyncio.to_thread(lambda: open(cache_path, 'rb').read())
  938. image_b64 = base64.b64encode(image_data).decode('utf-8')
  939. result = {
  940. "image_data": f"data:image/webp;base64,{image_b64}",
  941. "first_coordinate": first_coord_obj,
  942. "last_coordinate": last_coord_obj
  943. }
  944. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  945. return file_name, result
  946. except Exception as e:
  947. logger.error(f"Error processing {file_name}: {str(e)}")
  948. return file_name, {"error": str(e)}
  949. # Process all files concurrently
  950. tasks = [process_single_file(file_name) for file_name in file_names]
  951. file_results = await asyncio.gather(*tasks)
  952. # Convert results to dictionary
  953. results = dict(file_results)
  954. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  955. return JSONResponse(content=results, headers=headers)
  956. @app.get("/playlists")
  957. async def playlists(request: Request):
  958. logger.debug("Rendering playlists page")
  959. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name})
  960. @app.get("/image2sand")
  961. async def image2sand(request: Request):
  962. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name})
  963. @app.get("/wled")
  964. async def wled(request: Request):
  965. return templates.TemplateResponse("wled.html", {"request": request, "app_name": state.app_name})
  966. @app.get("/table_control")
  967. async def table_control(request: Request):
  968. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name})
  969. @app.get("/cache-progress")
  970. async def get_cache_progress_endpoint():
  971. """Get the current cache generation progress."""
  972. from modules.core.cache_manager import get_cache_progress
  973. return get_cache_progress()
  974. @app.post("/rebuild_cache")
  975. async def rebuild_cache_endpoint():
  976. """Trigger a rebuild of the pattern cache."""
  977. try:
  978. from modules.core.cache_manager import rebuild_cache
  979. await rebuild_cache()
  980. return {"success": True, "message": "Cache rebuild completed successfully"}
  981. except Exception as e:
  982. logger.error(f"Failed to rebuild cache: {str(e)}")
  983. raise HTTPException(status_code=500, detail=str(e))
  984. def signal_handler(signum, frame):
  985. """Handle shutdown signals gracefully but forcefully."""
  986. logger.info("Received shutdown signal, cleaning up...")
  987. try:
  988. if state.led_controller:
  989. state.led_controller.set_power(0)
  990. # Run cleanup operations - need to handle async in sync context
  991. try:
  992. # Try to run in existing loop if available
  993. import asyncio
  994. loop = asyncio.get_running_loop()
  995. # If we're in an event loop, schedule the coroutine
  996. import concurrent.futures
  997. with concurrent.futures.ThreadPoolExecutor() as executor:
  998. future = executor.submit(asyncio.run, pattern_manager.stop_actions())
  999. future.result(timeout=5.0) # Wait up to 5 seconds
  1000. except RuntimeError:
  1001. # No running loop, create a new one
  1002. import asyncio
  1003. asyncio.run(pattern_manager.stop_actions())
  1004. except Exception as cleanup_err:
  1005. logger.error(f"Error in async cleanup: {cleanup_err}")
  1006. state.save()
  1007. logger.info("Cleanup completed")
  1008. except Exception as e:
  1009. logger.error(f"Error during cleanup: {str(e)}")
  1010. finally:
  1011. logger.info("Exiting application...")
  1012. os._exit(0) # Force exit regardless of other threads
  1013. @app.get("/api/version")
  1014. async def get_version_info():
  1015. """Get current and latest version information"""
  1016. try:
  1017. version_info = await version_manager.get_version_info()
  1018. return JSONResponse(content=version_info)
  1019. except Exception as e:
  1020. logger.error(f"Error getting version info: {e}")
  1021. return JSONResponse(
  1022. content={
  1023. "current": version_manager.get_current_version(),
  1024. "latest": version_manager.get_current_version(),
  1025. "update_available": False,
  1026. "error": "Unable to check for updates"
  1027. },
  1028. status_code=200
  1029. )
  1030. @app.post("/api/update")
  1031. async def trigger_update():
  1032. """Trigger software update (placeholder for future implementation)"""
  1033. try:
  1034. # For now, just return the GitHub release URL
  1035. version_info = await version_manager.get_version_info()
  1036. if version_info.get("latest_release"):
  1037. return JSONResponse(content={
  1038. "success": False,
  1039. "message": "Automatic updates not implemented yet",
  1040. "manual_update_url": version_info["latest_release"].get("html_url"),
  1041. "instructions": "Please visit the GitHub release page to download and install the update manually"
  1042. })
  1043. else:
  1044. return JSONResponse(content={
  1045. "success": False,
  1046. "message": "No updates available"
  1047. })
  1048. except Exception as e:
  1049. logger.error(f"Error triggering update: {e}")
  1050. return JSONResponse(
  1051. content={"success": False, "message": "Failed to check for updates"},
  1052. status_code=500
  1053. )
  1054. def entrypoint():
  1055. import uvicorn
  1056. logger.info("Starting FastAPI server on port 8080...")
  1057. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  1058. if __name__ == "__main__":
  1059. entrypoint()