mqtt_server.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. """MQTT broker for virtual printer.
  2. Implements an MQTT broker that accepts connections from slicers,
  3. authenticates with the configured access code, and logs print commands.
  4. """
  5. import asyncio
  6. import copy
  7. import hmac
  8. import json
  9. import logging
  10. import socket
  11. import ssl
  12. import time
  13. from collections.abc import Callable
  14. from pathlib import Path
  15. from typing import TYPE_CHECKING
  16. from backend.app.services.virtual_printer._debug import append_event, dump_wire
  17. if TYPE_CHECKING:
  18. from backend.app.services.virtual_printer.mqtt_bridge import MQTTBridge
  19. logger = logging.getLogger(__name__)
  20. # Default MQTT port for Bambu printers (MQTT over TLS)
  21. MQTT_PORT = 8883
  22. # Per-IP MQTT auth rate-limit. 5 failures within 60 s blocks further attempts
  23. # for the remainder of the window. Bambu printers themselves don't rate-limit,
  24. # but they're not exposed past the LAN edge; Bambuddy's VPs sometimes are
  25. # (Tailscale, port-forwarded), so an 8-char access code without any
  26. # brute-force friction is too weak. The window auto-recovers — no manual
  27. # unblock — so a legitimate user who fat-fingered their access code 5 times
  28. # only waits up to 60 s.
  29. _AUTH_RATE_LIMIT_MAX_ATTEMPTS = 5
  30. _AUTH_RATE_LIMIT_WINDOW_SECONDS = 60.0
  31. # Pending-request map bound. Each entry maps a slicer command's
  32. # sequence_id to its originating client_id so the bridge response can be
  33. # routed back to just that client. Bounded so a slicer that issues
  34. # commands without ever consuming responses can't leak memory.
  35. _PENDING_REQUEST_MAX_ENTRIES = 256
  36. # Target-printer gcode_states for which the VP mirrors live print progress to
  37. # the slicer (#1887). BambuStudio and OrcaSlicer gate BOTH the Device-tab
  38. # progress panel and the Send button on the same predicate —
  39. # `MachineObject::is_in_printing()`, i.e. gcode_state in
  40. # {RUNNING, PAUSE, SLICING, PREPARE} — so reporting the real state verbatim
  41. # would show progress at the cost of blocking Send for as long as the printer
  42. # prints. That is exactly the #1558 regression. `FINISH` is the one state that
  43. # renders the progress panel (`is_in_printing() || print_status == "FINISH"` in
  44. # StatusPanel::update_subtask) while leaving Send enabled, so the mirror keeps
  45. # reporting FINISH and only fills in the numbers underneath it.
  46. _MIRRORED_PRINT_STATES = frozenset({"RUNNING", "PAUSE"})
  47. # How long after the last upload-state transition the VP keeps echoing the
  48. # slicer's own filename back at it before switching the report over to whatever
  49. # the target printer is really printing. The slicer releases its in-flight-job
  50. # lock when it sees gcode_state=FINISH carrying the subtask_name it uploaded
  51. # (#1280 / #1658); swapping in the printer's filename while that handshake is
  52. # still in flight wedges the send modal at "Downloading". 5 s covers the 1.5 s
  53. # `_schedule_finish_release` timer plus several 1 Hz pushes.
  54. _UPLOAD_SETTLE_SECONDS = 5.0
  55. # Model code → product_name for version response (must match what slicer expects)
  56. MODEL_PRODUCT_NAMES = {
  57. "BL-P001": "X1 Carbon",
  58. "BL-P002": "X1",
  59. "C13": "X1E",
  60. "N6": "X2D",
  61. "N9": "A2L",
  62. "C11": "P1P",
  63. "C12": "P1S",
  64. "N7": "P2S",
  65. "N2S": "A1",
  66. "N1": "A1 mini",
  67. "O1D": "H2D",
  68. "O1C": "H2C",
  69. "O1C2": "H2C",
  70. "O1S": "H2S",
  71. }
  72. class SimpleMQTTServer:
  73. """The virtual printer's MQTT server, on raw sockets.
  74. Handles the part of the MQTT protocol slicers use with a printer; not a
  75. general-purpose broker.
  76. """
  77. def __init__(
  78. self,
  79. serial: str,
  80. access_code: str,
  81. cert_path: Path,
  82. key_path: Path,
  83. port: int = MQTT_PORT,
  84. on_print_command: Callable[[str, dict], None] | None = None,
  85. model: str = "",
  86. bind_address: str = "0.0.0.0", # nosec B104
  87. vp_name: str = "",
  88. ):
  89. self.serial = serial
  90. self.access_code = access_code
  91. self.model = model
  92. self.cert_path = cert_path
  93. self.key_path = key_path
  94. self.port = port
  95. self.on_print_command = on_print_command
  96. self.bind_address = bind_address
  97. self.vp_name = vp_name
  98. self._log_prefix = f"[{vp_name}] " if vp_name else ""
  99. self._running = False
  100. # Set after the socket is bound — see ftp_server.py for rationale.
  101. self.ready = asyncio.Event()
  102. self._server = None
  103. self._clients: dict[str, asyncio.StreamWriter] = {}
  104. # Per-client "effective serial" — the serial the slicer actually uses in
  105. # device/{serial}/report|request topics. Populated from the first
  106. # SUBSCRIBE/PUBLISH we see on a connection. This lets the VP respond on
  107. # the topic the slicer is listening on even when it disagrees with
  108. # self.serial (e.g. a stale Orca config that was bound to an older VP
  109. # serial, or a printer entry that was re-pointed at the VP IP without
  110. # updating the serial).
  111. self._client_serials: dict[str, str] = {}
  112. self._status_push_task: asyncio.Task | None = None
  113. self._sequence_id = 0
  114. # Dynamic state for status reports
  115. self._gcode_state = "IDLE"
  116. self._current_file = ""
  117. self._prepare_percent = "0"
  118. # Monotonic timestamp of the last upload-state transition, so the live-
  119. # progress mirror can tell whether the slicer is still waiting on its
  120. # own upload handshake. Starts at -inf: a VP that has never seen an
  121. # upload has no handshake to protect and can mirror immediately.
  122. self._state_changed_at = float("-inf")
  123. # MQTT bridge for non-proxy modes — set by VirtualPrinterInstance after start().
  124. # When the bridge is_active, real printer pushes are fanned out to slicers and
  125. # the synthetic 1s push is suspended. When the target printer goes offline the
  126. # synthetic fallback resumes automatically.
  127. self._bridge: MQTTBridge | None = None
  128. # Per-source-IP failed-auth tracker for rate-limiting / lockout.
  129. # Maps IP → list[monotonic timestamp] of recent failures within the
  130. # window. Pruned on every check so it doesn't grow unbounded.
  131. self._auth_failures: dict[str, list[float]] = {}
  132. # Maps sequence_id → originating client_id for slicer-initiated
  133. # commands forwarded to the real printer. Used in
  134. # ``push_raw_to_clients`` to route the printer's response only
  135. # back to the requesting slicer instead of fanning out to all
  136. # connected clients (which leaks slicer A's responses to slicer
  137. # B in multi-slicer setups). FIFO-bounded; if a response never
  138. # arrives the entry ages out instead of leaking.
  139. self._pending_requests: dict[str, str] = {}
  140. async def start(self) -> None:
  141. """Start the MQTT server."""
  142. if self._running:
  143. return
  144. logger.info("Starting simple MQTT server on port %s", self.port)
  145. # Create SSL context with Bambu-compatible settings
  146. ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  147. ssl_context.load_cert_chain(str(self.cert_path), str(self.key_path))
  148. # Match Bambu printer behavior - accept any client
  149. ssl_context.verify_mode = ssl.CERT_NONE
  150. # Allow TLS 1.2 for broader compatibility (some slicers may not support 1.3)
  151. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  152. # Match real Bambu printer cipher behaviour: include the plain-RSA
  153. # AES-GCM suites the slicer expects. On hardened distros
  154. # (Fedora / RHEL with `update-crypto-policies`, hardened Alpine builds)
  155. # OpenSSL's `DEFAULT` list strips these suites, leaving no overlap
  156. # with the slicer's MQTT-over-TLS ClientHello — handshake fails
  157. # immediately and the slicer reports a connect error before any MQTT
  158. # CONNECT can be sent (#1610 audit). Same shape as the #620 fix.
  159. ssl_context.set_ciphers("DEFAULT:AES256-GCM-SHA384:AES128-GCM-SHA256")
  160. # Disable hostname checking
  161. ssl_context.check_hostname = False
  162. # Log certificate info
  163. import subprocess
  164. try:
  165. result = subprocess.run(
  166. ["openssl", "x509", "-in", str(self.cert_path), "-noout", "-subject", "-issuer"],
  167. capture_output=True,
  168. text=True,
  169. timeout=5,
  170. )
  171. logger.info("MQTT SSL cert info: %s", result.stdout.strip())
  172. except (OSError, subprocess.SubprocessError):
  173. pass # Certificate info is for debug logging only; not critical
  174. logger.info("MQTT SSL context: TLS 1.2+, cert=%s", self.cert_path)
  175. try:
  176. self._running = True
  177. # Wrapper to log ALL connection attempts including SSL errors
  178. async def connection_handler(reader, writer):
  179. try:
  180. addr = writer.get_extra_info("peername")
  181. ssl_obj = writer.get_extra_info("ssl_object")
  182. if ssl_obj:
  183. logger.info(
  184. f"{self._log_prefix}MQTT TLS connection from {addr} - cipher={ssl_obj.cipher()}, version={ssl_obj.version()}"
  185. )
  186. else:
  187. logger.info("%sMQTT connection from %s (no TLS?)", self._log_prefix, addr)
  188. await self._handle_client(reader, writer)
  189. except ssl.SSLError as e:
  190. logger.error("MQTT SSL error: %s", e)
  191. except Exception as e:
  192. logger.error("MQTT connection handler error: %s", e)
  193. self._server = await asyncio.start_server(
  194. connection_handler,
  195. self.bind_address,
  196. self.port,
  197. ssl=ssl_context,
  198. )
  199. self.ready.set()
  200. logger.info("Simple MQTT server listening on port %s", self.port)
  201. # Start periodic status push task
  202. self._status_push_task = asyncio.create_task(self._periodic_status_push())
  203. async with self._server:
  204. await self._server.serve_forever()
  205. except OSError as e:
  206. if e.errno == 98: # Address already in use
  207. logger.error("MQTT port %s is already in use", self.port)
  208. else:
  209. logger.error("MQTT server error: %s", e)
  210. except asyncio.CancelledError:
  211. logger.debug("MQTT server task cancelled")
  212. except Exception as e:
  213. logger.error("MQTT server error: %s", e)
  214. finally:
  215. await self.stop()
  216. async def stop(self) -> None:
  217. """Stop the MQTT server."""
  218. logger.info("Stopping simple MQTT server")
  219. self._running = False
  220. self.ready.clear()
  221. # Stop periodic status push
  222. if self._status_push_task:
  223. self._status_push_task.cancel()
  224. try:
  225. await self._status_push_task
  226. except asyncio.CancelledError:
  227. pass # Expected when stopping the periodic status push task
  228. self._status_push_task = None
  229. # Close all client connections (iterate over copy to avoid modification during iteration)
  230. for _client_id, writer in list(self._clients.items()):
  231. try:
  232. writer.close()
  233. await writer.wait_closed()
  234. except OSError:
  235. pass # Best-effort client connection cleanup; client may have disconnected
  236. self._clients.clear()
  237. self._client_serials.clear()
  238. if self._server:
  239. try:
  240. self._server.close()
  241. await self._server.wait_closed()
  242. except OSError:
  243. pass # Best-effort server shutdown; port may already be released
  244. self._server = None
  245. @staticmethod
  246. def _extract_serial_from_topic(topic: str) -> str | None:
  247. """Pull the serial out of a `device/{serial}/report|request` topic.
  248. Returns None if the topic doesn't match that shape — callers fall back
  249. to self.serial in that case.
  250. """
  251. if not topic.startswith("device/"):
  252. return None
  253. rest = topic[len("device/") :]
  254. # Expect "{serial}/report" or "{serial}/request" (possibly with suffixes).
  255. slash = rest.find("/")
  256. if slash <= 0:
  257. return None
  258. return rest[:slash]
  259. def set_bridge(self, bridge: "MQTTBridge | None") -> None:
  260. """Attach (or detach) the MQTT bridge that mirrors the target printer."""
  261. self._bridge = bridge
  262. async def _periodic_status_push(self) -> None:
  263. """Send periodic status updates to all connected clients (1 Hz, exact pre-bridge behaviour)."""
  264. logger.info("Starting periodic status push task")
  265. # Per-client push counters reset every 60 ticks. Lets us confirm from
  266. # logs whether the 1Hz push is actually reaching a specific slicer
  267. # connection (#1548 keepalive follow-up: keepalive parser shipped but
  268. # OrcaSlicer still disconnects on idle, and the periodic push is
  269. # otherwise silent at INFO level so it can't be observed in the
  270. # support bundle). One log line per minute per active connection —
  271. # nothing when no slicer is attached.
  272. push_counts: dict[str, int] = {}
  273. ticks_since_summary = 0
  274. while self._running:
  275. try:
  276. await asyncio.sleep(1) # Push every 1 second like real printers
  277. ticks_since_summary += 1
  278. disconnected = []
  279. for client_id, writer in list(self._clients.items()):
  280. try:
  281. if writer.is_closing():
  282. disconnected.append(client_id)
  283. continue
  284. serial = self._client_serials.get(client_id, self.serial)
  285. # log_event=False: the 1Hz cached push is already
  286. # captured by ``dump_wire`` snapshot mode (see
  287. # _debug.py); appending it to the cmd.jsonl would
  288. # flood the file ~60 lines/min per VP.
  289. await self._send_status_report(writer, serial=serial, log_event=False)
  290. push_counts[client_id] = push_counts.get(client_id, 0) + 1
  291. except OSError as e:
  292. logger.debug("Failed to push status to %s: %s", client_id, e)
  293. disconnected.append(client_id)
  294. # Remove disconnected clients
  295. for client_id in disconnected:
  296. self._clients.pop(client_id, None)
  297. self._client_serials.pop(client_id, None)
  298. push_counts.pop(client_id, None)
  299. if ticks_since_summary >= 60:
  300. for cid, count in push_counts.items():
  301. logger.info(
  302. "%s1Hz status push: %d pushes/min to %s",
  303. self._log_prefix,
  304. count,
  305. cid,
  306. )
  307. push_counts.clear()
  308. ticks_since_summary = 0
  309. except asyncio.CancelledError:
  310. break
  311. except Exception as e:
  312. logger.error("Periodic status push error: %s", e)
  313. logger.info("Periodic status push task stopped")
  314. async def push_raw_to_clients(self, topic: str, payload: bytes) -> None:
  315. """Publish a pre-serialized MQTT payload on `topic` to connected slicers.
  316. Called by MQTTBridge from the asyncio loop (scheduled via
  317. run_coroutine_threadsafe from paho's network thread).
  318. Routes the response only back to the originating slicer if the
  319. payload's sequence_id was previously recorded via
  320. ``_record_pending_request``. Falls back to fan-out for
  321. printer-initiated pushes (push_status etc.) and for sequence_ids
  322. we never saw (covers a slicer that subscribes mid-flight to a
  323. topic for which an earlier request is still in flight).
  324. """
  325. topic_bytes = topic.encode("utf-8")
  326. # MQTT remaining-length: 2-byte topic length prefix + topic + message body.
  327. remaining = 2 + len(topic_bytes) + len(payload)
  328. packet = bytearray([0x30]) # PUBLISH, QoS 0
  329. while True:
  330. byte = remaining % 128
  331. remaining //= 128
  332. if remaining > 0:
  333. byte |= 0x80
  334. packet.append(byte)
  335. if remaining == 0:
  336. break
  337. packet.extend([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF])
  338. packet.extend(topic_bytes)
  339. packet.extend(payload)
  340. frame = bytes(packet)
  341. target_client_id = self._lookup_pending_request_client(payload)
  342. disconnected = []
  343. for client_id, writer in list(self._clients.items()):
  344. if target_client_id is not None and client_id != target_client_id:
  345. continue
  346. try:
  347. if writer.is_closing():
  348. disconnected.append(client_id)
  349. continue
  350. writer.write(frame)
  351. try:
  352. await asyncio.wait_for(writer.drain(), timeout=5)
  353. except TimeoutError:
  354. logger.debug("MQTT drain timeout pushing bridge frame to %s", client_id)
  355. except OSError as e:
  356. logger.debug("Failed to push bridge frame to %s: %s", client_id, e)
  357. disconnected.append(client_id)
  358. for client_id in disconnected:
  359. self._clients.pop(client_id, None)
  360. self._client_serials.pop(client_id, None)
  361. async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  362. """Handle an MQTT client connection."""
  363. addr = writer.get_extra_info("peername")
  364. client_id = f"{addr[0]}:{addr[1]}" if addr else "unknown"
  365. logger.info("%sMQTT client connected: %s", self._log_prefix, client_id)
  366. authenticated = False
  367. # Per-packet read timeout. Before CONNECT we default to 60 s so a
  368. # client that opens TCP but never sends anything still gets reaped.
  369. # After CONNECT we drop the application-level read timeout entirely
  370. # and rely on TCP keepalive (SO_KEEPALIVE) to detect dead connections
  371. # — this matches real Bambu firmware, which does not enforce MQTT
  372. # spec §4.4's 1.5× idle disconnect (#1548 round 2). OrcaSlicer's
  373. # MQTT client on some platforms does not emit PINGREQ at all on idle
  374. # connections; the same install that stays connected to a real P1S
  375. # indefinitely was disconnecting from us at keepalive×1.5.
  376. read_timeout: float | None = 60.0
  377. try:
  378. while self._running:
  379. # Read MQTT fixed header
  380. try:
  381. header = await asyncio.wait_for(reader.read(1), timeout=read_timeout)
  382. except TimeoutError:
  383. break
  384. if not header:
  385. break
  386. packet_type = (header[0] & 0xF0) >> 4
  387. # Read remaining length
  388. remaining_length = await self._read_remaining_length(reader)
  389. if remaining_length is None:
  390. break
  391. # Read payload
  392. payload = await reader.read(remaining_length) if remaining_length > 0 else b""
  393. # Handle packet types
  394. if packet_type == 1: # CONNECT
  395. source_ip = addr[0] if addr else "unknown"
  396. if self._is_auth_rate_limited(source_ip):
  397. logger.warning(
  398. "%sMQTT auth rate-limited from %s (>=%d failures in %ds)",
  399. self._log_prefix,
  400. source_ip,
  401. _AUTH_RATE_LIMIT_MAX_ATTEMPTS,
  402. int(_AUTH_RATE_LIMIT_WINDOW_SECONDS),
  403. )
  404. writer.write(bytes([0x20, 0x02, 0x00, 0x05])) # Not authorized
  405. await writer.drain()
  406. break
  407. authenticated, keep_alive = await self._handle_connect(payload, writer)
  408. if not authenticated:
  409. self._record_auth_failure(source_ip)
  410. break
  411. self._clear_auth_failures(source_ip)
  412. # Drop the application-level read timeout; rely on
  413. # SO_KEEPALIVE below for dead-connection detection.
  414. # Real Bambu firmware does the same — accept any
  415. # negotiated keepalive but never enforce §4.4's 1.5×
  416. # disconnect on the otherwise-idle MQTT session
  417. # (#1548 round 2). keep_alive is logged for support
  418. # bundles but no longer drives a disconnect.
  419. read_timeout = None
  420. logger.info(
  421. "%sMQTT client %s authenticated (negotiated keepalive=%ds, idle disconnect disabled)",
  422. self._log_prefix,
  423. client_id,
  424. keep_alive,
  425. )
  426. # Enable TCP keepalive so a hard network drop is detected
  427. # by the OS within a few minutes rather than waiting for
  428. # the next outbound write to ECONNRESET.
  429. #
  430. # Also tighten the Linux keepalive schedule. Defaults are
  431. # tcp_keepalive_time=7200 s (2 h before first probe),
  432. # tcp_keepalive_intvl=75, tcp_keepalive_probes=9 — so a
  433. # macOS client that goes to sleep silently is only
  434. # detected as dead ~2 h 11 min later, and until then the
  435. # push loop keeps stalling on drain-timeouts to the
  436. # zombie socket. #1872: a P1S sleep/wake left the pre-
  437. # sleep session in _clients for 5+ min with no eviction
  438. # signal. New settings (idle=60 s, interval=15 s,
  439. # count=4) detect a dead peer in ~2 min. `getattr` guards
  440. # keep this cross-platform — macOS has TCP_KEEPINTVL but
  441. # not TCP_KEEPIDLE (uses TCP_KEEPALIVE); other platforms
  442. # silently skip.
  443. sock = writer.get_extra_info("socket")
  444. if sock is not None:
  445. try:
  446. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  447. except OSError as e:
  448. logger.debug("%sFailed to set SO_KEEPALIVE on %s: %s", self._log_prefix, client_id, e)
  449. for opt_name, opt_value in (
  450. ("TCP_KEEPIDLE", 60),
  451. ("TCP_KEEPINTVL", 15),
  452. ("TCP_KEEPCNT", 4),
  453. ):
  454. opt = getattr(socket, opt_name, None)
  455. if opt is None:
  456. continue
  457. try:
  458. sock.setsockopt(socket.IPPROTO_TCP, opt, opt_value)
  459. except OSError as e:
  460. logger.debug(
  461. "%sFailed to set %s=%s on %s: %s",
  462. self._log_prefix,
  463. opt_name,
  464. opt_value,
  465. client_id,
  466. e,
  467. )
  468. # Register client for periodic status pushes; start with
  469. # self.serial as the fallback until we learn the slicer's
  470. # preferred serial from the first SUBSCRIBE/PUBLISH.
  471. self._clients[client_id] = writer
  472. self._client_serials[client_id] = self.serial
  473. elif packet_type == 3: # PUBLISH
  474. if authenticated:
  475. await self._handle_publish(header[0], payload, writer, client_id)
  476. elif packet_type == 8: # SUBSCRIBE
  477. if authenticated:
  478. await self._handle_subscribe(payload, writer, client_id)
  479. elif packet_type == 12: # PINGREQ
  480. # Send PINGRESP
  481. writer.write(bytes([0xD0, 0x00]))
  482. await writer.drain()
  483. elif packet_type == 14: # DISCONNECT
  484. break
  485. except asyncio.CancelledError:
  486. pass # Expected when server is shutting down and cancels client tasks
  487. except Exception as e:
  488. # Outer handler — inner handlers already absorb expected parser
  489. # / IO failures at debug. Anything reaching here is unexpected
  490. # and would otherwise silently drop the slicer connection with
  491. # no actionable signal in production logs (defaults are INFO+).
  492. logger.warning("%sMQTT client session error from %s: %s", self._log_prefix, client_id, e)
  493. finally:
  494. logger.debug("MQTT client disconnected: %s", client_id)
  495. self._clients.pop(client_id, None)
  496. self._client_serials.pop(client_id, None)
  497. try:
  498. writer.close()
  499. await writer.wait_closed()
  500. except OSError:
  501. pass # Best-effort socket cleanup on client disconnect
  502. async def _read_remaining_length(self, reader: asyncio.StreamReader) -> int | None:
  503. """Read MQTT remaining length (variable byte integer)."""
  504. multiplier = 1
  505. value = 0
  506. for _ in range(4):
  507. try:
  508. byte = await reader.read(1)
  509. if not byte:
  510. return None
  511. encoded = byte[0]
  512. value += (encoded & 127) * multiplier
  513. if (encoded & 128) == 0:
  514. return value
  515. multiplier *= 128
  516. except OSError:
  517. return None
  518. return None
  519. def _record_pending_request(self, data: dict, client_id: str) -> None:
  520. """Stash sequence_id → client_id for any nested block with a sequence_id.
  521. Slicer commands typically wrap their seq id in ``{"print": {...}}`` or
  522. ``{"info": {...}}`` / ``{"system": {...}}`` etc. Walks top-level dict
  523. values once to find the seq id; if absent (some commands omit it) we
  524. skip — the response will fall through to broadcast which is fine for
  525. unsolicited pushes.
  526. """
  527. for block in data.values():
  528. if isinstance(block, dict):
  529. seq = block.get("sequence_id")
  530. if seq is not None:
  531. key = str(seq)
  532. # Evict oldest entry when over the cap. Python dicts
  533. # preserve insertion order so iter(self._pending_requests)
  534. # yields the oldest key first.
  535. while len(self._pending_requests) >= _PENDING_REQUEST_MAX_ENTRIES:
  536. oldest = next(iter(self._pending_requests))
  537. self._pending_requests.pop(oldest, None)
  538. self._pending_requests[key] = client_id
  539. return
  540. def _lookup_pending_request_client(self, payload: bytes) -> str | None:
  541. """Parse a bridge-forwarded MQTT payload and return the originating
  542. client_id if its sequence_id was recorded.
  543. Returns ``None`` for printer-initiated pushes (no recorded seq id) so
  544. push_raw_to_clients falls back to broadcast — required for push_status
  545. and the other unsolicited pushes that every connected slicer expects.
  546. """
  547. try:
  548. parsed = json.loads(payload)
  549. except (ValueError, TypeError):
  550. return None
  551. if not isinstance(parsed, dict):
  552. return None
  553. for block in parsed.values():
  554. if isinstance(block, dict):
  555. seq = block.get("sequence_id")
  556. if seq is not None:
  557. return self._pending_requests.pop(str(seq), None)
  558. return None
  559. def _is_auth_rate_limited(self, source_ip: str) -> bool:
  560. """Return True if ``source_ip`` has hit the per-IP failure cap.
  561. Prunes timestamps older than the window so the dict doesn't grow
  562. unbounded. Uses ``time.monotonic()`` for a wall-clock-jump-immune
  563. clock that's safe to call from any context (sync or async).
  564. """
  565. import time as _time
  566. now = _time.monotonic()
  567. window_start = now - _AUTH_RATE_LIMIT_WINDOW_SECONDS
  568. recent = [t for t in self._auth_failures.get(source_ip, []) if t >= window_start]
  569. if recent:
  570. self._auth_failures[source_ip] = recent
  571. else:
  572. self._auth_failures.pop(source_ip, None)
  573. return len(recent) >= _AUTH_RATE_LIMIT_MAX_ATTEMPTS
  574. def _record_auth_failure(self, source_ip: str) -> None:
  575. """Append a timestamp for ``source_ip``'s failed auth attempt."""
  576. import time as _time
  577. now = _time.monotonic()
  578. self._auth_failures.setdefault(source_ip, []).append(now)
  579. def _clear_auth_failures(self, source_ip: str) -> None:
  580. """Reset ``source_ip``'s failure history after a successful auth."""
  581. self._auth_failures.pop(source_ip, None)
  582. async def _handle_connect(self, payload: bytes, writer: asyncio.StreamWriter) -> tuple[bool, int]:
  583. """Handle MQTT CONNECT packet.
  584. Returns ``(authenticated, keep_alive_seconds)`` — the second element
  585. is the value the client advertised in CONNECT, so the caller's
  586. read-loop can honour it instead of the hardcoded default. ``0``
  587. means the client opted out of keepalive (#1548).
  588. """
  589. try:
  590. # Parse CONNECT packet
  591. # Skip protocol name length and name
  592. idx = 0
  593. proto_len = (payload[idx] << 8) | payload[idx + 1]
  594. idx += 2 + proto_len
  595. # Skip protocol level and connect flags
  596. # connect_flags = payload[idx + 1]
  597. idx += 2
  598. # Keepalive (2-byte big-endian, seconds). Honoured by the read
  599. # loop in `_handle_client` per MQTT spec §3.1.2.10 / §4.4 —
  600. # before #1548 we ignored this and used a hardcoded 60 s, which
  601. # closed OrcaSlicer's idle connection at exactly the negotiated
  602. # keepalive boundary instead of the spec-mandated 1.5×.
  603. keep_alive = (payload[idx] << 8) | payload[idx + 1]
  604. idx += 2
  605. # Read client ID
  606. client_id_len = (payload[idx] << 8) | payload[idx + 1]
  607. idx += 2
  608. # client_id = payload[idx : idx + client_id_len].decode("utf-8")
  609. idx += client_id_len
  610. # Read username
  611. username_len = (payload[idx] << 8) | payload[idx + 1]
  612. idx += 2
  613. username = payload[idx : idx + username_len].decode("utf-8")
  614. idx += username_len
  615. # Read password
  616. password_len = (payload[idx] << 8) | payload[idx + 1]
  617. idx += 2
  618. password = payload[idx : idx + password_len].decode("utf-8")
  619. # Authenticate. ``hmac.compare_digest`` is constant-time to keep
  620. # the auth check from leaking the access code via response timing
  621. # under network jitter — LAN-only threat is marginal, but it's
  622. # the standard fix and costs nothing.
  623. if username == "bblp" and hmac.compare_digest(password, self.access_code):
  624. # Send CONNACK with success
  625. writer.write(bytes([0x20, 0x02, 0x00, 0x00]))
  626. await writer.drain()
  627. logger.info("%sMQTT client authenticated successfully", self._log_prefix)
  628. # Send immediate status report after auth - slicer expects this
  629. await self._send_status_report(writer)
  630. return True, keep_alive
  631. else:
  632. # Send CONNACK with auth failure
  633. writer.write(bytes([0x20, 0x02, 0x00, 0x05])) # Not authorized
  634. await writer.drain()
  635. logger.warning("%sMQTT auth failed for user '%s' (access code mismatch)", self._log_prefix, username)
  636. return False, 0
  637. except (IndexError, ValueError) as e:
  638. logger.debug("MQTT CONNECT parse error: %s", e)
  639. # Send CONNACK with error
  640. writer.write(bytes([0x20, 0x02, 0x00, 0x02])) # Protocol error
  641. await writer.drain()
  642. return False, 0
  643. async def _handle_subscribe(self, payload: bytes, writer: asyncio.StreamWriter, client_id: str) -> None:
  644. """Handle MQTT SUBSCRIBE packet."""
  645. try:
  646. # Parse packet ID
  647. packet_id = (payload[0] << 8) | payload[1]
  648. # Parse topic filters (just acknowledge them)
  649. idx = 2
  650. granted_qos = []
  651. learned_serial: str | None = None
  652. while idx < len(payload):
  653. topic_len = (payload[idx] << 8) | payload[idx + 1]
  654. idx += 2
  655. topic = payload[idx : idx + topic_len].decode("utf-8")
  656. idx += topic_len
  657. requested_qos = payload[idx]
  658. idx += 1
  659. logger.info("%sMQTT subscribe: %s QoS=%s", self._log_prefix, topic, requested_qos)
  660. granted_qos.append(min(requested_qos, 1)) # Grant up to QoS 1
  661. # Remember the serial the slicer is listening on so status/version
  662. # responses go to a topic it actually subscribed to.
  663. if learned_serial is None:
  664. extracted = self._extract_serial_from_topic(topic)
  665. if extracted:
  666. learned_serial = extracted
  667. if learned_serial and learned_serial != self._client_serials.get(client_id):
  668. if learned_serial != self.serial:
  669. logger.info(
  670. "%sMQTT client subscribed with serial %s (VP serial is %s) — adapting responses",
  671. self._log_prefix,
  672. learned_serial,
  673. self.serial,
  674. )
  675. self._client_serials[client_id] = learned_serial
  676. # Send SUBACK
  677. suback = bytes([0x90, 2 + len(granted_qos), packet_id >> 8, packet_id & 0xFF])
  678. suback += bytes(granted_qos)
  679. writer.write(suback)
  680. await writer.drain()
  681. # Send initial status report after subscribe on the client's subscribed topic
  682. await self._send_status_report(writer, serial=self._client_serials.get(client_id, self.serial))
  683. except (IndexError, ValueError, OSError) as e:
  684. logger.debug("MQTT SUBSCRIBE error: %s", e)
  685. async def _send_status_report(
  686. self, writer: asyncio.StreamWriter, serial: str | None = None, log_event: bool = True
  687. ) -> None:
  688. """Send a status report to the slicer after connection.
  689. When a bridge is active and has cached the real printer's latest
  690. push_status, send a copy of the real push with only the upload-state-
  691. machine fields we own (gcode_state, gcode_file, prepare_percent,
  692. subtask_name) overridden. BambuStudio's Send pre-flight checks the
  693. push_status shape against what it expects from the printer model, and
  694. the synthetic stub introduced fields the real H2D doesn't have (storage,
  695. the wrong chamber_temper shape, etc.) which trip the check.
  696. While the target printer is actually printing and the VP has no upload
  697. handshake of its own in flight, the live-progress fields are mirrored
  698. through instead of zeroed, under a forced gcode_state=FINISH — see
  699. ``_mirroring_live_progress`` for why that specific state (#1887).
  700. """
  701. try:
  702. self._sequence_id += 1
  703. cached = self._bridge.get_latest_print_state() if self._bridge is not None else None
  704. if isinstance(cached, dict):
  705. # Real-printer-shaped response. Copy the cache, then replace the
  706. # protocol / upload-state fields with values under our control.
  707. # Deep copy — current mutations are top-level only, but a future
  708. # override that writes into a nested dict (e.g. ``online``,
  709. # ``upgrade_state``, ``ipcam``) would otherwise corrupt the
  710. # bridge cache and be read by every subsequent subscriber until
  711. # the next real-printer push lands. Cost is one allocation per
  712. # status report; the cached dict is already short-lived.
  713. print_block = copy.deepcopy(cached)
  714. print_block["sequence_id"] = str(self._sequence_id)
  715. print_block["command"] = "push_status"
  716. print_block["msg"] = 0
  717. mirroring = self._mirroring_live_progress(cached)
  718. if mirroring:
  719. # gcode_file / subtask_name / the progress fields stay as the
  720. # printer reported them — the slicer renders what is really
  721. # on the bed. FINISH keeps the Send button enabled.
  722. print_block["gcode_state"] = "FINISH"
  723. print_block["gcode_file_prepare_percent"] = "100"
  724. print_block.setdefault("subtask_name", "")
  725. else:
  726. print_block["gcode_state"] = self._gcode_state
  727. print_block["gcode_file"] = self._current_file
  728. print_block["gcode_file_prepare_percent"] = self._prepare_percent
  729. if self._current_file:
  730. print_block["subtask_name"] = self._current_file.replace(".3mf", "")
  731. else:
  732. # Don't override real subtask_name with empty if no upload pending.
  733. print_block.setdefault("subtask_name", "")
  734. # Storage-availability indicators the slicer's "Send" pre-flight reads
  735. # (#1228). P1S/A1-class firmware doesn't always include these in
  736. # push_status (no SD card inserted, older field shapes), and BambuStudio
  737. # rejects the send pre-flight with the generic "storage needs to be
  738. # inserted before send to printer" error before even attempting FTP.
  739. # For VP usage the slicer uploads via FTPS to Bambuddy's filesystem —
  740. # the printer's actual SD/storage state is irrelevant on that path.
  741. # Force "available" indicators so the pre-flight passes regardless of
  742. # what the real printer reports. Restores the 0.2.3.2 synthetic-stub
  743. # behaviour for these fields without losing the live AMS / k-profile /
  744. # camera mirror cached-as-base provides.
  745. print_block["home_flag"] = print_block.get("home_flag", 0) | 0x100 # bit 8 = HAS_SDCARD_NORMAL
  746. print_block["sdcard"] = True
  747. print_block.setdefault("storage", {"free": 1_000_000_000, "total": 32_000_000_000})
  748. # Live-progress fields the slicer's Send pre-flight reads
  749. # (#1558). When the VP reports itself idle, these have to read
  750. # idle too: the cached push_status carries the printer's real
  751. # values, and a report that says gcode_state=IDLE while
  752. # mc_percent>0 / stg_cur>0 is internally contradictory — the
  753. # slicer takes it as busy and blocks Send. Same shape as #1228
  754. # (storage). When the mirror is on, gcode_state=FINISH agrees
  755. # with a non-zero progress set, so they pass through instead.
  756. if not mirroring:
  757. print_block["mc_print_stage"] = ""
  758. print_block["mc_percent"] = 0
  759. print_block["mc_remaining_time"] = 0
  760. print_block["stg"] = []
  761. print_block["stg_cur"] = 0
  762. print_block["layer_num"] = 0
  763. print_block["total_layer_num"] = 0
  764. # print_error is never mirrored: StatusPanel raises a modal error
  765. # dialog for a non-zero code, and the VP is not the machine that
  766. # threw it — the user's own printer card in Bambuddy reports the
  767. # fault. Zero it in both branches.
  768. print_block["print_error"] = 0
  769. status = {"print": print_block}
  770. dump_wire(self.vp_name, "out", status)
  771. await self._publish_to_report(writer, status, serial or self.serial, log_event=log_event)
  772. return
  773. # No bridge / no cache yet — fall back to the synthetic stub.
  774. status = {
  775. "print": {
  776. "sequence_id": str(self._sequence_id),
  777. "command": "push_status",
  778. "msg": 0,
  779. "gcode_state": self._gcode_state,
  780. "gcode_file": self._current_file,
  781. "gcode_file_prepare_percent": self._prepare_percent,
  782. "subtask_name": self._current_file.replace(".3mf", "") if self._current_file else "",
  783. "mc_print_stage": "",
  784. "mc_percent": 0,
  785. "mc_remaining_time": 0,
  786. "wifi_signal": "-44dBm",
  787. "print_error": 0,
  788. "print_type": "",
  789. "bed_temper": 25.0,
  790. "bed_target_temper": 0.0,
  791. "nozzle_temper": 25.0,
  792. "nozzle_target_temper": 0.0,
  793. "chamber_temper": 25.0,
  794. "cooling_fan_speed": "0",
  795. "big_fan1_speed": "0",
  796. "big_fan2_speed": "0",
  797. "heatbreak_fan_speed": "0",
  798. "spd_lvl": 1,
  799. "spd_mag": 100,
  800. "stg": [],
  801. "stg_cur": 0,
  802. "layer_num": 0,
  803. "total_layer_num": 0,
  804. "home_flag": 256, # Bit 8 = SD card present (HAS_SDCARD_NORMAL)
  805. "hw_switch_state": 0,
  806. "online": {"ahb": False, "rfid": False, "version": 7},
  807. "ams_status": 0,
  808. "sdcard": True,
  809. "storage": {"free": 1000000000, "total": 32000000000},
  810. "upgrade_state": {
  811. "sequence_id": 0,
  812. "progress": "",
  813. "status": "",
  814. "consistency_request": False,
  815. "dis_state": 0,
  816. "err_code": 0,
  817. "force_upgrade": False,
  818. "message": "",
  819. "module": "",
  820. "new_version_state": 2,
  821. "new_ver_list": [],
  822. "ota_new_version_number": "",
  823. "ahb_new_version_number": "",
  824. },
  825. "ipcam": {
  826. "ipcam_dev": "1",
  827. "ipcam_record": "enable",
  828. "timelapse": "disable",
  829. "resolution": "1080p",
  830. "mode_bits": 0,
  831. },
  832. "xcam": {
  833. "allow_skip_parts": False,
  834. "buildplate_marker_detector": True,
  835. "first_layer_inspector": True,
  836. "halt_print_sensitivity": "medium",
  837. "print_halt": True,
  838. "printing_monitor": True,
  839. "spaghetti_detector": True,
  840. },
  841. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  842. "nozzle_diameter": "0.4",
  843. "nozzle_type": "hardened_steel",
  844. }
  845. }
  846. await self._publish_to_report(writer, status, serial or self.serial, log_event=log_event)
  847. except OSError as e:
  848. logger.error("Failed to send status report: %s", e)
  849. async def _send_version_response(
  850. self, writer: asyncio.StreamWriter, sequence_id: str, serial: str | None = None
  851. ) -> None:
  852. """Send version info response to the slicer."""
  853. try:
  854. product_name = MODEL_PRODUCT_NAMES.get(self.model, self.model or "X1 Carbon")
  855. # The serial is embedded inside the module[].sn fields *and* used as
  856. # the report topic. Use the client's effective serial so the slicer
  857. # sees internal/topic consistency even when it differs from self.serial.
  858. serial = serial or self.serial
  859. # Build version response matching OrcaSlicer expectations
  860. # Required fields per module: name, product_name, sw_ver, sw_new_ver, sn, hw_ver, flag
  861. version_info = {
  862. "info": {
  863. "command": "get_version",
  864. "sequence_id": sequence_id,
  865. "module": [
  866. {
  867. "name": "ota",
  868. "product_name": product_name,
  869. "sw_ver": "01.07.00.00",
  870. "sw_new_ver": "",
  871. "hw_ver": "OTA",
  872. "sn": serial,
  873. "flag": 0,
  874. },
  875. {
  876. "name": "esp32",
  877. "product_name": product_name,
  878. "sw_ver": "01.07.22.25",
  879. "sw_new_ver": "",
  880. "hw_ver": "AP05",
  881. "sn": serial,
  882. "flag": 0,
  883. },
  884. {
  885. "name": "rv1126",
  886. "product_name": product_name,
  887. "sw_ver": "00.00.27.38",
  888. "sw_new_ver": "",
  889. "hw_ver": "AP05",
  890. "sn": serial,
  891. "flag": 0,
  892. },
  893. {
  894. "name": "th",
  895. "product_name": product_name,
  896. "sw_ver": "00.00.04.00",
  897. "sw_new_ver": "",
  898. "hw_ver": "TH07",
  899. "sn": serial,
  900. "flag": 0,
  901. },
  902. {
  903. "name": "mc",
  904. "product_name": product_name,
  905. "sw_ver": "00.00.10.00",
  906. "sw_new_ver": "",
  907. "hw_ver": "MC07",
  908. "sn": serial,
  909. "flag": 0,
  910. },
  911. ],
  912. }
  913. }
  914. # Overlay real version modules from the bridge cache when available
  915. # (specifically the AMS modules ams/0, n3f/0, n3s/128 etc. that
  916. # BambuStudio's Prepare tab uses to identify AMS hardware — without
  917. # them every AMS unit shows as "unknown" in the Prepare panel).
  918. if self._bridge is not None:
  919. cached_modules = self._bridge.get_latest_version_modules()
  920. if isinstance(cached_modules, list) and cached_modules:
  921. version_info["info"]["module"] = cached_modules
  922. await self._publish_to_report(writer, version_info, serial)
  923. logger.info("Sent version response (product_name=%s)", product_name)
  924. except OSError as e:
  925. logger.error("Failed to send version response: %s", e)
  926. def set_gcode_state(self, state: str, filename: str = "", prepare_percent: str = "0") -> None:
  927. """Update the gcode state reported to connected slicers.
  928. Called by the manager to reflect FTP upload progress/completion.
  929. """
  930. self._gcode_state = state
  931. self._current_file = filename
  932. self._prepare_percent = prepare_percent
  933. self._state_changed_at = time.monotonic()
  934. def _mirroring_live_progress(self, cached: dict) -> bool:
  935. """True when the report should carry the target printer's live progress.
  936. The slicers gate the Device-tab progress panel and the Send button on
  937. the same predicate (``MachineObject::is_in_printing()``), so the VP
  938. cannot report the printer's real gcode_state without also telling the
  939. slicer it is too busy to accept a job — which is the whole point of a
  940. non-proxy VP, and was the #1558 regression. Reporting FINISH instead
  941. renders the panel (StatusPanel checks ``is_in_printing() ||
  942. print_status == "FINISH"``) and leaves Send enabled, so the mirror is
  943. FINISH plus the printer's real numbers.
  944. Two things suppress it:
  945. * The VP's own upload state machine owns the report while a job is
  946. being handed over (PREPARE), and for a short settle window after —
  947. the slicer only releases its in-flight-job lock once it sees FINISH
  948. carrying the ``subtask_name`` it just uploaded (#1280 / #1658), and
  949. swapping in the printer's filename mid-handshake wedges the send
  950. modal at "Downloading".
  951. * The printer isn't printing, in which case there is no progress to
  952. show and the VP's own state is the honest thing to report.
  953. """
  954. if self._gcode_state == "PREPARE":
  955. return False
  956. if time.monotonic() - self._state_changed_at < _UPLOAD_SETTLE_SECONDS:
  957. return False
  958. return str(cached.get("gcode_state") or "").upper() in _MIRRORED_PRINT_STATES
  959. async def _publish_to_report(
  960. self, writer: asyncio.StreamWriter, payload: dict, serial: str = "", log_event: bool = True
  961. ) -> None:
  962. """Publish a message on the device report topic.
  963. Real Bambu printers wire-format push_status JSON with 4-space indentation
  964. (32254 bytes for an idle H2D push vs 14268 bytes compact). BambuStudio's
  965. Send pre-flight rejects compact JSON — without matching the on-wire
  966. format the slicer never proceeds to FTP upload.
  967. ``log_event=True`` records the publish in ``vp_wire/<vp>_cmd.jsonl``
  968. under the ``bridge_to_slicer`` direction so #1622-style triages can
  969. diff the bridge's own outbound replies (info.get_version answer,
  970. project_file ack, on-demand pushall response) against the real
  971. printer's ``printer_to_slicer`` forwards. The 1Hz periodic push
  972. sets ``log_event=False`` because dump_wire's overwrite-snapshot
  973. already covers cache shape and a per-second JSONL line would dwarf
  974. the actual command events.
  975. """
  976. topic = f"device/{serial or self.serial}/report"
  977. message = json.dumps(payload, indent=4)
  978. topic_bytes = topic.encode("utf-8")
  979. message_bytes = message.encode("utf-8")
  980. remaining = 2 + len(topic_bytes) + len(message_bytes)
  981. packet = bytes([0x30]) # PUBLISH, QoS 0
  982. while remaining > 0:
  983. byte = remaining % 128
  984. remaining //= 128
  985. if remaining > 0:
  986. byte |= 0x80
  987. packet += bytes([byte])
  988. packet += bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF])
  989. packet += topic_bytes
  990. packet += message_bytes
  991. if log_event:
  992. # Env-flagged command trace (#1622): captures bridge-synthesised
  993. # replies (info.get_version, project_file ack, on-demand pushall
  994. # response) AFTER the payload is finalised but before it hits
  995. # the wire — so the cmd.jsonl reflects exactly what the slicer
  996. # parses. Pair with the slicer_to_bridge events from
  997. # _handle_publish and the printer_to_slicer fan-outs from
  998. # mqtt_bridge.
  999. append_event(self.vp_name, "bridge_to_slicer", topic, payload)
  1000. writer.write(packet)
  1001. # Timeout the drain to prevent blocking the event loop if the
  1002. # MQTT client stops reading (e.g. slicer busy with FTP upload,
  1003. # macOS suspends the client mid-session — #1872).
  1004. #
  1005. # On timeout, close the writer and raise BrokenPipeError so the
  1006. # push-loop's ``except OSError`` at ``_periodic_status_push``
  1007. # evicts the client from ``self._clients`` on this same tick.
  1008. # Before this, timeouts logged at DEBUG and returned silently,
  1009. # so the zombie writer sat in ``self._clients`` until SO_KEEPALIVE
  1010. # detected the dead peer (~2 h on Linux defaults). That kept the
  1011. # push loop spending 5 s per iteration on the stalled client and
  1012. # left the slicer's UI unaware the session was gone.
  1013. try:
  1014. await asyncio.wait_for(writer.drain(), timeout=5)
  1015. except TimeoutError as e:
  1016. logger.info(
  1017. "%sMQTT drain timeout for %s — closing stalled writer",
  1018. self._log_prefix,
  1019. topic,
  1020. )
  1021. try:
  1022. writer.close()
  1023. except Exception:
  1024. pass # best-effort — writer may already be broken
  1025. raise BrokenPipeError(f"drain timeout on {topic}") from e
  1026. async def _send_print_response(
  1027. self, writer: asyncio.StreamWriter, sequence_id: str, filename: str, serial: str | None = None
  1028. ) -> None:
  1029. """Send project_file acknowledgment matching real Bambu printer behavior."""
  1030. # Update state so periodic status pushes reflect preparation. Goes
  1031. # through set_gcode_state so the live-progress mirror sees the
  1032. # transition and holds off until the upload handshake has settled.
  1033. self.set_gcode_state("PREPARE", filename=filename, prepare_percent="0")
  1034. try:
  1035. # Send command acknowledgment — slicer expects to see
  1036. # command: "project_file" echoed back before starting FTP upload
  1037. subtask_name = filename.replace(".3mf", "") if filename else ""
  1038. response = {
  1039. "print": {
  1040. "command": "project_file",
  1041. "sequence_id": sequence_id,
  1042. "param": "Metadata/plate_1.gcode",
  1043. "subtask_name": subtask_name,
  1044. "gcode_state": "PREPARE",
  1045. "gcode_file": filename,
  1046. "gcode_file_prepare_percent": "0",
  1047. "result": "SUCCESS",
  1048. "msg": 0,
  1049. }
  1050. }
  1051. await self._publish_to_report(writer, response, serial or self.serial)
  1052. logger.info("Sent project_file acknowledgment for %s", filename)
  1053. except OSError as e:
  1054. logger.error("Failed to send print response: %s", e)
  1055. async def _handle_publish(self, header: int, payload: bytes, writer: asyncio.StreamWriter, client_id: str) -> None:
  1056. """Handle MQTT PUBLISH packet."""
  1057. try:
  1058. # Parse topic
  1059. idx = 0
  1060. topic_len = (payload[idx] << 8) | payload[idx + 1]
  1061. idx += 2
  1062. topic = payload[idx : idx + topic_len].decode("utf-8")
  1063. idx += topic_len
  1064. # Check for packet ID (QoS > 0)
  1065. qos = (header & 0x06) >> 1
  1066. if qos > 0:
  1067. # packet_id = (payload[idx] << 8) | payload[idx + 1]
  1068. idx += 2
  1069. # Parse message
  1070. message = payload[idx:].decode("utf-8")
  1071. logger.info("MQTT publish to %s: %s...", topic, message[:100])
  1072. # Only handle publishes on *some* device/.../request topic. The
  1073. # serial is taken from the topic rather than compared against
  1074. # self.serial: the client is already authenticated via the access
  1075. # code, and Orca/BambuStudio may have a cached serial that differs
  1076. # from the VP's computed self.serial (#927). Use the topic's serial
  1077. # for all responses so they land on the topic the slicer subscribed
  1078. # to.
  1079. if not topic.startswith("device/") or "/request" not in topic:
  1080. return
  1081. client_serial = self._extract_serial_from_topic(topic) or self.serial
  1082. if client_serial and client_serial != self._client_serials.get(client_id):
  1083. if client_serial != self.serial:
  1084. logger.info(
  1085. "%sMQTT client publishing with serial %s (VP serial is %s) — adapting responses",
  1086. self._log_prefix,
  1087. client_serial,
  1088. self.serial,
  1089. )
  1090. self._client_serials[client_id] = client_serial
  1091. try:
  1092. # Some slicer builds (observed with OrcaSlicer on Linux, #927)
  1093. # include the C-string null terminator in the MQTT payload
  1094. # length, so the decoded message ends with \x00. Real brokers
  1095. # pass the bytes through; strict json.loads raises "Extra data"
  1096. # and every pushall/get_version/project_file silently dropped.
  1097. data = json.loads(message.rstrip("\x00 \r\n\t"))
  1098. except json.JSONDecodeError as e:
  1099. logger.debug(
  1100. "MQTT publish JSON decode failed: %s (payload=%r)",
  1101. e,
  1102. message[:200],
  1103. )
  1104. return
  1105. # Env-flagged command trace (#1622): every slicer-originated publish
  1106. # gets a line in vp_wire/<vp>_cmd.jsonl alongside the printer-side
  1107. # responses captured in mqtt_bridge. Off by default.
  1108. append_event(self.vp_name, "slicer_to_bridge", topic, data)
  1109. # The synthetic flow below is the original (pre-bridge) behaviour and is
  1110. # what the proven-working FTP "Send" depends on. Do NOT replace any
  1111. # synthetic response with a forward — only ADD forwarding alongside,
  1112. # at the bottom, for commands the synthetic flow doesn't handle
  1113. # (AMS write / xcam / system / etc., which need to actually reach
  1114. # the real printer).
  1115. handled_locally = False
  1116. # Handle pushing command (status request)
  1117. if "pushing" in data:
  1118. pushing_data = data["pushing"]
  1119. command = pushing_data.get("command", "")
  1120. logger.info("MQTT pushing command: %s", command)
  1121. if command == "pushall":
  1122. logger.info("Sending status report in response to pushall")
  1123. await self._send_status_report(writer, serial=client_serial)
  1124. handled_locally = True
  1125. elif command == "start":
  1126. logger.info("Starting status push stream")
  1127. await self._send_status_report(writer, serial=client_serial)
  1128. handled_locally = True
  1129. # Handle info commands (get_version, etc.)
  1130. if "info" in data:
  1131. info_data = data["info"]
  1132. command = info_data.get("command", "")
  1133. sequence_id = info_data.get("sequence_id", "0")
  1134. logger.info("MQTT info command: %s", command)
  1135. if command == "get_version":
  1136. await self._send_version_response(writer, sequence_id, serial=client_serial)
  1137. handled_locally = True
  1138. # Handle print commands
  1139. if "print" in data:
  1140. print_data = data["print"]
  1141. command = print_data.get("command", "")
  1142. filename = print_data.get("subtask_name", "")
  1143. sequence_id = print_data.get("sequence_id", "0")
  1144. logger.info("MQTT print command: %s for %s", command, filename)
  1145. if command in ("project_file", "gcode_file"):
  1146. # File lives on Bambuddy, not the printer — synthetic only.
  1147. file_3mf = print_data.get("file", filename)
  1148. await self._send_print_response(writer, sequence_id, file_3mf, serial=client_serial)
  1149. if self.on_print_command:
  1150. # `filename` is the slicer's `subtask_name` (bare model
  1151. # name, no extension). Pass it through verbatim — the
  1152. # `_schedule_finish_release` chain echoes it back as
  1153. # gcode_file + subtask_name in push_status, and the
  1154. # slicer matches against its own subtask_name there.
  1155. # The FTP filename (with extension) is in print_data
  1156. # under "file" for the queue-stash side to use as its
  1157. # own key matching `_add_to_print_queue`'s lookup.
  1158. await self._notify_print_command(filename, print_data)
  1159. handled_locally = True
  1160. # Forward anything the synthetic flow didn't handle to the real
  1161. # printer. AMS load / dry / xcam / system / extrusion_cali_get etc.
  1162. if not handled_locally and self._bridge is not None and self._bridge.is_active:
  1163. # Remember which client originated this command so the
  1164. # printer's response goes back only to them (not fanned
  1165. # out to every connected slicer).
  1166. self._record_pending_request(data, client_id)
  1167. self._bridge.forward_to_printer(data)
  1168. except (IndexError, ValueError, OSError) as e:
  1169. logger.debug("MQTT PUBLISH error: %s", e)
  1170. async def _notify_print_command(self, filename: str, data: dict) -> None:
  1171. """Notify callback of print command."""
  1172. if self.on_print_command:
  1173. try:
  1174. result = self.on_print_command(filename, data)
  1175. if asyncio.iscoroutine(result):
  1176. await result
  1177. except Exception as e:
  1178. logger.error("Print command callback error: %s", e)