main.py 162 KB

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