printer_manager.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import asyncio
  2. from typing import Callable
  3. from dataclasses import asdict
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from sqlalchemy import select
  6. from backend.app.models.printer import Printer
  7. from backend.app.services.bambu_mqtt import BambuMQTTClient, PrinterState, MQTTLogEntry
  8. from backend.app.services.bambu_ftp import BambuFTPClient
  9. class PrinterManager:
  10. """Manager for multiple printer connections."""
  11. def __init__(self):
  12. self._clients: dict[int, BambuMQTTClient] = {}
  13. self._on_print_start: Callable[[int, dict], None] | None = None
  14. self._on_print_complete: Callable[[int, dict], None] | None = None
  15. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  16. self._on_ams_change: Callable[[int, list], None] | None = None
  17. self._loop: asyncio.AbstractEventLoop | None = None
  18. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  19. """Set the event loop for async callbacks."""
  20. self._loop = loop
  21. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  22. """Set callback for print start events."""
  23. self._on_print_start = callback
  24. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  25. """Set callback for print completion events."""
  26. self._on_print_complete = callback
  27. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  28. """Set callback for status change events."""
  29. self._on_status_change = callback
  30. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  31. """Set callback for AMS data change events."""
  32. self._on_ams_change = callback
  33. def _schedule_async(self, coro):
  34. """Schedule an async coroutine from a sync context."""
  35. if self._loop and self._loop.is_running():
  36. asyncio.run_coroutine_threadsafe(coro, self._loop)
  37. async def connect_printer(self, printer: Printer) -> bool:
  38. """Connect to a printer."""
  39. if printer.id in self._clients:
  40. self.disconnect_printer(printer.id)
  41. printer_id = printer.id
  42. def on_state_change(state: PrinterState):
  43. if self._on_status_change:
  44. self._schedule_async(
  45. self._on_status_change(printer_id, state)
  46. )
  47. def on_print_start(data: dict):
  48. if self._on_print_start:
  49. self._schedule_async(
  50. self._on_print_start(printer_id, data)
  51. )
  52. def on_print_complete(data: dict):
  53. if self._on_print_complete:
  54. self._schedule_async(
  55. self._on_print_complete(printer_id, data)
  56. )
  57. def on_ams_change(ams_data: list):
  58. if self._on_ams_change:
  59. self._schedule_async(
  60. self._on_ams_change(printer_id, ams_data)
  61. )
  62. client = BambuMQTTClient(
  63. ip_address=printer.ip_address,
  64. serial_number=printer.serial_number,
  65. access_code=printer.access_code,
  66. on_state_change=on_state_change,
  67. on_print_start=on_print_start,
  68. on_print_complete=on_print_complete,
  69. on_ams_change=on_ams_change,
  70. )
  71. client.connect()
  72. self._clients[printer_id] = client
  73. # Wait a moment for connection
  74. await asyncio.sleep(1)
  75. return client.state.connected
  76. def disconnect_printer(self, printer_id: int):
  77. """Disconnect from a printer."""
  78. if printer_id in self._clients:
  79. self._clients[printer_id].disconnect()
  80. del self._clients[printer_id]
  81. def disconnect_all(self):
  82. """Disconnect from all printers."""
  83. for printer_id in list(self._clients.keys()):
  84. self.disconnect_printer(printer_id)
  85. def get_status(self, printer_id: int) -> PrinterState | None:
  86. """Get the current status of a printer."""
  87. if printer_id in self._clients:
  88. return self._clients[printer_id].state
  89. return None
  90. def get_all_statuses(self) -> dict[int, PrinterState]:
  91. """Get status of all connected printers."""
  92. return {
  93. printer_id: client.state
  94. for printer_id, client in self._clients.items()
  95. }
  96. def is_connected(self, printer_id: int) -> bool:
  97. """Check if a printer is connected."""
  98. if printer_id in self._clients:
  99. return self._clients[printer_id].state.connected
  100. return False
  101. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  102. """Get the MQTT client for a printer."""
  103. return self._clients.get(printer_id)
  104. def mark_printer_offline(self, printer_id: int):
  105. """Mark a printer as offline and trigger status callback.
  106. This is used when we know the printer power was cut (e.g., smart plug turned off)
  107. to immediately update the UI without waiting for MQTT timeout.
  108. """
  109. import logging
  110. logger = logging.getLogger(__name__)
  111. if printer_id in self._clients:
  112. client = self._clients[printer_id]
  113. if client.state.connected:
  114. logger.info(f"Marking printer {printer_id} as offline (smart plug power off)")
  115. client.state.connected = False
  116. client.state.state = "unknown"
  117. # Trigger the status change callback to broadcast via WebSocket
  118. if self._on_status_change:
  119. self._schedule_async(self._on_status_change(printer_id, client.state))
  120. def start_print(self, printer_id: int, filename: str) -> bool:
  121. """Start a print on a connected printer."""
  122. if printer_id in self._clients:
  123. return self._clients[printer_id].start_print(filename)
  124. return False
  125. def stop_print(self, printer_id: int) -> bool:
  126. """Stop the current print on a connected printer."""
  127. if printer_id in self._clients:
  128. return self._clients[printer_id].stop_print()
  129. return False
  130. async def wait_for_cooldown(
  131. self,
  132. printer_id: int,
  133. target_temp: float = 50.0,
  134. timeout: int = 600,
  135. check_interval: int = 10,
  136. ) -> bool:
  137. """Wait for the nozzle to cool down to a safe temperature.
  138. Args:
  139. printer_id: The printer to monitor
  140. target_temp: Target temperature to wait for (default 50°C)
  141. timeout: Maximum seconds to wait (default 600s = 10 min)
  142. check_interval: Seconds between temperature checks (default 10s)
  143. Returns:
  144. True if cooled down, False if timeout or not connected
  145. """
  146. import logging
  147. logger = logging.getLogger(__name__)
  148. elapsed = 0
  149. while elapsed < timeout:
  150. state = self.get_status(printer_id)
  151. if not state or not state.connected:
  152. logger.warning(f"Printer {printer_id} disconnected during cooldown wait")
  153. return False
  154. # Check nozzle temperature (and nozzle_2 for dual extruders)
  155. nozzle_temp = state.temperatures.get("nozzle", 0)
  156. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  157. max_temp = max(nozzle_temp, nozzle_2_temp)
  158. if max_temp <= target_temp:
  159. logger.info(f"Printer {printer_id} cooled down to {max_temp}°C")
  160. return True
  161. logger.debug(f"Printer {printer_id} nozzle at {max_temp}°C, waiting for {target_temp}°C...")
  162. await asyncio.sleep(check_interval)
  163. elapsed += check_interval
  164. logger.warning(f"Printer {printer_id} cooldown timeout after {timeout}s")
  165. return False
  166. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  167. """Enable or disable MQTT logging for a printer."""
  168. if printer_id in self._clients:
  169. self._clients[printer_id].enable_logging(enabled)
  170. return True
  171. return False
  172. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  173. """Get MQTT logs for a printer."""
  174. if printer_id in self._clients:
  175. return self._clients[printer_id].get_logs()
  176. return []
  177. def clear_logs(self, printer_id: int) -> bool:
  178. """Clear MQTT logs for a printer."""
  179. if printer_id in self._clients:
  180. self._clients[printer_id].clear_logs()
  181. return True
  182. return False
  183. def is_logging_enabled(self, printer_id: int) -> bool:
  184. """Check if logging is enabled for a printer."""
  185. if printer_id in self._clients:
  186. return self._clients[printer_id].logging_enabled
  187. return False
  188. async def test_connection(
  189. self,
  190. ip_address: str,
  191. serial_number: str,
  192. access_code: str,
  193. ) -> dict:
  194. """Test connection to a printer without persisting."""
  195. client = BambuMQTTClient(
  196. ip_address=ip_address,
  197. serial_number=serial_number,
  198. access_code=access_code,
  199. )
  200. try:
  201. client.connect()
  202. await asyncio.sleep(2)
  203. result = {
  204. "success": client.state.connected,
  205. "state": client.state.state if client.state.connected else None,
  206. "model": client.state.raw_data.get("device_model"),
  207. }
  208. finally:
  209. client.disconnect()
  210. return result
  211. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None) -> dict:
  212. """Convert PrinterState to a JSON-serializable dict."""
  213. result = {
  214. "connected": state.connected,
  215. "state": state.state,
  216. "current_print": state.current_print,
  217. "subtask_name": state.subtask_name,
  218. "gcode_file": state.gcode_file,
  219. "progress": state.progress,
  220. "remaining_time": state.remaining_time,
  221. "layer_num": state.layer_num,
  222. "total_layers": state.total_layers,
  223. "temperatures": state.temperatures,
  224. "hms_errors": [
  225. {"code": e.code, "module": e.module, "severity": e.severity}
  226. for e in (state.hms_errors or [])
  227. ],
  228. }
  229. # Add cover URL if there's an active print and printer_id is provided
  230. if printer_id and state.state == "RUNNING" and state.gcode_file:
  231. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  232. else:
  233. result["cover_url"] = None
  234. return result
  235. # Global printer manager instance
  236. printer_manager = PrinterManager()
  237. async def init_printer_connections(db: AsyncSession):
  238. """Initialize connections to all active printers."""
  239. result = await db.execute(
  240. select(Printer).where(Printer.is_active == True)
  241. )
  242. printers = result.scalars().all()
  243. for printer in printers:
  244. await printer_manager.connect_printer(printer)