main.py 174 KB

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