mqtt_server.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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. sock = writer.get_extra_info("socket")
  519. if sock is not None:
  520. try:
  521. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  522. except OSError as e:
  523. logger.debug("%sFailed to set SO_KEEPALIVE on %s: %s", self._log_prefix, client_id, e)
  524. # Register client for periodic status pushes; start with
  525. # self.serial as the fallback until we learn the slicer's
  526. # preferred serial from the first SUBSCRIBE/PUBLISH.
  527. self._clients[client_id] = writer
  528. self._client_serials[client_id] = self.serial
  529. elif packet_type == 3: # PUBLISH
  530. if authenticated:
  531. await self._handle_publish(header[0], payload, writer, client_id)
  532. elif packet_type == 8: # SUBSCRIBE
  533. if authenticated:
  534. await self._handle_subscribe(payload, writer, client_id)
  535. elif packet_type == 12: # PINGREQ
  536. # Send PINGRESP
  537. writer.write(bytes([0xD0, 0x00]))
  538. await writer.drain()
  539. elif packet_type == 14: # DISCONNECT
  540. break
  541. except asyncio.CancelledError:
  542. pass # Expected when server is shutting down and cancels client tasks
  543. except Exception as e:
  544. # Outer handler — inner handlers already absorb expected parser
  545. # / IO failures at debug. Anything reaching here is unexpected
  546. # and would otherwise silently drop the slicer connection with
  547. # no actionable signal in production logs (defaults are INFO+).
  548. logger.warning("%sMQTT client session error from %s: %s", self._log_prefix, client_id, e)
  549. finally:
  550. logger.debug("MQTT client disconnected: %s", client_id)
  551. self._clients.pop(client_id, None)
  552. self._client_serials.pop(client_id, None)
  553. try:
  554. writer.close()
  555. await writer.wait_closed()
  556. except OSError:
  557. pass # Best-effort socket cleanup on client disconnect
  558. async def _read_remaining_length(self, reader: asyncio.StreamReader) -> int | None:
  559. """Read MQTT remaining length (variable byte integer)."""
  560. multiplier = 1
  561. value = 0
  562. for _ in range(4):
  563. try:
  564. byte = await reader.read(1)
  565. if not byte:
  566. return None
  567. encoded = byte[0]
  568. value += (encoded & 127) * multiplier
  569. if (encoded & 128) == 0:
  570. return value
  571. multiplier *= 128
  572. except OSError:
  573. return None
  574. return None
  575. def _record_pending_request(self, data: dict, client_id: str) -> None:
  576. """Stash sequence_id → client_id for any nested block with a sequence_id.
  577. Slicer commands typically wrap their seq id in ``{"print": {...}}`` or
  578. ``{"info": {...}}`` / ``{"system": {...}}`` etc. Walks top-level dict
  579. values once to find the seq id; if absent (some commands omit it) we
  580. skip — the response will fall through to broadcast which is fine for
  581. unsolicited pushes.
  582. """
  583. for block in data.values():
  584. if isinstance(block, dict):
  585. seq = block.get("sequence_id")
  586. if seq is not None:
  587. key = str(seq)
  588. # Evict oldest entry when over the cap. Python dicts
  589. # preserve insertion order so iter(self._pending_requests)
  590. # yields the oldest key first.
  591. while len(self._pending_requests) >= _PENDING_REQUEST_MAX_ENTRIES:
  592. oldest = next(iter(self._pending_requests))
  593. self._pending_requests.pop(oldest, None)
  594. self._pending_requests[key] = client_id
  595. return
  596. def _lookup_pending_request_client(self, payload: bytes) -> str | None:
  597. """Parse a bridge-forwarded MQTT payload and return the originating
  598. client_id if its sequence_id was recorded.
  599. Returns ``None`` for printer-initiated pushes (no recorded seq id) so
  600. push_raw_to_clients falls back to broadcast — required for push_status
  601. and the other unsolicited pushes that every connected slicer expects.
  602. """
  603. try:
  604. parsed = json.loads(payload)
  605. except (ValueError, TypeError):
  606. return None
  607. if not isinstance(parsed, dict):
  608. return None
  609. for block in parsed.values():
  610. if isinstance(block, dict):
  611. seq = block.get("sequence_id")
  612. if seq is not None:
  613. return self._pending_requests.pop(str(seq), None)
  614. return None
  615. def _is_auth_rate_limited(self, source_ip: str) -> bool:
  616. """Return True if ``source_ip`` has hit the per-IP failure cap.
  617. Prunes timestamps older than the window so the dict doesn't grow
  618. unbounded. Uses ``time.monotonic()`` for a wall-clock-jump-immune
  619. clock that's safe to call from any context (sync or async).
  620. """
  621. import time as _time
  622. now = _time.monotonic()
  623. window_start = now - _AUTH_RATE_LIMIT_WINDOW_SECONDS
  624. recent = [t for t in self._auth_failures.get(source_ip, []) if t >= window_start]
  625. if recent:
  626. self._auth_failures[source_ip] = recent
  627. else:
  628. self._auth_failures.pop(source_ip, None)
  629. return len(recent) >= _AUTH_RATE_LIMIT_MAX_ATTEMPTS
  630. def _record_auth_failure(self, source_ip: str) -> None:
  631. """Append a timestamp for ``source_ip``'s failed auth attempt."""
  632. import time as _time
  633. now = _time.monotonic()
  634. self._auth_failures.setdefault(source_ip, []).append(now)
  635. def _clear_auth_failures(self, source_ip: str) -> None:
  636. """Reset ``source_ip``'s failure history after a successful auth."""
  637. self._auth_failures.pop(source_ip, None)
  638. async def _handle_connect(self, payload: bytes, writer: asyncio.StreamWriter) -> tuple[bool, int]:
  639. """Handle MQTT CONNECT packet.
  640. Returns ``(authenticated, keep_alive_seconds)`` — the second element
  641. is the value the client advertised in CONNECT, so the caller's
  642. read-loop can honour it instead of the hardcoded default. ``0``
  643. means the client opted out of keepalive (#1548).
  644. """
  645. try:
  646. # Parse CONNECT packet
  647. # Skip protocol name length and name
  648. idx = 0
  649. proto_len = (payload[idx] << 8) | payload[idx + 1]
  650. idx += 2 + proto_len
  651. # Skip protocol level and connect flags
  652. # connect_flags = payload[idx + 1]
  653. idx += 2
  654. # Keepalive (2-byte big-endian, seconds). Honoured by the read
  655. # loop in `_handle_client` per MQTT spec §3.1.2.10 / §4.4 —
  656. # before #1548 we ignored this and used a hardcoded 60 s, which
  657. # closed OrcaSlicer's idle connection at exactly the negotiated
  658. # keepalive boundary instead of the spec-mandated 1.5×.
  659. keep_alive = (payload[idx] << 8) | payload[idx + 1]
  660. idx += 2
  661. # Read client ID
  662. client_id_len = (payload[idx] << 8) | payload[idx + 1]
  663. idx += 2
  664. # client_id = payload[idx : idx + client_id_len].decode("utf-8")
  665. idx += client_id_len
  666. # Read username
  667. username_len = (payload[idx] << 8) | payload[idx + 1]
  668. idx += 2
  669. username = payload[idx : idx + username_len].decode("utf-8")
  670. idx += username_len
  671. # Read password
  672. password_len = (payload[idx] << 8) | payload[idx + 1]
  673. idx += 2
  674. password = payload[idx : idx + password_len].decode("utf-8")
  675. # Authenticate. ``hmac.compare_digest`` is constant-time to keep
  676. # the auth check from leaking the access code via response timing
  677. # under network jitter — LAN-only threat is marginal, but it's
  678. # the standard fix and costs nothing.
  679. if username == "bblp" and hmac.compare_digest(password, self.access_code):
  680. # Send CONNACK with success
  681. writer.write(bytes([0x20, 0x02, 0x00, 0x00]))
  682. await writer.drain()
  683. logger.info("%sMQTT client authenticated successfully", self._log_prefix)
  684. # Send immediate status report after auth - slicer expects this
  685. await self._send_status_report(writer)
  686. return True, keep_alive
  687. else:
  688. # Send CONNACK with auth failure
  689. writer.write(bytes([0x20, 0x02, 0x00, 0x05])) # Not authorized
  690. await writer.drain()
  691. logger.warning("%sMQTT auth failed for user '%s' (access code mismatch)", self._log_prefix, username)
  692. return False, 0
  693. except (IndexError, ValueError) as e:
  694. logger.debug("MQTT CONNECT parse error: %s", e)
  695. # Send CONNACK with error
  696. writer.write(bytes([0x20, 0x02, 0x00, 0x02])) # Protocol error
  697. await writer.drain()
  698. return False, 0
  699. async def _handle_subscribe(self, payload: bytes, writer: asyncio.StreamWriter, client_id: str) -> None:
  700. """Handle MQTT SUBSCRIBE packet."""
  701. try:
  702. # Parse packet ID
  703. packet_id = (payload[0] << 8) | payload[1]
  704. # Parse topic filters (just acknowledge them)
  705. idx = 2
  706. granted_qos = []
  707. learned_serial: str | None = None
  708. while idx < len(payload):
  709. topic_len = (payload[idx] << 8) | payload[idx + 1]
  710. idx += 2
  711. topic = payload[idx : idx + topic_len].decode("utf-8")
  712. idx += topic_len
  713. requested_qos = payload[idx]
  714. idx += 1
  715. logger.info("%sMQTT subscribe: %s QoS=%s", self._log_prefix, topic, requested_qos)
  716. granted_qos.append(min(requested_qos, 1)) # Grant up to QoS 1
  717. # Remember the serial the slicer is listening on so status/version
  718. # responses go to a topic it actually subscribed to.
  719. if learned_serial is None:
  720. extracted = self._extract_serial_from_topic(topic)
  721. if extracted:
  722. learned_serial = extracted
  723. if learned_serial and learned_serial != self._client_serials.get(client_id):
  724. if learned_serial != self.serial:
  725. logger.info(
  726. "%sMQTT client subscribed with serial %s (VP serial is %s) — adapting responses",
  727. self._log_prefix,
  728. learned_serial,
  729. self.serial,
  730. )
  731. self._client_serials[client_id] = learned_serial
  732. # Send SUBACK
  733. suback = bytes([0x90, 2 + len(granted_qos), packet_id >> 8, packet_id & 0xFF])
  734. suback += bytes(granted_qos)
  735. writer.write(suback)
  736. await writer.drain()
  737. # Send initial status report after subscribe on the client's subscribed topic
  738. await self._send_status_report(writer, serial=self._client_serials.get(client_id, self.serial))
  739. except (IndexError, ValueError, OSError) as e:
  740. logger.debug("MQTT SUBSCRIBE error: %s", e)
  741. async def _send_status_report(
  742. self, writer: asyncio.StreamWriter, serial: str | None = None, log_event: bool = True
  743. ) -> None:
  744. """Send a status report to the slicer after connection.
  745. When a bridge is active and has cached the real printer's latest
  746. push_status, send a copy of the real push with only the upload-state-
  747. machine fields we own (gcode_state, gcode_file, prepare_percent,
  748. subtask_name) overridden. BambuStudio's Send pre-flight checks the
  749. push_status shape against what it expects from the printer model, and
  750. the synthetic stub introduced fields the real H2D doesn't have (storage,
  751. the wrong chamber_temper shape, etc.) which trip the check.
  752. """
  753. try:
  754. self._sequence_id += 1
  755. cached = self._bridge.get_latest_print_state() if self._bridge is not None else None
  756. if isinstance(cached, dict):
  757. # Real-printer-shaped response. Copy the cache, then replace the
  758. # protocol / upload-state fields with values under our control.
  759. # Deep copy — current mutations are top-level only, but a future
  760. # override that writes into a nested dict (e.g. ``online``,
  761. # ``upgrade_state``, ``ipcam``) would otherwise corrupt the
  762. # bridge cache and be read by every subsequent subscriber until
  763. # the next real-printer push lands. Cost is one allocation per
  764. # status report; the cached dict is already short-lived.
  765. print_block = copy.deepcopy(cached)
  766. print_block["sequence_id"] = str(self._sequence_id)
  767. print_block["command"] = "push_status"
  768. print_block["msg"] = 0
  769. print_block["gcode_state"] = self._gcode_state
  770. print_block["gcode_file"] = self._current_file
  771. print_block["gcode_file_prepare_percent"] = self._prepare_percent
  772. if self._current_file:
  773. print_block["subtask_name"] = self._current_file.replace(".3mf", "")
  774. else:
  775. # Don't override real subtask_name with empty if no upload pending.
  776. print_block.setdefault("subtask_name", "")
  777. # Storage-availability indicators the slicer's "Send" pre-flight reads
  778. # (#1228). P1S/A1-class firmware doesn't always include these in
  779. # push_status (no SD card inserted, older field shapes), and BambuStudio
  780. # rejects the send pre-flight with the generic "storage needs to be
  781. # inserted before send to printer" error before even attempting FTP.
  782. # For VP usage the slicer uploads via FTPS to Bambuddy's filesystem —
  783. # the printer's actual SD/storage state is irrelevant on that path.
  784. # Force "available" indicators so the pre-flight passes regardless of
  785. # what the real printer reports. Restores the 0.2.3.2 synthetic-stub
  786. # behaviour for these fields without losing the live AMS / k-profile /
  787. # camera mirror cached-as-base provides.
  788. print_block["home_flag"] = print_block.get("home_flag", 0) | 0x100 # bit 8 = HAS_SDCARD_NORMAL
  789. print_block["sdcard"] = True
  790. print_block.setdefault("storage", {"free": 1_000_000_000, "total": 32_000_000_000})
  791. # Live-progress fields the slicer's Send pre-flight reads
  792. # (#1558). When the real target printer is mid-print, the
  793. # cached push_status carries the real values for these
  794. # fields and the slicer reads the VP as "busy" — refusing
  795. # Send — even though gcode_state above is forced to IDLE.
  796. # For VP usage the VP isn't actually running the print
  797. # the printer is, so these need to mirror the synthetic
  798. # stub's idle values. Same shape as #1228 (storage) — the
  799. # cached-branch override set just needed extending.
  800. print_block["mc_print_stage"] = ""
  801. print_block["mc_percent"] = 0
  802. print_block["mc_remaining_time"] = 0
  803. print_block["stg"] = []
  804. print_block["stg_cur"] = 0
  805. print_block["layer_num"] = 0
  806. print_block["total_layer_num"] = 0
  807. print_block["print_error"] = 0
  808. status = {"print": print_block}
  809. dump_wire(self.vp_name, "out", status)
  810. await self._publish_to_report(writer, status, serial or self.serial, log_event=log_event)
  811. return
  812. # No bridge / no cache yet — fall back to the synthetic stub.
  813. status = {
  814. "print": {
  815. "sequence_id": str(self._sequence_id),
  816. "command": "push_status",
  817. "msg": 0,
  818. "gcode_state": self._gcode_state,
  819. "gcode_file": self._current_file,
  820. "gcode_file_prepare_percent": self._prepare_percent,
  821. "subtask_name": self._current_file.replace(".3mf", "") if self._current_file else "",
  822. "mc_print_stage": "",
  823. "mc_percent": 0,
  824. "mc_remaining_time": 0,
  825. "wifi_signal": "-44dBm",
  826. "print_error": 0,
  827. "print_type": "",
  828. "bed_temper": 25.0,
  829. "bed_target_temper": 0.0,
  830. "nozzle_temper": 25.0,
  831. "nozzle_target_temper": 0.0,
  832. "chamber_temper": 25.0,
  833. "cooling_fan_speed": "0",
  834. "big_fan1_speed": "0",
  835. "big_fan2_speed": "0",
  836. "heatbreak_fan_speed": "0",
  837. "spd_lvl": 1,
  838. "spd_mag": 100,
  839. "stg": [],
  840. "stg_cur": 0,
  841. "layer_num": 0,
  842. "total_layer_num": 0,
  843. "home_flag": 256, # Bit 8 = SD card present (HAS_SDCARD_NORMAL)
  844. "hw_switch_state": 0,
  845. "online": {"ahb": False, "rfid": False, "version": 7},
  846. "ams_status": 0,
  847. "sdcard": True,
  848. "storage": {"free": 1000000000, "total": 32000000000},
  849. "upgrade_state": {
  850. "sequence_id": 0,
  851. "progress": "",
  852. "status": "",
  853. "consistency_request": False,
  854. "dis_state": 0,
  855. "err_code": 0,
  856. "force_upgrade": False,
  857. "message": "",
  858. "module": "",
  859. "new_version_state": 2,
  860. "new_ver_list": [],
  861. "ota_new_version_number": "",
  862. "ahb_new_version_number": "",
  863. },
  864. "ipcam": {
  865. "ipcam_dev": "1",
  866. "ipcam_record": "enable",
  867. "timelapse": "disable",
  868. "resolution": "1080p",
  869. "mode_bits": 0,
  870. },
  871. "xcam": {
  872. "allow_skip_parts": False,
  873. "buildplate_marker_detector": True,
  874. "first_layer_inspector": True,
  875. "halt_print_sensitivity": "medium",
  876. "print_halt": True,
  877. "printing_monitor": True,
  878. "spaghetti_detector": True,
  879. },
  880. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  881. "nozzle_diameter": "0.4",
  882. "nozzle_type": "hardened_steel",
  883. }
  884. }
  885. await self._publish_to_report(writer, status, serial or self.serial, log_event=log_event)
  886. except OSError as e:
  887. logger.error("Failed to send status report: %s", e)
  888. async def _send_version_response(
  889. self, writer: asyncio.StreamWriter, sequence_id: str, serial: str | None = None
  890. ) -> None:
  891. """Send version info response to the slicer."""
  892. try:
  893. product_name = MODEL_PRODUCT_NAMES.get(self.model, self.model or "X1 Carbon")
  894. # The serial is embedded inside the module[].sn fields *and* used as
  895. # the report topic. Use the client's effective serial so the slicer
  896. # sees internal/topic consistency even when it differs from self.serial.
  897. serial = serial or self.serial
  898. # Build version response matching OrcaSlicer expectations
  899. # Required fields per module: name, product_name, sw_ver, sw_new_ver, sn, hw_ver, flag
  900. version_info = {
  901. "info": {
  902. "command": "get_version",
  903. "sequence_id": sequence_id,
  904. "module": [
  905. {
  906. "name": "ota",
  907. "product_name": product_name,
  908. "sw_ver": "01.07.00.00",
  909. "sw_new_ver": "",
  910. "hw_ver": "OTA",
  911. "sn": serial,
  912. "flag": 0,
  913. },
  914. {
  915. "name": "esp32",
  916. "product_name": product_name,
  917. "sw_ver": "01.07.22.25",
  918. "sw_new_ver": "",
  919. "hw_ver": "AP05",
  920. "sn": serial,
  921. "flag": 0,
  922. },
  923. {
  924. "name": "rv1126",
  925. "product_name": product_name,
  926. "sw_ver": "00.00.27.38",
  927. "sw_new_ver": "",
  928. "hw_ver": "AP05",
  929. "sn": serial,
  930. "flag": 0,
  931. },
  932. {
  933. "name": "th",
  934. "product_name": product_name,
  935. "sw_ver": "00.00.04.00",
  936. "sw_new_ver": "",
  937. "hw_ver": "TH07",
  938. "sn": serial,
  939. "flag": 0,
  940. },
  941. {
  942. "name": "mc",
  943. "product_name": product_name,
  944. "sw_ver": "00.00.10.00",
  945. "sw_new_ver": "",
  946. "hw_ver": "MC07",
  947. "sn": serial,
  948. "flag": 0,
  949. },
  950. ],
  951. }
  952. }
  953. # Overlay real version modules from the bridge cache when available
  954. # (specifically the AMS modules ams/0, n3f/0, n3s/128 etc. that
  955. # BambuStudio's Prepare tab uses to identify AMS hardware — without
  956. # them every AMS unit shows as "unknown" in the Prepare panel).
  957. if self._bridge is not None:
  958. cached_modules = self._bridge.get_latest_version_modules()
  959. if isinstance(cached_modules, list) and cached_modules:
  960. version_info["info"]["module"] = cached_modules
  961. await self._publish_to_report(writer, version_info, serial)
  962. logger.info("Sent version response (product_name=%s)", product_name)
  963. except OSError as e:
  964. logger.error("Failed to send version response: %s", e)
  965. def set_gcode_state(self, state: str, filename: str = "", prepare_percent: str = "0") -> None:
  966. """Update the gcode state reported to connected slicers.
  967. Called by the manager to reflect FTP upload progress/completion.
  968. """
  969. self._gcode_state = state
  970. self._current_file = filename
  971. self._prepare_percent = prepare_percent
  972. async def _publish_to_report(
  973. self, writer: asyncio.StreamWriter, payload: dict, serial: str = "", log_event: bool = True
  974. ) -> None:
  975. """Publish a message on the device report topic.
  976. Real Bambu printers wire-format push_status JSON with 4-space indentation
  977. (32254 bytes for an idle H2D push vs 14268 bytes compact). BambuStudio's
  978. Send pre-flight rejects compact JSON — without matching the on-wire
  979. format the slicer never proceeds to FTP upload.
  980. ``log_event=True`` records the publish in ``vp_wire/<vp>_cmd.jsonl``
  981. under the ``bridge_to_slicer`` direction so #1622-style triages can
  982. diff the bridge's own outbound replies (info.get_version answer,
  983. project_file ack, on-demand pushall response) against the real
  984. printer's ``printer_to_slicer`` forwards. The 1Hz periodic push
  985. sets ``log_event=False`` because dump_wire's overwrite-snapshot
  986. already covers cache shape and a per-second JSONL line would dwarf
  987. the actual command events.
  988. """
  989. topic = f"device/{serial or self.serial}/report"
  990. message = json.dumps(payload, indent=4)
  991. topic_bytes = topic.encode("utf-8")
  992. message_bytes = message.encode("utf-8")
  993. remaining = 2 + len(topic_bytes) + len(message_bytes)
  994. packet = bytes([0x30]) # PUBLISH, QoS 0
  995. while remaining > 0:
  996. byte = remaining % 128
  997. remaining //= 128
  998. if remaining > 0:
  999. byte |= 0x80
  1000. packet += bytes([byte])
  1001. packet += bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF])
  1002. packet += topic_bytes
  1003. packet += message_bytes
  1004. if log_event:
  1005. # Env-flagged command trace (#1622): captures bridge-synthesised
  1006. # replies (info.get_version, project_file ack, on-demand pushall
  1007. # response) AFTER the payload is finalised but before it hits
  1008. # the wire — so the cmd.jsonl reflects exactly what the slicer
  1009. # parses. Pair with the slicer_to_bridge events from
  1010. # _handle_publish and the printer_to_slicer fan-outs from
  1011. # mqtt_bridge.
  1012. append_event(self.vp_name, "bridge_to_slicer", topic, payload)
  1013. writer.write(packet)
  1014. # Timeout the drain to prevent blocking the event loop if the
  1015. # MQTT client stops reading (e.g. slicer busy with FTP upload).
  1016. try:
  1017. await asyncio.wait_for(writer.drain(), timeout=5)
  1018. except TimeoutError:
  1019. logger.debug("MQTT drain timeout for %s — client may be busy", topic)
  1020. async def _send_print_response(
  1021. self, writer: asyncio.StreamWriter, sequence_id: str, filename: str, serial: str | None = None
  1022. ) -> None:
  1023. """Send project_file acknowledgment matching real Bambu printer behavior."""
  1024. # Update state so periodic status pushes reflect preparation
  1025. self._gcode_state = "PREPARE"
  1026. self._current_file = filename
  1027. self._prepare_percent = "0"
  1028. try:
  1029. # Send command acknowledgment — slicer expects to see
  1030. # command: "project_file" echoed back before starting FTP upload
  1031. subtask_name = filename.replace(".3mf", "") if filename else ""
  1032. response = {
  1033. "print": {
  1034. "command": "project_file",
  1035. "sequence_id": sequence_id,
  1036. "param": "Metadata/plate_1.gcode",
  1037. "subtask_name": subtask_name,
  1038. "gcode_state": "PREPARE",
  1039. "gcode_file": filename,
  1040. "gcode_file_prepare_percent": "0",
  1041. "result": "SUCCESS",
  1042. "msg": 0,
  1043. }
  1044. }
  1045. await self._publish_to_report(writer, response, serial or self.serial)
  1046. logger.info("Sent project_file acknowledgment for %s", filename)
  1047. except OSError as e:
  1048. logger.error("Failed to send print response: %s", e)
  1049. async def _handle_publish(self, header: int, payload: bytes, writer: asyncio.StreamWriter, client_id: str) -> None:
  1050. """Handle MQTT PUBLISH packet."""
  1051. try:
  1052. # Parse topic
  1053. idx = 0
  1054. topic_len = (payload[idx] << 8) | payload[idx + 1]
  1055. idx += 2
  1056. topic = payload[idx : idx + topic_len].decode("utf-8")
  1057. idx += topic_len
  1058. # Check for packet ID (QoS > 0)
  1059. qos = (header & 0x06) >> 1
  1060. if qos > 0:
  1061. # packet_id = (payload[idx] << 8) | payload[idx + 1]
  1062. idx += 2
  1063. # Parse message
  1064. message = payload[idx:].decode("utf-8")
  1065. logger.info("MQTT publish to %s: %s...", topic, message[:100])
  1066. # Only handle publishes on *some* device/.../request topic. The
  1067. # serial is taken from the topic rather than compared against
  1068. # self.serial: the client is already authenticated via the access
  1069. # code, and Orca/BambuStudio may have a cached serial that differs
  1070. # from the VP's computed self.serial (#927). Use the topic's serial
  1071. # for all responses so they land on the topic the slicer subscribed
  1072. # to.
  1073. if not topic.startswith("device/") or "/request" not in topic:
  1074. return
  1075. client_serial = self._extract_serial_from_topic(topic) or self.serial
  1076. if client_serial and client_serial != self._client_serials.get(client_id):
  1077. if client_serial != self.serial:
  1078. logger.info(
  1079. "%sMQTT client publishing with serial %s (VP serial is %s) — adapting responses",
  1080. self._log_prefix,
  1081. client_serial,
  1082. self.serial,
  1083. )
  1084. self._client_serials[client_id] = client_serial
  1085. try:
  1086. # Some slicer builds (observed with OrcaSlicer on Linux, #927)
  1087. # include the C-string null terminator in the MQTT payload
  1088. # length, so the decoded message ends with \x00. Real brokers
  1089. # pass the bytes through; strict json.loads raises "Extra data"
  1090. # and every pushall/get_version/project_file silently dropped.
  1091. data = json.loads(message.rstrip("\x00 \r\n\t"))
  1092. except json.JSONDecodeError as e:
  1093. logger.debug(
  1094. "MQTT publish JSON decode failed: %s (payload=%r)",
  1095. e,
  1096. message[:200],
  1097. )
  1098. return
  1099. # Env-flagged command trace (#1622): every slicer-originated publish
  1100. # gets a line in vp_wire/<vp>_cmd.jsonl alongside the printer-side
  1101. # responses captured in mqtt_bridge. Off by default.
  1102. append_event(self.vp_name, "slicer_to_bridge", topic, data)
  1103. # The synthetic flow below is the original (pre-bridge) behaviour and is
  1104. # what the proven-working FTP "Send" depends on. Do NOT replace any
  1105. # synthetic response with a forward — only ADD forwarding alongside,
  1106. # at the bottom, for commands the synthetic flow doesn't handle
  1107. # (AMS write / xcam / system / etc., which need to actually reach
  1108. # the real printer).
  1109. handled_locally = False
  1110. # Handle pushing command (status request)
  1111. if "pushing" in data:
  1112. pushing_data = data["pushing"]
  1113. command = pushing_data.get("command", "")
  1114. logger.info("MQTT pushing command: %s", command)
  1115. if command == "pushall":
  1116. logger.info("Sending status report in response to pushall")
  1117. await self._send_status_report(writer, serial=client_serial)
  1118. handled_locally = True
  1119. elif command == "start":
  1120. logger.info("Starting status push stream")
  1121. await self._send_status_report(writer, serial=client_serial)
  1122. handled_locally = True
  1123. # Handle info commands (get_version, etc.)
  1124. if "info" in data:
  1125. info_data = data["info"]
  1126. command = info_data.get("command", "")
  1127. sequence_id = info_data.get("sequence_id", "0")
  1128. logger.info("MQTT info command: %s", command)
  1129. if command == "get_version":
  1130. await self._send_version_response(writer, sequence_id, serial=client_serial)
  1131. handled_locally = True
  1132. # Handle print commands
  1133. if "print" in data:
  1134. print_data = data["print"]
  1135. command = print_data.get("command", "")
  1136. filename = print_data.get("subtask_name", "")
  1137. sequence_id = print_data.get("sequence_id", "0")
  1138. logger.info("MQTT print command: %s for %s", command, filename)
  1139. if command in ("project_file", "gcode_file"):
  1140. # File lives on Bambuddy, not the printer — synthetic only.
  1141. file_3mf = print_data.get("file", filename)
  1142. await self._send_print_response(writer, sequence_id, file_3mf, serial=client_serial)
  1143. if self.on_print_command:
  1144. # `filename` is the slicer's `subtask_name` (bare model
  1145. # name, no extension). Pass it through verbatim — the
  1146. # `_schedule_finish_release` chain echoes it back as
  1147. # gcode_file + subtask_name in push_status, and the
  1148. # slicer matches against its own subtask_name there.
  1149. # The FTP filename (with extension) is in print_data
  1150. # under "file" for the queue-stash side to use as its
  1151. # own key matching `_add_to_print_queue`'s lookup.
  1152. await self._notify_print_command(filename, print_data)
  1153. handled_locally = True
  1154. # Forward anything the synthetic flow didn't handle to the real
  1155. # printer. AMS load / dry / xcam / system / extrusion_cali_get etc.
  1156. if not handled_locally and self._bridge is not None and self._bridge.is_active:
  1157. # Remember which client originated this command so the
  1158. # printer's response goes back only to them (not fanned
  1159. # out to every connected slicer).
  1160. self._record_pending_request(data, client_id)
  1161. self._bridge.forward_to_printer(data)
  1162. except (IndexError, ValueError, OSError) as e:
  1163. logger.debug("MQTT PUBLISH error: %s", e)
  1164. async def _notify_print_command(self, filename: str, data: dict) -> None:
  1165. """Notify callback of print command."""
  1166. if self.on_print_command:
  1167. try:
  1168. result = self.on_print_command(filename, data)
  1169. if asyncio.iscoroutine(result):
  1170. await result
  1171. except Exception as e:
  1172. logger.error("Print command callback error: %s", e)