main.py 86 KB

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