mqtt_server.py 56 KB

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