main.py 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  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. finish_pattern: Optional[bool] = False # Finish current pattern before pausing
  228. timezone: Optional[str] = None # IANA timezone or None for system default
  229. time_slots: List[TimeSlot] = []
  230. class CoordinateRequest(BaseModel):
  231. theta: float
  232. rho: float
  233. class PlaylistRequest(BaseModel):
  234. playlist_name: str
  235. files: List[str] = []
  236. pause_time: float = 0
  237. clear_pattern: Optional[str] = None
  238. run_mode: str = "single"
  239. shuffle: bool = False
  240. class PlaylistRunRequest(BaseModel):
  241. playlist_name: str
  242. pause_time: Optional[float] = 0
  243. clear_pattern: Optional[str] = None
  244. run_mode: Optional[str] = "single"
  245. shuffle: Optional[bool] = False
  246. start_time: Optional[str] = None
  247. end_time: Optional[str] = None
  248. class SpeedRequest(BaseModel):
  249. speed: float
  250. class WLEDRequest(BaseModel):
  251. wled_ip: Optional[str] = None
  252. class LEDConfigRequest(BaseModel):
  253. provider: str # "wled", "dw_leds", or "none"
  254. ip_address: Optional[str] = None # For WLED only
  255. # DW LED specific fields
  256. num_leds: Optional[int] = None
  257. gpio_pin: Optional[int] = None
  258. pixel_order: Optional[str] = None
  259. brightness: Optional[int] = None
  260. class DeletePlaylistRequest(BaseModel):
  261. playlist_name: str
  262. class RenamePlaylistRequest(BaseModel):
  263. old_name: str
  264. new_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. # ============================================================================
  271. # Unified Settings Models
  272. # ============================================================================
  273. class AppSettingsUpdate(BaseModel):
  274. name: Optional[str] = None
  275. class ConnectionSettingsUpdate(BaseModel):
  276. preferred_port: Optional[str] = None
  277. class PatternSettingsUpdate(BaseModel):
  278. clear_pattern_speed: Optional[int] = None
  279. custom_clear_from_in: Optional[str] = None
  280. custom_clear_from_out: Optional[str] = None
  281. class AutoPlaySettingsUpdate(BaseModel):
  282. enabled: Optional[bool] = None
  283. playlist: Optional[str] = None
  284. run_mode: Optional[str] = None
  285. pause_time: Optional[float] = None
  286. clear_pattern: Optional[str] = None
  287. shuffle: Optional[bool] = None
  288. class ScheduledPauseSettingsUpdate(BaseModel):
  289. enabled: Optional[bool] = None
  290. control_wled: Optional[bool] = None
  291. finish_pattern: Optional[bool] = None
  292. timezone: Optional[str] = None # IANA timezone (e.g., "America/New_York") or None for system default
  293. time_slots: Optional[List[TimeSlot]] = None
  294. class HomingSettingsUpdate(BaseModel):
  295. mode: Optional[int] = None
  296. angular_offset_degrees: Optional[float] = None
  297. auto_home_enabled: Optional[bool] = None
  298. auto_home_after_patterns: Optional[int] = None
  299. class DwLedSettingsUpdate(BaseModel):
  300. num_leds: Optional[int] = None
  301. gpio_pin: Optional[int] = None
  302. pixel_order: Optional[str] = None
  303. brightness: Optional[int] = None
  304. speed: Optional[int] = None
  305. intensity: Optional[int] = None
  306. idle_effect: Optional[dict] = None
  307. playing_effect: Optional[dict] = None
  308. idle_timeout_enabled: Optional[bool] = None
  309. idle_timeout_minutes: Optional[int] = None
  310. class LedSettingsUpdate(BaseModel):
  311. provider: Optional[str] = None # "none", "wled", "dw_leds"
  312. wled_ip: Optional[str] = None
  313. dw_led: Optional[DwLedSettingsUpdate] = None
  314. class MqttSettingsUpdate(BaseModel):
  315. enabled: Optional[bool] = None
  316. broker: Optional[str] = None
  317. port: Optional[int] = None
  318. username: Optional[str] = None
  319. password: Optional[str] = None # Write-only, never returned in GET
  320. client_id: Optional[str] = None
  321. discovery_prefix: Optional[str] = None
  322. device_id: Optional[str] = None
  323. device_name: Optional[str] = None
  324. class SettingsUpdate(BaseModel):
  325. """Request model for PATCH /api/settings - all fields optional for partial updates"""
  326. app: Optional[AppSettingsUpdate] = None
  327. connection: Optional[ConnectionSettingsUpdate] = None
  328. patterns: Optional[PatternSettingsUpdate] = None
  329. auto_play: Optional[AutoPlaySettingsUpdate] = None
  330. scheduled_pause: Optional[ScheduledPauseSettingsUpdate] = None
  331. homing: Optional[HomingSettingsUpdate] = None
  332. led: Optional[LedSettingsUpdate] = None
  333. mqtt: Optional[MqttSettingsUpdate] = None
  334. # Store active WebSocket connections
  335. active_status_connections = set()
  336. active_cache_progress_connections = set()
  337. @app.websocket("/ws/status")
  338. async def websocket_status_endpoint(websocket: WebSocket):
  339. await websocket.accept()
  340. active_status_connections.add(websocket)
  341. try:
  342. while True:
  343. status = pattern_manager.get_status()
  344. try:
  345. await websocket.send_json({
  346. "type": "status_update",
  347. "data": status
  348. })
  349. except RuntimeError as e:
  350. if "close message has been sent" in str(e):
  351. break
  352. raise
  353. await asyncio.sleep(1)
  354. except WebSocketDisconnect:
  355. pass
  356. finally:
  357. active_status_connections.discard(websocket)
  358. try:
  359. await websocket.close()
  360. except RuntimeError:
  361. pass
  362. async def broadcast_status_update(status: dict):
  363. """Broadcast status update to all connected clients."""
  364. disconnected = set()
  365. for websocket in active_status_connections:
  366. try:
  367. await websocket.send_json({
  368. "type": "status_update",
  369. "data": status
  370. })
  371. except WebSocketDisconnect:
  372. disconnected.add(websocket)
  373. except RuntimeError:
  374. disconnected.add(websocket)
  375. active_status_connections.difference_update(disconnected)
  376. @app.websocket("/ws/cache-progress")
  377. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  378. from modules.core.cache_manager import get_cache_progress
  379. await websocket.accept()
  380. active_cache_progress_connections.add(websocket)
  381. try:
  382. while True:
  383. progress = get_cache_progress()
  384. try:
  385. await websocket.send_json({
  386. "type": "cache_progress",
  387. "data": progress
  388. })
  389. except RuntimeError as e:
  390. if "close message has been sent" in str(e):
  391. break
  392. raise
  393. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  394. except WebSocketDisconnect:
  395. pass
  396. finally:
  397. active_cache_progress_connections.discard(websocket)
  398. try:
  399. await websocket.close()
  400. except RuntimeError:
  401. pass
  402. # FastAPI routes
  403. @app.get("/")
  404. async def index(request: Request):
  405. return templates.TemplateResponse("index.html", {"request": request, "app_name": state.app_name})
  406. @app.get("/settings")
  407. async def settings(request: Request):
  408. return templates.TemplateResponse("settings.html", {"request": request, "app_name": state.app_name})
  409. # ============================================================================
  410. # Unified Settings API
  411. # ============================================================================
  412. @app.get("/api/settings", tags=["settings"])
  413. async def get_all_settings():
  414. """
  415. Get all application settings in a unified structure.
  416. This endpoint consolidates multiple settings endpoints into a single response.
  417. Individual settings endpoints are deprecated but still functional.
  418. """
  419. return {
  420. "app": {
  421. "name": state.app_name
  422. },
  423. "connection": {
  424. "preferred_port": state.preferred_port
  425. },
  426. "patterns": {
  427. "clear_pattern_speed": state.clear_pattern_speed,
  428. "custom_clear_from_in": state.custom_clear_from_in,
  429. "custom_clear_from_out": state.custom_clear_from_out
  430. },
  431. "auto_play": {
  432. "enabled": state.auto_play_enabled,
  433. "playlist": state.auto_play_playlist,
  434. "run_mode": state.auto_play_run_mode,
  435. "pause_time": state.auto_play_pause_time,
  436. "clear_pattern": state.auto_play_clear_pattern,
  437. "shuffle": state.auto_play_shuffle
  438. },
  439. "scheduled_pause": {
  440. "enabled": state.scheduled_pause_enabled,
  441. "control_wled": state.scheduled_pause_control_wled,
  442. "finish_pattern": state.scheduled_pause_finish_pattern,
  443. "timezone": state.scheduled_pause_timezone,
  444. "time_slots": state.scheduled_pause_time_slots
  445. },
  446. "homing": {
  447. "mode": state.homing,
  448. "angular_offset_degrees": state.angular_homing_offset_degrees,
  449. "auto_home_enabled": state.auto_home_enabled,
  450. "auto_home_after_patterns": state.auto_home_after_patterns
  451. },
  452. "led": {
  453. "provider": state.led_provider,
  454. "wled_ip": state.wled_ip,
  455. "dw_led": {
  456. "num_leds": state.dw_led_num_leds,
  457. "gpio_pin": state.dw_led_gpio_pin,
  458. "pixel_order": state.dw_led_pixel_order,
  459. "brightness": state.dw_led_brightness,
  460. "speed": state.dw_led_speed,
  461. "intensity": state.dw_led_intensity,
  462. "idle_effect": state.dw_led_idle_effect,
  463. "playing_effect": state.dw_led_playing_effect,
  464. "idle_timeout_enabled": state.dw_led_idle_timeout_enabled,
  465. "idle_timeout_minutes": state.dw_led_idle_timeout_minutes
  466. }
  467. },
  468. "mqtt": {
  469. "enabled": state.mqtt_enabled,
  470. "broker": state.mqtt_broker,
  471. "port": state.mqtt_port,
  472. "username": state.mqtt_username,
  473. "has_password": bool(state.mqtt_password),
  474. "client_id": state.mqtt_client_id,
  475. "discovery_prefix": state.mqtt_discovery_prefix,
  476. "device_id": state.mqtt_device_id,
  477. "device_name": state.mqtt_device_name
  478. }
  479. }
  480. @app.patch("/api/settings", tags=["settings"])
  481. async def update_settings(settings_update: SettingsUpdate):
  482. """
  483. Partially update application settings.
  484. Only include the categories and fields you want to update.
  485. All fields are optional - only provided values will be updated.
  486. Example: {"app": {"name": "My Sand Table"}, "auto_play": {"enabled": true}}
  487. """
  488. updated_categories = []
  489. requires_restart = False
  490. led_reinit_needed = False
  491. old_led_provider = state.led_provider
  492. # App settings
  493. if settings_update.app:
  494. if settings_update.app.name is not None:
  495. state.app_name = settings_update.app.name or "Dune Weaver"
  496. updated_categories.append("app")
  497. # Connection settings
  498. if settings_update.connection:
  499. if settings_update.connection.preferred_port is not None:
  500. port = settings_update.connection.preferred_port
  501. state.preferred_port = None if port in ("", "none") else port
  502. updated_categories.append("connection")
  503. # Pattern settings
  504. if settings_update.patterns:
  505. p = settings_update.patterns
  506. if p.clear_pattern_speed is not None:
  507. state.clear_pattern_speed = p.clear_pattern_speed if p.clear_pattern_speed > 0 else None
  508. if p.custom_clear_from_in is not None:
  509. state.custom_clear_from_in = p.custom_clear_from_in or None
  510. if p.custom_clear_from_out is not None:
  511. state.custom_clear_from_out = p.custom_clear_from_out or None
  512. updated_categories.append("patterns")
  513. # Auto-play settings
  514. if settings_update.auto_play:
  515. ap = settings_update.auto_play
  516. if ap.enabled is not None:
  517. state.auto_play_enabled = ap.enabled
  518. if ap.playlist is not None:
  519. state.auto_play_playlist = ap.playlist or None
  520. if ap.run_mode is not None:
  521. state.auto_play_run_mode = ap.run_mode
  522. if ap.pause_time is not None:
  523. state.auto_play_pause_time = ap.pause_time
  524. if ap.clear_pattern is not None:
  525. state.auto_play_clear_pattern = ap.clear_pattern
  526. if ap.shuffle is not None:
  527. state.auto_play_shuffle = ap.shuffle
  528. updated_categories.append("auto_play")
  529. # Scheduled pause (Still Sands) settings
  530. if settings_update.scheduled_pause:
  531. sp = settings_update.scheduled_pause
  532. if sp.enabled is not None:
  533. state.scheduled_pause_enabled = sp.enabled
  534. if sp.control_wled is not None:
  535. state.scheduled_pause_control_wled = sp.control_wled
  536. if sp.finish_pattern is not None:
  537. state.scheduled_pause_finish_pattern = sp.finish_pattern
  538. if sp.timezone is not None:
  539. # Empty string means use system default (store as None)
  540. state.scheduled_pause_timezone = sp.timezone if sp.timezone else None
  541. # Clear cached timezone in pattern_manager so it picks up the new setting
  542. from modules.core import pattern_manager
  543. pattern_manager._cached_timezone = None
  544. pattern_manager._cached_zoneinfo = None
  545. if sp.time_slots is not None:
  546. state.scheduled_pause_time_slots = [slot.model_dump() for slot in sp.time_slots]
  547. updated_categories.append("scheduled_pause")
  548. # Homing settings
  549. if settings_update.homing:
  550. h = settings_update.homing
  551. if h.mode is not None:
  552. state.homing = h.mode
  553. if h.angular_offset_degrees is not None:
  554. state.angular_homing_offset_degrees = h.angular_offset_degrees
  555. if h.auto_home_enabled is not None:
  556. state.auto_home_enabled = h.auto_home_enabled
  557. if h.auto_home_after_patterns is not None:
  558. state.auto_home_after_patterns = h.auto_home_after_patterns
  559. updated_categories.append("homing")
  560. # LED settings
  561. if settings_update.led:
  562. led = settings_update.led
  563. if led.provider is not None:
  564. state.led_provider = led.provider
  565. if led.provider != old_led_provider:
  566. led_reinit_needed = True
  567. if led.wled_ip is not None:
  568. state.wled_ip = led.wled_ip or None
  569. if led.dw_led:
  570. dw = led.dw_led
  571. if dw.num_leds is not None:
  572. state.dw_led_num_leds = dw.num_leds
  573. if dw.gpio_pin is not None:
  574. state.dw_led_gpio_pin = dw.gpio_pin
  575. if dw.pixel_order is not None:
  576. state.dw_led_pixel_order = dw.pixel_order
  577. if dw.brightness is not None:
  578. state.dw_led_brightness = dw.brightness
  579. if dw.speed is not None:
  580. state.dw_led_speed = dw.speed
  581. if dw.intensity is not None:
  582. state.dw_led_intensity = dw.intensity
  583. if dw.idle_effect is not None:
  584. state.dw_led_idle_effect = dw.idle_effect
  585. if dw.playing_effect is not None:
  586. state.dw_led_playing_effect = dw.playing_effect
  587. if dw.idle_timeout_enabled is not None:
  588. state.dw_led_idle_timeout_enabled = dw.idle_timeout_enabled
  589. if dw.idle_timeout_minutes is not None:
  590. state.dw_led_idle_timeout_minutes = dw.idle_timeout_minutes
  591. updated_categories.append("led")
  592. # MQTT settings
  593. if settings_update.mqtt:
  594. m = settings_update.mqtt
  595. if m.enabled is not None:
  596. state.mqtt_enabled = m.enabled
  597. if m.broker is not None:
  598. state.mqtt_broker = m.broker
  599. if m.port is not None:
  600. state.mqtt_port = m.port
  601. if m.username is not None:
  602. state.mqtt_username = m.username
  603. if m.password is not None:
  604. state.mqtt_password = m.password
  605. if m.client_id is not None:
  606. state.mqtt_client_id = m.client_id
  607. if m.discovery_prefix is not None:
  608. state.mqtt_discovery_prefix = m.discovery_prefix
  609. if m.device_id is not None:
  610. state.mqtt_device_id = m.device_id
  611. if m.device_name is not None:
  612. state.mqtt_device_name = m.device_name
  613. updated_categories.append("mqtt")
  614. requires_restart = True
  615. # Save state
  616. state.save()
  617. # Handle LED reinitialization if provider changed
  618. if led_reinit_needed:
  619. logger.info(f"LED provider changed from {old_led_provider} to {state.led_provider}, reinitialization may be needed")
  620. logger.info(f"Settings updated: {', '.join(updated_categories)}")
  621. return {
  622. "success": True,
  623. "updated_categories": updated_categories,
  624. "requires_restart": requires_restart,
  625. "led_reinit_needed": led_reinit_needed
  626. }
  627. # ============================================================================
  628. # Individual Settings Endpoints (Deprecated - use /api/settings instead)
  629. # ============================================================================
  630. @app.get("/api/auto_play-mode", deprecated=True, tags=["settings-deprecated"])
  631. async def get_auto_play_mode():
  632. """DEPRECATED: Use GET /api/settings instead. Get current auto_play mode settings."""
  633. return {
  634. "enabled": state.auto_play_enabled,
  635. "playlist": state.auto_play_playlist,
  636. "run_mode": state.auto_play_run_mode,
  637. "pause_time": state.auto_play_pause_time,
  638. "clear_pattern": state.auto_play_clear_pattern,
  639. "shuffle": state.auto_play_shuffle
  640. }
  641. @app.post("/api/auto_play-mode", deprecated=True, tags=["settings-deprecated"])
  642. async def set_auto_play_mode(request: auto_playModeRequest):
  643. """DEPRECATED: Use PATCH /api/settings instead. Update auto_play mode settings."""
  644. state.auto_play_enabled = request.enabled
  645. if request.playlist is not None:
  646. state.auto_play_playlist = request.playlist
  647. if request.run_mode is not None:
  648. state.auto_play_run_mode = request.run_mode
  649. if request.pause_time is not None:
  650. state.auto_play_pause_time = request.pause_time
  651. if request.clear_pattern is not None:
  652. state.auto_play_clear_pattern = request.clear_pattern
  653. if request.shuffle is not None:
  654. state.auto_play_shuffle = request.shuffle
  655. state.save()
  656. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  657. return {"success": True, "message": "auto_play mode settings updated"}
  658. @app.get("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  659. async def get_scheduled_pause():
  660. """DEPRECATED: Use GET /api/settings instead. Get current Still Sands settings."""
  661. return {
  662. "enabled": state.scheduled_pause_enabled,
  663. "control_wled": state.scheduled_pause_control_wled,
  664. "finish_pattern": state.scheduled_pause_finish_pattern,
  665. "timezone": state.scheduled_pause_timezone,
  666. "time_slots": state.scheduled_pause_time_slots
  667. }
  668. @app.post("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  669. async def set_scheduled_pause(request: ScheduledPauseRequest):
  670. """Update Still Sands settings."""
  671. try:
  672. # Validate time slots
  673. for i, slot in enumerate(request.time_slots):
  674. # Validate time format (HH:MM)
  675. try:
  676. start_time = datetime.strptime(slot.start_time, "%H:%M").time()
  677. end_time = datetime.strptime(slot.end_time, "%H:%M").time()
  678. except ValueError:
  679. raise HTTPException(
  680. status_code=400,
  681. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  682. )
  683. # Validate days setting
  684. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  685. raise HTTPException(
  686. status_code=400,
  687. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  688. )
  689. # Validate custom days if applicable
  690. if slot.days == "custom":
  691. if not slot.custom_days or len(slot.custom_days) == 0:
  692. raise HTTPException(
  693. status_code=400,
  694. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  695. )
  696. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  697. for day in slot.custom_days:
  698. if day not in valid_days:
  699. raise HTTPException(
  700. status_code=400,
  701. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  702. )
  703. # Update state
  704. state.scheduled_pause_enabled = request.enabled
  705. state.scheduled_pause_control_wled = request.control_wled
  706. state.scheduled_pause_finish_pattern = request.finish_pattern
  707. state.scheduled_pause_timezone = request.timezone if request.timezone else None
  708. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  709. state.save()
  710. # Clear cached timezone so it picks up the new setting
  711. from modules.core import pattern_manager
  712. pattern_manager._cached_timezone = None
  713. pattern_manager._cached_zoneinfo = None
  714. wled_msg = " (with WLED control)" if request.control_wled else ""
  715. finish_msg = " (finish pattern first)" if request.finish_pattern else ""
  716. tz_msg = f" (timezone: {request.timezone})" if request.timezone else ""
  717. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}{finish_msg}{tz_msg}")
  718. return {"success": True, "message": "Still Sands settings updated"}
  719. except HTTPException:
  720. raise
  721. except Exception as e:
  722. logger.error(f"Error updating Still Sands settings: {str(e)}")
  723. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  724. @app.get("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  725. async def get_homing_config():
  726. """Get homing configuration (mode, compass offset, and auto-home settings)."""
  727. return {
  728. "homing_mode": state.homing,
  729. "angular_homing_offset_degrees": state.angular_homing_offset_degrees,
  730. "auto_home_enabled": state.auto_home_enabled,
  731. "auto_home_after_patterns": state.auto_home_after_patterns
  732. }
  733. class HomingConfigRequest(BaseModel):
  734. homing_mode: int = 0 # 0 = crash, 1 = sensor
  735. angular_homing_offset_degrees: float = 0.0
  736. auto_home_enabled: Optional[bool] = None
  737. auto_home_after_patterns: Optional[int] = None
  738. @app.post("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  739. async def set_homing_config(request: HomingConfigRequest):
  740. """Set homing configuration (mode, compass offset, and auto-home settings)."""
  741. try:
  742. # Validate homing mode
  743. if request.homing_mode not in [0, 1]:
  744. raise HTTPException(status_code=400, detail="Homing mode must be 0 (crash) or 1 (sensor)")
  745. state.homing = request.homing_mode
  746. state.angular_homing_offset_degrees = request.angular_homing_offset_degrees
  747. # Update auto-home settings if provided
  748. if request.auto_home_enabled is not None:
  749. state.auto_home_enabled = request.auto_home_enabled
  750. if request.auto_home_after_patterns is not None:
  751. if request.auto_home_after_patterns < 1:
  752. raise HTTPException(status_code=400, detail="Auto-home after patterns must be at least 1")
  753. state.auto_home_after_patterns = request.auto_home_after_patterns
  754. state.save()
  755. mode_name = "crash" if request.homing_mode == 0 else "sensor"
  756. logger.info(f"Homing mode set to {mode_name}, compass offset set to {request.angular_homing_offset_degrees}°")
  757. if request.auto_home_enabled is not None:
  758. logger.info(f"Auto-home enabled: {state.auto_home_enabled}, after {state.auto_home_after_patterns} patterns")
  759. return {"success": True, "message": "Homing configuration updated"}
  760. except HTTPException:
  761. raise
  762. except Exception as e:
  763. logger.error(f"Error updating homing configuration: {str(e)}")
  764. raise HTTPException(status_code=500, detail=f"Failed to update homing configuration: {str(e)}")
  765. @app.get("/list_serial_ports")
  766. async def list_ports():
  767. logger.debug("Listing available serial ports")
  768. return await asyncio.to_thread(connection_manager.list_serial_ports)
  769. @app.post("/connect")
  770. async def connect(request: ConnectRequest):
  771. if not request.port:
  772. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  773. connection_manager.device_init()
  774. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  775. return {"success": True}
  776. try:
  777. state.conn = connection_manager.SerialConnection(request.port)
  778. connection_manager.device_init()
  779. logger.info(f'Successfully connected to serial port {request.port}')
  780. return {"success": True}
  781. except Exception as e:
  782. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  783. raise HTTPException(status_code=500, detail=str(e))
  784. @app.post("/disconnect")
  785. async def disconnect():
  786. try:
  787. state.conn.close()
  788. logger.info('Successfully disconnected from serial port')
  789. return {"success": True}
  790. except Exception as e:
  791. logger.error(f'Failed to disconnect serial: {str(e)}')
  792. raise HTTPException(status_code=500, detail=str(e))
  793. @app.post("/restart_connection")
  794. async def restart(request: ConnectRequest):
  795. if not request.port:
  796. logger.warning("Restart serial request received without port")
  797. raise HTTPException(status_code=400, detail="No port provided")
  798. try:
  799. logger.info(f"Restarting connection on port {request.port}")
  800. connection_manager.restart_connection()
  801. return {"success": True}
  802. except Exception as e:
  803. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  804. raise HTTPException(status_code=500, detail=str(e))
  805. @app.get("/list_theta_rho_files")
  806. async def list_theta_rho_files():
  807. logger.debug("Listing theta-rho files")
  808. # Run the blocking file system operation in a thread pool
  809. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  810. return sorted(files)
  811. @app.get("/list_theta_rho_files_with_metadata")
  812. async def list_theta_rho_files_with_metadata():
  813. """Get list of theta-rho files with metadata for sorting and filtering.
  814. Optimized to process files asynchronously and support request cancellation.
  815. """
  816. from modules.core.cache_manager import get_pattern_metadata
  817. import asyncio
  818. from concurrent.futures import ThreadPoolExecutor
  819. # Run the blocking file listing in a thread
  820. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  821. files_with_metadata = []
  822. # Use ThreadPoolExecutor for I/O-bound operations
  823. executor = ThreadPoolExecutor(max_workers=4)
  824. def process_file(file_path):
  825. """Process a single file and return its metadata."""
  826. try:
  827. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  828. # Get file stats
  829. file_stat = os.stat(full_path)
  830. # Get cached metadata (this should be fast if cached)
  831. metadata = get_pattern_metadata(file_path)
  832. # Extract full folder path from file path
  833. path_parts = file_path.split('/')
  834. if len(path_parts) > 1:
  835. # Get everything except the filename (join all folder parts)
  836. category = '/'.join(path_parts[:-1])
  837. else:
  838. category = 'root'
  839. # Get file name without extension
  840. file_name = os.path.splitext(os.path.basename(file_path))[0]
  841. # Use modification time (mtime) for "date modified"
  842. date_modified = file_stat.st_mtime
  843. return {
  844. 'path': file_path,
  845. 'name': file_name,
  846. 'category': category,
  847. 'date_modified': date_modified,
  848. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  849. }
  850. except Exception as e:
  851. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  852. # Include file with minimal info if metadata fails
  853. path_parts = file_path.split('/')
  854. if len(path_parts) > 1:
  855. category = '/'.join(path_parts[:-1])
  856. else:
  857. category = 'root'
  858. return {
  859. 'path': file_path,
  860. 'name': os.path.splitext(os.path.basename(file_path))[0],
  861. 'category': category,
  862. 'date_modified': 0,
  863. 'coordinates_count': 0
  864. }
  865. # Load the entire metadata cache at once (async)
  866. # This is much faster than 1000+ individual metadata lookups
  867. try:
  868. import json
  869. metadata_cache_path = "metadata_cache.json"
  870. # Use async file reading to avoid blocking the event loop
  871. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  872. cache_dict = cache_data.get('data', {})
  873. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  874. # Process all files using cached data only
  875. for file_path in files:
  876. try:
  877. # Extract category from path
  878. path_parts = file_path.split('/')
  879. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  880. # Get file name without extension
  881. file_name = os.path.splitext(os.path.basename(file_path))[0]
  882. # Get metadata from cache
  883. cached_entry = cache_dict.get(file_path, {})
  884. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  885. metadata = cached_entry['metadata']
  886. coords_count = metadata.get('total_coordinates', 0)
  887. date_modified = cached_entry.get('mtime', 0)
  888. else:
  889. coords_count = 0
  890. date_modified = 0
  891. files_with_metadata.append({
  892. 'path': file_path,
  893. 'name': file_name,
  894. 'category': category,
  895. 'date_modified': date_modified,
  896. 'coordinates_count': coords_count
  897. })
  898. except Exception as e:
  899. logger.warning(f"Error processing {file_path}: {e}")
  900. # Include file with minimal info if processing fails
  901. path_parts = file_path.split('/')
  902. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  903. files_with_metadata.append({
  904. 'path': file_path,
  905. 'name': os.path.splitext(os.path.basename(file_path))[0],
  906. 'category': category,
  907. 'date_modified': 0,
  908. 'coordinates_count': 0
  909. })
  910. except Exception as e:
  911. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  912. # Fallback to original method if cache loading fails
  913. # Create tasks only when needed
  914. loop = asyncio.get_event_loop()
  915. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  916. for task in asyncio.as_completed(tasks):
  917. try:
  918. result = await task
  919. files_with_metadata.append(result)
  920. except Exception as task_error:
  921. logger.error(f"Error processing file: {str(task_error)}")
  922. # Clean up executor
  923. executor.shutdown(wait=False)
  924. return files_with_metadata
  925. @app.post("/upload_theta_rho")
  926. async def upload_theta_rho(file: UploadFile = File(...)):
  927. """Upload a theta-rho file."""
  928. try:
  929. # Save the file
  930. # Ensure custom_patterns directory exists
  931. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  932. os.makedirs(custom_patterns_dir, exist_ok=True)
  933. # Use forward slashes for internal path representation to maintain consistency
  934. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  935. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  936. # Save the uploaded file with proper encoding for Windows compatibility
  937. file_content = await file.read()
  938. try:
  939. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  940. text_content = file_content.decode('utf-8')
  941. with open(full_file_path, "w", encoding='utf-8') as f:
  942. f.write(text_content)
  943. except UnicodeDecodeError:
  944. # If UTF-8 decoding fails, save as binary (fallback)
  945. with open(full_file_path, "wb") as f:
  946. f.write(file_content)
  947. logger.info(f"File {file.filename} saved successfully")
  948. # Generate image preview for the new file with retry logic
  949. max_retries = 3
  950. for attempt in range(max_retries):
  951. try:
  952. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  953. success = await generate_image_preview(file_path_in_patterns_dir)
  954. if success:
  955. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  956. break
  957. else:
  958. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  959. if attempt < max_retries - 1:
  960. await asyncio.sleep(0.5) # Small delay before retry
  961. except Exception as e:
  962. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  963. if attempt < max_retries - 1:
  964. await asyncio.sleep(0.5) # Small delay before retry
  965. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  966. except Exception as e:
  967. logger.error(f"Error uploading file: {str(e)}")
  968. raise HTTPException(status_code=500, detail=str(e))
  969. @app.post("/get_theta_rho_coordinates")
  970. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  971. """Get theta-rho coordinates for animated preview."""
  972. try:
  973. # Normalize file path for cross-platform compatibility and remove prefixes
  974. file_name = normalize_file_path(request.file_name)
  975. file_path = os.path.join(THETA_RHO_DIR, file_name)
  976. # Check file existence asynchronously
  977. exists = await asyncio.to_thread(os.path.exists, file_path)
  978. if not exists:
  979. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  980. # Parse the theta-rho file in a separate process for CPU-intensive work
  981. # This prevents blocking the motion control thread
  982. loop = asyncio.get_event_loop()
  983. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, file_path)
  984. if not coordinates:
  985. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  986. return {
  987. "success": True,
  988. "coordinates": coordinates,
  989. "total_points": len(coordinates)
  990. }
  991. except Exception as e:
  992. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  993. raise HTTPException(status_code=500, detail=str(e))
  994. @app.post("/run_theta_rho")
  995. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  996. if not request.file_name:
  997. logger.warning('Run theta-rho request received without file name')
  998. raise HTTPException(status_code=400, detail="No file name provided")
  999. file_path = None
  1000. if 'clear' in request.file_name:
  1001. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  1002. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  1003. logger.info(f'Clear pattern file: {file_path}')
  1004. if not file_path:
  1005. # Normalize file path for cross-platform compatibility
  1006. normalized_file_name = normalize_file_path(request.file_name)
  1007. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1008. if not os.path.exists(file_path):
  1009. logger.error(f'Theta-rho file not found: {file_path}')
  1010. raise HTTPException(status_code=404, detail="File not found")
  1011. try:
  1012. if not (state.conn.is_connected() if state.conn else False):
  1013. logger.warning("Attempted to run a pattern without a connection")
  1014. raise HTTPException(status_code=400, detail="Connection not established")
  1015. if pattern_manager.pattern_lock.locked():
  1016. logger.warning("Attempted to run a pattern while another is already running")
  1017. raise HTTPException(status_code=409, detail="Another pattern is already running")
  1018. files_to_run = [file_path]
  1019. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  1020. # Only include clear_pattern if it's not "none"
  1021. kwargs = {}
  1022. if request.pre_execution != "none":
  1023. kwargs['clear_pattern'] = request.pre_execution
  1024. # Pass arguments properly
  1025. background_tasks.add_task(
  1026. pattern_manager.run_theta_rho_files,
  1027. files_to_run, # First positional argument
  1028. **kwargs # Spread keyword arguments
  1029. )
  1030. return {"success": True}
  1031. except HTTPException as http_exc:
  1032. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  1033. raise http_exc
  1034. except Exception as e:
  1035. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  1036. raise HTTPException(status_code=500, detail=str(e))
  1037. @app.post("/stop_execution")
  1038. async def stop_execution():
  1039. if not (state.conn.is_connected() if state.conn else False):
  1040. logger.warning("Attempted to stop without a connection")
  1041. raise HTTPException(status_code=400, detail="Connection not established")
  1042. await pattern_manager.stop_actions()
  1043. return {"success": True}
  1044. @app.post("/send_home")
  1045. async def send_home():
  1046. try:
  1047. if not (state.conn.is_connected() if state.conn else False):
  1048. logger.warning("Attempted to move to home without a connection")
  1049. raise HTTPException(status_code=400, detail="Connection not established")
  1050. # Run homing with 15 second timeout
  1051. success = await asyncio.to_thread(connection_manager.home)
  1052. if not success:
  1053. logger.error("Homing failed or timed out")
  1054. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  1055. return {"success": True}
  1056. except HTTPException:
  1057. raise
  1058. except Exception as e:
  1059. logger.error(f"Failed to send home command: {str(e)}")
  1060. raise HTTPException(status_code=500, detail=str(e))
  1061. @app.post("/run_theta_rho_file/{file_name}")
  1062. async def run_specific_theta_rho_file(file_name: str):
  1063. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  1064. if not os.path.exists(file_path):
  1065. raise HTTPException(status_code=404, detail="File not found")
  1066. if not (state.conn.is_connected() if state.conn else False):
  1067. logger.warning("Attempted to run a pattern without a connection")
  1068. raise HTTPException(status_code=400, detail="Connection not established")
  1069. pattern_manager.run_theta_rho_file(file_path)
  1070. return {"success": True}
  1071. class DeleteFileRequest(BaseModel):
  1072. file_name: str
  1073. @app.post("/delete_theta_rho_file")
  1074. async def delete_theta_rho_file(request: DeleteFileRequest):
  1075. if not request.file_name:
  1076. logger.warning("Delete theta-rho file request received without filename")
  1077. raise HTTPException(status_code=400, detail="No file name provided")
  1078. # Normalize file path for cross-platform compatibility
  1079. normalized_file_name = normalize_file_path(request.file_name)
  1080. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1081. # Check file existence asynchronously
  1082. exists = await asyncio.to_thread(os.path.exists, file_path)
  1083. if not exists:
  1084. logger.error(f"Attempted to delete non-existent file: {file_path}")
  1085. raise HTTPException(status_code=404, detail="File not found")
  1086. try:
  1087. # Delete the pattern file asynchronously
  1088. await asyncio.to_thread(os.remove, file_path)
  1089. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  1090. # Clean up cached preview image and metadata asynchronously
  1091. from modules.core.cache_manager import delete_pattern_cache
  1092. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  1093. if cache_cleanup_success:
  1094. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  1095. else:
  1096. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  1097. return {"success": True, "cache_cleanup": cache_cleanup_success}
  1098. except Exception as e:
  1099. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  1100. raise HTTPException(status_code=500, detail=str(e))
  1101. @app.post("/move_to_center")
  1102. async def move_to_center():
  1103. try:
  1104. if not (state.conn.is_connected() if state.conn else False):
  1105. logger.warning("Attempted to move to center without a connection")
  1106. raise HTTPException(status_code=400, detail="Connection not established")
  1107. logger.info("Moving device to center position")
  1108. await pattern_manager.reset_theta()
  1109. await pattern_manager.move_polar(0, 0)
  1110. return {"success": True}
  1111. except Exception as e:
  1112. logger.error(f"Failed to move to center: {str(e)}")
  1113. raise HTTPException(status_code=500, detail=str(e))
  1114. @app.post("/move_to_perimeter")
  1115. async def move_to_perimeter():
  1116. try:
  1117. if not (state.conn.is_connected() if state.conn else False):
  1118. logger.warning("Attempted to move to perimeter without a connection")
  1119. raise HTTPException(status_code=400, detail="Connection not established")
  1120. await pattern_manager.reset_theta()
  1121. await pattern_manager.move_polar(0, 1)
  1122. return {"success": True}
  1123. except Exception as e:
  1124. logger.error(f"Failed to move to perimeter: {str(e)}")
  1125. raise HTTPException(status_code=500, detail=str(e))
  1126. @app.post("/preview_thr")
  1127. async def preview_thr(request: DeleteFileRequest):
  1128. if not request.file_name:
  1129. logger.warning("Preview theta-rho request received without filename")
  1130. raise HTTPException(status_code=400, detail="No file name provided")
  1131. # Normalize file path for cross-platform compatibility
  1132. normalized_file_name = normalize_file_path(request.file_name)
  1133. # Construct the full path to the pattern file to check existence
  1134. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1135. # Check file existence asynchronously
  1136. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1137. if not exists:
  1138. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  1139. raise HTTPException(status_code=404, detail="Pattern file not found")
  1140. try:
  1141. cache_path = get_cache_path(normalized_file_name)
  1142. # Check cache existence asynchronously
  1143. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1144. if not cache_exists:
  1145. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  1146. # Attempt to generate the preview if it's missing
  1147. success = await generate_image_preview(normalized_file_name)
  1148. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1149. if not success or not cache_exists_after:
  1150. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  1151. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  1152. # Try to get coordinates from metadata cache first
  1153. metadata = get_pattern_metadata(normalized_file_name)
  1154. if metadata:
  1155. first_coord_obj = metadata.get('first_coordinate')
  1156. last_coord_obj = metadata.get('last_coordinate')
  1157. else:
  1158. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  1159. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  1160. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  1161. first_coord = coordinates[0] if coordinates else None
  1162. last_coord = coordinates[-1] if coordinates else None
  1163. # Format coordinates as objects with x and y properties
  1164. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1165. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1166. # Return JSON with preview URL and coordinates
  1167. # URL encode the file_name for the preview URL
  1168. # Handle both forward slashes and backslashes for cross-platform compatibility
  1169. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  1170. return {
  1171. "preview_url": f"/preview/{encoded_filename}",
  1172. "first_coordinate": first_coord_obj,
  1173. "last_coordinate": last_coord_obj
  1174. }
  1175. except HTTPException:
  1176. raise
  1177. except Exception as e:
  1178. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  1179. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  1180. @app.get("/preview/{encoded_filename}")
  1181. async def serve_preview(encoded_filename: str):
  1182. """Serve a preview image for a pattern file."""
  1183. # Decode the filename by replacing -- with the original path separators
  1184. # First try forward slash (most common case), then backslash if needed
  1185. file_name = encoded_filename.replace('--', '/')
  1186. # Apply normalization to handle any remaining path prefixes
  1187. file_name = normalize_file_path(file_name)
  1188. # Check if the decoded path exists, if not try backslash decoding
  1189. cache_path = get_cache_path(file_name)
  1190. if not os.path.exists(cache_path):
  1191. # Try with backslash for Windows paths
  1192. file_name_backslash = encoded_filename.replace('--', '\\')
  1193. file_name_backslash = normalize_file_path(file_name_backslash)
  1194. cache_path_backslash = get_cache_path(file_name_backslash)
  1195. if os.path.exists(cache_path_backslash):
  1196. file_name = file_name_backslash
  1197. cache_path = cache_path_backslash
  1198. # cache_path is already determined above in the decoding logic
  1199. if not os.path.exists(cache_path):
  1200. logger.error(f"Preview image not found for {file_name}")
  1201. raise HTTPException(status_code=404, detail="Preview image not found")
  1202. # Add caching headers
  1203. headers = {
  1204. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  1205. "Content-Type": "image/webp",
  1206. "Accept-Ranges": "bytes"
  1207. }
  1208. return FileResponse(
  1209. cache_path,
  1210. media_type="image/webp",
  1211. headers=headers
  1212. )
  1213. @app.post("/send_coordinate")
  1214. async def send_coordinate(request: CoordinateRequest):
  1215. if not (state.conn.is_connected() if state.conn else False):
  1216. logger.warning("Attempted to send coordinate without a connection")
  1217. raise HTTPException(status_code=400, detail="Connection not established")
  1218. try:
  1219. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  1220. await pattern_manager.move_polar(request.theta, request.rho)
  1221. return {"success": True}
  1222. except Exception as e:
  1223. logger.error(f"Failed to send coordinate: {str(e)}")
  1224. raise HTTPException(status_code=500, detail=str(e))
  1225. @app.get("/download/{filename}")
  1226. async def download_file(filename: str):
  1227. return FileResponse(
  1228. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  1229. filename=filename
  1230. )
  1231. @app.get("/serial_status")
  1232. async def serial_status():
  1233. connected = state.conn.is_connected() if state.conn else False
  1234. port = state.port
  1235. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  1236. return {
  1237. "connected": connected,
  1238. "port": port,
  1239. "preferred_port": state.preferred_port
  1240. }
  1241. @app.get("/api/preferred-port", deprecated=True, tags=["settings-deprecated"])
  1242. async def get_preferred_port():
  1243. """Get the currently configured preferred port for auto-connect."""
  1244. return {
  1245. "preferred_port": state.preferred_port
  1246. }
  1247. @app.post("/api/preferred-port", deprecated=True, tags=["settings-deprecated"])
  1248. async def set_preferred_port(request: Request):
  1249. """Set the preferred port for auto-connect."""
  1250. data = await request.json()
  1251. preferred_port = data.get("preferred_port")
  1252. # Allow setting to None to clear the preference
  1253. if preferred_port == "" or preferred_port == "none":
  1254. preferred_port = None
  1255. state.preferred_port = preferred_port
  1256. state.save()
  1257. logger.info(f"Preferred port set to: {preferred_port}")
  1258. return {
  1259. "success": True,
  1260. "preferred_port": state.preferred_port
  1261. }
  1262. @app.post("/pause_execution")
  1263. async def pause_execution():
  1264. if pattern_manager.pause_execution():
  1265. return {"success": True, "message": "Execution paused"}
  1266. raise HTTPException(status_code=500, detail="Failed to pause execution")
  1267. @app.post("/resume_execution")
  1268. async def resume_execution():
  1269. if pattern_manager.resume_execution():
  1270. return {"success": True, "message": "Execution resumed"}
  1271. raise HTTPException(status_code=500, detail="Failed to resume execution")
  1272. # Playlist endpoints
  1273. @app.get("/list_all_playlists")
  1274. async def list_all_playlists():
  1275. playlist_names = playlist_manager.list_all_playlists()
  1276. return playlist_names
  1277. @app.get("/get_playlist")
  1278. async def get_playlist(name: str):
  1279. if not name:
  1280. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  1281. playlist = playlist_manager.get_playlist(name)
  1282. if not playlist:
  1283. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  1284. return playlist
  1285. @app.post("/create_playlist")
  1286. async def create_playlist(request: PlaylistRequest):
  1287. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  1288. return {
  1289. "success": success,
  1290. "message": f"Playlist '{request.playlist_name}' created/updated"
  1291. }
  1292. @app.post("/modify_playlist")
  1293. async def modify_playlist(request: PlaylistRequest):
  1294. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  1295. return {
  1296. "success": success,
  1297. "message": f"Playlist '{request.playlist_name}' updated"
  1298. }
  1299. @app.delete("/delete_playlist")
  1300. async def delete_playlist(request: DeletePlaylistRequest):
  1301. success = playlist_manager.delete_playlist(request.playlist_name)
  1302. if not success:
  1303. raise HTTPException(
  1304. status_code=404,
  1305. detail=f"Playlist '{request.playlist_name}' not found"
  1306. )
  1307. return {
  1308. "success": True,
  1309. "message": f"Playlist '{request.playlist_name}' deleted"
  1310. }
  1311. @app.post("/rename_playlist")
  1312. async def rename_playlist(request: RenamePlaylistRequest):
  1313. """Rename an existing playlist."""
  1314. success, message = playlist_manager.rename_playlist(request.old_name, request.new_name)
  1315. if not success:
  1316. raise HTTPException(
  1317. status_code=400,
  1318. detail=message
  1319. )
  1320. return {
  1321. "success": True,
  1322. "message": message,
  1323. "new_name": request.new_name
  1324. }
  1325. class AddToPlaylistRequest(BaseModel):
  1326. playlist_name: str
  1327. pattern: str
  1328. @app.post("/add_to_playlist")
  1329. async def add_to_playlist(request: AddToPlaylistRequest):
  1330. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  1331. if not success:
  1332. raise HTTPException(status_code=404, detail="Playlist not found")
  1333. return {"success": True}
  1334. @app.post("/run_playlist")
  1335. async def run_playlist_endpoint(request: PlaylistRequest):
  1336. """Run a playlist with specified parameters."""
  1337. try:
  1338. if not (state.conn.is_connected() if state.conn else False):
  1339. logger.warning("Attempted to run a playlist without a connection")
  1340. raise HTTPException(status_code=400, detail="Connection not established")
  1341. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  1342. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  1343. # Start the playlist execution
  1344. success, message = await playlist_manager.run_playlist(
  1345. request.playlist_name,
  1346. pause_time=request.pause_time,
  1347. clear_pattern=request.clear_pattern,
  1348. run_mode=request.run_mode,
  1349. shuffle=request.shuffle
  1350. )
  1351. if not success:
  1352. raise HTTPException(status_code=409, detail=message)
  1353. return {"message": f"Started playlist: {request.playlist_name}"}
  1354. except Exception as e:
  1355. logger.error(f"Error running playlist: {e}")
  1356. raise HTTPException(status_code=500, detail=str(e))
  1357. @app.post("/set_speed")
  1358. async def set_speed(request: SpeedRequest):
  1359. try:
  1360. if not (state.conn.is_connected() if state.conn else False):
  1361. logger.warning("Attempted to change speed without a connection")
  1362. raise HTTPException(status_code=400, detail="Connection not established")
  1363. if request.speed <= 0:
  1364. logger.warning(f"Invalid speed value received: {request.speed}")
  1365. raise HTTPException(status_code=400, detail="Invalid speed value")
  1366. state.speed = request.speed
  1367. return {"success": True, "speed": request.speed}
  1368. except Exception as e:
  1369. logger.error(f"Failed to set speed: {str(e)}")
  1370. raise HTTPException(status_code=500, detail=str(e))
  1371. @app.get("/check_software_update")
  1372. async def check_updates():
  1373. update_info = update_manager.check_git_updates()
  1374. return update_info
  1375. @app.post("/update_software")
  1376. async def update_software():
  1377. logger.info("Starting software update process")
  1378. success, error_message, error_log = update_manager.update_software()
  1379. if success:
  1380. logger.info("Software update completed successfully")
  1381. return {"success": True}
  1382. else:
  1383. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  1384. raise HTTPException(
  1385. status_code=500,
  1386. detail={
  1387. "error": error_message,
  1388. "details": error_log
  1389. }
  1390. )
  1391. @app.post("/set_wled_ip")
  1392. async def set_wled_ip(request: WLEDRequest):
  1393. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  1394. state.wled_ip = request.wled_ip
  1395. state.led_provider = "wled" if request.wled_ip else "none"
  1396. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  1397. if state.led_controller:
  1398. state.led_controller.effect_idle()
  1399. _start_idle_led_timeout()
  1400. state.save()
  1401. logger.info(f"WLED IP updated: {request.wled_ip}")
  1402. return {"success": True, "wled_ip": state.wled_ip}
  1403. @app.get("/get_wled_ip")
  1404. async def get_wled_ip():
  1405. """Legacy endpoint for backward compatibility"""
  1406. if not state.wled_ip:
  1407. raise HTTPException(status_code=404, detail="No WLED IP set")
  1408. return {"success": True, "wled_ip": state.wled_ip}
  1409. @app.post("/set_led_config", deprecated=True, tags=["settings-deprecated"])
  1410. async def set_led_config(request: LEDConfigRequest):
  1411. """DEPRECATED: Use PATCH /api/settings instead. Configure LED provider (WLED, DW LEDs, or none)"""
  1412. if request.provider not in ["wled", "dw_leds", "none"]:
  1413. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'wled', 'dw_leds', or 'none'")
  1414. state.led_provider = request.provider
  1415. if request.provider == "wled":
  1416. if not request.ip_address:
  1417. raise HTTPException(status_code=400, detail="IP address required for WLED")
  1418. state.wled_ip = request.ip_address
  1419. state.led_controller = LEDInterface("wled", request.ip_address)
  1420. logger.info(f"LED provider set to WLED at {request.ip_address}")
  1421. elif request.provider == "dw_leds":
  1422. # Check if hardware settings changed (requires restart)
  1423. old_gpio_pin = state.dw_led_gpio_pin
  1424. old_pixel_order = state.dw_led_pixel_order
  1425. hardware_changed = (
  1426. old_gpio_pin != (request.gpio_pin or 12) or
  1427. old_pixel_order != (request.pixel_order or "GRB")
  1428. )
  1429. # Stop existing DW LED controller if hardware settings changed
  1430. if hardware_changed and state.led_controller and state.led_provider == "dw_leds":
  1431. logger.info("Hardware settings changed, stopping existing LED controller...")
  1432. controller = state.led_controller.get_controller()
  1433. if controller and hasattr(controller, 'stop'):
  1434. try:
  1435. controller.stop()
  1436. logger.info("LED controller stopped successfully")
  1437. except Exception as e:
  1438. logger.error(f"Error stopping LED controller: {e}")
  1439. state.dw_led_num_leds = request.num_leds or 60
  1440. state.dw_led_gpio_pin = request.gpio_pin or 12
  1441. state.dw_led_pixel_order = request.pixel_order or "GRB"
  1442. state.dw_led_brightness = request.brightness or 35
  1443. state.wled_ip = None
  1444. # Create new LED controller with updated settings
  1445. state.led_controller = LEDInterface(
  1446. "dw_leds",
  1447. num_leds=state.dw_led_num_leds,
  1448. gpio_pin=state.dw_led_gpio_pin,
  1449. pixel_order=state.dw_led_pixel_order,
  1450. brightness=state.dw_led_brightness / 100.0,
  1451. speed=state.dw_led_speed,
  1452. intensity=state.dw_led_intensity
  1453. )
  1454. restart_msg = " (restarted)" if hardware_changed else ""
  1455. 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}")
  1456. # Check if initialization succeeded by checking status
  1457. status = state.led_controller.check_status()
  1458. if not status.get("connected", False) and status.get("error"):
  1459. error_msg = status["error"]
  1460. logger.warning(f"DW LED initialization failed: {error_msg}, but configuration saved for testing")
  1461. state.led_controller = None
  1462. # Keep the provider setting for testing purposes
  1463. # state.led_provider remains "dw_leds" so settings can be saved/tested
  1464. # Save state even with error
  1465. state.save()
  1466. # Return success with warning instead of error
  1467. return {
  1468. "success": True,
  1469. "warning": error_msg,
  1470. "hardware_available": False,
  1471. "provider": state.led_provider,
  1472. "dw_led_num_leds": state.dw_led_num_leds,
  1473. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1474. "dw_led_pixel_order": state.dw_led_pixel_order,
  1475. "dw_led_brightness": state.dw_led_brightness
  1476. }
  1477. else: # none
  1478. state.wled_ip = None
  1479. state.led_controller = None
  1480. logger.info("LED provider disabled")
  1481. # Show idle effect if controller is configured
  1482. if state.led_controller:
  1483. state.led_controller.effect_idle()
  1484. _start_idle_led_timeout()
  1485. state.save()
  1486. return {
  1487. "success": True,
  1488. "provider": state.led_provider,
  1489. "wled_ip": state.wled_ip,
  1490. "dw_led_num_leds": state.dw_led_num_leds,
  1491. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1492. "dw_led_brightness": state.dw_led_brightness
  1493. }
  1494. @app.get("/get_led_config", deprecated=True, tags=["settings-deprecated"])
  1495. async def get_led_config():
  1496. """DEPRECATED: Use GET /api/settings instead. Get current LED provider configuration"""
  1497. # Auto-detect provider for backward compatibility with existing installations
  1498. provider = state.led_provider
  1499. if not provider or provider == "none":
  1500. # If no provider set but we have IPs configured, auto-detect
  1501. if state.wled_ip:
  1502. provider = "wled"
  1503. state.led_provider = "wled"
  1504. state.save()
  1505. logger.info("Auto-detected WLED provider from existing configuration")
  1506. else:
  1507. provider = "none"
  1508. return {
  1509. "success": True,
  1510. "provider": provider,
  1511. "wled_ip": state.wled_ip,
  1512. "dw_led_num_leds": state.dw_led_num_leds,
  1513. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1514. "dw_led_pixel_order": state.dw_led_pixel_order,
  1515. "dw_led_brightness": state.dw_led_brightness,
  1516. "dw_led_idle_effect": state.dw_led_idle_effect,
  1517. "dw_led_playing_effect": state.dw_led_playing_effect
  1518. }
  1519. @app.post("/skip_pattern")
  1520. async def skip_pattern():
  1521. if not state.current_playlist:
  1522. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1523. state.skip_requested = True
  1524. return {"success": True}
  1525. @app.get("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1526. async def get_custom_clear_patterns():
  1527. """Get the currently configured custom clear patterns."""
  1528. return {
  1529. "success": True,
  1530. "custom_clear_from_in": state.custom_clear_from_in,
  1531. "custom_clear_from_out": state.custom_clear_from_out
  1532. }
  1533. @app.post("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1534. async def set_custom_clear_patterns(request: dict):
  1535. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1536. try:
  1537. # Validate that the patterns exist if they're provided
  1538. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1539. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1540. if not os.path.exists(pattern_path):
  1541. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1542. state.custom_clear_from_in = request["custom_clear_from_in"]
  1543. elif "custom_clear_from_in" in request:
  1544. state.custom_clear_from_in = None
  1545. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1546. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1547. if not os.path.exists(pattern_path):
  1548. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1549. state.custom_clear_from_out = request["custom_clear_from_out"]
  1550. elif "custom_clear_from_out" in request:
  1551. state.custom_clear_from_out = None
  1552. state.save()
  1553. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1554. return {
  1555. "success": True,
  1556. "custom_clear_from_in": state.custom_clear_from_in,
  1557. "custom_clear_from_out": state.custom_clear_from_out
  1558. }
  1559. except Exception as e:
  1560. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  1561. raise HTTPException(status_code=500, detail=str(e))
  1562. @app.get("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  1563. async def get_clear_pattern_speed():
  1564. """Get the current clearing pattern speed setting."""
  1565. return {
  1566. "success": True,
  1567. "clear_pattern_speed": state.clear_pattern_speed,
  1568. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1569. }
  1570. @app.post("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  1571. async def set_clear_pattern_speed(request: dict):
  1572. """DEPRECATED: Use PATCH /api/settings instead. Set the clearing pattern speed."""
  1573. try:
  1574. # If speed is None or "none", use default behavior (state.speed)
  1575. speed_value = request.get("clear_pattern_speed")
  1576. if speed_value is None or speed_value == "none" or speed_value == "":
  1577. speed = None
  1578. else:
  1579. speed = int(speed_value)
  1580. # Validate speed range (same as regular speed limits) only if speed is not None
  1581. if speed is not None and not (50 <= speed <= 2000):
  1582. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  1583. state.clear_pattern_speed = speed
  1584. state.save()
  1585. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  1586. return {
  1587. "success": True,
  1588. "clear_pattern_speed": state.clear_pattern_speed,
  1589. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1590. }
  1591. except ValueError:
  1592. raise HTTPException(status_code=400, detail="Invalid speed value")
  1593. except Exception as e:
  1594. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  1595. raise HTTPException(status_code=500, detail=str(e))
  1596. @app.get("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  1597. async def get_app_name():
  1598. """DEPRECATED: Use GET /api/settings instead. Get current application name."""
  1599. return {"app_name": state.app_name}
  1600. @app.post("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  1601. async def set_app_name(request: dict):
  1602. """DEPRECATED: Use PATCH /api/settings instead. Update application name."""
  1603. app_name = request.get("app_name", "").strip()
  1604. if not app_name:
  1605. app_name = "Dune Weaver" # Reset to default if empty
  1606. state.app_name = app_name
  1607. state.save()
  1608. logger.info(f"Application name updated to: {app_name}")
  1609. return {"success": True, "app_name": app_name}
  1610. @app.get("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  1611. async def get_mqtt_config():
  1612. """DEPRECATED: Use GET /api/settings instead. Get current MQTT configuration.
  1613. Note: Password is not returned for security reasons.
  1614. """
  1615. from modules.mqtt import get_mqtt_handler
  1616. handler = get_mqtt_handler()
  1617. return {
  1618. "enabled": state.mqtt_enabled,
  1619. "broker": state.mqtt_broker,
  1620. "port": state.mqtt_port,
  1621. "username": state.mqtt_username,
  1622. # Password is intentionally omitted for security
  1623. "has_password": bool(state.mqtt_password),
  1624. "client_id": state.mqtt_client_id,
  1625. "discovery_prefix": state.mqtt_discovery_prefix,
  1626. "device_id": state.mqtt_device_id,
  1627. "device_name": state.mqtt_device_name,
  1628. "connected": handler.is_connected if hasattr(handler, 'is_connected') else False,
  1629. "is_mock": handler.__class__.__name__ == 'MockMQTTHandler'
  1630. }
  1631. @app.post("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  1632. async def set_mqtt_config(request: dict):
  1633. """DEPRECATED: Use PATCH /api/settings instead. Update MQTT configuration. Requires restart to take effect."""
  1634. try:
  1635. # Update state with new values
  1636. state.mqtt_enabled = request.get("enabled", False)
  1637. state.mqtt_broker = request.get("broker", "").strip()
  1638. state.mqtt_port = int(request.get("port", 1883))
  1639. state.mqtt_username = request.get("username", "").strip()
  1640. state.mqtt_password = request.get("password", "").strip()
  1641. state.mqtt_client_id = request.get("client_id", "dune_weaver").strip()
  1642. state.mqtt_discovery_prefix = request.get("discovery_prefix", "homeassistant").strip()
  1643. state.mqtt_device_id = request.get("device_id", "dune_weaver").strip()
  1644. state.mqtt_device_name = request.get("device_name", "Dune Weaver").strip()
  1645. # Validate required fields when enabled
  1646. if state.mqtt_enabled and not state.mqtt_broker:
  1647. return JSONResponse(
  1648. content={"success": False, "message": "Broker address is required when MQTT is enabled"},
  1649. status_code=400
  1650. )
  1651. state.save()
  1652. logger.info(f"MQTT configuration updated. Enabled: {state.mqtt_enabled}, Broker: {state.mqtt_broker}")
  1653. return {
  1654. "success": True,
  1655. "message": "MQTT configuration saved. Restart the application for changes to take effect.",
  1656. "requires_restart": True
  1657. }
  1658. except ValueError as e:
  1659. return JSONResponse(
  1660. content={"success": False, "message": f"Invalid value: {str(e)}"},
  1661. status_code=400
  1662. )
  1663. except Exception as e:
  1664. logger.error(f"Failed to update MQTT config: {str(e)}")
  1665. return JSONResponse(
  1666. content={"success": False, "message": str(e)},
  1667. status_code=500
  1668. )
  1669. @app.post("/api/mqtt-test")
  1670. async def test_mqtt_connection(request: dict):
  1671. """Test MQTT connection with provided settings."""
  1672. import paho.mqtt.client as mqtt_client
  1673. broker = request.get("broker", "").strip()
  1674. port = int(request.get("port", 1883))
  1675. username = request.get("username", "").strip()
  1676. password = request.get("password", "").strip()
  1677. client_id = request.get("client_id", "dune_weaver_test").strip()
  1678. if not broker:
  1679. return JSONResponse(
  1680. content={"success": False, "message": "Broker address is required"},
  1681. status_code=400
  1682. )
  1683. try:
  1684. # Create a test client
  1685. client = mqtt_client.Client(client_id=client_id + "_test")
  1686. if username:
  1687. client.username_pw_set(username, password)
  1688. # Connection result
  1689. connection_result = {"connected": False, "error": None}
  1690. def on_connect(client, userdata, flags, rc):
  1691. if rc == 0:
  1692. connection_result["connected"] = True
  1693. else:
  1694. error_messages = {
  1695. 1: "Incorrect protocol version",
  1696. 2: "Invalid client identifier",
  1697. 3: "Server unavailable",
  1698. 4: "Bad username or password",
  1699. 5: "Not authorized"
  1700. }
  1701. connection_result["error"] = error_messages.get(rc, f"Connection failed with code {rc}")
  1702. client.on_connect = on_connect
  1703. # Try to connect with timeout
  1704. client.connect_async(broker, port, keepalive=10)
  1705. client.loop_start()
  1706. # Wait for connection result (max 5 seconds)
  1707. import time
  1708. start_time = time.time()
  1709. while time.time() - start_time < 5:
  1710. if connection_result["connected"] or connection_result["error"]:
  1711. break
  1712. await asyncio.sleep(0.1)
  1713. client.loop_stop()
  1714. client.disconnect()
  1715. if connection_result["connected"]:
  1716. return {"success": True, "message": "Successfully connected to MQTT broker"}
  1717. elif connection_result["error"]:
  1718. return JSONResponse(
  1719. content={"success": False, "message": connection_result["error"]},
  1720. status_code=400
  1721. )
  1722. else:
  1723. return JSONResponse(
  1724. content={"success": False, "message": "Connection timed out. Check broker address and port."},
  1725. status_code=400
  1726. )
  1727. except Exception as e:
  1728. logger.error(f"MQTT test connection failed: {str(e)}")
  1729. return JSONResponse(
  1730. content={"success": False, "message": str(e)},
  1731. status_code=500
  1732. )
  1733. @app.post("/preview_thr_batch")
  1734. async def preview_thr_batch(request: dict):
  1735. start = time.time()
  1736. if not request.get("file_names"):
  1737. logger.warning("Batch preview request received without filenames")
  1738. raise HTTPException(status_code=400, detail="No file names provided")
  1739. file_names = request["file_names"]
  1740. if not isinstance(file_names, list):
  1741. raise HTTPException(status_code=400, detail="file_names must be a list")
  1742. headers = {
  1743. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  1744. "Content-Type": "application/json"
  1745. }
  1746. async def process_single_file(file_name):
  1747. """Process a single file and return its preview data."""
  1748. t1 = time.time()
  1749. try:
  1750. # Normalize file path for cross-platform compatibility
  1751. normalized_file_name = normalize_file_path(file_name)
  1752. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1753. # Check file existence asynchronously
  1754. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1755. if not exists:
  1756. logger.warning(f"Pattern file not found: {pattern_file_path}")
  1757. return file_name, {"error": "Pattern file not found"}
  1758. cache_path = get_cache_path(normalized_file_name)
  1759. # Check cache existence asynchronously
  1760. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1761. if not cache_exists:
  1762. logger.info(f"Cache miss for {file_name}. Generating preview...")
  1763. success = await generate_image_preview(normalized_file_name)
  1764. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1765. if not success or not cache_exists_after:
  1766. logger.error(f"Failed to generate or find preview for {file_name}")
  1767. return file_name, {"error": "Failed to generate preview"}
  1768. metadata = get_pattern_metadata(normalized_file_name)
  1769. if metadata:
  1770. first_coord_obj = metadata.get('first_coordinate')
  1771. last_coord_obj = metadata.get('last_coordinate')
  1772. else:
  1773. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  1774. # Use process pool for CPU-intensive parsing
  1775. loop = asyncio.get_event_loop()
  1776. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, pattern_file_path)
  1777. first_coord = coordinates[0] if coordinates else None
  1778. last_coord = coordinates[-1] if coordinates else None
  1779. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1780. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1781. # Read image file asynchronously
  1782. image_data = await asyncio.to_thread(lambda: open(cache_path, 'rb').read())
  1783. image_b64 = base64.b64encode(image_data).decode('utf-8')
  1784. result = {
  1785. "image_data": f"data:image/webp;base64,{image_b64}",
  1786. "first_coordinate": first_coord_obj,
  1787. "last_coordinate": last_coord_obj
  1788. }
  1789. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  1790. return file_name, result
  1791. except Exception as e:
  1792. logger.error(f"Error processing {file_name}: {str(e)}")
  1793. return file_name, {"error": str(e)}
  1794. # Process all files concurrently
  1795. tasks = [process_single_file(file_name) for file_name in file_names]
  1796. file_results = await asyncio.gather(*tasks)
  1797. # Convert results to dictionary
  1798. results = dict(file_results)
  1799. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  1800. return JSONResponse(content=results, headers=headers)
  1801. @app.get("/playlists")
  1802. async def playlists(request: Request):
  1803. logger.debug("Rendering playlists page")
  1804. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name})
  1805. @app.get("/image2sand")
  1806. async def image2sand(request: Request):
  1807. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name})
  1808. @app.get("/led")
  1809. async def led_control_page(request: Request):
  1810. return templates.TemplateResponse("led.html", {"request": request, "app_name": state.app_name})
  1811. # DW LED control endpoints
  1812. @app.get("/api/dw_leds/status")
  1813. async def dw_leds_status():
  1814. """Get DW LED controller status"""
  1815. if not state.led_controller or state.led_provider != "dw_leds":
  1816. return {"connected": False, "message": "DW LEDs not configured"}
  1817. try:
  1818. return state.led_controller.check_status()
  1819. except Exception as e:
  1820. logger.error(f"Failed to check DW LED status: {str(e)}")
  1821. return {"connected": False, "message": str(e)}
  1822. @app.post("/api/dw_leds/power")
  1823. async def dw_leds_power(request: dict):
  1824. """Control DW LED power (0=off, 1=on, 2=toggle)"""
  1825. if not state.led_controller or state.led_provider != "dw_leds":
  1826. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1827. state_value = request.get("state", 1)
  1828. if state_value not in [0, 1, 2]:
  1829. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  1830. try:
  1831. result = state.led_controller.set_power(state_value)
  1832. # Reset idle timeout when LEDs are manually powered on (only if idle timeout is enabled)
  1833. # This prevents idle timeout from immediately turning them back off
  1834. if state_value in [1, 2] and state.dw_led_idle_timeout_enabled: # Power on or toggle
  1835. state.dw_led_last_activity_time = time.time()
  1836. logger.debug(f"LED activity time reset due to manual power on")
  1837. return result
  1838. except Exception as e:
  1839. logger.error(f"Failed to set DW LED power: {str(e)}")
  1840. raise HTTPException(status_code=500, detail=str(e))
  1841. @app.post("/api/dw_leds/brightness")
  1842. async def dw_leds_brightness(request: dict):
  1843. """Set DW LED brightness (0-100)"""
  1844. if not state.led_controller or state.led_provider != "dw_leds":
  1845. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1846. value = request.get("value", 50)
  1847. if not 0 <= value <= 100:
  1848. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  1849. try:
  1850. controller = state.led_controller.get_controller()
  1851. result = controller.set_brightness(value)
  1852. # Update state if successful
  1853. if result.get("connected"):
  1854. state.dw_led_brightness = value
  1855. state.save()
  1856. return result
  1857. except Exception as e:
  1858. logger.error(f"Failed to set DW LED brightness: {str(e)}")
  1859. raise HTTPException(status_code=500, detail=str(e))
  1860. @app.post("/api/dw_leds/color")
  1861. async def dw_leds_color(request: dict):
  1862. """Set solid color (manual UI control - always powers on LEDs)"""
  1863. if not state.led_controller or state.led_provider != "dw_leds":
  1864. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1865. # Accept both formats: {"r": 255, "g": 0, "b": 0} or {"color": [255, 0, 0]}
  1866. if "color" in request:
  1867. color = request["color"]
  1868. if not isinstance(color, list) or len(color) != 3:
  1869. raise HTTPException(status_code=400, detail="Color must be [R, G, B] array")
  1870. r, g, b = color[0], color[1], color[2]
  1871. elif "r" in request and "g" in request and "b" in request:
  1872. r = request["r"]
  1873. g = request["g"]
  1874. b = request["b"]
  1875. else:
  1876. raise HTTPException(status_code=400, detail="Color must include r, g, b fields or color array")
  1877. try:
  1878. controller = state.led_controller.get_controller()
  1879. # Power on LEDs when user manually sets color via UI
  1880. controller.set_power(1)
  1881. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1882. if state.dw_led_idle_timeout_enabled:
  1883. state.dw_led_last_activity_time = time.time()
  1884. return controller.set_color(r, g, b)
  1885. except Exception as e:
  1886. logger.error(f"Failed to set DW LED color: {str(e)}")
  1887. raise HTTPException(status_code=500, detail=str(e))
  1888. @app.post("/api/dw_leds/colors")
  1889. async def dw_leds_colors(request: dict):
  1890. """Set effect colors (color1, color2, color3) - manual UI control - always powers on LEDs"""
  1891. if not state.led_controller or state.led_provider != "dw_leds":
  1892. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1893. # Parse colors from request
  1894. color1 = None
  1895. color2 = None
  1896. color3 = None
  1897. if "color1" in request:
  1898. c = request["color1"]
  1899. if isinstance(c, list) and len(c) == 3:
  1900. color1 = tuple(c)
  1901. else:
  1902. raise HTTPException(status_code=400, detail="color1 must be [R, G, B] array")
  1903. if "color2" in request:
  1904. c = request["color2"]
  1905. if isinstance(c, list) and len(c) == 3:
  1906. color2 = tuple(c)
  1907. else:
  1908. raise HTTPException(status_code=400, detail="color2 must be [R, G, B] array")
  1909. if "color3" in request:
  1910. c = request["color3"]
  1911. if isinstance(c, list) and len(c) == 3:
  1912. color3 = tuple(c)
  1913. else:
  1914. raise HTTPException(status_code=400, detail="color3 must be [R, G, B] array")
  1915. if not any([color1, color2, color3]):
  1916. raise HTTPException(status_code=400, detail="Must provide at least one color")
  1917. try:
  1918. controller = state.led_controller.get_controller()
  1919. # Power on LEDs when user manually sets colors via UI
  1920. controller.set_power(1)
  1921. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1922. if state.dw_led_idle_timeout_enabled:
  1923. state.dw_led_last_activity_time = time.time()
  1924. return controller.set_colors(color1=color1, color2=color2, color3=color3)
  1925. except Exception as e:
  1926. logger.error(f"Failed to set DW LED colors: {str(e)}")
  1927. raise HTTPException(status_code=500, detail=str(e))
  1928. @app.get("/api/dw_leds/effects")
  1929. async def dw_leds_effects():
  1930. """Get list of available effects"""
  1931. if not state.led_controller or state.led_provider != "dw_leds":
  1932. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1933. try:
  1934. controller = state.led_controller.get_controller()
  1935. effects = controller.get_effects()
  1936. # Convert tuples to lists for JSON serialization
  1937. effects_list = [[eid, name] for eid, name in effects]
  1938. return {
  1939. "success": True,
  1940. "effects": effects_list
  1941. }
  1942. except Exception as e:
  1943. logger.error(f"Failed to get DW LED effects: {str(e)}")
  1944. raise HTTPException(status_code=500, detail=str(e))
  1945. @app.get("/api/dw_leds/palettes")
  1946. async def dw_leds_palettes():
  1947. """Get list of available palettes"""
  1948. if not state.led_controller or state.led_provider != "dw_leds":
  1949. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1950. try:
  1951. controller = state.led_controller.get_controller()
  1952. palettes = controller.get_palettes()
  1953. # Convert tuples to lists for JSON serialization
  1954. palettes_list = [[pid, name] for pid, name in palettes]
  1955. return {
  1956. "success": True,
  1957. "palettes": palettes_list
  1958. }
  1959. except Exception as e:
  1960. logger.error(f"Failed to get DW LED palettes: {str(e)}")
  1961. raise HTTPException(status_code=500, detail=str(e))
  1962. @app.post("/api/dw_leds/effect")
  1963. async def dw_leds_effect(request: dict):
  1964. """Set effect by ID (manual UI control - always powers on LEDs)"""
  1965. if not state.led_controller or state.led_provider != "dw_leds":
  1966. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1967. effect_id = request.get("effect_id", 0)
  1968. speed = request.get("speed")
  1969. intensity = request.get("intensity")
  1970. try:
  1971. controller = state.led_controller.get_controller()
  1972. # Power on LEDs when user manually sets effect via UI
  1973. controller.set_power(1)
  1974. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1975. if state.dw_led_idle_timeout_enabled:
  1976. state.dw_led_last_activity_time = time.time()
  1977. return controller.set_effect(effect_id, speed=speed, intensity=intensity)
  1978. except Exception as e:
  1979. logger.error(f"Failed to set DW LED effect: {str(e)}")
  1980. raise HTTPException(status_code=500, detail=str(e))
  1981. @app.post("/api/dw_leds/palette")
  1982. async def dw_leds_palette(request: dict):
  1983. """Set palette by ID (manual UI control - always powers on LEDs)"""
  1984. if not state.led_controller or state.led_provider != "dw_leds":
  1985. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1986. palette_id = request.get("palette_id", 0)
  1987. try:
  1988. controller = state.led_controller.get_controller()
  1989. # Power on LEDs when user manually sets palette via UI
  1990. controller.set_power(1)
  1991. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1992. if state.dw_led_idle_timeout_enabled:
  1993. state.dw_led_last_activity_time = time.time()
  1994. return controller.set_palette(palette_id)
  1995. except Exception as e:
  1996. logger.error(f"Failed to set DW LED palette: {str(e)}")
  1997. raise HTTPException(status_code=500, detail=str(e))
  1998. @app.post("/api/dw_leds/speed")
  1999. async def dw_leds_speed(request: dict):
  2000. """Set effect speed (0-255)"""
  2001. if not state.led_controller or state.led_provider != "dw_leds":
  2002. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2003. value = request.get("speed", 128)
  2004. if not 0 <= value <= 255:
  2005. raise HTTPException(status_code=400, detail="Speed must be between 0 and 255")
  2006. try:
  2007. controller = state.led_controller.get_controller()
  2008. result = controller.set_speed(value)
  2009. # Save speed to state
  2010. state.dw_led_speed = value
  2011. state.save()
  2012. return result
  2013. except Exception as e:
  2014. logger.error(f"Failed to set DW LED speed: {str(e)}")
  2015. raise HTTPException(status_code=500, detail=str(e))
  2016. @app.post("/api/dw_leds/intensity")
  2017. async def dw_leds_intensity(request: dict):
  2018. """Set effect intensity (0-255)"""
  2019. if not state.led_controller or state.led_provider != "dw_leds":
  2020. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2021. value = request.get("intensity", 128)
  2022. if not 0 <= value <= 255:
  2023. raise HTTPException(status_code=400, detail="Intensity must be between 0 and 255")
  2024. try:
  2025. controller = state.led_controller.get_controller()
  2026. result = controller.set_intensity(value)
  2027. # Save intensity to state
  2028. state.dw_led_intensity = value
  2029. state.save()
  2030. return result
  2031. except Exception as e:
  2032. logger.error(f"Failed to set DW LED intensity: {str(e)}")
  2033. raise HTTPException(status_code=500, detail=str(e))
  2034. @app.post("/api/dw_leds/save_effect_settings")
  2035. async def dw_leds_save_effect_settings(request: dict):
  2036. """Save current LED settings as idle or playing effect"""
  2037. effect_type = request.get("type") # 'idle' or 'playing'
  2038. settings = {
  2039. "effect_id": request.get("effect_id"),
  2040. "palette_id": request.get("palette_id"),
  2041. "speed": request.get("speed"),
  2042. "intensity": request.get("intensity"),
  2043. "color1": request.get("color1"),
  2044. "color2": request.get("color2"),
  2045. "color3": request.get("color3")
  2046. }
  2047. if effect_type == "idle":
  2048. state.dw_led_idle_effect = settings
  2049. elif effect_type == "playing":
  2050. state.dw_led_playing_effect = settings
  2051. else:
  2052. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2053. state.save()
  2054. logger.info(f"DW LED {effect_type} effect settings saved: {settings}")
  2055. return {"success": True, "type": effect_type, "settings": settings}
  2056. @app.post("/api/dw_leds/clear_effect_settings")
  2057. async def dw_leds_clear_effect_settings(request: dict):
  2058. """Clear idle or playing effect settings"""
  2059. effect_type = request.get("type") # 'idle' or 'playing'
  2060. if effect_type == "idle":
  2061. state.dw_led_idle_effect = None
  2062. elif effect_type == "playing":
  2063. state.dw_led_playing_effect = None
  2064. else:
  2065. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2066. state.save()
  2067. logger.info(f"DW LED {effect_type} effect settings cleared")
  2068. return {"success": True, "type": effect_type}
  2069. @app.get("/api/dw_leds/get_effect_settings")
  2070. async def dw_leds_get_effect_settings():
  2071. """Get saved idle and playing effect settings"""
  2072. return {
  2073. "idle_effect": state.dw_led_idle_effect,
  2074. "playing_effect": state.dw_led_playing_effect
  2075. }
  2076. @app.post("/api/dw_leds/idle_timeout")
  2077. async def dw_leds_set_idle_timeout(request: dict):
  2078. """Configure LED idle timeout settings"""
  2079. enabled = request.get("enabled", False)
  2080. minutes = request.get("minutes", 30)
  2081. # Validate minutes (between 1 and 1440 - 24 hours)
  2082. if minutes < 1 or minutes > 1440:
  2083. raise HTTPException(status_code=400, detail="Timeout must be between 1 and 1440 minutes")
  2084. state.dw_led_idle_timeout_enabled = enabled
  2085. state.dw_led_idle_timeout_minutes = minutes
  2086. # Reset activity time when settings change
  2087. import time
  2088. state.dw_led_last_activity_time = time.time()
  2089. state.save()
  2090. logger.info(f"DW LED idle timeout configured: enabled={enabled}, minutes={minutes}")
  2091. return {
  2092. "success": True,
  2093. "enabled": enabled,
  2094. "minutes": minutes
  2095. }
  2096. @app.get("/api/dw_leds/idle_timeout")
  2097. async def dw_leds_get_idle_timeout():
  2098. """Get LED idle timeout settings"""
  2099. import time
  2100. # Calculate remaining time if timeout is active
  2101. remaining_minutes = None
  2102. if state.dw_led_idle_timeout_enabled and state.dw_led_last_activity_time:
  2103. elapsed_seconds = time.time() - state.dw_led_last_activity_time
  2104. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  2105. remaining_seconds = max(0, timeout_seconds - elapsed_seconds)
  2106. remaining_minutes = round(remaining_seconds / 60, 1)
  2107. return {
  2108. "enabled": state.dw_led_idle_timeout_enabled,
  2109. "minutes": state.dw_led_idle_timeout_minutes,
  2110. "remaining_minutes": remaining_minutes
  2111. }
  2112. @app.get("/table_control")
  2113. async def table_control(request: Request):
  2114. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name})
  2115. @app.get("/cache-progress")
  2116. async def get_cache_progress_endpoint():
  2117. """Get the current cache generation progress."""
  2118. from modules.core.cache_manager import get_cache_progress
  2119. return get_cache_progress()
  2120. @app.post("/rebuild_cache")
  2121. async def rebuild_cache_endpoint():
  2122. """Trigger a rebuild of the pattern cache."""
  2123. try:
  2124. from modules.core.cache_manager import rebuild_cache
  2125. await rebuild_cache()
  2126. return {"success": True, "message": "Cache rebuild completed successfully"}
  2127. except Exception as e:
  2128. logger.error(f"Failed to rebuild cache: {str(e)}")
  2129. raise HTTPException(status_code=500, detail=str(e))
  2130. def signal_handler(signum, frame):
  2131. """Handle shutdown signals gracefully but forcefully."""
  2132. logger.info("Received shutdown signal, cleaning up...")
  2133. try:
  2134. # Turn off all LEDs on shutdown
  2135. if state.led_controller:
  2136. state.led_controller.set_power(0)
  2137. # Run cleanup operations - need to handle async in sync context
  2138. try:
  2139. # Try to run in existing loop if available
  2140. import asyncio
  2141. loop = asyncio.get_running_loop()
  2142. # If we're in an event loop, schedule the coroutine
  2143. import concurrent.futures
  2144. with concurrent.futures.ThreadPoolExecutor() as executor:
  2145. future = executor.submit(asyncio.run, pattern_manager.stop_actions())
  2146. future.result(timeout=5.0) # Wait up to 5 seconds
  2147. except RuntimeError:
  2148. # No running loop, create a new one
  2149. import asyncio
  2150. asyncio.run(pattern_manager.stop_actions())
  2151. except Exception as cleanup_err:
  2152. logger.error(f"Error in async cleanup: {cleanup_err}")
  2153. state.save()
  2154. logger.info("Cleanup completed")
  2155. except Exception as e:
  2156. logger.error(f"Error during cleanup: {str(e)}")
  2157. finally:
  2158. logger.info("Exiting application...")
  2159. os._exit(0) # Force exit regardless of other threads
  2160. @app.get("/api/version")
  2161. async def get_version_info(force_refresh: bool = False):
  2162. """Get current and latest version information
  2163. Args:
  2164. force_refresh: If true, bypass cache and fetch fresh data from GitHub
  2165. """
  2166. try:
  2167. version_info = await version_manager.get_version_info(force_refresh=force_refresh)
  2168. return JSONResponse(content=version_info)
  2169. except Exception as e:
  2170. logger.error(f"Error getting version info: {e}")
  2171. return JSONResponse(
  2172. content={
  2173. "current": await version_manager.get_current_version(),
  2174. "latest": await version_manager.get_current_version(),
  2175. "update_available": False,
  2176. "error": "Unable to check for updates"
  2177. },
  2178. status_code=200
  2179. )
  2180. @app.post("/api/update")
  2181. async def trigger_update():
  2182. """Trigger software update (placeholder for future implementation)"""
  2183. try:
  2184. # For now, just return the GitHub release URL
  2185. version_info = await version_manager.get_version_info()
  2186. if version_info.get("latest_release"):
  2187. return JSONResponse(content={
  2188. "success": False,
  2189. "message": "Automatic updates not implemented yet",
  2190. "manual_update_url": version_info["latest_release"].get("html_url"),
  2191. "instructions": "Please visit the GitHub release page to download and install the update manually"
  2192. })
  2193. else:
  2194. return JSONResponse(content={
  2195. "success": False,
  2196. "message": "No updates available"
  2197. })
  2198. except Exception as e:
  2199. logger.error(f"Error triggering update: {e}")
  2200. return JSONResponse(
  2201. content={"success": False, "message": "Failed to check for updates"},
  2202. status_code=500
  2203. )
  2204. @app.post("/api/system/shutdown")
  2205. async def shutdown_system():
  2206. """Shutdown the system"""
  2207. try:
  2208. logger.warning("Shutdown initiated via API")
  2209. # Schedule shutdown command after a short delay to allow response to be sent
  2210. def delayed_shutdown():
  2211. time.sleep(2) # Give time for response to be sent
  2212. try:
  2213. # Use systemctl to shutdown the host (via mounted systemd socket)
  2214. subprocess.run(["systemctl", "poweroff"], check=True)
  2215. logger.info("Host shutdown command executed successfully via systemctl")
  2216. except FileNotFoundError:
  2217. logger.error("systemctl command not found - ensure systemd volumes are mounted")
  2218. except Exception as e:
  2219. logger.error(f"Error executing host shutdown command: {e}")
  2220. import threading
  2221. shutdown_thread = threading.Thread(target=delayed_shutdown)
  2222. shutdown_thread.start()
  2223. return {"success": True, "message": "System shutdown initiated"}
  2224. except Exception as e:
  2225. logger.error(f"Error initiating shutdown: {e}")
  2226. return JSONResponse(
  2227. content={"success": False, "message": str(e)},
  2228. status_code=500
  2229. )
  2230. @app.post("/api/system/restart")
  2231. async def restart_system():
  2232. """Restart the Docker containers using docker compose"""
  2233. try:
  2234. logger.warning("Restart initiated via API")
  2235. # Schedule restart command after a short delay to allow response to be sent
  2236. def delayed_restart():
  2237. time.sleep(2) # Give time for response to be sent
  2238. try:
  2239. # Use docker compose restart to restart the containers
  2240. subprocess.run(["docker", "compose", "restart"], check=True)
  2241. logger.info("Docker compose restart command executed successfully")
  2242. except FileNotFoundError:
  2243. logger.error("docker command not found")
  2244. except Exception as e:
  2245. logger.error(f"Error executing docker compose restart: {e}")
  2246. import threading
  2247. restart_thread = threading.Thread(target=delayed_restart)
  2248. restart_thread.start()
  2249. return {"success": True, "message": "System restart initiated"}
  2250. except Exception as e:
  2251. logger.error(f"Error initiating restart: {e}")
  2252. return JSONResponse(
  2253. content={"success": False, "message": str(e)},
  2254. status_code=500
  2255. )
  2256. def entrypoint():
  2257. import uvicorn
  2258. logger.info("Starting FastAPI server on port 8080...")
  2259. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  2260. if __name__ == "__main__":
  2261. entrypoint()