printer_diagnostic.py 12 KB

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