1
0

main.py 82 KB

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