printer_diagnostic.py 33 KB

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