mqtt_bridge.py 32 KB

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