main.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  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. import math
  25. from modules.core.cache_manager import generate_all_image_previews, get_cache_path, generate_image_preview, get_pattern_metadata
  26. from modules.core.version_manager import version_manager
  27. import json
  28. import base64
  29. import time
  30. import argparse
  31. from concurrent.futures import ProcessPoolExecutor
  32. import multiprocessing
  33. import subprocess
  34. import platform
  35. # Get log level from environment variable, default to INFO
  36. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  37. log_level = getattr(logging, log_level_str, logging.INFO)
  38. # Create a process pool for CPU-intensive tasks
  39. # Limit to reasonable number of workers for embedded systems
  40. cpu_count = multiprocessing.cpu_count()
  41. # Maximum 3 workers (leaving 1 for motion), minimum 1
  42. process_pool_size = min(3, max(1, cpu_count - 1))
  43. process_pool = None # Will be initialized in lifespan
  44. logging.basicConfig(
  45. level=log_level,
  46. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  47. handlers=[
  48. logging.StreamHandler(),
  49. ]
  50. )
  51. logger = logging.getLogger(__name__)
  52. def normalize_file_path(file_path: str) -> str:
  53. """Normalize file path separators for consistent cross-platform handling."""
  54. if not file_path:
  55. return ''
  56. # First normalize path separators
  57. normalized = file_path.replace('\\', '/')
  58. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  59. if normalized.startswith('./patterns/'):
  60. normalized = normalized[11:]
  61. elif normalized.startswith('patterns/'):
  62. normalized = normalized[9:]
  63. return normalized
  64. @asynccontextmanager
  65. async def lifespan(app: FastAPI):
  66. # Startup
  67. logger.info("Starting Dune Weaver application...")
  68. # Register signal handlers
  69. signal.signal(signal.SIGINT, signal_handler)
  70. signal.signal(signal.SIGTERM, signal_handler)
  71. # Initialize process pool for CPU-intensive tasks
  72. global process_pool
  73. process_pool = ProcessPoolExecutor(max_workers=process_pool_size)
  74. logger.info(f"Initialized process pool with {process_pool_size} workers (detected {cpu_count} cores total)")
  75. try:
  76. connection_manager.connect_device()
  77. except Exception as e:
  78. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  79. # Initialize LED controller based on saved configuration
  80. try:
  81. # Auto-detect provider for backward compatibility with existing installations
  82. if not state.led_provider or state.led_provider == "none":
  83. if state.wled_ip:
  84. state.led_provider = "wled"
  85. logger.info("Auto-detected WLED provider from existing configuration")
  86. elif state.hyperion_ip:
  87. state.led_provider = "hyperion"
  88. logger.info("Auto-detected Hyperion provider from existing configuration")
  89. # Initialize the appropriate controller
  90. if state.led_provider == "wled" and state.wled_ip:
  91. state.led_controller = LEDInterface("wled", state.wled_ip)
  92. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  93. elif state.led_provider == "hyperion" and state.hyperion_ip:
  94. state.led_controller = LEDInterface("hyperion", state.hyperion_ip, state.hyperion_port)
  95. logger.info(f"LED controller initialized: Hyperion at {state.hyperion_ip}:{state.hyperion_port}")
  96. else:
  97. state.led_controller = None
  98. logger.info("LED controller not configured")
  99. # Save if provider was auto-detected
  100. if state.led_provider and (state.wled_ip or state.hyperion_ip):
  101. state.save()
  102. except Exception as e:
  103. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  104. state.led_controller = None
  105. # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
  106. if state.auto_play_enabled and state.auto_play_playlist:
  107. logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
  108. try:
  109. # Check if we have a valid connection before starting playlist
  110. if state.conn and hasattr(state.conn, 'is_connected') and state.conn.is_connected():
  111. 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}")
  112. asyncio.create_task(playlist_manager.run_playlist(
  113. state.auto_play_playlist,
  114. pause_time=state.auto_play_pause_time,
  115. clear_pattern=state.auto_play_clear_pattern,
  116. run_mode=state.auto_play_run_mode,
  117. shuffle=state.auto_play_shuffle
  118. ))
  119. else:
  120. logger.warning("No hardware connection available, skipping auto_play mode auto-play")
  121. except Exception as e:
  122. logger.error(f"Failed to auto-play auto_play playlist: {str(e)}")
  123. try:
  124. mqtt_handler = mqtt.init_mqtt()
  125. except Exception as e:
  126. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  127. # Schedule cache generation check for later (non-blocking startup)
  128. async def delayed_cache_check():
  129. """Check and generate cache in background."""
  130. try:
  131. logger.info("Starting cache check...")
  132. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  133. if await is_cache_generation_needed_async():
  134. logger.info("Cache generation needed, starting background task...")
  135. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  136. else:
  137. logger.info("Cache is up to date, skipping generation")
  138. except Exception as e:
  139. logger.warning(f"Failed during cache generation: {str(e)}")
  140. # Start cache check in background immediately
  141. asyncio.create_task(delayed_cache_check())
  142. yield # This separates startup from shutdown code
  143. # Shutdown
  144. logger.info("Shutting down Dune Weaver application...")
  145. # Shutdown process pool
  146. if process_pool:
  147. process_pool.shutdown(wait=True)
  148. logger.info("Process pool shutdown complete")
  149. app = FastAPI(lifespan=lifespan)
  150. templates = Jinja2Templates(directory="templates")
  151. app.mount("/static", StaticFiles(directory="static"), name="static")
  152. # Pydantic models for request/response validation
  153. class ConnectRequest(BaseModel):
  154. port: Optional[str] = None
  155. class auto_playModeRequest(BaseModel):
  156. enabled: bool
  157. playlist: Optional[str] = None
  158. run_mode: Optional[str] = "loop"
  159. pause_time: Optional[float] = 5.0
  160. clear_pattern: Optional[str] = "adaptive"
  161. shuffle: Optional[bool] = False
  162. class TimeSlot(BaseModel):
  163. start_time: str # HH:MM format
  164. end_time: str # HH:MM format
  165. days: str # "daily", "weekdays", "weekends", or "custom"
  166. custom_days: Optional[List[str]] = [] # ["monday", "tuesday", etc.]
  167. class ScheduledPauseRequest(BaseModel):
  168. enabled: bool
  169. control_wled: Optional[bool] = False
  170. time_slots: List[TimeSlot] = []
  171. class CoordinateRequest(BaseModel):
  172. theta: float
  173. rho: float
  174. class PlaylistRequest(BaseModel):
  175. playlist_name: str
  176. files: List[str] = []
  177. pause_time: float = 0
  178. clear_pattern: Optional[str] = None
  179. run_mode: str = "single"
  180. shuffle: bool = False
  181. class PlaylistRunRequest(BaseModel):
  182. playlist_name: str
  183. pause_time: Optional[float] = 0
  184. clear_pattern: Optional[str] = None
  185. run_mode: Optional[str] = "single"
  186. shuffle: Optional[bool] = False
  187. start_time: Optional[str] = None
  188. end_time: Optional[str] = None
  189. class SpeedRequest(BaseModel):
  190. speed: float
  191. class WLEDRequest(BaseModel):
  192. wled_ip: Optional[str] = None
  193. class LEDConfigRequest(BaseModel):
  194. provider: str # "wled", "hyperion", or "none"
  195. ip_address: Optional[str] = None
  196. port: Optional[int] = None
  197. class DeletePlaylistRequest(BaseModel):
  198. playlist_name: str
  199. class ThetaRhoRequest(BaseModel):
  200. file_name: str
  201. pre_execution: Optional[str] = "none"
  202. class GetCoordinatesRequest(BaseModel):
  203. file_name: str
  204. # Store active WebSocket connections
  205. active_status_connections = set()
  206. active_cache_progress_connections = set()
  207. @app.websocket("/ws/status")
  208. async def websocket_status_endpoint(websocket: WebSocket):
  209. await websocket.accept()
  210. active_status_connections.add(websocket)
  211. try:
  212. while True:
  213. status = pattern_manager.get_status()
  214. try:
  215. await websocket.send_json({
  216. "type": "status_update",
  217. "data": status
  218. })
  219. except RuntimeError as e:
  220. if "close message has been sent" in str(e):
  221. break
  222. raise
  223. await asyncio.sleep(1)
  224. except WebSocketDisconnect:
  225. pass
  226. finally:
  227. active_status_connections.discard(websocket)
  228. try:
  229. await websocket.close()
  230. except RuntimeError:
  231. pass
  232. async def broadcast_status_update(status: dict):
  233. """Broadcast status update to all connected clients."""
  234. disconnected = set()
  235. for websocket in active_status_connections:
  236. try:
  237. await websocket.send_json({
  238. "type": "status_update",
  239. "data": status
  240. })
  241. except WebSocketDisconnect:
  242. disconnected.add(websocket)
  243. except RuntimeError:
  244. disconnected.add(websocket)
  245. active_status_connections.difference_update(disconnected)
  246. @app.websocket("/ws/cache-progress")
  247. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  248. from modules.core.cache_manager import get_cache_progress
  249. await websocket.accept()
  250. active_cache_progress_connections.add(websocket)
  251. try:
  252. while True:
  253. progress = get_cache_progress()
  254. try:
  255. await websocket.send_json({
  256. "type": "cache_progress",
  257. "data": progress
  258. })
  259. except RuntimeError as e:
  260. if "close message has been sent" in str(e):
  261. break
  262. raise
  263. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  264. except WebSocketDisconnect:
  265. pass
  266. finally:
  267. active_cache_progress_connections.discard(websocket)
  268. try:
  269. await websocket.close()
  270. except RuntimeError:
  271. pass
  272. # FastAPI routes
  273. @app.get("/")
  274. async def index(request: Request):
  275. return templates.TemplateResponse("index.html", {"request": request, "app_name": state.app_name})
  276. @app.get("/settings")
  277. async def settings(request: Request):
  278. return templates.TemplateResponse("settings.html", {"request": request, "app_name": state.app_name})
  279. @app.get("/api/auto_play-mode")
  280. async def get_auto_play_mode():
  281. """Get current auto_play mode settings."""
  282. return {
  283. "enabled": state.auto_play_enabled,
  284. "playlist": state.auto_play_playlist,
  285. "run_mode": state.auto_play_run_mode,
  286. "pause_time": state.auto_play_pause_time,
  287. "clear_pattern": state.auto_play_clear_pattern,
  288. "shuffle": state.auto_play_shuffle
  289. }
  290. @app.post("/api/auto_play-mode")
  291. async def set_auto_play_mode(request: auto_playModeRequest):
  292. """Update auto_play mode settings."""
  293. state.auto_play_enabled = request.enabled
  294. if request.playlist is not None:
  295. state.auto_play_playlist = request.playlist
  296. if request.run_mode is not None:
  297. state.auto_play_run_mode = request.run_mode
  298. if request.pause_time is not None:
  299. state.auto_play_pause_time = request.pause_time
  300. if request.clear_pattern is not None:
  301. state.auto_play_clear_pattern = request.clear_pattern
  302. if request.shuffle is not None:
  303. state.auto_play_shuffle = request.shuffle
  304. state.save()
  305. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  306. return {"success": True, "message": "auto_play mode settings updated"}
  307. @app.get("/api/scheduled-pause")
  308. async def get_scheduled_pause():
  309. """Get current Still Sands settings."""
  310. return {
  311. "enabled": state.scheduled_pause_enabled,
  312. "control_wled": state.scheduled_pause_control_wled,
  313. "time_slots": state.scheduled_pause_time_slots
  314. }
  315. @app.post("/api/scheduled-pause")
  316. async def set_scheduled_pause(request: ScheduledPauseRequest):
  317. """Update Still Sands settings."""
  318. try:
  319. # Validate time slots
  320. for i, slot in enumerate(request.time_slots):
  321. # Validate time format (HH:MM)
  322. try:
  323. start_time = datetime.strptime(slot.start_time, "%H:%M").time()
  324. end_time = datetime.strptime(slot.end_time, "%H:%M").time()
  325. except ValueError:
  326. raise HTTPException(
  327. status_code=400,
  328. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  329. )
  330. # Validate days setting
  331. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  332. raise HTTPException(
  333. status_code=400,
  334. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  335. )
  336. # Validate custom days if applicable
  337. if slot.days == "custom":
  338. if not slot.custom_days or len(slot.custom_days) == 0:
  339. raise HTTPException(
  340. status_code=400,
  341. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  342. )
  343. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  344. for day in slot.custom_days:
  345. if day not in valid_days:
  346. raise HTTPException(
  347. status_code=400,
  348. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  349. )
  350. # Update state
  351. state.scheduled_pause_enabled = request.enabled
  352. state.scheduled_pause_control_wled = request.control_wled
  353. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  354. state.save()
  355. wled_msg = " (with WLED control)" if request.control_wled else ""
  356. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}")
  357. return {"success": True, "message": "Still Sands settings updated"}
  358. except HTTPException:
  359. raise
  360. except Exception as e:
  361. logger.error(f"Error updating Still Sands settings: {str(e)}")
  362. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  363. @app.get("/list_serial_ports")
  364. async def list_ports():
  365. logger.debug("Listing available serial ports")
  366. return await asyncio.to_thread(connection_manager.list_serial_ports)
  367. @app.post("/connect")
  368. async def connect(request: ConnectRequest):
  369. if not request.port:
  370. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  371. connection_manager.device_init()
  372. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  373. return {"success": True}
  374. try:
  375. state.conn = connection_manager.SerialConnection(request.port)
  376. connection_manager.device_init()
  377. logger.info(f'Successfully connected to serial port {request.port}')
  378. return {"success": True}
  379. except Exception as e:
  380. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  381. raise HTTPException(status_code=500, detail=str(e))
  382. @app.post("/disconnect")
  383. async def disconnect():
  384. try:
  385. state.conn.close()
  386. logger.info('Successfully disconnected from serial port')
  387. return {"success": True}
  388. except Exception as e:
  389. logger.error(f'Failed to disconnect serial: {str(e)}')
  390. raise HTTPException(status_code=500, detail=str(e))
  391. @app.post("/restart_connection")
  392. async def restart(request: ConnectRequest):
  393. if not request.port:
  394. logger.warning("Restart serial request received without port")
  395. raise HTTPException(status_code=400, detail="No port provided")
  396. try:
  397. logger.info(f"Restarting connection on port {request.port}")
  398. connection_manager.restart_connection()
  399. return {"success": True}
  400. except Exception as e:
  401. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  402. raise HTTPException(status_code=500, detail=str(e))
  403. @app.get("/list_theta_rho_files")
  404. async def list_theta_rho_files():
  405. logger.debug("Listing theta-rho files")
  406. # Run the blocking file system operation in a thread pool
  407. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  408. return sorted(files)
  409. @app.get("/list_theta_rho_files_with_metadata")
  410. async def list_theta_rho_files_with_metadata():
  411. """Get list of theta-rho files with metadata for sorting and filtering.
  412. Optimized to process files asynchronously and support request cancellation.
  413. """
  414. from modules.core.cache_manager import get_pattern_metadata
  415. import asyncio
  416. from concurrent.futures import ThreadPoolExecutor
  417. # Run the blocking file listing in a thread
  418. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  419. files_with_metadata = []
  420. # Use ThreadPoolExecutor for I/O-bound operations
  421. executor = ThreadPoolExecutor(max_workers=4)
  422. def process_file(file_path):
  423. """Process a single file and return its metadata."""
  424. try:
  425. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  426. # Get file stats
  427. file_stat = os.stat(full_path)
  428. # Get cached metadata (this should be fast if cached)
  429. metadata = get_pattern_metadata(file_path)
  430. # Extract full folder path from file path
  431. path_parts = file_path.split('/')
  432. if len(path_parts) > 1:
  433. # Get everything except the filename (join all folder parts)
  434. category = '/'.join(path_parts[:-1])
  435. else:
  436. category = 'root'
  437. # Get file name without extension
  438. file_name = os.path.splitext(os.path.basename(file_path))[0]
  439. # Use modification time (mtime) for "date modified"
  440. date_modified = file_stat.st_mtime
  441. return {
  442. 'path': file_path,
  443. 'name': file_name,
  444. 'category': category,
  445. 'date_modified': date_modified,
  446. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  447. }
  448. except Exception as e:
  449. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  450. # Include file with minimal info if metadata fails
  451. path_parts = file_path.split('/')
  452. if len(path_parts) > 1:
  453. category = '/'.join(path_parts[:-1])
  454. else:
  455. category = 'root'
  456. return {
  457. 'path': file_path,
  458. 'name': os.path.splitext(os.path.basename(file_path))[0],
  459. 'category': category,
  460. 'date_modified': 0,
  461. 'coordinates_count': 0
  462. }
  463. # Load the entire metadata cache at once (async)
  464. # This is much faster than 1000+ individual metadata lookups
  465. try:
  466. import json
  467. metadata_cache_path = "metadata_cache.json"
  468. # Use async file reading to avoid blocking the event loop
  469. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  470. cache_dict = cache_data.get('data', {})
  471. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  472. # Process all files using cached data only
  473. for file_path in files:
  474. try:
  475. # Extract category from path
  476. path_parts = file_path.split('/')
  477. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  478. # Get file name without extension
  479. file_name = os.path.splitext(os.path.basename(file_path))[0]
  480. # Get metadata from cache
  481. cached_entry = cache_dict.get(file_path, {})
  482. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  483. metadata = cached_entry['metadata']
  484. coords_count = metadata.get('total_coordinates', 0)
  485. date_modified = cached_entry.get('mtime', 0)
  486. else:
  487. coords_count = 0
  488. date_modified = 0
  489. files_with_metadata.append({
  490. 'path': file_path,
  491. 'name': file_name,
  492. 'category': category,
  493. 'date_modified': date_modified,
  494. 'coordinates_count': coords_count
  495. })
  496. except Exception as e:
  497. logger.warning(f"Error processing {file_path}: {e}")
  498. # Include file with minimal info if processing fails
  499. path_parts = file_path.split('/')
  500. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  501. files_with_metadata.append({
  502. 'path': file_path,
  503. 'name': os.path.splitext(os.path.basename(file_path))[0],
  504. 'category': category,
  505. 'date_modified': 0,
  506. 'coordinates_count': 0
  507. })
  508. except Exception as e:
  509. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  510. # Fallback to original method if cache loading fails
  511. # Create tasks only when needed
  512. loop = asyncio.get_event_loop()
  513. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  514. for task in asyncio.as_completed(tasks):
  515. try:
  516. result = await task
  517. files_with_metadata.append(result)
  518. except Exception as task_error:
  519. logger.error(f"Error processing file: {str(task_error)}")
  520. # Clean up executor
  521. executor.shutdown(wait=False)
  522. return files_with_metadata
  523. @app.post("/upload_theta_rho")
  524. async def upload_theta_rho(file: UploadFile = File(...)):
  525. """Upload a theta-rho file."""
  526. try:
  527. # Save the file
  528. # Ensure custom_patterns directory exists
  529. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  530. os.makedirs(custom_patterns_dir, exist_ok=True)
  531. # Use forward slashes for internal path representation to maintain consistency
  532. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  533. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  534. # Save the uploaded file with proper encoding for Windows compatibility
  535. file_content = await file.read()
  536. try:
  537. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  538. text_content = file_content.decode('utf-8')
  539. with open(full_file_path, "w", encoding='utf-8') as f:
  540. f.write(text_content)
  541. except UnicodeDecodeError:
  542. # If UTF-8 decoding fails, save as binary (fallback)
  543. with open(full_file_path, "wb") as f:
  544. f.write(file_content)
  545. logger.info(f"File {file.filename} saved successfully")
  546. # Generate image preview for the new file with retry logic
  547. max_retries = 3
  548. for attempt in range(max_retries):
  549. try:
  550. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  551. success = await generate_image_preview(file_path_in_patterns_dir)
  552. if success:
  553. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  554. break
  555. else:
  556. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  557. if attempt < max_retries - 1:
  558. await asyncio.sleep(0.5) # Small delay before retry
  559. except Exception as e:
  560. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  561. if attempt < max_retries - 1:
  562. await asyncio.sleep(0.5) # Small delay before retry
  563. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  564. except Exception as e:
  565. logger.error(f"Error uploading file: {str(e)}")
  566. raise HTTPException(status_code=500, detail=str(e))
  567. @app.post("/get_theta_rho_coordinates")
  568. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  569. """Get theta-rho coordinates for animated preview."""
  570. try:
  571. # Normalize file path for cross-platform compatibility and remove prefixes
  572. file_name = normalize_file_path(request.file_name)
  573. file_path = os.path.join(THETA_RHO_DIR, file_name)
  574. # Check file existence asynchronously
  575. exists = await asyncio.to_thread(os.path.exists, file_path)
  576. if not exists:
  577. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  578. # Parse the theta-rho file in a separate process for CPU-intensive work
  579. # This prevents blocking the motion control thread
  580. loop = asyncio.get_event_loop()
  581. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, file_path)
  582. if not coordinates:
  583. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  584. return {
  585. "success": True,
  586. "coordinates": coordinates,
  587. "total_points": len(coordinates)
  588. }
  589. except Exception as e:
  590. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  591. raise HTTPException(status_code=500, detail=str(e))
  592. @app.post("/run_theta_rho")
  593. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  594. if not request.file_name:
  595. logger.warning('Run theta-rho request received without file name')
  596. raise HTTPException(status_code=400, detail="No file name provided")
  597. file_path = None
  598. if 'clear' in request.file_name:
  599. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  600. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  601. logger.info(f'Clear pattern file: {file_path}')
  602. if not file_path:
  603. # Normalize file path for cross-platform compatibility
  604. normalized_file_name = normalize_file_path(request.file_name)
  605. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  606. if not os.path.exists(file_path):
  607. logger.error(f'Theta-rho file not found: {file_path}')
  608. raise HTTPException(status_code=404, detail="File not found")
  609. try:
  610. if not (state.conn.is_connected() if state.conn else False):
  611. logger.warning("Attempted to run a pattern without a connection")
  612. raise HTTPException(status_code=400, detail="Connection not established")
  613. if pattern_manager.pattern_lock.locked():
  614. logger.warning("Attempted to run a pattern while another is already running")
  615. raise HTTPException(status_code=409, detail="Another pattern is already running")
  616. files_to_run = [file_path]
  617. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  618. # Only include clear_pattern if it's not "none"
  619. kwargs = {}
  620. if request.pre_execution != "none":
  621. kwargs['clear_pattern'] = request.pre_execution
  622. # Pass arguments properly
  623. background_tasks.add_task(
  624. pattern_manager.run_theta_rho_files,
  625. files_to_run, # First positional argument
  626. **kwargs # Spread keyword arguments
  627. )
  628. return {"success": True}
  629. except HTTPException as http_exc:
  630. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  631. raise http_exc
  632. except Exception as e:
  633. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  634. raise HTTPException(status_code=500, detail=str(e))
  635. @app.post("/stop_execution")
  636. async def stop_execution():
  637. if not (state.conn.is_connected() if state.conn else False):
  638. logger.warning("Attempted to stop without a connection")
  639. raise HTTPException(status_code=400, detail="Connection not established")
  640. await pattern_manager.stop_actions()
  641. return {"success": True}
  642. @app.post("/send_home")
  643. async def send_home():
  644. try:
  645. if not (state.conn.is_connected() if state.conn else False):
  646. logger.warning("Attempted to move to home without a connection")
  647. raise HTTPException(status_code=400, detail="Connection not established")
  648. # Run homing with 15 second timeout
  649. success = await asyncio.to_thread(connection_manager.home)
  650. if not success:
  651. logger.error("Homing failed or timed out")
  652. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  653. return {"success": True}
  654. except HTTPException:
  655. raise
  656. except Exception as e:
  657. logger.error(f"Failed to send home command: {str(e)}")
  658. raise HTTPException(status_code=500, detail=str(e))
  659. @app.post("/run_theta_rho_file/{file_name}")
  660. async def run_specific_theta_rho_file(file_name: str):
  661. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  662. if not os.path.exists(file_path):
  663. raise HTTPException(status_code=404, detail="File not found")
  664. if not (state.conn.is_connected() if state.conn else False):
  665. logger.warning("Attempted to run a pattern without a connection")
  666. raise HTTPException(status_code=400, detail="Connection not established")
  667. pattern_manager.run_theta_rho_file(file_path)
  668. return {"success": True}
  669. class DeleteFileRequest(BaseModel):
  670. file_name: str
  671. @app.post("/delete_theta_rho_file")
  672. async def delete_theta_rho_file(request: DeleteFileRequest):
  673. if not request.file_name:
  674. logger.warning("Delete theta-rho file request received without filename")
  675. raise HTTPException(status_code=400, detail="No file name provided")
  676. # Normalize file path for cross-platform compatibility
  677. normalized_file_name = normalize_file_path(request.file_name)
  678. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  679. # Check file existence asynchronously
  680. exists = await asyncio.to_thread(os.path.exists, file_path)
  681. if not exists:
  682. logger.error(f"Attempted to delete non-existent file: {file_path}")
  683. raise HTTPException(status_code=404, detail="File not found")
  684. try:
  685. # Delete the pattern file asynchronously
  686. await asyncio.to_thread(os.remove, file_path)
  687. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  688. # Clean up cached preview image and metadata asynchronously
  689. from modules.core.cache_manager import delete_pattern_cache
  690. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  691. if cache_cleanup_success:
  692. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  693. else:
  694. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  695. return {"success": True, "cache_cleanup": cache_cleanup_success}
  696. except Exception as e:
  697. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  698. raise HTTPException(status_code=500, detail=str(e))
  699. @app.post("/move_to_center")
  700. async def move_to_center():
  701. try:
  702. if not (state.conn.is_connected() if state.conn else False):
  703. logger.warning("Attempted to move to center without a connection")
  704. raise HTTPException(status_code=400, detail="Connection not established")
  705. logger.info("Moving device to center position")
  706. await pattern_manager.reset_theta()
  707. await pattern_manager.move_polar(0, 0)
  708. return {"success": True}
  709. except Exception as e:
  710. logger.error(f"Failed to move to center: {str(e)}")
  711. raise HTTPException(status_code=500, detail=str(e))
  712. @app.post("/move_to_perimeter")
  713. async def move_to_perimeter():
  714. try:
  715. if not (state.conn.is_connected() if state.conn else False):
  716. logger.warning("Attempted to move to perimeter without a connection")
  717. raise HTTPException(status_code=400, detail="Connection not established")
  718. await pattern_manager.reset_theta()
  719. await pattern_manager.move_polar(0, 1)
  720. return {"success": True}
  721. except Exception as e:
  722. logger.error(f"Failed to move to perimeter: {str(e)}")
  723. raise HTTPException(status_code=500, detail=str(e))
  724. @app.post("/preview_thr")
  725. async def preview_thr(request: DeleteFileRequest):
  726. if not request.file_name:
  727. logger.warning("Preview theta-rho request received without filename")
  728. raise HTTPException(status_code=400, detail="No file name provided")
  729. # Normalize file path for cross-platform compatibility
  730. normalized_file_name = normalize_file_path(request.file_name)
  731. # Construct the full path to the pattern file to check existence
  732. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  733. # Check file existence asynchronously
  734. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  735. if not exists:
  736. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  737. raise HTTPException(status_code=404, detail="Pattern file not found")
  738. try:
  739. cache_path = get_cache_path(normalized_file_name)
  740. # Check cache existence asynchronously
  741. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  742. if not cache_exists:
  743. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  744. # Attempt to generate the preview if it's missing
  745. success = await generate_image_preview(normalized_file_name)
  746. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  747. if not success or not cache_exists_after:
  748. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  749. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  750. # Try to get coordinates from metadata cache first
  751. metadata = get_pattern_metadata(normalized_file_name)
  752. if metadata:
  753. first_coord_obj = metadata.get('first_coordinate')
  754. last_coord_obj = metadata.get('last_coordinate')
  755. else:
  756. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  757. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  758. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  759. first_coord = coordinates[0] if coordinates else None
  760. last_coord = coordinates[-1] if coordinates else None
  761. # Format coordinates as objects with x and y properties
  762. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  763. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  764. # Return JSON with preview URL and coordinates
  765. # URL encode the file_name for the preview URL
  766. # Handle both forward slashes and backslashes for cross-platform compatibility
  767. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  768. return {
  769. "preview_url": f"/preview/{encoded_filename}",
  770. "first_coordinate": first_coord_obj,
  771. "last_coordinate": last_coord_obj
  772. }
  773. except HTTPException:
  774. raise
  775. except Exception as e:
  776. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  777. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  778. @app.get("/preview/{encoded_filename}")
  779. async def serve_preview(encoded_filename: str):
  780. """Serve a preview image for a pattern file."""
  781. # Decode the filename by replacing -- with the original path separators
  782. # First try forward slash (most common case), then backslash if needed
  783. file_name = encoded_filename.replace('--', '/')
  784. # Apply normalization to handle any remaining path prefixes
  785. file_name = normalize_file_path(file_name)
  786. # Check if the decoded path exists, if not try backslash decoding
  787. cache_path = get_cache_path(file_name)
  788. if not os.path.exists(cache_path):
  789. # Try with backslash for Windows paths
  790. file_name_backslash = encoded_filename.replace('--', '\\')
  791. file_name_backslash = normalize_file_path(file_name_backslash)
  792. cache_path_backslash = get_cache_path(file_name_backslash)
  793. if os.path.exists(cache_path_backslash):
  794. file_name = file_name_backslash
  795. cache_path = cache_path_backslash
  796. # cache_path is already determined above in the decoding logic
  797. if not os.path.exists(cache_path):
  798. logger.error(f"Preview image not found for {file_name}")
  799. raise HTTPException(status_code=404, detail="Preview image not found")
  800. # Add caching headers
  801. headers = {
  802. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  803. "Content-Type": "image/webp",
  804. "Accept-Ranges": "bytes"
  805. }
  806. return FileResponse(
  807. cache_path,
  808. media_type="image/webp",
  809. headers=headers
  810. )
  811. @app.post("/send_coordinate")
  812. async def send_coordinate(request: CoordinateRequest):
  813. if not (state.conn.is_connected() if state.conn else False):
  814. logger.warning("Attempted to send coordinate without a connection")
  815. raise HTTPException(status_code=400, detail="Connection not established")
  816. try:
  817. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  818. await pattern_manager.move_polar(request.theta, request.rho)
  819. return {"success": True}
  820. except Exception as e:
  821. logger.error(f"Failed to send coordinate: {str(e)}")
  822. raise HTTPException(status_code=500, detail=str(e))
  823. @app.get("/download/{filename}")
  824. async def download_file(filename: str):
  825. return FileResponse(
  826. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  827. filename=filename
  828. )
  829. @app.get("/serial_status")
  830. async def serial_status():
  831. connected = state.conn.is_connected() if state.conn else False
  832. port = state.port
  833. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  834. return {
  835. "connected": connected,
  836. "port": port
  837. }
  838. @app.post("/pause_execution")
  839. async def pause_execution():
  840. if pattern_manager.pause_execution():
  841. return {"success": True, "message": "Execution paused"}
  842. raise HTTPException(status_code=500, detail="Failed to pause execution")
  843. @app.post("/resume_execution")
  844. async def resume_execution():
  845. if pattern_manager.resume_execution():
  846. return {"success": True, "message": "Execution resumed"}
  847. raise HTTPException(status_code=500, detail="Failed to resume execution")
  848. # Playlist endpoints
  849. @app.get("/list_all_playlists")
  850. async def list_all_playlists():
  851. playlist_names = playlist_manager.list_all_playlists()
  852. return playlist_names
  853. @app.get("/get_playlist")
  854. async def get_playlist(name: str):
  855. if not name:
  856. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  857. playlist = playlist_manager.get_playlist(name)
  858. if not playlist:
  859. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  860. return playlist
  861. @app.post("/create_playlist")
  862. async def create_playlist(request: PlaylistRequest):
  863. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  864. return {
  865. "success": success,
  866. "message": f"Playlist '{request.playlist_name}' created/updated"
  867. }
  868. @app.post("/modify_playlist")
  869. async def modify_playlist(request: PlaylistRequest):
  870. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  871. return {
  872. "success": success,
  873. "message": f"Playlist '{request.playlist_name}' updated"
  874. }
  875. @app.delete("/delete_playlist")
  876. async def delete_playlist(request: DeletePlaylistRequest):
  877. success = playlist_manager.delete_playlist(request.playlist_name)
  878. if not success:
  879. raise HTTPException(
  880. status_code=404,
  881. detail=f"Playlist '{request.playlist_name}' not found"
  882. )
  883. return {
  884. "success": True,
  885. "message": f"Playlist '{request.playlist_name}' deleted"
  886. }
  887. class AddToPlaylistRequest(BaseModel):
  888. playlist_name: str
  889. pattern: str
  890. @app.post("/add_to_playlist")
  891. async def add_to_playlist(request: AddToPlaylistRequest):
  892. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  893. if not success:
  894. raise HTTPException(status_code=404, detail="Playlist not found")
  895. return {"success": True}
  896. @app.post("/run_playlist")
  897. async def run_playlist_endpoint(request: PlaylistRequest):
  898. """Run a playlist with specified parameters."""
  899. try:
  900. if not (state.conn.is_connected() if state.conn else False):
  901. logger.warning("Attempted to run a playlist without a connection")
  902. raise HTTPException(status_code=400, detail="Connection not established")
  903. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  904. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  905. # Start the playlist execution
  906. success, message = await playlist_manager.run_playlist(
  907. request.playlist_name,
  908. pause_time=request.pause_time,
  909. clear_pattern=request.clear_pattern,
  910. run_mode=request.run_mode,
  911. shuffle=request.shuffle
  912. )
  913. if not success:
  914. raise HTTPException(status_code=409, detail=message)
  915. return {"message": f"Started playlist: {request.playlist_name}"}
  916. except Exception as e:
  917. logger.error(f"Error running playlist: {e}")
  918. raise HTTPException(status_code=500, detail=str(e))
  919. @app.post("/set_speed")
  920. async def set_speed(request: SpeedRequest):
  921. try:
  922. if not (state.conn.is_connected() if state.conn else False):
  923. logger.warning("Attempted to change speed without a connection")
  924. raise HTTPException(status_code=400, detail="Connection not established")
  925. if request.speed <= 0:
  926. logger.warning(f"Invalid speed value received: {request.speed}")
  927. raise HTTPException(status_code=400, detail="Invalid speed value")
  928. state.speed = request.speed
  929. return {"success": True, "speed": request.speed}
  930. except Exception as e:
  931. logger.error(f"Failed to set speed: {str(e)}")
  932. raise HTTPException(status_code=500, detail=str(e))
  933. @app.get("/check_software_update")
  934. async def check_updates():
  935. update_info = update_manager.check_git_updates()
  936. return update_info
  937. @app.post("/update_software")
  938. async def update_software():
  939. logger.info("Starting software update process")
  940. success, error_message, error_log = update_manager.update_software()
  941. if success:
  942. logger.info("Software update completed successfully")
  943. return {"success": True}
  944. else:
  945. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  946. raise HTTPException(
  947. status_code=500,
  948. detail={
  949. "error": error_message,
  950. "details": error_log
  951. }
  952. )
  953. @app.post("/set_wled_ip")
  954. async def set_wled_ip(request: WLEDRequest):
  955. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  956. state.wled_ip = request.wled_ip
  957. state.led_provider = "wled" if request.wled_ip else "none"
  958. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  959. if state.led_controller:
  960. state.led_controller.effect_idle()
  961. state.save()
  962. logger.info(f"WLED IP updated: {request.wled_ip}")
  963. return {"success": True, "wled_ip": state.wled_ip}
  964. @app.get("/get_wled_ip")
  965. async def get_wled_ip():
  966. """Legacy endpoint for backward compatibility"""
  967. if not state.wled_ip:
  968. raise HTTPException(status_code=404, detail="No WLED IP set")
  969. return {"success": True, "wled_ip": state.wled_ip}
  970. @app.post("/set_led_config")
  971. async def set_led_config(request: LEDConfigRequest):
  972. """Configure LED provider (WLED, Hyperion, or none)"""
  973. if request.provider not in ["wled", "hyperion", "none"]:
  974. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'wled', 'hyperion', or 'none'")
  975. state.led_provider = request.provider
  976. if request.provider == "wled":
  977. if not request.ip_address:
  978. raise HTTPException(status_code=400, detail="IP address required for WLED")
  979. state.wled_ip = request.ip_address
  980. state.hyperion_ip = None # Clear other provider
  981. state.led_controller = LEDInterface("wled", request.ip_address)
  982. logger.info(f"LED provider set to WLED at {request.ip_address}")
  983. elif request.provider == "hyperion":
  984. if not request.ip_address:
  985. raise HTTPException(status_code=400, detail="IP address required for Hyperion")
  986. state.hyperion_ip = request.ip_address
  987. state.hyperion_port = request.port or 8090
  988. state.wled_ip = None # Clear other provider
  989. state.led_controller = LEDInterface("hyperion", request.ip_address, request.port or 8090)
  990. logger.info(f"LED provider set to Hyperion at {request.ip_address}:{request.port or 8090}")
  991. else: # none
  992. state.wled_ip = None
  993. state.hyperion_ip = None
  994. state.led_controller = None
  995. logger.info("LED provider disabled")
  996. # Show idle effect if controller is configured
  997. if state.led_controller:
  998. state.led_controller.effect_idle()
  999. state.save()
  1000. return {
  1001. "success": True,
  1002. "provider": state.led_provider,
  1003. "wled_ip": state.wled_ip,
  1004. "hyperion_ip": state.hyperion_ip,
  1005. "hyperion_port": state.hyperion_port
  1006. }
  1007. @app.get("/get_led_config")
  1008. async def get_led_config():
  1009. """Get current LED provider configuration"""
  1010. # Auto-detect provider for backward compatibility with existing installations
  1011. provider = state.led_provider
  1012. if not provider or provider == "none":
  1013. # If no provider set but we have IPs configured, auto-detect
  1014. if state.wled_ip:
  1015. provider = "wled"
  1016. state.led_provider = "wled"
  1017. state.save()
  1018. logger.info("Auto-detected WLED provider from existing configuration")
  1019. elif state.hyperion_ip:
  1020. provider = "hyperion"
  1021. state.led_provider = "hyperion"
  1022. state.save()
  1023. logger.info("Auto-detected Hyperion provider from existing configuration")
  1024. else:
  1025. provider = "none"
  1026. return {
  1027. "success": True,
  1028. "provider": provider,
  1029. "wled_ip": state.wled_ip,
  1030. "hyperion_ip": state.hyperion_ip,
  1031. "hyperion_port": state.hyperion_port,
  1032. "hyperion_idle_effect": state.hyperion_idle_effect,
  1033. "hyperion_playing_effect": state.hyperion_playing_effect
  1034. }
  1035. @app.post("/skip_pattern")
  1036. async def skip_pattern():
  1037. if not state.current_playlist:
  1038. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1039. state.skip_requested = True
  1040. return {"success": True}
  1041. @app.get("/api/custom_clear_patterns")
  1042. async def get_custom_clear_patterns():
  1043. """Get the currently configured custom clear patterns."""
  1044. return {
  1045. "success": True,
  1046. "custom_clear_from_in": state.custom_clear_from_in,
  1047. "custom_clear_from_out": state.custom_clear_from_out
  1048. }
  1049. @app.post("/api/custom_clear_patterns")
  1050. async def set_custom_clear_patterns(request: dict):
  1051. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1052. try:
  1053. # Validate that the patterns exist if they're provided
  1054. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1055. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1056. if not os.path.exists(pattern_path):
  1057. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1058. state.custom_clear_from_in = request["custom_clear_from_in"]
  1059. elif "custom_clear_from_in" in request:
  1060. state.custom_clear_from_in = None
  1061. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1062. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1063. if not os.path.exists(pattern_path):
  1064. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1065. state.custom_clear_from_out = request["custom_clear_from_out"]
  1066. elif "custom_clear_from_out" in request:
  1067. state.custom_clear_from_out = None
  1068. state.save()
  1069. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1070. return {
  1071. "success": True,
  1072. "custom_clear_from_in": state.custom_clear_from_in,
  1073. "custom_clear_from_out": state.custom_clear_from_out
  1074. }
  1075. except Exception as e:
  1076. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  1077. raise HTTPException(status_code=500, detail=str(e))
  1078. @app.get("/api/clear_pattern_speed")
  1079. async def get_clear_pattern_speed():
  1080. """Get the current clearing pattern speed setting."""
  1081. return {
  1082. "success": True,
  1083. "clear_pattern_speed": state.clear_pattern_speed,
  1084. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1085. }
  1086. @app.post("/api/clear_pattern_speed")
  1087. async def set_clear_pattern_speed(request: dict):
  1088. """Set the clearing pattern speed."""
  1089. try:
  1090. # If speed is None or "none", use default behavior (state.speed)
  1091. speed_value = request.get("clear_pattern_speed")
  1092. if speed_value is None or speed_value == "none" or speed_value == "":
  1093. speed = None
  1094. else:
  1095. speed = int(speed_value)
  1096. # Validate speed range (same as regular speed limits) only if speed is not None
  1097. if speed is not None and not (50 <= speed <= 2000):
  1098. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  1099. state.clear_pattern_speed = speed
  1100. state.save()
  1101. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  1102. return {
  1103. "success": True,
  1104. "clear_pattern_speed": state.clear_pattern_speed,
  1105. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1106. }
  1107. except ValueError:
  1108. raise HTTPException(status_code=400, detail="Invalid speed value")
  1109. except Exception as e:
  1110. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  1111. raise HTTPException(status_code=500, detail=str(e))
  1112. @app.get("/api/app-name")
  1113. async def get_app_name():
  1114. """Get current application name."""
  1115. return {"app_name": state.app_name}
  1116. @app.post("/api/app-name")
  1117. async def set_app_name(request: dict):
  1118. """Update application name."""
  1119. app_name = request.get("app_name", "").strip()
  1120. if not app_name:
  1121. app_name = "Dune Weaver" # Reset to default if empty
  1122. state.app_name = app_name
  1123. state.save()
  1124. logger.info(f"Application name updated to: {app_name}")
  1125. return {"success": True, "app_name": app_name}
  1126. @app.post("/preview_thr_batch")
  1127. async def preview_thr_batch(request: dict):
  1128. start = time.time()
  1129. if not request.get("file_names"):
  1130. logger.warning("Batch preview request received without filenames")
  1131. raise HTTPException(status_code=400, detail="No file names provided")
  1132. file_names = request["file_names"]
  1133. if not isinstance(file_names, list):
  1134. raise HTTPException(status_code=400, detail="file_names must be a list")
  1135. headers = {
  1136. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  1137. "Content-Type": "application/json"
  1138. }
  1139. async def process_single_file(file_name):
  1140. """Process a single file and return its preview data."""
  1141. t1 = time.time()
  1142. try:
  1143. # Normalize file path for cross-platform compatibility
  1144. normalized_file_name = normalize_file_path(file_name)
  1145. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1146. # Check file existence asynchronously
  1147. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1148. if not exists:
  1149. logger.warning(f"Pattern file not found: {pattern_file_path}")
  1150. return file_name, {"error": "Pattern file not found"}
  1151. cache_path = get_cache_path(normalized_file_name)
  1152. # Check cache existence asynchronously
  1153. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1154. if not cache_exists:
  1155. logger.info(f"Cache miss for {file_name}. Generating preview...")
  1156. success = await generate_image_preview(normalized_file_name)
  1157. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1158. if not success or not cache_exists_after:
  1159. logger.error(f"Failed to generate or find preview for {file_name}")
  1160. return file_name, {"error": "Failed to generate preview"}
  1161. metadata = get_pattern_metadata(normalized_file_name)
  1162. if metadata:
  1163. first_coord_obj = metadata.get('first_coordinate')
  1164. last_coord_obj = metadata.get('last_coordinate')
  1165. else:
  1166. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  1167. # Use process pool for CPU-intensive parsing
  1168. loop = asyncio.get_event_loop()
  1169. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, pattern_file_path)
  1170. first_coord = coordinates[0] if coordinates else None
  1171. last_coord = coordinates[-1] if coordinates else None
  1172. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1173. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1174. # Read image file asynchronously
  1175. image_data = await asyncio.to_thread(lambda: open(cache_path, 'rb').read())
  1176. image_b64 = base64.b64encode(image_data).decode('utf-8')
  1177. result = {
  1178. "image_data": f"data:image/webp;base64,{image_b64}",
  1179. "first_coordinate": first_coord_obj,
  1180. "last_coordinate": last_coord_obj
  1181. }
  1182. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  1183. return file_name, result
  1184. except Exception as e:
  1185. logger.error(f"Error processing {file_name}: {str(e)}")
  1186. return file_name, {"error": str(e)}
  1187. # Process all files concurrently
  1188. tasks = [process_single_file(file_name) for file_name in file_names]
  1189. file_results = await asyncio.gather(*tasks)
  1190. # Convert results to dictionary
  1191. results = dict(file_results)
  1192. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  1193. return JSONResponse(content=results, headers=headers)
  1194. @app.get("/playlists")
  1195. async def playlists(request: Request):
  1196. logger.debug("Rendering playlists page")
  1197. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name})
  1198. @app.get("/image2sand")
  1199. async def image2sand(request: Request):
  1200. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name})
  1201. @app.get("/wled")
  1202. async def wled(request: Request):
  1203. return templates.TemplateResponse("wled.html", {"request": request, "app_name": state.app_name})
  1204. # Hyperion control endpoints
  1205. @app.get("/api/hyperion/status")
  1206. async def hyperion_status():
  1207. """Get Hyperion connection status"""
  1208. if not state.led_controller or state.led_provider != "hyperion":
  1209. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1210. try:
  1211. status = state.led_controller.check_status()
  1212. return status
  1213. except Exception as e:
  1214. logger.error(f"Failed to check Hyperion status: {str(e)}")
  1215. return {"connected": False, "message": str(e)}
  1216. @app.post("/api/hyperion/power")
  1217. async def hyperion_power(request: dict):
  1218. """Control Hyperion power state"""
  1219. if not state.led_controller or state.led_provider != "hyperion":
  1220. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1221. state_value = request.get("state", 1)
  1222. if state_value not in [0, 1, 2]:
  1223. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  1224. try:
  1225. result = state.led_controller.set_power(state_value)
  1226. return result
  1227. except Exception as e:
  1228. logger.error(f"Failed to set Hyperion power: {str(e)}")
  1229. raise HTTPException(status_code=500, detail=str(e))
  1230. @app.post("/api/hyperion/brightness")
  1231. async def hyperion_brightness(request: dict):
  1232. """Set Hyperion brightness"""
  1233. if not state.led_controller or state.led_provider != "hyperion":
  1234. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1235. value = request.get("value", 100)
  1236. if not 0 <= value <= 100:
  1237. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  1238. try:
  1239. controller = state.led_controller.get_controller()
  1240. result = controller.set_brightness(value)
  1241. return result
  1242. except Exception as e:
  1243. logger.error(f"Failed to set Hyperion brightness: {str(e)}")
  1244. raise HTTPException(status_code=500, detail=str(e))
  1245. @app.post("/api/hyperion/color")
  1246. async def hyperion_color(request: dict):
  1247. """Set Hyperion color"""
  1248. if not state.led_controller or state.led_provider != "hyperion":
  1249. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1250. hex_color = request.get("hex")
  1251. r = request.get("r")
  1252. g = request.get("g")
  1253. b = request.get("b")
  1254. if not hex_color and (r is None or g is None or b is None):
  1255. raise HTTPException(status_code=400, detail="Either hex or RGB values required")
  1256. try:
  1257. controller = state.led_controller.get_controller()
  1258. # Convert hex to RGB if hex was provided
  1259. if hex_color:
  1260. hex_color = hex_color.lstrip('#')
  1261. if len(hex_color) != 6:
  1262. raise HTTPException(status_code=400, detail="Hex color must be 6 characters")
  1263. r = int(hex_color[0:2], 16)
  1264. g = int(hex_color[2:4], 16)
  1265. b = int(hex_color[4:6], 16)
  1266. result = controller.set_color(r=r, g=g, b=b)
  1267. return result
  1268. except ValueError as e:
  1269. logger.error(f"Failed to parse hex color: {str(e)}")
  1270. raise HTTPException(status_code=400, detail="Invalid hex color format")
  1271. except Exception as e:
  1272. logger.error(f"Failed to set Hyperion color: {str(e)}")
  1273. raise HTTPException(status_code=500, detail=str(e))
  1274. @app.post("/api/hyperion/clear")
  1275. async def hyperion_clear(request: dict):
  1276. """Clear Hyperion priority"""
  1277. if not state.led_controller or state.led_provider != "hyperion":
  1278. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1279. try:
  1280. controller = state.led_controller.get_controller()
  1281. result = controller.clear_priority()
  1282. return result
  1283. except Exception as e:
  1284. logger.error(f"Failed to clear Hyperion priority: {str(e)}")
  1285. raise HTTPException(status_code=500, detail=str(e))
  1286. @app.get("/api/hyperion/effects")
  1287. async def hyperion_effects():
  1288. """Get list of available Hyperion effects"""
  1289. if not state.led_controller or state.led_provider != "hyperion":
  1290. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1291. try:
  1292. import requests as req
  1293. response = req.post(
  1294. f"http://{state.hyperion_ip}:{state.hyperion_port}/json-rpc",
  1295. json={"command": "serverinfo"},
  1296. timeout=2
  1297. )
  1298. data = response.json()
  1299. effects = data.get('info', {}).get('effects', [])
  1300. # Return sorted list of effects
  1301. effects_list = [{"name": e.get("name"), "args": e.get("args", {})} for e in effects]
  1302. effects_list.sort(key=lambda x: x["name"])
  1303. return {"success": True, "effects": effects_list}
  1304. except Exception as e:
  1305. logger.error(f"Failed to get Hyperion effects: {str(e)}")
  1306. raise HTTPException(status_code=500, detail=str(e))
  1307. @app.post("/api/hyperion/effect")
  1308. async def hyperion_effect(request: dict):
  1309. """Set Hyperion effect"""
  1310. if not state.led_controller or state.led_provider != "hyperion":
  1311. raise HTTPException(status_code=400, detail="Hyperion not configured")
  1312. effect_name = request.get("effect_name")
  1313. effect_args = request.get("args", {})
  1314. if not effect_name:
  1315. raise HTTPException(status_code=400, detail="effect_name required")
  1316. try:
  1317. controller = state.led_controller.get_controller()
  1318. result = controller.set_effect(effect_name, effect_args)
  1319. return result
  1320. except Exception as e:
  1321. logger.error(f"Failed to set Hyperion effect: {str(e)}")
  1322. raise HTTPException(status_code=500, detail=str(e))
  1323. @app.post("/api/hyperion/set_effects")
  1324. async def hyperion_set_effects(request: dict):
  1325. """Configure idle and playing effects for Hyperion"""
  1326. idle_effect = request.get("idle_effect")
  1327. playing_effect = request.get("playing_effect")
  1328. # Save effect settings - "off"/None/empty string all mean clear priority
  1329. state.hyperion_idle_effect = idle_effect if idle_effect else "off"
  1330. state.hyperion_playing_effect = playing_effect if playing_effect else "off"
  1331. state.save()
  1332. logger.info(f"Hyperion effects configured - Idle: {state.hyperion_idle_effect}, Playing: {state.hyperion_playing_effect}")
  1333. return {
  1334. "success": True,
  1335. "idle_effect": state.hyperion_idle_effect,
  1336. "playing_effect": state.hyperion_playing_effect
  1337. }
  1338. @app.get("/table_control")
  1339. async def table_control(request: Request):
  1340. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name})
  1341. @app.get("/cache-progress")
  1342. async def get_cache_progress_endpoint():
  1343. """Get the current cache generation progress."""
  1344. from modules.core.cache_manager import get_cache_progress
  1345. return get_cache_progress()
  1346. @app.post("/rebuild_cache")
  1347. async def rebuild_cache_endpoint():
  1348. """Trigger a rebuild of the pattern cache."""
  1349. try:
  1350. from modules.core.cache_manager import rebuild_cache
  1351. await rebuild_cache()
  1352. return {"success": True, "message": "Cache rebuild completed successfully"}
  1353. except Exception as e:
  1354. logger.error(f"Failed to rebuild cache: {str(e)}")
  1355. raise HTTPException(status_code=500, detail=str(e))
  1356. def signal_handler(signum, frame):
  1357. """Handle shutdown signals gracefully but forcefully."""
  1358. logger.info("Received shutdown signal, cleaning up...")
  1359. try:
  1360. if state.led_controller:
  1361. state.led_controller.set_power(0)
  1362. # Run cleanup operations - need to handle async in sync context
  1363. try:
  1364. # Try to run in existing loop if available
  1365. import asyncio
  1366. loop = asyncio.get_running_loop()
  1367. # If we're in an event loop, schedule the coroutine
  1368. import concurrent.futures
  1369. with concurrent.futures.ThreadPoolExecutor() as executor:
  1370. future = executor.submit(asyncio.run, pattern_manager.stop_actions())
  1371. future.result(timeout=5.0) # Wait up to 5 seconds
  1372. except RuntimeError:
  1373. # No running loop, create a new one
  1374. import asyncio
  1375. asyncio.run(pattern_manager.stop_actions())
  1376. except Exception as cleanup_err:
  1377. logger.error(f"Error in async cleanup: {cleanup_err}")
  1378. state.save()
  1379. logger.info("Cleanup completed")
  1380. except Exception as e:
  1381. logger.error(f"Error during cleanup: {str(e)}")
  1382. finally:
  1383. logger.info("Exiting application...")
  1384. os._exit(0) # Force exit regardless of other threads
  1385. @app.get("/api/version")
  1386. async def get_version_info():
  1387. """Get current and latest version information"""
  1388. try:
  1389. version_info = await version_manager.get_version_info()
  1390. return JSONResponse(content=version_info)
  1391. except Exception as e:
  1392. logger.error(f"Error getting version info: {e}")
  1393. return JSONResponse(
  1394. content={
  1395. "current": version_manager.get_current_version(),
  1396. "latest": version_manager.get_current_version(),
  1397. "update_available": False,
  1398. "error": "Unable to check for updates"
  1399. },
  1400. status_code=200
  1401. )
  1402. @app.post("/api/update")
  1403. async def trigger_update():
  1404. """Trigger software update (placeholder for future implementation)"""
  1405. try:
  1406. # For now, just return the GitHub release URL
  1407. version_info = await version_manager.get_version_info()
  1408. if version_info.get("latest_release"):
  1409. return JSONResponse(content={
  1410. "success": False,
  1411. "message": "Automatic updates not implemented yet",
  1412. "manual_update_url": version_info["latest_release"].get("html_url"),
  1413. "instructions": "Please visit the GitHub release page to download and install the update manually"
  1414. })
  1415. else:
  1416. return JSONResponse(content={
  1417. "success": False,
  1418. "message": "No updates available"
  1419. })
  1420. except Exception as e:
  1421. logger.error(f"Error triggering update: {e}")
  1422. return JSONResponse(
  1423. content={"success": False, "message": "Failed to check for updates"},
  1424. status_code=500
  1425. )
  1426. @app.get("/api/system/check_pi")
  1427. async def check_pi():
  1428. """Check if the system is a Raspberry Pi"""
  1429. try:
  1430. # Check if running on ARM architecture (Raspberry Pi indicator)
  1431. is_arm = platform.machine().startswith('arm') or platform.machine().startswith('aarch')
  1432. # Additional check: look for Raspberry Pi specific files
  1433. is_pi_file = os.path.exists('/proc/device-tree/model')
  1434. if is_pi_file:
  1435. with open('/proc/device-tree/model', 'r') as f:
  1436. model = f.read()
  1437. is_raspberry_pi = 'Raspberry Pi' in model
  1438. else:
  1439. is_raspberry_pi = False
  1440. # System is considered Pi if either check passes
  1441. is_pi = is_arm or is_raspberry_pi
  1442. return {"is_pi": is_pi}
  1443. except Exception as e:
  1444. logger.error(f"Error checking if system is Pi: {e}")
  1445. return {"is_pi": False}
  1446. @app.post("/api/system/shutdown")
  1447. async def shutdown_system():
  1448. """Shutdown the Raspberry Pi system"""
  1449. try:
  1450. # Double-check it's a Pi before allowing shutdown
  1451. check_result = await check_pi()
  1452. if not check_result["is_pi"]:
  1453. return JSONResponse(
  1454. content={"success": False, "message": "Shutdown only available on Raspberry Pi"},
  1455. status_code=403
  1456. )
  1457. logger.warning("Shutdown initiated via API")
  1458. # Run docker compose down in background
  1459. try:
  1460. # Get the directory where main.py is located
  1461. app_dir = os.path.dirname(os.path.abspath(__file__))
  1462. subprocess.Popen(
  1463. ["docker", "compose", "down"],
  1464. cwd=app_dir,
  1465. stdout=subprocess.DEVNULL,
  1466. stderr=subprocess.DEVNULL
  1467. )
  1468. logger.info("Docker compose down command issued")
  1469. except Exception as e:
  1470. logger.error(f"Error running docker compose down: {e}")
  1471. # Schedule shutdown command after a short delay to allow response to be sent
  1472. def delayed_shutdown():
  1473. time.sleep(2) # Give time for response to be sent
  1474. try:
  1475. subprocess.run(["sudo", "shutdown", "-h", "now"], check=True)
  1476. except Exception as e:
  1477. logger.error(f"Error executing shutdown command: {e}")
  1478. import threading
  1479. shutdown_thread = threading.Thread(target=delayed_shutdown)
  1480. shutdown_thread.start()
  1481. return {"success": True, "message": "System shutdown initiated"}
  1482. except Exception as e:
  1483. logger.error(f"Error initiating shutdown: {e}")
  1484. return JSONResponse(
  1485. content={"success": False, "message": str(e)},
  1486. status_code=500
  1487. )
  1488. def entrypoint():
  1489. import uvicorn
  1490. logger.info("Starting FastAPI server on port 8080...")
  1491. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  1492. if __name__ == "__main__":
  1493. entrypoint()