main.py 159 KB

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