mqtt_server.py 62 KB

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