main.py 176 KB

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