main.py 85 KB

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