printer_diagnostic.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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, Docker 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. from backend.app.models.printer import Printer
  14. from backend.app.schemas.printer import DiagnosticCheck, PrinterDiagnosticResult
  15. from backend.app.services.bambu_mqtt import CONNECT_ERROR_AUTH_REJECTED
  16. from backend.app.services.camera import get_camera_port
  17. from backend.app.services.discovery import is_running_in_docker
  18. from backend.app.services.printer_manager import printer_manager
  19. from backend.app.utils.printer_models import has_external_storage, has_remote_storage_toggle
  20. logger = logging.getLogger(__name__)
  21. # Bambu LAN-mode ports.
  22. PORT_MQTT = 8883 # MQTT over TLS — control + status. Connection-critical.
  23. PORT_FTPS = 990 # FTPS — file upload; required to send prints.
  24. PORT_RTSPS = 322 # RTSPS — camera stream; optional.
  25. PORT_CHAMBER_IMAGE = 6000 # Chamber image protocol — A1/P1 camera stream; optional.
  26. _PORT_PROBE_TIMEOUT = 3.0
  27. # Default seconds the `printer_publishing` check will wait for the first
  28. # report-topic message before declaring fail. Bambu printers in idle publish
  29. # push_status every few seconds; 10s catches healthy bridges with margin while
  30. # staying short enough that the spinner-with-countdown UX stays acceptable.
  31. # The check exits the moment a message arrives, so the typical wall-clock is
  32. # 1–2s, not the full 10. Passed as ``wait_for_publish_seconds`` per call so
  33. # the support-package code path can skip the wait entirely (defaults to 0).
  34. PUBLISH_WAIT_DEFAULT = 10.0
  35. _PUBLISH_POLL_INTERVAL = 0.5
  36. async def _check_port(ip: str, port: int, timeout: float = _PORT_PROBE_TIMEOUT) -> bool:
  37. """Test TCP connectivity to ip:port. Returns True if reachable."""
  38. try:
  39. _reader, writer = await asyncio.wait_for(asyncio.open_connection(ip, port), timeout=timeout)
  40. writer.close()
  41. try:
  42. await writer.wait_closed()
  43. except Exception:
  44. pass
  45. return True
  46. except Exception:
  47. return False
  48. # Public alias. The connection watchdog probes the MQTT port before rebuilding a
  49. # client, so it can tell "the printer is switched off" (leave it alone, paho will
  50. # keep retrying) from "the printer is answering but our session is dead" (#2732).
  51. check_port = _check_port
  52. def _auth_reason_params(reason: str | None) -> dict:
  53. """Map a client's CONNACK-refusal slug onto the check's `params.reason`.
  54. The frontend renders `diagnostic.check.<id>.<status>_<reason>` when a reason
  55. is present and falls back to the plain per-status text otherwise, so an
  56. unknown or absent slug degrades to today's generic wording rather than a
  57. missing string. Only `auth_rejected` currently carries its own message:
  58. that is the one case where the printer positively told us the credentials
  59. were wrong, as opposed to us merely observing that we are not connected.
  60. """
  61. if reason == CONNECT_ERROR_AUTH_REJECTED:
  62. return {"reason": CONNECT_ERROR_AUTH_REJECTED}
  63. return {}
  64. def _camera_port_for_printer(printer: Printer | None) -> tuple[int, str]:
  65. """Return the model-specific camera diagnostic port and display protocol."""
  66. if not printer:
  67. return PORT_RTSPS, "RTSPS"
  68. model = getattr(printer, "model", None)
  69. if not model:
  70. return PORT_RTSPS, "RTSPS"
  71. camera_port = get_camera_port(model)
  72. if camera_port == PORT_CHAMBER_IMAGE:
  73. return camera_port, "Chamber Image"
  74. return camera_port, "RTSPS"
  75. def _detect_docker_network_mode() -> str:
  76. """Detect Docker network mode.
  77. In host mode the container shares the host network namespace, so Docker
  78. infrastructure interfaces (docker0, br-*, veth*) are visible. In bridge
  79. mode the container only sees its own eth0.
  80. """
  81. try:
  82. for _idx, name in socket.if_nameindex():
  83. if name.startswith(("docker", "br-", "veth", "virbr")):
  84. return "host"
  85. except Exception:
  86. pass
  87. return "bridge"
  88. def _get_host_ip() -> str | None:
  89. """Best-effort IPv4 address the Bambuddy host routes from."""
  90. try:
  91. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  92. try:
  93. # No packets are sent; this just picks the routing-table source IP.
  94. s.connect(("10.255.255.255", 1))
  95. return s.getsockname()[0]
  96. finally:
  97. s.close()
  98. except Exception:
  99. return None
  100. def _same_subnet(ip_a: str, ip_b: str) -> bool | None:
  101. """True/False if both are IPv4 literals in the same /24; None if undeterminable."""
  102. try:
  103. addr_a = ipaddress.ip_address(ip_a)
  104. addr_b = ipaddress.ip_address(ip_b)
  105. except ValueError:
  106. return None
  107. if addr_a.version != 4 or addr_b.version != 4:
  108. return None
  109. net_a = ipaddress.ip_network(f"{addr_a}/24", strict=False)
  110. net_b = ipaddress.ip_network(f"{addr_b}/24", strict=False)
  111. return net_a == net_b
  112. async def run_connection_diagnostic(
  113. ip_address: str,
  114. *,
  115. printer: Printer | None = None,
  116. serial_number: str | None = None,
  117. access_code: str | None = None,
  118. wait_for_publish_seconds: float = 0.0,
  119. ) -> PrinterDiagnosticResult:
  120. """Run connection checks for a printer.
  121. Works for an existing saved printer (pass ``printer``) and for the
  122. pre-save Add-Printer flow (pass ``serial_number`` + ``access_code``).
  123. Each check carries a stable ``id`` and a ``status`` of
  124. pass / fail / warn / skip; the frontend renders the human-readable
  125. title and fix text (localized) keyed on that id + status.
  126. """
  127. checks: list[DiagnosticCheck] = []
  128. # --- Port reachability (probed in parallel) ---
  129. camera_port, camera_protocol = _camera_port_for_printer(printer)
  130. mqtt_ok, ftps_ok, camera_ok = await asyncio.gather(
  131. _check_port(ip_address, PORT_MQTT),
  132. _check_port(ip_address, PORT_FTPS),
  133. _check_port(ip_address, camera_port),
  134. )
  135. # MQTT is connection-critical; FTPS/camera only degrade printing/camera.
  136. checks.append(DiagnosticCheck(id="port_mqtt", status="pass" if mqtt_ok else "fail"))
  137. checks.append(DiagnosticCheck(id="port_ftps", status="pass" if ftps_ok else "warn"))
  138. checks.append(
  139. DiagnosticCheck(
  140. id="port_rtsps",
  141. status="pass" if camera_ok else "warn",
  142. params={"port": camera_port, "protocol": camera_protocol},
  143. )
  144. )
  145. # --- Docker network mode ---
  146. network_mode: str | None = None
  147. if is_running_in_docker():
  148. network_mode = _detect_docker_network_mode()
  149. checks.append(
  150. DiagnosticCheck(
  151. id="network_mode",
  152. status="pass" if network_mode == "host" else "warn",
  153. params={"mode": network_mode},
  154. )
  155. )
  156. else:
  157. checks.append(DiagnosticCheck(id="network_mode", status="skip"))
  158. # --- Subnet match ---
  159. # Skipped in bridge mode: the container IP is the bridge IP, not the host's,
  160. # so the comparison is meaningless and the network_mode check already covers it.
  161. if network_mode == "bridge":
  162. checks.append(DiagnosticCheck(id="subnet", status="skip"))
  163. else:
  164. host_ip = _get_host_ip()
  165. same = _same_subnet(ip_address, host_ip) if host_ip else None
  166. if same is None:
  167. checks.append(DiagnosticCheck(id="subnet", status="skip"))
  168. else:
  169. checks.append(
  170. DiagnosticCheck(
  171. id="subnet",
  172. status="pass" if same else "warn",
  173. params={"printer_ip": ip_address, "host_ip": host_ip},
  174. )
  175. )
  176. # --- External storage (printer-side "Store sent files on external storage") ---
  177. # Install step 4. The setting has two variants depending on
  178. # firmware/slicer combo: on newer firmware the toggle lives on the
  179. # printer (P2S 01.02 / BambuStudio 2.6+), on older versions it's
  180. # purely a slicer-side preference.
  181. #
  182. # For the printer-side variant, `home_flag` bit 11 is pushed on every
  183. # status report and parsed into state.store_to_sdcard (bambu_mqtt.py
  184. # line 153). That's the signal here — instant, no FTP I/O.
  185. #
  186. # For the slicer-side variant, the printer never hears about it and
  187. # this check will pass even when the user is missing step 4. That gap
  188. # is covered separately by the "no_3mf_available" archive-fallback
  189. # banner. An FTP upload-and-verify probe was tried and rejected — the
  190. # /cache directory is always writable from Bambuddy regardless of
  191. # either toggle, so the probe always passes and detects nothing.
  192. #
  193. # Skip entirely on models with no external-storage slot at all (A1
  194. # and A1 Mini). They never set home_flag bit 11, so a naive read of
  195. # `store_to_sdcard` would fall through to a false `fail` for every
  196. # A1-series user (#1703).
  197. #
  198. # Some models (P1-series) DO have a slot but no reachable control to turn
  199. # the option on: the Bambu Studio toggle only appears when the printer
  200. # publishes `support_save_remote_print_file_to_storage`, which current
  201. # P1 firmware never does, and the P1S/P1P have no screen. For those,
  202. # `store_to_sdcard` is stuck False with no way to fix it — report `skip`
  203. # (with a reason the UI explains) instead of a permanently-red `fail`
  204. # (#2524).
  205. state = printer_manager.get_status(printer.id) if printer else None
  206. model = getattr(printer, "model", None) if printer else None
  207. model_has_slot = has_external_storage(model) if printer else True
  208. store_to_sdcard = getattr(state, "store_to_sdcard", None) if state else None
  209. if not model_has_slot or state is None or not state.connected:
  210. checks.append(DiagnosticCheck(id="external_storage", status="skip"))
  211. elif store_to_sdcard is True:
  212. checks.append(DiagnosticCheck(id="external_storage", status="pass"))
  213. elif store_to_sdcard is False and not has_remote_storage_toggle(model):
  214. # Slot present but no way to enable it on this firmware — don't nag
  215. # with an unresolvable fail; explain why via the reason param.
  216. checks.append(
  217. DiagnosticCheck(
  218. id="external_storage",
  219. status="skip",
  220. params={"reason": "unsupported_model"},
  221. )
  222. )
  223. elif store_to_sdcard is False:
  224. checks.append(DiagnosticCheck(id="external_storage", status="fail"))
  225. else:
  226. # State exists but the field was never populated — skip rather than
  227. # report a false fail.
  228. checks.append(DiagnosticCheck(id="external_storage", status="skip"))
  229. # --- MQTT credentials / connection ---
  230. if not mqtt_ok:
  231. # Can't reach the broker at all — the port check already reported it.
  232. checks.append(DiagnosticCheck(id="mqtt_auth", status="skip"))
  233. elif serial_number and access_code:
  234. # Pre-add flow: actively probe with the credentials the user entered.
  235. try:
  236. result = await printer_manager.test_connection(
  237. ip_address=ip_address,
  238. serial_number=serial_number,
  239. access_code=access_code,
  240. )
  241. checks.append(
  242. DiagnosticCheck(
  243. id="mqtt_auth",
  244. status="pass" if result.get("success") else "fail",
  245. params=_auth_reason_params(result.get("reason")),
  246. )
  247. )
  248. except Exception:
  249. logger.debug("test_connection failed during diagnostic", exc_info=True)
  250. checks.append(DiagnosticCheck(id="mqtt_auth", status="fail"))
  251. elif state is not None:
  252. # Existing printer: trust the live MQTT state rather than opening a
  253. # second connection (Bambu printers tolerate few concurrent sessions).
  254. # `connected == False` alone does not say *why* — the live client keeps
  255. # the last CONNACK refusal, so a rejected access code can be reported as
  256. # such instead of as a generic failure the user has to guess at (#2698).
  257. client = printer_manager.get_client(printer.id) if printer else None
  258. checks.append(
  259. DiagnosticCheck(
  260. id="mqtt_auth",
  261. status="pass" if state.connected else "fail",
  262. params={} if state.connected else _auth_reason_params(getattr(client, "last_connect_error", None)),
  263. )
  264. )
  265. else:
  266. checks.append(DiagnosticCheck(id="mqtt_auth", status="skip"))
  267. # --- LAN developer mode (only readable over a live MQTT connection) ---
  268. if state is not None and state.connected:
  269. if state.developer_mode is True:
  270. dev_status = "pass"
  271. elif state.developer_mode is False:
  272. dev_status = "fail"
  273. else:
  274. dev_status = "skip"
  275. checks.append(DiagnosticCheck(id="developer_mode", status=dev_status))
  276. else:
  277. checks.append(DiagnosticCheck(id="developer_mode", status="skip"))
  278. # --- Printer is actually publishing on its report topic ---
  279. # The mqtt_auth check above only proves TCP + TLS + auth + SUBSCRIBE
  280. # succeed. A printer with a wrong-cased serial — or one that simply isn't
  281. # publishing for some other reason — still passes mqtt_auth because the
  282. # broker accepts the subscription regardless. The user-visible symptom in
  283. # that case is "AMS / K-profiles / custom filaments missing on the slicer
  284. # side": the VP bridge has nothing cached to mirror because no reports
  285. # arrived. #1622 surfaced this: bridge keep-alive timeouts paired with
  286. # the `Connected and subscribed, but the printer has sent zero status
  287. # reports` warning. The check below turns that warning into a structured
  288. # diagnostic result the user can act on without grepping container logs.
  289. #
  290. # If ``_report_messages_since_connect`` is already > 0, we exit
  291. # immediately — the bridge has seen reports. If it's 0 and a wait is
  292. # requested, we poll every PUBLISH_POLL_INTERVAL up to
  293. # ``wait_for_publish_seconds`` so a fresh reconnect (counter reset to 0)
  294. # isn't reported as fail before the printer's first idle push lands.
  295. publishing_params: dict[str, int | float] | None = None
  296. publishing_status = "skip"
  297. if printer is not None and state is not None and state.connected:
  298. client = printer_manager.get_client(printer.id)
  299. if client is not None:
  300. wait_budget = max(wait_for_publish_seconds, 0.0)
  301. if wait_budget > 0:
  302. # Expose the budget so the UI can render a countdown next to
  303. # the spinner — the user knows how long this check might take.
  304. publishing_params = {"max_wait_seconds": wait_budget}
  305. loop = asyncio.get_running_loop()
  306. deadline = loop.time() + wait_budget
  307. while True:
  308. if client.report_messages_since_connect > 0:
  309. publishing_status = "pass"
  310. break
  311. if loop.time() >= deadline:
  312. publishing_status = "fail"
  313. break
  314. await asyncio.sleep(_PUBLISH_POLL_INTERVAL)
  315. checks.append(
  316. DiagnosticCheck(
  317. id="printer_publishing",
  318. status=publishing_status,
  319. params=publishing_params or {},
  320. )
  321. )
  322. statuses = {c.status for c in checks}
  323. if "fail" in statuses:
  324. overall = "problems"
  325. elif "warn" in statuses:
  326. overall = "warnings"
  327. else:
  328. overall = "ok"
  329. return PrinterDiagnosticResult(
  330. printer_id=printer.id if printer else None,
  331. ip_address=ip_address,
  332. overall=overall,
  333. checks=checks,
  334. )