mqtt_server.py 56 KB

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