printer_manager.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. Captures exceptions from the coroutine and logs them to prevent
  36. silent failures in callbacks.
  37. """
  38. if self._loop and self._loop.is_running():
  39. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  40. def handle_exception(f):
  41. try:
  42. # This will re-raise any exception from the coroutine
  43. f.result()
  44. except Exception as e:
  45. import logging
  46. logging.getLogger(__name__).error(
  47. f"Exception in scheduled callback: {e}", exc_info=True
  48. )
  49. future.add_done_callback(handle_exception)
  50. async def connect_printer(self, printer: Printer) -> bool:
  51. """Connect to a printer."""
  52. if printer.id in self._clients:
  53. self.disconnect_printer(printer.id)
  54. printer_id = printer.id
  55. def on_state_change(state: PrinterState):
  56. if self._on_status_change:
  57. self._schedule_async(
  58. self._on_status_change(printer_id, state)
  59. )
  60. def on_print_start(data: dict):
  61. if self._on_print_start:
  62. self._schedule_async(
  63. self._on_print_start(printer_id, data)
  64. )
  65. def on_print_complete(data: dict):
  66. if self._on_print_complete:
  67. self._schedule_async(
  68. self._on_print_complete(printer_id, data)
  69. )
  70. def on_ams_change(ams_data: list):
  71. if self._on_ams_change:
  72. self._schedule_async(
  73. self._on_ams_change(printer_id, ams_data)
  74. )
  75. client = BambuMQTTClient(
  76. ip_address=printer.ip_address,
  77. serial_number=printer.serial_number,
  78. access_code=printer.access_code,
  79. on_state_change=on_state_change,
  80. on_print_start=on_print_start,
  81. on_print_complete=on_print_complete,
  82. on_ams_change=on_ams_change,
  83. )
  84. client.connect()
  85. self._clients[printer_id] = client
  86. # Wait a moment for connection
  87. await asyncio.sleep(1)
  88. return client.state.connected
  89. def disconnect_printer(self, printer_id: int):
  90. """Disconnect from a printer."""
  91. if printer_id in self._clients:
  92. self._clients[printer_id].disconnect()
  93. del self._clients[printer_id]
  94. def disconnect_all(self):
  95. """Disconnect from all printers."""
  96. for printer_id in list(self._clients.keys()):
  97. self.disconnect_printer(printer_id)
  98. def get_status(self, printer_id: int) -> PrinterState | None:
  99. """Get the current status of a printer (checks for stale connections)."""
  100. if printer_id in self._clients:
  101. client = self._clients[printer_id]
  102. # Check staleness and update connected state if needed
  103. client.check_staleness()
  104. return client.state
  105. return None
  106. def get_all_statuses(self) -> dict[int, PrinterState]:
  107. """Get status of all connected printers (checks for stale connections)."""
  108. result = {}
  109. for printer_id, client in self._clients.items():
  110. # Check staleness and update connected state if needed
  111. client.check_staleness()
  112. result[printer_id] = client.state
  113. return result
  114. def is_connected(self, printer_id: int) -> bool:
  115. """Check if a printer is connected (checks for stale connections)."""
  116. if printer_id in self._clients:
  117. client = self._clients[printer_id]
  118. # Check staleness and update connected state if needed
  119. return client.check_staleness()
  120. return False
  121. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  122. """Get the MQTT client for a printer."""
  123. return self._clients.get(printer_id)
  124. def mark_printer_offline(self, printer_id: int):
  125. """Mark a printer as offline and trigger status callback.
  126. This is used when we know the printer power was cut (e.g., smart plug turned off)
  127. to immediately update the UI without waiting for MQTT timeout.
  128. """
  129. import logging
  130. logger = logging.getLogger(__name__)
  131. if printer_id in self._clients:
  132. client = self._clients[printer_id]
  133. if client.state.connected:
  134. logger.info(f"Marking printer {printer_id} as offline (smart plug power off)")
  135. client.state.connected = False
  136. client.state.state = "unknown"
  137. # Trigger the status change callback to broadcast via WebSocket
  138. if self._on_status_change:
  139. self._schedule_async(self._on_status_change(printer_id, client.state))
  140. def start_print(self, printer_id: int, filename: str) -> bool:
  141. """Start a print on a connected printer."""
  142. if printer_id in self._clients:
  143. return self._clients[printer_id].start_print(filename)
  144. return False
  145. def stop_print(self, printer_id: int) -> bool:
  146. """Stop the current print on a connected printer."""
  147. if printer_id in self._clients:
  148. return self._clients[printer_id].stop_print()
  149. return False
  150. async def wait_for_cooldown(
  151. self,
  152. printer_id: int,
  153. target_temp: float = 50.0,
  154. timeout: int = 600,
  155. check_interval: int = 10,
  156. ) -> bool:
  157. """Wait for the nozzle to cool down to a safe temperature.
  158. Args:
  159. printer_id: The printer to monitor
  160. target_temp: Target temperature to wait for (default 50°C)
  161. timeout: Maximum seconds to wait (default 600s = 10 min)
  162. check_interval: Seconds between temperature checks (default 10s)
  163. Returns:
  164. True if cooled down, False if timeout or not connected
  165. """
  166. import logging
  167. logger = logging.getLogger(__name__)
  168. elapsed = 0
  169. while elapsed < timeout:
  170. state = self.get_status(printer_id)
  171. if not state or not state.connected:
  172. logger.warning(f"Printer {printer_id} disconnected during cooldown wait")
  173. return False
  174. # Check nozzle temperature (and nozzle_2 for dual extruders)
  175. nozzle_temp = state.temperatures.get("nozzle", 0)
  176. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  177. max_temp = max(nozzle_temp, nozzle_2_temp)
  178. if max_temp <= target_temp:
  179. logger.info(f"Printer {printer_id} cooled down to {max_temp}°C")
  180. return True
  181. logger.debug(f"Printer {printer_id} nozzle at {max_temp}°C, waiting for {target_temp}°C...")
  182. await asyncio.sleep(check_interval)
  183. elapsed += check_interval
  184. logger.warning(f"Printer {printer_id} cooldown timeout after {timeout}s")
  185. return False
  186. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  187. """Enable or disable MQTT logging for a printer."""
  188. if printer_id in self._clients:
  189. self._clients[printer_id].enable_logging(enabled)
  190. return True
  191. return False
  192. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  193. """Get MQTT logs for a printer."""
  194. if printer_id in self._clients:
  195. return self._clients[printer_id].get_logs()
  196. return []
  197. def clear_logs(self, printer_id: int) -> bool:
  198. """Clear MQTT logs for a printer."""
  199. if printer_id in self._clients:
  200. self._clients[printer_id].clear_logs()
  201. return True
  202. return False
  203. def is_logging_enabled(self, printer_id: int) -> bool:
  204. """Check if logging is enabled for a printer."""
  205. if printer_id in self._clients:
  206. return self._clients[printer_id].logging_enabled
  207. return False
  208. def request_status_update(self, printer_id: int) -> bool:
  209. """Request a full status update from the printer.
  210. This sends a 'pushall' command to get the latest data including nozzle info.
  211. """
  212. if printer_id in self._clients:
  213. return self._clients[printer_id].request_status_update()
  214. return False
  215. async def test_connection(
  216. self,
  217. ip_address: str,
  218. serial_number: str,
  219. access_code: str,
  220. ) -> dict:
  221. """Test connection to a printer without persisting."""
  222. client = BambuMQTTClient(
  223. ip_address=ip_address,
  224. serial_number=serial_number,
  225. access_code=access_code,
  226. )
  227. try:
  228. client.connect()
  229. await asyncio.sleep(2)
  230. result = {
  231. "success": client.state.connected,
  232. "state": client.state.state if client.state.connected else None,
  233. "model": client.state.raw_data.get("device_model"),
  234. }
  235. finally:
  236. client.disconnect()
  237. return result
  238. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None) -> dict:
  239. """Convert PrinterState to a JSON-serializable dict."""
  240. # Parse AMS data from raw_data
  241. ams_units = []
  242. vt_tray = None
  243. raw_data = state.raw_data or {}
  244. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  245. for ams_data in raw_data["ams"]:
  246. trays = []
  247. for tray in ams_data.get("tray", []):
  248. tag_uid = tray.get("tag_uid")
  249. if tag_uid in ("", "0000000000000000"):
  250. tag_uid = None
  251. tray_uuid = tray.get("tray_uuid")
  252. if tray_uuid in ("", "00000000000000000000000000000000"):
  253. tray_uuid = None
  254. trays.append({
  255. "id": tray.get("id", 0),
  256. "tray_color": tray.get("tray_color"),
  257. "tray_type": tray.get("tray_type"),
  258. "tray_sub_brands": tray.get("tray_sub_brands"),
  259. "remain": tray.get("remain", 0),
  260. "k": tray.get("k"),
  261. "tag_uid": tag_uid,
  262. "tray_uuid": tray_uuid,
  263. })
  264. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  265. humidity_raw = ams_data.get("humidity_raw")
  266. humidity_idx = ams_data.get("humidity")
  267. humidity_value = None
  268. if humidity_raw is not None:
  269. try:
  270. humidity_value = int(humidity_raw)
  271. except (ValueError, TypeError):
  272. pass
  273. # Fall back to index if no raw value (index is 1-5, not percentage)
  274. if humidity_value is None and humidity_idx is not None:
  275. try:
  276. humidity_value = int(humidity_idx)
  277. except (ValueError, TypeError):
  278. pass
  279. # AMS-HT has 1 tray, regular AMS has 4 trays
  280. is_ams_ht = len(trays) == 1
  281. ams_units.append({
  282. "id": ams_data.get("id", 0),
  283. "humidity": humidity_value,
  284. "temp": ams_data.get("temp"),
  285. "is_ams_ht": is_ams_ht,
  286. "tray": trays,
  287. })
  288. # Parse virtual tray (external spool)
  289. if "vt_tray" in raw_data:
  290. vt_data = raw_data["vt_tray"]
  291. vt_tag_uid = vt_data.get("tag_uid")
  292. if vt_tag_uid in ("", "0000000000000000"):
  293. vt_tag_uid = None
  294. vt_tray = {
  295. "id": 254,
  296. "tray_color": vt_data.get("tray_color"),
  297. "tray_type": vt_data.get("tray_type"),
  298. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  299. "remain": vt_data.get("remain", 0),
  300. "tag_uid": vt_tag_uid,
  301. }
  302. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  303. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  304. result = {
  305. "connected": state.connected,
  306. "state": state.state,
  307. "current_print": state.current_print,
  308. "subtask_name": state.subtask_name,
  309. "gcode_file": state.gcode_file,
  310. "progress": state.progress,
  311. "remaining_time": state.remaining_time,
  312. "layer_num": state.layer_num,
  313. "total_layers": state.total_layers,
  314. "temperatures": state.temperatures,
  315. "hms_errors": [
  316. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  317. for e in (state.hms_errors or [])
  318. ],
  319. # AMS data for filament colors
  320. "ams": ams_units if ams_units else None,
  321. "vt_tray": vt_tray,
  322. # AMS status for filament change tracking
  323. "ams_status_main": state.ams_status_main,
  324. "ams_status_sub": state.ams_status_sub,
  325. "tray_now": state.tray_now,
  326. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  327. "ams_extruder_map": ams_extruder_map,
  328. # WiFi signal strength
  329. "wifi_signal": state.wifi_signal,
  330. }
  331. # Add cover URL if there's an active print and printer_id is provided
  332. if printer_id and state.state == "RUNNING" and state.gcode_file:
  333. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  334. else:
  335. result["cover_url"] = None
  336. return result
  337. # Global printer manager instance
  338. printer_manager = PrinterManager()
  339. async def init_printer_connections(db: AsyncSession):
  340. """Initialize connections to all active printers."""
  341. result = await db.execute(
  342. select(Printer).where(Printer.is_active == True)
  343. )
  344. printers = result.scalars().all()
  345. for printer in printers:
  346. await printer_manager.connect_printer(printer)