main.py 156 KB

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