main.py 163 KB

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