printer_manager.py 23 KB

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