main.py 122 KB

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