main.py 133 KB

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