main.py 85 KB

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