1
0

main.py 86 KB

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