main.py 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183
  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.middleware.cors import CORSMiddleware
  5. from fastapi.templating import Jinja2Templates
  6. from pydantic import BaseModel
  7. from typing import List, Optional, Tuple, Dict, Any, Union
  8. import atexit
  9. import os
  10. import logging
  11. from datetime import datetime, time
  12. from modules.connection import connection_manager
  13. from modules.core import pattern_manager
  14. from modules.core.pattern_manager import parse_theta_rho_file, THETA_RHO_DIR
  15. from modules.core import playlist_manager
  16. from modules.update import update_manager
  17. from modules.core.state import state
  18. from modules import mqtt
  19. import signal
  20. import sys
  21. import asyncio
  22. from contextlib import asynccontextmanager
  23. from modules.led.led_controller import LEDController, effect_idle
  24. from modules.led.led_interface import LEDInterface
  25. from modules.led.idle_timeout_manager import idle_timeout_manager
  26. import math
  27. from modules.core.cache_manager import generate_all_image_previews, get_cache_path, generate_image_preview, get_pattern_metadata
  28. from modules.core.version_manager import version_manager
  29. from modules.core.log_handler import init_memory_handler, get_memory_handler
  30. import json
  31. import base64
  32. import time
  33. import argparse
  34. import subprocess
  35. import platform
  36. from modules.core import process_pool as pool_module
  37. # Get log level from environment variable, default to INFO
  38. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  39. log_level = getattr(logging, log_level_str, logging.INFO)
  40. logging.basicConfig(
  41. level=log_level,
  42. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  43. handlers=[
  44. logging.StreamHandler(),
  45. ]
  46. )
  47. # Initialize memory log handler for web UI log viewer
  48. init_memory_handler(max_entries=500)
  49. logger = logging.getLogger(__name__)
  50. async def _check_table_is_idle() -> bool:
  51. """Helper function to check if table is idle."""
  52. return not state.current_playing_file or state.pause_requested
  53. def _start_idle_led_timeout():
  54. """Start idle LED timeout if enabled."""
  55. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  56. return
  57. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  58. idle_timeout_manager.start_idle_timeout(
  59. timeout_minutes=state.dw_led_idle_timeout_minutes,
  60. state=state,
  61. check_idle_callback=_check_table_is_idle
  62. )
  63. def check_homing_in_progress():
  64. """Check if homing is in progress and raise exception if so."""
  65. if state.is_homing:
  66. raise HTTPException(status_code=409, detail="Cannot perform this action while homing is in progress")
  67. def normalize_file_path(file_path: str) -> str:
  68. """Normalize file path separators for consistent cross-platform handling."""
  69. if not file_path:
  70. return ''
  71. # First normalize path separators
  72. normalized = file_path.replace('\\', '/')
  73. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  74. if normalized.startswith('./patterns/'):
  75. normalized = normalized[11:]
  76. elif normalized.startswith('patterns/'):
  77. normalized = normalized[9:]
  78. return normalized
  79. @asynccontextmanager
  80. async def lifespan(app: FastAPI):
  81. # Startup
  82. logger.info("Starting Dune Weaver application...")
  83. # Register signal handlers
  84. signal.signal(signal.SIGINT, signal_handler)
  85. signal.signal(signal.SIGTERM, signal_handler)
  86. # Initialize shared process pool for CPU-intensive tasks
  87. pool_module.init_pool()
  88. # Pin main process to CPUs 1-N to keep CPU 0 dedicated to motion/LED
  89. from modules.core import scheduling
  90. background_cpus = scheduling.get_background_cpus()
  91. if background_cpus:
  92. scheduling.pin_to_cpus(background_cpus)
  93. logger.info(f"FastAPI main process pinned to CPUs {sorted(background_cpus)}")
  94. else:
  95. logger.info("Single-core system detected, skipping CPU pinning")
  96. # Connect device in background so the web server starts immediately
  97. async def connect_and_home():
  98. """Connect to device and perform homing in background."""
  99. try:
  100. # Connect without homing first (fast)
  101. await asyncio.to_thread(connection_manager.connect_device, False)
  102. # If connected, perform homing in background
  103. if state.conn and state.conn.is_connected():
  104. logger.info("Device connected, starting homing in background...")
  105. state.is_homing = True
  106. try:
  107. success = await asyncio.to_thread(connection_manager.home)
  108. if not success:
  109. logger.warning("Background homing failed or was skipped")
  110. finally:
  111. state.is_homing = False
  112. logger.info("Background homing completed")
  113. # After homing, check for auto_play mode
  114. if state.auto_play_enabled and state.auto_play_playlist:
  115. logger.info(f"Homing complete, checking auto_play playlist: {state.auto_play_playlist}")
  116. try:
  117. playlist_exists = playlist_manager.get_playlist(state.auto_play_playlist) is not None
  118. if not playlist_exists:
  119. logger.warning(f"Auto-play playlist '{state.auto_play_playlist}' not found. Clearing invalid reference.")
  120. state.auto_play_playlist = None
  121. state.save()
  122. elif state.conn and state.conn.is_connected():
  123. logger.info(f"Starting auto-play playlist: {state.auto_play_playlist}")
  124. asyncio.create_task(playlist_manager.run_playlist(
  125. state.auto_play_playlist,
  126. pause_time=state.auto_play_pause_time,
  127. clear_pattern=state.auto_play_clear_pattern,
  128. run_mode=state.auto_play_run_mode,
  129. shuffle=state.auto_play_shuffle
  130. ))
  131. except Exception as e:
  132. logger.error(f"Failed to auto-play playlist: {str(e)}")
  133. except Exception as e:
  134. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  135. # Start connection/homing in background - doesn't block server startup
  136. asyncio.create_task(connect_and_home())
  137. # Initialize LED controller based on saved configuration
  138. try:
  139. # Auto-detect provider for backward compatibility with existing installations
  140. if not state.led_provider or state.led_provider == "none":
  141. if state.wled_ip:
  142. state.led_provider = "wled"
  143. logger.info("Auto-detected WLED provider from existing configuration")
  144. # Initialize the appropriate controller
  145. if state.led_provider == "wled" and state.wled_ip:
  146. state.led_controller = LEDInterface("wled", state.wled_ip)
  147. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  148. elif state.led_provider == "dw_leds":
  149. state.led_controller = LEDInterface(
  150. "dw_leds",
  151. num_leds=state.dw_led_num_leds,
  152. gpio_pin=state.dw_led_gpio_pin,
  153. pixel_order=state.dw_led_pixel_order,
  154. brightness=state.dw_led_brightness / 100.0,
  155. speed=state.dw_led_speed,
  156. intensity=state.dw_led_intensity
  157. )
  158. 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})")
  159. # Initialize hardware and start idle effect (matches behavior of /set_led_config)
  160. status = state.led_controller.check_status()
  161. if status.get("connected", False):
  162. state.led_controller.effect_idle(state.dw_led_idle_effect)
  163. _start_idle_led_timeout()
  164. logger.info("DW LEDs hardware initialized and idle effect started")
  165. else:
  166. error_msg = status.get("error", "Unknown error")
  167. logger.warning(f"DW LED hardware initialization failed: {error_msg}")
  168. else:
  169. state.led_controller = None
  170. logger.info("LED controller not configured")
  171. # Save if provider was auto-detected
  172. if state.led_provider and state.wled_ip:
  173. state.save()
  174. except Exception as e:
  175. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  176. state.led_controller = None
  177. # Note: auto_play is now handled in connect_and_home() after homing completes
  178. try:
  179. mqtt_handler = mqtt.init_mqtt()
  180. except Exception as e:
  181. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  182. # Schedule cache generation check for later (non-blocking startup)
  183. async def delayed_cache_check():
  184. """Check and generate cache in background."""
  185. try:
  186. logger.info("Starting cache check...")
  187. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  188. if await is_cache_generation_needed_async():
  189. logger.info("Cache generation needed, starting background task...")
  190. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  191. else:
  192. logger.info("Cache is up to date, skipping generation")
  193. except Exception as e:
  194. logger.warning(f"Failed during cache generation: {str(e)}")
  195. # Start cache check in background immediately
  196. asyncio.create_task(delayed_cache_check())
  197. # Start idle timeout monitor
  198. async def idle_timeout_monitor():
  199. """Monitor LED idle timeout and turn off LEDs when timeout expires."""
  200. import time
  201. while True:
  202. try:
  203. await asyncio.sleep(30) # Check every 30 seconds
  204. if not state.dw_led_idle_timeout_enabled:
  205. continue
  206. if not state.led_controller or not state.led_controller.is_configured:
  207. continue
  208. # Check if we're currently playing a pattern
  209. is_playing = bool(state.current_playing_file or state.current_playlist)
  210. if is_playing:
  211. # Reset activity time when playing
  212. state.dw_led_last_activity_time = time.time()
  213. continue
  214. # If no activity time set, initialize it
  215. if state.dw_led_last_activity_time is None:
  216. state.dw_led_last_activity_time = time.time()
  217. continue
  218. # Calculate idle duration
  219. idle_seconds = time.time() - state.dw_led_last_activity_time
  220. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  221. # Turn off LEDs if timeout expired
  222. if idle_seconds >= timeout_seconds:
  223. status = state.led_controller.check_status()
  224. # Check both "power" (WLED) and "power_on" (DW LEDs) keys
  225. is_powered_on = status.get("power", False) or status.get("power_on", False)
  226. if is_powered_on: # Only turn off if currently on
  227. logger.info(f"Idle timeout ({state.dw_led_idle_timeout_minutes} minutes) expired, turning off LEDs")
  228. state.led_controller.set_power(0)
  229. # Reset activity time to prevent repeated turn-off attempts
  230. state.dw_led_last_activity_time = time.time()
  231. except Exception as e:
  232. logger.error(f"Error in idle timeout monitor: {e}")
  233. await asyncio.sleep(60) # Wait longer on error
  234. asyncio.create_task(idle_timeout_monitor())
  235. yield # This separates startup from shutdown code
  236. # Shutdown
  237. logger.info("Shutting down Dune Weaver application...")
  238. # Shutdown process pool
  239. pool_module.shutdown_pool(wait=True)
  240. app = FastAPI(lifespan=lifespan)
  241. # Add CORS middleware to allow cross-origin requests from other Dune Weaver frontends
  242. # This enables multi-table control from a single frontend
  243. app.add_middleware(
  244. CORSMiddleware,
  245. allow_origins=["*"], # Allow all origins for local network access
  246. allow_credentials=True,
  247. allow_methods=["*"],
  248. allow_headers=["*"],
  249. )
  250. templates = Jinja2Templates(directory="templates")
  251. app.mount("/static", StaticFiles(directory="static"), name="static")
  252. # Global semaphore to limit concurrent preview processing
  253. # Prevents resource exhaustion when loading many previews simultaneously
  254. preview_semaphore = asyncio.Semaphore(5)
  255. # Pydantic models for request/response validation
  256. class ConnectRequest(BaseModel):
  257. port: Optional[str] = None
  258. class auto_playModeRequest(BaseModel):
  259. enabled: bool
  260. playlist: Optional[str] = None
  261. run_mode: Optional[str] = "loop"
  262. pause_time: Optional[float] = 5.0
  263. clear_pattern: Optional[str] = "adaptive"
  264. shuffle: Optional[bool] = False
  265. class TimeSlot(BaseModel):
  266. start_time: str # HH:MM format
  267. end_time: str # HH:MM format
  268. days: str # "daily", "weekdays", "weekends", or "custom"
  269. custom_days: Optional[List[str]] = [] # ["monday", "tuesday", etc.]
  270. class ScheduledPauseRequest(BaseModel):
  271. enabled: bool
  272. control_wled: Optional[bool] = False
  273. finish_pattern: Optional[bool] = False # Finish current pattern before pausing
  274. timezone: Optional[str] = None # IANA timezone or None for system default
  275. time_slots: List[TimeSlot] = []
  276. class CoordinateRequest(BaseModel):
  277. theta: float
  278. rho: float
  279. class PlaylistRequest(BaseModel):
  280. playlist_name: str
  281. files: List[str] = []
  282. pause_time: float = 0
  283. clear_pattern: Optional[str] = None
  284. run_mode: str = "single"
  285. shuffle: bool = False
  286. class PlaylistRunRequest(BaseModel):
  287. playlist_name: str
  288. pause_time: Optional[float] = 0
  289. clear_pattern: Optional[str] = None
  290. run_mode: Optional[str] = "single"
  291. shuffle: Optional[bool] = False
  292. start_time: Optional[str] = None
  293. end_time: Optional[str] = None
  294. class SpeedRequest(BaseModel):
  295. speed: float
  296. class WLEDRequest(BaseModel):
  297. wled_ip: Optional[str] = None
  298. class LEDConfigRequest(BaseModel):
  299. provider: str # "wled", "dw_leds", or "none"
  300. ip_address: Optional[str] = None # For WLED only
  301. # DW LED specific fields
  302. num_leds: Optional[int] = None
  303. gpio_pin: Optional[int] = None
  304. pixel_order: Optional[str] = None
  305. brightness: Optional[int] = None
  306. class DeletePlaylistRequest(BaseModel):
  307. playlist_name: str
  308. class RenamePlaylistRequest(BaseModel):
  309. old_name: str
  310. new_name: str
  311. class ThetaRhoRequest(BaseModel):
  312. file_name: str
  313. pre_execution: Optional[str] = "none"
  314. class GetCoordinatesRequest(BaseModel):
  315. file_name: str
  316. # ============================================================================
  317. # Unified Settings Models
  318. # ============================================================================
  319. class AppSettingsUpdate(BaseModel):
  320. name: Optional[str] = None
  321. custom_logo: Optional[str] = None # Filename or empty string to clear (favicon auto-generated)
  322. class ConnectionSettingsUpdate(BaseModel):
  323. preferred_port: Optional[str] = None
  324. class PatternSettingsUpdate(BaseModel):
  325. clear_pattern_speed: Optional[int] = None
  326. custom_clear_from_in: Optional[str] = None
  327. custom_clear_from_out: Optional[str] = None
  328. class AutoPlaySettingsUpdate(BaseModel):
  329. enabled: Optional[bool] = None
  330. playlist: Optional[str] = None
  331. run_mode: Optional[str] = None
  332. pause_time: Optional[float] = None
  333. clear_pattern: Optional[str] = None
  334. shuffle: Optional[bool] = None
  335. class ScheduledPauseSettingsUpdate(BaseModel):
  336. enabled: Optional[bool] = None
  337. control_wled: Optional[bool] = None
  338. finish_pattern: Optional[bool] = None
  339. timezone: Optional[str] = None # IANA timezone (e.g., "America/New_York") or None for system default
  340. time_slots: Optional[List[TimeSlot]] = None
  341. class HomingSettingsUpdate(BaseModel):
  342. mode: Optional[int] = None
  343. angular_offset_degrees: Optional[float] = None
  344. auto_home_enabled: Optional[bool] = None
  345. auto_home_after_patterns: Optional[int] = None
  346. class DwLedSettingsUpdate(BaseModel):
  347. num_leds: Optional[int] = None
  348. gpio_pin: Optional[int] = None
  349. pixel_order: Optional[str] = None
  350. brightness: Optional[int] = None
  351. speed: Optional[int] = None
  352. intensity: Optional[int] = None
  353. idle_effect: Optional[dict] = None
  354. playing_effect: Optional[dict] = None
  355. idle_timeout_enabled: Optional[bool] = None
  356. idle_timeout_minutes: Optional[int] = None
  357. class LedSettingsUpdate(BaseModel):
  358. provider: Optional[str] = None # "none", "wled", "dw_leds"
  359. wled_ip: Optional[str] = None
  360. dw_led: Optional[DwLedSettingsUpdate] = None
  361. class MqttSettingsUpdate(BaseModel):
  362. enabled: Optional[bool] = None
  363. broker: Optional[str] = None
  364. port: Optional[int] = None
  365. username: Optional[str] = None
  366. password: Optional[str] = None # Write-only, never returned in GET
  367. client_id: Optional[str] = None
  368. discovery_prefix: Optional[str] = None
  369. device_id: Optional[str] = None
  370. device_name: Optional[str] = None
  371. class MachineSettingsUpdate(BaseModel):
  372. table_type_override: Optional[str] = None # Override detected table type, or empty string/"auto" to clear
  373. timezone: Optional[str] = None # IANA timezone (e.g., "America/New_York", "UTC")
  374. class SettingsUpdate(BaseModel):
  375. """Request model for PATCH /api/settings - all fields optional for partial updates"""
  376. app: Optional[AppSettingsUpdate] = None
  377. connection: Optional[ConnectionSettingsUpdate] = None
  378. patterns: Optional[PatternSettingsUpdate] = None
  379. auto_play: Optional[AutoPlaySettingsUpdate] = None
  380. scheduled_pause: Optional[ScheduledPauseSettingsUpdate] = None
  381. homing: Optional[HomingSettingsUpdate] = None
  382. led: Optional[LedSettingsUpdate] = None
  383. mqtt: Optional[MqttSettingsUpdate] = None
  384. machine: Optional[MachineSettingsUpdate] = None
  385. # Store active WebSocket connections
  386. active_status_connections = set()
  387. active_cache_progress_connections = set()
  388. @app.websocket("/ws/status")
  389. async def websocket_status_endpoint(websocket: WebSocket):
  390. await websocket.accept()
  391. active_status_connections.add(websocket)
  392. try:
  393. while True:
  394. status = pattern_manager.get_status()
  395. try:
  396. await websocket.send_json({
  397. "type": "status_update",
  398. "data": status
  399. })
  400. except RuntimeError as e:
  401. if "close message has been sent" in str(e):
  402. break
  403. raise
  404. await asyncio.sleep(1)
  405. except WebSocketDisconnect:
  406. pass
  407. finally:
  408. active_status_connections.discard(websocket)
  409. try:
  410. await websocket.close()
  411. except RuntimeError:
  412. pass
  413. async def broadcast_status_update(status: dict):
  414. """Broadcast status update to all connected clients."""
  415. disconnected = set()
  416. for websocket in active_status_connections:
  417. try:
  418. await websocket.send_json({
  419. "type": "status_update",
  420. "data": status
  421. })
  422. except WebSocketDisconnect:
  423. disconnected.add(websocket)
  424. except RuntimeError:
  425. disconnected.add(websocket)
  426. active_status_connections.difference_update(disconnected)
  427. @app.websocket("/ws/cache-progress")
  428. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  429. from modules.core.cache_manager import get_cache_progress
  430. await websocket.accept()
  431. active_cache_progress_connections.add(websocket)
  432. try:
  433. while True:
  434. progress = get_cache_progress()
  435. try:
  436. await websocket.send_json({
  437. "type": "cache_progress",
  438. "data": progress
  439. })
  440. except RuntimeError as e:
  441. if "close message has been sent" in str(e):
  442. break
  443. raise
  444. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  445. except WebSocketDisconnect:
  446. pass
  447. finally:
  448. active_cache_progress_connections.discard(websocket)
  449. try:
  450. await websocket.close()
  451. except RuntimeError:
  452. pass
  453. # WebSocket endpoint for real-time log streaming
  454. @app.websocket("/ws/logs")
  455. async def websocket_logs_endpoint(websocket: WebSocket):
  456. """Stream application logs in real-time via WebSocket."""
  457. await websocket.accept()
  458. handler = get_memory_handler()
  459. if not handler:
  460. await websocket.close()
  461. return
  462. # Subscribe to log updates
  463. log_queue = handler.subscribe()
  464. try:
  465. while True:
  466. try:
  467. # Wait for new log entry with timeout
  468. log_entry = await asyncio.wait_for(log_queue.get(), timeout=30.0)
  469. await websocket.send_json({
  470. "type": "log_entry",
  471. "data": log_entry
  472. })
  473. except asyncio.TimeoutError:
  474. # Send heartbeat to keep connection alive
  475. await websocket.send_json({"type": "heartbeat"})
  476. except RuntimeError as e:
  477. if "close message has been sent" in str(e):
  478. break
  479. raise
  480. except WebSocketDisconnect:
  481. pass
  482. finally:
  483. handler.unsubscribe(log_queue)
  484. try:
  485. await websocket.close()
  486. except RuntimeError:
  487. pass
  488. # API endpoint to retrieve logs
  489. @app.get("/api/logs", tags=["logs"])
  490. async def get_logs(limit: int = 100, level: str = None):
  491. """
  492. Retrieve application logs from memory buffer.
  493. Args:
  494. limit: Maximum number of log entries to return (default: 100, max: 500)
  495. level: Filter by log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  496. Returns:
  497. List of log entries with timestamp, level, logger, and message.
  498. """
  499. handler = get_memory_handler()
  500. if not handler:
  501. return {"logs": [], "error": "Log handler not initialized"}
  502. # Clamp limit to reasonable range
  503. limit = max(1, min(limit, 500))
  504. logs = handler.get_logs(limit=limit, level=level)
  505. return {"logs": logs, "count": len(logs)}
  506. @app.delete("/api/logs", tags=["logs"])
  507. async def clear_logs():
  508. """Clear all logs from the memory buffer."""
  509. handler = get_memory_handler()
  510. if handler:
  511. handler.clear()
  512. return {"status": "ok", "message": "Logs cleared"}
  513. # FastAPI routes - Redirect old frontend routes to new React frontend on port 80
  514. def get_redirect_response(request: Request):
  515. """Return redirect page pointing users to the new frontend."""
  516. host = request.headers.get("host", "localhost").split(":")[0] # Remove port if present
  517. return templates.TemplateResponse("redirect.html", {"request": request, "host": host})
  518. @app.get("/")
  519. async def index(request: Request):
  520. return get_redirect_response(request)
  521. @app.get("/settings")
  522. async def settings_page(request: Request):
  523. return get_redirect_response(request)
  524. # ============================================================================
  525. # Unified Settings API
  526. # ============================================================================
  527. @app.get("/api/settings", tags=["settings"])
  528. async def get_all_settings():
  529. """
  530. Get all application settings in a unified structure.
  531. This endpoint consolidates multiple settings endpoints into a single response.
  532. Individual settings endpoints are deprecated but still functional.
  533. """
  534. return {
  535. "app": {
  536. "name": state.app_name,
  537. "custom_logo": state.custom_logo
  538. },
  539. "connection": {
  540. "preferred_port": state.preferred_port
  541. },
  542. "patterns": {
  543. "clear_pattern_speed": state.clear_pattern_speed,
  544. "custom_clear_from_in": state.custom_clear_from_in,
  545. "custom_clear_from_out": state.custom_clear_from_out
  546. },
  547. "auto_play": {
  548. "enabled": state.auto_play_enabled,
  549. "playlist": state.auto_play_playlist,
  550. "run_mode": state.auto_play_run_mode,
  551. "pause_time": state.auto_play_pause_time,
  552. "clear_pattern": state.auto_play_clear_pattern,
  553. "shuffle": state.auto_play_shuffle
  554. },
  555. "scheduled_pause": {
  556. "enabled": state.scheduled_pause_enabled,
  557. "control_wled": state.scheduled_pause_control_wled,
  558. "finish_pattern": state.scheduled_pause_finish_pattern,
  559. "timezone": state.scheduled_pause_timezone,
  560. "time_slots": state.scheduled_pause_time_slots
  561. },
  562. "homing": {
  563. "mode": state.homing,
  564. "user_override": state.homing_user_override, # True if user explicitly set, False if auto-detected
  565. "angular_offset_degrees": state.angular_homing_offset_degrees,
  566. "auto_home_enabled": state.auto_home_enabled,
  567. "auto_home_after_patterns": state.auto_home_after_patterns
  568. },
  569. "led": {
  570. "provider": state.led_provider,
  571. "wled_ip": state.wled_ip,
  572. "dw_led": {
  573. "num_leds": state.dw_led_num_leds,
  574. "gpio_pin": state.dw_led_gpio_pin,
  575. "pixel_order": state.dw_led_pixel_order,
  576. "brightness": state.dw_led_brightness,
  577. "speed": state.dw_led_speed,
  578. "intensity": state.dw_led_intensity,
  579. "idle_effect": state.dw_led_idle_effect,
  580. "playing_effect": state.dw_led_playing_effect,
  581. "idle_timeout_enabled": state.dw_led_idle_timeout_enabled,
  582. "idle_timeout_minutes": state.dw_led_idle_timeout_minutes
  583. }
  584. },
  585. "mqtt": {
  586. "enabled": state.mqtt_enabled,
  587. "broker": state.mqtt_broker,
  588. "port": state.mqtt_port,
  589. "username": state.mqtt_username,
  590. "has_password": bool(state.mqtt_password),
  591. "client_id": state.mqtt_client_id,
  592. "discovery_prefix": state.mqtt_discovery_prefix,
  593. "device_id": state.mqtt_device_id,
  594. "device_name": state.mqtt_device_name
  595. },
  596. "machine": {
  597. "detected_table_type": state.table_type,
  598. "table_type_override": state.table_type_override,
  599. "effective_table_type": state.table_type_override or state.table_type,
  600. "gear_ratio": state.gear_ratio,
  601. "x_steps_per_mm": state.x_steps_per_mm,
  602. "y_steps_per_mm": state.y_steps_per_mm,
  603. "timezone": state.timezone,
  604. "available_table_types": [
  605. {"value": "dune_weaver_mini", "label": "Dune Weaver Mini"},
  606. {"value": "dune_weaver_mini_pro", "label": "Dune Weaver Mini Pro"},
  607. {"value": "dune_weaver_mini_pro_byj", "label": "Dune Weaver Mini Pro (BYJ)"},
  608. {"value": "dune_weaver_gold", "label": "Dune Weaver Gold"},
  609. {"value": "dune_weaver", "label": "Dune Weaver"},
  610. {"value": "dune_weaver_pro", "label": "Dune Weaver Pro"}
  611. ]
  612. }
  613. }
  614. @app.patch("/api/settings", tags=["settings"])
  615. async def update_settings(settings_update: SettingsUpdate):
  616. """
  617. Partially update application settings.
  618. Only include the categories and fields you want to update.
  619. All fields are optional - only provided values will be updated.
  620. Example: {"app": {"name": "My Sand Table"}, "auto_play": {"enabled": true}}
  621. """
  622. updated_categories = []
  623. requires_restart = False
  624. led_reinit_needed = False
  625. old_led_provider = state.led_provider
  626. # App settings
  627. if settings_update.app:
  628. if settings_update.app.name is not None:
  629. state.app_name = settings_update.app.name or "Dune Weaver"
  630. if settings_update.app.custom_logo is not None:
  631. state.custom_logo = settings_update.app.custom_logo or None
  632. updated_categories.append("app")
  633. # Connection settings
  634. if settings_update.connection:
  635. if settings_update.connection.preferred_port is not None:
  636. port = settings_update.connection.preferred_port
  637. state.preferred_port = None if port in ("", "none") else port
  638. updated_categories.append("connection")
  639. # Pattern settings
  640. if settings_update.patterns:
  641. p = settings_update.patterns
  642. if p.clear_pattern_speed is not None:
  643. state.clear_pattern_speed = p.clear_pattern_speed if p.clear_pattern_speed > 0 else None
  644. if p.custom_clear_from_in is not None:
  645. state.custom_clear_from_in = p.custom_clear_from_in or None
  646. if p.custom_clear_from_out is not None:
  647. state.custom_clear_from_out = p.custom_clear_from_out or None
  648. updated_categories.append("patterns")
  649. # Auto-play settings
  650. if settings_update.auto_play:
  651. ap = settings_update.auto_play
  652. if ap.enabled is not None:
  653. state.auto_play_enabled = ap.enabled
  654. if ap.playlist is not None:
  655. state.auto_play_playlist = ap.playlist or None
  656. if ap.run_mode is not None:
  657. state.auto_play_run_mode = ap.run_mode
  658. if ap.pause_time is not None:
  659. state.auto_play_pause_time = ap.pause_time
  660. if ap.clear_pattern is not None:
  661. state.auto_play_clear_pattern = ap.clear_pattern
  662. if ap.shuffle is not None:
  663. state.auto_play_shuffle = ap.shuffle
  664. updated_categories.append("auto_play")
  665. # Scheduled pause (Still Sands) settings
  666. if settings_update.scheduled_pause:
  667. sp = settings_update.scheduled_pause
  668. if sp.enabled is not None:
  669. state.scheduled_pause_enabled = sp.enabled
  670. if sp.control_wled is not None:
  671. state.scheduled_pause_control_wled = sp.control_wled
  672. if sp.finish_pattern is not None:
  673. state.scheduled_pause_finish_pattern = sp.finish_pattern
  674. if sp.timezone is not None:
  675. # Empty string means use system default (store as None)
  676. state.scheduled_pause_timezone = sp.timezone if sp.timezone else None
  677. # Clear cached timezone in pattern_manager so it picks up the new setting
  678. from modules.core import pattern_manager
  679. pattern_manager._cached_timezone = None
  680. pattern_manager._cached_zoneinfo = None
  681. if sp.time_slots is not None:
  682. state.scheduled_pause_time_slots = [slot.model_dump() for slot in sp.time_slots]
  683. updated_categories.append("scheduled_pause")
  684. # Homing settings
  685. if settings_update.homing:
  686. h = settings_update.homing
  687. if h.mode is not None:
  688. state.homing = h.mode
  689. state.homing_user_override = True # User explicitly set preference
  690. if h.angular_offset_degrees is not None:
  691. state.angular_homing_offset_degrees = h.angular_offset_degrees
  692. if h.auto_home_enabled is not None:
  693. state.auto_home_enabled = h.auto_home_enabled
  694. if h.auto_home_after_patterns is not None:
  695. state.auto_home_after_patterns = h.auto_home_after_patterns
  696. updated_categories.append("homing")
  697. # LED settings
  698. if settings_update.led:
  699. led = settings_update.led
  700. if led.provider is not None:
  701. state.led_provider = led.provider
  702. if led.provider != old_led_provider:
  703. led_reinit_needed = True
  704. if led.wled_ip is not None:
  705. state.wled_ip = led.wled_ip or None
  706. if led.dw_led:
  707. dw = led.dw_led
  708. if dw.num_leds is not None:
  709. state.dw_led_num_leds = dw.num_leds
  710. if dw.gpio_pin is not None:
  711. state.dw_led_gpio_pin = dw.gpio_pin
  712. if dw.pixel_order is not None:
  713. state.dw_led_pixel_order = dw.pixel_order
  714. if dw.brightness is not None:
  715. state.dw_led_brightness = dw.brightness
  716. if dw.speed is not None:
  717. state.dw_led_speed = dw.speed
  718. if dw.intensity is not None:
  719. state.dw_led_intensity = dw.intensity
  720. if dw.idle_effect is not None:
  721. state.dw_led_idle_effect = dw.idle_effect
  722. if dw.playing_effect is not None:
  723. state.dw_led_playing_effect = dw.playing_effect
  724. if dw.idle_timeout_enabled is not None:
  725. state.dw_led_idle_timeout_enabled = dw.idle_timeout_enabled
  726. if dw.idle_timeout_minutes is not None:
  727. state.dw_led_idle_timeout_minutes = dw.idle_timeout_minutes
  728. updated_categories.append("led")
  729. # MQTT settings
  730. if settings_update.mqtt:
  731. m = settings_update.mqtt
  732. if m.enabled is not None:
  733. state.mqtt_enabled = m.enabled
  734. if m.broker is not None:
  735. state.mqtt_broker = m.broker
  736. if m.port is not None:
  737. state.mqtt_port = m.port
  738. if m.username is not None:
  739. state.mqtt_username = m.username
  740. if m.password is not None:
  741. state.mqtt_password = m.password
  742. if m.client_id is not None:
  743. state.mqtt_client_id = m.client_id
  744. if m.discovery_prefix is not None:
  745. state.mqtt_discovery_prefix = m.discovery_prefix
  746. if m.device_id is not None:
  747. state.mqtt_device_id = m.device_id
  748. if m.device_name is not None:
  749. state.mqtt_device_name = m.device_name
  750. updated_categories.append("mqtt")
  751. requires_restart = True
  752. # Machine settings
  753. if settings_update.machine:
  754. m = settings_update.machine
  755. if m.table_type_override is not None:
  756. # Empty string or "auto" clears the override
  757. state.table_type_override = None if m.table_type_override in ("", "auto") else m.table_type_override
  758. if m.timezone is not None:
  759. # Validate timezone by trying to create a ZoneInfo object
  760. try:
  761. from zoneinfo import ZoneInfo
  762. except ImportError:
  763. from backports.zoneinfo import ZoneInfo
  764. try:
  765. ZoneInfo(m.timezone) # Validate
  766. state.timezone = m.timezone
  767. # Also update scheduled_pause_timezone to keep in sync
  768. state.scheduled_pause_timezone = m.timezone
  769. # Clear cached timezone in pattern_manager so it picks up the new setting
  770. from modules.core import pattern_manager
  771. pattern_manager._cached_timezone = None
  772. pattern_manager._cached_zoneinfo = None
  773. logger.info(f"Timezone updated to: {m.timezone}")
  774. except Exception as e:
  775. logger.warning(f"Invalid timezone '{m.timezone}': {e}")
  776. updated_categories.append("machine")
  777. # Save state
  778. state.save()
  779. # Handle LED reinitialization if provider changed
  780. if led_reinit_needed:
  781. logger.info(f"LED provider changed from {old_led_provider} to {state.led_provider}, reinitialization may be needed")
  782. logger.info(f"Settings updated: {', '.join(updated_categories)}")
  783. return {
  784. "success": True,
  785. "updated_categories": updated_categories,
  786. "requires_restart": requires_restart,
  787. "led_reinit_needed": led_reinit_needed
  788. }
  789. # ============================================================================
  790. # Multi-Table Identity Endpoints
  791. # ============================================================================
  792. class TableInfoUpdate(BaseModel):
  793. name: Optional[str] = None
  794. @app.get("/api/table-info", tags=["multi-table"])
  795. async def get_table_info():
  796. """
  797. Get table identity information for multi-table discovery.
  798. Returns the table's unique ID, name, and version.
  799. """
  800. return {
  801. "id": state.table_id,
  802. "name": state.table_name,
  803. "version": await version_manager.get_current_version()
  804. }
  805. @app.patch("/api/table-info", tags=["multi-table"])
  806. async def update_table_info(update: TableInfoUpdate):
  807. """
  808. Update table identity information.
  809. Currently only the table name can be updated.
  810. The table ID is immutable after generation.
  811. """
  812. if update.name is not None:
  813. state.table_name = update.name.strip() or "My Sand Table"
  814. state.save()
  815. logger.info(f"Table name updated to: {state.table_name}")
  816. return {
  817. "success": True,
  818. "id": state.table_id,
  819. "name": state.table_name
  820. }
  821. # ============================================================================
  822. # Individual Settings Endpoints (Deprecated - use /api/settings instead)
  823. # ============================================================================
  824. @app.get("/api/auto_play-mode", deprecated=True, tags=["settings-deprecated"])
  825. async def get_auto_play_mode():
  826. """DEPRECATED: Use GET /api/settings instead. Get current auto_play mode settings."""
  827. return {
  828. "enabled": state.auto_play_enabled,
  829. "playlist": state.auto_play_playlist,
  830. "run_mode": state.auto_play_run_mode,
  831. "pause_time": state.auto_play_pause_time,
  832. "clear_pattern": state.auto_play_clear_pattern,
  833. "shuffle": state.auto_play_shuffle
  834. }
  835. @app.post("/api/auto_play-mode", deprecated=True, tags=["settings-deprecated"])
  836. async def set_auto_play_mode(request: auto_playModeRequest):
  837. """DEPRECATED: Use PATCH /api/settings instead. Update auto_play mode settings."""
  838. state.auto_play_enabled = request.enabled
  839. if request.playlist is not None:
  840. state.auto_play_playlist = request.playlist
  841. if request.run_mode is not None:
  842. state.auto_play_run_mode = request.run_mode
  843. if request.pause_time is not None:
  844. state.auto_play_pause_time = request.pause_time
  845. if request.clear_pattern is not None:
  846. state.auto_play_clear_pattern = request.clear_pattern
  847. if request.shuffle is not None:
  848. state.auto_play_shuffle = request.shuffle
  849. state.save()
  850. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  851. return {"success": True, "message": "auto_play mode settings updated"}
  852. @app.get("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  853. async def get_scheduled_pause():
  854. """DEPRECATED: Use GET /api/settings instead. Get current Still Sands settings."""
  855. return {
  856. "enabled": state.scheduled_pause_enabled,
  857. "control_wled": state.scheduled_pause_control_wled,
  858. "finish_pattern": state.scheduled_pause_finish_pattern,
  859. "timezone": state.scheduled_pause_timezone,
  860. "time_slots": state.scheduled_pause_time_slots
  861. }
  862. @app.post("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  863. async def set_scheduled_pause(request: ScheduledPauseRequest):
  864. """Update Still Sands settings."""
  865. try:
  866. # Validate time slots
  867. for i, slot in enumerate(request.time_slots):
  868. # Validate time format (HH:MM)
  869. try:
  870. start_time = datetime.strptime(slot.start_time, "%H:%M").time()
  871. end_time = datetime.strptime(slot.end_time, "%H:%M").time()
  872. except ValueError:
  873. raise HTTPException(
  874. status_code=400,
  875. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  876. )
  877. # Validate days setting
  878. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  879. raise HTTPException(
  880. status_code=400,
  881. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  882. )
  883. # Validate custom days if applicable
  884. if slot.days == "custom":
  885. if not slot.custom_days or len(slot.custom_days) == 0:
  886. raise HTTPException(
  887. status_code=400,
  888. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  889. )
  890. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  891. for day in slot.custom_days:
  892. if day not in valid_days:
  893. raise HTTPException(
  894. status_code=400,
  895. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  896. )
  897. # Update state
  898. state.scheduled_pause_enabled = request.enabled
  899. state.scheduled_pause_control_wled = request.control_wled
  900. state.scheduled_pause_finish_pattern = request.finish_pattern
  901. state.scheduled_pause_timezone = request.timezone if request.timezone else None
  902. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  903. state.save()
  904. # Clear cached timezone so it picks up the new setting
  905. from modules.core import pattern_manager
  906. pattern_manager._cached_timezone = None
  907. pattern_manager._cached_zoneinfo = None
  908. wled_msg = " (with WLED control)" if request.control_wled else ""
  909. finish_msg = " (finish pattern first)" if request.finish_pattern else ""
  910. tz_msg = f" (timezone: {request.timezone})" if request.timezone else ""
  911. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}{finish_msg}{tz_msg}")
  912. return {"success": True, "message": "Still Sands settings updated"}
  913. except HTTPException:
  914. raise
  915. except Exception as e:
  916. logger.error(f"Error updating Still Sands settings: {str(e)}")
  917. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  918. @app.get("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  919. async def get_homing_config():
  920. """Get homing configuration (mode, compass offset, and auto-home settings)."""
  921. return {
  922. "homing_mode": state.homing,
  923. "angular_homing_offset_degrees": state.angular_homing_offset_degrees,
  924. "auto_home_enabled": state.auto_home_enabled,
  925. "auto_home_after_patterns": state.auto_home_after_patterns
  926. }
  927. class HomingConfigRequest(BaseModel):
  928. homing_mode: int = 0 # 0 = crash, 1 = sensor
  929. angular_homing_offset_degrees: float = 0.0
  930. auto_home_enabled: Optional[bool] = None
  931. auto_home_after_patterns: Optional[int] = None
  932. @app.post("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  933. async def set_homing_config(request: HomingConfigRequest):
  934. """Set homing configuration (mode, compass offset, and auto-home settings)."""
  935. try:
  936. # Validate homing mode
  937. if request.homing_mode not in [0, 1]:
  938. raise HTTPException(status_code=400, detail="Homing mode must be 0 (crash) or 1 (sensor)")
  939. state.homing = request.homing_mode
  940. state.homing_user_override = True # User explicitly set preference
  941. state.angular_homing_offset_degrees = request.angular_homing_offset_degrees
  942. # Update auto-home settings if provided
  943. if request.auto_home_enabled is not None:
  944. state.auto_home_enabled = request.auto_home_enabled
  945. if request.auto_home_after_patterns is not None:
  946. if request.auto_home_after_patterns < 1:
  947. raise HTTPException(status_code=400, detail="Auto-home after patterns must be at least 1")
  948. state.auto_home_after_patterns = request.auto_home_after_patterns
  949. state.save()
  950. mode_name = "crash" if request.homing_mode == 0 else "sensor"
  951. logger.info(f"Homing mode set to {mode_name}, compass offset set to {request.angular_homing_offset_degrees}°")
  952. if request.auto_home_enabled is not None:
  953. logger.info(f"Auto-home enabled: {state.auto_home_enabled}, after {state.auto_home_after_patterns} patterns")
  954. return {"success": True, "message": "Homing configuration updated"}
  955. except HTTPException:
  956. raise
  957. except Exception as e:
  958. logger.error(f"Error updating homing configuration: {str(e)}")
  959. raise HTTPException(status_code=500, detail=f"Failed to update homing configuration: {str(e)}")
  960. @app.get("/list_serial_ports")
  961. async def list_ports():
  962. logger.debug("Listing available serial ports")
  963. return await asyncio.to_thread(connection_manager.list_serial_ports)
  964. @app.post("/connect")
  965. async def connect(request: ConnectRequest):
  966. if not request.port:
  967. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  968. connection_manager.device_init()
  969. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  970. return {"success": True}
  971. try:
  972. state.conn = connection_manager.SerialConnection(request.port)
  973. connection_manager.device_init()
  974. logger.info(f'Successfully connected to serial port {request.port}')
  975. return {"success": True}
  976. except Exception as e:
  977. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  978. raise HTTPException(status_code=500, detail=str(e))
  979. @app.post("/disconnect")
  980. async def disconnect():
  981. try:
  982. state.conn.close()
  983. logger.info('Successfully disconnected from serial port')
  984. return {"success": True}
  985. except Exception as e:
  986. logger.error(f'Failed to disconnect serial: {str(e)}')
  987. raise HTTPException(status_code=500, detail=str(e))
  988. @app.post("/restart_connection")
  989. async def restart(request: ConnectRequest):
  990. if not request.port:
  991. logger.warning("Restart serial request received without port")
  992. raise HTTPException(status_code=400, detail="No port provided")
  993. try:
  994. logger.info(f"Restarting connection on port {request.port}")
  995. connection_manager.restart_connection()
  996. return {"success": True}
  997. except Exception as e:
  998. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  999. raise HTTPException(status_code=500, detail=str(e))
  1000. ###############################################################################
  1001. # Debug Serial Terminal - Independent raw serial communication
  1002. ###############################################################################
  1003. # Store for debug serial connections (separate from main connection)
  1004. _debug_serial_connections: dict = {}
  1005. _debug_serial_lock = asyncio.Lock()
  1006. class DebugSerialRequest(BaseModel):
  1007. port: str
  1008. baudrate: int = 115200
  1009. timeout: float = 2.0
  1010. class DebugSerialCommand(BaseModel):
  1011. port: str
  1012. command: str
  1013. timeout: float = 2.0
  1014. @app.post("/api/debug-serial/open", tags=["debug-serial"])
  1015. async def debug_serial_open(request: DebugSerialRequest):
  1016. """Open a debug serial connection (independent of main connection)."""
  1017. import serial
  1018. async with _debug_serial_lock:
  1019. # Close existing connection on this port if any
  1020. if request.port in _debug_serial_connections:
  1021. try:
  1022. _debug_serial_connections[request.port].close()
  1023. except:
  1024. pass
  1025. del _debug_serial_connections[request.port]
  1026. try:
  1027. ser = serial.Serial(
  1028. request.port,
  1029. baudrate=request.baudrate,
  1030. timeout=request.timeout
  1031. )
  1032. _debug_serial_connections[request.port] = ser
  1033. logger.info(f"Debug serial opened on {request.port}")
  1034. return {"success": True, "port": request.port, "baudrate": request.baudrate}
  1035. except Exception as e:
  1036. logger.error(f"Failed to open debug serial on {request.port}: {e}")
  1037. raise HTTPException(status_code=500, detail=str(e))
  1038. @app.post("/api/debug-serial/close", tags=["debug-serial"])
  1039. async def debug_serial_close(request: ConnectRequest):
  1040. """Close a debug serial connection."""
  1041. async with _debug_serial_lock:
  1042. if request.port not in _debug_serial_connections:
  1043. return {"success": True, "message": "Port not open"}
  1044. try:
  1045. _debug_serial_connections[request.port].close()
  1046. del _debug_serial_connections[request.port]
  1047. logger.info(f"Debug serial closed on {request.port}")
  1048. return {"success": True}
  1049. except Exception as e:
  1050. logger.error(f"Failed to close debug serial on {request.port}: {e}")
  1051. raise HTTPException(status_code=500, detail=str(e))
  1052. @app.post("/api/debug-serial/send", tags=["debug-serial"])
  1053. async def debug_serial_send(request: DebugSerialCommand):
  1054. """Send a command and receive response on debug serial connection."""
  1055. import serial
  1056. async with _debug_serial_lock:
  1057. if request.port not in _debug_serial_connections:
  1058. raise HTTPException(status_code=400, detail="Port not open. Open it first.")
  1059. ser = _debug_serial_connections[request.port]
  1060. try:
  1061. # Clear input buffer
  1062. ser.reset_input_buffer()
  1063. # Send command with newline
  1064. command = request.command.strip()
  1065. if not command.endswith('\n'):
  1066. command += '\n'
  1067. await asyncio.to_thread(ser.write, command.encode())
  1068. await asyncio.to_thread(ser.flush)
  1069. # Read response lines with timeout
  1070. responses = []
  1071. start_time = time.time()
  1072. original_timeout = ser.timeout
  1073. ser.timeout = 0.1 # Short timeout for reading
  1074. while time.time() - start_time < request.timeout:
  1075. try:
  1076. line = await asyncio.to_thread(ser.readline)
  1077. if line:
  1078. decoded = line.decode('utf-8', errors='replace').strip()
  1079. if decoded:
  1080. responses.append(decoded)
  1081. # Check for ok/error to know command completed
  1082. if decoded.lower() in ['ok', 'error'] or decoded.lower().startswith('error:'):
  1083. break
  1084. else:
  1085. # No data, small delay
  1086. await asyncio.sleep(0.05)
  1087. except:
  1088. break
  1089. ser.timeout = original_timeout
  1090. return {
  1091. "success": True,
  1092. "command": request.command.strip(),
  1093. "responses": responses,
  1094. "raw": '\n'.join(responses)
  1095. }
  1096. except Exception as e:
  1097. logger.error(f"Debug serial send error: {e}")
  1098. raise HTTPException(status_code=500, detail=str(e))
  1099. @app.get("/api/debug-serial/status", tags=["debug-serial"])
  1100. async def debug_serial_status():
  1101. """Get status of all debug serial connections."""
  1102. async with _debug_serial_lock:
  1103. status = {}
  1104. for port, ser in _debug_serial_connections.items():
  1105. try:
  1106. status[port] = {
  1107. "open": ser.is_open,
  1108. "baudrate": ser.baudrate
  1109. }
  1110. except:
  1111. status[port] = {"open": False}
  1112. return {"connections": status}
  1113. @app.get("/list_theta_rho_files")
  1114. async def list_theta_rho_files():
  1115. logger.debug("Listing theta-rho files")
  1116. # Run the blocking file system operation in a thread pool
  1117. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  1118. return sorted(files)
  1119. @app.get("/list_theta_rho_files_with_metadata")
  1120. async def list_theta_rho_files_with_metadata():
  1121. """Get list of theta-rho files with metadata for sorting and filtering.
  1122. Optimized to process files asynchronously and support request cancellation.
  1123. """
  1124. from modules.core.cache_manager import get_pattern_metadata
  1125. import asyncio
  1126. from concurrent.futures import ThreadPoolExecutor
  1127. # Run the blocking file listing in a thread
  1128. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  1129. files_with_metadata = []
  1130. # Use ThreadPoolExecutor for I/O-bound operations
  1131. executor = ThreadPoolExecutor(max_workers=4)
  1132. def process_file(file_path):
  1133. """Process a single file and return its metadata."""
  1134. try:
  1135. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  1136. # Get file stats
  1137. file_stat = os.stat(full_path)
  1138. # Get cached metadata (this should be fast if cached)
  1139. metadata = get_pattern_metadata(file_path)
  1140. # Extract full folder path from file path
  1141. path_parts = file_path.split('/')
  1142. if len(path_parts) > 1:
  1143. # Get everything except the filename (join all folder parts)
  1144. category = '/'.join(path_parts[:-1])
  1145. else:
  1146. category = 'root'
  1147. # Get file name without extension
  1148. file_name = os.path.splitext(os.path.basename(file_path))[0]
  1149. # Use modification time (mtime) for "date modified"
  1150. date_modified = file_stat.st_mtime
  1151. return {
  1152. 'path': file_path,
  1153. 'name': file_name,
  1154. 'category': category,
  1155. 'date_modified': date_modified,
  1156. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  1157. }
  1158. except Exception as e:
  1159. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  1160. # Include file with minimal info if metadata fails
  1161. path_parts = file_path.split('/')
  1162. if len(path_parts) > 1:
  1163. category = '/'.join(path_parts[:-1])
  1164. else:
  1165. category = 'root'
  1166. return {
  1167. 'path': file_path,
  1168. 'name': os.path.splitext(os.path.basename(file_path))[0],
  1169. 'category': category,
  1170. 'date_modified': 0,
  1171. 'coordinates_count': 0
  1172. }
  1173. # Load the entire metadata cache at once (async)
  1174. # This is much faster than 1000+ individual metadata lookups
  1175. try:
  1176. import json
  1177. metadata_cache_path = "metadata_cache.json"
  1178. # Use async file reading to avoid blocking the event loop
  1179. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  1180. cache_dict = cache_data.get('data', {})
  1181. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  1182. # Process all files using cached data only
  1183. for file_path in files:
  1184. try:
  1185. # Extract category from path
  1186. path_parts = file_path.split('/')
  1187. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  1188. # Get file name without extension
  1189. file_name = os.path.splitext(os.path.basename(file_path))[0]
  1190. # Get metadata from cache
  1191. cached_entry = cache_dict.get(file_path, {})
  1192. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  1193. metadata = cached_entry['metadata']
  1194. coords_count = metadata.get('total_coordinates', 0)
  1195. date_modified = cached_entry.get('mtime', 0)
  1196. else:
  1197. coords_count = 0
  1198. date_modified = 0
  1199. files_with_metadata.append({
  1200. 'path': file_path,
  1201. 'name': file_name,
  1202. 'category': category,
  1203. 'date_modified': date_modified,
  1204. 'coordinates_count': coords_count
  1205. })
  1206. except Exception as e:
  1207. logger.warning(f"Error processing {file_path}: {e}")
  1208. # Include file with minimal info if processing fails
  1209. path_parts = file_path.split('/')
  1210. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  1211. files_with_metadata.append({
  1212. 'path': file_path,
  1213. 'name': os.path.splitext(os.path.basename(file_path))[0],
  1214. 'category': category,
  1215. 'date_modified': 0,
  1216. 'coordinates_count': 0
  1217. })
  1218. except Exception as e:
  1219. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  1220. # Fallback to original method if cache loading fails
  1221. # Create tasks only when needed
  1222. loop = asyncio.get_running_loop()
  1223. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  1224. for task in asyncio.as_completed(tasks):
  1225. try:
  1226. result = await task
  1227. files_with_metadata.append(result)
  1228. except Exception as task_error:
  1229. logger.error(f"Error processing file: {str(task_error)}")
  1230. # Clean up executor
  1231. executor.shutdown(wait=False)
  1232. return files_with_metadata
  1233. @app.post("/upload_theta_rho")
  1234. async def upload_theta_rho(file: UploadFile = File(...)):
  1235. """Upload a theta-rho file."""
  1236. try:
  1237. # Save the file
  1238. # Ensure custom_patterns directory exists
  1239. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  1240. os.makedirs(custom_patterns_dir, exist_ok=True)
  1241. # Use forward slashes for internal path representation to maintain consistency
  1242. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  1243. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  1244. # Save the uploaded file with proper encoding for Windows compatibility
  1245. file_content = await file.read()
  1246. try:
  1247. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  1248. text_content = file_content.decode('utf-8')
  1249. with open(full_file_path, "w", encoding='utf-8') as f:
  1250. f.write(text_content)
  1251. except UnicodeDecodeError:
  1252. # If UTF-8 decoding fails, save as binary (fallback)
  1253. with open(full_file_path, "wb") as f:
  1254. f.write(file_content)
  1255. logger.info(f"File {file.filename} saved successfully")
  1256. # Generate image preview for the new file with retry logic
  1257. max_retries = 3
  1258. for attempt in range(max_retries):
  1259. try:
  1260. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  1261. success = await generate_image_preview(file_path_in_patterns_dir)
  1262. if success:
  1263. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  1264. break
  1265. else:
  1266. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  1267. if attempt < max_retries - 1:
  1268. await asyncio.sleep(0.5) # Small delay before retry
  1269. except Exception as e:
  1270. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  1271. if attempt < max_retries - 1:
  1272. await asyncio.sleep(0.5) # Small delay before retry
  1273. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  1274. except Exception as e:
  1275. logger.error(f"Error uploading file: {str(e)}")
  1276. raise HTTPException(status_code=500, detail=str(e))
  1277. @app.post("/get_theta_rho_coordinates")
  1278. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  1279. """Get theta-rho coordinates for animated preview."""
  1280. try:
  1281. # Normalize file path for cross-platform compatibility and remove prefixes
  1282. file_name = normalize_file_path(request.file_name)
  1283. file_path = os.path.join(THETA_RHO_DIR, file_name)
  1284. # Check file existence asynchronously
  1285. exists = await asyncio.to_thread(os.path.exists, file_path)
  1286. if not exists:
  1287. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  1288. # Parse the theta-rho file in a separate process for CPU-intensive work
  1289. # This prevents blocking the motion control thread
  1290. loop = asyncio.get_running_loop()
  1291. coordinates = await loop.run_in_executor(pool_module.get_pool(), parse_theta_rho_file, file_path)
  1292. if not coordinates:
  1293. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  1294. return {
  1295. "success": True,
  1296. "coordinates": coordinates,
  1297. "total_points": len(coordinates)
  1298. }
  1299. except Exception as e:
  1300. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  1301. raise HTTPException(status_code=500, detail=str(e))
  1302. @app.post("/run_theta_rho")
  1303. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  1304. if not request.file_name:
  1305. logger.warning('Run theta-rho request received without file name')
  1306. raise HTTPException(status_code=400, detail="No file name provided")
  1307. file_path = None
  1308. if 'clear' in request.file_name:
  1309. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  1310. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  1311. logger.info(f'Clear pattern file: {file_path}')
  1312. if not file_path:
  1313. # Normalize file path for cross-platform compatibility
  1314. normalized_file_name = normalize_file_path(request.file_name)
  1315. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1316. if not os.path.exists(file_path):
  1317. logger.error(f'Theta-rho file not found: {file_path}')
  1318. raise HTTPException(status_code=404, detail="File not found")
  1319. try:
  1320. if not (state.conn.is_connected() if state.conn else False):
  1321. logger.warning("Attempted to run a pattern without a connection")
  1322. raise HTTPException(status_code=400, detail="Connection not established")
  1323. check_homing_in_progress()
  1324. if pattern_manager.get_pattern_lock().locked():
  1325. logger.info("Another pattern is running, stopping it first...")
  1326. await pattern_manager.stop_actions()
  1327. files_to_run = [file_path]
  1328. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  1329. # Only include clear_pattern if it's not "none"
  1330. kwargs = {}
  1331. if request.pre_execution != "none":
  1332. kwargs['clear_pattern'] = request.pre_execution
  1333. # Pass arguments properly
  1334. background_tasks.add_task(
  1335. pattern_manager.run_theta_rho_files,
  1336. files_to_run, # First positional argument
  1337. **kwargs # Spread keyword arguments
  1338. )
  1339. return {"success": True}
  1340. except HTTPException as http_exc:
  1341. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  1342. raise http_exc
  1343. except Exception as e:
  1344. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  1345. raise HTTPException(status_code=500, detail=str(e))
  1346. @app.post("/stop_execution")
  1347. async def stop_execution():
  1348. if not (state.conn.is_connected() if state.conn else False):
  1349. logger.warning("Attempted to stop without a connection")
  1350. raise HTTPException(status_code=400, detail="Connection not established")
  1351. await pattern_manager.stop_actions()
  1352. return {"success": True}
  1353. @app.post("/send_home")
  1354. async def send_home():
  1355. try:
  1356. if not (state.conn.is_connected() if state.conn else False):
  1357. logger.warning("Attempted to move to home without a connection")
  1358. raise HTTPException(status_code=400, detail="Connection not established")
  1359. if state.is_homing:
  1360. raise HTTPException(status_code=409, detail="Homing already in progress")
  1361. # Set homing flag to block other movement operations
  1362. state.is_homing = True
  1363. logger.info("Homing started - blocking other movement operations")
  1364. try:
  1365. # Run homing with 15 second timeout
  1366. success = await asyncio.to_thread(connection_manager.home)
  1367. if not success:
  1368. logger.error("Homing failed or timed out")
  1369. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  1370. return {"success": True}
  1371. finally:
  1372. # Always clear homing flag when done (success or failure)
  1373. state.is_homing = False
  1374. logger.info("Homing completed - movement operations unblocked")
  1375. except HTTPException:
  1376. raise
  1377. except Exception as e:
  1378. logger.error(f"Failed to send home command: {str(e)}")
  1379. raise HTTPException(status_code=500, detail=str(e))
  1380. @app.post("/run_theta_rho_file/{file_name}")
  1381. async def run_specific_theta_rho_file(file_name: str):
  1382. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  1383. if not os.path.exists(file_path):
  1384. raise HTTPException(status_code=404, detail="File not found")
  1385. if not (state.conn.is_connected() if state.conn else False):
  1386. logger.warning("Attempted to run a pattern without a connection")
  1387. raise HTTPException(status_code=400, detail="Connection not established")
  1388. check_homing_in_progress()
  1389. pattern_manager.run_theta_rho_file(file_path)
  1390. return {"success": True}
  1391. class DeleteFileRequest(BaseModel):
  1392. file_name: str
  1393. @app.post("/delete_theta_rho_file")
  1394. async def delete_theta_rho_file(request: DeleteFileRequest):
  1395. if not request.file_name:
  1396. logger.warning("Delete theta-rho file request received without filename")
  1397. raise HTTPException(status_code=400, detail="No file name provided")
  1398. # Normalize file path for cross-platform compatibility
  1399. normalized_file_name = normalize_file_path(request.file_name)
  1400. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1401. # Check file existence asynchronously
  1402. exists = await asyncio.to_thread(os.path.exists, file_path)
  1403. if not exists:
  1404. logger.error(f"Attempted to delete non-existent file: {file_path}")
  1405. raise HTTPException(status_code=404, detail="File not found")
  1406. try:
  1407. # Delete the pattern file asynchronously
  1408. await asyncio.to_thread(os.remove, file_path)
  1409. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  1410. # Clean up cached preview image and metadata asynchronously
  1411. from modules.core.cache_manager import delete_pattern_cache
  1412. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  1413. if cache_cleanup_success:
  1414. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  1415. else:
  1416. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  1417. return {"success": True, "cache_cleanup": cache_cleanup_success}
  1418. except Exception as e:
  1419. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  1420. raise HTTPException(status_code=500, detail=str(e))
  1421. @app.post("/move_to_center")
  1422. async def move_to_center():
  1423. try:
  1424. if not (state.conn.is_connected() if state.conn else False):
  1425. logger.warning("Attempted to move to center without a connection")
  1426. raise HTTPException(status_code=400, detail="Connection not established")
  1427. check_homing_in_progress()
  1428. logger.info("Moving device to center position")
  1429. await pattern_manager.reset_theta()
  1430. await pattern_manager.move_polar(0, 0)
  1431. return {"success": True}
  1432. except HTTPException:
  1433. raise
  1434. except Exception as e:
  1435. logger.error(f"Failed to move to center: {str(e)}")
  1436. raise HTTPException(status_code=500, detail=str(e))
  1437. @app.post("/move_to_perimeter")
  1438. async def move_to_perimeter():
  1439. try:
  1440. if not (state.conn.is_connected() if state.conn else False):
  1441. logger.warning("Attempted to move to perimeter without a connection")
  1442. raise HTTPException(status_code=400, detail="Connection not established")
  1443. check_homing_in_progress()
  1444. await pattern_manager.reset_theta()
  1445. await pattern_manager.move_polar(0, 1)
  1446. return {"success": True}
  1447. except HTTPException:
  1448. raise
  1449. except Exception as e:
  1450. logger.error(f"Failed to move to perimeter: {str(e)}")
  1451. raise HTTPException(status_code=500, detail=str(e))
  1452. @app.post("/preview_thr")
  1453. async def preview_thr(request: DeleteFileRequest):
  1454. if not request.file_name:
  1455. logger.warning("Preview theta-rho request received without filename")
  1456. raise HTTPException(status_code=400, detail="No file name provided")
  1457. # Normalize file path for cross-platform compatibility
  1458. normalized_file_name = normalize_file_path(request.file_name)
  1459. # Construct the full path to the pattern file to check existence
  1460. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1461. # Check file existence asynchronously
  1462. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1463. if not exists:
  1464. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  1465. raise HTTPException(status_code=404, detail="Pattern file not found")
  1466. try:
  1467. cache_path = get_cache_path(normalized_file_name)
  1468. # Check cache existence asynchronously
  1469. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1470. if not cache_exists:
  1471. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  1472. # Attempt to generate the preview if it's missing
  1473. success = await generate_image_preview(normalized_file_name)
  1474. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1475. if not success or not cache_exists_after:
  1476. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  1477. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  1478. # Try to get coordinates from metadata cache first
  1479. metadata = get_pattern_metadata(normalized_file_name)
  1480. if metadata:
  1481. first_coord_obj = metadata.get('first_coordinate')
  1482. last_coord_obj = metadata.get('last_coordinate')
  1483. else:
  1484. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  1485. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  1486. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  1487. first_coord = coordinates[0] if coordinates else None
  1488. last_coord = coordinates[-1] if coordinates else None
  1489. # Format coordinates as objects with x and y properties
  1490. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1491. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1492. # Return JSON with preview URL and coordinates
  1493. # URL encode the file_name for the preview URL
  1494. # Handle both forward slashes and backslashes for cross-platform compatibility
  1495. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  1496. return {
  1497. "preview_url": f"/preview/{encoded_filename}",
  1498. "first_coordinate": first_coord_obj,
  1499. "last_coordinate": last_coord_obj
  1500. }
  1501. except HTTPException:
  1502. raise
  1503. except Exception as e:
  1504. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  1505. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  1506. @app.get("/preview/{encoded_filename}")
  1507. async def serve_preview(encoded_filename: str):
  1508. """Serve a preview image for a pattern file."""
  1509. # Decode the filename by replacing -- with the original path separators
  1510. # First try forward slash (most common case), then backslash if needed
  1511. file_name = encoded_filename.replace('--', '/')
  1512. # Apply normalization to handle any remaining path prefixes
  1513. file_name = normalize_file_path(file_name)
  1514. # Check if the decoded path exists, if not try backslash decoding
  1515. cache_path = get_cache_path(file_name)
  1516. if not os.path.exists(cache_path):
  1517. # Try with backslash for Windows paths
  1518. file_name_backslash = encoded_filename.replace('--', '\\')
  1519. file_name_backslash = normalize_file_path(file_name_backslash)
  1520. cache_path_backslash = get_cache_path(file_name_backslash)
  1521. if os.path.exists(cache_path_backslash):
  1522. file_name = file_name_backslash
  1523. cache_path = cache_path_backslash
  1524. # cache_path is already determined above in the decoding logic
  1525. if not os.path.exists(cache_path):
  1526. logger.error(f"Preview image not found for {file_name}")
  1527. raise HTTPException(status_code=404, detail="Preview image not found")
  1528. # Add caching headers
  1529. headers = {
  1530. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  1531. "Content-Type": "image/webp",
  1532. "Accept-Ranges": "bytes"
  1533. }
  1534. return FileResponse(
  1535. cache_path,
  1536. media_type="image/webp",
  1537. headers=headers
  1538. )
  1539. @app.post("/send_coordinate")
  1540. async def send_coordinate(request: CoordinateRequest):
  1541. if not (state.conn.is_connected() if state.conn else False):
  1542. logger.warning("Attempted to send coordinate without a connection")
  1543. raise HTTPException(status_code=400, detail="Connection not established")
  1544. check_homing_in_progress()
  1545. try:
  1546. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  1547. await pattern_manager.move_polar(request.theta, request.rho)
  1548. return {"success": True}
  1549. except Exception as e:
  1550. logger.error(f"Failed to send coordinate: {str(e)}")
  1551. raise HTTPException(status_code=500, detail=str(e))
  1552. @app.get("/download/{filename}")
  1553. async def download_file(filename: str):
  1554. return FileResponse(
  1555. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  1556. filename=filename
  1557. )
  1558. @app.get("/serial_status")
  1559. async def serial_status():
  1560. connected = state.conn.is_connected() if state.conn else False
  1561. port = state.port
  1562. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  1563. return {
  1564. "connected": connected,
  1565. "port": port,
  1566. "preferred_port": state.preferred_port
  1567. }
  1568. @app.get("/api/preferred-port", deprecated=True, tags=["settings-deprecated"])
  1569. async def get_preferred_port():
  1570. """Get the currently configured preferred port for auto-connect."""
  1571. return {
  1572. "preferred_port": state.preferred_port
  1573. }
  1574. @app.post("/api/preferred-port", deprecated=True, tags=["settings-deprecated"])
  1575. async def set_preferred_port(request: Request):
  1576. """Set the preferred port for auto-connect."""
  1577. data = await request.json()
  1578. preferred_port = data.get("preferred_port")
  1579. # Allow setting to None to clear the preference
  1580. if preferred_port == "" or preferred_port == "none":
  1581. preferred_port = None
  1582. state.preferred_port = preferred_port
  1583. state.save()
  1584. logger.info(f"Preferred port set to: {preferred_port}")
  1585. return {
  1586. "success": True,
  1587. "preferred_port": state.preferred_port
  1588. }
  1589. @app.post("/pause_execution")
  1590. async def pause_execution():
  1591. if pattern_manager.pause_execution():
  1592. return {"success": True, "message": "Execution paused"}
  1593. raise HTTPException(status_code=500, detail="Failed to pause execution")
  1594. @app.post("/resume_execution")
  1595. async def resume_execution():
  1596. if pattern_manager.resume_execution():
  1597. return {"success": True, "message": "Execution resumed"}
  1598. raise HTTPException(status_code=500, detail="Failed to resume execution")
  1599. # Playlist endpoints
  1600. @app.get("/list_all_playlists")
  1601. async def list_all_playlists():
  1602. playlist_names = playlist_manager.list_all_playlists()
  1603. return playlist_names
  1604. @app.get("/get_playlist")
  1605. async def get_playlist(name: str):
  1606. if not name:
  1607. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  1608. playlist = playlist_manager.get_playlist(name)
  1609. if not playlist:
  1610. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  1611. return playlist
  1612. @app.post("/create_playlist")
  1613. async def create_playlist(request: PlaylistRequest):
  1614. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  1615. return {
  1616. "success": success,
  1617. "message": f"Playlist '{request.playlist_name}' created/updated"
  1618. }
  1619. @app.post("/modify_playlist")
  1620. async def modify_playlist(request: PlaylistRequest):
  1621. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  1622. return {
  1623. "success": success,
  1624. "message": f"Playlist '{request.playlist_name}' updated"
  1625. }
  1626. @app.delete("/delete_playlist")
  1627. async def delete_playlist(request: DeletePlaylistRequest):
  1628. success = playlist_manager.delete_playlist(request.playlist_name)
  1629. if not success:
  1630. raise HTTPException(
  1631. status_code=404,
  1632. detail=f"Playlist '{request.playlist_name}' not found"
  1633. )
  1634. return {
  1635. "success": True,
  1636. "message": f"Playlist '{request.playlist_name}' deleted"
  1637. }
  1638. @app.post("/rename_playlist")
  1639. async def rename_playlist(request: RenamePlaylistRequest):
  1640. """Rename an existing playlist."""
  1641. success, message = playlist_manager.rename_playlist(request.old_name, request.new_name)
  1642. if not success:
  1643. raise HTTPException(
  1644. status_code=400,
  1645. detail=message
  1646. )
  1647. return {
  1648. "success": True,
  1649. "message": message,
  1650. "new_name": request.new_name
  1651. }
  1652. class AddToPlaylistRequest(BaseModel):
  1653. playlist_name: str
  1654. pattern: str
  1655. @app.post("/add_to_playlist")
  1656. async def add_to_playlist(request: AddToPlaylistRequest):
  1657. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  1658. if not success:
  1659. raise HTTPException(status_code=404, detail="Playlist not found")
  1660. return {"success": True}
  1661. @app.post("/run_playlist")
  1662. async def run_playlist_endpoint(request: PlaylistRequest):
  1663. """Run a playlist with specified parameters."""
  1664. try:
  1665. if not (state.conn.is_connected() if state.conn else False):
  1666. logger.warning("Attempted to run a playlist without a connection")
  1667. raise HTTPException(status_code=400, detail="Connection not established")
  1668. check_homing_in_progress()
  1669. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  1670. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  1671. # Start the playlist execution
  1672. success, message = await playlist_manager.run_playlist(
  1673. request.playlist_name,
  1674. pause_time=request.pause_time,
  1675. clear_pattern=request.clear_pattern,
  1676. run_mode=request.run_mode,
  1677. shuffle=request.shuffle
  1678. )
  1679. if not success:
  1680. raise HTTPException(status_code=409, detail=message)
  1681. return {"message": f"Started playlist: {request.playlist_name}"}
  1682. except Exception as e:
  1683. logger.error(f"Error running playlist: {e}")
  1684. raise HTTPException(status_code=500, detail=str(e))
  1685. @app.post("/set_speed")
  1686. async def set_speed(request: SpeedRequest):
  1687. try:
  1688. if not (state.conn.is_connected() if state.conn else False):
  1689. logger.warning("Attempted to change speed without a connection")
  1690. raise HTTPException(status_code=400, detail="Connection not established")
  1691. if request.speed <= 0:
  1692. logger.warning(f"Invalid speed value received: {request.speed}")
  1693. raise HTTPException(status_code=400, detail="Invalid speed value")
  1694. state.speed = request.speed
  1695. return {"success": True, "speed": request.speed}
  1696. except Exception as e:
  1697. logger.error(f"Failed to set speed: {str(e)}")
  1698. raise HTTPException(status_code=500, detail=str(e))
  1699. @app.get("/check_software_update")
  1700. async def check_updates():
  1701. update_info = update_manager.check_git_updates()
  1702. return update_info
  1703. @app.post("/update_software")
  1704. async def update_software():
  1705. logger.info("Starting software update process")
  1706. success, error_message, error_log = update_manager.update_software()
  1707. if success:
  1708. logger.info("Software update completed successfully")
  1709. return {"success": True}
  1710. else:
  1711. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  1712. raise HTTPException(
  1713. status_code=500,
  1714. detail={
  1715. "error": error_message,
  1716. "details": error_log
  1717. }
  1718. )
  1719. @app.post("/set_wled_ip")
  1720. async def set_wled_ip(request: WLEDRequest):
  1721. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  1722. state.wled_ip = request.wled_ip
  1723. state.led_provider = "wled" if request.wled_ip else "none"
  1724. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  1725. if state.led_controller:
  1726. state.led_controller.effect_idle()
  1727. _start_idle_led_timeout()
  1728. state.save()
  1729. logger.info(f"WLED IP updated: {request.wled_ip}")
  1730. return {"success": True, "wled_ip": state.wled_ip}
  1731. @app.get("/get_wled_ip")
  1732. async def get_wled_ip():
  1733. """Legacy endpoint for backward compatibility"""
  1734. if not state.wled_ip:
  1735. raise HTTPException(status_code=404, detail="No WLED IP set")
  1736. return {"success": True, "wled_ip": state.wled_ip}
  1737. @app.post("/set_led_config", deprecated=True, tags=["settings-deprecated"])
  1738. async def set_led_config(request: LEDConfigRequest):
  1739. """DEPRECATED: Use PATCH /api/settings instead. Configure LED provider (WLED, DW LEDs, or none)"""
  1740. if request.provider not in ["wled", "dw_leds", "none"]:
  1741. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'wled', 'dw_leds', or 'none'")
  1742. state.led_provider = request.provider
  1743. if request.provider == "wled":
  1744. if not request.ip_address:
  1745. raise HTTPException(status_code=400, detail="IP address required for WLED")
  1746. state.wled_ip = request.ip_address
  1747. state.led_controller = LEDInterface("wled", request.ip_address)
  1748. logger.info(f"LED provider set to WLED at {request.ip_address}")
  1749. elif request.provider == "dw_leds":
  1750. # Check if hardware settings changed (requires restart)
  1751. old_gpio_pin = state.dw_led_gpio_pin
  1752. old_pixel_order = state.dw_led_pixel_order
  1753. hardware_changed = (
  1754. old_gpio_pin != (request.gpio_pin or 12) or
  1755. old_pixel_order != (request.pixel_order or "GRB")
  1756. )
  1757. # Stop existing DW LED controller if hardware settings changed
  1758. if hardware_changed and state.led_controller and state.led_provider == "dw_leds":
  1759. logger.info("Hardware settings changed, stopping existing LED controller...")
  1760. controller = state.led_controller.get_controller()
  1761. if controller and hasattr(controller, 'stop'):
  1762. try:
  1763. controller.stop()
  1764. logger.info("LED controller stopped successfully")
  1765. except Exception as e:
  1766. logger.error(f"Error stopping LED controller: {e}")
  1767. state.dw_led_num_leds = request.num_leds or 60
  1768. state.dw_led_gpio_pin = request.gpio_pin or 12
  1769. state.dw_led_pixel_order = request.pixel_order or "GRB"
  1770. state.dw_led_brightness = request.brightness or 35
  1771. state.wled_ip = None
  1772. # Create new LED controller with updated settings
  1773. state.led_controller = LEDInterface(
  1774. "dw_leds",
  1775. num_leds=state.dw_led_num_leds,
  1776. gpio_pin=state.dw_led_gpio_pin,
  1777. pixel_order=state.dw_led_pixel_order,
  1778. brightness=state.dw_led_brightness / 100.0,
  1779. speed=state.dw_led_speed,
  1780. intensity=state.dw_led_intensity
  1781. )
  1782. restart_msg = " (restarted)" if hardware_changed else ""
  1783. 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}")
  1784. # Check if initialization succeeded by checking status
  1785. status = state.led_controller.check_status()
  1786. if not status.get("connected", False) and status.get("error"):
  1787. error_msg = status["error"]
  1788. logger.warning(f"DW LED initialization failed: {error_msg}, but configuration saved for testing")
  1789. state.led_controller = None
  1790. # Keep the provider setting for testing purposes
  1791. # state.led_provider remains "dw_leds" so settings can be saved/tested
  1792. # Save state even with error
  1793. state.save()
  1794. # Return success with warning instead of error
  1795. return {
  1796. "success": True,
  1797. "warning": error_msg,
  1798. "hardware_available": False,
  1799. "provider": state.led_provider,
  1800. "dw_led_num_leds": state.dw_led_num_leds,
  1801. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1802. "dw_led_pixel_order": state.dw_led_pixel_order,
  1803. "dw_led_brightness": state.dw_led_brightness
  1804. }
  1805. else: # none
  1806. state.wled_ip = None
  1807. state.led_controller = None
  1808. logger.info("LED provider disabled")
  1809. # Show idle effect if controller is configured
  1810. if state.led_controller:
  1811. state.led_controller.effect_idle()
  1812. _start_idle_led_timeout()
  1813. state.save()
  1814. return {
  1815. "success": True,
  1816. "provider": state.led_provider,
  1817. "wled_ip": state.wled_ip,
  1818. "dw_led_num_leds": state.dw_led_num_leds,
  1819. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1820. "dw_led_brightness": state.dw_led_brightness
  1821. }
  1822. @app.get("/get_led_config", deprecated=True, tags=["settings-deprecated"])
  1823. async def get_led_config():
  1824. """DEPRECATED: Use GET /api/settings instead. Get current LED provider configuration"""
  1825. # Auto-detect provider for backward compatibility with existing installations
  1826. provider = state.led_provider
  1827. if not provider or provider == "none":
  1828. # If no provider set but we have IPs configured, auto-detect
  1829. if state.wled_ip:
  1830. provider = "wled"
  1831. state.led_provider = "wled"
  1832. state.save()
  1833. logger.info("Auto-detected WLED provider from existing configuration")
  1834. else:
  1835. provider = "none"
  1836. return {
  1837. "success": True,
  1838. "provider": provider,
  1839. "wled_ip": state.wled_ip,
  1840. "dw_led_num_leds": state.dw_led_num_leds,
  1841. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1842. "dw_led_pixel_order": state.dw_led_pixel_order,
  1843. "dw_led_brightness": state.dw_led_brightness,
  1844. "dw_led_idle_effect": state.dw_led_idle_effect,
  1845. "dw_led_playing_effect": state.dw_led_playing_effect
  1846. }
  1847. @app.post("/skip_pattern")
  1848. async def skip_pattern():
  1849. if not state.current_playlist:
  1850. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1851. state.skip_requested = True
  1852. return {"success": True}
  1853. @app.get("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1854. async def get_custom_clear_patterns():
  1855. """Get the currently configured custom clear patterns."""
  1856. return {
  1857. "success": True,
  1858. "custom_clear_from_in": state.custom_clear_from_in,
  1859. "custom_clear_from_out": state.custom_clear_from_out
  1860. }
  1861. @app.post("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1862. async def set_custom_clear_patterns(request: dict):
  1863. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1864. try:
  1865. # Validate that the patterns exist if they're provided
  1866. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1867. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1868. if not os.path.exists(pattern_path):
  1869. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1870. state.custom_clear_from_in = request["custom_clear_from_in"]
  1871. elif "custom_clear_from_in" in request:
  1872. state.custom_clear_from_in = None
  1873. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1874. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1875. if not os.path.exists(pattern_path):
  1876. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1877. state.custom_clear_from_out = request["custom_clear_from_out"]
  1878. elif "custom_clear_from_out" in request:
  1879. state.custom_clear_from_out = None
  1880. state.save()
  1881. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1882. return {
  1883. "success": True,
  1884. "custom_clear_from_in": state.custom_clear_from_in,
  1885. "custom_clear_from_out": state.custom_clear_from_out
  1886. }
  1887. except Exception as e:
  1888. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  1889. raise HTTPException(status_code=500, detail=str(e))
  1890. @app.get("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  1891. async def get_clear_pattern_speed():
  1892. """Get the current clearing pattern speed setting."""
  1893. return {
  1894. "success": True,
  1895. "clear_pattern_speed": state.clear_pattern_speed,
  1896. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1897. }
  1898. @app.post("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  1899. async def set_clear_pattern_speed(request: dict):
  1900. """DEPRECATED: Use PATCH /api/settings instead. Set the clearing pattern speed."""
  1901. try:
  1902. # If speed is None or "none", use default behavior (state.speed)
  1903. speed_value = request.get("clear_pattern_speed")
  1904. if speed_value is None or speed_value == "none" or speed_value == "":
  1905. speed = None
  1906. else:
  1907. speed = int(speed_value)
  1908. # Validate speed range (same as regular speed limits) only if speed is not None
  1909. if speed is not None and not (50 <= speed <= 2000):
  1910. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  1911. state.clear_pattern_speed = speed
  1912. state.save()
  1913. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  1914. return {
  1915. "success": True,
  1916. "clear_pattern_speed": state.clear_pattern_speed,
  1917. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1918. }
  1919. except ValueError:
  1920. raise HTTPException(status_code=400, detail="Invalid speed value")
  1921. except Exception as e:
  1922. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  1923. raise HTTPException(status_code=500, detail=str(e))
  1924. @app.get("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  1925. async def get_app_name():
  1926. """DEPRECATED: Use GET /api/settings instead. Get current application name."""
  1927. return {"app_name": state.app_name}
  1928. @app.post("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  1929. async def set_app_name(request: dict):
  1930. """DEPRECATED: Use PATCH /api/settings instead. Update application name."""
  1931. app_name = request.get("app_name", "").strip()
  1932. if not app_name:
  1933. app_name = "Dune Weaver" # Reset to default if empty
  1934. state.app_name = app_name
  1935. state.save()
  1936. logger.info(f"Application name updated to: {app_name}")
  1937. return {"success": True, "app_name": app_name}
  1938. # ============================================================================
  1939. # Custom Branding Upload Endpoints
  1940. # ============================================================================
  1941. CUSTOM_BRANDING_DIR = os.path.join("static", "custom")
  1942. ALLOWED_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"}
  1943. MAX_LOGO_SIZE = 5 * 1024 * 1024 # 5MB
  1944. def generate_favicon_from_logo(logo_path: str, favicon_path: str) -> bool:
  1945. """Generate a circular-cropped favicon from the uploaded logo using PIL.
  1946. Creates a multi-size ICO file (16x16, 32x32, 48x48) with circular crop.
  1947. Returns True on success, False on failure.
  1948. """
  1949. try:
  1950. from PIL import Image, ImageDraw
  1951. def create_circular_image(img, size):
  1952. """Create a circular-cropped image at the specified size."""
  1953. # Resize to target size
  1954. resized = img.resize((size, size), Image.Resampling.LANCZOS)
  1955. # Create circular mask
  1956. mask = Image.new('L', (size, size), 0)
  1957. draw = ImageDraw.Draw(mask)
  1958. draw.ellipse((0, 0, size - 1, size - 1), fill=255)
  1959. # Apply circular mask - create transparent background
  1960. output = Image.new('RGBA', (size, size), (0, 0, 0, 0))
  1961. output.paste(resized, (0, 0), mask)
  1962. return output
  1963. with Image.open(logo_path) as img:
  1964. # Convert to RGBA if needed
  1965. if img.mode != 'RGBA':
  1966. img = img.convert('RGBA')
  1967. # Crop to square (center crop)
  1968. width, height = img.size
  1969. min_dim = min(width, height)
  1970. left = (width - min_dim) // 2
  1971. top = (height - min_dim) // 2
  1972. img = img.crop((left, top, left + min_dim, top + min_dim))
  1973. # Create circular images at each favicon size
  1974. sizes = [48, 32, 16]
  1975. circular_images = [create_circular_image(img, size) for size in sizes]
  1976. # Save as ICO - first image is the main one, rest are appended
  1977. circular_images[0].save(
  1978. favicon_path,
  1979. format='ICO',
  1980. append_images=circular_images[1:],
  1981. sizes=[(s, s) for s in sizes]
  1982. )
  1983. return True
  1984. except Exception as e:
  1985. logger.error(f"Failed to generate favicon: {str(e)}")
  1986. return False
  1987. @app.post("/api/upload-logo", tags=["settings"])
  1988. async def upload_logo(file: UploadFile = File(...)):
  1989. """Upload a custom logo image.
  1990. Supported formats: PNG, JPG, JPEG, GIF, WebP, SVG
  1991. Maximum size: 5MB
  1992. The uploaded file will be stored and used as the application logo.
  1993. A favicon will be automatically generated from the logo.
  1994. """
  1995. try:
  1996. # Validate file extension
  1997. file_ext = os.path.splitext(file.filename)[1].lower()
  1998. if file_ext not in ALLOWED_IMAGE_EXTENSIONS:
  1999. raise HTTPException(
  2000. status_code=400,
  2001. detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}"
  2002. )
  2003. # Read and validate file size
  2004. content = await file.read()
  2005. if len(content) > MAX_LOGO_SIZE:
  2006. raise HTTPException(
  2007. status_code=400,
  2008. detail=f"File too large. Maximum size: {MAX_LOGO_SIZE // (1024*1024)}MB"
  2009. )
  2010. # Ensure custom branding directory exists
  2011. os.makedirs(CUSTOM_BRANDING_DIR, exist_ok=True)
  2012. # Delete old logo and favicon if they exist
  2013. if state.custom_logo:
  2014. old_logo_path = os.path.join(CUSTOM_BRANDING_DIR, state.custom_logo)
  2015. if os.path.exists(old_logo_path):
  2016. os.remove(old_logo_path)
  2017. # Also remove old favicon
  2018. old_favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  2019. if os.path.exists(old_favicon_path):
  2020. os.remove(old_favicon_path)
  2021. # Generate a unique filename to prevent caching issues
  2022. import uuid
  2023. filename = f"logo-{uuid.uuid4().hex[:8]}{file_ext}"
  2024. file_path = os.path.join(CUSTOM_BRANDING_DIR, filename)
  2025. # Save the logo file
  2026. with open(file_path, "wb") as f:
  2027. f.write(content)
  2028. # Generate favicon from logo (for non-SVG files)
  2029. favicon_generated = False
  2030. if file_ext != ".svg":
  2031. favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  2032. favicon_generated = generate_favicon_from_logo(file_path, favicon_path)
  2033. # Update state
  2034. state.custom_logo = filename
  2035. state.save()
  2036. logger.info(f"Custom logo uploaded: {filename}, favicon generated: {favicon_generated}")
  2037. return {
  2038. "success": True,
  2039. "filename": filename,
  2040. "url": f"/static/custom/{filename}",
  2041. "favicon_generated": favicon_generated
  2042. }
  2043. except HTTPException:
  2044. raise
  2045. except Exception as e:
  2046. logger.error(f"Error uploading logo: {str(e)}")
  2047. raise HTTPException(status_code=500, detail=str(e))
  2048. @app.delete("/api/custom-logo", tags=["settings"])
  2049. async def delete_custom_logo():
  2050. """Remove custom logo and favicon, reverting to defaults."""
  2051. try:
  2052. if state.custom_logo:
  2053. # Remove logo
  2054. logo_path = os.path.join(CUSTOM_BRANDING_DIR, state.custom_logo)
  2055. if os.path.exists(logo_path):
  2056. os.remove(logo_path)
  2057. # Remove generated favicon
  2058. favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  2059. if os.path.exists(favicon_path):
  2060. os.remove(favicon_path)
  2061. state.custom_logo = None
  2062. state.save()
  2063. logger.info("Custom logo and favicon removed")
  2064. return {"success": True}
  2065. except Exception as e:
  2066. logger.error(f"Error removing logo: {str(e)}")
  2067. raise HTTPException(status_code=500, detail=str(e))
  2068. @app.get("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  2069. async def get_mqtt_config():
  2070. """DEPRECATED: Use GET /api/settings instead. Get current MQTT configuration.
  2071. Note: Password is not returned for security reasons.
  2072. """
  2073. from modules.mqtt import get_mqtt_handler
  2074. handler = get_mqtt_handler()
  2075. return {
  2076. "enabled": state.mqtt_enabled,
  2077. "broker": state.mqtt_broker,
  2078. "port": state.mqtt_port,
  2079. "username": state.mqtt_username,
  2080. # Password is intentionally omitted for security
  2081. "has_password": bool(state.mqtt_password),
  2082. "client_id": state.mqtt_client_id,
  2083. "discovery_prefix": state.mqtt_discovery_prefix,
  2084. "device_id": state.mqtt_device_id,
  2085. "device_name": state.mqtt_device_name,
  2086. "connected": handler.is_connected if hasattr(handler, 'is_connected') else False,
  2087. "is_mock": handler.__class__.__name__ == 'MockMQTTHandler'
  2088. }
  2089. @app.post("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  2090. async def set_mqtt_config(request: dict):
  2091. """DEPRECATED: Use PATCH /api/settings instead. Update MQTT configuration. Requires restart to take effect."""
  2092. try:
  2093. # Update state with new values
  2094. state.mqtt_enabled = request.get("enabled", False)
  2095. state.mqtt_broker = (request.get("broker") or "").strip()
  2096. state.mqtt_port = int(request.get("port") or 1883)
  2097. state.mqtt_username = (request.get("username") or "").strip()
  2098. state.mqtt_password = (request.get("password") or "").strip()
  2099. state.mqtt_client_id = (request.get("client_id") or "dune_weaver").strip()
  2100. state.mqtt_discovery_prefix = (request.get("discovery_prefix") or "homeassistant").strip()
  2101. state.mqtt_device_id = (request.get("device_id") or "dune_weaver").strip()
  2102. state.mqtt_device_name = (request.get("device_name") or "Dune Weaver").strip()
  2103. # Validate required fields when enabled
  2104. if state.mqtt_enabled and not state.mqtt_broker:
  2105. return JSONResponse(
  2106. content={"success": False, "message": "Broker address is required when MQTT is enabled"},
  2107. status_code=400
  2108. )
  2109. state.save()
  2110. logger.info(f"MQTT configuration updated. Enabled: {state.mqtt_enabled}, Broker: {state.mqtt_broker}")
  2111. return {
  2112. "success": True,
  2113. "message": "MQTT configuration saved. Restart the application for changes to take effect.",
  2114. "requires_restart": True
  2115. }
  2116. except ValueError as e:
  2117. return JSONResponse(
  2118. content={"success": False, "message": f"Invalid value: {str(e)}"},
  2119. status_code=400
  2120. )
  2121. except Exception as e:
  2122. logger.error(f"Failed to update MQTT config: {str(e)}")
  2123. return JSONResponse(
  2124. content={"success": False, "message": str(e)},
  2125. status_code=500
  2126. )
  2127. @app.post("/api/mqtt-test")
  2128. async def test_mqtt_connection(request: dict):
  2129. """Test MQTT connection with provided settings."""
  2130. import paho.mqtt.client as mqtt_client
  2131. broker = (request.get("broker") or "").strip()
  2132. port = int(request.get("port") or 1883)
  2133. username = (request.get("username") or "").strip()
  2134. password = (request.get("password") or "").strip()
  2135. client_id = (request.get("client_id") or "dune_weaver_test").strip()
  2136. if not broker:
  2137. return JSONResponse(
  2138. content={"success": False, "message": "Broker address is required"},
  2139. status_code=400
  2140. )
  2141. try:
  2142. # Create a test client
  2143. client = mqtt_client.Client(client_id=client_id + "_test")
  2144. if username:
  2145. client.username_pw_set(username, password)
  2146. # Connection result
  2147. connection_result = {"connected": False, "error": None}
  2148. def on_connect(client, userdata, flags, rc):
  2149. if rc == 0:
  2150. connection_result["connected"] = True
  2151. else:
  2152. error_messages = {
  2153. 1: "Incorrect protocol version",
  2154. 2: "Invalid client identifier",
  2155. 3: "Server unavailable",
  2156. 4: "Bad username or password",
  2157. 5: "Not authorized"
  2158. }
  2159. connection_result["error"] = error_messages.get(rc, f"Connection failed with code {rc}")
  2160. client.on_connect = on_connect
  2161. # Try to connect with timeout
  2162. client.connect_async(broker, port, keepalive=10)
  2163. client.loop_start()
  2164. # Wait for connection result (max 5 seconds)
  2165. import time
  2166. start_time = time.time()
  2167. while time.time() - start_time < 5:
  2168. if connection_result["connected"] or connection_result["error"]:
  2169. break
  2170. await asyncio.sleep(0.1)
  2171. client.loop_stop()
  2172. client.disconnect()
  2173. if connection_result["connected"]:
  2174. return {"success": True, "message": "Successfully connected to MQTT broker"}
  2175. elif connection_result["error"]:
  2176. return JSONResponse(
  2177. content={"success": False, "message": connection_result["error"]},
  2178. status_code=400
  2179. )
  2180. else:
  2181. return JSONResponse(
  2182. content={"success": False, "message": "Connection timed out. Check broker address and port."},
  2183. status_code=400
  2184. )
  2185. except Exception as e:
  2186. logger.error(f"MQTT test connection failed: {str(e)}")
  2187. return JSONResponse(
  2188. content={"success": False, "message": str(e)},
  2189. status_code=500
  2190. )
  2191. def _read_and_encode_preview(cache_path: str) -> str:
  2192. """Read preview image from disk and encode as base64.
  2193. Combines file I/O and base64 encoding in a single function
  2194. to be run in executor, reducing context switches.
  2195. """
  2196. with open(cache_path, 'rb') as f:
  2197. image_data = f.read()
  2198. return base64.b64encode(image_data).decode('utf-8')
  2199. @app.post("/preview_thr_batch")
  2200. async def preview_thr_batch(request: dict):
  2201. start = time.time()
  2202. if not request.get("file_names"):
  2203. logger.warning("Batch preview request received without filenames")
  2204. raise HTTPException(status_code=400, detail="No file names provided")
  2205. file_names = request["file_names"]
  2206. if not isinstance(file_names, list):
  2207. raise HTTPException(status_code=400, detail="file_names must be a list")
  2208. headers = {
  2209. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  2210. "Content-Type": "application/json"
  2211. }
  2212. async def process_single_file(file_name):
  2213. """Process a single file and return its preview data."""
  2214. # Acquire semaphore to limit concurrent processing
  2215. async with preview_semaphore:
  2216. t1 = time.time()
  2217. try:
  2218. # Normalize file path for cross-platform compatibility
  2219. normalized_file_name = normalize_file_path(file_name)
  2220. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  2221. # Check file existence asynchronously
  2222. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  2223. if not exists:
  2224. logger.warning(f"Pattern file not found: {pattern_file_path}")
  2225. return file_name, {"error": "Pattern file not found"}
  2226. cache_path = get_cache_path(normalized_file_name)
  2227. # Check cache existence asynchronously
  2228. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  2229. if not cache_exists:
  2230. logger.info(f"Cache miss for {file_name}. Generating preview...")
  2231. success = await generate_image_preview(normalized_file_name)
  2232. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  2233. if not success or not cache_exists_after:
  2234. logger.error(f"Failed to generate or find preview for {file_name}")
  2235. return file_name, {"error": "Failed to generate preview"}
  2236. metadata = get_pattern_metadata(normalized_file_name)
  2237. if metadata:
  2238. first_coord_obj = metadata.get('first_coordinate')
  2239. last_coord_obj = metadata.get('last_coordinate')
  2240. else:
  2241. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  2242. # Use process pool for CPU-intensive parsing
  2243. loop = asyncio.get_running_loop()
  2244. coordinates = await loop.run_in_executor(pool_module.get_pool(), parse_theta_rho_file, pattern_file_path)
  2245. first_coord = coordinates[0] if coordinates else None
  2246. last_coord = coordinates[-1] if coordinates else None
  2247. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  2248. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  2249. # Read image file and encode in executor to avoid blocking event loop
  2250. loop = asyncio.get_running_loop()
  2251. image_b64 = await loop.run_in_executor(None, _read_and_encode_preview, cache_path)
  2252. result = {
  2253. "image_data": f"data:image/webp;base64,{image_b64}",
  2254. "first_coordinate": first_coord_obj,
  2255. "last_coordinate": last_coord_obj
  2256. }
  2257. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  2258. return file_name, result
  2259. except Exception as e:
  2260. logger.error(f"Error processing {file_name}: {str(e)}")
  2261. return file_name, {"error": str(e)}
  2262. # Process all files concurrently
  2263. tasks = [process_single_file(file_name) for file_name in file_names]
  2264. file_results = await asyncio.gather(*tasks)
  2265. # Convert results to dictionary
  2266. results = dict(file_results)
  2267. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  2268. return JSONResponse(content=results, headers=headers)
  2269. @app.get("/playlists")
  2270. async def playlists_page(request: Request):
  2271. return get_redirect_response(request)
  2272. @app.get("/image2sand")
  2273. async def image2sand_page(request: Request):
  2274. return get_redirect_response(request)
  2275. @app.get("/led")
  2276. async def led_control_page(request: Request):
  2277. return get_redirect_response(request)
  2278. # DW LED control endpoints
  2279. @app.get("/api/dw_leds/status")
  2280. async def dw_leds_status():
  2281. """Get DW LED controller status"""
  2282. if not state.led_controller or state.led_provider != "dw_leds":
  2283. return {"connected": False, "message": "DW LEDs not configured"}
  2284. try:
  2285. return state.led_controller.check_status()
  2286. except Exception as e:
  2287. logger.error(f"Failed to check DW LED status: {str(e)}")
  2288. return {"connected": False, "message": str(e)}
  2289. @app.post("/api/dw_leds/power")
  2290. async def dw_leds_power(request: dict):
  2291. """Control DW LED power (0=off, 1=on, 2=toggle)"""
  2292. if not state.led_controller or state.led_provider != "dw_leds":
  2293. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2294. state_value = request.get("state", 1)
  2295. if state_value not in [0, 1, 2]:
  2296. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  2297. try:
  2298. result = state.led_controller.set_power(state_value)
  2299. # Reset idle timeout when LEDs are manually powered on (only if idle timeout is enabled)
  2300. # This prevents idle timeout from immediately turning them back off
  2301. if state_value in [1, 2] and state.dw_led_idle_timeout_enabled: # Power on or toggle
  2302. state.dw_led_last_activity_time = time.time()
  2303. logger.debug(f"LED activity time reset due to manual power on")
  2304. return result
  2305. except Exception as e:
  2306. logger.error(f"Failed to set DW LED power: {str(e)}")
  2307. raise HTTPException(status_code=500, detail=str(e))
  2308. @app.post("/api/dw_leds/brightness")
  2309. async def dw_leds_brightness(request: dict):
  2310. """Set DW LED brightness (0-100)"""
  2311. if not state.led_controller or state.led_provider != "dw_leds":
  2312. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2313. value = request.get("value", 50)
  2314. if not 0 <= value <= 100:
  2315. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  2316. try:
  2317. controller = state.led_controller.get_controller()
  2318. result = controller.set_brightness(value)
  2319. # Update state if successful
  2320. if result.get("connected"):
  2321. state.dw_led_brightness = value
  2322. state.save()
  2323. return result
  2324. except Exception as e:
  2325. logger.error(f"Failed to set DW LED brightness: {str(e)}")
  2326. raise HTTPException(status_code=500, detail=str(e))
  2327. @app.post("/api/dw_leds/color")
  2328. async def dw_leds_color(request: dict):
  2329. """Set solid color (manual UI control - always powers on LEDs)"""
  2330. if not state.led_controller or state.led_provider != "dw_leds":
  2331. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2332. # Accept both formats: {"r": 255, "g": 0, "b": 0} or {"color": [255, 0, 0]}
  2333. if "color" in request:
  2334. color = request["color"]
  2335. if not isinstance(color, list) or len(color) != 3:
  2336. raise HTTPException(status_code=400, detail="Color must be [R, G, B] array")
  2337. r, g, b = color[0], color[1], color[2]
  2338. elif "r" in request and "g" in request and "b" in request:
  2339. r = request["r"]
  2340. g = request["g"]
  2341. b = request["b"]
  2342. else:
  2343. raise HTTPException(status_code=400, detail="Color must include r, g, b fields or color array")
  2344. try:
  2345. controller = state.led_controller.get_controller()
  2346. # Power on LEDs when user manually sets color via UI
  2347. controller.set_power(1)
  2348. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2349. if state.dw_led_idle_timeout_enabled:
  2350. state.dw_led_last_activity_time = time.time()
  2351. return controller.set_color(r, g, b)
  2352. except Exception as e:
  2353. logger.error(f"Failed to set DW LED color: {str(e)}")
  2354. raise HTTPException(status_code=500, detail=str(e))
  2355. @app.post("/api/dw_leds/colors")
  2356. async def dw_leds_colors(request: dict):
  2357. """Set effect colors (color1, color2, color3) - manual UI control - always powers on LEDs"""
  2358. if not state.led_controller or state.led_provider != "dw_leds":
  2359. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2360. # Parse colors from request
  2361. color1 = None
  2362. color2 = None
  2363. color3 = None
  2364. if "color1" in request:
  2365. c = request["color1"]
  2366. if isinstance(c, list) and len(c) == 3:
  2367. color1 = tuple(c)
  2368. else:
  2369. raise HTTPException(status_code=400, detail="color1 must be [R, G, B] array")
  2370. if "color2" in request:
  2371. c = request["color2"]
  2372. if isinstance(c, list) and len(c) == 3:
  2373. color2 = tuple(c)
  2374. else:
  2375. raise HTTPException(status_code=400, detail="color2 must be [R, G, B] array")
  2376. if "color3" in request:
  2377. c = request["color3"]
  2378. if isinstance(c, list) and len(c) == 3:
  2379. color3 = tuple(c)
  2380. else:
  2381. raise HTTPException(status_code=400, detail="color3 must be [R, G, B] array")
  2382. if not any([color1, color2, color3]):
  2383. raise HTTPException(status_code=400, detail="Must provide at least one color")
  2384. try:
  2385. controller = state.led_controller.get_controller()
  2386. # Power on LEDs when user manually sets colors via UI
  2387. controller.set_power(1)
  2388. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2389. if state.dw_led_idle_timeout_enabled:
  2390. state.dw_led_last_activity_time = time.time()
  2391. return controller.set_colors(color1=color1, color2=color2, color3=color3)
  2392. except Exception as e:
  2393. logger.error(f"Failed to set DW LED colors: {str(e)}")
  2394. raise HTTPException(status_code=500, detail=str(e))
  2395. @app.get("/api/dw_leds/effects")
  2396. async def dw_leds_effects():
  2397. """Get list of available effects"""
  2398. if not state.led_controller or state.led_provider != "dw_leds":
  2399. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2400. try:
  2401. controller = state.led_controller.get_controller()
  2402. effects = controller.get_effects()
  2403. # Convert tuples to lists for JSON serialization
  2404. effects_list = [[eid, name] for eid, name in effects]
  2405. return {
  2406. "success": True,
  2407. "effects": effects_list
  2408. }
  2409. except Exception as e:
  2410. logger.error(f"Failed to get DW LED effects: {str(e)}")
  2411. raise HTTPException(status_code=500, detail=str(e))
  2412. @app.get("/api/dw_leds/palettes")
  2413. async def dw_leds_palettes():
  2414. """Get list of available palettes"""
  2415. if not state.led_controller or state.led_provider != "dw_leds":
  2416. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2417. try:
  2418. controller = state.led_controller.get_controller()
  2419. palettes = controller.get_palettes()
  2420. # Convert tuples to lists for JSON serialization
  2421. palettes_list = [[pid, name] for pid, name in palettes]
  2422. return {
  2423. "success": True,
  2424. "palettes": palettes_list
  2425. }
  2426. except Exception as e:
  2427. logger.error(f"Failed to get DW LED palettes: {str(e)}")
  2428. raise HTTPException(status_code=500, detail=str(e))
  2429. @app.post("/api/dw_leds/effect")
  2430. async def dw_leds_effect(request: dict):
  2431. """Set effect by ID (manual UI control - always powers on LEDs)"""
  2432. if not state.led_controller or state.led_provider != "dw_leds":
  2433. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2434. effect_id = request.get("effect_id", 0)
  2435. speed = request.get("speed")
  2436. intensity = request.get("intensity")
  2437. try:
  2438. controller = state.led_controller.get_controller()
  2439. # Power on LEDs when user manually sets effect via UI
  2440. controller.set_power(1)
  2441. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2442. if state.dw_led_idle_timeout_enabled:
  2443. state.dw_led_last_activity_time = time.time()
  2444. return controller.set_effect(effect_id, speed=speed, intensity=intensity)
  2445. except Exception as e:
  2446. logger.error(f"Failed to set DW LED effect: {str(e)}")
  2447. raise HTTPException(status_code=500, detail=str(e))
  2448. @app.post("/api/dw_leds/palette")
  2449. async def dw_leds_palette(request: dict):
  2450. """Set palette by ID (manual UI control - always powers on LEDs)"""
  2451. if not state.led_controller or state.led_provider != "dw_leds":
  2452. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2453. palette_id = request.get("palette_id", 0)
  2454. try:
  2455. controller = state.led_controller.get_controller()
  2456. # Power on LEDs when user manually sets palette via UI
  2457. controller.set_power(1)
  2458. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2459. if state.dw_led_idle_timeout_enabled:
  2460. state.dw_led_last_activity_time = time.time()
  2461. return controller.set_palette(palette_id)
  2462. except Exception as e:
  2463. logger.error(f"Failed to set DW LED palette: {str(e)}")
  2464. raise HTTPException(status_code=500, detail=str(e))
  2465. @app.post("/api/dw_leds/speed")
  2466. async def dw_leds_speed(request: dict):
  2467. """Set effect speed (0-255)"""
  2468. if not state.led_controller or state.led_provider != "dw_leds":
  2469. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2470. value = request.get("speed", 128)
  2471. if not 0 <= value <= 255:
  2472. raise HTTPException(status_code=400, detail="Speed must be between 0 and 255")
  2473. try:
  2474. controller = state.led_controller.get_controller()
  2475. result = controller.set_speed(value)
  2476. # Save speed to state
  2477. state.dw_led_speed = value
  2478. state.save()
  2479. return result
  2480. except Exception as e:
  2481. logger.error(f"Failed to set DW LED speed: {str(e)}")
  2482. raise HTTPException(status_code=500, detail=str(e))
  2483. @app.post("/api/dw_leds/intensity")
  2484. async def dw_leds_intensity(request: dict):
  2485. """Set effect intensity (0-255)"""
  2486. if not state.led_controller or state.led_provider != "dw_leds":
  2487. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2488. value = request.get("intensity", 128)
  2489. if not 0 <= value <= 255:
  2490. raise HTTPException(status_code=400, detail="Intensity must be between 0 and 255")
  2491. try:
  2492. controller = state.led_controller.get_controller()
  2493. result = controller.set_intensity(value)
  2494. # Save intensity to state
  2495. state.dw_led_intensity = value
  2496. state.save()
  2497. return result
  2498. except Exception as e:
  2499. logger.error(f"Failed to set DW LED intensity: {str(e)}")
  2500. raise HTTPException(status_code=500, detail=str(e))
  2501. @app.post("/api/dw_leds/save_effect_settings")
  2502. async def dw_leds_save_effect_settings(request: dict):
  2503. """Save current LED settings as idle or playing effect"""
  2504. effect_type = request.get("type") # 'idle' or 'playing'
  2505. settings = {
  2506. "effect_id": request.get("effect_id"),
  2507. "palette_id": request.get("palette_id"),
  2508. "speed": request.get("speed"),
  2509. "intensity": request.get("intensity"),
  2510. "color1": request.get("color1"),
  2511. "color2": request.get("color2"),
  2512. "color3": request.get("color3")
  2513. }
  2514. if effect_type == "idle":
  2515. state.dw_led_idle_effect = settings
  2516. elif effect_type == "playing":
  2517. state.dw_led_playing_effect = settings
  2518. else:
  2519. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2520. state.save()
  2521. logger.info(f"DW LED {effect_type} effect settings saved: {settings}")
  2522. return {"success": True, "type": effect_type, "settings": settings}
  2523. @app.post("/api/dw_leds/clear_effect_settings")
  2524. async def dw_leds_clear_effect_settings(request: dict):
  2525. """Clear idle or playing effect settings"""
  2526. effect_type = request.get("type") # 'idle' or 'playing'
  2527. if effect_type == "idle":
  2528. state.dw_led_idle_effect = None
  2529. elif effect_type == "playing":
  2530. state.dw_led_playing_effect = None
  2531. else:
  2532. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2533. state.save()
  2534. logger.info(f"DW LED {effect_type} effect settings cleared")
  2535. return {"success": True, "type": effect_type}
  2536. @app.get("/api/dw_leds/get_effect_settings")
  2537. async def dw_leds_get_effect_settings():
  2538. """Get saved idle and playing effect settings"""
  2539. return {
  2540. "idle_effect": state.dw_led_idle_effect,
  2541. "playing_effect": state.dw_led_playing_effect
  2542. }
  2543. @app.post("/api/dw_leds/idle_timeout")
  2544. async def dw_leds_set_idle_timeout(request: dict):
  2545. """Configure LED idle timeout settings"""
  2546. enabled = request.get("enabled", False)
  2547. minutes = request.get("minutes", 30)
  2548. # Validate minutes (between 1 and 1440 - 24 hours)
  2549. if minutes < 1 or minutes > 1440:
  2550. raise HTTPException(status_code=400, detail="Timeout must be between 1 and 1440 minutes")
  2551. state.dw_led_idle_timeout_enabled = enabled
  2552. state.dw_led_idle_timeout_minutes = minutes
  2553. # Reset activity time when settings change
  2554. import time
  2555. state.dw_led_last_activity_time = time.time()
  2556. state.save()
  2557. logger.info(f"DW LED idle timeout configured: enabled={enabled}, minutes={minutes}")
  2558. return {
  2559. "success": True,
  2560. "enabled": enabled,
  2561. "minutes": minutes
  2562. }
  2563. @app.get("/api/dw_leds/idle_timeout")
  2564. async def dw_leds_get_idle_timeout():
  2565. """Get LED idle timeout settings"""
  2566. import time
  2567. # Calculate remaining time if timeout is active
  2568. remaining_minutes = None
  2569. if state.dw_led_idle_timeout_enabled and state.dw_led_last_activity_time:
  2570. elapsed_seconds = time.time() - state.dw_led_last_activity_time
  2571. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  2572. remaining_seconds = max(0, timeout_seconds - elapsed_seconds)
  2573. remaining_minutes = round(remaining_seconds / 60, 1)
  2574. return {
  2575. "enabled": state.dw_led_idle_timeout_enabled,
  2576. "minutes": state.dw_led_idle_timeout_minutes,
  2577. "remaining_minutes": remaining_minutes
  2578. }
  2579. @app.get("/table_control")
  2580. async def table_control_page(request: Request):
  2581. return get_redirect_response(request)
  2582. @app.get("/cache-progress")
  2583. async def get_cache_progress_endpoint():
  2584. """Get the current cache generation progress."""
  2585. from modules.core.cache_manager import get_cache_progress
  2586. return get_cache_progress()
  2587. @app.post("/rebuild_cache")
  2588. async def rebuild_cache_endpoint():
  2589. """Trigger a rebuild of the pattern cache."""
  2590. try:
  2591. from modules.core.cache_manager import rebuild_cache
  2592. await rebuild_cache()
  2593. return {"success": True, "message": "Cache rebuild completed successfully"}
  2594. except Exception as e:
  2595. logger.error(f"Failed to rebuild cache: {str(e)}")
  2596. raise HTTPException(status_code=500, detail=str(e))
  2597. def signal_handler(signum, frame):
  2598. """Handle shutdown signals gracefully."""
  2599. logger.info("Received shutdown signal, cleaning up...")
  2600. try:
  2601. # Turn off all LEDs on shutdown
  2602. if state.led_controller:
  2603. state.led_controller.set_power(0)
  2604. # Shutdown process pool to prevent semaphore leaks
  2605. pool_module.shutdown_pool(wait=False, cancel_futures=True)
  2606. # Stop pattern manager motion controller
  2607. pattern_manager.motion_controller.stop()
  2608. # Set stop flags to halt any running patterns
  2609. state.stop_requested = True
  2610. state.pause_requested = False
  2611. state.save()
  2612. logger.info("Cleanup completed")
  2613. except Exception as e:
  2614. logger.error(f"Error during cleanup: {str(e)}")
  2615. finally:
  2616. logger.info("Exiting application...")
  2617. # Use os._exit after cleanup is complete to avoid async stack tracebacks
  2618. # This is safe because we've already: shut down process pool, stopped motion controller, saved state
  2619. os._exit(0)
  2620. @app.get("/api/version")
  2621. async def get_version_info(force_refresh: bool = False):
  2622. """Get current and latest version information
  2623. Args:
  2624. force_refresh: If true, bypass cache and fetch fresh data from GitHub
  2625. """
  2626. try:
  2627. version_info = await version_manager.get_version_info(force_refresh=force_refresh)
  2628. return JSONResponse(content=version_info)
  2629. except Exception as e:
  2630. logger.error(f"Error getting version info: {e}")
  2631. return JSONResponse(
  2632. content={
  2633. "current": await version_manager.get_current_version(),
  2634. "latest": await version_manager.get_current_version(),
  2635. "update_available": False,
  2636. "error": "Unable to check for updates"
  2637. },
  2638. status_code=200
  2639. )
  2640. @app.post("/api/update")
  2641. async def trigger_update():
  2642. """Trigger software update by pulling latest Docker images and recreating containers."""
  2643. try:
  2644. logger.info("Update triggered via API")
  2645. success, error_message, error_log = update_manager.update_software()
  2646. if success:
  2647. return JSONResponse(content={
  2648. "success": True,
  2649. "message": "Update started. Containers are being recreated with the latest images. The page will reload shortly."
  2650. })
  2651. else:
  2652. return JSONResponse(content={
  2653. "success": False,
  2654. "message": error_message or "Update failed",
  2655. "errors": error_log
  2656. })
  2657. except Exception as e:
  2658. logger.error(f"Error triggering update: {e}")
  2659. return JSONResponse(
  2660. content={"success": False, "message": f"Failed to trigger update: {str(e)}"},
  2661. status_code=500
  2662. )
  2663. @app.post("/api/system/shutdown")
  2664. async def shutdown_system():
  2665. """Shutdown the system"""
  2666. try:
  2667. logger.warning("Shutdown initiated via API")
  2668. # Schedule shutdown command after a short delay to allow response to be sent
  2669. def delayed_shutdown():
  2670. time.sleep(2) # Give time for response to be sent
  2671. try:
  2672. # Use systemctl to shutdown the host (via mounted systemd socket)
  2673. subprocess.run(["systemctl", "poweroff"], check=True)
  2674. logger.info("Host shutdown command executed successfully via systemctl")
  2675. except FileNotFoundError:
  2676. logger.error("systemctl command not found - ensure systemd volumes are mounted")
  2677. except Exception as e:
  2678. logger.error(f"Error executing host shutdown command: {e}")
  2679. import threading
  2680. shutdown_thread = threading.Thread(target=delayed_shutdown)
  2681. shutdown_thread.start()
  2682. return {"success": True, "message": "System shutdown initiated"}
  2683. except Exception as e:
  2684. logger.error(f"Error initiating shutdown: {e}")
  2685. return JSONResponse(
  2686. content={"success": False, "message": str(e)},
  2687. status_code=500
  2688. )
  2689. @app.post("/api/system/restart")
  2690. async def restart_system():
  2691. """Restart the Docker containers using docker compose"""
  2692. try:
  2693. logger.warning("Restart initiated via API")
  2694. # Schedule restart command after a short delay to allow response to be sent
  2695. def delayed_restart():
  2696. time.sleep(2) # Give time for response to be sent
  2697. try:
  2698. # Use docker restart directly with container name
  2699. # This is simpler and doesn't require the compose file path
  2700. subprocess.run(["docker", "restart", "dune-weaver-backend"], check=True)
  2701. logger.info("Docker restart command executed successfully")
  2702. except FileNotFoundError:
  2703. logger.error("docker command not found")
  2704. except Exception as e:
  2705. logger.error(f"Error executing docker restart: {e}")
  2706. import threading
  2707. restart_thread = threading.Thread(target=delayed_restart)
  2708. restart_thread.start()
  2709. return {"success": True, "message": "System restart initiated"}
  2710. except Exception as e:
  2711. logger.error(f"Error initiating restart: {e}")
  2712. return JSONResponse(
  2713. content={"success": False, "message": str(e)},
  2714. status_code=500
  2715. )
  2716. def entrypoint():
  2717. import uvicorn
  2718. logger.info("Starting FastAPI server on port 8080...")
  2719. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  2720. if __name__ == "__main__":
  2721. entrypoint()