printer_manager.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. import asyncio
  2. import logging
  3. import re
  4. import traceback
  5. from collections.abc import Callable
  6. from sqlalchemy import select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from backend.app.models.printer import Printer
  9. from backend.app.services.bambu_mqtt import BambuMQTTClient, MQTTLogEntry, PrinterState, get_stage_name
  10. logger = logging.getLogger(__name__)
  11. # Models that have a real chamber temperature sensor
  12. # Based on Home Assistant Bambu Lab integration
  13. # P1P/P1S and A1/A1Mini do NOT have chamber temp sensors
  14. # Includes both display names and internal codes from MQTT/SSDP
  15. CHAMBER_TEMP_SUPPORTED_MODELS = frozenset(
  16. [
  17. # Display names
  18. "X1",
  19. "X1C",
  20. "X1E", # X1 series
  21. "X2D", # X2 series
  22. "P2S", # P2 series
  23. "H2C",
  24. "H2D",
  25. "H2DPRO",
  26. "H2S", # H2 series
  27. # Internal codes (from MQTT/SSDP)
  28. "BL-P001", # X1/X1C
  29. "C13", # X1E
  30. "N6", # X2D
  31. "O1D", # H2D
  32. "O1C", # H2C
  33. "O1C2", # H2C (dual nozzle variant)
  34. "O1S", # H2S
  35. "O1E", # H2D Pro
  36. "O2D", # H2D Pro (alternate code)
  37. "N7", # P2S
  38. ]
  39. )
  40. # Models that may incorrectly report stg_cur=0 when idle (firmware bug)
  41. # Based on Home Assistant Bambu Lab integration observations
  42. # See: https://github.com/greghesp/ha-bambulab/blob/main/custom_components/bambu_lab/pybambu/models.py
  43. A1_MODELS = frozenset(
  44. [
  45. # Display names
  46. "A1",
  47. "A1 MINI",
  48. "A1-MINI",
  49. "A1MINI",
  50. # Internal codes (from MQTT/SSDP)
  51. "N1", # A1 Mini
  52. "N2S", # A1
  53. ]
  54. )
  55. # Models affected by the stg_cur=0 idle bug (firmware reports stg_cur=0 when idle,
  56. # which maps to "Printing" in STAGE_NAMES and overrides the correct IDLE state)
  57. STG_CUR_IDLE_BUG_MODELS = A1_MODELS | frozenset(
  58. [
  59. # Display names
  60. "P1P",
  61. "P1S",
  62. # Internal codes (from MQTT/SSDP)
  63. "C11", # P1P
  64. "C12", # P1S
  65. ]
  66. )
  67. def supports_chamber_temp(model: str | None) -> bool:
  68. """Check if a printer model has a real chamber temperature sensor.
  69. P1P, P1S, A1, and A1Mini do NOT have chamber temp sensors.
  70. The 'chamber_temper' value they report is meaningless.
  71. """
  72. if not model:
  73. return False
  74. # Normalize model name (uppercase, strip whitespace)
  75. model_upper = model.strip().upper()
  76. return model_upper in CHAMBER_TEMP_SUPPORTED_MODELS
  77. # Models with an ACTIVE chamber heater (M141 has an effect).
  78. # Many printers in CHAMBER_TEMP_SUPPORTED_MODELS only have a passive sensor —
  79. # X1C, X1E, P2S report chamber temperature but cannot actively heat it. Only
  80. # the models below ship a PTC heater that responds to M141.
  81. CHAMBER_HEATER_MODELS = frozenset(
  82. [
  83. # Display names
  84. "H2C",
  85. "H2D",
  86. "H2DPRO",
  87. "H2S",
  88. "X2D",
  89. # Internal codes (from MQTT/SSDP)
  90. "O1C", # H2C
  91. "O1C2", # H2C dual-nozzle variant
  92. "O1D", # H2D
  93. "O1E", # H2D Pro
  94. "O2D", # H2D Pro alternate code
  95. "O1S", # H2S
  96. "N6", # X2D
  97. ]
  98. )
  99. def supports_chamber_heater(model: str | None) -> bool:
  100. """Check if a printer model has an active chamber heater (responds to M141).
  101. The chamber temperature SENSOR is more widely deployed than the chamber
  102. HEATER — X1C/X1E/P2S report chamber temp but ignore M141. Only H2C, H2D,
  103. H2D Pro, H2S, X2D actually heat. Sensor-only models silently swallow the
  104. command at the firmware level, so we 400 at the route to surface that.
  105. """
  106. if not model:
  107. return False
  108. return model.strip().upper() in CHAMBER_HEATER_MODELS
  109. def has_stg_cur_idle_bug(model: str | None) -> bool:
  110. """Check if a printer model may incorrectly report stg_cur=0 when idle.
  111. Some firmware versions report stg_cur=0 (which maps to "Printing")
  112. even when the printer is idle. Originally observed on A1/A1 Mini via the
  113. Home Assistant Bambu Lab integration, also confirmed on P1S.
  114. """
  115. if not model:
  116. return False
  117. model_upper = model.strip().upper()
  118. return model_upper in STG_CUR_IDLE_BUG_MODELS
  119. def is_bed_slinger(model: str | None) -> bool:
  120. """Whether the printer's Z axis controls the *toolhead*, not the bed.
  121. Bambu's A1 family (A1, A1 Mini; internal codes N1 / N2S) are open-frame
  122. bed-slingers: the bed moves on Y, the toolhead moves on X+Z. On every
  123. other current model (X1, P1, H2, H2C, H2D, H2S, P2S, ...) the bed moves
  124. on Z and the toolhead is fixed in Z.
  125. G-code direction is opposite on these two families. `G1 Z-10` reduces
  126. the nozzle-bed gap on both, but on bed-on-Z machines it does so by
  127. moving the BED up, while on bed-slingers it does so by moving the
  128. TOOLHEAD down — which is what crashed the nozzle in #1334.
  129. """
  130. if not model:
  131. return False
  132. return model.strip().upper() in A1_MODELS
  133. # Minimum firmware versions for AMS drying support (confirmed via capture testing)
  134. # Keys are exact model names (upper-cased). Do NOT use substring matching — it would
  135. # incorrectly gate X1E (matched by "X1") and H2D Pro (matched by "H2D").
  136. _DRYING_MIN_FIRMWARE: dict[str, str] = {
  137. "H2D": "01.02.30.00",
  138. "H2S": "01.02.00.00",
  139. "H2C": "01.02.00.00",
  140. "O1C": "01.02.00.00", # H2C SSDP model code
  141. "O1C2": "01.02.00.00", # H2C dual-nozzle SSDP model code
  142. "X1": "01.09.00.00",
  143. "X1C": "01.09.00.00",
  144. "P1P": "01.08.00.00",
  145. "P1S": "01.08.00.00",
  146. "P2S": "01.02.00.00",
  147. "N7": "01.02.00.00", # P2S internal model code
  148. }
  149. # Models that definitely don't support AMS drying (no AMS 2 Pro / AMS-HT compatibility)
  150. _DRYING_UNSUPPORTED_MODELS = frozenset({"A1", "A1MINI", "A1-MINI", "A1 MINI", "O1S", "N1", "N2S"})
  151. def supports_drying(model: str | None, firmware: str | None) -> bool:
  152. """Check if a printer model supports AMS drying commands.
  153. Known models with confirmed min firmware get version-gated.
  154. Known unsupported models are blocked.
  155. All other models (H2D Pro, X1E, future models) are allowed —
  156. the command fails gracefully with result: "fail" if unsupported.
  157. """
  158. if not model:
  159. return False
  160. model_upper = model.strip().upper()
  161. if model_upper in _DRYING_UNSUPPORTED_MODELS:
  162. return False
  163. if model_upper in _DRYING_MIN_FIRMWARE:
  164. return bool(firmware and firmware >= _DRYING_MIN_FIRMWARE[model_upper])
  165. # For all other models: allow
  166. return True
  167. # Minimum firmware versions for AMS "Print While Drying" — drying that runs CONCURRENTLY
  168. # with an active print. Strictly stricter than _DRYING_MIN_FIRMWARE (idle drying). Verified
  169. # against Bambu wiki release notes — the canonical phrasing on every supported model is
  170. # "printing while filament is drying" / "Print While Drying". Models absent from the wiki
  171. # release notes (A1, A1 Mini, P1*, X1 non-C, X1E) are intentionally excluded — the firmware
  172. # will reject the command in those cases anyway via dry_sf_reason=[0] (TaskOccupied).
  173. _DRY_WHILE_PRINTING_MIN_FIRMWARE: dict[str, str] = {
  174. "H2D": "01.03.00.00",
  175. "H2D PRO": "01.02.00.00",
  176. "H2DPRO": "01.02.00.00",
  177. "O1E": "01.02.00.00", # H2D Pro SSDP code
  178. "O2D": "01.02.00.00", # H2D Pro alternate code
  179. "H2C": "01.02.00.00",
  180. "O1C": "01.02.00.00", # H2C SSDP code
  181. "O1C2": "01.02.00.00", # H2C dual-nozzle SSDP code
  182. "H2S": "01.02.00.00",
  183. "X2D": "01.01.00.00",
  184. "N6": "01.01.00.00", # X2D internal code
  185. "X1C": "01.11.02.00",
  186. "BL-P001": "01.11.02.00", # X1C internal code
  187. "P2S": "01.02.00.00",
  188. "N7": "01.02.00.00", # P2S internal code
  189. "A2L": "01.01.00.00",
  190. "N9": "01.01.00.00", # A2L internal code
  191. }
  192. def supports_drying_while_printing(model: str | None, firmware: str | None) -> bool:
  193. """Check if a printer model+firmware supports running AMS drying CONCURRENTLY
  194. with an active print.
  195. Distinct from supports_drying() — that gates idle drying. This gate is strict:
  196. only models explicitly confirmed by Bambu wiki release notes are allowed.
  197. On unsupported models the firmware returns dry_sf_reason=[0] (TaskOccupied)
  198. while a print is running, so being conservative here costs nothing — the
  199. firmware is the ultimate arbiter, this gate just hides UI affordances.
  200. """
  201. if not model:
  202. return False
  203. model_upper = model.strip().upper()
  204. if model_upper not in _DRY_WHILE_PRINTING_MIN_FIRMWARE:
  205. return False
  206. return bool(firmware and firmware >= _DRY_WHILE_PRINTING_MIN_FIRMWARE[model_upper])
  207. class PrinterInfo:
  208. """Basic printer info for callbacks."""
  209. def __init__(self, name: str, serial_number: str):
  210. self.name = name
  211. self.serial_number = serial_number
  212. class PrinterManager:
  213. """Manager for multiple printer connections."""
  214. def __init__(self):
  215. self._clients: dict[int, BambuMQTTClient] = {}
  216. self._models: dict[int, str | None] = {} # Cache printer models for feature detection
  217. self._printer_info: dict[int, PrinterInfo] = {} # Cache printer name/serial for callbacks
  218. self._on_print_start: Callable[[int, dict], None] | None = None
  219. self._on_print_complete: Callable[[int, dict], None] | None = None
  220. self._on_print_running_observed: Callable[[int, dict], None] | None = None
  221. self._on_finish_photo_moment: Callable[[int, dict], None] | None = None
  222. self._on_status_change: Callable[[int, PrinterState], None] | None = None
  223. self._on_ams_change: Callable[[int, list], None] | None = None
  224. self._on_layer_change: Callable[[int, int], None] | None = None
  225. self._on_bed_temp_update: Callable[[int, float], None] | None = None
  226. self._on_drying_complete: Callable[[int, int], None] | None = None
  227. self._loop: asyncio.AbstractEventLoop | None = None
  228. # Track who started the current print (Issue #206)
  229. self._current_print_user: dict[int, dict] = {} # {printer_id: {"user_id": int, "username": str}}
  230. # Track printers awaiting plate-clear acknowledgment after a finished/failed print.
  231. # Persisted to DB (printers.awaiting_plate_clear) so the gate survives restarts/power
  232. # cycles — see issue #961. Loaded into this set at startup via load_awaiting_plate_clear_from_db().
  233. self._awaiting_plate_clear: set[int] = set()
  234. def get_printer(self, printer_id: int) -> PrinterInfo | None:
  235. """Get printer info by ID."""
  236. return self._printer_info.get(printer_id)
  237. def set_current_print_user(self, printer_id: int, user_id: int, username: str):
  238. """Track who started the current print (Issue #206)."""
  239. self._current_print_user[printer_id] = {"user_id": user_id, "username": username}
  240. def get_current_print_user(self, printer_id: int) -> dict | None:
  241. """Get the user who started the current print (Issue #206)."""
  242. return self._current_print_user.get(printer_id)
  243. def clear_current_print_user(self, printer_id: int):
  244. """Clear the current print user when print completes (Issue #206)."""
  245. self._current_print_user.pop(printer_id, None)
  246. def is_awaiting_plate_clear(self, printer_id: int) -> bool:
  247. """Return True when the printer finished/failed a print and is waiting for the
  248. user to acknowledge the plate is cleared before the queue may dispatch the next job.
  249. """
  250. return printer_id in self._awaiting_plate_clear
  251. def set_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  252. """Set/clear the awaiting-plate-clear gate and persist it to DB.
  253. Persisted so the gate survives Bambuddy/printer restarts (#961): after Auto Off
  254. cycles the printer, the printer boots into IDLE with no memory of the previous
  255. finish, and without persistence the queue would bypass the confirmation prompt.
  256. Also broadcasts an updated ``printer_status`` over the WebSocket (#1128).
  257. ``awaiting_plate_clear`` is a Bambuddy-side flag — toggling it does not
  258. produce an MQTT push from the printer, so without an explicit broadcast
  259. any UI subscriber that's NOT the originating tab would stay stale until
  260. the next coincidental status refresh. The plate-clear button on the
  261. printer card disappeared "immediately" only because of an optimistic
  262. React Query cache update on the click path; clearing the flag through
  263. any other route (an admin script, a second tab, an automation that
  264. hits ``POST /printers/{id}/clear-plate`` directly) silently broke the
  265. UI without it. Centralised here so every current AND future caller is
  266. covered without each one having to remember to broadcast.
  267. """
  268. if awaiting:
  269. self._awaiting_plate_clear.add(printer_id)
  270. else:
  271. self._awaiting_plate_clear.discard(printer_id)
  272. # Only create the coroutine when there is a loop to run it on — otherwise Python
  273. # emits "coroutine was never awaited" warnings (e.g. in sync unit tests).
  274. if self._loop and self._loop.is_running():
  275. self._schedule_async(self._persist_awaiting_plate_clear(printer_id, awaiting))
  276. self._schedule_async(self._broadcast_status_change(printer_id))
  277. async def _broadcast_status_change(self, printer_id: int) -> None:
  278. """Emit a ``printer_status`` WebSocket update for this printer (#1128).
  279. Used for state changes that don't come from MQTT — currently just the
  280. ``awaiting_plate_clear`` flag, but any future Bambuddy-side flag added
  281. to ``printer_state_to_dict`` should plumb through here too. The
  282. existing MQTT-driven broadcast in ``main.on_printer_status_change``
  283. deduplicates on a status_key that intentionally excludes Bambuddy
  284. flags (so e.g. queue-state changes don't get echoed as printer
  285. events), which is precisely why those flags need their own emit.
  286. Lazy-imports ``ws_manager`` to keep ``printer_manager`` clean of
  287. application-layer infra at module-import time — the broadcast is the
  288. only thing here that needs it.
  289. """
  290. state = self.get_status(printer_id)
  291. if not state:
  292. # Printer disconnected or unknown — nothing to broadcast. The
  293. # next reconnect will produce a fresh status push anyway, so the
  294. # UI eventually catches up without us forcing a stale snapshot
  295. # on subscribers now.
  296. return
  297. try:
  298. from backend.app.core.websocket import ws_manager
  299. await ws_manager.send_printer_status(
  300. printer_id,
  301. printer_state_to_dict(
  302. state,
  303. printer_id,
  304. self.get_model(printer_id),
  305. self.get_drying_targets(printer_id),
  306. ),
  307. )
  308. except Exception as e:
  309. logger.warning(
  310. "Failed to broadcast printer_status after Bambuddy-side state change for printer %d: %s",
  311. printer_id,
  312. e,
  313. )
  314. async def _persist_awaiting_plate_clear(self, printer_id: int, awaiting: bool):
  315. from backend.app.core.database import run_with_retry
  316. async def _do(db):
  317. printer = await db.get(Printer, printer_id)
  318. if printer is not None:
  319. printer.awaiting_plate_clear = awaiting
  320. await db.commit()
  321. try:
  322. await run_with_retry(_do, label=f"persist awaiting_plate_clear printer={printer_id}")
  323. except Exception as e:
  324. logger.warning("Failed to persist awaiting_plate_clear for printer %d: %s", printer_id, e)
  325. async def load_awaiting_plate_clear_from_db(self):
  326. """Rehydrate the awaiting-plate-clear set from the printers table on startup."""
  327. from backend.app.core.database import async_session
  328. try:
  329. async with async_session() as db:
  330. result = await db.execute(select(Printer.id).where(Printer.awaiting_plate_clear.is_(True)))
  331. ids = {row[0] for row in result.all()}
  332. self._awaiting_plate_clear = ids
  333. if ids:
  334. logger.info("Loaded %d printer(s) awaiting plate-clear acknowledgment: %s", len(ids), sorted(ids))
  335. except Exception as e:
  336. logger.warning("Failed to load awaiting_plate_clear from DB: %s", e)
  337. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  338. """Set the event loop for async callbacks."""
  339. self._loop = loop
  340. def set_print_start_callback(self, callback: Callable[[int, dict], None]):
  341. """Set callback for print start events."""
  342. self._on_print_start = callback
  343. def set_print_complete_callback(self, callback: Callable[[int, dict], None]):
  344. """Set callback for print completion events."""
  345. self._on_print_complete = callback
  346. def set_print_running_observed_callback(self, callback: Callable[[int, dict], None]):
  347. """Set callback for restart-recovery RUNNING-state observations (#1485
  348. follow-up). Fires the first time we see ``state == RUNNING`` for a
  349. printer that started its print before Bambuddy came up — the #1304
  350. guard suppresses ``on_print_start`` for these, so anything that
  351. normally hangs off it (e.g. timelapse baseline capture) needs this
  352. hook to recover."""
  353. self._on_print_running_observed = callback
  354. def set_finish_photo_moment_callback(self, callback: Callable[[int, dict], None]):
  355. """Set callback for the #1721 finish-photo moment.
  356. Fires on the stage-22 (\"Filament unloading\") edge at end-of-print
  357. — the framing window where the toolhead is parked but the bed
  358. hasn't dropped yet. Falls back to firing at the FINISH-state
  359. transition for prints that skip stage 22 (cancel, external-spool-
  360. only, HMS halt, firmware variants). Payload includes the
  361. ``trigger`` key (``\"stage_22\"`` or ``\"finish_state\"``) and
  362. ``timelapse_was_active`` so the photo path can choose between
  363. live-camera capture and timelapse last-frame extraction."""
  364. self._on_finish_photo_moment = callback
  365. def set_status_change_callback(self, callback: Callable[[int, PrinterState], None]):
  366. """Set callback for status change events."""
  367. self._on_status_change = callback
  368. def set_ams_change_callback(self, callback: Callable[[int, list], None]):
  369. """Set callback for AMS data change events."""
  370. self._on_ams_change = callback
  371. def set_layer_change_callback(self, callback: Callable[[int, int], None]):
  372. """Set callback for layer change events. Receives (printer_id, layer_num)."""
  373. self._on_layer_change = callback
  374. def set_bed_temp_update_callback(self, callback: Callable[[int, float], None]):
  375. """Set callback for bed temperature updates. Receives (printer_id, bed_temp)."""
  376. self._on_bed_temp_update = callback
  377. def set_drying_complete_callback(self, callback: Callable[[int, int], None]):
  378. """Set callback for AMS drying completion events (#1349).
  379. Receives ``(printer_id, ams_id)``. Fires once per falling edge of
  380. ``dry_time`` (>0 → 0) for each AMS unit.
  381. """
  382. self._on_drying_complete = callback
  383. def _schedule_async(self, coro):
  384. """Schedule an async coroutine from a sync context.
  385. Captures exceptions from the coroutine and logs them to prevent
  386. silent failures in callbacks.
  387. """
  388. if self._loop and self._loop.is_running():
  389. future = asyncio.run_coroutine_threadsafe(coro, self._loop)
  390. def handle_exception(f):
  391. try:
  392. # This will re-raise any exception from the coroutine
  393. f.result()
  394. except Exception as e:
  395. import logging
  396. logging.getLogger(__name__).error(f"Exception in scheduled callback: {e}", exc_info=True)
  397. future.add_done_callback(handle_exception)
  398. async def connect_printer(self, printer: Printer) -> bool:
  399. """Connect to a printer."""
  400. if printer.id in self._clients:
  401. self.disconnect_printer(printer.id)
  402. printer_id = printer.id
  403. def on_state_change(state: PrinterState):
  404. if self._on_status_change:
  405. self._schedule_async(self._on_status_change(printer_id, state))
  406. def on_print_start(data: dict):
  407. if self._on_print_start:
  408. self._schedule_async(self._on_print_start(printer_id, data))
  409. def on_print_complete(data: dict):
  410. if self._on_print_complete:
  411. self._schedule_async(self._on_print_complete(printer_id, data))
  412. def on_print_running_observed(data: dict):
  413. if self._on_print_running_observed:
  414. self._schedule_async(self._on_print_running_observed(printer_id, data))
  415. def on_finish_photo_moment(data: dict):
  416. if self._on_finish_photo_moment:
  417. self._schedule_async(self._on_finish_photo_moment(printer_id, data))
  418. def on_ams_change(ams_data: list):
  419. if self._on_ams_change:
  420. self._schedule_async(self._on_ams_change(printer_id, ams_data))
  421. def on_layer_change(layer_num: int):
  422. if self._on_layer_change:
  423. self._schedule_async(self._on_layer_change(printer_id, layer_num))
  424. def on_bed_temp_update(bed_temp: float):
  425. if self._on_bed_temp_update:
  426. self._schedule_async(self._on_bed_temp_update(printer_id, bed_temp))
  427. def on_drying_complete(ams_id: int):
  428. if self._on_drying_complete:
  429. self._schedule_async(self._on_drying_complete(printer_id, ams_id))
  430. client = BambuMQTTClient(
  431. ip_address=printer.ip_address,
  432. serial_number=printer.serial_number,
  433. access_code=printer.access_code,
  434. model=printer.model,
  435. on_state_change=on_state_change,
  436. on_print_start=on_print_start,
  437. on_print_complete=on_print_complete,
  438. on_ams_change=on_ams_change,
  439. on_layer_change=on_layer_change,
  440. on_bed_temp_update=on_bed_temp_update,
  441. on_drying_complete=on_drying_complete,
  442. on_print_running_observed=on_print_running_observed,
  443. on_finish_photo_moment=on_finish_photo_moment,
  444. )
  445. client.connect()
  446. self._clients[printer_id] = client
  447. self._models[printer_id] = printer.model # Cache model for feature detection
  448. self._printer_info[printer_id] = PrinterInfo(printer.name, printer.serial_number)
  449. # Wait a moment for connection
  450. await asyncio.sleep(1)
  451. return client.state.connected
  452. def disconnect_printer(self, printer_id: int, timeout: float = 0):
  453. """Disconnect from a printer."""
  454. if printer_id in self._clients:
  455. self._clients[printer_id].disconnect(timeout=timeout)
  456. del self._clients[printer_id]
  457. self._models.pop(printer_id, None) # Clean up model cache
  458. self._printer_info.pop(printer_id, None) # Clean up printer info cache
  459. def disconnect_all(self, timeout: float = 0):
  460. """Disconnect from all printers."""
  461. for printer_id in list(self._clients.keys()):
  462. self.disconnect_printer(printer_id, timeout=timeout)
  463. def get_status(self, printer_id: int) -> PrinterState | None:
  464. """Get the current status of a printer (checks for stale connections)."""
  465. if printer_id in self._clients:
  466. client = self._clients[printer_id]
  467. # Check staleness and update connected state if needed
  468. client.check_staleness()
  469. return client.state
  470. return None
  471. def get_model(self, printer_id: int) -> str | None:
  472. """Get the cached model for a printer."""
  473. return self._models.get(printer_id)
  474. def get_drying_targets(self, printer_id: int) -> dict[int, dict] | None:
  475. """Get cached active drying target params keyed by AMS id.
  476. Returned dict shape: ``{ams_id: {"filament": str, "temp": int}}``.
  477. Returns ``None`` when the printer is not connected. The cache is
  478. seeded by ``send_drying_command(mode=1)`` and cleared when drying
  479. stops or on the ``dry_time`` falling edge (handled inside
  480. ``BambuMQTTClient``).
  481. """
  482. client = self._clients.get(printer_id)
  483. return client._drying_targets if client else None
  484. def get_all_statuses(self) -> dict[int, PrinterState]:
  485. """Get status of all connected printers (checks for stale connections)."""
  486. result = {}
  487. for printer_id, client in self._clients.items():
  488. # Check staleness and update connected state if needed
  489. client.check_staleness()
  490. result[printer_id] = client.state
  491. return result
  492. def is_connected(self, printer_id: int) -> bool:
  493. """Check if a printer is connected (checks for stale connections)."""
  494. if printer_id in self._clients:
  495. client = self._clients[printer_id]
  496. # Check staleness and update connected state if needed
  497. return client.check_staleness()
  498. return False
  499. def get_client(self, printer_id: int) -> BambuMQTTClient | None:
  500. """Get the MQTT client for a printer."""
  501. return self._clients.get(printer_id)
  502. def mark_printer_offline(self, printer_id: int):
  503. """Mark a printer as offline and trigger status callback.
  504. This is used when we know the printer power was cut (e.g., smart plug turned off)
  505. to immediately update the UI without waiting for MQTT timeout.
  506. """
  507. import logging
  508. logger = logging.getLogger(__name__)
  509. if printer_id in self._clients:
  510. client = self._clients[printer_id]
  511. if client.state.connected:
  512. logger.info("Marking printer %s as offline (smart plug power off)", printer_id)
  513. client.state.connected = False
  514. client.state.state = "unknown"
  515. # Trigger the status change callback to broadcast via WebSocket
  516. if self._on_status_change:
  517. self._schedule_async(self._on_status_change(printer_id, client.state))
  518. def start_print(
  519. self,
  520. printer_id: int,
  521. filename: str,
  522. plate_id: int = 1,
  523. ams_mapping: list[int] | None = None,
  524. bed_levelling: bool = True,
  525. flow_cali: bool = False,
  526. vibration_cali: bool = True,
  527. layer_inspect: bool = False,
  528. timelapse: bool = False,
  529. use_ams: bool = True,
  530. nozzle_offset_cali: bool = False,
  531. nozzle_mapping: str | None = None,
  532. ) -> bool:
  533. """Start a print on a connected printer.
  534. ``nozzle_mapping`` is an opaque JSON string captured from BambuStudio's
  535. project_file MQTT command (H2C rack-swap slicer pick preservation,
  536. #1780). It rides through to the MQTT client untouched; the dispatch
  537. builder there parses + injects it only on dual-nozzle models.
  538. """
  539. caller = traceback.extract_stack(limit=3)[0]
  540. logger.info(
  541. "PRINT COMMAND: printer=%s, file=%s, caller=%s:%s:%s",
  542. printer_id,
  543. filename,
  544. caller.filename.split("/")[-1],
  545. caller.lineno,
  546. caller.name,
  547. )
  548. if printer_id in self._clients:
  549. return self._clients[printer_id].start_print(
  550. filename,
  551. plate_id,
  552. ams_mapping=ams_mapping,
  553. timelapse=timelapse,
  554. bed_levelling=bed_levelling,
  555. flow_cali=flow_cali,
  556. vibration_cali=vibration_cali,
  557. layer_inspect=layer_inspect,
  558. use_ams=use_ams,
  559. nozzle_offset_cali=nozzle_offset_cali,
  560. nozzle_mapping=nozzle_mapping,
  561. )
  562. return False
  563. def stop_print(self, printer_id: int) -> bool:
  564. """Stop the current print on a connected printer."""
  565. if printer_id in self._clients:
  566. return self._clients[printer_id].stop_print()
  567. return False
  568. async def wait_for_cooldown(
  569. self,
  570. printer_id: int,
  571. target_temp: float = 50.0,
  572. timeout: int = 600,
  573. check_interval: int = 10,
  574. ) -> bool:
  575. """Wait for the nozzle to cool down to a safe temperature.
  576. Args:
  577. printer_id: The printer to monitor
  578. target_temp: Target temperature to wait for (default 50°C)
  579. timeout: Maximum seconds to wait (default 600s = 10 min)
  580. check_interval: Seconds between temperature checks (default 10s)
  581. Returns:
  582. True if cooled down, False if timeout or not connected
  583. """
  584. import logging
  585. logger = logging.getLogger(__name__)
  586. elapsed = 0
  587. while elapsed < timeout:
  588. state = self.get_status(printer_id)
  589. if not state or not state.connected:
  590. logger.warning("Printer %s disconnected during cooldown wait", printer_id)
  591. return False
  592. # Check nozzle temperature (and nozzle_2 for dual extruders)
  593. nozzle_temp = state.temperatures.get("nozzle", 0)
  594. nozzle_2_temp = state.temperatures.get("nozzle_2", 0)
  595. max_temp = max(nozzle_temp, nozzle_2_temp)
  596. if max_temp <= target_temp:
  597. logger.info("Printer %s cooled down to %s°C", printer_id, max_temp)
  598. return True
  599. logger.debug("Printer %s nozzle at %s°C, waiting for %s°C...", printer_id, max_temp, target_temp)
  600. await asyncio.sleep(check_interval)
  601. elapsed += check_interval
  602. logger.warning("Printer %s cooldown timeout after %ss", printer_id, timeout)
  603. return False
  604. def enable_logging(self, printer_id: int, enabled: bool = True) -> bool:
  605. """Enable or disable MQTT logging for a printer."""
  606. if printer_id in self._clients:
  607. self._clients[printer_id].enable_logging(enabled)
  608. return True
  609. return False
  610. def get_logs(self, printer_id: int) -> list[MQTTLogEntry]:
  611. """Get MQTT logs for a printer."""
  612. if printer_id in self._clients:
  613. return self._clients[printer_id].get_logs()
  614. return []
  615. def clear_logs(self, printer_id: int) -> bool:
  616. """Clear MQTT logs for a printer."""
  617. if printer_id in self._clients:
  618. self._clients[printer_id].clear_logs()
  619. return True
  620. return False
  621. def is_logging_enabled(self, printer_id: int) -> bool:
  622. """Check if logging is enabled for a printer."""
  623. if printer_id in self._clients:
  624. return self._clients[printer_id].logging_enabled
  625. return False
  626. def send_drying_command(
  627. self,
  628. printer_id: int,
  629. ams_id: int,
  630. temp: int,
  631. duration: int,
  632. mode: int = 1,
  633. filament: str = "",
  634. rotate_tray: bool = False,
  635. ) -> bool:
  636. """Send AMS drying command to printer."""
  637. if printer_id not in self._clients:
  638. return False
  639. return self._clients[printer_id].send_drying_command(ams_id, temp, duration, mode, filament, rotate_tray)
  640. def request_status_update(self, printer_id: int) -> bool:
  641. """Request a full status update from the printer.
  642. This sends a 'pushall' command to get the latest data including nozzle info.
  643. """
  644. if printer_id in self._clients:
  645. return self._clients[printer_id].request_status_update()
  646. return False
  647. # Probe budget for test_connection (#1445). Was a fixed 2s sleep, which was
  648. # too short for P1S firmware whose broker / TLS handshake routinely takes
  649. # 3–5s to surface a CONNACK on a cold MQTT session. We now poll up to
  650. # PROBE_TIMEOUT_SECONDS and early-return the moment we see connected=True,
  651. # so happy-path connections still finish in ~1–2s and slow brokers get the
  652. # headroom they need instead of getting falsely rejected.
  653. PROBE_TIMEOUT_SECONDS = 8.0
  654. PROBE_POLL_INTERVAL_SECONDS = 0.2
  655. async def test_connection(
  656. self,
  657. ip_address: str,
  658. serial_number: str,
  659. access_code: str,
  660. ) -> dict:
  661. """Test connection to a printer without persisting.
  662. Polls for up to PROBE_TIMEOUT_SECONDS and tears the probe client down
  663. off-loop. The teardown matters: `client.disconnect()` ends in paho's
  664. `loop_stop()` which `join()`s the network thread — if the thread is
  665. still mid-TLS-handshake to a slow printer, that join blocks the
  666. asyncio event loop and every other HTTP request queues behind it. The
  667. original synchronous teardown produced the #1445 "Docker container
  668. hangs" symptom on P1S when called from POST /printers/.
  669. """
  670. client = BambuMQTTClient(
  671. ip_address=ip_address,
  672. serial_number=serial_number,
  673. access_code=access_code,
  674. )
  675. try:
  676. client.connect()
  677. deadline = asyncio.get_running_loop().time() + self.PROBE_TIMEOUT_SECONDS
  678. while not client.state.connected and asyncio.get_running_loop().time() < deadline:
  679. await asyncio.sleep(self.PROBE_POLL_INTERVAL_SECONDS)
  680. result = {
  681. "success": client.state.connected,
  682. "state": client.state.state if client.state.connected else None,
  683. "model": client.state.raw_data.get("device_model"),
  684. }
  685. finally:
  686. # Off-loop teardown — see docstring. paho's loop_stop() joins the
  687. # network thread which may still be in a slow TLS handshake.
  688. await asyncio.to_thread(client.disconnect)
  689. return result
  690. def get_derived_status_name(state: PrinterState, model: str | None = None) -> str | None:
  691. """
  692. Compute a human-readable status name based on printer state.
  693. Uses stg_cur when available, otherwise derives status from temperature data
  694. when the printer is heating before a print starts.
  695. Args:
  696. state: The printer state to analyze
  697. model: Optional printer model for model-specific workarounds
  698. """
  699. # Firmware bug: some models (A1, P1P, P1S) report stg_cur=0 when not printing.
  700. # stg_cur=0 maps to "Printing" in STAGE_NAMES, which incorrectly overrides the
  701. # real state (IDLE, FINISH, FAILED, etc.). Only trust stg_cur when the printer
  702. # is actually in an active print state (RUNNING or PAUSE).
  703. if state.state not in ("RUNNING", "PAUSE") and state.stg_cur == 0 and has_stg_cur_idle_bug(model):
  704. return None
  705. # If we have a valid calibration stage, use it
  706. # X1 models use -1 for idle, A1/P1 models use 255 for idle
  707. # Valid stage numbers are 0-254
  708. if 0 <= state.stg_cur < 255:
  709. return get_stage_name(state.stg_cur)
  710. # If not in RUNNING state, no derived status needed
  711. if state.state != "RUNNING":
  712. return None
  713. # Check if we're in an early phase where temperatures are heating
  714. temps = state.temperatures or {}
  715. progress = state.progress or 0
  716. # Only derive heating status when progress is very low (< 2%)
  717. # This indicates we're in the preparation phase, not actually printing
  718. if progress >= 2:
  719. return None
  720. # Check bed temperature - if target is set and current is significantly below
  721. bed_temp = temps.get("bed", 0)
  722. bed_target = temps.get("bed_target", 0)
  723. # Check nozzle temperature
  724. nozzle_temp = temps.get("nozzle", 0)
  725. nozzle_target = temps.get("nozzle_target", 0)
  726. # Temperature thresholds: consider "heating" if more than 10°C below target
  727. TEMP_THRESHOLD = 10
  728. # Determine what's heating (prioritize bed since it takes longer)
  729. if bed_target > 30 and (bed_target - bed_temp) > TEMP_THRESHOLD:
  730. return "Heating heatbed"
  731. elif nozzle_target > 30 and (nozzle_target - nozzle_temp) > TEMP_THRESHOLD:
  732. return "Heating nozzle"
  733. # If targets are set but we're close to them, we might be in final prep
  734. if bed_target > 30 or nozzle_target > 30:
  735. if progress == 0 and state.layer_num == 0:
  736. return "Preparing"
  737. return None
  738. _PLATE_ID_RE = re.compile(r"plate_(\d+)\.gcode")
  739. def parse_plate_id(gcode_file: str | None) -> int | None:
  740. """Extract the 1-indexed plate number from a Bambu gcode_file path.
  741. Returns None when the path is missing or has no `plate_N.gcode` segment.
  742. Shared by the REST status route and the WebSocket push path so both agree
  743. on the value sent to the frontend (#881 follow-up).
  744. """
  745. if not gcode_file:
  746. return None
  747. match = _PLATE_ID_RE.search(gcode_file)
  748. return int(match.group(1)) if match else None
  749. def resolve_plate_id(state) -> int | None:
  750. """Resolve the active plate number from a PrinterState.
  751. Some firmware versions (e.g. P1S 01.10.00.00, #1166) put only the .3mf
  752. filename in print.gcode_file, so parse_plate_id() returns None and the
  753. printer card falls back to plate 1 — wrong thumbnail. When Bambuddy
  754. dispatched the print itself we already know the right plate, so we prefer
  755. that over the gcode_file echo. The subtask check prevents stale values
  756. from a previous Bambuddy-dispatched print bleeding into a Studio-direct
  757. print on the same printer.
  758. """
  759. dispatched_plate = getattr(state, "dispatched_plate_id", None)
  760. dispatched_subtask = getattr(state, "dispatched_subtask", None)
  761. if (
  762. dispatched_plate is not None
  763. and dispatched_subtask is not None
  764. and state.subtask_name
  765. and dispatched_subtask == state.subtask_name
  766. ):
  767. return dispatched_plate
  768. return parse_plate_id(state.gcode_file)
  769. def printer_state_to_dict(
  770. state: PrinterState,
  771. printer_id: int | None = None,
  772. model: str | None = None,
  773. drying_targets: dict[int, dict] | None = None,
  774. ) -> dict:
  775. """Convert PrinterState to a JSON-serializable dict.
  776. Args:
  777. state: The printer state to convert
  778. printer_id: Optional printer ID for generating cover URLs
  779. model: Optional printer model for filtering unsupported features
  780. drying_targets: Optional per-AMS active-cycle params
  781. (``{ams_id: {"filament": str, "temp": int}}``) sourced from the
  782. BambuMQTTClient cache so the badge can display "PETG @ 65°C".
  783. """
  784. # Parse AMS data from raw_data
  785. ams_units = []
  786. vt_tray = []
  787. raw_data = state.raw_data or {}
  788. # Build K-profile lookup map: cali_idx -> k_value
  789. kprofile_map: dict[int, float] = {}
  790. for kp in state.kprofiles or []:
  791. if kp.slot_id is not None and kp.k_value:
  792. try:
  793. kprofile_map[kp.slot_id] = float(kp.k_value)
  794. except (ValueError, TypeError):
  795. pass # Skip K-profile entries with unparseable values
  796. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  797. for ams_data in raw_data["ams"]:
  798. trays = []
  799. for tray in ams_data.get("tray", []):
  800. tag_uid = tray.get("tag_uid")
  801. if tag_uid in ("", "0000000000000000"):
  802. tag_uid = None
  803. tray_uuid = tray.get("tray_uuid")
  804. if tray_uuid in ("", "00000000000000000000000000000000"):
  805. tray_uuid = None
  806. # Get K value: first try tray's k field, then lookup from K-profiles
  807. k_value = tray.get("k")
  808. cali_idx = tray.get("cali_idx")
  809. if k_value is None and cali_idx is not None and cali_idx in kprofile_map:
  810. k_value = kprofile_map[cali_idx]
  811. # P1S / A1 Mini physically-empty-slot signal (#1322 follow-up by
  812. # @RosdasHH): for a truly empty slot the firmware sends only
  813. # {"id": N} — no state, no tray_type, no anything else. Treat
  814. # that as the firmware's "no spool" indicator (state=9) so the
  815. # assign-spool path in inventory.py can short-circuit a MQTT
  816. # publish the firmware would silently drop anyway. The
  817. # post-"Reset Slot" A1 Mini BMCU case sends a populated payload
  818. # (state=3, tray_type="") — different shape, doesn't match this
  819. # guard, still attempts the MQTT push per the #1322 fix.
  820. state_val = tray.get("state")
  821. if state_val is None and len(tray) == 1 and "id" in tray:
  822. state_val = 9
  823. trays.append(
  824. {
  825. "id": int(tray.get("id", 0)),
  826. "tray_color": tray.get("tray_color"),
  827. "tray_type": tray.get("tray_type"),
  828. "tray_sub_brands": tray.get("tray_sub_brands"),
  829. "tray_id_name": tray.get("tray_id_name"),
  830. "tray_info_idx": tray.get("tray_info_idx"),
  831. "remain": tray.get("remain", 0),
  832. "k": k_value,
  833. "cali_idx": cali_idx,
  834. "tag_uid": tag_uid,
  835. "tray_uuid": tray_uuid,
  836. "nozzle_temp_min": tray.get("nozzle_temp_min"),
  837. "nozzle_temp_max": tray.get("nozzle_temp_max"),
  838. "drying_temp": tray.get("drying_temp"),
  839. "drying_time": tray.get("drying_time"),
  840. "state": state_val,
  841. }
  842. )
  843. # Prefer humidity_raw (actual percentage) over humidity (index 1-5)
  844. humidity_raw = ams_data.get("humidity_raw")
  845. humidity_idx = ams_data.get("humidity")
  846. humidity_value = None
  847. if humidity_raw is not None:
  848. try:
  849. humidity_value = int(humidity_raw)
  850. except (ValueError, TypeError):
  851. pass # Skip unparseable humidity; will try index fallback
  852. # Fall back to index if no raw value (index is 1-5, not percentage)
  853. if humidity_value is None and humidity_idx is not None:
  854. try:
  855. humidity_value = int(humidity_idx)
  856. except (ValueError, TypeError):
  857. pass # Skip unparseable humidity index; humidity remains None
  858. # AMS-HT has 1 tray, regular AMS has 4 trays
  859. is_ams_ht = len(trays) == 1
  860. # Active-cycle filament + target temperature for the badge.
  861. # Bambu does not echo the cycle's chosen filament/temp on the
  862. # per-tick AMS push, so prefer the cached target from the last
  863. # ``send_drying_command``. When we have no record (drying
  864. # started in a previous backend lifetime, or the cache was
  865. # never seeded), fall back to the first loaded tray's
  866. # tray_type + RFID-recommended drying_temp — the same heuristic
  867. # the popover already uses to seed defaults.
  868. ams_id_int = int(ams_data.get("id", 0))
  869. target = (drying_targets or {}).get(ams_id_int)
  870. dry_target_temp: int | None = None
  871. dry_filament: str | None = None
  872. if target:
  873. temp_val = target.get("temp")
  874. fil_val = target.get("filament") or ""
  875. if temp_val is not None:
  876. try:
  877. dry_target_temp = int(temp_val)
  878. except (TypeError, ValueError):
  879. dry_target_temp = None
  880. if fil_val:
  881. dry_filament = str(fil_val)
  882. if dry_target_temp is None or not dry_filament:
  883. for tray in trays:
  884. if tray.get("tray_type"):
  885. if not dry_filament:
  886. dry_filament = str(tray["tray_type"])
  887. if dry_target_temp is None and tray.get("drying_temp"):
  888. try:
  889. dry_target_temp = int(tray["drying_temp"])
  890. except (TypeError, ValueError):
  891. pass
  892. break
  893. ams_units.append(
  894. {
  895. "id": ams_id_int,
  896. "humidity": humidity_value,
  897. "temp": ams_data.get("temp"),
  898. "is_ams_ht": is_ams_ht,
  899. "tray": trays,
  900. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  901. "serial_number": str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  902. # Firmware version: populated by _handle_version_info from get_version
  903. "sw_ver": str(ams_data.get("sw_ver") or ""),
  904. # Drying: dry_time > 0 means drying is active (minutes remaining)
  905. "dry_time": int(ams_data.get("dry_time") or 0),
  906. # Drying status from info hex bits (0=Off, 1=Checking, 2=Drying, 3=Cooling, etc.)
  907. "dry_status": int(ams_data.get("dry_status") or 0),
  908. "dry_sub_status": int(ams_data.get("dry_sub_status") or 0),
  909. # Cannot-dry reasons from firmware (e.g. 1=InsufficientPower, 8=NeedPluginPower)
  910. "dry_sf_reason": list(ams_data.get("dry_sf_reason") or []),
  911. # Active-cycle filament name + target temperature
  912. "dry_target_temp": dry_target_temp,
  913. "dry_filament": dry_filament,
  914. # Module type: "ams", "n3f", "n3s" (from get_version)
  915. "module_type": str(ams_data.get("module_type") or ""),
  916. }
  917. )
  918. # Parse virtual tray (external spool) — now a list
  919. if "vt_tray" in raw_data:
  920. vt_tray_raw = raw_data["vt_tray"]
  921. # Defensive: MQTT sends vt_tray as a dict; normalize to list
  922. if isinstance(vt_tray_raw, dict):
  923. vt_tray_raw = [vt_tray_raw]
  924. elif not isinstance(vt_tray_raw, list):
  925. vt_tray_raw = []
  926. for vt_data in vt_tray_raw:
  927. vt_tag_uid = vt_data.get("tag_uid")
  928. if vt_tag_uid in ("", "0000000000000000"):
  929. vt_tag_uid = None
  930. vt_tray_uuid = vt_data.get("tray_uuid")
  931. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  932. vt_tray_uuid = None
  933. # Get K value for vt_tray
  934. vt_k_value = vt_data.get("k")
  935. vt_cali_idx = vt_data.get("cali_idx")
  936. if vt_k_value is None and vt_cali_idx is not None and vt_cali_idx in kprofile_map:
  937. vt_k_value = kprofile_map[vt_cali_idx]
  938. tray_id = int(vt_data.get("id", 254))
  939. vt_tray.append(
  940. {
  941. "id": tray_id,
  942. "tray_color": vt_data.get("tray_color"),
  943. "tray_type": vt_data.get("tray_type"),
  944. "tray_sub_brands": vt_data.get("tray_sub_brands"),
  945. "tray_id_name": vt_data.get("tray_id_name"),
  946. "tray_info_idx": vt_data.get("tray_info_idx"),
  947. "remain": vt_data.get("remain", 0),
  948. "k": vt_k_value,
  949. "cali_idx": vt_cali_idx,
  950. "tag_uid": vt_tag_uid,
  951. "tray_uuid": vt_tray_uuid,
  952. "nozzle_temp_min": vt_data.get("nozzle_temp_min"),
  953. "nozzle_temp_max": vt_data.get("nozzle_temp_max"),
  954. }
  955. )
  956. # Get ams_extruder_map from raw_data (populated by MQTT handler from AMS info field)
  957. ams_extruder_map = raw_data.get("ams_extruder_map", {})
  958. # Filter out chamber temp for models that don't have a real sensor
  959. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  960. temperatures = state.temperatures
  961. if not supports_chamber_temp(model):
  962. temperatures = {
  963. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  964. }
  965. result = {
  966. "connected": state.connected,
  967. "state": state.state,
  968. "current_print": state.current_print,
  969. "subtask_name": state.subtask_name,
  970. "gcode_file": state.gcode_file,
  971. "progress": state.progress,
  972. "remaining_time": state.remaining_time,
  973. "layer_num": state.layer_num,
  974. "total_layers": state.total_layers,
  975. "temperatures": temperatures,
  976. "hms_errors": [
  977. {
  978. "code": e.code,
  979. "attr": e.attr,
  980. "module": e.module,
  981. "severity": e.severity,
  982. "actions": e.actions,
  983. "job_id": e.job_id,
  984. "full_code": e.full_code,
  985. }
  986. for e in (state.hms_errors or [])
  987. ],
  988. # AMS data for filament colors
  989. "ams": ams_units if ams_units else None,
  990. "vt_tray": vt_tray,
  991. # AMS status for filament change tracking
  992. "ams_status_main": state.ams_status_main,
  993. "ams_status_sub": state.ams_status_sub,
  994. "tray_now": state.tray_now,
  995. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right, 1=left
  996. "ams_extruder_map": ams_extruder_map,
  997. # WiFi signal strength
  998. "wifi_signal": state.wifi_signal,
  999. "wired_network": state.wired_network,
  1000. "door_open": state.door_open,
  1001. # AMS Filament Backup state (auto-switch to second spool). Tri-state:
  1002. # True / False / None. None = unknown or unsupported (A1 family). UI
  1003. # uses this to drive the small status icon next to the AMS drying icon.
  1004. "ams_filament_backup": state.ams_filament_backup,
  1005. # Calibration stage tracking
  1006. "stg_cur": state.stg_cur,
  1007. "stg_cur_name": get_derived_status_name(state, model),
  1008. # Printable objects count for skip objects feature
  1009. "printable_objects_count": len(state.printable_objects),
  1010. # Fan speeds (0-100 percentage, None if not available)
  1011. "cooling_fan_speed": state.cooling_fan_speed,
  1012. "big_fan1_speed": state.big_fan1_speed,
  1013. "big_fan2_speed": state.big_fan2_speed,
  1014. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  1015. # Chamber light state
  1016. "chamber_light": state.chamber_light,
  1017. # Active extruder for dual-nozzle printers (0=right, 1=left)
  1018. "active_extruder": state.active_extruder,
  1019. # Print speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1020. "speed_level": state.speed_level,
  1021. # H2C nozzle rack (tool-changer dock positions)
  1022. # Map raw MQTT field names (type/diameter) to schema names (nozzle_type/nozzle_diameter)
  1023. "nozzle_rack": [
  1024. {
  1025. "id": n.get("id", 0),
  1026. "nozzle_type": n.get("type", ""),
  1027. "nozzle_diameter": n.get("diameter", ""),
  1028. "wear": n.get("wear"),
  1029. "stat": n.get("stat"),
  1030. "max_temp": n.get("max_temp", 0),
  1031. "serial_number": n.get("serial_number", ""),
  1032. "filament_color": n.get("filament_color", ""),
  1033. "filament_id": n.get("filament_id", ""),
  1034. }
  1035. for n in (state.nozzle_rack or [])
  1036. ],
  1037. # AMS drying support
  1038. "supports_drying": supports_drying(model, state.firmware_version),
  1039. "supports_drying_while_printing": supports_drying_while_printing(model, state.firmware_version),
  1040. # 1-indexed plate number parsed from gcode_file (e.g. /Metadata/plate_2.gcode).
  1041. # Pushed via WebSocket so the printer card picks up plate transitions within
  1042. # a multi-plate 3MF without waiting for the 30 s REST poll (#881 follow-up).
  1043. # current_archive_id is intentionally REST-only — it's stable for the life
  1044. # of a print and needs a DB lookup the WebSocket path shouldn't pay for.
  1045. "current_plate_id": resolve_plate_id(state),
  1046. # Plate-clear gate (#939). Lives on the PrinterManager rather than PrinterState,
  1047. # so surface it here — without this, WebSocket merges drop the flag and the
  1048. # "Clear Plate" button only appears when the 30 s REST fallback poll runs.
  1049. "awaiting_plate_clear": printer_manager.is_awaiting_plate_clear(printer_id) if printer_id else False,
  1050. }
  1051. # Add cover URL if there's an active print and printer_id is provided
  1052. # Include PAUSE state so skip objects modal can show cover
  1053. if printer_id and state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  1054. result["cover_url"] = f"/api/v1/printers/{printer_id}/cover"
  1055. else:
  1056. result["cover_url"] = None
  1057. # Surface the display name + model so WS consumers (gcode viewer printer
  1058. # selector) can render proper labels on the initial snapshot without racing
  1059. # a separate /api/v1/printers fetch (#963 follow-up). PrinterInfo only
  1060. # carries name/serial_number; the model comes through via the `model` arg.
  1061. if printer_id:
  1062. _printer_info = printer_manager.get_printer(printer_id)
  1063. if _printer_info is not None:
  1064. result["name"] = _printer_info.name
  1065. if model:
  1066. result["model"] = model
  1067. return result
  1068. # Global printer manager instance
  1069. printer_manager = PrinterManager()
  1070. async def init_printer_connections(db: AsyncSession):
  1071. """Initialize connections to all active printers."""
  1072. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1073. printers = result.scalars().all()
  1074. for printer in printers:
  1075. await printer_manager.connect_printer(printer)