mqtt_server.py 61 KB

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