main.py 152 KB

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