printer_diagnostic.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. """Connection diagnostic for Bambu printers.
  2. Runs the checks a maintainer performs by hand when triaging a
  3. "printer won't connect / won't print" report — port reachability, LAN
  4. developer mode, container network mode, subnet match, and MQTT credentials —
  5. so users can self-diagnose setup problems instead of opening an issue.
  6. See the 2026-05-21 issue-triage analysis: ~1/3 of closed issues were
  7. user-side setup errors clustered on exactly these causes.
  8. """
  9. import asyncio
  10. import ipaddress
  11. import logging
  12. import socket
  13. import ssl
  14. from pathlib import Path
  15. from backend.app.models.printer import Printer
  16. from backend.app.schemas.printer import DiagnosticCheck, PrinterDiagnosticResult
  17. from backend.app.services.bambu_ftp import find_remote_file_async
  18. from backend.app.services.bambu_mqtt import CONNECT_ERROR_AUTH_REJECTED
  19. from backend.app.services.camera import get_camera_port
  20. from backend.app.services.discovery import OCI_RUNTIMES, detect_container_runtime
  21. from backend.app.services.ftp_profiles import get_ftp_profile
  22. from backend.app.services.network_utils import find_local_ipv4_network
  23. from backend.app.services.print_storage import (
  24. REASON_INTERNAL_STORAGE,
  25. StorageVerdict,
  26. ftp_probe_paths,
  27. last_print_storage_verdict,
  28. )
  29. from backend.app.services.printer_manager import printer_manager
  30. from backend.app.utils.printer_models import has_external_storage, has_remote_storage_toggle
  31. logger = logging.getLogger(__name__)
  32. # Bambu LAN-mode ports.
  33. PORT_MQTT = 8883 # MQTT over TLS — control + status. Connection-critical.
  34. PORT_FTPS = 990 # FTPS — file upload; required to send prints.
  35. PORT_RTSPS = 322 # RTSPS — camera stream; optional.
  36. PORT_CHAMBER_IMAGE = 6000 # Chamber image protocol — A1/P1 camera stream; optional.
  37. _PORT_PROBE_TIMEOUT = 3.0
  38. # Cap for the storage probe (#2856). One connection and a handful of directory
  39. # listings, so a healthy printer answers in well under a second. Kept short on
  40. # purpose: this check sits inside the support bundle's 15s-per-printer budget,
  41. # and in the interactive run it is spinner time the user is watching.
  42. _STORAGE_PROBE_TIMEOUT = 6.0
  43. # Default seconds the `printer_publishing` check will wait for the first
  44. # report-topic message before declaring fail. Bambu printers in idle publish
  45. # push_status every few seconds; 10s catches healthy bridges with margin while
  46. # staying short enough that the spinner-with-countdown UX stays acceptable.
  47. # The check exits the moment a message arrives, so the typical wall-clock is
  48. # 1–2s, not the full 10. Passed as ``wait_for_publish_seconds`` per call so
  49. # the support-package code path can skip the wait entirely (defaults to 0).
  50. PUBLISH_WAIT_DEFAULT = 10.0
  51. _PUBLISH_POLL_INTERVAL = 0.5
  52. async def _check_port(ip: str, port: int, timeout: float = _PORT_PROBE_TIMEOUT) -> bool:
  53. """Test TCP connectivity to ip:port. Returns True if reachable."""
  54. try:
  55. _reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, port), timeout=timeout)
  56. writer.close()
  57. try:
  58. await writer.wait_closed()
  59. except Exception:
  60. pass
  61. return True
  62. except Exception:
  63. return False
  64. # Public alias. The connection watchdog probes the MQTT port before rebuilding a
  65. # client, so it can tell "the printer is switched off" (leave it alone, paho will
  66. # keep retrying) from "the printer is answering but our session is dead" (#2732).
  67. check_port = _check_port
  68. async def _check_ftps_tls(ip: str, model: str | None, timeout: float = _PORT_PROBE_TIMEOUT) -> str:
  69. """Probe port 990 the way the FTP client does, and say how far it got.
  70. Returns ``"ok"``, ``"closed"`` (nothing accepted the TCP connection) or
  71. ``"no_tls"`` (the port accepted the connection but the TLS handshake did
  72. not complete).
  73. A plain TCP probe cannot tell the last two apart, which is exactly how
  74. #2780 hid: the reporter's diagnostic reported port 990 as reachable and
  75. green while every real transfer died in the handshake with
  76. ``WRONG_VERSION_NUMBER``, so archives quietly arrived empty with nothing
  77. on screen to explain it.
  78. The context mirrors :class:`~backend.app.services.bambu_ftp.ImplicitFTP_TLS`
  79. -- including the model's TLS cap -- so a pass here means the FTP client
  80. would also get through. Handshake only; no login is attempted, so this
  81. stays valid for the pre-save Add-Printer flow where no access code exists
  82. yet.
  83. """
  84. context = ssl.create_default_context()
  85. context.check_hostname = False
  86. context.verify_mode = ssl.CERT_NONE
  87. context.minimum_version = ssl.TLSVersion.TLSv1_2
  88. if get_ftp_profile(model).cap_tls_v1_2:
  89. context.maximum_version = ssl.TLSVersion.TLSv1_2
  90. writer = None
  91. try:
  92. _reader, writer = await asyncio.wait_for(
  93. asyncio.open_connection(ip, PORT_FTPS, ssl=context),
  94. timeout=timeout,
  95. )
  96. return "ok"
  97. except ssl.SSLError:
  98. # The socket was accepted and then failed to negotiate TLS. Reaching
  99. # here at all proves something is listening, so this is never "port
  100. # blocked" -- it is the printer's file service in a state no retry
  101. # gets past.
  102. return "no_tls"
  103. except Exception:
  104. return "closed"
  105. finally:
  106. if writer is not None:
  107. writer.close()
  108. try:
  109. await writer.wait_closed()
  110. except Exception:
  111. pass
  112. async def _last_print_file_is_reachable(
  113. printer: Printer | None,
  114. verdict: StorageVerdict,
  115. *,
  116. ftps_ok: bool,
  117. ) -> bool:
  118. """Did the last print's file turn up on external storage after all? (#2856)
  119. ``verdict`` is read off the dispatch URL, which says where the printer
  120. *put* the file, not whether port 990 can serve it: an H2D with a card in
  121. the slot reports ``brtc://emmc/<name>`` and then hands the same file over
  122. from ``/cache`` without complaint. Warning that the file is out of reach
  123. while that user's archives are quietly complete would send them chasing a
  124. setting that is already right.
  125. So check before saying it -- one connection, one listing per candidate
  126. directory, no transfer, and only for the check that is about to warn.
  127. "Could not check" returns False and leaves the warning standing, which is
  128. the safe direction: it is a warn, not a fail.
  129. """
  130. if not ftps_ok or not verdict.probe_filename or printer is None:
  131. return False
  132. # Attribute reads inside the guard too: this also runs from the support
  133. # bundle, where the row may outlive its session, and a detached-instance
  134. # error there is "could not check", not a broken diagnostic.
  135. ip_address = None
  136. try:
  137. ip_address = getattr(printer, "ip_address", None)
  138. access_code = getattr(printer, "access_code", None)
  139. if not ip_address or not access_code:
  140. return False
  141. found = await find_remote_file_async(
  142. ip_address,
  143. access_code,
  144. ftp_probe_paths(verdict.probe_filename),
  145. timeout=_STORAGE_PROBE_TIMEOUT,
  146. socket_timeout=_STORAGE_PROBE_TIMEOUT,
  147. printer_model=getattr(printer, "model", None),
  148. )
  149. except Exception as e:
  150. logger.debug("Could not probe %s for %s: %s", ip_address, verdict.probe_filename, e)
  151. return False
  152. if found:
  153. logger.debug("Last print file is on external storage at %s despite %s", found, verdict.reason)
  154. return found is not None
  155. def _auth_reason_params(reason: str | None) -> dict:
  156. """Map a client's CONNACK-refusal slug onto the check's `params.reason`.
  157. The frontend renders `diagnostic.check.<id>.<status>_<reason>` when a reason
  158. is present and falls back to the plain per-status text otherwise, so an
  159. unknown or absent slug degrades to today's generic wording rather than a
  160. missing string. Only `auth_rejected` currently carries its own message:
  161. that is the one case where the printer positively told us the credentials
  162. were wrong, as opposed to us merely observing that we are not connected.
  163. """
  164. if reason == CONNECT_ERROR_AUTH_REJECTED:
  165. return {"reason": CONNECT_ERROR_AUTH_REJECTED}
  166. return {}
  167. def _camera_port_for_printer(printer: Printer | None) -> tuple[int, str]:
  168. """Return the model-specific camera diagnostic port and display protocol."""
  169. if not printer:
  170. return PORT_RTSPS, "RTSPS"
  171. model = getattr(printer, "model", None)
  172. if not model:
  173. return PORT_RTSPS, "RTSPS"
  174. camera_port = get_camera_port(model)
  175. if camera_port == PORT_CHAMBER_IMAGE:
  176. return camera_port, "Chamber Image"
  177. return camera_port, "RTSPS"
  178. # Interfaces a container engine creates on the *host*. Seeing one of them
  179. # means we are in the host's network namespace.
  180. _HOST_INFRA_PREFIXES = ("docker", "br-", "veth", "virbr", "podman", "cni-", "cni_")
  181. def _has_native_interface() -> bool:
  182. """True if some interface here was created in this network namespace.
  183. A NAT-networked container is handed one end of a veth pair per attached
  184. network, and a veth's ``iflink`` points at its peer's index in the *other*
  185. namespace, so it never equals its own ``ifindex``. An interface where the
  186. two agree was made here — a physical NIC, a bridge, a VLAN — which a
  187. container with its own namespace does not get.
  188. tun/tap devices are skipped: a container can legitimately run its own
  189. WireGuard or Tailscale client, and that tun would otherwise read as
  190. evidence of a namespace it is not evidence of.
  191. """
  192. try:
  193. entries = [(idx, name) for idx, name in socket.if_nameindex() if name != "lo"]
  194. except Exception:
  195. return False
  196. for index, name in entries:
  197. # Never user input: the kernel's own interface table, and never a path.
  198. iface = Path("/sys/class/net") / name # SEC-PATH-OK: name from socket.if_nameindex()
  199. if (iface / "tun_flags").exists():
  200. continue
  201. try:
  202. ifindex = (iface / "ifindex").read_text().strip()
  203. iflink = (iface / "iflink").read_text().strip()
  204. except (OSError, ValueError):
  205. continue
  206. # sysfs is tagged by network namespace, but a container given a bind
  207. # mount of the host's /sys sees the host's interfaces under names that
  208. # may collide with its own. Reading a different interface's numbers
  209. # would be reading another namespace's answer, so require that the
  210. # entry found here is the one the kernel just named.
  211. if ifindex != str(index):
  212. continue
  213. if ifindex == iflink:
  214. return True
  215. return False
  216. def _detect_container_network_mode(runtime: str | None) -> str | None:
  217. """Return "host", "bridge", or None when it genuinely cannot be told.
  218. The first rule is the original Docker one and is kept exactly: a Docker
  219. *host* always has a docker0, so a container that can see it shares the
  220. host's namespace. It says nothing about Podman, which on a host running
  221. no bridge containers creates no such interface at all — which is how a
  222. host-networked Podman container came to be told it was on bridge
  223. networking (#3092).
  224. The second rule is the general form of the same idea and is what answers
  225. for Podman. The third is the fallback the first rule always implied: an
  226. OCI container that can see neither is isolated, which is what bridge
  227. networking means.
  228. """
  229. try:
  230. for _idx, name in socket.if_nameindex():
  231. if name.startswith(_HOST_INFRA_PREFIXES):
  232. return "host"
  233. except Exception:
  234. pass
  235. if _has_native_interface():
  236. return "host"
  237. if runtime in OCI_RUNTIMES:
  238. return "bridge"
  239. return None
  240. def _host_source_ip(destination_ip: str) -> str | None:
  241. """The local IPv4 address Bambuddy would send from toward ``destination_ip``.
  242. Asking about the printer's own address rather than a fixed far-away one
  243. matters on any host with more than one NIC: the source for a route to the
  244. internet is simply not the source for a route to the printer, and
  245. comparing the printer against the wrong interface is a warning about
  246. nothing (#3092).
  247. Literals only. ``connect()`` on a name would resolve it, and this runs on
  248. the event loop; ``_same_subnet`` rejects names anyway, so nothing is lost.
  249. """
  250. try:
  251. if ipaddress.ip_address(destination_ip).version != 4:
  252. return None
  253. except ValueError:
  254. return None
  255. try:
  256. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  257. try:
  258. # No packets are sent; this just picks the routing-table source IP.
  259. s.connect((destination_ip, 1))
  260. return s.getsockname()[0]
  261. finally:
  262. s.close()
  263. except Exception:
  264. # Fail soft: this is a diagnostic, and an unroutable address or an
  265. # exhausted fd table must leave the check skipped, not 500 the page.
  266. return None
  267. def _same_subnet(printer_ip: str, host_ip: str) -> bool | None:
  268. """Is ``printer_ip`` inside the network configured on Bambuddy's ``host_ip``?
  269. None means undeterminable — a name instead of an IPv4 literal, or no
  270. local interface claiming ``host_ip``.
  271. An address does not carry its prefix, and this used to supply ``/24`` for
  272. both sides. That is the most common LAN and not the only one: on the
  273. reporter's ``192.168.96.0/22`` it declared a printer four hundred
  274. addresses away to be on a different network and told him to go configure
  275. routing between two halves of one subnet (#3092). The prefix is read off
  276. the interface that owns the source address instead.
  277. """
  278. try:
  279. printer_addr = ipaddress.ip_address(printer_ip)
  280. host_addr = ipaddress.ip_address(host_ip)
  281. except ValueError:
  282. return None
  283. if printer_addr.version != 4 or host_addr.version != 4:
  284. return None
  285. network = find_local_ipv4_network(str(host_addr))
  286. if network is None:
  287. return None
  288. return printer_addr in network
  289. async def run_connection_diagnostic(
  290. ip_address: str,
  291. *,
  292. printer: Printer | None = None,
  293. serial_number: str | None = None,
  294. access_code: str | None = None,
  295. wait_for_publish_seconds: float = 0.0,
  296. ) -> PrinterDiagnosticResult:
  297. """Run connection checks for a printer.
  298. Works for an existing saved printer (pass ``printer``) and for the
  299. pre-save Add-Printer flow (pass ``serial_number`` + ``access_code``).
  300. Each check carries a stable ``id`` and a ``status`` of
  301. pass / fail / warn / skip; the frontend renders the human-readable
  302. title and fix text (localized) keyed on that id + status.
  303. """
  304. checks: list[DiagnosticCheck] = []
  305. # --- Port reachability (probed in parallel) ---
  306. camera_port, camera_protocol = _camera_port_for_printer(printer)
  307. mqtt_ok, ftps_state, camera_ok = await asyncio.gather(
  308. _check_port(ip_address, PORT_MQTT),
  309. _check_ftps_tls(ip_address, getattr(printer, "model", None) if printer else None),
  310. _check_port(ip_address, camera_port),
  311. )
  312. # MQTT is connection-critical; FTPS/camera only degrade printing/camera.
  313. checks.append(DiagnosticCheck(id="port_mqtt", status="pass" if mqtt_ok else "fail"))
  314. # "no_tls" gets its own message: the port is open, so the usual advice
  315. # (unblock port 990) is wrong and only a printer restart helps (#2780).
  316. checks.append(
  317. DiagnosticCheck(
  318. id="port_ftps",
  319. status="pass" if ftps_state == "ok" else "warn",
  320. params={} if ftps_state != "no_tls" else {"reason": "no_tls"},
  321. )
  322. )
  323. checks.append(
  324. DiagnosticCheck(
  325. id="port_rtsps",
  326. status="pass" if camera_ok else "warn",
  327. params={"port": camera_port, "protocol": camera_protocol},
  328. )
  329. )
  330. # --- Container network mode ---
  331. # Not Docker-only: Podman runs Bambuddy in exactly the same two shapes and
  332. # its users were told "Not running in Docker", which reads as "you are on
  333. # bare metal" and sent them looking for the problem somewhere else (#3092).
  334. runtime = detect_container_runtime()
  335. network_mode: str | None = None
  336. if runtime is None:
  337. checks.append(DiagnosticCheck(id="network_mode", status="skip"))
  338. elif runtime not in OCI_RUNTIMES:
  339. # An LXC/LXD system container is bridged onto the LAN like a small VM.
  340. # There is no network mode to recommend, so don't imply there is one.
  341. checks.append(
  342. DiagnosticCheck(id="network_mode", status="skip", params={"reason": "system_container", "runtime": runtime})
  343. )
  344. else:
  345. network_mode = _detect_container_network_mode(runtime)
  346. if network_mode is None:
  347. checks.append(
  348. DiagnosticCheck(id="network_mode", status="skip", params={"reason": "unknown", "runtime": runtime})
  349. )
  350. else:
  351. checks.append(
  352. DiagnosticCheck(
  353. id="network_mode",
  354. status="pass" if network_mode == "host" else "warn",
  355. params={"mode": network_mode, "runtime": runtime},
  356. )
  357. )
  358. # --- Subnet match ---
  359. # Skipped in bridge mode: the container IP is the bridge IP, not the host's,
  360. # so the comparison is meaningless and the network_mode check already covers it.
  361. if network_mode == "bridge":
  362. checks.append(DiagnosticCheck(id="subnet", status="skip"))
  363. else:
  364. host_ip = _host_source_ip(ip_address)
  365. # Off the loop: resolving the prefix shells out to `ip -j addr show`.
  366. same = await asyncio.to_thread(_same_subnet, ip_address, host_ip) if host_ip else None
  367. if same is None:
  368. checks.append(DiagnosticCheck(id="subnet", status="skip"))
  369. else:
  370. checks.append(
  371. DiagnosticCheck(
  372. id="subnet",
  373. status="pass" if same else "warn",
  374. params={"printer_ip": ip_address, "host_ip": host_ip},
  375. )
  376. )
  377. # --- External storage (printer-side "Store sent files on external storage") ---
  378. # Install step 4. The setting has two variants depending on
  379. # firmware/slicer combo: on newer firmware the toggle lives on the
  380. # printer (P2S 01.02 / BambuStudio 2.6+), on older versions it's
  381. # purely a slicer-side preference.
  382. #
  383. # For the printer-side variant, `home_flag` bit 11 is pushed on every
  384. # status report and parsed into state.store_to_sdcard (bambu_mqtt.py
  385. # line 153). That's the signal here — instant, no FTP I/O.
  386. #
  387. # For the slicer-side variant, the printer never hears about it and
  388. # this check will pass even when the user is missing step 4. That gap
  389. # is covered separately by the "no_3mf_available" archive-fallback
  390. # banner. An FTP upload-and-verify probe was tried and rejected — the
  391. # /cache directory is always writable from Bambuddy regardless of
  392. # either toggle, so the probe always passes and detects nothing.
  393. #
  394. # Skip entirely on models with no external-storage slot at all (A1
  395. # and A1 Mini). They never set home_flag bit 11, so a naive read of
  396. # `store_to_sdcard` would fall through to a false `fail` for every
  397. # A1-series user (#1703).
  398. #
  399. # Some models (P1-series) DO have a slot but no reachable control to turn
  400. # the option on: the Bambu Studio toggle only appears when the printer
  401. # publishes `support_save_remote_print_file_to_storage`, which current
  402. # P1 firmware never does, and the P1S/P1P have no screen. For those,
  403. # `store_to_sdcard` is stuck False with no way to fix it — report `skip`
  404. # (with a reason the UI explains) instead of a permanently-red `fail`
  405. # (#2524).
  406. state = printer_manager.get_status(printer.id) if printer else None
  407. model = getattr(printer, "model", None) if printer else None
  408. model_has_slot = has_external_storage(model) if printer else True
  409. store_to_sdcard = getattr(state, "store_to_sdcard", None) if state else None
  410. if not model_has_slot or state is None or not state.connected:
  411. checks.append(DiagnosticCheck(id="external_storage", status="skip"))
  412. elif store_to_sdcard is False and not has_remote_storage_toggle(model):
  413. # Slot present but no way to enable it on this firmware — don't nag
  414. # with an unresolvable fail; explain why via the reason param.
  415. #
  416. # Ahead of the empty-slot check below on purpose (#2524 over #2780):
  417. # on a P1-series the toggle cannot be switched on at all, so telling
  418. # the operator to insert a card would promise a fix that inserting a
  419. # card does not deliver.
  420. checks.append(
  421. DiagnosticCheck(
  422. id="external_storage",
  423. status="skip",
  424. params={"reason": "unsupported_model"},
  425. )
  426. )
  427. elif getattr(state, "sdcard_reported", False) and not getattr(state, "sdcard", False):
  428. # The toggle can be on and still achieve nothing with an empty slot,
  429. # and that combination used to report a clean pass — #2780's H2C had
  430. # `store_to_sdcard` set and `sdcard` False for three solid weeks while
  431. # every one of its archives came out blank. Report the empty slot,
  432. # which is the part the operator can actually act on.
  433. checks.append(
  434. DiagnosticCheck(
  435. id="external_storage",
  436. status="fail",
  437. params={"reason": "no_media"},
  438. )
  439. )
  440. elif not (last_verdict := last_print_storage_verdict(state)).reachable and not await _last_print_file_is_reachable(
  441. printer, last_verdict, ftps_ok=ftps_state == "ok"
  442. ):
  443. # The toggle is on, a card is in, the printer said the last print's file
  444. # is on internal storage — and a probe confirmed it really is out of
  445. # reach. That is what H2-series and P2S firmware does, and no setting
  446. # here changes it (#2762 tracks reading that storage). A pass here would
  447. # be a lie; a fail would be unresolvable.
  448. #
  449. # The verdict's own reason, not a fixed one: a print started from the
  450. # printer's screen reaches this branch too, and it never involved a
  451. # slicer, so the advice attached to REASON_INTERNAL_STORAGE would name a
  452. # dialog its operator never opened (#1820).
  453. checks.append(
  454. DiagnosticCheck(
  455. id="external_storage",
  456. status="warn",
  457. params={"reason": last_verdict.reason or REASON_INTERNAL_STORAGE},
  458. )
  459. )
  460. elif not last_verdict.reachable:
  461. # Reached only when the probe above found the file: the printer named
  462. # internal storage and served it over FTPS anyway. What this check is
  463. # for is whether Bambuddy can read the print file, and it demonstrably
  464. # can — so pass, whatever the toggle happens to say (#2856).
  465. checks.append(DiagnosticCheck(id="external_storage", status="pass"))
  466. elif store_to_sdcard is True:
  467. checks.append(DiagnosticCheck(id="external_storage", status="pass"))
  468. elif store_to_sdcard is False:
  469. checks.append(DiagnosticCheck(id="external_storage", status="fail"))
  470. else:
  471. # State exists but the field was never populated — skip rather than
  472. # report a false fail.
  473. checks.append(DiagnosticCheck(id="external_storage", status="skip"))
  474. # --- MQTT credentials / connection ---
  475. if not mqtt_ok:
  476. # Can't reach the broker at all — the port check already reported it.
  477. checks.append(DiagnosticCheck(id="mqtt_auth", status="skip"))
  478. elif serial_number and access_code:
  479. # Pre-add flow: actively probe with the credentials the user entered.
  480. try:
  481. result = await printer_manager.test_connection(
  482. ip_address=ip_address,
  483. serial_number=serial_number,
  484. access_code=access_code,
  485. )
  486. checks.append(
  487. DiagnosticCheck(
  488. id="mqtt_auth",
  489. status="pass" if result.get("success") else "fail",
  490. params=_auth_reason_params(result.get("reason")),
  491. )
  492. )
  493. except Exception:
  494. logger.debug("test_connection failed during diagnostic", exc_info=True)
  495. checks.append(DiagnosticCheck(id="mqtt_auth", status="fail"))
  496. elif state is not None:
  497. # Existing printer: trust the live MQTT state rather than opening a
  498. # second connection (Bambu printers tolerate few concurrent sessions).
  499. # `connected == False` alone does not say *why* — the live client keeps
  500. # the last CONNACK refusal, so a rejected access code can be reported as
  501. # such instead of as a generic failure the user has to guess at (#2698).
  502. client = printer_manager.get_client(printer.id) if printer else None
  503. checks.append(
  504. DiagnosticCheck(
  505. id="mqtt_auth",
  506. status="pass" if state.connected else "fail",
  507. params={} if state.connected else _auth_reason_params(getattr(client, "last_connect_error", None)),
  508. )
  509. )
  510. else:
  511. checks.append(DiagnosticCheck(id="mqtt_auth", status="skip"))
  512. # --- LAN developer mode (only readable over a live MQTT connection) ---
  513. if state is not None and state.connected:
  514. if state.developer_mode is True:
  515. dev_status = "pass"
  516. elif state.developer_mode is False:
  517. dev_status = "fail"
  518. else:
  519. dev_status = "skip"
  520. checks.append(DiagnosticCheck(id="developer_mode", status=dev_status))
  521. else:
  522. checks.append(DiagnosticCheck(id="developer_mode", status="skip"))
  523. # --- Printer is actually publishing on its report topic ---
  524. # The mqtt_auth check above only proves TCP + TLS + auth + SUBSCRIBE
  525. # succeed. A printer with a wrong-cased serial — or one that simply isn't
  526. # publishing for some other reason — still passes mqtt_auth because the
  527. # broker accepts the subscription regardless. The user-visible symptom in
  528. # that case is "AMS / K-profiles / custom filaments missing on the slicer
  529. # side": the VP bridge has nothing cached to mirror because no reports
  530. # arrived. #1622 surfaced this: bridge keep-alive timeouts paired with
  531. # the `Connected and subscribed, but the printer has sent zero status
  532. # reports` warning. The check below turns that warning into a structured
  533. # diagnostic result the user can act on without grepping container logs.
  534. #
  535. # If ``_report_messages_since_connect`` is already > 0, we exit
  536. # immediately — the bridge has seen reports. If it's 0 and a wait is
  537. # requested, we poll every PUBLISH_POLL_INTERVAL up to
  538. # ``wait_for_publish_seconds`` so a fresh reconnect (counter reset to 0)
  539. # isn't reported as fail before the printer's first idle push lands.
  540. publishing_params: dict[str, int | float] | None = None
  541. publishing_status = "skip"
  542. if printer is not None and state is not None and state.connected:
  543. client = printer_manager.get_client(printer.id)
  544. if client is not None:
  545. wait_budget = max(wait_for_publish_seconds, 0.0)
  546. if wait_budget > 0:
  547. # Expose the budget so the UI can render a countdown next to
  548. # the spinner — the user knows how long this check might take.
  549. publishing_params = {"max_wait_seconds": wait_budget}
  550. loop = asyncio.get_running_loop()
  551. deadline = loop.time() + wait_budget
  552. while True:
  553. if client.report_messages_since_connect > 0:
  554. publishing_status = "pass"
  555. break
  556. if loop.time() >= deadline:
  557. publishing_status = "fail"
  558. break
  559. await asyncio.sleep(_PUBLISH_POLL_INTERVAL)
  560. checks.append(
  561. DiagnosticCheck(
  562. id="printer_publishing",
  563. status=publishing_status,
  564. params=publishing_params or {},
  565. )
  566. )
  567. statuses = {c.status for c in checks}
  568. if "fail" in statuses:
  569. overall = "problems"
  570. elif "warn" in statuses:
  571. overall = "warnings"
  572. else:
  573. overall = "ok"
  574. return PrinterDiagnosticResult(
  575. printer_id=printer.id if printer else None,
  576. ip_address=ip_address,
  577. overall=overall,
  578. checks=checks,
  579. )