mqtt_bridge.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. """MQTT bridge for non-proxy virtual printers.
  2. Mirrors the target printer's state to slicers connected to a virtual printer
  3. without opening a second MQTT session on the printer (reuses Bambuddy's
  4. existing subscription — firmware inflight budget unaffected, see PR #1164).
  5. Architecture (cached-as-base, not a separate fan-out stream):
  6. - **push_status** snapshots from the printer are CACHED here. The VP's
  7. `SimpleMQTTServer._send_status_report` consults that cache and sends
  8. a near-byte-identical copy of the real push to the slicer (with
  9. sequence_id / gcode_state / etc. overridden). Single source of truth
  10. keeps BambuStudio's Send pre-flight happy.
  11. - **info.get_version** responses are also cached so the synthetic version
  12. response can include the real AMS module list (n3f/n3s/ams entries).
  13. Without this BambuStudio's Prepare tab labels every AMS as "unknown".
  14. - **Other command responses** (extrusion_cali_get, AMS write acks,
  15. xcam responses, …) are fanned out raw to the slicer — they carry
  16. sequence_ids the slicer is waiting on; the slicer matches and ignores
  17. unrelated ones.
  18. Identity rewriting at cache time:
  19. - `upgrade_state.sn` (and any other nested dict's `sn` matching the real
  20. serial) → VP serial
  21. - `net.info[*].ip` little-endian uint32 → VP bind IP. BambuStudio reads
  22. this as the FTP destination IP. Without this the slicer FTPs straight
  23. to the real printer and bypasses Bambuddy.
  24. - `ipcam.rtsp_url` is left unchanged: BambuStudio overrides the URL host
  25. with the device IP it bound to (the VP), so the slicer hits the VP's
  26. own RTSPS proxy on port 322.
  27. """
  28. from __future__ import annotations
  29. import asyncio
  30. import copy
  31. import ipaddress
  32. import json
  33. import logging
  34. import socket
  35. from typing import TYPE_CHECKING
  36. from backend.app.services.virtual_printer._debug import append_event, dump_wire
  37. if TYPE_CHECKING:
  38. from backend.app.services.bambu_mqtt import BambuMQTTClient
  39. from backend.app.services.printer_manager import PrinterManager
  40. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  41. logger = logging.getLogger(__name__)
  42. REFRESH_INTERVAL_SECONDS = 30.0
  43. # Bambuddy's internal printer state in bambu_mqtt.py (around line 2686+) is
  44. # updated per-field — each `if "X" in data: self.state.X = ...` block leaves
  45. # every other field untouched, so the state accumulates everything the
  46. # printer has ever sent. The bridge cache below mirrors that pattern: when
  47. # the incoming push_status omits a field, the previous value is preserved
  48. # verbatim; only fields actually present in the new push overwrite. This
  49. # stops capability/lifecycle fields (cali_version, print_type, mc_print_stage,
  50. # device, ...) draining out of the cache between pushalls, which surfaced
  51. # as #1622 (BambuStudio's Device-tab UIs greying out on P1S after the
  52. # cache drained to a thin incremental snapshot). The `ams` field still
  53. # gets unit-/tray-level deep merge via `_merge_ams_dict` because firmware
  54. # sends partial `ams` blobs under the same key (#1387).
  55. def _ip_to_uint32_le(ip_str: str) -> int:
  56. """Encode dotted-quad IPv4 as little-endian uint32 (Bambu MQTT's `net.info[].ip` shape)."""
  57. parts = [int(x) for x in ip_str.split(".")]
  58. if len(parts) != 4 or any(p < 0 or p > 255 for p in parts):
  59. raise ValueError(f"invalid IPv4: {ip_str!r}")
  60. return parts[0] | (parts[1] << 8) | (parts[2] << 16) | (parts[3] << 24)
  61. def _resolve_target_to_ipv4(target: str) -> str | None:
  62. """Return a dotted-quad IPv4 for `target`, resolving hostnames if needed.
  63. The printer client may be configured by IPv4 *or* by hostname/FQDN
  64. (e.g. `p1s.fritz.box`) — the latter is common on home LANs with a
  65. DNS-providing router. The downstream `net.info[].ip` field is a
  66. 32-bit little-endian integer though, so a hostname can't round-trip
  67. through it; we have to pick *one* concrete IPv4 to write in.
  68. Returns None if `target` is empty, not parseable as IPv4, and DNS
  69. resolution fails — caller logs that as the not-armed reason and
  70. re-tries on the next refresh tick (DHCP/DNS churn picks itself up).
  71. """
  72. if not target:
  73. return None
  74. try:
  75. return str(ipaddress.IPv4Address(target))
  76. except (ValueError, ipaddress.AddressValueError):
  77. pass
  78. try:
  79. # AF_INET filters to IPv4 only; the rewrite field is uint32 LE,
  80. # there's no IPv6 representation that fits.
  81. infos = socket.getaddrinfo(target, None, family=socket.AF_INET)
  82. except OSError:
  83. return None
  84. for info in infos:
  85. sockaddr = info[4]
  86. if sockaddr and isinstance(sockaddr[0], str):
  87. return sockaddr[0]
  88. return None
  89. def _resolve_host_interface_for_target(target_ip: str) -> str | None:
  90. """Pick a host-side IPv4 for `net.info[].ip` when the VP has no dedicated bind IP.
  91. Used when `mqtt_server.bind_address` is empty or 0.0.0.0 — the listener
  92. accepts on every interface but we still need ONE concrete IPv4 to write
  93. into the rewritten `net.info[].ip` field so the slicer's FTP target
  94. resolves to Bambuddy rather than the real printer. Returns the IPv4 of
  95. the host interface that shares a subnet with the printer (best fit
  96. because the slicer is typically on the same LAN as the printer), or
  97. None if no interface matches — in which case the bridge leaves
  98. encoding unarmed and the previous (still-leaky) behaviour stands.
  99. """
  100. try:
  101. from backend.app.services.network_utils import find_interface_for_ip
  102. except Exception: # pragma: no cover - import shielding
  103. return None
  104. try:
  105. iface = find_interface_for_ip(target_ip)
  106. except Exception:
  107. logger.exception("MQTT bridge: find_interface_for_ip(%s) crashed", target_ip)
  108. return None
  109. if not iface:
  110. return None
  111. ip = iface.get("ip")
  112. return ip if isinstance(ip, str) and ip else None
  113. def _merge_ams_dict(prev_ams: dict, new_ams: dict) -> dict:
  114. """Merge a new ``ams`` blob from an incremental push onto the previous one.
  115. Bambu firmware sends three shapes for the ``ams`` field on push_status:
  116. 1. Full pushall (after a printer reconnect or explicit pushall request):
  117. ``{ams: [{id, tray: [{id, tray_type, ...}, ...]}, ...], ams_status, ams_exist_bits, ...}``
  118. — every unit + every tray populated.
  119. 2. Status-only incremental: ``{ams_status: 1}`` or ``{humidity: 30}`` —
  120. no ``ams`` array at all. Bambuddy logs these as "AMS partial update
  121. (no tray data)" (#784 vintage).
  122. 3. Tray-targeted incremental during a print: ``{ams: [{id: 0, tray:
  123. [{id: 0, state: 11}]}]}`` — only the units / trays whose state
  124. changed.
  125. Replacing the cached ``ams`` wholesale on shapes (2) and (3) is what
  126. made the slicer "lose" AMS between pushalls and trip the symptom in
  127. #1387: the slicer would see a stripped ``ams_status``-only blob and
  128. fall back to its "no AMS" default render. This merge mirrors the
  129. deep-merge logic in ``bambu_mqtt.py::_handle_ams_data`` at the bridge
  130. layer so the slicer-facing cache always carries the latest known
  131. coherent state.
  132. Strategy:
  133. - Shallow-merge top-level scalars: keys in ``new`` win; keys only
  134. in ``prev`` are preserved.
  135. - For the ``ams`` array (list of units): match by ``id``. Units
  136. only in ``prev`` survive. Units in ``new`` overlay onto their
  137. ``prev`` counterpart; same recursion applies to each unit's
  138. ``tray`` array by tray ``id``.
  139. """
  140. merged = dict(prev_ams)
  141. for k, v in new_ams.items():
  142. if k != "ams":
  143. merged[k] = v
  144. prev_units = prev_ams.get("ams") if isinstance(prev_ams.get("ams"), list) else []
  145. new_units = new_ams.get("ams") if isinstance(new_ams.get("ams"), list) else None
  146. if new_units is None:
  147. # Shape (2): no ``ams`` array in the incremental — keep prev's units.
  148. if prev_units:
  149. merged["ams"] = prev_units
  150. return merged
  151. prev_by_id = {u.get("id"): u for u in prev_units if isinstance(u, dict) and u.get("id") is not None}
  152. merged_units: list = []
  153. seen_ids: set = set()
  154. for new_unit in new_units:
  155. if not isinstance(new_unit, dict):
  156. merged_units.append(new_unit)
  157. continue
  158. uid = new_unit.get("id")
  159. prev_unit = prev_by_id.get(uid) if uid is not None else None
  160. if prev_unit is None:
  161. merged_units.append(new_unit)
  162. if uid is not None:
  163. seen_ids.add(uid)
  164. continue
  165. # Shallow-merge unit fields; preserve prev's trays not present in new.
  166. merged_unit = dict(prev_unit)
  167. for k, v in new_unit.items():
  168. if k != "tray":
  169. merged_unit[k] = v
  170. new_trays = new_unit.get("tray") if isinstance(new_unit.get("tray"), list) else None
  171. if new_trays is None:
  172. # Unit-level partial — keep prev's tray list intact.
  173. pass
  174. else:
  175. prev_trays = prev_unit.get("tray") if isinstance(prev_unit.get("tray"), list) else []
  176. prev_trays_by_id = {t.get("id"): t for t in prev_trays if isinstance(t, dict) and t.get("id") is not None}
  177. merged_trays: list = []
  178. seen_tray_ids: set = set()
  179. for new_tray in new_trays:
  180. if not isinstance(new_tray, dict):
  181. merged_trays.append(new_tray)
  182. continue
  183. tid = new_tray.get("id")
  184. prev_tray = prev_trays_by_id.get(tid) if tid is not None else None
  185. if prev_tray is None:
  186. merged_trays.append(new_tray)
  187. else:
  188. merged_tray = dict(prev_tray)
  189. merged_tray.update(new_tray)
  190. merged_trays.append(merged_tray)
  191. if tid is not None:
  192. seen_tray_ids.add(tid)
  193. # Preserve prev trays not mentioned in the incremental.
  194. for tid, prev_tray in prev_trays_by_id.items():
  195. if tid not in seen_tray_ids:
  196. merged_trays.append(prev_tray)
  197. merged_unit["tray"] = merged_trays
  198. merged_units.append(merged_unit)
  199. if uid is not None:
  200. seen_ids.add(uid)
  201. # Preserve prev units not mentioned in the incremental.
  202. for uid, prev_unit in prev_by_id.items():
  203. if uid not in seen_ids:
  204. merged_units.append(prev_unit)
  205. merged["ams"] = merged_units
  206. return merged
  207. class MQTTBridge:
  208. """Per-VP MQTT fan-out between a real printer and slicers connected to a VP."""
  209. def __init__(
  210. self,
  211. *,
  212. vp_id: int,
  213. vp_name: str,
  214. vp_serial: str,
  215. target_printer_id: int,
  216. mqtt_server: SimpleMQTTServer,
  217. printer_manager: PrinterManager,
  218. ):
  219. self.vp_id = vp_id
  220. self.vp_name = vp_name
  221. self.vp_serial = vp_serial
  222. self.target_printer_id = target_printer_id
  223. self._mqtt_server = mqtt_server
  224. self._printer_manager = printer_manager
  225. self._target_client: BambuMQTTClient | None = None
  226. self._target_serial: str | None = None
  227. self._target_ip_uint32_le: int | None = None
  228. self._vp_ip_uint32_le: int | None = None
  229. # Last reason `_refresh_ip_encoding` early-returned without arming.
  230. # Used to throttle the "NOT armed" diagnostic log to one line per
  231. # state change — refresh runs every 30s, so without throttling an
  232. # idle-but-unarmed bridge would emit one line per tick forever. Set
  233. # to None once arming succeeds so the next failure re-logs. #1429
  234. # follow-up: makes silent early-returns visible without grepping the
  235. # source.
  236. self._not_armed_reason: str | None = None
  237. self._loop: asyncio.AbstractEventLoop | None = None
  238. self._refresh_task: asyncio.Task | None = None
  239. self._stopping = False
  240. self._latest_print_state: dict | None = None
  241. self._latest_version_modules: list | None = None
  242. @property
  243. def is_active(self) -> bool:
  244. """True iff a target client is bound and currently connected."""
  245. client = self._target_client
  246. return bool(client is not None and getattr(client, "state", None) and client.state.connected)
  247. async def start(self) -> None:
  248. """Bind to the target printer (if connected) and start the refresh loop."""
  249. self._loop = asyncio.get_running_loop()
  250. self._stopping = False
  251. self._resolve_client()
  252. self._refresh_task = asyncio.create_task(self._refresh_loop())
  253. async def stop(self) -> None:
  254. """Detach from the target printer and stop the refresh loop."""
  255. self._stopping = True
  256. if self._refresh_task is not None:
  257. self._refresh_task.cancel()
  258. try:
  259. await self._refresh_task
  260. except asyncio.CancelledError:
  261. pass
  262. self._refresh_task = None
  263. self._unbind_client()
  264. self._loop = None
  265. async def _refresh_loop(self) -> None:
  266. """Re-resolve the target client periodically — paho clients can be replaced.
  267. BambuMQTTClient is destroyed and recreated on PrinterManager.connect_printer
  268. (e.g. printer config update). Without periodic refresh the bridge would lose
  269. fan-out after such a churn until the VP itself restarts.
  270. On crash exit, the handler must be unbound — otherwise the registered
  271. ``_on_printer_raw`` keeps firing on every real-printer message even
  272. though the bridge is functionally dead (memory leak + behaviour leak
  273. across VP restart).
  274. """
  275. try:
  276. while not self._stopping:
  277. await asyncio.sleep(REFRESH_INTERVAL_SECONDS)
  278. self._resolve_client()
  279. except asyncio.CancelledError:
  280. raise
  281. except Exception:
  282. logger.exception("[%s] MQTT bridge refresh loop crashed", self.vp_name)
  283. # Crash exit — unbind so the orphaned handler stops firing.
  284. # ``stop()`` won't be invoked because the task completes done-not-cancelled.
  285. self._unbind_client()
  286. def _resolve_client(self) -> None:
  287. """Look up the current client for target_printer_id and rebind if it changed."""
  288. try:
  289. current = self._printer_manager.get_client(self.target_printer_id)
  290. except Exception:
  291. logger.exception("[%s] MQTT bridge: get_client failed", self.vp_name)
  292. return
  293. if current is self._target_client:
  294. # Same client object — but `ip_address` can fill in *after* the
  295. # initial bind (e.g. DB row had a stale/empty value until the
  296. # client's first SSDP-driven IP refresh). The original code only
  297. # encoded `_target_ip_uint32_le` on client-identity change, so
  298. # that late-arriving IP was never picked up, the `net.info[*].ip`
  299. # rewrite stayed disabled, and the cache filled with the real
  300. # printer IP — #1429. Refresh the encoding every tick so it
  301. # self-heals once `ip_address` becomes valid.
  302. self._refresh_ip_encoding()
  303. return
  304. # Client identity changed — unregister from the old, register on the new.
  305. self._unbind_client()
  306. if current is None:
  307. return
  308. try:
  309. current.register_raw_message_handler(self._on_printer_raw)
  310. except Exception:
  311. logger.exception("[%s] MQTT bridge: register_raw_message_handler failed", self.vp_name)
  312. return
  313. self._target_client = current
  314. self._target_serial = getattr(current, "serial_number", None)
  315. self._refresh_ip_encoding()
  316. logger.info(
  317. "[%s] MQTT bridge bound to printer %s (serial=%s)",
  318. self.vp_name,
  319. self.target_printer_id,
  320. self._target_serial,
  321. )
  322. # Trigger a fresh get_version + pushall against the printer so the bridge
  323. # cache populates immediately. Bambuddy itself queries these on connect,
  324. # but that fires before the bridge attaches as a raw-message consumer,
  325. # so without this nudge the cache stays empty until the next periodic
  326. # query (which can be minutes away).
  327. request_fn = getattr(current, "_request_version", None)
  328. if callable(request_fn):
  329. try:
  330. request_fn()
  331. except Exception:
  332. logger.exception("[%s] MQTT bridge: _request_version failed", self.vp_name)
  333. request_status_fn = getattr(current, "request_status_update", None)
  334. if callable(request_status_fn):
  335. try:
  336. request_status_fn()
  337. except Exception:
  338. logger.exception("[%s] MQTT bridge: request_status_update failed", self.vp_name)
  339. def _unbind_client(self) -> None:
  340. if self._target_client is None:
  341. return
  342. try:
  343. self._target_client.unregister_raw_message_handler(self._on_printer_raw)
  344. except Exception:
  345. logger.exception("[%s] MQTT bridge: unregister_raw_message_handler failed", self.vp_name)
  346. logger.info("[%s] MQTT bridge unbound from printer %s", self.vp_name, self.target_printer_id)
  347. self._target_client = None
  348. self._target_serial = None
  349. def _refresh_ip_encoding(self) -> None:
  350. """(Re-)encode `_target_ip_uint32_le` / `_vp_ip_uint32_le` from current values.
  351. Called on every refresh tick, not just on client-identity change, so
  352. a late-arriving printer IP (or a bind-address change) is picked up
  353. without restarting the VP. When the encoding becomes valid for the
  354. first time *after* the cache already received a push with the real
  355. printer IP, also sweep the existing cache so the slicer's next pull
  356. sees the rewritten value (#1429). Without this sweep the sticky-key
  357. preservation keeps the poisoned `net.info[].ip` alive forever.
  358. VP bind IP resolution: when `mqtt_server.bind_address` is empty or
  359. `0.0.0.0` (the default for VPs that were never assigned a dedicated
  360. bind IP), fall back to auto-resolving the host interface in the same
  361. subnet as the printer's IP. Without this fallback, the rewrite never
  362. arms on a default-config flat-LAN install and `net.info[].ip` leaks
  363. the real printer IP — slicer follows it on Send (#1429 residual).
  364. """
  365. def _log_not_armed(reason: str) -> None:
  366. # Throttle: only log when the reason changes, otherwise an idle
  367. # unarmed bridge would emit one INFO line every refresh tick
  368. # (~30s) forever. Cleared on arm so a regression re-logs.
  369. if reason != self._not_armed_reason:
  370. logger.info("[%s] MQTT bridge IP encoding NOT armed: %s", self.vp_name, reason)
  371. self._not_armed_reason = reason
  372. client = self._target_client
  373. if client is None:
  374. _log_not_armed("target_client is None (bridge not bound to a printer)")
  375. return
  376. configured_target = getattr(client, "ip_address", None)
  377. if not configured_target:
  378. _log_not_armed("printer client has no ip_address yet")
  379. return
  380. # Printers configured by hostname/FQDN (e.g. `p1s.fritz.box`) need to
  381. # be resolved to an IPv4 before encoding: net.info[*].ip is uint32 LE
  382. # and can't carry a hostname (#1429 follow-up).
  383. target_ip = _resolve_target_to_ipv4(configured_target)
  384. if not target_ip:
  385. _log_not_armed(
  386. f"could not resolve printer host {configured_target!r} to IPv4 (invalid address and DNS lookup failed)"
  387. )
  388. return
  389. vp_ip = getattr(self._mqtt_server, "bind_address", None)
  390. vp_ip_source = "bind_address"
  391. if not vp_ip or vp_ip in ("0.0.0.0", ""): # nosec B104
  392. resolved = _resolve_host_interface_for_target(target_ip)
  393. if not resolved:
  394. _log_not_armed(
  395. f"no host interface shares a subnet with printer IP {target_ip} "
  396. "(and VP bind_address is 0.0.0.0/empty)"
  397. )
  398. return
  399. vp_ip = resolved
  400. vp_ip_source = "auto-resolved"
  401. try:
  402. new_target_le = _ip_to_uint32_le(target_ip)
  403. new_vp_le = _ip_to_uint32_le(vp_ip)
  404. except ValueError as e:
  405. _log_not_armed(f"invalid IPv4 (target={target_ip!r}, vp={vp_ip!r}): {e}")
  406. return
  407. if new_target_le == self._target_ip_uint32_le and new_vp_le == self._vp_ip_uint32_le:
  408. return # No change — nothing to do.
  409. # Encoding either became valid for the first time or shifted (DHCP
  410. # renewal, bind_ip reconfigured, etc.). Update + sweep the cache.
  411. was_armed = self._target_ip_uint32_le is not None and self._vp_ip_uint32_le is not None
  412. self._target_ip_uint32_le = new_target_le
  413. self._vp_ip_uint32_le = new_vp_le
  414. # Clear the dedup so a future failure re-emits the diagnostic line.
  415. self._not_armed_reason = None
  416. target_display = target_ip if target_ip == configured_target else f"{configured_target}→{target_ip}"
  417. logger.info(
  418. "[%s] MQTT bridge IP encoding %s: target=%s vp=%s (%s)",
  419. self.vp_name,
  420. "updated" if was_armed else "armed",
  421. target_display,
  422. vp_ip,
  423. vp_ip_source,
  424. )
  425. cached = self._latest_print_state
  426. if isinstance(cached, dict):
  427. n = self._rewrite_net_info_ips(cached)
  428. if n:
  429. logger.info(
  430. "[%s] MQTT bridge swept %d net.info[].ip entries in cached push",
  431. self.vp_name,
  432. n,
  433. )
  434. def _rewrite_net_info_ips(self, print_state: dict) -> int:
  435. """Rewrite every non-zero `net.info[].ip` in `print_state` to the VP bind IP.
  436. Returns the number of entries rewritten. Mutates `print_state` in place.
  437. Strategy: rewrite ALL entries with a non-zero `ip`, not only those
  438. matching `_target_ip_uint32_le`. Real printers (X1C, H2D Pro) can
  439. report multiple active interfaces (WiFi + Ethernet) with different
  440. IPs — only one matches the IP Bambuddy tracks, but the slicer may
  441. read any of them. Leaving non-matching entries pointing at real
  442. printer interfaces leaks an FTP fallback path that bypasses the VP
  443. (the #1429 / #1302 symptom). Entries with `ip == 0` are placeholders
  444. for unpopulated interfaces — leave them alone so the slicer's
  445. "active interface" detection still recognises them as absent.
  446. """
  447. if self._vp_ip_uint32_le is None:
  448. return 0
  449. net = print_state.get("net")
  450. if not isinstance(net, dict):
  451. return 0
  452. info = net.get("info")
  453. if not isinstance(info, list):
  454. return 0
  455. rewritten = 0
  456. for entry in info:
  457. if not isinstance(entry, dict):
  458. continue
  459. ip_value = entry.get("ip")
  460. if not isinstance(ip_value, int) or ip_value == 0:
  461. continue
  462. if ip_value == self._vp_ip_uint32_le:
  463. continue
  464. entry["ip"] = self._vp_ip_uint32_le
  465. rewritten += 1
  466. return rewritten
  467. def _on_printer_raw(self, topic: str, payload: bytes) -> None:
  468. """Paho-thread callback — cache the latest push_status for synthetic replay.
  469. Instead of fanning out a second stream of MQTT messages to the slicer
  470. (which trips BambuStudio's Send pre-flight consistency checks), we cache
  471. the latest real printer push_status here. The VP's existing 1 Hz
  472. synthetic push (which is what Send is built around) consults this cache
  473. and replaces its stub fields with real values when available.
  474. """
  475. if self._stopping:
  476. return
  477. target_serial = self._target_serial
  478. if not target_serial:
  479. return
  480. prefix = f"device/{target_serial}/"
  481. if not topic.startswith(prefix):
  482. return
  483. suffix = topic[len(prefix) :]
  484. if not suffix.startswith("report"):
  485. return
  486. try:
  487. data = json.loads(payload)
  488. except json.JSONDecodeError:
  489. return
  490. # Race-free by construction: `json.loads` returns a fresh dict tree per
  491. # call so paho-thread mutations below cannot collide with prior cached
  492. # state held by the asyncio thread. `_send_status_report`'s shallow
  493. # `dict(cached)` is also safe because nothing else writes to the cached
  494. # tree after assignment. The defensive deep-copy on store below removes
  495. # any future risk if a maintainer later re-enters the cached dict to
  496. # mutate it.
  497. # push_status snapshots → cache the print dict for the periodic 1 Hz
  498. # cached-as-base delivery. We do NOT fan these out separately (the
  499. # 1 Hz cached-as-base IS the slicer-facing push_status stream).
  500. print_data = data.get("print")
  501. if isinstance(print_data, dict) and print_data.get("command") == "push_status":
  502. for value in print_data.values():
  503. if isinstance(value, dict) and value.get("sn") == target_serial:
  504. value["sn"] = self.vp_serial
  505. # Note: `ipcam.rtsp_url` carries the real printer's IP. We pass it
  506. # through unchanged — the slicer uses it to fetch the live camera
  507. # stream directly from the printer. On the same LAN this works as
  508. # long as the slicer's stored access code matches the printer's
  509. # (i.e. configure the VP with the same access code as its target).
  510. # Rewrite real printer IP → VP bind IP in `net.info[*].ip` so the
  511. # slicer's FTP destination resolves to the VP, not the real printer.
  512. self._rewrite_net_info_ips(print_data)
  513. # Defensive deep copy on store so the cache is fully decoupled from
  514. # the freshly-parsed tree and from any reader's reference.
  515. new_state = copy.deepcopy(print_data)
  516. # Bambu firmware sends two kinds of push_status: full pushall
  517. # responses (on `pushall` requests / printer reconnect) which
  518. # include the full top-level field set (AMS, vt_tray, net,
  519. # cali_version, print_type, mc_print_stage, device, ...) — and
  520. # ~1 Hz incrementals with just the fields that changed (temps,
  521. # fan, wifi, status). Carry over every prev field the incoming
  522. # push doesn't overwrite, mirroring the per-field accumulate
  523. # pattern in bambu_mqtt.py's internal state handler — without
  524. # this the cache thins out to whatever the latest incremental
  525. # carried (~17 keys on P1S in #1622), and the slicer's Device-
  526. # tab capability gates (manage-calibration, AMS-assign dropdown,
  527. # …) flip off because their gating fields drained from the
  528. # cache. The deep-copy is defensive: without it the carried-
  529. # over nested dicts/lists are shared with the previous cache,
  530. # so any in-place mutation later would corrupt both.
  531. prev = self._latest_print_state
  532. if prev is not None:
  533. for prev_key, prev_value in prev.items():
  534. if prev_key not in new_state:
  535. new_state[prev_key] = copy.deepcopy(prev_value)
  536. # Firmware sends partial `ams` blobs (status-only / unit-
  537. # targeted / tray-targeted) under the same key on
  538. # incremental updates, which would overwrite the cached
  539. # full blob and break the slicer's AMS render (#1387 /
  540. # #1371). Deep-merge mirrors what bambu_mqtt.py does
  541. # internally in `_handle_ams_data`.
  542. if isinstance(new_state.get("ams"), dict) and isinstance(prev.get("ams"), dict):
  543. new_state["ams"] = _merge_ams_dict(prev["ams"], new_state["ams"])
  544. # Same per-field accumulate rule applied one level deeper for
  545. # other top-level dict-shaped fields. Firmware sends partial
  546. # `vt_tray` (external spool) updates right after a slicer
  547. # `ams_filament_setting` pick — typically just `{tray_info_idx,
  548. # tray_color}`, dropping the ~18 other fields (`tray_type`,
  549. # `state`, `remain`, `k`, `n`, `cali_idx`, `nozzle_temp_min/max`,
  550. # `tray_uuid`, `xcam_info`, ...) the slicer needs to render the
  551. # slot. Without overlay the next 1 Hz cached-as-base push
  552. # delivered the stripped dict and the slicer rendered the
  553. # external slot as "invalid" until a reload triggered a fresh
  554. # pushall (#1622 round 5, reported by @shaddowlink). AMS slots
  555. # didn't suffer because `_merge_ams_dict` deep-merges per tray.
  556. # Same shape covers `device`, `online`, `upgrade_state`, `ipcam`,
  557. # `upload`, `net`, ... against future firmware partials too.
  558. # `ams` is excluded — already deep-merged above.
  559. for key, new_value in list(new_state.items()):
  560. if key == "ams":
  561. continue
  562. prev_value = prev.get(key)
  563. if isinstance(prev_value, dict) and isinstance(new_value, dict):
  564. merged = dict(prev_value)
  565. merged.update(new_value)
  566. new_state[key] = merged
  567. self._latest_print_state = new_state
  568. dump_wire(self.vp_name, "in", new_state)
  569. return
  570. # info.get_version responses → cache the module list so the synthetic
  571. # version response can include the real AMS modules.
  572. info_data = data.get("info")
  573. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  574. modules = info_data.get("module")
  575. if isinstance(modules, list):
  576. rewritten: list = []
  577. for module in modules:
  578. if isinstance(module, dict):
  579. module = dict(module)
  580. if module.get("sn") == target_serial:
  581. module["sn"] = self.vp_serial
  582. rewritten.append(module)
  583. self._latest_version_modules = rewritten
  584. # Don't fan out get_version — the slicer's request (when it issues
  585. # one) is intercepted locally and answered from the cached modules.
  586. return
  587. # Everything else (extrusion_cali_get response, AMS write acks, xcam
  588. # responses, …): fan out to the slicer. These are responses to commands
  589. # the slicer (or Bambuddy) issued; the slicer matches by sequence_id and
  590. # ignores responses to commands it didn't send. Without this, slicer-
  591. # initiated queries like extrusion_cali_get hang forever and BambuStudio
  592. # blocks Send waiting for the response.
  593. loop = self._loop
  594. if loop is None:
  595. return
  596. target_bytes = target_serial.encode("ascii")
  597. if target_bytes in payload:
  598. payload = payload.replace(target_bytes, self.vp_serial.encode("ascii"))
  599. vp_topic = f"device/{self.vp_serial}/{suffix}"
  600. # Env-flagged command trace (#1622): every printer-originated response
  601. # that gets fanned to the slicer (extrusion_cali_get / ams write acks /
  602. # xcam / system / etc.) gets a line in vp_wire/<vp>_cmd.jsonl. Pair
  603. # with the slicer-side publishes captured in mqtt_server. Off by
  604. # default. Capture AFTER serial rewrite so the dump matches what the
  605. # slicer actually sees on the wire.
  606. append_event(self.vp_name, "printer_to_slicer", vp_topic, payload)
  607. try:
  608. asyncio.run_coroutine_threadsafe(
  609. self._mqtt_server.push_raw_to_clients(vp_topic, payload),
  610. loop,
  611. )
  612. except RuntimeError:
  613. pass
  614. def get_latest_print_state(self) -> dict | None:
  615. """Return the most recent real printer push_status `print` dict, or None."""
  616. return self._latest_print_state
  617. def get_latest_version_modules(self) -> list | None:
  618. """Return the most recent real printer get_version `module` list, or None."""
  619. return self._latest_version_modules
  620. def forward_to_printer(self, payload: dict) -> bool:
  621. """Publish a slicer-originated command to the real printer's request topic.
  622. Returns False if no printer client is currently bound.
  623. """
  624. client = self._target_client
  625. target_serial = self._target_serial
  626. if client is None or target_serial is None:
  627. logger.debug(
  628. "[%s] forward_to_printer dropped (printer %s not bound): %s",
  629. self.vp_name,
  630. self.target_printer_id,
  631. list(payload.keys()),
  632. )
  633. return False
  634. topic = f"device/{target_serial}/request"
  635. try:
  636. return client.publish_raw(topic, json.dumps(payload), qos=1)
  637. except Exception:
  638. logger.exception("[%s] forward_to_printer publish failed", self.vp_name)
  639. return False