main.py 166 KB

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