app.py 20 KB

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