main.py 179 KB

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