main.py 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect, Request
  2. from fastapi.responses import JSONResponse, FileResponse
  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
  8. import os
  9. import logging
  10. from datetime import datetime
  11. from modules.connection import connection_manager
  12. from modules.core import pattern_manager
  13. from modules.core.pattern_manager import parse_theta_rho_file, THETA_RHO_DIR
  14. from modules.core import playlist_manager
  15. from modules.core import board_settings
  16. from modules.core import execution
  17. from modules.update import update_manager
  18. from modules.core.state import state
  19. from modules import mqtt
  20. import signal
  21. import asyncio
  22. from contextlib import asynccontextmanager
  23. from modules.led.led_interface import LEDInterface
  24. from modules.screen.screen_controller import ScreenController
  25. from modules.led.idle_timeout_manager import idle_timeout_manager
  26. from modules.core.cache_manager import get_cache_path, generate_image_preview, get_pattern_metadata
  27. from modules.core.version_manager import version_manager
  28. from modules.core.mdns_discovery import discovery as mdns_discovery
  29. from modules.core.log_handler import init_memory_handler, get_memory_handler
  30. from modules.wifi.router import router as wifi_router, captive_portal_router
  31. import json
  32. import base64
  33. import hashlib
  34. import time
  35. import subprocess
  36. # Get log level from environment variable, default to INFO
  37. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  38. log_level = getattr(logging, log_level_str, logging.INFO)
  39. logging.basicConfig(
  40. level=log_level,
  41. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  42. handlers=[
  43. logging.StreamHandler(),
  44. ]
  45. )
  46. # Initialize memory log handler for web UI log viewer
  47. # Increased to 5000 entries to support lazy loading in the UI
  48. init_memory_handler(max_entries=5000)
  49. logger = logging.getLogger(__name__)
  50. async def _check_table_is_idle() -> bool:
  51. """Helper function to check if table is idle."""
  52. return not state.current_playing_file or state.pause_requested
  53. def _start_idle_led_timeout():
  54. """Start idle LED timeout if enabled."""
  55. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  56. return
  57. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  58. idle_timeout_manager.start_idle_timeout(
  59. timeout_minutes=state.dw_led_idle_timeout_minutes,
  60. state=state,
  61. check_idle_callback=_check_table_is_idle
  62. )
  63. def check_homing_in_progress():
  64. """Check if homing is in progress and raise exception if so."""
  65. if state.is_homing:
  66. raise HTTPException(status_code=409, detail="Cannot perform this action while homing is in progress")
  67. def normalize_file_path(file_path: str) -> str:
  68. """Normalize file path separators for consistent cross-platform handling."""
  69. if not file_path:
  70. return ''
  71. # First normalize path separators
  72. normalized = file_path.replace('\\', '/')
  73. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  74. if normalized.startswith('./patterns/'):
  75. normalized = normalized[11:]
  76. elif normalized.startswith('patterns/'):
  77. normalized = normalized[9:]
  78. return normalized
  79. @asynccontextmanager
  80. async def lifespan(app: FastAPI):
  81. # Startup
  82. logger.info("Starting Dune Weaver application...")
  83. # Register signal handlers
  84. signal.signal(signal.SIGINT, signal_handler)
  85. signal.signal(signal.SIGTERM, signal_handler)
  86. # Connect device in background so the web server starts immediately
  87. async def connect_and_home():
  88. """Connect to device and perform homing in background."""
  89. try:
  90. # Connect without homing first (fast)
  91. await asyncio.to_thread(connection_manager.connect_device, False)
  92. # If connected, perform homing in background (unless disabled)
  93. if state.conn and state.conn.is_connected():
  94. if not state.home_on_connect:
  95. logger.info("Device connected. Home-on-connect is disabled — skipping automatic homing.")
  96. else:
  97. logger.info("Device connected, starting homing in background...")
  98. state.is_homing = True
  99. try:
  100. success = await asyncio.to_thread(connection_manager.home)
  101. if not success:
  102. logger.warning("Background homing failed or was skipped")
  103. # If sensor homing failed, close connection and wait for user action
  104. if state.sensor_homing_failed:
  105. logger.error("Sensor homing failed - closing connection. User must check sensor or switch to crash homing.")
  106. if state.conn:
  107. await asyncio.to_thread(state.conn.close)
  108. state.conn = None
  109. return # Don't proceed with auto-play
  110. finally:
  111. state.is_homing = False
  112. logger.info("Background homing completed")
  113. # Auto-play on boot lives on the board ($Playlist/Autostart,
  114. # set via Settings) — nothing to do host-side.
  115. except Exception as e:
  116. logger.warning(f"Failed to auto-connect to board: {str(e)}")
  117. # Start connection/homing in background - doesn't block server startup
  118. asyncio.create_task(connect_and_home())
  119. # The board observer is the single status loop: it polls /sand_status,
  120. # translates it into the /ws/status contract, logs play history on file
  121. # transitions, runs the clear-speed and WLED quiet-hours shims, adopts
  122. # board-side Still Sands edits, and broadcasts to all clients.
  123. execution.observer.on_status = broadcast_status_update
  124. execution.observer.start()
  125. # Initialize LED controller based on saved configuration
  126. try:
  127. # Auto-detect provider for backward compatibility with existing installations
  128. if not state.led_provider or state.led_provider == "none":
  129. if state.wled_ip:
  130. state.led_provider = "wled"
  131. logger.info("Auto-detected WLED provider from existing configuration")
  132. # Initialize the appropriate controller
  133. if state.led_provider == "wled" and state.wled_ip:
  134. state.led_controller = LEDInterface("wled", state.wled_ip)
  135. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  136. elif state.led_provider == "board":
  137. state.led_controller = LEDInterface("board")
  138. logger.info("LED controller initialized: table's built-in LEDs (firmware-controlled)")
  139. else:
  140. if state.led_provider == "dw_leds":
  141. # Host GPIO NeoPixels were removed — the table's own ring
  142. # (firmware-controlled) replaced them.
  143. logger.warning("LED provider 'dw_leds' no longer exists; "
  144. "select 'Table LEDs' in Settings")
  145. state.led_controller = None
  146. logger.info("LED controller not configured")
  147. # Save if provider was auto-detected
  148. if state.led_provider and state.wled_ip:
  149. state.save()
  150. except Exception as e:
  151. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  152. state.led_controller = None
  153. # Initialize screen controller for LCD backlight control
  154. try:
  155. state.screen_controller = ScreenController()
  156. if state.screen_controller.available:
  157. logger.info("Screen controller initialized (backlight control available)")
  158. else:
  159. logger.info("Screen controller initialized (no backlight device found)")
  160. except Exception as e:
  161. logger.warning(f"Failed to initialize screen controller: {e}")
  162. state.screen_controller = None
  163. # Note: auto_play is now handled in connect_and_home() after homing completes
  164. try:
  165. mqtt.init_mqtt()
  166. except Exception as e:
  167. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  168. # Schedule cache generation check for later (non-blocking startup)
  169. async def delayed_cache_check():
  170. """Check and generate cache in background."""
  171. try:
  172. logger.info("Starting cache check...")
  173. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  174. if await is_cache_generation_needed_async():
  175. logger.info("Cache generation needed, starting background task...")
  176. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  177. else:
  178. logger.info("Cache is up to date, skipping generation")
  179. except Exception as e:
  180. logger.warning(f"Failed during cache generation: {str(e)}")
  181. # Start cache check in background immediately
  182. asyncio.create_task(delayed_cache_check())
  183. # Advertise this table via mDNS and browse for peer tables (best-effort)
  184. try:
  185. await mdns_discovery.start(
  186. table_id=state.table_id,
  187. table_name=state.table_name,
  188. port=8080,
  189. version=await version_manager.get_current_version(),
  190. )
  191. except Exception as e:
  192. logger.warning(f"mDNS table discovery unavailable: {e}")
  193. yield # This separates startup from shutdown code
  194. # Shutdown
  195. logger.info("Shutting down Dune Weaver application...")
  196. await mdns_discovery.stop()
  197. app = FastAPI(lifespan=lifespan)
  198. # Add CORS middleware to allow cross-origin requests from other Dune Weaver frontends
  199. # This enables multi-table control from a single frontend
  200. # Note: allow_credentials must be False when allow_origins=["*"] (browser security requirement)
  201. app.add_middleware(
  202. CORSMiddleware,
  203. allow_origins=["*"], # Allow all origins for local network access
  204. allow_credentials=False,
  205. allow_methods=["*"],
  206. allow_headers=["*"],
  207. )
  208. templates = Jinja2Templates(directory="templates")
  209. app.mount("/static", StaticFiles(directory="static"), name="static")
  210. # Include WiFi management router
  211. app.include_router(wifi_router)
  212. app.include_router(captive_portal_router)
  213. # Global semaphore to limit concurrent preview processing
  214. # Prevents resource exhaustion when loading many previews simultaneously
  215. # Lazily initialized to avoid "attached to a different loop" errors
  216. _preview_semaphore: Optional[asyncio.Semaphore] = None
  217. def get_preview_semaphore() -> asyncio.Semaphore:
  218. """Get or create the preview semaphore in the current event loop."""
  219. global _preview_semaphore
  220. if _preview_semaphore is None:
  221. _preview_semaphore = asyncio.Semaphore(5)
  222. return _preview_semaphore
  223. # Pydantic models for request/response validation
  224. class ConnectRequest(BaseModel):
  225. port: Optional[str] = None
  226. class auto_playModeRequest(BaseModel):
  227. enabled: bool
  228. playlist: Optional[str] = None
  229. run_mode: Optional[str] = "loop"
  230. pause_time: Optional[float] = 5.0
  231. clear_pattern: Optional[str] = "adaptive"
  232. shuffle: Optional[bool] = False
  233. class TimeSlot(BaseModel):
  234. start_time: str # HH:MM format
  235. end_time: str # HH:MM format
  236. days: str # "daily", "weekdays", "weekends", or "custom"
  237. custom_days: Optional[List[str]] = [] # ["monday", "tuesday", etc.]
  238. class ScheduledPauseRequest(BaseModel):
  239. enabled: bool
  240. control_wled: Optional[bool] = False
  241. finish_pattern: Optional[bool] = False # Finish current pattern before pausing
  242. timezone: Optional[str] = None # IANA timezone or None for system default
  243. time_slots: List[TimeSlot] = []
  244. class CoordinateRequest(BaseModel):
  245. theta: float
  246. rho: float
  247. class PlaylistRequest(BaseModel):
  248. playlist_name: str
  249. files: List[str] = []
  250. pause_time: float = 0
  251. clear_pattern: Optional[str] = None
  252. run_mode: str = "single"
  253. shuffle: bool = False
  254. class PlaylistRunRequest(BaseModel):
  255. playlist_name: str
  256. pause_time: Optional[float] = 0
  257. clear_pattern: Optional[str] = None
  258. run_mode: Optional[str] = "single"
  259. shuffle: Optional[bool] = False
  260. start_time: Optional[str] = None
  261. end_time: Optional[str] = None
  262. class SpeedRequest(BaseModel):
  263. speed: float
  264. class WLEDRequest(BaseModel):
  265. wled_ip: Optional[str] = None
  266. class LEDConfigRequest(BaseModel):
  267. provider: str # "wled", "dw_leds", or "none"
  268. ip_address: Optional[str] = None # For WLED only
  269. # DW LED specific fields
  270. num_leds: Optional[int] = None
  271. gpio_pin: Optional[int] = None
  272. pixel_order: Optional[str] = None
  273. brightness: Optional[int] = None
  274. class DeletePlaylistRequest(BaseModel):
  275. playlist_name: str
  276. class RenamePlaylistRequest(BaseModel):
  277. old_name: str
  278. new_name: str
  279. class ThetaRhoRequest(BaseModel):
  280. file_name: str
  281. pre_execution: Optional[str] = "none"
  282. class GetCoordinatesRequest(BaseModel):
  283. file_name: str
  284. # ============================================================================
  285. # Unified Settings Models
  286. # ============================================================================
  287. class AppSettingsUpdate(BaseModel):
  288. name: Optional[str] = None
  289. custom_logo: Optional[str] = None # Filename or empty string to clear (favicon auto-generated)
  290. class PatternSettingsUpdate(BaseModel):
  291. clear_pattern_speed: Optional[int] = None
  292. custom_clear_from_in: Optional[str] = None
  293. custom_clear_from_out: Optional[str] = None
  294. class ScheduledPauseSettingsUpdate(BaseModel):
  295. enabled: Optional[bool] = None
  296. control_wled: Optional[bool] = None
  297. finish_pattern: Optional[bool] = None
  298. timezone: Optional[str] = None # IANA timezone (e.g., "America/New_York") or None for system default
  299. time_slots: Optional[List[TimeSlot]] = None
  300. class HomingSettingsUpdate(BaseModel):
  301. mode: Optional[int] = None
  302. angular_offset_degrees: Optional[float] = None
  303. home_on_connect: Optional[bool] = None # Auto-home after connecting on startup
  304. auto_home_enabled: Optional[bool] = None
  305. auto_home_after_patterns: Optional[int] = None
  306. hard_reset_theta: Optional[bool] = None # Enable hard reset ($Bye) when resetting theta
  307. class LedSettingsUpdate(BaseModel):
  308. provider: Optional[str] = None # "none", "wled", "board"
  309. wled_ip: Optional[str] = None
  310. control_mode: Optional[str] = None # "manual" or "automated"
  311. idle_timeout_enabled: Optional[bool] = None
  312. idle_timeout_minutes: Optional[int] = None
  313. class MqttSettingsUpdate(BaseModel):
  314. enabled: Optional[bool] = None
  315. broker: Optional[str] = None
  316. port: Optional[int] = None
  317. username: Optional[str] = None
  318. password: Optional[str] = None # Write-only, never returned in GET
  319. client_id: Optional[str] = None
  320. discovery_prefix: Optional[str] = None
  321. device_id: Optional[str] = None
  322. device_name: Optional[str] = None
  323. class MachineSettingsUpdate(BaseModel):
  324. timezone: Optional[str] = None # IANA timezone (e.g., "America/New_York", "UTC")
  325. class SecuritySettingsUpdate(BaseModel):
  326. mode: Optional[str] = None # "off", "lockdown", "play_only"
  327. password: Optional[str] = None # Write-only, stored as SHA-256 hash
  328. class SecurityVerifyRequest(BaseModel):
  329. password: str
  330. class SettingsUpdate(BaseModel):
  331. """Request model for PATCH /api/settings - all fields optional for partial updates"""
  332. app: Optional[AppSettingsUpdate] = None
  333. patterns: Optional[PatternSettingsUpdate] = None
  334. scheduled_pause: Optional[ScheduledPauseSettingsUpdate] = None
  335. homing: Optional[HomingSettingsUpdate] = None
  336. led: Optional[LedSettingsUpdate] = None
  337. mqtt: Optional[MqttSettingsUpdate] = None
  338. machine: Optional[MachineSettingsUpdate] = None
  339. security: Optional[SecuritySettingsUpdate] = None
  340. # Store active WebSocket connections
  341. active_status_connections = set()
  342. active_cache_progress_connections = set()
  343. @app.websocket("/ws/status")
  344. async def websocket_status_endpoint(websocket: WebSocket):
  345. """Status stream. The board observer pushes every update via
  346. broadcast_status_update; this handler only sends the cached snapshot on
  347. connect and then holds the socket open."""
  348. await websocket.accept()
  349. active_status_connections.add(websocket)
  350. try:
  351. await websocket.send_json({
  352. "type": "status_update",
  353. "data": execution.get_cached_status()
  354. })
  355. while True:
  356. # Drain any client messages (none are expected) until disconnect.
  357. await websocket.receive_text()
  358. except (WebSocketDisconnect, RuntimeError):
  359. pass
  360. finally:
  361. active_status_connections.discard(websocket)
  362. try:
  363. await websocket.close()
  364. except RuntimeError:
  365. pass
  366. async def broadcast_status_update(status: dict):
  367. """Broadcast status update to all connected clients."""
  368. disconnected = set()
  369. for websocket in active_status_connections:
  370. try:
  371. await websocket.send_json({
  372. "type": "status_update",
  373. "data": status
  374. })
  375. except WebSocketDisconnect:
  376. disconnected.add(websocket)
  377. except RuntimeError:
  378. disconnected.add(websocket)
  379. active_status_connections.difference_update(disconnected)
  380. @app.websocket("/ws/cache-progress")
  381. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  382. from modules.core.cache_manager import get_cache_progress
  383. await websocket.accept()
  384. active_cache_progress_connections.add(websocket)
  385. try:
  386. while True:
  387. progress = get_cache_progress()
  388. try:
  389. await websocket.send_json({
  390. "type": "cache_progress",
  391. "data": progress
  392. })
  393. except RuntimeError as e:
  394. if "close message has been sent" in str(e):
  395. break
  396. raise
  397. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  398. except WebSocketDisconnect:
  399. pass
  400. finally:
  401. active_cache_progress_connections.discard(websocket)
  402. try:
  403. await websocket.close()
  404. except RuntimeError:
  405. pass
  406. # WebSocket endpoint for real-time log streaming
  407. @app.websocket("/ws/logs")
  408. async def websocket_logs_endpoint(websocket: WebSocket):
  409. """Stream application logs in real-time via WebSocket."""
  410. await websocket.accept()
  411. handler = get_memory_handler()
  412. if not handler:
  413. await websocket.close()
  414. return
  415. # Subscribe to log updates
  416. log_queue = handler.subscribe()
  417. try:
  418. while True:
  419. try:
  420. # Wait for new log entry with timeout
  421. log_entry = await asyncio.wait_for(log_queue.get(), timeout=30.0)
  422. await websocket.send_json({
  423. "type": "log_entry",
  424. "data": log_entry
  425. })
  426. except asyncio.TimeoutError:
  427. # Send heartbeat to keep connection alive
  428. await websocket.send_json({"type": "heartbeat"})
  429. except RuntimeError as e:
  430. if "close message has been sent" in str(e):
  431. break
  432. raise
  433. except WebSocketDisconnect:
  434. pass
  435. finally:
  436. handler.unsubscribe(log_queue)
  437. try:
  438. await websocket.close()
  439. except RuntimeError:
  440. pass
  441. # API endpoint to retrieve logs
  442. @app.get("/api/logs", tags=["logs"])
  443. async def get_logs(limit: int = 100, level: str = None, offset: int = 0):
  444. """
  445. Retrieve application logs from memory buffer with pagination.
  446. Args:
  447. limit: Maximum number of log entries to return (default: 100)
  448. level: Filter by log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  449. offset: Number of entries to skip from newest (for lazy loading older logs)
  450. Returns:
  451. List of log entries with timestamp, level, logger, and message.
  452. Also returns total count and whether there are more logs available.
  453. """
  454. handler = get_memory_handler()
  455. if not handler:
  456. return {"logs": [], "count": 0, "total": 0, "has_more": False, "error": "Log handler not initialized"}
  457. # Clamp limit to reasonable range (no max limit for lazy loading)
  458. limit = max(1, limit)
  459. offset = max(0, offset)
  460. logs = handler.get_logs(limit=limit, level=level, offset=offset)
  461. total = handler.get_total_count(level=level)
  462. has_more = offset + len(logs) < total
  463. return {"logs": logs, "count": len(logs), "total": total, "has_more": has_more}
  464. @app.delete("/api/logs", tags=["logs"])
  465. async def clear_logs():
  466. """Clear all logs from the memory buffer."""
  467. handler = get_memory_handler()
  468. if handler:
  469. handler.clear()
  470. return {"status": "ok", "message": "Logs cleared"}
  471. # FastAPI routes - Redirect old frontend routes to new React frontend on port 80
  472. def get_redirect_response(request: Request):
  473. """Return redirect page pointing users to the new frontend."""
  474. host = request.headers.get("host", "localhost").split(":")[0] # Remove port if present
  475. return templates.TemplateResponse("redirect.html", {"request": request, "host": host})
  476. @app.get("/")
  477. async def index(request: Request):
  478. return get_redirect_response(request)
  479. @app.get("/settings")
  480. async def settings_page(request: Request):
  481. return get_redirect_response(request)
  482. # ============================================================================
  483. # Unified Settings API
  484. # ============================================================================
  485. @app.get("/api/settings", tags=["settings"])
  486. async def get_all_settings():
  487. """
  488. Get all application settings in a unified structure.
  489. This endpoint consolidates multiple settings endpoints into a single response.
  490. Individual settings endpoints are deprecated but still functional.
  491. """
  492. return {
  493. "app": {
  494. "name": state.app_name,
  495. "custom_logo": state.custom_logo
  496. },
  497. "patterns": {
  498. "clear_pattern_speed": state.clear_pattern_speed,
  499. "custom_clear_from_in": state.custom_clear_from_in,
  500. "custom_clear_from_out": state.custom_clear_from_out
  501. },
  502. "scheduled_pause": {
  503. "enabled": state.scheduled_pause_enabled,
  504. "control_wled": state.scheduled_pause_control_wled,
  505. "finish_pattern": state.scheduled_pause_finish_pattern,
  506. "timezone": state.scheduled_pause_timezone,
  507. "time_slots": state.scheduled_pause_time_slots
  508. },
  509. "homing": {
  510. "mode": state.homing,
  511. "user_override": state.homing_user_override, # True if user explicitly set, False if auto-detected
  512. "angular_offset_degrees": state.angular_homing_offset_degrees,
  513. "home_on_connect": state.home_on_connect,
  514. "auto_home_enabled": state.auto_home_enabled,
  515. "auto_home_after_patterns": state.auto_home_after_patterns,
  516. "hard_reset_theta": state.hard_reset_theta # Enable hard reset when resetting theta
  517. },
  518. "led": {
  519. "provider": state.led_provider,
  520. "wled_ip": state.wled_ip,
  521. "control_mode": state.dw_led_control_mode,
  522. "idle_timeout_enabled": state.dw_led_idle_timeout_enabled,
  523. "idle_timeout_minutes": state.dw_led_idle_timeout_minutes
  524. },
  525. "mqtt": {
  526. "enabled": state.mqtt_enabled,
  527. "broker": state.mqtt_broker,
  528. "port": state.mqtt_port,
  529. "username": state.mqtt_username,
  530. "has_password": bool(state.mqtt_password),
  531. "client_id": state.mqtt_client_id,
  532. "discovery_prefix": state.mqtt_discovery_prefix,
  533. "device_id": state.mqtt_device_id,
  534. "device_name": state.mqtt_device_name
  535. },
  536. "machine": {
  537. # Kinematics live in the board's config.yaml; the host only keeps a timezone.
  538. "timezone": state.timezone,
  539. },
  540. "security": {
  541. "mode": state.security_mode,
  542. "has_password": bool(state.security_password_hash)
  543. }
  544. }
  545. @app.get("/api/manifest.webmanifest", tags=["settings"])
  546. async def get_dynamic_manifest():
  547. """
  548. Get a dynamically generated web manifest.
  549. Returns manifest with custom icons and app name if custom branding is configured,
  550. otherwise returns defaults.
  551. """
  552. # Determine icon paths based on whether custom logo exists
  553. if state.custom_logo:
  554. icon_base = "/static/custom"
  555. else:
  556. icon_base = "/static"
  557. # Use custom app name or default
  558. app_name = state.app_name or "Dune Weaver"
  559. return {
  560. "name": app_name,
  561. "short_name": app_name,
  562. "description": "Control your kinetic sand table",
  563. "icons": [
  564. {
  565. "src": f"{icon_base}/android-chrome-192x192.png",
  566. "sizes": "192x192",
  567. "type": "image/png",
  568. "purpose": "any"
  569. },
  570. {
  571. "src": f"{icon_base}/android-chrome-512x512.png",
  572. "sizes": "512x512",
  573. "type": "image/png",
  574. "purpose": "any"
  575. },
  576. {
  577. "src": f"{icon_base}/android-chrome-192x192.png",
  578. "sizes": "192x192",
  579. "type": "image/png",
  580. "purpose": "maskable"
  581. },
  582. {
  583. "src": f"{icon_base}/android-chrome-512x512.png",
  584. "sizes": "512x512",
  585. "type": "image/png",
  586. "purpose": "maskable"
  587. }
  588. ],
  589. "start_url": "/",
  590. "scope": "/",
  591. "display": "standalone",
  592. "orientation": "any",
  593. "theme_color": "#0a0a0a",
  594. "background_color": "#0a0a0a",
  595. "categories": ["utilities", "entertainment"]
  596. }
  597. @app.patch("/api/settings", tags=["settings"])
  598. async def update_settings(settings_update: SettingsUpdate):
  599. """
  600. Partially update application settings.
  601. Only include the categories and fields you want to update.
  602. All fields are optional - only provided values will be updated.
  603. Example: {"app": {"name": "Dune Weaver"}, "auto_play": {"enabled": true}}
  604. """
  605. updated_categories = []
  606. requires_restart = False
  607. led_reinit_needed = False
  608. old_led_provider = state.led_provider
  609. # App settings
  610. if settings_update.app:
  611. if settings_update.app.name is not None:
  612. state.app_name = settings_update.app.name or "Dune Weaver"
  613. if settings_update.app.custom_logo is not None:
  614. state.custom_logo = settings_update.app.custom_logo or None
  615. updated_categories.append("app")
  616. # Pattern settings
  617. if settings_update.patterns:
  618. p = settings_update.patterns
  619. if p.clear_pattern_speed is not None:
  620. state.clear_pattern_speed = p.clear_pattern_speed if p.clear_pattern_speed > 0 else None
  621. if p.custom_clear_from_in is not None:
  622. state.custom_clear_from_in = p.custom_clear_from_in or None
  623. if p.custom_clear_from_out is not None:
  624. state.custom_clear_from_out = p.custom_clear_from_out or None
  625. # The firmware runs its own clear files; mirror custom choices onto them.
  626. if p.custom_clear_from_in is not None or p.custom_clear_from_out is not None:
  627. board_settings.push_custom_clears_async()
  628. updated_categories.append("patterns")
  629. # Scheduled pause (Still Sands) settings
  630. if settings_update.scheduled_pause:
  631. sp = settings_update.scheduled_pause
  632. if sp.enabled is not None:
  633. state.scheduled_pause_enabled = sp.enabled
  634. if sp.control_wled is not None:
  635. state.scheduled_pause_control_wled = sp.control_wled
  636. if sp.finish_pattern is not None:
  637. state.scheduled_pause_finish_pattern = sp.finish_pattern
  638. if sp.timezone is not None:
  639. # Empty string means use system default (store as None)
  640. state.scheduled_pause_timezone = sp.timezone if sp.timezone else None
  641. # Clear cached timezone in pattern_manager so it picks up the new setting
  642. from modules.core import pattern_manager
  643. pattern_manager._cached_timezone = None
  644. pattern_manager._cached_zoneinfo = None
  645. if sp.time_slots is not None:
  646. state.scheduled_pause_time_slots = [slot.model_dump() for slot in sp.time_slots]
  647. updated_categories.append("scheduled_pause")
  648. # Board NVS is canonical for Still Sands (the mobile apps edit it there);
  649. # push the new values, plus the timezone so board-local schedules match.
  650. if state.conn:
  651. def _push_sands():
  652. try:
  653. board_settings.push_still_sands()
  654. if sp.timezone is not None:
  655. board_settings.sync_board_time()
  656. except Exception as e:
  657. logger.warning(f"Could not push Still Sands settings to board: {e}")
  658. asyncio.create_task(asyncio.to_thread(_push_sands))
  659. # Homing settings
  660. if settings_update.homing:
  661. h = settings_update.homing
  662. if h.mode is not None:
  663. state.homing = h.mode
  664. state.homing_user_override = True # User explicitly set preference
  665. if h.angular_offset_degrees is not None:
  666. state.angular_homing_offset_degrees = h.angular_offset_degrees
  667. if h.home_on_connect is not None:
  668. state.home_on_connect = h.home_on_connect
  669. if h.auto_home_enabled is not None:
  670. state.auto_home_enabled = h.auto_home_enabled
  671. if h.auto_home_after_patterns is not None:
  672. state.auto_home_after_patterns = h.auto_home_after_patterns
  673. if h.hard_reset_theta is not None:
  674. state.hard_reset_theta = h.hard_reset_theta
  675. updated_categories.append("homing")
  676. # Mirror to the board: mode/offset now (idle-gated NVS; also re-pushed on
  677. # every home), and the auto-home cadence for firmware-sequenced playlists.
  678. if state.conn:
  679. def _push_homing():
  680. try:
  681. if h.mode is not None:
  682. state.conn.set_homing_mode("crash" if state.homing == 0 else "sensor")
  683. if h.angular_offset_degrees is not None:
  684. state.conn.set_theta_offset(state.angular_homing_offset_degrees)
  685. if h.auto_home_enabled is not None or h.auto_home_after_patterns is not None:
  686. board_settings.push_auto_home()
  687. except Exception as e:
  688. logger.warning(f"Could not push homing settings to board: {e}")
  689. asyncio.create_task(asyncio.to_thread(_push_homing))
  690. # LED settings
  691. if settings_update.led:
  692. led = settings_update.led
  693. if led.provider is not None:
  694. state.led_provider = led.provider
  695. if led.provider != old_led_provider:
  696. led_reinit_needed = True
  697. if led.wled_ip is not None:
  698. state.wled_ip = led.wled_ip or None
  699. if led.control_mode is not None:
  700. state.dw_led_control_mode = led.control_mode
  701. if led.idle_timeout_enabled is not None:
  702. state.dw_led_idle_timeout_enabled = led.idle_timeout_enabled
  703. if led.idle_timeout_minutes is not None:
  704. state.dw_led_idle_timeout_minutes = led.idle_timeout_minutes
  705. updated_categories.append("led")
  706. # MQTT settings
  707. if settings_update.mqtt:
  708. m = settings_update.mqtt
  709. if m.enabled is not None:
  710. state.mqtt_enabled = m.enabled
  711. if m.broker is not None:
  712. state.mqtt_broker = m.broker
  713. if m.port is not None:
  714. state.mqtt_port = m.port
  715. if m.username is not None:
  716. state.mqtt_username = m.username
  717. if m.password is not None:
  718. state.mqtt_password = m.password
  719. if m.client_id is not None:
  720. state.mqtt_client_id = m.client_id
  721. if m.discovery_prefix is not None:
  722. state.mqtt_discovery_prefix = m.discovery_prefix
  723. if m.device_id is not None:
  724. state.mqtt_device_id = m.device_id
  725. if m.device_name is not None:
  726. state.mqtt_device_name = m.device_name
  727. updated_categories.append("mqtt")
  728. requires_restart = True
  729. # Machine settings (kinematics live in the board's config.yaml; only the
  730. # host timezone remains)
  731. if settings_update.machine:
  732. m = settings_update.machine
  733. if m.timezone is not None:
  734. # Validate timezone by trying to create a ZoneInfo object
  735. try:
  736. from zoneinfo import ZoneInfo
  737. except ImportError:
  738. from backports.zoneinfo import ZoneInfo
  739. try:
  740. ZoneInfo(m.timezone) # Validate
  741. state.timezone = m.timezone
  742. # Also update scheduled_pause_timezone to keep in sync
  743. state.scheduled_pause_timezone = m.timezone
  744. # Clear cached timezone in pattern_manager so it picks up the new setting
  745. from modules.core import pattern_manager
  746. pattern_manager._cached_timezone = None
  747. pattern_manager._cached_zoneinfo = None
  748. logger.info(f"Timezone updated to: {m.timezone}")
  749. except Exception as e:
  750. logger.warning(f"Invalid timezone '{m.timezone}': {e}")
  751. updated_categories.append("machine")
  752. # Security settings
  753. if settings_update.security:
  754. sec = settings_update.security
  755. if sec.mode is not None:
  756. if sec.mode not in ("off", "lockdown", "play_only"):
  757. raise HTTPException(status_code=400, detail="Invalid security mode. Must be 'off', 'lockdown', or 'play_only'.")
  758. state.security_mode = sec.mode
  759. # When turning off, clear the password hash
  760. if sec.mode == "off":
  761. state.security_password_hash = ""
  762. if sec.password is not None and sec.password != "":
  763. state.security_password_hash = hashlib.sha256(sec.password.encode('utf-8')).hexdigest()
  764. updated_categories.append("security")
  765. # Save state
  766. state.save()
  767. # Handle LED reinitialization if provider changed
  768. if led_reinit_needed:
  769. logger.info(f"LED provider changed from {old_led_provider} to {state.led_provider}, reinitialization may be needed")
  770. logger.info(f"Settings updated: {', '.join(updated_categories)}")
  771. return {
  772. "success": True,
  773. "updated_categories": updated_categories,
  774. "requires_restart": requires_restart,
  775. "led_reinit_needed": led_reinit_needed
  776. }
  777. @app.post("/api/security/verify", tags=["settings"])
  778. async def verify_security_password(request: SecurityVerifyRequest):
  779. """Verify a security password against the stored hash."""
  780. if not state.security_password_hash:
  781. return {"valid": False}
  782. input_hash = hashlib.sha256(request.password.encode('utf-8')).hexdigest()
  783. return {"valid": input_hash == state.security_password_hash}
  784. # ============================================================================
  785. # Board-owned settings (FluidNC NVS) — proxied for the web UI
  786. # ============================================================================
  787. class AutostartSettingsUpdate(BaseModel):
  788. playlist: Optional[str] = None # empty string disables auto-play on boot
  789. run_mode: Optional[str] = None # "single" | "loop"
  790. shuffle: Optional[bool] = None
  791. pause_seconds: Optional[int] = None
  792. pause_from_start: Optional[bool] = None
  793. clear_pattern: Optional[str] = None # none|adaptive|in|out|sideway|random
  794. class BoardSettingsUpdate(BaseModel):
  795. autostart: Optional[AutostartSettingsUpdate] = None
  796. @app.get("/api/board/settings", tags=["settings"])
  797. async def get_board_settings():
  798. """
  799. Read the board-owned settings (auto-play on boot, homing, clock) straight
  800. from the FluidNC board's NVS. These fire on table power-on, independent of
  801. this backend, and are shared with the native mobile apps.
  802. """
  803. if not state.conn:
  804. return {"reachable": False}
  805. try:
  806. return await asyncio.to_thread(board_settings.get_board_settings)
  807. except Exception as e:
  808. logger.warning(f"Could not read board settings: {e}")
  809. return {"reachable": False}
  810. @app.patch("/api/board/settings", tags=["settings"])
  811. async def update_board_settings(update: BoardSettingsUpdate):
  812. """Write board-owned settings ($Playlist/Autostart* family) to the board."""
  813. if not state.conn:
  814. raise HTTPException(status_code=409, detail="Not connected to the board")
  815. try:
  816. if update.autostart:
  817. autostart = update.autostart.model_dump(exclude_none=True)
  818. await asyncio.to_thread(board_settings.apply_autostart, autostart)
  819. # A newly selected boot playlist must exist on the board SD, with
  820. # all of its patterns, before the next power-on.
  821. playlist_name = autostart.get("playlist")
  822. if playlist_name:
  823. playlist = playlist_manager.get_playlist(playlist_name)
  824. if playlist:
  825. asyncio.create_task(asyncio.to_thread(
  826. board_settings.mirror_playlist,
  827. playlist_name, playlist["files"], None, True,
  828. ))
  829. return {"success": True}
  830. except Exception as e:
  831. logger.warning(f"Could not write board settings: {e}")
  832. raise HTTPException(status_code=502, detail=f"Board rejected the update: {e}")
  833. class BoardCommandRequest(BaseModel):
  834. command: str
  835. @app.post("/api/board/command", tags=["settings"])
  836. async def board_command(request: BoardCommandRequest):
  837. """Advanced console: send a $-command to the board and return the recent
  838. session log (the board streams command output to its log, not HTTP)."""
  839. if not state.conn:
  840. raise HTTPException(status_code=409, detail="Not connected to the board")
  841. command = request.command.strip()
  842. if not command:
  843. raise HTTPException(status_code=400, detail="Empty command")
  844. try:
  845. response = await asyncio.to_thread(state.conn.run_command, command)
  846. log_tail = ""
  847. try:
  848. log_text = await asyncio.to_thread(
  849. lambda: state.conn._get("/sand_log").text)
  850. log_tail = "\n".join(log_text.strip().splitlines()[-15:])
  851. except Exception:
  852. pass
  853. responses = [line for line in (response or "").strip().splitlines() if line]
  854. return {"success": True, "responses": responses, "log": log_tail}
  855. except Exception as e:
  856. raise HTTPException(status_code=502, detail=f"Board command failed: {e}")
  857. @app.post("/api/board/sync_time", tags=["settings"])
  858. async def sync_board_time():
  859. """Push the host's clock and timezone to the board (quiet hours need it)."""
  860. if not state.conn:
  861. raise HTTPException(status_code=409, detail="Not connected to the board")
  862. try:
  863. result = await asyncio.to_thread(board_settings.sync_board_time)
  864. return {"success": True, "time": result}
  865. except Exception as e:
  866. raise HTTPException(status_code=502, detail=f"Clock sync failed: {e}")
  867. # ============================================================================
  868. # Multi-Table Identity Endpoints
  869. # ============================================================================
  870. class TableInfoUpdate(BaseModel):
  871. name: Optional[str] = None
  872. class KnownTableAdd(BaseModel):
  873. id: str
  874. name: str
  875. url: str
  876. host: Optional[str] = None
  877. port: Optional[int] = None
  878. version: Optional[str] = None
  879. class KnownTableUpdate(BaseModel):
  880. name: Optional[str] = None
  881. @app.get("/api/table-info", tags=["multi-table"])
  882. async def get_table_info():
  883. """
  884. Get table identity information for multi-table discovery.
  885. Returns the table's unique ID, name, and version.
  886. """
  887. return {
  888. "id": state.table_id,
  889. "name": state.table_name,
  890. "version": await version_manager.get_current_version()
  891. }
  892. @app.patch("/api/table-info", tags=["multi-table"])
  893. async def update_table_info(update: TableInfoUpdate):
  894. """
  895. Update table identity information.
  896. Currently only the table name can be updated.
  897. The table ID is immutable after generation.
  898. """
  899. if update.name is not None:
  900. state.table_name = update.name.strip() or "Dune Weaver"
  901. state.save()
  902. logger.info(f"Table name updated to: {state.table_name}")
  903. await mdns_discovery.update_name(state.table_name)
  904. return {
  905. "success": True,
  906. "id": state.table_id,
  907. "name": state.table_name
  908. }
  909. @app.get("/api/discovered-tables", tags=["multi-table"])
  910. async def get_discovered_tables():
  911. """
  912. Get Dune Weaver tables auto-discovered via mDNS on the local network.
  913. Unlike known-tables these are not persisted - the list reflects which
  914. peer backends are currently advertising themselves. Returns an empty
  915. list when mDNS is unavailable (e.g. zeroconf not installed).
  916. """
  917. return {"tables": mdns_discovery.get_tables()}
  918. @app.get("/api/known-tables", tags=["multi-table"])
  919. async def get_known_tables():
  920. """
  921. Get list of known remote tables.
  922. These are tables that have been manually added and are persisted
  923. for multi-table management.
  924. """
  925. return {"tables": state.known_tables}
  926. @app.post("/api/known-tables", tags=["multi-table"])
  927. async def add_known_table(table: KnownTableAdd):
  928. """
  929. Add a known remote table.
  930. This persists the table information so it's available across
  931. browser sessions and devices.
  932. """
  933. # Check if table with same ID already exists
  934. existing_ids = [t.get("id") for t in state.known_tables]
  935. if table.id in existing_ids:
  936. raise HTTPException(status_code=400, detail="Table with this ID already exists")
  937. # Check if table with same URL already exists
  938. existing_urls = [t.get("url") for t in state.known_tables]
  939. if table.url in existing_urls:
  940. raise HTTPException(status_code=400, detail="Table with this URL already exists")
  941. new_table = {
  942. "id": table.id,
  943. "name": table.name,
  944. "url": table.url,
  945. }
  946. if table.host:
  947. new_table["host"] = table.host
  948. if table.port:
  949. new_table["port"] = table.port
  950. if table.version:
  951. new_table["version"] = table.version
  952. state.known_tables.append(new_table)
  953. state.save()
  954. logger.info(f"Added known table: {table.name} ({table.url})")
  955. return {"success": True, "table": new_table}
  956. @app.delete("/api/known-tables/{table_id}", tags=["multi-table"])
  957. async def remove_known_table(table_id: str):
  958. """
  959. Remove a known remote table by ID.
  960. """
  961. original_count = len(state.known_tables)
  962. state.known_tables = [t for t in state.known_tables if t.get("id") != table_id]
  963. if len(state.known_tables) == original_count:
  964. raise HTTPException(status_code=404, detail="Table not found")
  965. state.save()
  966. logger.info(f"Removed known table: {table_id}")
  967. return {"success": True}
  968. @app.patch("/api/known-tables/{table_id}", tags=["multi-table"])
  969. async def update_known_table(table_id: str, update: KnownTableUpdate):
  970. """
  971. Update a known remote table's name.
  972. """
  973. for table in state.known_tables:
  974. if table.get("id") == table_id:
  975. if update.name is not None:
  976. table["name"] = update.name.strip()
  977. state.save()
  978. logger.info(f"Updated known table {table_id}: name={update.name}")
  979. return {"success": True, "table": table}
  980. raise HTTPException(status_code=404, detail="Table not found")
  981. # ============================================================================
  982. # Individual Settings Endpoints (Deprecated - use /api/settings instead)
  983. # ============================================================================
  984. @app.get("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  985. async def get_scheduled_pause():
  986. """DEPRECATED: Use GET /api/settings instead. Get current Still Sands settings."""
  987. return {
  988. "enabled": state.scheduled_pause_enabled,
  989. "control_wled": state.scheduled_pause_control_wled,
  990. "finish_pattern": state.scheduled_pause_finish_pattern,
  991. "timezone": state.scheduled_pause_timezone,
  992. "time_slots": state.scheduled_pause_time_slots
  993. }
  994. @app.post("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  995. async def set_scheduled_pause(request: ScheduledPauseRequest):
  996. """Update Still Sands settings."""
  997. try:
  998. # Validate time slots
  999. for i, slot in enumerate(request.time_slots):
  1000. # Validate time format (HH:MM)
  1001. try:
  1002. datetime.strptime(slot.start_time, "%H:%M")
  1003. datetime.strptime(slot.end_time, "%H:%M")
  1004. except ValueError:
  1005. raise HTTPException(
  1006. status_code=400,
  1007. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  1008. )
  1009. # Validate days setting
  1010. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  1011. raise HTTPException(
  1012. status_code=400,
  1013. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  1014. )
  1015. # Validate custom days if applicable
  1016. if slot.days == "custom":
  1017. if not slot.custom_days or len(slot.custom_days) == 0:
  1018. raise HTTPException(
  1019. status_code=400,
  1020. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  1021. )
  1022. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  1023. for day in slot.custom_days:
  1024. if day not in valid_days:
  1025. raise HTTPException(
  1026. status_code=400,
  1027. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  1028. )
  1029. # Update state
  1030. state.scheduled_pause_enabled = request.enabled
  1031. state.scheduled_pause_control_wled = request.control_wled
  1032. state.scheduled_pause_finish_pattern = request.finish_pattern
  1033. state.scheduled_pause_timezone = request.timezone if request.timezone else None
  1034. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  1035. state.save()
  1036. # Clear cached timezone so it picks up the new setting
  1037. from modules.core import pattern_manager
  1038. pattern_manager._cached_timezone = None
  1039. pattern_manager._cached_zoneinfo = None
  1040. wled_msg = " (with WLED control)" if request.control_wled else ""
  1041. finish_msg = " (finish pattern first)" if request.finish_pattern else ""
  1042. tz_msg = f" (timezone: {request.timezone})" if request.timezone else ""
  1043. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}{finish_msg}{tz_msg}")
  1044. return {"success": True, "message": "Still Sands settings updated"}
  1045. except HTTPException:
  1046. raise
  1047. except Exception as e:
  1048. logger.error(f"Error updating Still Sands settings: {str(e)}")
  1049. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  1050. @app.get("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  1051. async def get_homing_config():
  1052. """Get homing configuration (mode, compass offset, and auto-home settings)."""
  1053. return {
  1054. "homing_mode": state.homing,
  1055. "angular_homing_offset_degrees": state.angular_homing_offset_degrees,
  1056. "auto_home_enabled": state.auto_home_enabled,
  1057. "auto_home_after_patterns": state.auto_home_after_patterns
  1058. }
  1059. class HomingConfigRequest(BaseModel):
  1060. homing_mode: int = 0 # 0 = crash, 1 = sensor
  1061. angular_homing_offset_degrees: float = 0.0
  1062. auto_home_enabled: Optional[bool] = None
  1063. auto_home_after_patterns: Optional[int] = None
  1064. @app.post("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  1065. async def set_homing_config(request: HomingConfigRequest):
  1066. """Set homing configuration (mode, compass offset, and auto-home settings)."""
  1067. try:
  1068. # Validate homing mode
  1069. if request.homing_mode not in [0, 1]:
  1070. raise HTTPException(status_code=400, detail="Homing mode must be 0 (crash) or 1 (sensor)")
  1071. state.homing = request.homing_mode
  1072. state.homing_user_override = True # User explicitly set preference
  1073. state.angular_homing_offset_degrees = request.angular_homing_offset_degrees
  1074. # Update auto-home settings if provided
  1075. if request.auto_home_enabled is not None:
  1076. state.auto_home_enabled = request.auto_home_enabled
  1077. if request.auto_home_after_patterns is not None:
  1078. if request.auto_home_after_patterns < 1:
  1079. raise HTTPException(status_code=400, detail="Auto-home after patterns must be at least 1")
  1080. state.auto_home_after_patterns = request.auto_home_after_patterns
  1081. state.save()
  1082. mode_name = "crash" if request.homing_mode == 0 else "sensor"
  1083. logger.info(f"Homing mode set to {mode_name}, compass offset set to {request.angular_homing_offset_degrees}°")
  1084. if request.auto_home_enabled is not None:
  1085. logger.info(f"Auto-home enabled: {state.auto_home_enabled}, after {state.auto_home_after_patterns} patterns")
  1086. return {"success": True, "message": "Homing configuration updated"}
  1087. except HTTPException:
  1088. raise
  1089. except Exception as e:
  1090. logger.error(f"Error updating homing configuration: {str(e)}")
  1091. raise HTTPException(status_code=500, detail=f"Failed to update homing configuration: {str(e)}")
  1092. @app.get("/list_serial_ports")
  1093. async def list_ports():
  1094. logger.debug("Listing available serial ports")
  1095. return await asyncio.to_thread(connection_manager.list_serial_ports)
  1096. @app.post("/connect")
  1097. async def connect(request: ConnectRequest):
  1098. # `request.port` carries the board address now (a URL or bare IP). Blank =>
  1099. # use the configured/default board URL.
  1100. from modules.connection.fluidnc_client import FluidNCClient
  1101. try:
  1102. url = connection_manager._normalize_board_url(request.port or "") or connection_manager.board_url()
  1103. state.board_url = url
  1104. state.port = url
  1105. state.save()
  1106. state.conn = FluidNCClient(url)
  1107. if not state.conn.reachable():
  1108. state.conn = None
  1109. raise HTTPException(status_code=500, detail=f"Board not reachable at {url}")
  1110. if not await asyncio.to_thread(connection_manager.device_init, False):
  1111. raise HTTPException(status_code=500, detail="Failed to initialize board")
  1112. logger.info(f"Successfully connected to board at {url}")
  1113. return {"success": True}
  1114. except HTTPException:
  1115. raise
  1116. except Exception as e:
  1117. logger.error(f"Failed to connect to board: {str(e)}")
  1118. raise HTTPException(status_code=500, detail=str(e))
  1119. @app.post("/disconnect")
  1120. async def disconnect():
  1121. try:
  1122. state.conn.close()
  1123. logger.info('Successfully disconnected from serial port')
  1124. return {"success": True}
  1125. except Exception as e:
  1126. logger.error(f'Failed to disconnect serial: {str(e)}')
  1127. raise HTTPException(status_code=500, detail=str(e))
  1128. @app.post("/restart_connection")
  1129. async def restart(request: ConnectRequest):
  1130. if not request.port:
  1131. logger.warning("Restart serial request received without port")
  1132. raise HTTPException(status_code=400, detail="No port provided")
  1133. try:
  1134. logger.info(f"Restarting connection on port {request.port}")
  1135. connection_manager.restart_connection()
  1136. return {"success": True}
  1137. except Exception as e:
  1138. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  1139. raise HTTPException(status_code=500, detail=str(e))
  1140. @app.get("/list_theta_rho_files")
  1141. async def list_theta_rho_files():
  1142. logger.debug("Listing theta-rho files")
  1143. # Run the blocking file system operation in a thread pool
  1144. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  1145. return sorted(files)
  1146. @app.get("/list_theta_rho_files_with_metadata")
  1147. async def list_theta_rho_files_with_metadata():
  1148. """Get list of theta-rho files with metadata for sorting and filtering.
  1149. Optimized to process files asynchronously and support request cancellation.
  1150. """
  1151. from modules.core.cache_manager import get_pattern_metadata
  1152. import asyncio
  1153. from concurrent.futures import ThreadPoolExecutor
  1154. # Run the blocking file listing in a thread
  1155. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  1156. files_with_metadata = []
  1157. # Use ThreadPoolExecutor for I/O-bound operations
  1158. executor = ThreadPoolExecutor(max_workers=4)
  1159. def process_file(file_path):
  1160. """Process a single file and return its metadata."""
  1161. try:
  1162. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  1163. # Get file stats
  1164. file_stat = os.stat(full_path)
  1165. # Get cached metadata (this should be fast if cached)
  1166. metadata = get_pattern_metadata(file_path)
  1167. # Extract full folder path from file path
  1168. path_parts = file_path.split('/')
  1169. if len(path_parts) > 1:
  1170. # Get everything except the filename (join all folder parts)
  1171. category = '/'.join(path_parts[:-1])
  1172. else:
  1173. category = 'root'
  1174. # Get file name without extension
  1175. file_name = os.path.splitext(os.path.basename(file_path))[0]
  1176. # Use modification time (mtime) for "date modified"
  1177. date_modified = file_stat.st_mtime
  1178. return {
  1179. 'path': file_path,
  1180. 'name': file_name,
  1181. 'category': category,
  1182. 'date_modified': date_modified,
  1183. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  1184. }
  1185. except Exception as e:
  1186. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  1187. # Include file with minimal info if metadata fails
  1188. path_parts = file_path.split('/')
  1189. if len(path_parts) > 1:
  1190. category = '/'.join(path_parts[:-1])
  1191. else:
  1192. category = 'root'
  1193. return {
  1194. 'path': file_path,
  1195. 'name': os.path.splitext(os.path.basename(file_path))[0],
  1196. 'category': category,
  1197. 'date_modified': 0,
  1198. 'coordinates_count': 0
  1199. }
  1200. # Load the entire metadata cache at once (async)
  1201. # This is much faster than 1000+ individual metadata lookups
  1202. try:
  1203. import json
  1204. metadata_cache_path = "metadata_cache.json"
  1205. # Use async file reading to avoid blocking the event loop
  1206. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  1207. cache_dict = cache_data.get('data', {})
  1208. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  1209. # Process all files using cached data only
  1210. for file_path in files:
  1211. try:
  1212. # Extract category from path
  1213. path_parts = file_path.split('/')
  1214. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  1215. # Get file name without extension
  1216. file_name = os.path.splitext(os.path.basename(file_path))[0]
  1217. # Get metadata from cache
  1218. cached_entry = cache_dict.get(file_path, {})
  1219. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  1220. metadata = cached_entry['metadata']
  1221. coords_count = metadata.get('total_coordinates', 0)
  1222. date_modified = cached_entry.get('mtime', 0)
  1223. else:
  1224. coords_count = 0
  1225. date_modified = 0
  1226. files_with_metadata.append({
  1227. 'path': file_path,
  1228. 'name': file_name,
  1229. 'category': category,
  1230. 'date_modified': date_modified,
  1231. 'coordinates_count': coords_count
  1232. })
  1233. except Exception as e:
  1234. logger.warning(f"Error processing {file_path}: {e}")
  1235. # Include file with minimal info if processing fails
  1236. path_parts = file_path.split('/')
  1237. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  1238. files_with_metadata.append({
  1239. 'path': file_path,
  1240. 'name': os.path.splitext(os.path.basename(file_path))[0],
  1241. 'category': category,
  1242. 'date_modified': 0,
  1243. 'coordinates_count': 0
  1244. })
  1245. except Exception as e:
  1246. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  1247. # Fallback to original method if cache loading fails
  1248. # Create tasks only when needed
  1249. loop = asyncio.get_running_loop()
  1250. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  1251. for task in asyncio.as_completed(tasks):
  1252. try:
  1253. result = await task
  1254. files_with_metadata.append(result)
  1255. except Exception as task_error:
  1256. logger.error(f"Error processing file: {str(task_error)}")
  1257. # Clean up executor
  1258. executor.shutdown(wait=False)
  1259. return files_with_metadata
  1260. @app.post("/upload_theta_rho")
  1261. async def upload_theta_rho(file: UploadFile = File(...)):
  1262. """Upload a theta-rho file."""
  1263. try:
  1264. # Save the file
  1265. # Ensure custom_patterns directory exists
  1266. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  1267. os.makedirs(custom_patterns_dir, exist_ok=True)
  1268. # Use forward slashes for internal path representation to maintain consistency
  1269. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  1270. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  1271. # Save the uploaded file with proper encoding for Windows compatibility
  1272. file_content = await file.read()
  1273. try:
  1274. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  1275. text_content = file_content.decode('utf-8')
  1276. with open(full_file_path, "w", encoding='utf-8') as f:
  1277. f.write(text_content)
  1278. except UnicodeDecodeError:
  1279. # If UTF-8 decoding fails, save as binary (fallback)
  1280. with open(full_file_path, "wb") as f:
  1281. f.write(file_content)
  1282. logger.info(f"File {file.filename} saved successfully")
  1283. # Generate image preview for the new file with retry logic
  1284. max_retries = 3
  1285. for attempt in range(max_retries):
  1286. try:
  1287. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  1288. success = await generate_image_preview(file_path_in_patterns_dir)
  1289. if success:
  1290. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  1291. break
  1292. else:
  1293. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  1294. if attempt < max_retries - 1:
  1295. await asyncio.sleep(0.5) # Small delay before retry
  1296. except Exception as e:
  1297. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  1298. if attempt < max_retries - 1:
  1299. await asyncio.sleep(0.5) # Small delay before retry
  1300. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  1301. except Exception as e:
  1302. logger.error(f"Error uploading file: {str(e)}")
  1303. raise HTTPException(status_code=500, detail=str(e))
  1304. @app.post("/get_theta_rho_coordinates")
  1305. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  1306. """Get theta-rho coordinates for animated preview."""
  1307. try:
  1308. # Normalize file path for cross-platform compatibility and remove prefixes
  1309. file_name = normalize_file_path(request.file_name)
  1310. file_path = os.path.join(THETA_RHO_DIR, file_name)
  1311. # Check if we can use cached coordinates (already loaded for current playback)
  1312. # This avoids re-parsing large files (2MB+) which can cause issues on Pi Zero 2W
  1313. current_file = state.current_playing_file
  1314. if current_file and state._current_coordinates:
  1315. # Normalize current file path for comparison
  1316. current_normalized = normalize_file_path(current_file)
  1317. if current_normalized == file_name:
  1318. logger.debug(f"Using cached coordinates for {file_name}")
  1319. return {
  1320. "success": True,
  1321. "coordinates": state._current_coordinates,
  1322. "total_points": len(state._current_coordinates)
  1323. }
  1324. # Check file existence asynchronously
  1325. exists = await asyncio.to_thread(os.path.exists, file_path)
  1326. if not exists:
  1327. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  1328. # Parse the theta-rho file in a thread (not process) to avoid memory pressure
  1329. # on resource-constrained devices like Pi Zero 2W
  1330. coordinates = await asyncio.to_thread(parse_theta_rho_file, file_path)
  1331. if not coordinates:
  1332. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  1333. return {
  1334. "success": True,
  1335. "coordinates": coordinates,
  1336. "total_points": len(coordinates)
  1337. }
  1338. except Exception as e:
  1339. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  1340. raise HTTPException(status_code=500, detail=str(e))
  1341. @app.post("/run_theta_rho")
  1342. async def run_theta_rho(request: ThetaRhoRequest):
  1343. """Run one pattern. The firmware sequences the pre-execution clear
  1344. ($Sand/Run clear=<mode>) and aborts any current job first."""
  1345. if not request.file_name:
  1346. logger.warning('Run theta-rho request received without file name')
  1347. raise HTTPException(status_code=400, detail="No file name provided")
  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. if not (state.conn.is_connected() if state.conn else False):
  1354. logger.warning("Attempted to run a pattern without a connection")
  1355. raise HTTPException(status_code=400, detail="Connection not established")
  1356. check_homing_in_progress()
  1357. try:
  1358. await execution.run_pattern(file_path, request.pre_execution)
  1359. return {"success": True}
  1360. except execution.ExecutionError as e:
  1361. raise HTTPException(status_code=409, detail=str(e))
  1362. except Exception as e:
  1363. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  1364. raise HTTPException(status_code=500, detail=str(e))
  1365. @app.post("/stop_execution")
  1366. async def stop_execution():
  1367. if not (state.conn.is_connected() if state.conn else False):
  1368. logger.warning("Attempted to stop without a connection")
  1369. raise HTTPException(status_code=400, detail="Connection not established")
  1370. try:
  1371. success = await execution.stop()
  1372. except execution.ExecutionError as e:
  1373. raise HTTPException(status_code=500, detail=str(e))
  1374. if not success:
  1375. raise HTTPException(status_code=500, detail="Stop timed out - use force_stop")
  1376. return {"success": True}
  1377. @app.post("/force_stop")
  1378. async def force_stop():
  1379. """Best-effort board stop + unconditional host-state reset. Use when the
  1380. normal stop doesn't come back."""
  1381. logger.info("Force stop requested - clearing all run state")
  1382. await execution.stop(force=True)
  1383. state.is_homing = False
  1384. return {"success": True, "message": "Force stop completed"}
  1385. @app.post("/soft_reset")
  1386. async def soft_reset():
  1387. """Send $Bye soft reset to FluidNC controller. Resets position counters to 0."""
  1388. if not (state.conn and state.conn.is_connected()):
  1389. logger.warning("Attempted to soft reset without a connection")
  1390. raise HTTPException(status_code=400, detail="Connection not established")
  1391. try:
  1392. # Stop any running patterns first
  1393. await execution.stop(force=True)
  1394. # Use the shared soft reset function
  1395. await connection_manager.perform_soft_reset()
  1396. return {"success": True, "message": "Soft reset sent. Position reset to 0."}
  1397. except Exception as e:
  1398. logger.error(f"Error sending soft reset: {e}")
  1399. raise HTTPException(status_code=500, detail=str(e))
  1400. @app.post("/send_home")
  1401. async def send_home():
  1402. try:
  1403. if not (state.conn.is_connected() if state.conn else False):
  1404. logger.warning("Attempted to move to home without a connection")
  1405. raise HTTPException(status_code=400, detail="Connection not established")
  1406. if state.is_homing:
  1407. raise HTTPException(status_code=409, detail="Homing already in progress")
  1408. # Set homing flag to block other movement operations
  1409. state.is_homing = True
  1410. logger.info("Homing started - blocking other movement operations")
  1411. try:
  1412. # Run homing with 15 second timeout
  1413. success = await asyncio.to_thread(connection_manager.home)
  1414. if not success:
  1415. logger.error("Homing failed or timed out")
  1416. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  1417. return {"success": True}
  1418. finally:
  1419. # Always clear homing flag when done (success or failure)
  1420. state.is_homing = False
  1421. logger.info("Homing completed - movement operations unblocked")
  1422. except HTTPException:
  1423. raise
  1424. except Exception as e:
  1425. logger.error(f"Failed to send home command: {str(e)}")
  1426. raise HTTPException(status_code=500, detail=str(e))
  1427. class SensorHomingRecoveryRequest(BaseModel):
  1428. switch_to_crash_homing: bool = False
  1429. @app.post("/recover_sensor_homing")
  1430. async def recover_sensor_homing(request: SensorHomingRecoveryRequest):
  1431. """
  1432. Recover from sensor homing failure.
  1433. If switch_to_crash_homing is True, changes homing mode to crash homing (mode 0)
  1434. and saves the setting. Then attempts to reconnect and home the device.
  1435. If switch_to_crash_homing is False, just clears the failure flag and retries
  1436. with sensor homing.
  1437. """
  1438. try:
  1439. # Clear the sensor homing failure flag first
  1440. state.sensor_homing_failed = False
  1441. if request.switch_to_crash_homing:
  1442. # Switch to crash homing mode
  1443. logger.info("Switching to crash homing mode per user request")
  1444. state.homing = 0
  1445. state.homing_user_override = True
  1446. state.save()
  1447. # If already connected, just perform homing
  1448. if state.conn and state.conn.is_connected():
  1449. logger.info("Device already connected, performing homing...")
  1450. state.is_homing = True
  1451. try:
  1452. success = await asyncio.to_thread(connection_manager.home)
  1453. if not success:
  1454. # Check if sensor homing failed again
  1455. if state.sensor_homing_failed:
  1456. return {
  1457. "success": False,
  1458. "sensor_homing_failed": True,
  1459. "message": "Sensor homing failed again. Please check sensor position or switch to crash homing."
  1460. }
  1461. return {"success": False, "message": "Homing failed"}
  1462. return {"success": True, "message": "Homing completed successfully"}
  1463. finally:
  1464. state.is_homing = False
  1465. else:
  1466. # Need to reconnect
  1467. logger.info("Reconnecting device and performing homing...")
  1468. state.is_homing = True
  1469. try:
  1470. # connect_device includes homing
  1471. await asyncio.to_thread(connection_manager.connect_device, True)
  1472. # Check if sensor homing failed during connection
  1473. if state.sensor_homing_failed:
  1474. return {
  1475. "success": False,
  1476. "sensor_homing_failed": True,
  1477. "message": "Sensor homing failed. Please check sensor position or switch to crash homing."
  1478. }
  1479. if state.conn and state.conn.is_connected():
  1480. return {"success": True, "message": "Connected and homed successfully"}
  1481. else:
  1482. return {"success": False, "message": "Failed to establish connection"}
  1483. finally:
  1484. state.is_homing = False
  1485. except Exception as e:
  1486. logger.error(f"Error during sensor homing recovery: {e}")
  1487. state.is_homing = False
  1488. raise HTTPException(status_code=500, detail=str(e))
  1489. @app.post("/run_theta_rho_file/{file_name}")
  1490. async def run_specific_theta_rho_file(file_name: str):
  1491. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  1492. if not os.path.exists(file_path):
  1493. raise HTTPException(status_code=404, detail="File not found")
  1494. if not (state.conn.is_connected() if state.conn else False):
  1495. logger.warning("Attempted to run a pattern without a connection")
  1496. raise HTTPException(status_code=400, detail="Connection not established")
  1497. check_homing_in_progress()
  1498. await execution.run_pattern(file_path)
  1499. return {"success": True}
  1500. class DeleteFileRequest(BaseModel):
  1501. file_name: str
  1502. @app.post("/delete_theta_rho_file")
  1503. async def delete_theta_rho_file(request: DeleteFileRequest):
  1504. if not request.file_name:
  1505. logger.warning("Delete theta-rho file request received without filename")
  1506. raise HTTPException(status_code=400, detail="No file name provided")
  1507. # Normalize file path for cross-platform compatibility
  1508. normalized_file_name = normalize_file_path(request.file_name)
  1509. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1510. # Check file existence asynchronously
  1511. exists = await asyncio.to_thread(os.path.exists, file_path)
  1512. if not exists:
  1513. logger.error(f"Attempted to delete non-existent file: {file_path}")
  1514. raise HTTPException(status_code=404, detail="File not found")
  1515. try:
  1516. # Delete the pattern file asynchronously
  1517. await asyncio.to_thread(os.remove, file_path)
  1518. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  1519. # Clean up cached preview image and metadata asynchronously
  1520. from modules.core.cache_manager import delete_pattern_cache
  1521. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  1522. if cache_cleanup_success:
  1523. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  1524. else:
  1525. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  1526. return {"success": True, "cache_cleanup": cache_cleanup_success}
  1527. except Exception as e:
  1528. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  1529. raise HTTPException(status_code=500, detail=str(e))
  1530. @app.post("/move_to_center")
  1531. async def move_to_center():
  1532. try:
  1533. if not (state.conn.is_connected() if state.conn else False):
  1534. logger.warning("Attempted to move to center without a connection")
  1535. raise HTTPException(status_code=400, detail="Connection not established")
  1536. check_homing_in_progress()
  1537. logger.info("Moving device to center position")
  1538. await pattern_manager.reset_theta()
  1539. await pattern_manager.move_polar(0, 0)
  1540. # Wait for machine to reach idle before returning
  1541. idle = await connection_manager.check_idle_async(timeout=60)
  1542. if not idle:
  1543. logger.warning("Machine did not reach idle after move to center")
  1544. return {"success": True}
  1545. except HTTPException:
  1546. raise
  1547. except Exception as e:
  1548. logger.error(f"Failed to move to center: {str(e)}")
  1549. raise HTTPException(status_code=500, detail=str(e))
  1550. @app.post("/move_to_perimeter")
  1551. async def move_to_perimeter():
  1552. try:
  1553. if not (state.conn.is_connected() if state.conn else False):
  1554. logger.warning("Attempted to move to perimeter without a connection")
  1555. raise HTTPException(status_code=400, detail="Connection not established")
  1556. check_homing_in_progress()
  1557. logger.info("Moving device to perimeter position")
  1558. await pattern_manager.reset_theta()
  1559. await pattern_manager.move_polar(0, 1)
  1560. # Wait for machine to reach idle before returning
  1561. idle = await connection_manager.check_idle_async(timeout=60)
  1562. if not idle:
  1563. logger.warning("Machine did not reach idle after move to perimeter")
  1564. return {"success": True}
  1565. except HTTPException:
  1566. raise
  1567. except Exception as e:
  1568. logger.error(f"Failed to move to perimeter: {str(e)}")
  1569. raise HTTPException(status_code=500, detail=str(e))
  1570. @app.post("/preview_thr")
  1571. async def preview_thr(request: DeleteFileRequest):
  1572. if not request.file_name:
  1573. logger.warning("Preview theta-rho request received without filename")
  1574. raise HTTPException(status_code=400, detail="No file name provided")
  1575. # Normalize file path for cross-platform compatibility
  1576. normalized_file_name = normalize_file_path(request.file_name)
  1577. # Construct the full path to the pattern file to check existence
  1578. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1579. # Check file existence asynchronously
  1580. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1581. if not exists:
  1582. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  1583. raise HTTPException(status_code=404, detail="Pattern file not found")
  1584. try:
  1585. cache_path = get_cache_path(normalized_file_name)
  1586. # Check cache existence asynchronously
  1587. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1588. if not cache_exists:
  1589. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  1590. # Attempt to generate the preview if it's missing
  1591. success = await generate_image_preview(normalized_file_name)
  1592. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1593. if not success or not cache_exists_after:
  1594. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  1595. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  1596. # Try to get coordinates from metadata cache first
  1597. metadata = get_pattern_metadata(normalized_file_name)
  1598. if metadata:
  1599. first_coord_obj = metadata.get('first_coordinate')
  1600. last_coord_obj = metadata.get('last_coordinate')
  1601. else:
  1602. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  1603. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  1604. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  1605. first_coord = coordinates[0] if coordinates else None
  1606. last_coord = coordinates[-1] if coordinates else None
  1607. # Format coordinates as objects with x and y properties
  1608. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1609. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1610. # Return JSON with preview URL and coordinates
  1611. # URL encode the file_name for the preview URL
  1612. # Handle both forward slashes and backslashes for cross-platform compatibility
  1613. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  1614. return {
  1615. "preview_url": f"/preview/{encoded_filename}",
  1616. "first_coordinate": first_coord_obj,
  1617. "last_coordinate": last_coord_obj
  1618. }
  1619. except HTTPException:
  1620. raise
  1621. except Exception as e:
  1622. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  1623. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  1624. @app.get("/api/pattern_history/{pattern_name:path}")
  1625. async def get_pattern_history(pattern_name: str):
  1626. """Get the most recent execution history for a pattern.
  1627. Returns the last completed execution time and speed for the given pattern.
  1628. """
  1629. from modules.core.pattern_manager import get_pattern_execution_history
  1630. # Get just the filename if a full path was provided
  1631. filename = os.path.basename(pattern_name)
  1632. if not filename.endswith('.thr'):
  1633. filename = f"{filename}.thr"
  1634. history = get_pattern_execution_history(filename)
  1635. if history:
  1636. return history
  1637. return {"actual_time_seconds": None, "actual_time_formatted": None, "speed": None, "timestamp": None}
  1638. @app.get("/api/pattern_history_all")
  1639. async def get_all_pattern_history():
  1640. """Get execution history for all patterns in a single request.
  1641. Returns a dict mapping pattern names to their most recent execution history.
  1642. """
  1643. from modules.core.pattern_manager import EXECUTION_LOG_FILE
  1644. if not os.path.exists(EXECUTION_LOG_FILE):
  1645. return {}
  1646. try:
  1647. history_map = {}
  1648. play_counts = {}
  1649. with open(EXECUTION_LOG_FILE, 'r') as f:
  1650. for line in f:
  1651. line = line.strip()
  1652. if not line:
  1653. continue
  1654. try:
  1655. entry = json.loads(line)
  1656. # Only consider fully completed patterns
  1657. if entry.get('completed', False):
  1658. pattern_name = entry.get('pattern_name')
  1659. if pattern_name:
  1660. play_counts[pattern_name] = play_counts.get(pattern_name, 0) + 1
  1661. # Keep the most recent match (last one in file wins)
  1662. history_map[pattern_name] = {
  1663. "actual_time_seconds": entry.get('actual_time_seconds'),
  1664. "actual_time_formatted": entry.get('actual_time_formatted'),
  1665. "speed": entry.get('speed'),
  1666. "timestamp": entry.get('timestamp'),
  1667. "play_count": play_counts[pattern_name],
  1668. "last_played": entry.get('timestamp')
  1669. }
  1670. except json.JSONDecodeError:
  1671. continue
  1672. return history_map
  1673. except Exception as e:
  1674. logger.error(f"Failed to read execution time log: {e}")
  1675. return {}
  1676. @app.get("/preview/{encoded_filename}")
  1677. async def serve_preview(encoded_filename: str):
  1678. """Serve a preview image for a pattern file."""
  1679. # Decode the filename by replacing -- with the original path separators
  1680. # First try forward slash (most common case), then backslash if needed
  1681. file_name = encoded_filename.replace('--', '/')
  1682. # Apply normalization to handle any remaining path prefixes
  1683. file_name = normalize_file_path(file_name)
  1684. # Check if the decoded path exists, if not try backslash decoding
  1685. cache_path = get_cache_path(file_name)
  1686. if not os.path.exists(cache_path):
  1687. # Try with backslash for Windows paths
  1688. file_name_backslash = encoded_filename.replace('--', '\\')
  1689. file_name_backslash = normalize_file_path(file_name_backslash)
  1690. cache_path_backslash = get_cache_path(file_name_backslash)
  1691. if os.path.exists(cache_path_backslash):
  1692. file_name = file_name_backslash
  1693. cache_path = cache_path_backslash
  1694. # cache_path is already determined above in the decoding logic
  1695. if not os.path.exists(cache_path):
  1696. logger.error(f"Preview image not found for {file_name}")
  1697. raise HTTPException(status_code=404, detail="Preview image not found")
  1698. # Add caching headers
  1699. headers = {
  1700. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  1701. "Content-Type": "image/webp",
  1702. "Accept-Ranges": "bytes"
  1703. }
  1704. return FileResponse(
  1705. cache_path,
  1706. media_type="image/webp",
  1707. headers=headers
  1708. )
  1709. @app.post("/send_coordinate")
  1710. async def send_coordinate(request: CoordinateRequest):
  1711. if not (state.conn.is_connected() if state.conn else False):
  1712. logger.warning("Attempted to send coordinate without a connection")
  1713. raise HTTPException(status_code=400, detail="Connection not established")
  1714. check_homing_in_progress()
  1715. try:
  1716. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  1717. await pattern_manager.move_polar(request.theta, request.rho)
  1718. # Wait for machine to reach idle before returning
  1719. idle = await connection_manager.check_idle_async(timeout=60)
  1720. if not idle:
  1721. logger.warning("Machine did not reach idle after send_coordinate")
  1722. return {"success": True}
  1723. except Exception as e:
  1724. logger.error(f"Failed to send coordinate: {str(e)}")
  1725. raise HTTPException(status_code=500, detail=str(e))
  1726. @app.get("/download/{filename}")
  1727. async def download_file(filename: str):
  1728. return FileResponse(
  1729. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  1730. filename=filename
  1731. )
  1732. @app.get("/serial_status")
  1733. async def serial_status():
  1734. """Connection status. `port` is the configured board address (HTTP, not serial)."""
  1735. connected = state.conn.is_connected() if state.conn else False
  1736. port = connection_manager.board_url()
  1737. logger.debug(f"Connection status check - connected: {connected}, board: {port}")
  1738. return {
  1739. "connected": connected,
  1740. "port": port,
  1741. }
  1742. @app.post("/pause_execution")
  1743. async def pause_execution():
  1744. status = execution.get_cached_status()
  1745. if not (status.get("is_running") or status.get("pause_time_remaining")):
  1746. raise HTTPException(status_code=400, detail="Nothing is currently playing")
  1747. try:
  1748. await execution.pause()
  1749. return {"success": True, "message": "Execution paused"}
  1750. except Exception as e:
  1751. raise HTTPException(status_code=500, detail=f"Failed to pause execution: {e}")
  1752. @app.post("/resume_execution")
  1753. async def resume_execution():
  1754. if not execution.get_cached_status().get("is_paused"):
  1755. raise HTTPException(status_code=400, detail="Execution is not paused")
  1756. try:
  1757. await execution.resume()
  1758. return {"success": True, "message": "Execution resumed"}
  1759. except Exception as e:
  1760. raise HTTPException(status_code=500, detail=f"Failed to resume execution: {e}")
  1761. # Playlist endpoints
  1762. @app.get("/list_all_playlists")
  1763. async def list_all_playlists():
  1764. playlist_names = playlist_manager.list_all_playlists()
  1765. return playlist_names
  1766. @app.get("/get_playlist")
  1767. async def get_playlist(name: str):
  1768. if not name:
  1769. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  1770. playlist = playlist_manager.get_playlist(name)
  1771. if not playlist:
  1772. # Auto-create empty playlist if not found
  1773. logger.info(f"Playlist '{name}' not found, creating empty playlist")
  1774. playlist_manager.create_playlist(name, [])
  1775. playlist = {"name": name, "files": []}
  1776. return playlist
  1777. @app.post("/create_playlist")
  1778. async def create_playlist(request: PlaylistRequest):
  1779. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  1780. return {
  1781. "success": success,
  1782. "message": f"Playlist '{request.playlist_name}' created/updated"
  1783. }
  1784. @app.post("/modify_playlist")
  1785. async def modify_playlist(request: PlaylistRequest):
  1786. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  1787. return {
  1788. "success": success,
  1789. "message": f"Playlist '{request.playlist_name}' updated"
  1790. }
  1791. @app.delete("/delete_playlist")
  1792. async def delete_playlist(request: DeletePlaylistRequest):
  1793. success = playlist_manager.delete_playlist(request.playlist_name)
  1794. if not success:
  1795. raise HTTPException(
  1796. status_code=404,
  1797. detail=f"Playlist '{request.playlist_name}' not found"
  1798. )
  1799. return {
  1800. "success": True,
  1801. "message": f"Playlist '{request.playlist_name}' deleted"
  1802. }
  1803. @app.post("/rename_playlist")
  1804. async def rename_playlist(request: RenamePlaylistRequest):
  1805. """Rename an existing playlist."""
  1806. success, message = playlist_manager.rename_playlist(request.old_name, request.new_name)
  1807. if not success:
  1808. raise HTTPException(
  1809. status_code=400,
  1810. detail=message
  1811. )
  1812. return {
  1813. "success": True,
  1814. "message": message,
  1815. "new_name": request.new_name
  1816. }
  1817. class AddToPlaylistRequest(BaseModel):
  1818. playlist_name: str
  1819. pattern: str
  1820. @app.post("/add_to_playlist")
  1821. async def add_to_playlist(request: AddToPlaylistRequest):
  1822. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  1823. if not success:
  1824. raise HTTPException(status_code=404, detail="Playlist not found")
  1825. return {"success": True}
  1826. @app.post("/run_playlist")
  1827. async def run_playlist_endpoint(request: PlaylistRequest):
  1828. """Run a playlist on the board ($Playlist/Run; the firmware sequences it)."""
  1829. if not (state.conn.is_connected() if state.conn else False):
  1830. logger.warning("Attempted to run a playlist without a connection")
  1831. raise HTTPException(status_code=400, detail="Connection not established")
  1832. check_homing_in_progress()
  1833. try:
  1834. await execution.start_playlist(
  1835. request.playlist_name,
  1836. run_mode=request.run_mode,
  1837. pause_time=request.pause_time,
  1838. clear_pattern=request.clear_pattern,
  1839. shuffle=request.shuffle,
  1840. )
  1841. return {"message": f"Started playlist: {request.playlist_name}"}
  1842. except execution.ExecutionError as e:
  1843. detail = str(e)
  1844. status = 404 if "not found" in detail else 409
  1845. raise HTTPException(status_code=status, detail=detail)
  1846. except Exception as e:
  1847. logger.error(f"Error running playlist: {e}")
  1848. raise HTTPException(status_code=500, detail=str(e))
  1849. @app.post("/set_speed")
  1850. async def set_speed(request: SpeedRequest):
  1851. try:
  1852. if not (state.conn.is_connected() if state.conn else False):
  1853. logger.warning("Attempted to change speed without a connection")
  1854. raise HTTPException(status_code=400, detail="Connection not established")
  1855. if request.speed <= 0:
  1856. logger.warning(f"Invalid speed value received: {request.speed}")
  1857. raise HTTPException(status_code=400, detail="Invalid speed value")
  1858. state.speed = request.speed
  1859. # Push the feed live to the board (works mid-pattern; persists across the run).
  1860. try:
  1861. await asyncio.to_thread(state.conn.set_feed, int(request.speed))
  1862. except Exception as e:
  1863. logger.warning(f"Could not push feed to board: {e}")
  1864. return {"success": True, "speed": request.speed}
  1865. except HTTPException:
  1866. raise # Re-raise HTTPException as-is
  1867. except Exception as e:
  1868. logger.error(f"Failed to set speed: {str(e)}")
  1869. raise HTTPException(status_code=500, detail=str(e))
  1870. @app.get("/check_software_update")
  1871. async def check_updates():
  1872. update_info = update_manager.check_git_updates()
  1873. return update_info
  1874. @app.post("/update_software")
  1875. async def update_software():
  1876. logger.info("Starting software update process")
  1877. success, error_message, error_log = update_manager.update_software()
  1878. if success:
  1879. logger.info("Software update completed successfully")
  1880. return {"success": True}
  1881. else:
  1882. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  1883. raise HTTPException(
  1884. status_code=500,
  1885. detail={
  1886. "error": error_message,
  1887. "details": error_log
  1888. }
  1889. )
  1890. @app.post("/set_wled_ip")
  1891. async def set_wled_ip(request: WLEDRequest):
  1892. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  1893. state.wled_ip = request.wled_ip
  1894. state.led_provider = "wled" if request.wled_ip else "none"
  1895. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  1896. if state.led_controller:
  1897. state.led_controller.effect_idle()
  1898. _start_idle_led_timeout()
  1899. state.save()
  1900. logger.info(f"WLED IP updated: {request.wled_ip}")
  1901. return {"success": True, "wled_ip": state.wled_ip}
  1902. @app.get("/get_wled_ip")
  1903. async def get_wled_ip():
  1904. """Legacy endpoint for backward compatibility"""
  1905. if not state.wled_ip:
  1906. raise HTTPException(status_code=404, detail="No WLED IP set")
  1907. return {"success": True, "wled_ip": state.wled_ip}
  1908. @app.post("/set_led_config", deprecated=True, tags=["settings-deprecated"])
  1909. async def set_led_config(request: LEDConfigRequest):
  1910. """DEPRECATED: Use PATCH /api/settings instead. Configure LED provider (board, WLED, or none)"""
  1911. if request.provider not in ["wled", "board", "none"]:
  1912. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'board', 'wled', or 'none'")
  1913. state.led_provider = request.provider
  1914. if request.provider == "wled":
  1915. if not request.ip_address:
  1916. raise HTTPException(status_code=400, detail="IP address required for WLED")
  1917. state.wled_ip = request.ip_address
  1918. state.led_controller = LEDInterface("wled", request.ip_address)
  1919. logger.info(f"LED provider set to WLED at {request.ip_address}")
  1920. elif request.provider == "board":
  1921. # The table's own LED ring, driven by the FluidNC firmware.
  1922. state.led_controller = LEDInterface("board")
  1923. logger.info("LED provider set to the table's built-in LEDs (firmware-controlled)")
  1924. else: # none
  1925. state.wled_ip = None
  1926. state.led_controller = None
  1927. logger.info("LED provider disabled")
  1928. # Show idle effect if controller is configured
  1929. if state.led_controller:
  1930. state.led_controller.effect_idle()
  1931. _start_idle_led_timeout()
  1932. state.save()
  1933. return {
  1934. "success": True,
  1935. "provider": state.led_provider,
  1936. "wled_ip": state.wled_ip,
  1937. }
  1938. @app.get("/get_led_config", deprecated=True, tags=["settings-deprecated"])
  1939. async def get_led_config():
  1940. """DEPRECATED: Use GET /api/settings instead. Get current LED provider configuration"""
  1941. # Auto-detect provider for backward compatibility with existing installations
  1942. provider = state.led_provider
  1943. if not provider or provider == "none":
  1944. # If no provider set but we have IPs configured, auto-detect
  1945. if state.wled_ip:
  1946. provider = "wled"
  1947. state.led_provider = "wled"
  1948. state.save()
  1949. logger.info("Auto-detected WLED provider from existing configuration")
  1950. else:
  1951. provider = "none"
  1952. return {
  1953. "success": True,
  1954. "provider": provider,
  1955. "wled_ip": state.wled_ip,
  1956. }
  1957. @app.post("/skip_pattern")
  1958. async def skip_pattern():
  1959. try:
  1960. skipped = await execution.skip()
  1961. except execution.ExecutionError as e:
  1962. raise HTTPException(status_code=400, detail=str(e))
  1963. if not skipped:
  1964. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1965. return {"success": True}
  1966. @app.get("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1967. async def get_custom_clear_patterns():
  1968. """Get the currently configured custom clear patterns."""
  1969. return {
  1970. "success": True,
  1971. "custom_clear_from_in": state.custom_clear_from_in,
  1972. "custom_clear_from_out": state.custom_clear_from_out
  1973. }
  1974. @app.post("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1975. async def set_custom_clear_patterns(request: dict):
  1976. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1977. try:
  1978. # Validate that the patterns exist if they're provided
  1979. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1980. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1981. if not os.path.exists(pattern_path):
  1982. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1983. state.custom_clear_from_in = request["custom_clear_from_in"]
  1984. elif "custom_clear_from_in" in request:
  1985. state.custom_clear_from_in = None
  1986. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1987. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1988. if not os.path.exists(pattern_path):
  1989. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1990. state.custom_clear_from_out = request["custom_clear_from_out"]
  1991. elif "custom_clear_from_out" in request:
  1992. state.custom_clear_from_out = None
  1993. state.save()
  1994. # The firmware runs its own clear files; mirror the choice onto them.
  1995. board_settings.push_custom_clears_async()
  1996. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1997. return {
  1998. "success": True,
  1999. "custom_clear_from_in": state.custom_clear_from_in,
  2000. "custom_clear_from_out": state.custom_clear_from_out
  2001. }
  2002. except Exception as e:
  2003. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  2004. raise HTTPException(status_code=500, detail=str(e))
  2005. @app.get("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  2006. async def get_clear_pattern_speed():
  2007. """Get the current clearing pattern speed setting."""
  2008. return {
  2009. "success": True,
  2010. "clear_pattern_speed": state.clear_pattern_speed,
  2011. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  2012. }
  2013. @app.post("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  2014. async def set_clear_pattern_speed(request: dict):
  2015. """DEPRECATED: Use PATCH /api/settings instead. Set the clearing pattern speed."""
  2016. try:
  2017. # If speed is None or "none", use default behavior (state.speed)
  2018. speed_value = request.get("clear_pattern_speed")
  2019. if speed_value is None or speed_value == "none" or speed_value == "":
  2020. speed = None
  2021. else:
  2022. speed = int(speed_value)
  2023. # Validate speed range (same as regular speed limits) only if speed is not None
  2024. if speed is not None and not (50 <= speed <= 2000):
  2025. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  2026. state.clear_pattern_speed = speed
  2027. state.save()
  2028. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  2029. return {
  2030. "success": True,
  2031. "clear_pattern_speed": state.clear_pattern_speed,
  2032. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  2033. }
  2034. except ValueError:
  2035. raise HTTPException(status_code=400, detail="Invalid speed value")
  2036. except Exception as e:
  2037. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  2038. raise HTTPException(status_code=500, detail=str(e))
  2039. @app.get("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  2040. async def get_app_name():
  2041. """DEPRECATED: Use GET /api/settings instead. Get current application name."""
  2042. return {"app_name": state.app_name}
  2043. @app.post("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  2044. async def set_app_name(request: dict):
  2045. """DEPRECATED: Use PATCH /api/settings instead. Update application name."""
  2046. app_name = request.get("app_name", "").strip()
  2047. if not app_name:
  2048. app_name = "Dune Weaver" # Reset to default if empty
  2049. state.app_name = app_name
  2050. state.save()
  2051. logger.info(f"Application name updated to: {app_name}")
  2052. return {"success": True, "app_name": app_name}
  2053. # ============================================================================
  2054. # Custom Branding Upload Endpoints
  2055. # ============================================================================
  2056. CUSTOM_BRANDING_DIR = os.path.join("static", "custom")
  2057. ALLOWED_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"}
  2058. MAX_LOGO_SIZE = 10 * 1024 * 1024 # 10MB
  2059. MAX_LOGO_DIMENSION = 512 # Max width/height for optimized logo
  2060. def optimize_logo_image(content: bytes, original_ext: str) -> tuple[bytes, str]:
  2061. """Optimize logo image by resizing and converting to WebP.
  2062. Args:
  2063. content: Original image bytes
  2064. original_ext: Original file extension (e.g., '.png', '.jpg')
  2065. Returns:
  2066. Tuple of (optimized_bytes, new_extension)
  2067. For SVG files, returns the original content unchanged.
  2068. For raster images, resizes to MAX_LOGO_DIMENSION and converts to WebP.
  2069. """
  2070. # SVG files are already lightweight vectors - keep as-is
  2071. if original_ext.lower() == ".svg":
  2072. return content, original_ext
  2073. try:
  2074. from PIL import Image
  2075. import io
  2076. with Image.open(io.BytesIO(content)) as img:
  2077. # Convert to RGBA for transparency support
  2078. if img.mode in ('P', 'LA') or (img.mode == 'RGBA' and 'transparency' in img.info):
  2079. img = img.convert('RGBA')
  2080. elif img.mode != 'RGBA':
  2081. img = img.convert('RGB')
  2082. # Resize if larger than max dimension (maintain aspect ratio)
  2083. width, height = img.size
  2084. if width > MAX_LOGO_DIMENSION or height > MAX_LOGO_DIMENSION:
  2085. ratio = min(MAX_LOGO_DIMENSION / width, MAX_LOGO_DIMENSION / height)
  2086. new_size = (int(width * ratio), int(height * ratio))
  2087. img = img.resize(new_size, Image.Resampling.LANCZOS)
  2088. logger.info(f"Logo resized from {width}x{height} to {new_size[0]}x{new_size[1]}")
  2089. # Save as WebP with good quality/size balance
  2090. output = io.BytesIO()
  2091. img.save(output, format='WEBP', quality=85, method=6)
  2092. optimized_bytes = output.getvalue()
  2093. original_size = len(content)
  2094. new_size = len(optimized_bytes)
  2095. reduction = ((original_size - new_size) / original_size) * 100
  2096. logger.info(f"Logo optimized: {original_size:,} bytes -> {new_size:,} bytes ({reduction:.1f}% reduction)")
  2097. return optimized_bytes, ".webp"
  2098. except Exception as e:
  2099. logger.warning(f"Logo optimization failed, using original: {str(e)}")
  2100. return content, original_ext
  2101. def generate_favicon_from_logo(logo_path: str, output_dir: str) -> bool:
  2102. """Generate circular favicons with transparent background from the uploaded logo.
  2103. Creates:
  2104. - favicon.ico (multi-size: 256, 128, 64, 48, 32, 16)
  2105. - favicon-16x16.png, favicon-32x32.png, favicon-96x96.png, favicon-128x128.png
  2106. Returns True on success, False on failure.
  2107. """
  2108. try:
  2109. from PIL import Image, ImageDraw
  2110. def create_circular_transparent(img, size):
  2111. """Create circular image with transparent background."""
  2112. resized = img.resize((size, size), Image.Resampling.LANCZOS)
  2113. mask = Image.new('L', (size, size), 0)
  2114. draw = ImageDraw.Draw(mask)
  2115. draw.ellipse((0, 0, size - 1, size - 1), fill=255)
  2116. output = Image.new('RGBA', (size, size), (0, 0, 0, 0))
  2117. output.paste(resized, (0, 0), mask)
  2118. return output
  2119. with Image.open(logo_path) as img:
  2120. # Convert to RGBA if needed
  2121. if img.mode != 'RGBA':
  2122. img = img.convert('RGBA')
  2123. # Crop to square (center crop)
  2124. width, height = img.size
  2125. min_dim = min(width, height)
  2126. left = (width - min_dim) // 2
  2127. top = (height - min_dim) // 2
  2128. img = img.crop((left, top, left + min_dim, top + min_dim))
  2129. # Generate circular favicon PNGs with transparent background
  2130. png_sizes = {
  2131. "favicon-16x16.png": 16,
  2132. "favicon-32x32.png": 32,
  2133. "favicon-96x96.png": 96,
  2134. "favicon-128x128.png": 128,
  2135. }
  2136. for filename, size in png_sizes.items():
  2137. icon = create_circular_transparent(img, size)
  2138. icon.save(os.path.join(output_dir, filename), format='PNG')
  2139. # Generate high-resolution favicon.ico
  2140. ico_sizes = [256, 128, 64, 48, 32, 16]
  2141. ico_images = [create_circular_transparent(img, s) for s in ico_sizes]
  2142. ico_images[0].save(
  2143. os.path.join(output_dir, "favicon.ico"),
  2144. format='ICO',
  2145. append_images=ico_images[1:],
  2146. sizes=[(s, s) for s in ico_sizes]
  2147. )
  2148. return True
  2149. except Exception as e:
  2150. logger.error(f"Failed to generate favicon: {str(e)}")
  2151. return False
  2152. def generate_pwa_icons_from_logo(logo_path: str, output_dir: str) -> bool:
  2153. """Generate square PWA app icons from the uploaded logo.
  2154. Creates square icons (no circular crop) - OS will apply its own mask.
  2155. Composites onto a solid background to avoid transparency issues
  2156. (iOS fills transparent areas with white on home screen icons).
  2157. Generates:
  2158. - apple-touch-icon.png (180x180)
  2159. - android-chrome-192x192.png (192x192)
  2160. - android-chrome-512x512.png (512x512)
  2161. Returns True on success, False on failure.
  2162. """
  2163. try:
  2164. from PIL import Image
  2165. with Image.open(logo_path) as img:
  2166. # Convert to RGBA if needed
  2167. if img.mode != 'RGBA':
  2168. img = img.convert('RGBA')
  2169. # Crop to square (center crop)
  2170. width, height = img.size
  2171. min_dim = min(width, height)
  2172. left = (width - min_dim) // 2
  2173. top = (height - min_dim) // 2
  2174. img = img.crop((left, top, left + min_dim, top + min_dim))
  2175. # Generate square icons at each required size
  2176. icon_sizes = {
  2177. "apple-touch-icon.png": 180,
  2178. "android-chrome-192x192.png": 192,
  2179. "android-chrome-512x512.png": 512,
  2180. }
  2181. for filename, size in icon_sizes.items():
  2182. resized = img.resize((size, size), Image.Resampling.LANCZOS)
  2183. # Composite onto solid background to eliminate transparency
  2184. # (iOS shows white behind transparent areas on home screen)
  2185. background = Image.new('RGB', (size, size), (10, 10, 10)) # #0a0a0a theme color
  2186. background.paste(resized, (0, 0), resized) # Use resized as its own alpha mask
  2187. icon_path = os.path.join(output_dir, filename)
  2188. background.save(icon_path, format='PNG')
  2189. logger.info(f"Generated PWA icon: {filename}")
  2190. return True
  2191. except Exception as e:
  2192. logger.error(f"Failed to generate PWA icons: {str(e)}")
  2193. return False
  2194. @app.post("/api/upload-logo", tags=["settings"])
  2195. async def upload_logo(file: UploadFile = File(...)):
  2196. """Upload a custom logo image.
  2197. Supported formats: PNG, JPG, JPEG, GIF, WebP, SVG
  2198. Maximum upload size: 10MB
  2199. Images are automatically optimized:
  2200. - Resized to max 512x512 pixels
  2201. - Converted to WebP format for smaller file size
  2202. - SVG files are kept as-is (already lightweight)
  2203. A favicon and PWA icons will be automatically generated from the logo.
  2204. """
  2205. try:
  2206. # Validate file extension
  2207. file_ext = os.path.splitext(file.filename)[1].lower()
  2208. if file_ext not in ALLOWED_IMAGE_EXTENSIONS:
  2209. raise HTTPException(
  2210. status_code=400,
  2211. detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}"
  2212. )
  2213. # Read and validate file size
  2214. content = await file.read()
  2215. if len(content) > MAX_LOGO_SIZE:
  2216. raise HTTPException(
  2217. status_code=400,
  2218. detail=f"File too large. Maximum size: {MAX_LOGO_SIZE // (1024*1024)}MB"
  2219. )
  2220. # Ensure custom branding directory exists
  2221. os.makedirs(CUSTOM_BRANDING_DIR, exist_ok=True)
  2222. # Delete old logo and favicon if they exist
  2223. if state.custom_logo:
  2224. old_logo_path = os.path.join(CUSTOM_BRANDING_DIR, state.custom_logo)
  2225. if os.path.exists(old_logo_path):
  2226. os.remove(old_logo_path)
  2227. # Also remove old favicon
  2228. old_favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  2229. if os.path.exists(old_favicon_path):
  2230. os.remove(old_favicon_path)
  2231. # Optimize the image (resize + convert to WebP for smaller file size)
  2232. optimized_content, optimized_ext = optimize_logo_image(content, file_ext)
  2233. # Generate a unique filename to prevent caching issues
  2234. import uuid
  2235. filename = f"logo-{uuid.uuid4().hex[:8]}{optimized_ext}"
  2236. file_path = os.path.join(CUSTOM_BRANDING_DIR, filename)
  2237. # Save the optimized logo file
  2238. with open(file_path, "wb") as f:
  2239. f.write(optimized_content)
  2240. # Generate favicon and PWA icons from logo (for non-SVG files)
  2241. favicon_generated = False
  2242. pwa_icons_generated = False
  2243. if optimized_ext != ".svg":
  2244. favicon_generated = generate_favicon_from_logo(file_path, CUSTOM_BRANDING_DIR)
  2245. pwa_icons_generated = generate_pwa_icons_from_logo(file_path, CUSTOM_BRANDING_DIR)
  2246. # Update state
  2247. state.custom_logo = filename
  2248. state.save()
  2249. logger.info(f"Custom logo uploaded: {filename}, favicon generated: {favicon_generated}, PWA icons generated: {pwa_icons_generated}")
  2250. return {
  2251. "success": True,
  2252. "filename": filename,
  2253. "url": f"/static/custom/{filename}",
  2254. "favicon_generated": favicon_generated,
  2255. "pwa_icons_generated": pwa_icons_generated
  2256. }
  2257. except HTTPException:
  2258. raise
  2259. except Exception as e:
  2260. logger.error(f"Error uploading logo: {str(e)}")
  2261. raise HTTPException(status_code=500, detail=str(e))
  2262. @app.delete("/api/custom-logo", tags=["settings"])
  2263. async def delete_custom_logo():
  2264. """Remove custom logo, favicon, and PWA icons, reverting to defaults."""
  2265. try:
  2266. if state.custom_logo:
  2267. # Remove logo
  2268. logo_path = os.path.join(CUSTOM_BRANDING_DIR, state.custom_logo)
  2269. if os.path.exists(logo_path):
  2270. os.remove(logo_path)
  2271. # Remove generated favicons
  2272. favicon_files = [
  2273. "favicon.ico",
  2274. "favicon-16x16.png",
  2275. "favicon-32x32.png",
  2276. "favicon-96x96.png",
  2277. "favicon-128x128.png",
  2278. ]
  2279. for favicon_name in favicon_files:
  2280. favicon_path = os.path.join(CUSTOM_BRANDING_DIR, favicon_name)
  2281. if os.path.exists(favicon_path):
  2282. os.remove(favicon_path)
  2283. # Remove generated PWA icons
  2284. pwa_icons = [
  2285. "apple-touch-icon.png",
  2286. "android-chrome-192x192.png",
  2287. "android-chrome-512x512.png",
  2288. ]
  2289. for icon_name in pwa_icons:
  2290. icon_path = os.path.join(CUSTOM_BRANDING_DIR, icon_name)
  2291. if os.path.exists(icon_path):
  2292. os.remove(icon_path)
  2293. state.custom_logo = None
  2294. state.save()
  2295. logger.info("Custom logo, favicon, and PWA icons removed")
  2296. return {"success": True}
  2297. except Exception as e:
  2298. logger.error(f"Error removing logo: {str(e)}")
  2299. raise HTTPException(status_code=500, detail=str(e))
  2300. @app.get("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  2301. async def get_mqtt_config():
  2302. """DEPRECATED: Use GET /api/settings instead. Get current MQTT configuration.
  2303. Note: Password is not returned for security reasons.
  2304. """
  2305. from modules.mqtt import get_mqtt_handler
  2306. handler = get_mqtt_handler()
  2307. return {
  2308. "enabled": state.mqtt_enabled,
  2309. "broker": state.mqtt_broker,
  2310. "port": state.mqtt_port,
  2311. "username": state.mqtt_username,
  2312. # Password is intentionally omitted for security
  2313. "has_password": bool(state.mqtt_password),
  2314. "client_id": state.mqtt_client_id,
  2315. "discovery_prefix": state.mqtt_discovery_prefix,
  2316. "device_id": state.mqtt_device_id,
  2317. "device_name": state.mqtt_device_name,
  2318. "connected": handler.is_connected if hasattr(handler, 'is_connected') else False,
  2319. "is_mock": handler.__class__.__name__ == 'MockMQTTHandler'
  2320. }
  2321. @app.post("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  2322. async def set_mqtt_config(request: dict):
  2323. """DEPRECATED: Use PATCH /api/settings instead. Update MQTT configuration. Requires restart to take effect."""
  2324. try:
  2325. # Update state with new values
  2326. state.mqtt_enabled = request.get("enabled", False)
  2327. state.mqtt_broker = (request.get("broker") or "").strip()
  2328. state.mqtt_port = int(request.get("port") or 1883)
  2329. state.mqtt_username = (request.get("username") or "").strip()
  2330. state.mqtt_password = (request.get("password") or "").strip()
  2331. state.mqtt_client_id = (request.get("client_id") or "dune_weaver").strip()
  2332. state.mqtt_discovery_prefix = (request.get("discovery_prefix") or "homeassistant").strip()
  2333. state.mqtt_device_id = (request.get("device_id") or "dune_weaver").strip()
  2334. state.mqtt_device_name = (request.get("device_name") or "Dune Weaver").strip()
  2335. # Validate required fields when enabled
  2336. if state.mqtt_enabled and not state.mqtt_broker:
  2337. return JSONResponse(
  2338. content={"success": False, "message": "Broker address is required when MQTT is enabled"},
  2339. status_code=400
  2340. )
  2341. state.save()
  2342. logger.info(f"MQTT configuration updated. Enabled: {state.mqtt_enabled}, Broker: {state.mqtt_broker}")
  2343. return {
  2344. "success": True,
  2345. "message": "MQTT configuration saved. Restart the application for changes to take effect.",
  2346. "requires_restart": True
  2347. }
  2348. except ValueError as e:
  2349. return JSONResponse(
  2350. content={"success": False, "message": f"Invalid value: {str(e)}"},
  2351. status_code=400
  2352. )
  2353. except Exception as e:
  2354. logger.error(f"Failed to update MQTT config: {str(e)}")
  2355. return JSONResponse(
  2356. content={"success": False, "message": str(e)},
  2357. status_code=500
  2358. )
  2359. @app.post("/api/mqtt-test")
  2360. async def test_mqtt_connection(request: dict):
  2361. """Test MQTT connection with provided settings."""
  2362. import paho.mqtt.client as mqtt_client
  2363. broker = (request.get("broker") or "").strip()
  2364. port = int(request.get("port") or 1883)
  2365. username = (request.get("username") or "").strip()
  2366. password = (request.get("password") or "").strip()
  2367. client_id = (request.get("client_id") or "dune_weaver_test").strip()
  2368. if not broker:
  2369. return JSONResponse(
  2370. content={"success": False, "message": "Broker address is required"},
  2371. status_code=400
  2372. )
  2373. try:
  2374. # Create a test client
  2375. client = mqtt_client.Client(client_id=client_id + "_test")
  2376. if username:
  2377. client.username_pw_set(username, password)
  2378. # Connection result
  2379. connection_result = {"connected": False, "error": None}
  2380. def on_connect(client, userdata, flags, rc):
  2381. if rc == 0:
  2382. connection_result["connected"] = True
  2383. else:
  2384. error_messages = {
  2385. 1: "Incorrect protocol version",
  2386. 2: "Invalid client identifier",
  2387. 3: "Server unavailable",
  2388. 4: "Bad username or password",
  2389. 5: "Not authorized"
  2390. }
  2391. connection_result["error"] = error_messages.get(rc, f"Connection failed with code {rc}")
  2392. client.on_connect = on_connect
  2393. # Try to connect with timeout
  2394. client.connect_async(broker, port, keepalive=10)
  2395. client.loop_start()
  2396. # Wait for connection result (max 5 seconds)
  2397. import time
  2398. start_time = time.time()
  2399. while time.time() - start_time < 5:
  2400. if connection_result["connected"] or connection_result["error"]:
  2401. break
  2402. await asyncio.sleep(0.1)
  2403. client.loop_stop()
  2404. client.disconnect()
  2405. if connection_result["connected"]:
  2406. return {"success": True, "message": "Successfully connected to MQTT broker"}
  2407. elif connection_result["error"]:
  2408. return JSONResponse(
  2409. content={"success": False, "message": connection_result["error"]},
  2410. status_code=400
  2411. )
  2412. else:
  2413. return JSONResponse(
  2414. content={"success": False, "message": "Connection timed out. Check broker address and port."},
  2415. status_code=400
  2416. )
  2417. except Exception as e:
  2418. logger.error(f"MQTT test connection failed: {str(e)}")
  2419. return JSONResponse(
  2420. content={"success": False, "message": str(e)},
  2421. status_code=500
  2422. )
  2423. def _read_and_encode_preview(cache_path: str) -> str:
  2424. """Read preview image from disk and encode as base64.
  2425. Combines file I/O and base64 encoding in a single function
  2426. to be run in executor, reducing context switches.
  2427. """
  2428. with open(cache_path, 'rb') as f:
  2429. image_data = f.read()
  2430. return base64.b64encode(image_data).decode('utf-8')
  2431. @app.post("/preview_thr_batch")
  2432. async def preview_thr_batch(request: dict):
  2433. start = time.time()
  2434. if not request.get("file_names"):
  2435. logger.warning("Batch preview request received without filenames")
  2436. raise HTTPException(status_code=400, detail="No file names provided")
  2437. file_names = request["file_names"]
  2438. if not isinstance(file_names, list):
  2439. raise HTTPException(status_code=400, detail="file_names must be a list")
  2440. headers = {
  2441. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  2442. "Content-Type": "application/json"
  2443. }
  2444. async def process_single_file(file_name):
  2445. """Process a single file and return its preview data."""
  2446. # Check in-memory cache first (for current and next playing patterns)
  2447. normalized_for_cache = normalize_file_path(file_name)
  2448. if state._current_preview and state._current_preview[0] == normalized_for_cache:
  2449. logger.debug(f"Using cached preview for current: {file_name}")
  2450. return file_name, state._current_preview[1]
  2451. if state._next_preview and state._next_preview[0] == normalized_for_cache:
  2452. logger.debug(f"Using cached preview for next: {file_name}")
  2453. return file_name, state._next_preview[1]
  2454. # Acquire semaphore to limit concurrent processing
  2455. async with get_preview_semaphore():
  2456. t1 = time.time()
  2457. try:
  2458. # Normalize file path for cross-platform compatibility
  2459. normalized_file_name = normalize_file_path(file_name)
  2460. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  2461. # Check file existence asynchronously
  2462. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  2463. if not exists:
  2464. logger.warning(f"Pattern file not found: {pattern_file_path}")
  2465. return file_name, {"error": "Pattern file not found"}
  2466. cache_path = get_cache_path(normalized_file_name)
  2467. # Check cache existence asynchronously
  2468. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  2469. if not cache_exists:
  2470. logger.info(f"Cache miss for {file_name}. Generating preview...")
  2471. success = await generate_image_preview(normalized_file_name)
  2472. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  2473. if not success or not cache_exists_after:
  2474. logger.error(f"Failed to generate or find preview for {file_name}")
  2475. return file_name, {"error": "Failed to generate preview"}
  2476. metadata = get_pattern_metadata(normalized_file_name)
  2477. if metadata:
  2478. first_coord_obj = metadata.get('first_coordinate')
  2479. last_coord_obj = metadata.get('last_coordinate')
  2480. else:
  2481. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  2482. # Use thread pool to avoid memory pressure on resource-constrained devices
  2483. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  2484. first_coord = coordinates[0] if coordinates else None
  2485. last_coord = coordinates[-1] if coordinates else None
  2486. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  2487. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  2488. # Read image file and encode in executor to avoid blocking event loop
  2489. loop = asyncio.get_running_loop()
  2490. image_b64 = await loop.run_in_executor(None, _read_and_encode_preview, cache_path)
  2491. result = {
  2492. "image_data": f"data:image/webp;base64,{image_b64}",
  2493. "first_coordinate": first_coord_obj,
  2494. "last_coordinate": last_coord_obj
  2495. }
  2496. # Cache preview for current/next pattern to speed up subsequent requests
  2497. current_file = state.current_playing_file
  2498. if current_file:
  2499. current_normalized = normalize_file_path(current_file)
  2500. if normalized_file_name == current_normalized:
  2501. state._current_preview = (normalized_file_name, result)
  2502. logger.debug(f"Cached preview for current: {file_name}")
  2503. elif state.current_playlist:
  2504. # Check if this is the next pattern in playlist
  2505. playlist = state.current_playlist
  2506. status_pl = execution.get_cached_status().get("playlist") or {}
  2507. idx = status_pl.get("current_index")
  2508. if idx is not None and idx + 1 < len(playlist):
  2509. next_file = normalize_file_path(playlist[idx + 1])
  2510. if normalized_file_name == next_file:
  2511. state._next_preview = (normalized_file_name, result)
  2512. logger.debug(f"Cached preview for next: {file_name}")
  2513. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  2514. return file_name, result
  2515. except Exception as e:
  2516. logger.error(f"Error processing {file_name}: {str(e)}")
  2517. return file_name, {"error": str(e)}
  2518. # Process all files concurrently
  2519. tasks = [process_single_file(file_name) for file_name in file_names]
  2520. file_results = await asyncio.gather(*tasks)
  2521. # Convert results to dictionary
  2522. results = dict(file_results)
  2523. logger.debug(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  2524. return JSONResponse(content=results, headers=headers)
  2525. @app.get("/playlists")
  2526. async def playlists_page(request: Request):
  2527. return get_redirect_response(request)
  2528. @app.get("/image2sand")
  2529. async def image2sand_page(request: Request):
  2530. return get_redirect_response(request)
  2531. @app.get("/led")
  2532. async def led_control_page(request: Request):
  2533. return get_redirect_response(request)
  2534. # DW LED control endpoints
  2535. @app.get("/api/dw_leds/status")
  2536. async def dw_leds_status():
  2537. """Get DW LED controller status"""
  2538. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2539. return {"connected": False, "message": "DW LEDs not configured"}
  2540. try:
  2541. return state.led_controller.check_status()
  2542. except Exception as e:
  2543. logger.error(f"Failed to check DW LED status: {str(e)}")
  2544. return {"connected": False, "message": str(e)}
  2545. @app.post("/api/dw_leds/power")
  2546. async def dw_leds_power(request: dict):
  2547. """Control DW LED power (0=off, 1=on, 2=toggle)"""
  2548. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2549. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2550. state_value = request.get("state", 1)
  2551. if state_value not in [0, 1, 2]:
  2552. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  2553. try:
  2554. result = state.led_controller.set_power(state_value)
  2555. # Reset idle timeout when LEDs are manually powered on (only if idle timeout is enabled)
  2556. # This prevents idle timeout from immediately turning them back off
  2557. if state_value in [1, 2] and state.dw_led_idle_timeout_enabled: # Power on or toggle
  2558. state.dw_led_last_activity_time = time.time()
  2559. logger.debug("LED activity time reset due to manual power on")
  2560. return result
  2561. except Exception as e:
  2562. logger.error(f"Failed to set DW LED power: {str(e)}")
  2563. raise HTTPException(status_code=500, detail=str(e))
  2564. @app.post("/api/dw_leds/brightness")
  2565. async def dw_leds_brightness(request: dict):
  2566. """Set DW LED brightness (0-100)"""
  2567. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2568. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2569. value = request.get("value", 50)
  2570. if not 0 <= value <= 100:
  2571. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  2572. try:
  2573. controller = state.led_controller.get_controller()
  2574. # The value persists where it lives (board NVS / WLED) — no host state.
  2575. return controller.set_brightness(value)
  2576. except Exception as e:
  2577. logger.error(f"Failed to set LED brightness: {str(e)}")
  2578. raise HTTPException(status_code=500, detail=str(e))
  2579. @app.post("/api/dw_leds/color")
  2580. async def dw_leds_color(request: dict):
  2581. """Set solid color (manual UI control - always powers on LEDs)"""
  2582. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2583. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2584. # Accept both formats: {"r": 255, "g": 0, "b": 0} or {"color": [255, 0, 0]}
  2585. if "color" in request:
  2586. color = request["color"]
  2587. if not isinstance(color, list) or len(color) != 3:
  2588. raise HTTPException(status_code=400, detail="Color must be [R, G, B] array")
  2589. r, g, b = color[0], color[1], color[2]
  2590. elif "r" in request and "g" in request and "b" in request:
  2591. r = request["r"]
  2592. g = request["g"]
  2593. b = request["b"]
  2594. else:
  2595. raise HTTPException(status_code=400, detail="Color must include r, g, b fields or color array")
  2596. try:
  2597. controller = state.led_controller.get_controller()
  2598. # Power on LEDs when user manually sets color via UI
  2599. controller.set_power(1)
  2600. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2601. if state.dw_led_idle_timeout_enabled:
  2602. state.dw_led_last_activity_time = time.time()
  2603. return controller.set_color(r, g, b)
  2604. except Exception as e:
  2605. logger.error(f"Failed to set DW LED color: {str(e)}")
  2606. raise HTTPException(status_code=500, detail=str(e))
  2607. @app.post("/api/dw_leds/colors")
  2608. async def dw_leds_colors(request: dict):
  2609. """Set effect colors (color1, color2, color3) - manual UI control - always powers on LEDs"""
  2610. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2611. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2612. # Parse colors from request
  2613. color1 = None
  2614. color2 = None
  2615. color3 = None
  2616. if "color1" in request:
  2617. c = request["color1"]
  2618. if isinstance(c, list) and len(c) == 3:
  2619. color1 = tuple(c)
  2620. else:
  2621. raise HTTPException(status_code=400, detail="color1 must be [R, G, B] array")
  2622. if "color2" in request:
  2623. c = request["color2"]
  2624. if isinstance(c, list) and len(c) == 3:
  2625. color2 = tuple(c)
  2626. else:
  2627. raise HTTPException(status_code=400, detail="color2 must be [R, G, B] array")
  2628. if "color3" in request:
  2629. c = request["color3"]
  2630. if isinstance(c, list) and len(c) == 3:
  2631. color3 = tuple(c)
  2632. else:
  2633. raise HTTPException(status_code=400, detail="color3 must be [R, G, B] array")
  2634. if not any([color1, color2, color3]):
  2635. raise HTTPException(status_code=400, detail="Must provide at least one color")
  2636. try:
  2637. controller = state.led_controller.get_controller()
  2638. # Power on LEDs when user manually sets colors via UI
  2639. controller.set_power(1)
  2640. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2641. if state.dw_led_idle_timeout_enabled:
  2642. state.dw_led_last_activity_time = time.time()
  2643. return controller.set_colors(color1=color1, color2=color2, color3=color3)
  2644. except Exception as e:
  2645. logger.error(f"Failed to set DW LED colors: {str(e)}")
  2646. raise HTTPException(status_code=500, detail=str(e))
  2647. @app.get("/api/dw_leds/effects")
  2648. async def dw_leds_effects():
  2649. """Get list of available effects"""
  2650. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2651. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2652. try:
  2653. controller = state.led_controller.get_controller()
  2654. effects = controller.get_effects()
  2655. # Convert tuples to lists for JSON serialization
  2656. effects_list = [[eid, name] for eid, name in effects]
  2657. result = {"success": True, "effects": effects_list}
  2658. # Board provider: also expose the firmware effect *names* (id -> name),
  2659. # which the ball tracker's background sub-effect picker needs.
  2660. if state.led_provider == "board":
  2661. from modules.led.board_led_controller import BOARD_EFFECTS
  2662. result["names"] = [[i, name] for i, (name, _label) in enumerate(BOARD_EFFECTS)]
  2663. return result
  2664. except Exception as e:
  2665. logger.error(f"Failed to get DW LED effects: {str(e)}")
  2666. raise HTTPException(status_code=500, detail=str(e))
  2667. @app.get("/api/dw_leds/palettes")
  2668. async def dw_leds_palettes():
  2669. """Get list of available palettes"""
  2670. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2671. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2672. try:
  2673. controller = state.led_controller.get_controller()
  2674. palettes = controller.get_palettes()
  2675. # Convert tuples to lists for JSON serialization
  2676. palettes_list = [[pid, name] for pid, name in palettes]
  2677. return {
  2678. "success": True,
  2679. "palettes": palettes_list
  2680. }
  2681. except Exception as e:
  2682. logger.error(f"Failed to get DW LED palettes: {str(e)}")
  2683. raise HTTPException(status_code=500, detail=str(e))
  2684. @app.post("/api/dw_leds/effect")
  2685. async def dw_leds_effect(request: dict):
  2686. """Set effect by ID (manual UI control - always powers on LEDs)"""
  2687. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2688. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2689. effect_id = request.get("effect_id", 0)
  2690. speed = request.get("speed")
  2691. intensity = request.get("intensity")
  2692. try:
  2693. controller = state.led_controller.get_controller()
  2694. # Power on LEDs when user manually sets effect via UI
  2695. controller.set_power(1)
  2696. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2697. if state.dw_led_idle_timeout_enabled:
  2698. state.dw_led_last_activity_time = time.time()
  2699. return controller.set_effect(effect_id, speed=speed, intensity=intensity)
  2700. except Exception as e:
  2701. logger.error(f"Failed to set DW LED effect: {str(e)}")
  2702. raise HTTPException(status_code=500, detail=str(e))
  2703. @app.post("/api/dw_leds/palette")
  2704. async def dw_leds_palette(request: dict):
  2705. """Set palette by ID (manual UI control - always powers on LEDs)"""
  2706. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2707. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2708. palette_id = request.get("palette_id", 0)
  2709. try:
  2710. controller = state.led_controller.get_controller()
  2711. # Power on LEDs when user manually sets palette via UI
  2712. controller.set_power(1)
  2713. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2714. if state.dw_led_idle_timeout_enabled:
  2715. state.dw_led_last_activity_time = time.time()
  2716. return controller.set_palette(palette_id)
  2717. except Exception as e:
  2718. logger.error(f"Failed to set DW LED palette: {str(e)}")
  2719. raise HTTPException(status_code=500, detail=str(e))
  2720. @app.post("/api/dw_leds/speed")
  2721. async def dw_leds_speed(request: dict):
  2722. """Set effect speed (0-255)"""
  2723. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2724. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2725. value = request.get("speed", 128)
  2726. if not 0 <= value <= 255:
  2727. raise HTTPException(status_code=400, detail="Speed must be between 0 and 255")
  2728. try:
  2729. controller = state.led_controller.get_controller()
  2730. return controller.set_speed(value)
  2731. except Exception as e:
  2732. logger.error(f"Failed to set LED speed: {str(e)}")
  2733. raise HTTPException(status_code=500, detail=str(e))
  2734. @app.post("/api/dw_leds/ball")
  2735. async def dw_leds_ball(request: dict):
  2736. """Tune the firmware-native 'ball' tracker effect (board provider only).
  2737. Accepts any of: fgbright, bgbright, size, align (ints), direction ('cw'|'ccw'),
  2738. bg (background sub-effect name / 'static' / 'off'), color, color2 (RRGGBB hex).
  2739. Applied live via /sand_led; persisted to the board's NVS at idle.
  2740. """
  2741. if not state.led_controller or state.led_provider != "board":
  2742. raise HTTPException(status_code=400, detail="The ball tracker requires the Table LEDs provider")
  2743. try:
  2744. controller = state.led_controller.get_controller()
  2745. return await asyncio.to_thread(controller.set_ball, **request)
  2746. except Exception as e:
  2747. logger.error(f"Failed to set ball effect: {str(e)}")
  2748. raise HTTPException(status_code=500, detail=str(e))
  2749. @app.post("/api/dw_leds/intensity")
  2750. async def dw_leds_intensity(request: dict):
  2751. """Set effect intensity (0-255)"""
  2752. if not state.led_controller or state.led_provider not in ("dw_leds", "board"):
  2753. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2754. value = request.get("intensity", 128)
  2755. if not 0 <= value <= 255:
  2756. raise HTTPException(status_code=400, detail="Intensity must be between 0 and 255")
  2757. try:
  2758. controller = state.led_controller.get_controller()
  2759. return controller.set_intensity(value)
  2760. except Exception as e:
  2761. logger.error(f"Failed to set LED intensity: {str(e)}")
  2762. raise HTTPException(status_code=500, detail=str(e))
  2763. @app.post("/api/dw_leds/save_effect_settings")
  2764. async def dw_leds_save_effect_settings(request: dict):
  2765. """Save current LED settings as idle or playing effect"""
  2766. effect_type = request.get("type") # 'idle' or 'playing'
  2767. settings = {
  2768. "effect_id": request.get("effect_id"),
  2769. "palette_id": request.get("palette_id"),
  2770. "speed": request.get("speed"),
  2771. "intensity": request.get("intensity"),
  2772. "color1": request.get("color1"),
  2773. "color2": request.get("color2"),
  2774. "color3": request.get("color3")
  2775. }
  2776. if effect_type not in ("idle", "playing"):
  2777. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2778. # Board provider: the firmware switches effects itself — persist the choice
  2779. # as $LED/IdleEffect / $LED/RunEffect on the board instead of host state.
  2780. if state.led_provider == "board":
  2781. from modules.led.board_led_controller import effect_name_for_id
  2782. name = effect_name_for_id(int(settings.get("effect_id") or 0)) or "none"
  2783. controller = state.led_controller.get_controller() if state.led_controller else None
  2784. if not controller:
  2785. raise HTTPException(status_code=409, detail="Table LEDs not configured")
  2786. ok = await asyncio.to_thread(
  2787. controller.set_idle_effect if effect_type == "idle" else controller.set_run_effect, name
  2788. )
  2789. if not ok:
  2790. raise HTTPException(status_code=502, detail="Table rejected the setting (is it idle?)")
  2791. logger.info(f"Board LED {effect_type} effect set to {name}")
  2792. return {"success": True, "type": effect_type, "settings": settings}
  2793. raise HTTPException(status_code=400, detail="Effect automation requires the Table LEDs provider")
  2794. @app.post("/api/dw_leds/clear_effect_settings")
  2795. async def dw_leds_clear_effect_settings(request: dict):
  2796. """Clear idle or playing effect settings"""
  2797. effect_type = request.get("type") # 'idle' or 'playing'
  2798. if effect_type not in ("idle", "playing"):
  2799. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2800. if state.led_provider == "board":
  2801. controller = state.led_controller.get_controller() if state.led_controller else None
  2802. if not controller:
  2803. raise HTTPException(status_code=409, detail="Table LEDs not configured")
  2804. ok = await asyncio.to_thread(
  2805. controller.set_idle_effect if effect_type == "idle" else controller.set_run_effect, "none"
  2806. )
  2807. if not ok:
  2808. raise HTTPException(status_code=502, detail="Table rejected the setting (is it idle?)")
  2809. logger.info(f"Board LED {effect_type} effect disabled")
  2810. return {"success": True, "type": effect_type}
  2811. raise HTTPException(status_code=400, detail="Effect automation requires the Table LEDs provider")
  2812. @app.get("/api/dw_leds/get_effect_settings")
  2813. async def dw_leds_get_effect_settings():
  2814. """Get saved idle and playing effect settings"""
  2815. # Board provider: the choices live on the board ($LED/IdleEffect / RunEffect).
  2816. if state.led_provider == "board" and state.led_controller:
  2817. from modules.led.board_led_controller import effect_id_for_name
  2818. status = await asyncio.to_thread(state.led_controller.check_status)
  2819. if status.get("connected"):
  2820. def as_settings(name):
  2821. if not name or name == "none":
  2822. return None
  2823. return {"effect_id": effect_id_for_name(name), "palette_id": None,
  2824. "speed": None, "intensity": None,
  2825. "color1": None, "color2": None, "color3": None}
  2826. return {
  2827. "idle_effect": as_settings(status.get("idle_effect")),
  2828. "playing_effect": as_settings(status.get("run_effect")),
  2829. }
  2830. return {"idle_effect": None, "playing_effect": None}
  2831. @app.post("/api/dw_leds/idle_timeout")
  2832. async def dw_leds_set_idle_timeout(request: dict):
  2833. """Configure LED idle timeout settings"""
  2834. enabled = request.get("enabled", False)
  2835. minutes = request.get("minutes", 30)
  2836. # Validate minutes (between 1 and 1440 - 24 hours)
  2837. if minutes < 1 or minutes > 1440:
  2838. raise HTTPException(status_code=400, detail="Timeout must be between 1 and 1440 minutes")
  2839. state.dw_led_idle_timeout_enabled = enabled
  2840. state.dw_led_idle_timeout_minutes = minutes
  2841. # Reset activity time when settings change
  2842. import time
  2843. state.dw_led_last_activity_time = time.time()
  2844. state.save()
  2845. logger.info(f"DW LED idle timeout configured: enabled={enabled}, minutes={minutes}")
  2846. return {
  2847. "success": True,
  2848. "enabled": enabled,
  2849. "minutes": minutes
  2850. }
  2851. @app.get("/api/dw_leds/idle_timeout")
  2852. async def dw_leds_get_idle_timeout():
  2853. """Get LED idle timeout settings"""
  2854. import time
  2855. # Calculate remaining time if timeout is active
  2856. remaining_minutes = None
  2857. if state.dw_led_idle_timeout_enabled and state.dw_led_last_activity_time:
  2858. elapsed_seconds = time.time() - state.dw_led_last_activity_time
  2859. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  2860. remaining_seconds = max(0, timeout_seconds - elapsed_seconds)
  2861. remaining_minutes = round(remaining_seconds / 60, 1)
  2862. return {
  2863. "enabled": state.dw_led_idle_timeout_enabled,
  2864. "minutes": state.dw_led_idle_timeout_minutes,
  2865. "remaining_minutes": remaining_minutes
  2866. }
  2867. # ── Screen (LCD backlight) control endpoints ──────────────────────
  2868. @app.get("/api/screen/status")
  2869. async def screen_status():
  2870. """Get screen controller status."""
  2871. if not state.screen_controller:
  2872. return {"available": False, "message": "Screen controller not initialized"}
  2873. return state.screen_controller.get_status()
  2874. @app.post("/api/screen/power")
  2875. async def screen_power(request: dict):
  2876. """Turn screen on/off. Body: {"on": true/false}"""
  2877. if not state.screen_controller or not state.screen_controller.available:
  2878. raise HTTPException(status_code=400, detail="Screen control not available")
  2879. on = request.get("on", True)
  2880. result = state.screen_controller.set_power(on)
  2881. if not result.get("success"):
  2882. raise HTTPException(status_code=500, detail=result.get("message", "Unknown error"))
  2883. # Publish updated state to MQTT
  2884. if state.mqtt_handler and state.mqtt_handler.is_enabled:
  2885. state.mqtt_handler._publish_screen_state()
  2886. return result
  2887. @app.post("/api/screen/brightness")
  2888. async def screen_brightness(request: dict):
  2889. """Set screen brightness. Body: {"value": 0-max_brightness}"""
  2890. if not state.screen_controller or not state.screen_controller.available:
  2891. raise HTTPException(status_code=400, detail="Screen control not available")
  2892. value = request.get("value", 128)
  2893. result = state.screen_controller.set_brightness(value)
  2894. if not result.get("success"):
  2895. raise HTTPException(status_code=500, detail=result.get("message", "Unknown error"))
  2896. # Publish updated state to MQTT
  2897. if state.mqtt_handler and state.mqtt_handler.is_enabled:
  2898. state.mqtt_handler._publish_screen_state()
  2899. return result
  2900. @app.get("/table_control")
  2901. async def table_control_page(request: Request):
  2902. return get_redirect_response(request)
  2903. @app.get("/cache-progress")
  2904. async def get_cache_progress_endpoint():
  2905. """Get the current cache generation progress."""
  2906. from modules.core.cache_manager import get_cache_progress
  2907. return get_cache_progress()
  2908. @app.post("/rebuild_cache")
  2909. async def rebuild_cache_endpoint():
  2910. """Trigger a rebuild of the pattern cache."""
  2911. try:
  2912. from modules.core.cache_manager import rebuild_cache
  2913. await rebuild_cache()
  2914. return {"success": True, "message": "Cache rebuild completed successfully"}
  2915. except Exception as e:
  2916. logger.error(f"Failed to rebuild cache: {str(e)}")
  2917. raise HTTPException(status_code=500, detail=str(e))
  2918. def signal_handler(signum, frame):
  2919. """Handle shutdown signals gracefully."""
  2920. logger.info("Received shutdown signal, cleaning up...")
  2921. try:
  2922. # Turn off all LEDs on shutdown
  2923. if state.led_controller:
  2924. state.led_controller.set_power(0)
  2925. state.save()
  2926. logger.info("Cleanup completed")
  2927. except Exception as e:
  2928. logger.error(f"Error during cleanup: {str(e)}")
  2929. finally:
  2930. logger.info("Exiting application...")
  2931. # Use os._exit after cleanup is complete to avoid async stack tracebacks
  2932. # This is safe because we've already: shut down process pool, stopped motion controller, saved state
  2933. os._exit(0)
  2934. @app.get("/api/version")
  2935. async def get_version_info(force_refresh: bool = False):
  2936. """Get current and latest version information
  2937. Args:
  2938. force_refresh: If true, bypass cache and fetch fresh data from GitHub
  2939. """
  2940. try:
  2941. version_info = await version_manager.get_version_info(force_refresh=force_refresh)
  2942. return JSONResponse(content=version_info)
  2943. except Exception as e:
  2944. logger.error(f"Error getting version info: {e}")
  2945. return JSONResponse(
  2946. content={
  2947. "current": await version_manager.get_current_version(),
  2948. "latest": await version_manager.get_current_version(),
  2949. "update_available": False,
  2950. "error": "Unable to check for updates"
  2951. },
  2952. status_code=200
  2953. )
  2954. @app.post("/api/update")
  2955. async def trigger_update():
  2956. """Trigger software update by running `dw update` as a detached process.
  2957. The `dw` CLI handles pulling code and restarting the service.
  2958. We fire-and-forget so the response returns immediately before the
  2959. service goes down for restart.
  2960. """
  2961. try:
  2962. logger.info("Update triggered via API")
  2963. dw_path = '/usr/local/bin/dw'
  2964. log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'update.log')
  2965. logger.info(f"Running: {dw_path} update (log: {log_file})")
  2966. with open(log_file, 'w') as f:
  2967. subprocess.Popen(
  2968. [dw_path, 'update'],
  2969. stdout=f,
  2970. stderr=subprocess.STDOUT,
  2971. start_new_session=True,
  2972. cwd=os.path.dirname(os.path.abspath(__file__))
  2973. )
  2974. return JSONResponse(content={
  2975. "success": True,
  2976. "message": "Update started"
  2977. })
  2978. except Exception as e:
  2979. logger.error(f"Error triggering update: {e}")
  2980. return JSONResponse(
  2981. content={"success": False, "message": f"Failed to trigger update: {str(e)}"},
  2982. status_code=500
  2983. )
  2984. @app.post("/api/system/shutdown")
  2985. async def shutdown_system():
  2986. """Shutdown the system"""
  2987. try:
  2988. logger.warning("Shutdown initiated via API")
  2989. # Schedule shutdown command after a short delay to allow response to be sent
  2990. def delayed_shutdown():
  2991. time.sleep(2) # Give time for response to be sent
  2992. try:
  2993. subprocess.run(["/usr/bin/sudo", "/usr/bin/systemctl", "poweroff"], check=True)
  2994. logger.info("System shutdown command executed successfully")
  2995. except FileNotFoundError:
  2996. logger.error("sudo or systemctl command not found - ensure systemd is available")
  2997. except Exception as e:
  2998. logger.error(f"Error executing host shutdown command: {e}")
  2999. import threading
  3000. shutdown_thread = threading.Thread(target=delayed_shutdown)
  3001. shutdown_thread.start()
  3002. return {"success": True, "message": "System shutdown initiated"}
  3003. except Exception as e:
  3004. logger.error(f"Error initiating shutdown: {e}")
  3005. return JSONResponse(
  3006. content={"success": False, "message": str(e)},
  3007. status_code=500
  3008. )
  3009. @app.post("/api/system/restart")
  3010. async def restart_system():
  3011. """Restart the Dune Weaver service via systemctl."""
  3012. try:
  3013. logger.warning("Restart initiated via API")
  3014. # Schedule restart command after a short delay to allow response to be sent
  3015. def delayed_restart():
  3016. time.sleep(2) # Give time for response to be sent
  3017. try:
  3018. subprocess.run(["/usr/bin/sudo", "/usr/bin/systemctl", "restart", "dune-weaver"], check=True)
  3019. logger.info("Service restart command executed successfully")
  3020. except FileNotFoundError:
  3021. logger.error("sudo or systemctl command not found - ensure systemd is available")
  3022. except Exception as e:
  3023. logger.error(f"Error executing service restart: {e}")
  3024. import threading
  3025. restart_thread = threading.Thread(target=delayed_restart)
  3026. restart_thread.start()
  3027. return {"success": True, "message": "System restart initiated"}
  3028. except Exception as e:
  3029. logger.error(f"Error initiating restart: {e}")
  3030. return JSONResponse(
  3031. content={"success": False, "message": str(e)},
  3032. status_code=500
  3033. )
  3034. ###############################################################################
  3035. # FluidNC Config Endpoints
  3036. ###############################################################################
  3037. def entrypoint():
  3038. import uvicorn
  3039. logger.info("Starting FastAPI server on port 8080...")
  3040. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  3041. if __name__ == "__main__":
  3042. entrypoint()