app.py 23 KB

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