1
0

main.py 178 KB

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