main.py 81 KB

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