main.py 131 KB

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