printer_diagnostic.py 13 KB

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