printer_diagnostic.py 18 KB

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