main.py 119 KB

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