main.py 153 KB

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