printer_manager.py 10 KB

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