mqtt_server.py 64 KB

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