printer_manager.py 32 KB

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