app.py 20 KB

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