printer_manager.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. def request_status_update(self, printer_id: int) -> bool:
  189. """Request a full status update from the printer.
  190. This sends a 'pushall' command to get the latest data including nozzle info.
  191. """
  192. if printer_id in self._clients:
  193. return self._clients[printer_id].request_status_update()
  194. return False
  195. async def test_connection(
  196. self,
  197. ip_address: str,
  198. serial_number: str,
  199. access_code: str,
  200. ) -> dict:
  201. """Test connection to a printer without persisting."""
  202. client = BambuMQTTClient(
  203. ip_address=ip_address,
  204. serial_number=serial_number,
  205. access_code=access_code,
  206. )
  207. try:
  208. client.connect()
  209. await asyncio.sleep(2)
  210. result = {
  211. "success": client.state.connected,
  212. "state": client.state.state if client.state.connected else None,
  213. "model": client.state.raw_data.get("device_model"),
  214. }
  215. finally:
  216. client.disconnect()
  217. return result
  218. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None) -> dict:
  219. """Convert PrinterState to a JSON-serializable dict."""
  220. # Parse AMS data from raw_data
  221. ams_units = []
  222. vt_tray = None
  223. raw_data = state.raw_data or {}
  224. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  225. for ams_data in raw_data["ams"]:
  226. trays = []
  227. for tray in ams_data.get("tray", []):
  228. tag_uid = tray.get("tag_uid")
  229. if tag_uid in ("", "0000000000000000"):
  230. tag_uid = None
  231. tray_uuid = tray.get("tray_uuid")
  232. if tray_uuid in ("", "00000000000000000000000000000000"):
  233. tray_uuid = None
  234. trays.append({
  235. "id": tray.get("id", 0),
  236. "tray_color": tray.get("tray_color"),
  237. "tray_type": tray.get("tray_type"),
  238. "tray_sub_brands": tray.get("tray_sub_brands"),
  239. "remain": tray.get("remain", 0),
  240. "k": tray.get("k"),
  241. "tag_uid": tag_uid,
  242. "tray_uuid": tray_uuid,
  243. })
  244. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  245. humidity_raw = ams_data.get("humidity_raw")
  246. humidity_idx = ams_data.get("humidity")
  247. humidity_value = None
  248. if humidity_raw is not None:
  249. try:
  250. humidity_value = int(humidity_raw)
  251. except (ValueError, TypeError):
  252. pass
  253. # Fall back to index if no raw value (index is 1-5, not percentage)
  254. if humidity_value is None and humidity_idx is not None:
  255. try:
  256. humidity_value = int(humidity_idx)
  257. except (ValueError, TypeError):
  258. pass
  259. # AMS-HT has 1 tray, regular AMS has 4 trays
  260. is_ams_ht = len(trays) == 1
  261. ams_units.append({
  262. "id": ams_data.get("id", 0),
  263. "humidity": humidity_value,
  264. "temp": ams_data.get("temp"),
  265. "is_ams_ht": is_ams_ht,
  266. "tray": trays,
  267. })
  268. # Parse virtual tray (external spool)
  269. if "vt_tray" in raw_data:
  270. vt_data = raw_data["vt_tray"]
  271. vt_tag_uid = vt_data.get("tag_uid")
  272. if vt_tag_uid in ("", "0000000000000000"):
  273. vt_tag_uid = None
  274. vt_tray = {
  275. "id": 254,
  276. "tray_color": vt_data.get("tray_color"),
  277. "tray_type": vt_data.get("tray_type"),
  278. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  279. "remain": vt_data.get("remain", 0),
  280. "tag_uid": vt_tag_uid,
  281. }
  282. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  283. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  284. result = {
  285. "connected": state.connected,
  286. "state": state.state,
  287. "current_print": state.current_print,
  288. "subtask_name": state.subtask_name,
  289. "gcode_file": state.gcode_file,
  290. "progress": state.progress,
  291. "remaining_time": state.remaining_time,
  292. "layer_num": state.layer_num,
  293. "total_layers": state.total_layers,
  294. "temperatures": state.temperatures,
  295. "hms_errors": [
  296. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  297. for e in (state.hms_errors or [])
  298. ],
  299. # AMS data for filament colors
  300. "ams": ams_units if ams_units else None,
  301. "vt_tray": vt_tray,
  302. # AMS status for filament change tracking
  303. "ams_status_main": state.ams_status_main,
  304. "ams_status_sub": state.ams_status_sub,
  305. "tray_now": state.tray_now,
  306. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  307. "ams_extruder_map": ams_extruder_map,
  308. # WiFi signal strength
  309. "wifi_signal": state.wifi_signal,
  310. }
  311. # Add cover URL if there's an active print and printer_id is provided
  312. if printer_id and state.state == "RUNNING" and state.gcode_file:
  313. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  314. else:
  315. result["cover_url"] = None
  316. return result
  317. # Global printer manager instance
  318. printer_manager = PrinterManager()
  319. async def init_printer_connections(db: AsyncSession):
  320. """Initialize connections to all active printers."""
  321. result = await db.execute(
  322. select(Printer).where(Printer.is_active == True)
  323. )
  324. printers = result.scalars().all()
  325. for printer in printers:
  326. await printer_manager.connect_printer(printer)