main.py 96 KB

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