main.py 160 KB

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