1
0

app.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect
  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 import playlist_manager
  14. from modules.update import update_manager
  15. from modules.core.state import state
  16. from modules import mqtt
  17. import signal
  18. import sys
  19. import asyncio
  20. from contextlib import asynccontextmanager
  21. from modules.led.led_controller import LEDController, effect_idle
  22. import math
  23. from modules.core.svg_cache_manager import generate_all_svg_previews, get_cache_path, generate_svg_preview
  24. # Configure logging
  25. logging.basicConfig(
  26. level=logging.INFO,
  27. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  28. handlers=[
  29. logging.StreamHandler(),
  30. ]
  31. )
  32. logger = logging.getLogger(__name__)
  33. @asynccontextmanager
  34. async def lifespan(app: FastAPI):
  35. # Startup
  36. logger.info("Starting Dune Weaver application...")
  37. # Register signal handlers
  38. signal.signal(signal.SIGINT, signal_handler)
  39. signal.signal(signal.SIGTERM, signal_handler)
  40. try:
  41. connection_manager.connect_device()
  42. except Exception as e:
  43. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  44. try:
  45. mqtt_handler = mqtt.init_mqtt()
  46. except Exception as e:
  47. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  48. # Generate SVG previews for all patterns
  49. try:
  50. logger.info("Starting SVG cache generation...")
  51. await generate_all_svg_previews()
  52. except Exception as e:
  53. logger.warning(f"Failed to generate SVG cache: {str(e)}")
  54. yield # This separates startup from shutdown code
  55. app = FastAPI(lifespan=lifespan)
  56. templates = Jinja2Templates(directory="templates")
  57. app.mount("/static", StaticFiles(directory="static"), name="static")
  58. # Pydantic models for request/response validation
  59. class ConnectRequest(BaseModel):
  60. port: Optional[str] = None
  61. class CoordinateRequest(BaseModel):
  62. theta: float
  63. rho: float
  64. class PlaylistRequest(BaseModel):
  65. playlist_name: str
  66. files: List[str] = []
  67. pause_time: float = 0
  68. clear_pattern: Optional[str] = None
  69. run_mode: str = "single"
  70. shuffle: bool = False
  71. class PlaylistRunRequest(BaseModel):
  72. playlist_name: str
  73. pause_time: Optional[float] = 0
  74. clear_pattern: Optional[str] = None
  75. run_mode: Optional[str] = "single"
  76. shuffle: Optional[bool] = False
  77. start_time: Optional[str] = None
  78. end_time: Optional[str] = None
  79. class SpeedRequest(BaseModel):
  80. speed: float
  81. class WLEDRequest(BaseModel):
  82. wled_ip: Optional[str] = None
  83. class DeletePlaylistRequest(BaseModel):
  84. playlist_name: str
  85. # Store active WebSocket connections
  86. active_status_connections = set()
  87. @app.websocket("/ws/status")
  88. async def websocket_status_endpoint(websocket: WebSocket):
  89. await websocket.accept()
  90. active_status_connections.add(websocket)
  91. try:
  92. while True:
  93. status = pattern_manager.get_status()
  94. try:
  95. await websocket.send_json({
  96. "type": "status_update",
  97. "data": status
  98. })
  99. except RuntimeError as e:
  100. if "close message has been sent" in str(e):
  101. break
  102. raise
  103. await asyncio.sleep(1)
  104. except WebSocketDisconnect:
  105. pass
  106. finally:
  107. active_status_connections.discard(websocket)
  108. try:
  109. await websocket.close()
  110. except RuntimeError:
  111. pass
  112. async def broadcast_status_update(status: dict):
  113. """Broadcast status update to all connected clients."""
  114. disconnected = set()
  115. for websocket in active_status_connections:
  116. try:
  117. await websocket.send_json({
  118. "type": "status_update",
  119. "data": status
  120. })
  121. except WebSocketDisconnect:
  122. disconnected.add(websocket)
  123. except RuntimeError:
  124. disconnected.add(websocket)
  125. active_status_connections.difference_update(disconnected)
  126. # FastAPI routes
  127. @app.get("/")
  128. async def index():
  129. return templates.TemplateResponse("index.html", {"request": {}})
  130. @app.get("/list_serial_ports")
  131. async def list_ports():
  132. logger.debug("Listing available serial ports")
  133. return connection_manager.list_serial_ports()
  134. @app.post("/connect")
  135. async def connect(request: ConnectRequest):
  136. if not request.port:
  137. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  138. connection_manager.device_init()
  139. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  140. return {"success": True}
  141. try:
  142. state.conn = connection_manager.SerialConnection(request.port)
  143. connection_manager.device_init()
  144. logger.info(f'Successfully connected to serial port {request.port}')
  145. return {"success": True}
  146. except Exception as e:
  147. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  148. raise HTTPException(status_code=500, detail=str(e))
  149. @app.post("/disconnect")
  150. async def disconnect():
  151. try:
  152. state.conn.close()
  153. logger.info('Successfully disconnected from serial port')
  154. return {"success": True}
  155. except Exception as e:
  156. logger.error(f'Failed to disconnect serial: {str(e)}')
  157. raise HTTPException(status_code=500, detail=str(e))
  158. @app.post("/restart_connection")
  159. async def restart(request: ConnectRequest):
  160. if not request.port:
  161. logger.warning("Restart serial request received without port")
  162. raise HTTPException(status_code=400, detail="No port provided")
  163. try:
  164. logger.info(f"Restarting connection on port {request.port}")
  165. connection_manager.restart_connection()
  166. return {"success": True}
  167. except Exception as e:
  168. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  169. raise HTTPException(status_code=500, detail=str(e))
  170. @app.get("/list_theta_rho_files")
  171. async def list_theta_rho_files():
  172. logger.debug("Listing theta-rho files")
  173. files = pattern_manager.list_theta_rho_files()
  174. return sorted(files)
  175. @app.post("/upload_theta_rho")
  176. async def upload_theta_rho(file: UploadFile = File(...)):
  177. """Upload a theta-rho file."""
  178. try:
  179. # Save the file
  180. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns", file.filename)
  181. with open(file_path, "wb") as f:
  182. f.write(await file.read())
  183. # Generate SVG preview for the new file
  184. await generate_svg_preview(os.path.join("custom_patterns", file.filename))
  185. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  186. except Exception as e:
  187. logger.error(f"Error uploading file: {str(e)}")
  188. raise HTTPException(status_code=500, detail=str(e))
  189. class ThetaRhoRequest(BaseModel):
  190. file_name: str
  191. pre_execution: Optional[str] = "none"
  192. @app.post("/run_theta_rho")
  193. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  194. if not request.file_name:
  195. logger.warning('Run theta-rho request received without file name')
  196. raise HTTPException(status_code=400, detail="No file name provided")
  197. file_path = None
  198. if 'clear' in request.file_name:
  199. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  200. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  201. logger.info(f'Clear pattern file: {file_path}')
  202. if not file_path:
  203. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  204. if not os.path.exists(file_path):
  205. logger.error(f'Theta-rho file not found: {file_path}')
  206. raise HTTPException(status_code=404, detail="File not found")
  207. try:
  208. if not (state.conn.is_connected() if state.conn else False):
  209. logger.warning("Attempted to run a pattern without a connection")
  210. raise HTTPException(status_code=400, detail="Connection not established")
  211. if pattern_manager.pattern_lock.locked():
  212. logger.warning("Attempted to run a pattern while another is already running")
  213. raise HTTPException(status_code=409, detail="Another pattern is already running")
  214. files_to_run = [file_path]
  215. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  216. # Only include clear_pattern if it's not "none"
  217. kwargs = {}
  218. if request.pre_execution != "none":
  219. kwargs['clear_pattern'] = request.pre_execution
  220. # Pass arguments properly
  221. background_tasks.add_task(
  222. pattern_manager.run_theta_rho_files,
  223. files_to_run, # First positional argument
  224. **kwargs # Spread keyword arguments
  225. )
  226. return {"success": True}
  227. except Exception as e:
  228. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  229. raise HTTPException(status_code=500, detail=str(e))
  230. @app.post("/stop_execution")
  231. async def stop_execution():
  232. if not (state.conn.is_connected() if state.conn else False):
  233. logger.warning("Attempted to stop without a connection")
  234. raise HTTPException(status_code=400, detail="Connection not established")
  235. pattern_manager.stop_actions()
  236. return {"success": True}
  237. @app.post("/send_home")
  238. async def send_home():
  239. try:
  240. if not (state.conn.is_connected() if state.conn else False):
  241. logger.warning("Attempted to move to home without a connection")
  242. raise HTTPException(status_code=400, detail="Connection not established")
  243. connection_manager.home()
  244. return {"success": True}
  245. except Exception as e:
  246. logger.error(f"Failed to send home command: {str(e)}")
  247. raise HTTPException(status_code=500, detail=str(e))
  248. @app.post("/run_theta_rho_file/{file_name}")
  249. async def run_specific_theta_rho_file(file_name: str):
  250. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  251. if not os.path.exists(file_path):
  252. raise HTTPException(status_code=404, detail="File not found")
  253. if not (state.conn.is_connected() if state.conn else False):
  254. logger.warning("Attempted to run a pattern without a connection")
  255. raise HTTPException(status_code=400, detail="Connection not established")
  256. pattern_manager.run_theta_rho_file(file_path)
  257. return {"success": True}
  258. class DeleteFileRequest(BaseModel):
  259. file_name: str
  260. @app.post("/delete_theta_rho_file")
  261. async def delete_theta_rho_file(request: DeleteFileRequest):
  262. if not request.file_name:
  263. logger.warning("Delete theta-rho file request received without filename")
  264. raise HTTPException(status_code=400, detail="No file name provided")
  265. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  266. if not os.path.exists(file_path):
  267. logger.error(f"Attempted to delete non-existent file: {file_path}")
  268. raise HTTPException(status_code=404, detail="File not found")
  269. try:
  270. os.remove(file_path)
  271. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  272. return {"success": True}
  273. except Exception as e:
  274. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  275. raise HTTPException(status_code=500, detail=str(e))
  276. @app.post("/move_to_center")
  277. async def move_to_center():
  278. try:
  279. if not (state.conn.is_connected() if state.conn else False):
  280. logger.warning("Attempted to move to center without a connection")
  281. raise HTTPException(status_code=400, detail="Connection not established")
  282. logger.info("Moving device to center position")
  283. pattern_manager.reset_theta()
  284. pattern_manager.move_polar(0, 0)
  285. return {"success": True}
  286. except Exception as e:
  287. logger.error(f"Failed to move to center: {str(e)}")
  288. raise HTTPException(status_code=500, detail=str(e))
  289. @app.post("/move_to_perimeter")
  290. async def move_to_perimeter():
  291. try:
  292. if not (state.conn.is_connected() if state.conn else False):
  293. logger.warning("Attempted to move to perimeter without a connection")
  294. raise HTTPException(status_code=400, detail="Connection not established")
  295. pattern_manager.reset_theta()
  296. pattern_manager.move_polar(0, 1)
  297. return {"success": True}
  298. except Exception as e:
  299. logger.error(f"Failed to move to perimeter: {str(e)}")
  300. raise HTTPException(status_code=500, detail=str(e))
  301. @app.post("/preview_thr")
  302. async def preview_thr(request: DeleteFileRequest):
  303. if not request.file_name:
  304. logger.warning("Preview theta-rho request received without filename")
  305. raise HTTPException(status_code=400, detail="No file name provided")
  306. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  307. if not os.path.exists(file_path):
  308. logger.error(f"Attempted to preview non-existent file: {file_path}")
  309. raise HTTPException(status_code=404, detail="File not found")
  310. try:
  311. # Check if cached SVG exists
  312. cache_path = get_cache_path(request.file_name)
  313. if os.path.exists(cache_path):
  314. with open(cache_path, 'r', encoding='utf-8') as f:
  315. svg_content = f.read()
  316. # Parse coordinates for first and last points
  317. coordinates = pattern_manager.parse_theta_rho_file(file_path)
  318. first_coord = coordinates[0] if coordinates else None
  319. last_coord = coordinates[-1] if coordinates else None
  320. return {
  321. "svg": svg_content,
  322. "first_coordinate": first_coord,
  323. "last_coordinate": last_coord
  324. }
  325. # If not cached, generate SVG as before
  326. coordinates = pattern_manager.parse_theta_rho_file(file_path)
  327. # Convert polar coordinates to SVG path
  328. svg_path = []
  329. for i, (theta, rho) in enumerate(coordinates):
  330. x = 100 - rho * 90 * math.cos(theta)
  331. y = 100 - rho * 90 * math.sin(theta)
  332. if i == 0:
  333. svg_path.append(f"M {x:.2f} {y:.2f}")
  334. else:
  335. svg_path.append(f"L {x:.2f} {y:.2f}")
  336. svg = f'''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  337. <svg width="100%" height="100%" viewBox="0 0 200 200" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg">
  338. <path d="{' '.join(svg_path)}"
  339. fill="none"
  340. stroke="currentColor"
  341. stroke-width="0.5"/>
  342. </svg>'''
  343. # Cache the SVG for future use
  344. with open(cache_path, 'w', encoding='utf-8') as f:
  345. f.write(svg)
  346. return {
  347. "svg": svg,
  348. "first_coordinate": coordinates[0] if coordinates else None,
  349. "last_coordinate": coordinates[-1] if coordinates else None
  350. }
  351. except Exception as e:
  352. logger.error(f"Failed to generate preview for {request.file_name}: {str(e)}")
  353. raise HTTPException(status_code=500, detail=str(e))
  354. @app.post("/send_coordinate")
  355. async def send_coordinate(request: CoordinateRequest):
  356. if not (state.conn.is_connected() if state.conn else False):
  357. logger.warning("Attempted to send coordinate without a connection")
  358. raise HTTPException(status_code=400, detail="Connection not established")
  359. try:
  360. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  361. pattern_manager.move_polar(request.theta, request.rho)
  362. return {"success": True}
  363. except Exception as e:
  364. logger.error(f"Failed to send coordinate: {str(e)}")
  365. raise HTTPException(status_code=500, detail=str(e))
  366. @app.get("/download/{filename}")
  367. async def download_file(filename: str):
  368. return FileResponse(
  369. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  370. filename=filename
  371. )
  372. @app.get("/serial_status")
  373. async def serial_status():
  374. connected = state.conn.is_connected() if state.conn else False
  375. port = state.port
  376. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  377. return {
  378. "connected": connected,
  379. "port": port
  380. }
  381. @app.post("/pause_execution")
  382. async def pause_execution():
  383. if pattern_manager.pause_execution():
  384. return {"success": True, "message": "Execution paused"}
  385. raise HTTPException(status_code=500, detail="Failed to pause execution")
  386. @app.post("/resume_execution")
  387. async def resume_execution():
  388. if pattern_manager.resume_execution():
  389. return {"success": True, "message": "Execution resumed"}
  390. raise HTTPException(status_code=500, detail="Failed to resume execution")
  391. # Playlist endpoints
  392. @app.get("/list_all_playlists")
  393. async def list_all_playlists():
  394. playlist_names = playlist_manager.list_all_playlists()
  395. return playlist_names
  396. @app.get("/get_playlist")
  397. async def get_playlist(name: str):
  398. if not name:
  399. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  400. playlist = playlist_manager.get_playlist(name)
  401. if not playlist:
  402. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  403. return playlist
  404. @app.post("/create_playlist")
  405. async def create_playlist(request: PlaylistRequest):
  406. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  407. return {
  408. "success": success,
  409. "message": f"Playlist '{request.playlist_name}' created/updated"
  410. }
  411. @app.post("/modify_playlist")
  412. async def modify_playlist(request: PlaylistRequest):
  413. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  414. return {
  415. "success": success,
  416. "message": f"Playlist '{request.playlist_name}' updated"
  417. }
  418. @app.delete("/delete_playlist")
  419. async def delete_playlist(request: DeletePlaylistRequest):
  420. success = playlist_manager.delete_playlist(request.playlist_name)
  421. if not success:
  422. raise HTTPException(
  423. status_code=404,
  424. detail=f"Playlist '{request.playlist_name}' not found"
  425. )
  426. return {
  427. "success": True,
  428. "message": f"Playlist '{request.playlist_name}' deleted"
  429. }
  430. class AddToPlaylistRequest(BaseModel):
  431. playlist_name: str
  432. pattern: str
  433. @app.post("/add_to_playlist")
  434. async def add_to_playlist(request: AddToPlaylistRequest):
  435. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  436. if not success:
  437. raise HTTPException(status_code=404, detail="Playlist not found")
  438. return {"success": True}
  439. @app.post("/run_playlist")
  440. async def run_playlist_endpoint(request: PlaylistRequest):
  441. """Run a playlist with specified parameters."""
  442. try:
  443. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  444. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  445. # Start the playlist execution
  446. asyncio.create_task(playlist_manager.run_playlist(
  447. request.playlist_name,
  448. pause_time=request.pause_time,
  449. clear_pattern=request.clear_pattern,
  450. run_mode=request.run_mode,
  451. shuffle=request.shuffle
  452. ))
  453. return {"message": f"Started playlist: {request.playlist_name}"}
  454. except Exception as e:
  455. logger.error(f"Error running playlist: {e}")
  456. raise HTTPException(status_code=500, detail=str(e))
  457. @app.post("/set_speed")
  458. async def set_speed(request: SpeedRequest):
  459. try:
  460. if not (state.conn.is_connected() if state.conn else False):
  461. logger.warning("Attempted to change speed without a connection")
  462. raise HTTPException(status_code=400, detail="Connection not established")
  463. if request.speed <= 0:
  464. logger.warning(f"Invalid speed value received: {request.speed}")
  465. raise HTTPException(status_code=400, detail="Invalid speed value")
  466. state.speed = request.speed
  467. return {"success": True, "speed": request.speed}
  468. except Exception as e:
  469. logger.error(f"Failed to set speed: {str(e)}")
  470. raise HTTPException(status_code=500, detail=str(e))
  471. @app.get("/check_software_update")
  472. async def check_updates():
  473. update_info = update_manager.check_git_updates()
  474. return update_info
  475. @app.post("/update_software")
  476. async def update_software():
  477. logger.info("Starting software update process")
  478. success, error_message, error_log = update_manager.update_software()
  479. if success:
  480. logger.info("Software update completed successfully")
  481. return {"success": True}
  482. else:
  483. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  484. raise HTTPException(
  485. status_code=500,
  486. detail={
  487. "error": error_message,
  488. "details": error_log
  489. }
  490. )
  491. @app.post("/set_wled_ip")
  492. async def set_wled_ip(request: WLEDRequest):
  493. state.wled_ip = request.wled_ip
  494. state.led_controller = LEDController(request.wled_ip)
  495. effect_idle(state.led_controller)
  496. state.save()
  497. logger.info(f"WLED IP updated: {request.wled_ip}")
  498. return {"success": True, "wled_ip": state.wled_ip}
  499. @app.get("/get_wled_ip")
  500. async def get_wled_ip():
  501. if not state.wled_ip:
  502. raise HTTPException(status_code=404, detail="No WLED IP set")
  503. return {"success": True, "wled_ip": state.wled_ip}
  504. @app.post("/skip_pattern")
  505. async def skip_pattern():
  506. if not state.current_playlist:
  507. raise HTTPException(status_code=400, detail="No playlist is currently running")
  508. state.skip_requested = True
  509. return {"success": True}
  510. def signal_handler(signum, frame):
  511. """Handle shutdown signals gracefully but forcefully."""
  512. logger.info("Received shutdown signal, cleaning up...")
  513. try:
  514. if state.led_controller:
  515. state.led_controller.set_power(0)
  516. # Run cleanup operations synchronously to ensure completion
  517. pattern_manager.stop_actions()
  518. state.save()
  519. logger.info("Cleanup completed")
  520. except Exception as e:
  521. logger.error(f"Error during cleanup: {str(e)}")
  522. finally:
  523. logger.info("Exiting application...")
  524. os._exit(0) # Force exit regardless of other threads
  525. def entrypoint():
  526. import uvicorn
  527. logger.info("Starting FastAPI server on port 8080...")
  528. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  529. if __name__ == "__main__":
  530. entrypoint()