app.py 22 KB

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