main.py 50 KB

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