printer_manager.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. import asyncio
  2. import logging
  3. import traceback
  4. from collections.abc import Callable
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.models.printer import Printer
  8. from backend.app.services.bambu_mqtt import BambuMQTTClient, MQTTLogEntry, PrinterState, get_stage_name
  9. logger = logging.getLogger(__name__)
  10. # Models that have a real chamber temperature sensor
  11. # Based on Home Assistant Bambu Lab integration
  12. # P1P/P1S and A1/A1Mini do NOT have chamber temp sensors
  13. # Includes both display names and internal codes from MQTT/SSDP
  14. CHAMBER_TEMP_SUPPORTED_MODELS = frozenset(
  15. [
  16. # Display names
  17. "X1",
  18. "X1C",
  19. "X1E", # X1 series
  20. "P2S", # P2 series
  21. "H2C",
  22. "H2D",
  23. "H2DPRO",
  24. "H2S", # H2 series
  25. # Internal codes (from MQTT/SSDP)
  26. "BL-P001", # X1/X1C
  27. "C13", # X1E
  28. "O1D", # H2D
  29. "O1C", # H2C
  30. "O1C2", # H2C (dual nozzle variant)
  31. "O1S", # H2S
  32. "O1E", # H2D Pro
  33. "O2D", # H2D Pro (alternate code)
  34. "N7", # P2S
  35. ]
  36. )
  37. # Models that may incorrectly report stg_cur=0 when idle (firmware bug)
  38. # Based on Home Assistant Bambu Lab integration observations
  39. # See: https://github.com/greghesp/ha-bambulab/blob/main/custom_components/bambu_lab/pybambu/models.py
  40. A1_MODELS = frozenset(
  41. [
  42. # Display names
  43. "A1",
  44. "A1 MINI",
  45. "A1-MINI",
  46. "A1MINI",
  47. # Internal codes (from MQTT/SSDP)
  48. "N1", # A1 Mini
  49. "N2S", # A1
  50. ]
  51. )
  52. def supports_chamber_temp(model: str | None) -> bool:
  53. """Check if a printer model has a real chamber temperature sensor.
  54. P1P, P1S, A1, and A1Mini do NOT have chamber temp sensors.
  55. The 'chamber_temper' value they report is meaningless.
  56. """
  57. if not model:
  58. return False
  59. # Normalize model name (uppercase, strip whitespace)
  60. model_upper = model.strip().upper()
  61. return model_upper in CHAMBER_TEMP_SUPPORTED_MODELS
  62. def has_stg_cur_idle_bug(model: str | None) -> bool:
  63. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  64. Some A1/A1 Mini firmware versions report stg_cur=0 (which maps to "Printing")
  65. even when the printer is idle. This is a known firmware bug that was observed
  66. in the Home Assistant Bambu Lab integration.
  67. """
  68. if not model:
  69. return False
  70. model_upper = model.strip().upper()
  71. return model_upper in A1_MODELS
  72. # Minimum firmware versions for AMS drying support (confirmed via capture testing)
  73. # Keys are exact model names (upper-cased). Do NOT use substring matching — it would
  74. # incorrectly gate X1E (matched by "X1") and H2D Pro (matched by "H2D").
  75. _DRYING_MIN_FIRMWARE: dict[str, str] = {
  76. "H2D": "01.02.30.00",
  77. "X1": "01.09.00.00",
  78. "X1C": "01.09.00.00",
  79. "P1P": "01.08.00.00",
  80. "P1S": "01.08.00.00",
  81. }
  82. # Models that definitely don't support AMS drying (no AMS 2 Pro / AMS-HT compatibility)
  83. _DRYING_UNSUPPORTED_MODELS = frozenset(
  84. {"P2S", "A1", "A1MINI", "A1-MINI", "A1 MINI", "H2S", "H2C", "N7", "O1C", "O1C2", "O1S", "N1", "N2S"}
  85. )
  86. def supports_drying(model: str | None, firmware: str | None) -> bool:
  87. """Check if a printer model supports AMS drying commands.
  88. Known models with confirmed min firmware get version-gated.
  89. Known unsupported models are blocked.
  90. All other models (H2D Pro, X1E, future models) are allowed —
  91. the command fails gracefully with result: "fail" if unsupported.
  92. """
  93. if not model:
  94. return False
  95. model_upper = model.strip().upper()
  96. if model_upper in _DRYING_UNSUPPORTED_MODELS:
  97. return False
  98. if model_upper in _DRYING_MIN_FIRMWARE:
  99. return bool(firmware and firmware >= _DRYING_MIN_FIRMWARE[model_upper])
  100. # For all other models: allow
  101. return True
  102. class PrinterInfo:
  103. """Basic printer info for callbacks."""
  104. def __init__(self, name: str, serial_number: str):
  105. self.name = name
  106. self.serial_number = serial_number
  107. class PrinterManager:
  108. """Manager for multiple printer connections."""
  109. def __init__(self):
  110. self._clients: dict[int, BambuMQTTClient] = {}
  111. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  112. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  113. self._on_print_start: Callable[[int, dict], None] | None = None
  114. self._on_print_complete: Callable[[int, dict], None] | None = None
  115. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  116. self._on_ams_change: Callable[[int, list], None] | None = None
  117. self._on_layer_change: Callable[[int, int], None] | None = None
  118. self._loop: asyncio.AbstractEventLoop | None = None
  119. # Track who started the current print (Issue #206)
  120. self._current_print_user: dict[int, dict] = {} # {printer_id: {"user_id": int, "username": str}}
  121. # Track plate-cleared acknowledgments for queue flow
  122. self._plate_cleared: set[int] = set() # printer_ids where user confirmed plate is cleared
  123. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  124. """Get printer info by ID."""
  125. return self._printer_info.get(printer_id)
  126. def set_current_print_user(self, printer_id: int, user_id: int, username: str):
  127. """Track who started the current print (Issue #206)."""
  128. self._current_print_user[printer_id] = {"user_id": user_id, "username": username}
  129. def get_current_print_user(self, printer_id: int) -> dict | None:
  130. """Get the user who started the current print (Issue #206)."""
  131. return self._current_print_user.get(printer_id)
  132. def clear_current_print_user(self, printer_id: int):
  133. """Clear the current print user when print completes (Issue #206)."""
  134. self._current_print_user.pop(printer_id, None)
  135. def set_plate_cleared(self, printer_id: int):
  136. """Mark that user has cleared the build plate for this printer."""
  137. self._plate_cleared.add(printer_id)
  138. def is_plate_cleared(self, printer_id: int) -> bool:
  139. """Check if user has confirmed the plate is cleared."""
  140. return printer_id in self._plate_cleared
  141. def consume_plate_cleared(self, printer_id: int):
  142. """Clear the plate-cleared flag (called when scheduler starts next print)."""
  143. self._plate_cleared.discard(printer_id)
  144. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  145. """Set the event loop for async callbacks."""
  146. self._loop = loop
  147. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  148. """Set callback for print start events."""
  149. self._on_print_start = callback
  150. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  151. """Set callback for print completion events."""
  152. self._on_print_complete = callback
  153. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  154. """Set callback for status change events."""
  155. self._on_status_change = callback
  156. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  157. """Set callback for AMS data change events."""
  158. self._on_ams_change = callback
  159. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  160. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  161. self._on_layer_change = callback
  162. def _schedule_async(self, coro):
  163. """Schedule an async coroutine from a sync context.
  164. Captures exceptions from the coroutine and logs them to prevent
  165. silent failures in callbacks.
  166. """
  167. if self._loop and self._loop.is_running():
  168. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  169. def handle_exception(f):
  170. try:
  171. # This will re-raise any exception from the coroutine
  172. f.result()
  173. except Exception as e:
  174. import logging
  175. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  176. future.add_done_callback(handle_exception)
  177. async def connect_printer(self, printer: Printer) -> bool:
  178. """Connect to a printer."""
  179. if printer.id in self._clients:
  180. self.disconnect_printer(printer.id)
  181. printer_id = printer.id
  182. def on_state_change(state: PrinterState):
  183. if self._on_status_change:
  184. self._schedule_async(self._on_status_change(printer_id, state))
  185. def on_print_start(data: dict):
  186. if self._on_print_start:
  187. self._schedule_async(self._on_print_start(printer_id, data))
  188. def on_print_complete(data: dict):
  189. if self._on_print_complete:
  190. self._schedule_async(self._on_print_complete(printer_id, data))
  191. def on_ams_change(ams_data: list):
  192. if self._on_ams_change:
  193. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  194. def on_layer_change(layer_num: int):
  195. if self._on_layer_change:
  196. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  197. client = BambuMQTTClient(
  198. ip_address=printer.ip_address,
  199. serial_number=printer.serial_number,
  200. access_code=printer.access_code,
  201. model=printer.model,
  202. on_state_change=on_state_change,
  203. on_print_start=on_print_start,
  204. on_print_complete=on_print_complete,
  205. on_ams_change=on_ams_change,
  206. on_layer_change=on_layer_change,
  207. )
  208. client.connect()
  209. self._clients[printer_id] = client
  210. self._models[printer_id] = printer.model # Cache model for feature detection
  211. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  212. # Wait a moment for connection
  213. await asyncio.sleep(1)
  214. return client.state.connected
  215. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  216. """Disconnect from a printer."""
  217. if printer_id in self._clients:
  218. self._clients[printer_id].disconnect(timeout=timeout)
  219. del self._clients[printer_id]
  220. self._models.pop(printer_id, None) # Clean up model cache
  221. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  222. def disconnect_all(self, timeout: float = 0):
  223. """Disconnect from all printers."""
  224. for printer_id in list(self._clients.keys()):
  225. self.disconnect_printer(printer_id, timeout=timeout)
  226. def get_status(self, printer_id: int) -> PrinterState | None:
  227. """Get the current status of a printer (checks for stale connections)."""
  228. if printer_id in self._clients:
  229. client = self._clients[printer_id]
  230. # Check staleness and update connected state if needed
  231. client.check_staleness()
  232. return client.state
  233. return None
  234. def get_model(self, printer_id: int) -> str | None:
  235. """Get the cached model for a printer."""
  236. return self._models.get(printer_id)
  237. def get_all_statuses(self) -> dict[int, PrinterState]:
  238. """Get status of all connected printers (checks for stale connections)."""
  239. result = {}
  240. for printer_id, client in self._clients.items():
  241. # Check staleness and update connected state if needed
  242. client.check_staleness()
  243. result[printer_id] = client.state
  244. return result
  245. def is_connected(self, printer_id: int) -> bool:
  246. """Check if a printer is connected (checks for stale connections)."""
  247. if printer_id in self._clients:
  248. client = self._clients[printer_id]
  249. # Check staleness and update connected state if needed
  250. return client.check_staleness()
  251. return False
  252. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  253. """Get the MQTT client for a printer."""
  254. return self._clients.get(printer_id)
  255. def mark_printer_offline(self, printer_id: int):
  256. """Mark a printer as offline and trigger status callback.
  257. This is used when we know the printer power was cut (e.g., smart plug turned off)
  258. to immediately update the UI without waiting for MQTT timeout.
  259. """
  260. import logging
  261. logger = logging.getLogger(__name__)
  262. if printer_id in self._clients:
  263. client = self._clients[printer_id]
  264. if client.state.connected:
  265. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  266. client.state.connected = False
  267. client.state.state = "unknown"
  268. # Trigger the status change callback to broadcast via WebSocket
  269. if self._on_status_change:
  270. self._schedule_async(self._on_status_change(printer_id, client.state))
  271. def start_print(
  272. self,
  273. printer_id: int,
  274. filename: str,
  275. plate_id: int = 1,
  276. ams_mapping: list[int] | None = None,
  277. bed_levelling: bool = True,
  278. flow_cali: bool = False,
  279. vibration_cali: bool = True,
  280. layer_inspect: bool = False,
  281. timelapse: bool = False,
  282. use_ams: bool = True,
  283. ) -> bool:
  284. """Start a print on a connected printer."""
  285. caller = traceback.extract_stack(limit=3)[0]
  286. logger.info(
  287. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  288. printer_id,
  289. filename,
  290. caller.filename.split("/")[-1],
  291. caller.lineno,
  292. caller.name,
  293. )
  294. if printer_id in self._clients:
  295. return self._clients[printer_id].start_print(
  296. filename,
  297. plate_id,
  298. ams_mapping=ams_mapping,
  299. timelapse=timelapse,
  300. bed_levelling=bed_levelling,
  301. flow_cali=flow_cali,
  302. vibration_cali=vibration_cali,
  303. layer_inspect=layer_inspect,
  304. use_ams=use_ams,
  305. )
  306. return False
  307. def stop_print(self, printer_id: int) -> bool:
  308. """Stop the current print on a connected printer."""
  309. if printer_id in self._clients:
  310. return self._clients[printer_id].stop_print()
  311. return False
  312. async def wait_for_cooldown(
  313. self,
  314. printer_id: int,
  315. target_temp: float = 50.0,
  316. timeout: int = 600,
  317. check_interval: int = 10,
  318. ) -> bool:
  319. """Wait for the nozzle to cool down to a safe temperature.
  320. Args:
  321. printer_id: The printer to monitor
  322. target_temp: Target temperature to wait for (default 50°C)
  323. timeout: Maximum seconds to wait (default 600s = 10 min)
  324. check_interval: Seconds between temperature checks (default 10s)
  325. Returns:
  326. True if cooled down, False if timeout or not connected
  327. """
  328. import logging
  329. logger = logging.getLogger(__name__)
  330. elapsed = 0
  331. while elapsed < timeout:
  332. state = self.get_status(printer_id)
  333. if not state or not state.connected:
  334. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  335. return False
  336. # Check nozzle temperature (and nozzle_2 for dual extruders)
  337. nozzle_temp = state.temperatures.get("nozzle", 0)
  338. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  339. max_temp = max(nozzle_temp, nozzle_2_temp)
  340. if max_temp <= target_temp:
  341. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  342. return True
  343. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  344. await asyncio.sleep(check_interval)
  345. elapsed += check_interval
  346. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  347. return False
  348. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  349. """Enable or disable MQTT logging for a printer."""
  350. if printer_id in self._clients:
  351. self._clients[printer_id].enable_logging(enabled)
  352. return True
  353. return False
  354. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  355. """Get MQTT logs for a printer."""
  356. if printer_id in self._clients:
  357. return self._clients[printer_id].get_logs()
  358. return []
  359. def clear_logs(self, printer_id: int) -> bool:
  360. """Clear MQTT logs for a printer."""
  361. if printer_id in self._clients:
  362. self._clients[printer_id].clear_logs()
  363. return True
  364. return False
  365. def is_logging_enabled(self, printer_id: int) -> bool:
  366. """Check if logging is enabled for a printer."""
  367. if printer_id in self._clients:
  368. return self._clients[printer_id].logging_enabled
  369. return False
  370. def send_drying_command(
  371. self,
  372. printer_id: int,
  373. ams_id: int,
  374. temp: int,
  375. duration: int,
  376. mode: int = 1,
  377. filament: str = "",
  378. rotate_tray: bool = False,
  379. ) -> bool:
  380. """Send AMS drying command to printer."""
  381. if printer_id not in self._clients:
  382. return False
  383. return self._clients[printer_id].send_drying_command(ams_id, temp, duration, mode, filament, rotate_tray)
  384. def request_status_update(self, printer_id: int) -> bool:
  385. """Request a full status update from the printer.
  386. This sends a 'pushall' command to get the latest data including nozzle info.
  387. """
  388. if printer_id in self._clients:
  389. return self._clients[printer_id].request_status_update()
  390. return False
  391. async def test_connection(
  392. self,
  393. ip_address: str,
  394. serial_number: str,
  395. access_code: str,
  396. ) -> dict:
  397. """Test connection to a printer without persisting."""
  398. client = BambuMQTTClient(
  399. ip_address=ip_address,
  400. serial_number=serial_number,
  401. access_code=access_code,
  402. )
  403. try:
  404. client.connect()
  405. await asyncio.sleep(2)
  406. result = {
  407. "success": client.state.connected,
  408. "state": client.state.state if client.state.connected else None,
  409. "model": client.state.raw_data.get("device_model"),
  410. }
  411. finally:
  412. client.disconnect()
  413. return result
  414. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  415. """
  416. Compute a human-readable status name based on printer state.
  417. Uses stg_cur when available, otherwise derives status from temperature data
  418. when the printer is heating before a print starts.
  419. Args:
  420. state: The printer state to analyze
  421. model: Optional printer model for model-specific workarounds
  422. """
  423. # A1/A1 Mini firmware bug: some versions report stg_cur=0 when idle
  424. # Only correct this specific case (IDLE + stg_cur=0) for affected models
  425. if state.state == "IDLE" and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  426. return None
  427. # If we have a valid calibration stage, use it
  428. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  429. # Valid stage numbers are 0-254
  430. if 0 <= state.stg_cur < 255:
  431. return get_stage_name(state.stg_cur)
  432. # If not in RUNNING state, no derived status needed
  433. if state.state != "RUNNING":
  434. return None
  435. # Check if we're in an early phase where temperatures are heating
  436. temps = state.temperatures or {}
  437. progress = state.progress or 0
  438. # Only derive heating status when progress is very low (< 2%)
  439. # This indicates we're in the preparation phase, not actually printing
  440. if progress >= 2:
  441. return None
  442. # Check bed temperature - if target is set and current is significantly below
  443. bed_temp = temps.get("bed", 0)
  444. bed_target = temps.get("bed_target", 0)
  445. # Check nozzle temperature
  446. nozzle_temp = temps.get("nozzle", 0)
  447. nozzle_target = temps.get("nozzle_target", 0)
  448. # Temperature thresholds: consider "heating" if more than 10°C below target
  449. TEMP_THRESHOLD = 10
  450. # Determine what's heating (prioritize bed since it takes longer)
  451. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  452. return "Heating heatbed"
  453. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  454. return "Heating nozzle"
  455. # If targets are set but we're close to them, we might be in final prep
  456. if bed_target > 30 or nozzle_target > 30:
  457. if progress == 0 and state.layer_num == 0:
  458. return "Preparing"
  459. return None
  460. def printer_state_to_dict(state: PrinterState, printer_id: int | None = None, model: str | None = None) -> dict:
  461. """Convert PrinterState to a JSON-serializable dict.
  462. Args:
  463. state: The printer state to convert
  464. printer_id: Optional printer ID for generating cover URLs
  465. model: Optional printer model for filtering unsupported features
  466. """
  467. # Parse AMS data from raw_data
  468. ams_units = []
  469. vt_tray = []
  470. raw_data = state.raw_data or {}
  471. # Build K-profile lookup map: cali_idx -> k_value
  472. kprofile_map: dict[int, float] = {}
  473. for kp in state.kprofiles or []:
  474. if kp.slot_id is not None and kp.k_value:
  475. try:
  476. kprofile_map[kp.slot_id] = float(kp.k_value)
  477. except (ValueError, TypeError):
  478. pass # Skip K-profile entries with unparseable values
  479. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  480. for ams_data in raw_data["ams"]:
  481. trays = []
  482. for tray in ams_data.get("tray", []):
  483. tag_uid = tray.get("tag_uid")
  484. if tag_uid in ("", "0000000000000000"):
  485. tag_uid = None
  486. tray_uuid = tray.get("tray_uuid")
  487. if tray_uuid in ("", "00000000000000000000000000000000"):
  488. tray_uuid = None
  489. # Get K value: first try tray's k field, then lookup from K-profiles
  490. k_value = tray.get("k")
  491. cali_idx = tray.get("cali_idx")
  492. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  493. k_value = kprofile_map[cali_idx]
  494. trays.append(
  495. {
  496. "id": int(tray.get("id", 0)),
  497. "tray_color": tray.get("tray_color"),
  498. "tray_type": tray.get("tray_type"),
  499. "tray_sub_brands": tray.get("tray_sub_brands"),
  500. "tray_id_name": tray.get("tray_id_name"),
  501. "tray_info_idx": tray.get("tray_info_idx"),
  502. "remain": tray.get("remain", 0),
  503. "k": k_value,
  504. "cali_idx": cali_idx,
  505. "tag_uid": tag_uid,
  506. "tray_uuid": tray_uuid,
  507. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  508. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  509. "drying_temp": tray.get("drying_temp"),
  510. "drying_time": tray.get("drying_time"),
  511. "state": tray.get("state"),
  512. }
  513. )
  514. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  515. humidity_raw = ams_data.get("humidity_raw")
  516. humidity_idx = ams_data.get("humidity")
  517. humidity_value = None
  518. if humidity_raw is not None:
  519. try:
  520. humidity_value = int(humidity_raw)
  521. except (ValueError, TypeError):
  522. pass # Skip unparseable humidity; will try index fallback
  523. # Fall back to index if no raw value (index is 1-5, not percentage)
  524. if humidity_value is None and humidity_idx is not None:
  525. try:
  526. humidity_value = int(humidity_idx)
  527. except (ValueError, TypeError):
  528. pass # Skip unparseable humidity index; humidity remains None
  529. # AMS-HT has 1 tray, regular AMS has 4 trays
  530. is_ams_ht = len(trays) == 1
  531. ams_units.append(
  532. {
  533. "id": int(ams_data.get("id", 0)),
  534. "humidity": humidity_value,
  535. "temp": ams_data.get("temp"),
  536. "is_ams_ht": is_ams_ht,
  537. "tray": trays,
  538. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  539. "serial_number": str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  540. # Firmware version: populated by _handle_version_info from get_version
  541. "sw_ver": str(ams_data.get("sw_ver") or ""),
  542. # Drying: dry_time > 0 means drying is active (minutes remaining)
  543. "dry_time": int(ams_data.get("dry_time") or 0),
  544. # Drying status from info hex bits (0=Off, 1=Checking, 2=Drying, 3=Cooling, etc.)
  545. "dry_status": int(ams_data.get("dry_status") or 0),
  546. "dry_sub_status": int(ams_data.get("dry_sub_status") or 0),
  547. # Cannot-dry reasons from firmware (e.g. 1=InsufficientPower, 8=NeedPluginPower)
  548. "dry_sf_reason": list(ams_data.get("dry_sf_reason") or []),
  549. # Module type: "ams", "n3f", "n3s" (from get_version)
  550. "module_type": str(ams_data.get("module_type") or ""),
  551. }
  552. )
  553. # Parse virtual tray (external spool) — now a list
  554. if "vt_tray" in raw_data:
  555. for vt_data in raw_data["vt_tray"]:
  556. vt_tag_uid = vt_data.get("tag_uid")
  557. if vt_tag_uid in ("", "0000000000000000"):
  558. vt_tag_uid = None
  559. vt_tray_uuid = vt_data.get("tray_uuid")
  560. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  561. vt_tray_uuid = None
  562. # Get K value for vt_tray
  563. vt_k_value = vt_data.get("k")
  564. vt_cali_idx = vt_data.get("cali_idx")
  565. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  566. vt_k_value = kprofile_map[vt_cali_idx]
  567. tray_id = int(vt_data.get("id", 254))
  568. vt_tray.append(
  569. {
  570. "id": tray_id,
  571. "tray_color": vt_data.get("tray_color"),
  572. "tray_type": vt_data.get("tray_type"),
  573. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  574. "tray_id_name": vt_data.get("tray_id_name"),
  575. "tray_info_idx": vt_data.get("tray_info_idx"),
  576. "remain": vt_data.get("remain", 0),
  577. "k": vt_k_value,
  578. "cali_idx": vt_cali_idx,
  579. "tag_uid": vt_tag_uid,
  580. "tray_uuid": vt_tray_uuid,
  581. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  582. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  583. }
  584. )
  585. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  586. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  587. # Filter out chamber temp for models that don't have a real sensor
  588. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  589. temperatures = state.temperatures
  590. if not supports_chamber_temp(model):
  591. temperatures = {
  592. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  593. }
  594. result = {
  595. "connected": state.connected,
  596. "state": state.state,
  597. "current_print": state.current_print,
  598. "subtask_name": state.subtask_name,
  599. "gcode_file": state.gcode_file,
  600. "progress": state.progress,
  601. "remaining_time": state.remaining_time,
  602. "layer_num": state.layer_num,
  603. "total_layers": state.total_layers,
  604. "temperatures": temperatures,
  605. "hms_errors": [
  606. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  607. for e in (state.hms_errors or [])
  608. ],
  609. # AMS data for filament colors
  610. "ams": ams_units if ams_units else None,
  611. "vt_tray": vt_tray,
  612. # AMS status for filament change tracking
  613. "ams_status_main": state.ams_status_main,
  614. "ams_status_sub": state.ams_status_sub,
  615. "tray_now": state.tray_now,
  616. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  617. "ams_extruder_map": ams_extruder_map,
  618. # WiFi signal strength
  619. "wifi_signal": state.wifi_signal,
  620. "wired_network": state.wired_network,
  621. # Calibration stage tracking
  622. "stg_cur": state.stg_cur,
  623. "stg_cur_name": get_derived_status_name(state, model),
  624. # Printable objects count for skip objects feature
  625. "printable_objects_count": len(state.printable_objects),
  626. # Fan speeds (0-100 percentage, None if not available)
  627. "cooling_fan_speed": state.cooling_fan_speed,
  628. "big_fan1_speed": state.big_fan1_speed,
  629. "big_fan2_speed": state.big_fan2_speed,
  630. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  631. # Chamber light state
  632. "chamber_light": state.chamber_light,
  633. # Active extruder for dual-nozzle printers (0=right, 1=left)
  634. "active_extruder": state.active_extruder,
  635. # H2C nozzle rack (tool-changer dock positions)
  636. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  637. "nozzle_rack": [
  638. {
  639. "id": n.get("id", 0),
  640. "nozzle_type": n.get("type", ""),
  641. "nozzle_diameter": n.get("diameter", ""),
  642. "wear": n.get("wear"),
  643. "stat": n.get("stat"),
  644. "max_temp": n.get("max_temp", 0),
  645. "serial_number": n.get("serial_number", ""),
  646. "filament_color": n.get("filament_color", ""),
  647. "filament_id": n.get("filament_id", ""),
  648. }
  649. for n in (state.nozzle_rack or [])
  650. ],
  651. # AMS drying support
  652. "supports_drying": supports_drying(model, state.firmware_version),
  653. }
  654. # Add cover URL if there's an active print and printer_id is provided
  655. # Include PAUSE state so skip objects modal can show cover
  656. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  657. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  658. else:
  659. result["cover_url"] = None
  660. return result
  661. # Global printer manager instance
  662. printer_manager = PrinterManager()
  663. async def init_printer_connections(db: AsyncSession):
  664. """Initialize connections to all active printers."""
  665. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  666. printers = result.scalars().all()
  667. for printer in printers:
  668. await printer_manager.connect_printer(printer)