main.py 176 KB

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