mqtt_bridge.py 38 KB

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