1
0

main.py 163 KB

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