main.py 115 KB

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