main.py 132 KB

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