printer_manager.py 22 KB

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