main.py 108 KB

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