mqtt_server.py 54 KB

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