printer_manager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import asyncio
  2. from collections.abc import Callable
  3. from sqlalchemy import select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from backend.app.models.printer import Printer
  6. from backend.app.services.bambu_mqtt import BambuMQTTClient, MQTTLogEntry, PrinterState, get_stage_name
  7. class PrinterManager:
  8. """Manager for multiple printer connections."""
  9. def __init__(self):
  10. self._clients: dict[int, BambuMQTTClient] = {}
  11. self._on_print_start: Callable[[int, dict], None] | None = None
  12. self._on_print_complete: Callable[[int, dict], None] | None = None
  13. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  14. self._on_ams_change: Callable[[int, list], None] | None = None
  15. self._loop: asyncio.AbstractEventLoop | None = None
  16. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  17. """Set the event loop for async callbacks."""
  18. self._loop = loop
  19. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  20. """Set callback for print start events."""
  21. self._on_print_start = callback
  22. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  23. """Set callback for print completion events."""
  24. self._on_print_complete = callback
  25. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  26. """Set callback for status change events."""
  27. self._on_status_change = callback
  28. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  29. """Set callback for AMS data change events."""
  30. self._on_ams_change = callback
  31. def _schedule_async(self, coro):
  32. """Schedule an async coroutine from a sync context.
  33. Captures exceptions from the coroutine and logs them to prevent
  34. silent failures in callbacks.
  35. """
  36. if self._loop and self._loop.is_running():
  37. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  38. def handle_exception(f):
  39. try:
  40. # This will re-raise any exception from the coroutine
  41. f.result()
  42. except Exception as e:
  43. import logging
  44. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  45. future.add_done_callback(handle_exception)
  46. async def connect_printer(self, printer: Printer) -> bool:
  47. """Connect to a printer."""
  48. if printer.id in self._clients:
  49. self.disconnect_printer(printer.id)
  50. printer_id = printer.id
  51. def on_state_change(state: PrinterState):
  52. if self._on_status_change:
  53. self._schedule_async(self._on_status_change(printer_id, state))
  54. def on_print_start(data: dict):
  55. if self._on_print_start:
  56. self._schedule_async(self._on_print_start(printer_id, data))
  57. def on_print_complete(data: dict):
  58. if self._on_print_complete:
  59. self._schedule_async(self._on_print_complete(printer_id, data))
  60. def on_ams_change(ams_data: list):
  61. if self._on_ams_change:
  62. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  63. client = BambuMQTTClient(
  64. ip_address=printer.ip_address,
  65. serial_number=printer.serial_number,
  66. access_code=printer.access_code,
  67. on_state_change=on_state_change,
  68. on_print_start=on_print_start,
  69. on_print_complete=on_print_complete,
  70. on_ams_change=on_ams_change,
  71. )
  72. client.connect()
  73. self._clients[printer_id] = client
  74. # Wait a moment for connection
  75. await asyncio.sleep(1)
  76. return client.state.connected
  77. def disconnect_printer(self, printer_id: int):
  78. """Disconnect from a printer."""
  79. if printer_id in self._clients:
  80. self._clients[printer_id].disconnect()
  81. del self._clients[printer_id]
  82. def disconnect_all(self):
  83. """Disconnect from all printers."""
  84. for printer_id in list(self._clients.keys()):
  85. self.disconnect_printer(printer_id)
  86. def get_status(self, printer_id: int) -> PrinterState | None:
  87. """Get the current status of a printer (checks for stale connections)."""
  88. if printer_id in self._clients:
  89. client = self._clients[printer_id]
  90. # Check staleness and update connected state if needed
  91. client.check_staleness()
  92. return client.state
  93. return None
  94. def get_all_statuses(self) -> dict[int, PrinterState]:
  95. """Get status of all connected printers (checks for stale connections)."""
  96. result = {}
  97. for printer_id, client in self._clients.items():
  98. # Check staleness and update connected state if needed
  99. client.check_staleness()
  100. result[printer_id] = client.state
  101. return result
  102. def is_connected(self, printer_id: int) -> bool:
  103. """Check if a printer is connected (checks for stale connections)."""
  104. if printer_id in self._clients:
  105. client = self._clients[printer_id]
  106. # Check staleness and update connected state if needed
  107. return client.check_staleness()
  108. return False
  109. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  110. """Get the MQTT client for a printer."""
  111. return self._clients.get(printer_id)
  112. def mark_printer_offline(self, printer_id: int):
  113. """Mark a printer as offline and trigger status callback.
  114. This is used when we know the printer power was cut (e.g., smart plug turned off)
  115. to immediately update the UI without waiting for MQTT timeout.
  116. """
  117. import logging
  118. logger = logging.getLogger(__name__)
  119. if printer_id in self._clients:
  120. client = self._clients[printer_id]
  121. if client.state.connected:
  122. logger.info(f"Marking printer {printer_id} as offline (smart plug power off)")
  123. client.state.connected = False
  124. client.state.state = "unknown"
  125. # Trigger the status change callback to broadcast via WebSocket
  126. if self._on_status_change:
  127. self._schedule_async(self._on_status_change(printer_id, client.state))
  128. def start_print(
  129. self,
  130. printer_id: int,
  131. filename: str,
  132. plate_id: int = 1,
  133. ams_mapping: list[int] | None = None,
  134. bed_levelling: bool = True,
  135. flow_cali: bool = False,
  136. vibration_cali: bool = True,
  137. layer_inspect: bool = False,
  138. timelapse: bool = False,
  139. use_ams: bool = True,
  140. ) -> bool:
  141. """Start a print on a connected printer."""
  142. if printer_id in self._clients:
  143. return self._clients[printer_id].start_print(
  144. filename,
  145. plate_id,
  146. ams_mapping=ams_mapping,
  147. timelapse=timelapse,
  148. bed_levelling=bed_levelling,
  149. flow_cali=flow_cali,
  150. vibration_cali=vibration_cali,
  151. layer_inspect=layer_inspect,
  152. use_ams=use_ams,
  153. )
  154. return False
  155. def stop_print(self, printer_id: int) -> bool:
  156. """Stop the current print on a connected printer."""
  157. if printer_id in self._clients:
  158. return self._clients[printer_id].stop_print()
  159. return False
  160. async def wait_for_cooldown(
  161. self,
  162. printer_id: int,
  163. target_temp: float = 50.0,
  164. timeout: int = 600,
  165. check_interval: int = 10,
  166. ) -> bool:
  167. """Wait for the nozzle to cool down to a safe temperature.
  168. Args:
  169. printer_id: The printer to monitor
  170. target_temp: Target temperature to wait for (default 50°C)
  171. timeout: Maximum seconds to wait (default 600s = 10 min)
  172. check_interval: Seconds between temperature checks (default 10s)
  173. Returns:
  174. True if cooled down, False if timeout or not connected
  175. """
  176. import logging
  177. logger = logging.getLogger(__name__)
  178. elapsed = 0
  179. while elapsed < timeout:
  180. state = self.get_status(printer_id)
  181. if not state or not state.connected:
  182. logger.warning(f"Printer {printer_id} disconnected during cooldown wait")
  183. return False
  184. # Check nozzle temperature (and nozzle_2 for dual extruders)
  185. nozzle_temp = state.temperatures.get("nozzle", 0)
  186. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  187. max_temp = max(nozzle_temp, nozzle_2_temp)
  188. if max_temp <= target_temp:
  189. logger.info(f"Printer {printer_id} cooled down to {max_temp}°C")
  190. return True
  191. logger.debug(f"Printer {printer_id} nozzle at {max_temp}°C, waiting for {target_temp}°C...")
  192. await asyncio.sleep(check_interval)
  193. elapsed += check_interval
  194. logger.warning(f"Printer {printer_id} cooldown timeout after {timeout}s")
  195. return False
  196. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  197. """Enable or disable MQTT logging for a printer."""
  198. if printer_id in self._clients:
  199. self._clients[printer_id].enable_logging(enabled)
  200. return True
  201. return False
  202. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  203. """Get MQTT logs for a printer."""
  204. if printer_id in self._clients:
  205. return self._clients[printer_id].get_logs()
  206. return []
  207. def clear_logs(self, printer_id: int) -> bool:
  208. """Clear MQTT logs for a printer."""
  209. if printer_id in self._clients:
  210. self._clients[printer_id].clear_logs()
  211. return True
  212. return False
  213. def is_logging_enabled(self, printer_id: int) -> bool:
  214. """Check if logging is enabled for a printer."""
  215. if printer_id in self._clients:
  216. return self._clients[printer_id].logging_enabled
  217. return False
  218. def request_status_update(self, printer_id: int) -> bool:
  219. """Request a full status update from the printer.
  220. This sends a 'pushall' command to get the latest data including nozzle info.
  221. """
  222. if printer_id in self._clients:
  223. return self._clients[printer_id].request_status_update()
  224. return False
  225. async def test_connection(
  226. self,
  227. ip_address: str,
  228. serial_number: str,
  229. access_code: str,
  230. ) -> dict:
  231. """Test connection to a printer without persisting."""
  232. client = BambuMQTTClient(
  233. ip_address=ip_address,
  234. serial_number=serial_number,
  235. access_code=access_code,
  236. )
  237. try:
  238. client.connect()
  239. await asyncio.sleep(2)
  240. result = {
  241. "success": client.state.connected,
  242. "state": client.state.state if client.state.connected else None,
  243. "model": client.state.raw_data.get("device_model"),
  244. }
  245. finally:
  246. client.disconnect()
  247. return result
  248. def get_derived_status_name(state: PrinterState) -> str | None:
  249. """
  250. Compute a human-readable status name based on printer state.
  251. Uses stg_cur when available, otherwise derives status from temperature data
  252. when the printer is heating before a print starts.
  253. """
  254. # If we have a valid calibration stage, use it
  255. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  256. # Valid stage numbers are 0-254
  257. if 0 <= state.stg_cur < 255:
  258. return get_stage_name(state.stg_cur)
  259. # If not in RUNNING state, no derived status needed
  260. if state.state != "RUNNING":
  261. return None
  262. # Check if we're in an early phase where temperatures are heating
  263. temps = state.temperatures or {}
  264. progress = state.progress or 0
  265. # Only derive heating status when progress is very low (< 2%)
  266. # This indicates we're in the preparation phase, not actually printing
  267. if progress >= 2:
  268. return None
  269. # Check bed temperature - if target is set and current is significantly below
  270. bed_temp = temps.get("bed", 0)
  271. bed_target = temps.get("bed_target", 0)
  272. # Check nozzle temperature
  273. nozzle_temp = temps.get("nozzle", 0)
  274. nozzle_target = temps.get("nozzle_target", 0)
  275. # Temperature thresholds: consider "heating" if more than 10°C below target
  276. TEMP_THRESHOLD = 10
  277. # Determine what's heating (prioritize bed since it takes longer)
  278. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  279. return "Heating heatbed"
  280. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  281. return "Heating nozzle"
  282. # If targets are set but we're close to them, we might be in final prep
  283. if bed_target > 30 or nozzle_target > 30:
  284. if progress == 0 and state.layer_num == 0:
  285. return "Preparing"
  286. return None
  287. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None) -> dict:
  288. """Convert PrinterState to a JSON-serializable dict."""
  289. # Parse AMS data from raw_data
  290. ams_units = []
  291. vt_tray = None
  292. raw_data = state.raw_data or {}
  293. # Build K-profile lookup map: cali_idx -> k_value
  294. kprofile_map: dict[int, float] = {}
  295. for kp in state.kprofiles or []:
  296. if kp.slot_id is not None and kp.k_value:
  297. try:
  298. kprofile_map[kp.slot_id] = float(kp.k_value)
  299. except (ValueError, TypeError):
  300. pass
  301. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  302. for ams_data in raw_data["ams"]:
  303. trays = []
  304. for tray in ams_data.get("tray", []):
  305. tag_uid = tray.get("tag_uid")
  306. if tag_uid in ("", "0000000000000000"):
  307. tag_uid = None
  308. tray_uuid = tray.get("tray_uuid")
  309. if tray_uuid in ("", "00000000000000000000000000000000"):
  310. tray_uuid = None
  311. # Get K value: first try tray's k field, then lookup from K-profiles
  312. k_value = tray.get("k")
  313. cali_idx = tray.get("cali_idx")
  314. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  315. k_value = kprofile_map[cali_idx]
  316. trays.append(
  317. {
  318. "id": tray.get("id", 0),
  319. "tray_color": tray.get("tray_color"),
  320. "tray_type": tray.get("tray_type"),
  321. "tray_sub_brands": tray.get("tray_sub_brands"),
  322. "tray_id_name": tray.get("tray_id_name"),
  323. "tray_info_idx": tray.get("tray_info_idx"),
  324. "remain": tray.get("remain", 0),
  325. "k": k_value,
  326. "cali_idx": cali_idx,
  327. "tag_uid": tag_uid,
  328. "tray_uuid": tray_uuid,
  329. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  330. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  331. }
  332. )
  333. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  334. humidity_raw = ams_data.get("humidity_raw")
  335. humidity_idx = ams_data.get("humidity")
  336. humidity_value = None
  337. if humidity_raw is not None:
  338. try:
  339. humidity_value = int(humidity_raw)
  340. except (ValueError, TypeError):
  341. pass
  342. # Fall back to index if no raw value (index is 1-5, not percentage)
  343. if humidity_value is None and humidity_idx is not None:
  344. try:
  345. humidity_value = int(humidity_idx)
  346. except (ValueError, TypeError):
  347. pass
  348. # AMS-HT has 1 tray, regular AMS has 4 trays
  349. is_ams_ht = len(trays) == 1
  350. ams_units.append(
  351. {
  352. "id": ams_data.get("id", 0),
  353. "humidity": humidity_value,
  354. "temp": ams_data.get("temp"),
  355. "is_ams_ht": is_ams_ht,
  356. "tray": trays,
  357. }
  358. )
  359. # Parse virtual tray (external spool)
  360. if "vt_tray" in raw_data:
  361. vt_data = raw_data["vt_tray"]
  362. vt_tag_uid = vt_data.get("tag_uid")
  363. if vt_tag_uid in ("", "0000000000000000"):
  364. vt_tag_uid = None
  365. vt_tray_uuid = vt_data.get("tray_uuid")
  366. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  367. vt_tray_uuid = None
  368. # Get K value for vt_tray
  369. vt_k_value = vt_data.get("k")
  370. vt_cali_idx = vt_data.get("cali_idx")
  371. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  372. vt_k_value = kprofile_map[vt_cali_idx]
  373. vt_tray = {
  374. "id": 254,
  375. "tray_color": vt_data.get("tray_color"),
  376. "tray_type": vt_data.get("tray_type"),
  377. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  378. "tray_id_name": vt_data.get("tray_id_name"),
  379. "tray_info_idx": vt_data.get("tray_info_idx"),
  380. "remain": vt_data.get("remain", 0),
  381. "k": vt_k_value,
  382. "cali_idx": vt_cali_idx,
  383. "tag_uid": vt_tag_uid,
  384. "tray_uuid": vt_tray_uuid,
  385. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  386. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  387. }
  388. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  389. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  390. result = {
  391. "connected": state.connected,
  392. "state": state.state,
  393. "current_print": state.current_print,
  394. "subtask_name": state.subtask_name,
  395. "gcode_file": state.gcode_file,
  396. "progress": state.progress,
  397. "remaining_time": state.remaining_time,
  398. "layer_num": state.layer_num,
  399. "total_layers": state.total_layers,
  400. "temperatures": state.temperatures,
  401. "hms_errors": [
  402. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  403. for e in (state.hms_errors or [])
  404. ],
  405. # AMS data for filament colors
  406. "ams": ams_units if ams_units else None,
  407. "vt_tray": vt_tray,
  408. # AMS status for filament change tracking
  409. "ams_status_main": state.ams_status_main,
  410. "ams_status_sub": state.ams_status_sub,
  411. "tray_now": state.tray_now,
  412. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  413. "ams_extruder_map": ams_extruder_map,
  414. # WiFi signal strength
  415. "wifi_signal": state.wifi_signal,
  416. # Calibration stage tracking
  417. "stg_cur": state.stg_cur,
  418. "stg_cur_name": get_derived_status_name(state),
  419. # Printable objects count for skip objects feature
  420. "printable_objects_count": len(state.printable_objects),
  421. # Fan speeds (0-100 percentage, None if not available)
  422. "cooling_fan_speed": state.cooling_fan_speed,
  423. "big_fan1_speed": state.big_fan1_speed,
  424. "big_fan2_speed": state.big_fan2_speed,
  425. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  426. # Chamber light state
  427. "chamber_light": state.chamber_light,
  428. }
  429. # Add cover URL if there's an active print and printer_id is provided
  430. # Include PAUSE/PAUSED states so skip objects modal can show cover
  431. if printer_id and state.state in ("RUNNING", "PAUSE", "PAUSED") and state.gcode_file:
  432. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  433. else:
  434. result["cover_url"] = None
  435. return result
  436. # Global printer manager instance
  437. printer_manager = PrinterManager()
  438. async def init_printer_connections(db: AsyncSession):
  439. """Initialize connections to all active printers."""
  440. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  441. printers = result.scalars().all()
  442. for printer in printers:
  443. await printer_manager.connect_printer(printer)