1
0

main.py 98 KB

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