main.py 74 KB

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