app.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect
  2. from fastapi.responses import JSONResponse, FileResponse
  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. # Configure logging
  22. logging.basicConfig(
  23. level=logging.INFO,
  24. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  25. handlers=[
  26. logging.StreamHandler(),
  27. ]
  28. )
  29. logger = logging.getLogger(__name__)
  30. @asynccontextmanager
  31. async def lifespan(app: FastAPI):
  32. # Startup
  33. logger.info("Starting Dune Weaver application...")
  34. # Register signal handlers
  35. signal.signal(signal.SIGINT, signal_handler)
  36. signal.signal(signal.SIGTERM, signal_handler)
  37. try:
  38. connection_manager.connect_device()
  39. except Exception as e:
  40. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  41. try:
  42. mqtt_handler = mqtt.init_mqtt()
  43. except Exception as e:
  44. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  45. yield # This separates startup from shutdown code
  46. # Shutdown
  47. on_exit()
  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. pause_time: float = 0
  60. clear_pattern: Optional[str] = None
  61. run_mode: str = "single"
  62. shuffle: bool = False
  63. class PlaylistRunRequest(BaseModel):
  64. playlist_name: str
  65. pause_time: Optional[float] = 0
  66. clear_pattern: Optional[str] = None
  67. run_mode: Optional[str] = "single"
  68. shuffle: Optional[bool] = False
  69. start_time: Optional[str] = None
  70. end_time: Optional[str] = None
  71. class SpeedRequest(BaseModel):
  72. speed: float
  73. class WLEDRequest(BaseModel):
  74. wled_ip: Optional[str] = None
  75. # Store active WebSocket connections
  76. active_status_connections = set()
  77. @app.websocket("/ws/status")
  78. async def websocket_status_endpoint(websocket: WebSocket):
  79. await websocket.accept()
  80. active_status_connections.add(websocket)
  81. try:
  82. while True:
  83. # Keep the connection alive and handle any incoming messages
  84. data = await websocket.receive_text()
  85. if data == "get_status":
  86. status = pattern_manager.get_status()
  87. await websocket.send_json(status)
  88. except WebSocketDisconnect:
  89. active_status_connections.remove(websocket)
  90. async def broadcast_status_update(status: dict):
  91. """Broadcast status update to all connected clients."""
  92. disconnected = set()
  93. for websocket in active_status_connections:
  94. try:
  95. await websocket.send_json(status)
  96. except WebSocketDisconnect:
  97. disconnected.add(websocket)
  98. # Clean up disconnected clients
  99. active_status_connections.difference_update(disconnected)
  100. # FastAPI routes
  101. @app.get("/")
  102. async def index():
  103. return templates.TemplateResponse("index.html", {"request": {}})
  104. @app.get("/list_serial_ports")
  105. async def list_ports():
  106. logger.debug("Listing available serial ports")
  107. return connection_manager.list_serial_ports()
  108. @app.post("/connect")
  109. async def connect(request: ConnectRequest):
  110. if not request.port:
  111. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  112. connection_manager.device_init()
  113. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  114. return {"success": True}
  115. try:
  116. state.conn = connection_manager.SerialConnection(request.port)
  117. connection_manager.device_init()
  118. logger.info(f'Successfully connected to serial port {request.port}')
  119. return {"success": True}
  120. except Exception as e:
  121. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  122. raise HTTPException(status_code=500, detail=str(e))
  123. @app.post("/disconnect")
  124. async def disconnect():
  125. try:
  126. state.conn.close()
  127. logger.info('Successfully disconnected from serial port')
  128. return {"success": True}
  129. except Exception as e:
  130. logger.error(f'Failed to disconnect serial: {str(e)}')
  131. raise HTTPException(status_code=500, detail=str(e))
  132. @app.post("/restart_connection")
  133. async def restart(request: ConnectRequest):
  134. if not request.port:
  135. logger.warning("Restart serial request received without port")
  136. raise HTTPException(status_code=400, detail="No port provided")
  137. try:
  138. logger.info(f"Restarting connection on port {request.port}")
  139. connection_manager.restart_connection()
  140. return {"success": True}
  141. except Exception as e:
  142. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  143. raise HTTPException(status_code=500, detail=str(e))
  144. @app.get("/list_theta_rho_files")
  145. async def list_theta_rho_files():
  146. logger.debug("Listing theta-rho files")
  147. files = pattern_manager.list_theta_rho_files()
  148. return sorted(files)
  149. @app.post("/upload_theta_rho")
  150. async def upload_theta_rho(file: UploadFile = File(...)):
  151. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, 'custom_patterns')
  152. os.makedirs(custom_patterns_dir, exist_ok=True)
  153. logger.debug(f'Ensuring custom patterns directory exists: {custom_patterns_dir}')
  154. if file:
  155. file_path = os.path.join(custom_patterns_dir, file.filename)
  156. contents = await file.read()
  157. with open(file_path, "wb") as f:
  158. f.write(contents)
  159. logger.info(f'Successfully uploaded theta-rho file: {file.filename}')
  160. return {"success": True}
  161. logger.warning('Upload theta-rho request received without file')
  162. return {"success": False}
  163. class ThetaRhoRequest(BaseModel):
  164. file_name: str
  165. pre_execution: Optional[str] = "none"
  166. @app.post("/run_theta_rho")
  167. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  168. if not request.file_name:
  169. logger.warning('Run theta-rho request received without file name')
  170. raise HTTPException(status_code=400, detail="No file name provided")
  171. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  172. if not os.path.exists(file_path):
  173. logger.error(f'Theta-rho file not found: {file_path}')
  174. raise HTTPException(status_code=404, detail="File not found")
  175. try:
  176. if not (state.conn.is_connected() if state.conn else False):
  177. logger.warning("Attempted to run a pattern without a connection")
  178. raise HTTPException(status_code=400, detail="Connection not established")
  179. if pattern_manager.pattern_lock.locked():
  180. logger.warning("Attempted to run a pattern while another is already running")
  181. raise HTTPException(status_code=409, detail="Another pattern is already running")
  182. files_to_run = [file_path]
  183. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  184. background_tasks.add_task(
  185. pattern_manager.run_theta_rho_files,
  186. files_to_run,
  187. clear_pattern=request.pre_execution if request.pre_execution != "none" else None
  188. )
  189. return {"success": True}
  190. except Exception as e:
  191. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  192. raise HTTPException(status_code=500, detail=str(e))
  193. @app.post("/stop_execution")
  194. async def stop_execution():
  195. if not (state.conn.is_connected() if state.conn else False):
  196. logger.warning("Attempted to stop without a connection")
  197. raise HTTPException(status_code=400, detail="Connection not established")
  198. pattern_manager.stop_actions()
  199. return {"success": True}
  200. @app.post("/send_home")
  201. async def send_home():
  202. try:
  203. if not (state.conn.is_connected() if state.conn else False):
  204. logger.warning("Attempted to move to home without a connection")
  205. raise HTTPException(status_code=400, detail="Connection not established")
  206. connection_manager.home()
  207. return {"success": True}
  208. except Exception as e:
  209. logger.error(f"Failed to send home command: {str(e)}")
  210. raise HTTPException(status_code=500, detail=str(e))
  211. @app.post("/run_theta_rho_file/{file_name}")
  212. async def run_specific_theta_rho_file(file_name: str):
  213. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  214. if not os.path.exists(file_path):
  215. raise HTTPException(status_code=404, detail="File not found")
  216. if not (state.conn.is_connected() if state.conn else False):
  217. logger.warning("Attempted to run a pattern without a connection")
  218. raise HTTPException(status_code=400, detail="Connection not established")
  219. pattern_manager.run_theta_rho_file(file_path)
  220. return {"success": True}
  221. class DeleteFileRequest(BaseModel):
  222. file_name: str
  223. @app.post("/delete_theta_rho_file")
  224. async def delete_theta_rho_file(request: DeleteFileRequest):
  225. if not request.file_name:
  226. logger.warning("Delete theta-rho file request received without filename")
  227. raise HTTPException(status_code=400, detail="No file name provided")
  228. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  229. if not os.path.exists(file_path):
  230. logger.error(f"Attempted to delete non-existent file: {file_path}")
  231. raise HTTPException(status_code=404, detail="File not found")
  232. try:
  233. os.remove(file_path)
  234. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  235. return {"success": True}
  236. except Exception as e:
  237. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  238. raise HTTPException(status_code=500, detail=str(e))
  239. @app.post("/move_to_center")
  240. async def move_to_center():
  241. try:
  242. if not (state.conn.is_connected() if state.conn else False):
  243. logger.warning("Attempted to move to center without a connection")
  244. raise HTTPException(status_code=400, detail="Connection not established")
  245. logger.info("Moving device to center position")
  246. pattern_manager.reset_theta()
  247. pattern_manager.move_polar(0, 0)
  248. return {"success": True}
  249. except Exception as e:
  250. logger.error(f"Failed to move to center: {str(e)}")
  251. raise HTTPException(status_code=500, detail=str(e))
  252. @app.post("/move_to_perimeter")
  253. async def move_to_perimeter():
  254. try:
  255. if not (state.conn.is_connected() if state.conn else False):
  256. logger.warning("Attempted to move to perimeter without a connection")
  257. raise HTTPException(status_code=400, detail="Connection not established")
  258. pattern_manager.reset_theta()
  259. pattern_manager.move_polar(0, 1)
  260. return {"success": True}
  261. except Exception as e:
  262. logger.error(f"Failed to move to perimeter: {str(e)}")
  263. raise HTTPException(status_code=500, detail=str(e))
  264. @app.post("/preview_thr")
  265. async def preview_thr(request: DeleteFileRequest):
  266. if not request.file_name:
  267. logger.warning("Preview theta-rho request received without filename")
  268. raise HTTPException(status_code=400, detail="No file name provided")
  269. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, request.file_name)
  270. if not os.path.exists(file_path):
  271. logger.error(f"Attempted to preview non-existent file: {file_path}")
  272. raise HTTPException(status_code=404, detail="File not found")
  273. try:
  274. coordinates = pattern_manager.parse_theta_rho_file(file_path)
  275. return {"success": True, "coordinates": coordinates}
  276. except Exception as e:
  277. logger.error(f"Failed to generate preview for {request.file_name}: {str(e)}")
  278. raise HTTPException(status_code=500, detail=str(e))
  279. @app.post("/send_coordinate")
  280. async def send_coordinate(request: CoordinateRequest):
  281. if not (state.conn.is_connected() if state.conn else False):
  282. logger.warning("Attempted to send coordinate without a connection")
  283. raise HTTPException(status_code=400, detail="Connection not established")
  284. try:
  285. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  286. pattern_manager.move_polar(request.theta, request.rho)
  287. return {"success": True}
  288. except Exception as e:
  289. logger.error(f"Failed to send coordinate: {str(e)}")
  290. raise HTTPException(status_code=500, detail=str(e))
  291. @app.get("/download/{filename}")
  292. async def download_file(filename: str):
  293. return FileResponse(
  294. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  295. filename=filename
  296. )
  297. @app.get("/serial_status")
  298. async def serial_status():
  299. connected = state.conn.is_connected() if state.conn else False
  300. port = state.port
  301. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  302. return {
  303. "connected": connected,
  304. "port": port
  305. }
  306. @app.post("/pause_execution")
  307. async def pause_execution():
  308. if pattern_manager.pause_execution():
  309. return {"success": True, "message": "Execution paused"}
  310. raise HTTPException(status_code=500, detail="Failed to pause execution")
  311. @app.get("/status")
  312. async def get_status():
  313. status = pattern_manager.get_status()
  314. await broadcast_status_update(status)
  315. return status
  316. @app.post("/resume_execution")
  317. async def resume_execution():
  318. if pattern_manager.resume_execution():
  319. return {"success": True, "message": "Execution resumed"}
  320. raise HTTPException(status_code=500, detail="Failed to resume execution")
  321. # Playlist endpoints
  322. @app.get("/list_all_playlists")
  323. async def list_all_playlists():
  324. playlist_names = playlist_manager.list_all_playlists()
  325. return playlist_names
  326. @app.get("/get_playlist")
  327. async def get_playlist(name: str):
  328. if not name:
  329. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  330. playlist = playlist_manager.get_playlist(name)
  331. if not playlist:
  332. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  333. return playlist
  334. @app.post("/create_playlist")
  335. async def create_playlist(request: PlaylistRequest):
  336. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  337. return {
  338. "success": success,
  339. "message": f"Playlist '{request.playlist_name}' created/updated"
  340. }
  341. @app.post("/modify_playlist")
  342. async def modify_playlist(request: PlaylistRequest):
  343. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  344. return {
  345. "success": success,
  346. "message": f"Playlist '{request.playlist_name}' updated"
  347. }
  348. @app.delete("/delete_playlist")
  349. async def delete_playlist(request: DeleteFileRequest):
  350. success = playlist_manager.delete_playlist(request.file_name)
  351. if not success:
  352. raise HTTPException(
  353. status_code=404,
  354. detail=f"Playlist '{request.file_name}' not found"
  355. )
  356. return {
  357. "success": True,
  358. "message": f"Playlist '{request.file_name}' deleted"
  359. }
  360. class AddToPlaylistRequest(BaseModel):
  361. playlist_name: str
  362. pattern: str
  363. @app.post("/add_to_playlist")
  364. async def add_to_playlist(request: AddToPlaylistRequest):
  365. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  366. if not success:
  367. raise HTTPException(status_code=404, detail="Playlist not found")
  368. return {"success": True}
  369. @app.post("/run_playlist")
  370. async def run_playlist_endpoint(request: PlaylistRequest):
  371. """Run a playlist with specified parameters."""
  372. try:
  373. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  374. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  375. # Start the playlist execution
  376. asyncio.create_task(playlist_manager.run_playlist(
  377. request.playlist_name,
  378. pause_time=request.pause_time,
  379. clear_pattern=request.clear_pattern,
  380. run_mode=request.run_mode,
  381. shuffle=request.shuffle
  382. ))
  383. return {"message": f"Started playlist: {request.playlist_name}"}
  384. except Exception as e:
  385. logger.error(f"Error running playlist: {e}")
  386. raise HTTPException(status_code=500, detail=str(e))
  387. @app.post("/set_speed")
  388. async def set_speed(request: SpeedRequest):
  389. try:
  390. if not (state.conn.is_connected() if state.conn else False):
  391. logger.warning("Attempted to change speed without a connection")
  392. raise HTTPException(status_code=400, detail="Connection not established")
  393. if request.speed <= 0:
  394. logger.warning(f"Invalid speed value received: {request.speed}")
  395. raise HTTPException(status_code=400, detail="Invalid speed value")
  396. state.speed = request.speed
  397. return {"success": True, "speed": request.speed}
  398. except Exception as e:
  399. logger.error(f"Failed to set speed: {str(e)}")
  400. raise HTTPException(status_code=500, detail=str(e))
  401. @app.get("/check_software_update")
  402. async def check_updates():
  403. update_info = update_manager.check_git_updates()
  404. return update_info
  405. @app.post("/update_software")
  406. async def update_software():
  407. logger.info("Starting software update process")
  408. success, error_message, error_log = update_manager.update_software()
  409. if success:
  410. logger.info("Software update completed successfully")
  411. return {"success": True}
  412. else:
  413. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  414. raise HTTPException(
  415. status_code=500,
  416. detail={
  417. "error": error_message,
  418. "details": error_log
  419. }
  420. )
  421. @app.post("/set_wled_ip")
  422. async def set_wled_ip(request: WLEDRequest):
  423. state.wled_ip = request.wled_ip
  424. state.save()
  425. logger.info(f"WLED IP updated: {request.wled_ip}")
  426. return {"success": True, "wled_ip": state.wled_ip}
  427. @app.get("/get_wled_ip")
  428. async def get_wled_ip():
  429. if not state.wled_ip:
  430. raise HTTPException(status_code=404, detail="No WLED IP set")
  431. return {"success": True, "wled_ip": state.wled_ip}
  432. def on_exit():
  433. """Function to execute on application shutdown."""
  434. logger.info("Shutting down gracefully, please wait for execution to complete")
  435. pattern_manager.stop_actions()
  436. state.save()
  437. mqtt.cleanup_mqtt()
  438. def signal_handler(signum, frame):
  439. """Handle shutdown signals gracefully but forcefully."""
  440. logger.info("Received shutdown signal, cleaning up...")
  441. try:
  442. # Set a short timeout for cleanup operations
  443. import threading
  444. cleanup_thread = threading.Thread(target=lambda: [
  445. pattern_manager.stop_actions(),
  446. state.save(),
  447. mqtt.cleanup_mqtt()
  448. ])
  449. cleanup_thread.daemon = True # Make thread daemonic so it won't block exit
  450. cleanup_thread.start()
  451. cleanup_thread.join(timeout=10.0) # Wait up to 2 seconds for cleanup
  452. except Exception as e:
  453. logger.error(f"Error during cleanup: {str(e)}")
  454. finally:
  455. logger.info("Forcing exit...")
  456. os._exit(0) # Force exit regardless of other threads
  457. def entrypoint():
  458. import uvicorn
  459. atexit.register(on_exit)
  460. logger.info("Starting FastAPI server on port 8080...")
  461. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  462. if __name__ == "__main__":
  463. entrypoint()