main.py 176 KB

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