mqtt_server.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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 json
  7. import logging
  8. import ssl
  9. from collections.abc import Callable
  10. from pathlib import Path
  11. logger = logging.getLogger(__name__)
  12. # Default MQTT port for Bambu printers (MQTT over TLS)
  13. MQTT_PORT = 8883
  14. # Model code → product_name for version response (must match what slicer expects)
  15. MODEL_PRODUCT_NAMES = {
  16. "BL-P001": "X1 Carbon",
  17. "BL-P002": "X1",
  18. "C13": "X1E",
  19. "C11": "P1P",
  20. "C12": "P1S",
  21. "N7": "P2S",
  22. "N2S": "A1",
  23. "N1": "A1 mini",
  24. "O1D": "H2D",
  25. "O1C": "H2C",
  26. "O1C2": "H2C",
  27. "O1S": "H2S",
  28. }
  29. class VirtualPrinterMQTTServer:
  30. """MQTT broker that accepts connections from slicers.
  31. This is a minimal MQTT broker implementation that:
  32. - Accepts TLS connections on port 8883
  33. - Authenticates with username 'bblp' and the configured access code
  34. - Receives print commands on device/{serial}/request
  35. - Can publish status on device/{serial}/report
  36. """
  37. def __init__(
  38. self,
  39. serial: str,
  40. access_code: str,
  41. cert_path: Path,
  42. key_path: Path,
  43. port: int = MQTT_PORT,
  44. on_print_command: Callable[[str, dict], None] | None = None,
  45. ):
  46. """Initialize the MQTT server.
  47. Args:
  48. serial: Virtual printer serial number
  49. access_code: Password for authentication
  50. cert_path: Path to TLS certificate
  51. key_path: Path to TLS private key
  52. port: Port to listen on (default 8883)
  53. on_print_command: Callback when print command received (filename, data)
  54. """
  55. self.serial = serial
  56. self.access_code = access_code
  57. self.cert_path = cert_path
  58. self.key_path = key_path
  59. self.port = port
  60. self.on_print_command = on_print_command
  61. self._running = False
  62. self._broker = None
  63. self._broker_task = None
  64. async def start(self) -> None:
  65. """Start the MQTT broker."""
  66. if self._running:
  67. return
  68. # Try to import amqtt
  69. try:
  70. from amqtt.broker import Broker
  71. except ImportError:
  72. logger.error("amqtt not installed. Run: pip install amqtt")
  73. return
  74. logger.info("Starting virtual printer MQTT broker on port %s", self.port)
  75. # Build broker configuration
  76. config = {
  77. "listeners": {
  78. "default": {
  79. "type": "tcp",
  80. "bind": f"0.0.0.0:{self.port}",
  81. "ssl": "on",
  82. "certfile": str(self.cert_path),
  83. "keyfile": str(self.key_path),
  84. },
  85. },
  86. "auth": {
  87. "allow-anonymous": False,
  88. "plugins": ["auth_custom"],
  89. },
  90. "topic-check": {
  91. "enabled": False, # Allow any topic
  92. },
  93. }
  94. try:
  95. self._running = True
  96. # Create and start broker
  97. self._broker = Broker(config)
  98. # Register custom auth plugin
  99. self._broker.plugins_manager.plugins_handlers["auth_custom"] = self._authenticate
  100. # Start the broker
  101. await self._broker.start()
  102. logger.info("MQTT broker started on port %s", self.port)
  103. # Keep running
  104. while self._running:
  105. await asyncio.sleep(1)
  106. except OSError as e:
  107. if e.errno == 98: # Address already in use
  108. logger.error("MQTT port %s is already in use", self.port)
  109. else:
  110. logger.error("MQTT broker error: %s", e)
  111. except asyncio.CancelledError:
  112. logger.debug("MQTT broker task cancelled")
  113. except Exception as e:
  114. logger.error("MQTT broker error: %s", e)
  115. finally:
  116. await self.stop()
  117. async def _authenticate(self, session) -> bool:
  118. """Authenticate MQTT connection.
  119. Args:
  120. session: MQTT session with username/password
  121. Returns:
  122. True if authentication successful
  123. """
  124. username = getattr(session, "username", None)
  125. password = getattr(session, "password", None)
  126. # Bambu slicers use 'bblp' as username and access code as password
  127. if username == "bblp" and password == self.access_code:
  128. logger.debug("MQTT client authenticated from %s", session.remote_address)
  129. return True
  130. logger.warning("MQTT auth failed for user '%s' from %s", username, session.remote_address)
  131. return False
  132. async def stop(self) -> None:
  133. """Stop the MQTT broker."""
  134. logger.info("Stopping MQTT broker")
  135. self._running = False
  136. if self._broker:
  137. try:
  138. await self._broker.shutdown()
  139. except OSError as e:
  140. logger.debug("Error shutting down MQTT broker: %s", e)
  141. self._broker = None
  142. class SimpleMQTTServer:
  143. """Simplified MQTT server using raw sockets.
  144. This is a fallback implementation that handles basic MQTT protocol
  145. without requiring the amqtt library. It's less feature-complete but
  146. more lightweight.
  147. """
  148. def __init__(
  149. self,
  150. serial: str,
  151. access_code: str,
  152. cert_path: Path,
  153. key_path: Path,
  154. port: int = MQTT_PORT,
  155. on_print_command: Callable[[str, dict], None] | None = None,
  156. model: str = "",
  157. bind_address: str = "0.0.0.0", # nosec B104
  158. ):
  159. self.serial = serial
  160. self.access_code = access_code
  161. self.model = model
  162. self.cert_path = cert_path
  163. self.key_path = key_path
  164. self.port = port
  165. self.on_print_command = on_print_command
  166. self.bind_address = bind_address
  167. self._running = False
  168. self._server = None
  169. self._clients: dict[str, asyncio.StreamWriter] = {}
  170. self._status_push_task: asyncio.Task | None = None
  171. self._sequence_id = 0
  172. # Dynamic state for status reports
  173. self._gcode_state = "IDLE"
  174. self._current_file = ""
  175. self._prepare_percent = "0"
  176. async def start(self) -> None:
  177. """Start the MQTT server."""
  178. if self._running:
  179. return
  180. logger.info("Starting simple MQTT server on port %s", self.port)
  181. # Create SSL context with Bambu-compatible settings
  182. ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  183. ssl_context.load_cert_chain(str(self.cert_path), str(self.key_path))
  184. # Match Bambu printer behavior - accept any client
  185. ssl_context.verify_mode = ssl.CERT_NONE
  186. # Allow TLS 1.2 for broader compatibility (some slicers may not support 1.3)
  187. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  188. # Disable hostname checking
  189. ssl_context.check_hostname = False
  190. # Log certificate info
  191. import subprocess
  192. try:
  193. result = subprocess.run(
  194. ["openssl", "x509", "-in", str(self.cert_path), "-noout", "-subject", "-issuer"],
  195. capture_output=True,
  196. text=True,
  197. timeout=5,
  198. )
  199. logger.info("MQTT SSL cert info: %s", result.stdout.strip())
  200. except (OSError, subprocess.SubprocessError):
  201. pass # Certificate info is for debug logging only; not critical
  202. logger.info("MQTT SSL context: TLS 1.2+, cert=%s", self.cert_path)
  203. try:
  204. self._running = True
  205. # Wrapper to log ALL connection attempts including SSL errors
  206. async def connection_handler(reader, writer):
  207. try:
  208. addr = writer.get_extra_info("peername")
  209. ssl_obj = writer.get_extra_info("ssl_object")
  210. if ssl_obj:
  211. logger.info(
  212. f"MQTT TLS connection from {addr} - cipher={ssl_obj.cipher()}, version={ssl_obj.version()}"
  213. )
  214. else:
  215. logger.info("MQTT connection from %s (no TLS?)", addr)
  216. await self._handle_client(reader, writer)
  217. except ssl.SSLError as e:
  218. logger.error("MQTT SSL error: %s", e)
  219. except Exception as e:
  220. logger.error("MQTT connection handler error: %s", e)
  221. self._server = await asyncio.start_server(
  222. connection_handler,
  223. self.bind_address,
  224. self.port,
  225. ssl=ssl_context,
  226. )
  227. logger.info("Simple MQTT server listening on port %s", self.port)
  228. # Start periodic status push task
  229. self._status_push_task = asyncio.create_task(self._periodic_status_push())
  230. async with self._server:
  231. await self._server.serve_forever()
  232. except OSError as e:
  233. if e.errno == 98: # Address already in use
  234. logger.error("MQTT port %s is already in use", self.port)
  235. else:
  236. logger.error("MQTT server error: %s", e)
  237. except asyncio.CancelledError:
  238. logger.debug("MQTT server task cancelled")
  239. except Exception as e:
  240. logger.error("MQTT server error: %s", e)
  241. finally:
  242. await self.stop()
  243. async def stop(self) -> None:
  244. """Stop the MQTT server."""
  245. logger.info("Stopping simple MQTT server")
  246. self._running = False
  247. # Stop periodic status push
  248. if self._status_push_task:
  249. self._status_push_task.cancel()
  250. try:
  251. await self._status_push_task
  252. except asyncio.CancelledError:
  253. pass # Expected when stopping the periodic status push task
  254. self._status_push_task = None
  255. # Close all client connections (iterate over copy to avoid modification during iteration)
  256. for _client_id, writer in list(self._clients.items()):
  257. try:
  258. writer.close()
  259. await writer.wait_closed()
  260. except OSError:
  261. pass # Best-effort client connection cleanup; client may have disconnected
  262. self._clients.clear()
  263. if self._server:
  264. try:
  265. self._server.close()
  266. await self._server.wait_closed()
  267. except OSError:
  268. pass # Best-effort server shutdown; port may already be released
  269. self._server = None
  270. async def _periodic_status_push(self) -> None:
  271. """Send periodic status updates to all connected clients."""
  272. logger.info("Starting periodic status push task")
  273. while self._running:
  274. try:
  275. await asyncio.sleep(1) # Push every 1 second like real printers
  276. # Send status to all connected clients
  277. disconnected = []
  278. for client_id, writer in list(self._clients.items()):
  279. try:
  280. if writer.is_closing():
  281. disconnected.append(client_id)
  282. continue
  283. await self._send_status_report(writer)
  284. except OSError as e:
  285. logger.debug("Failed to push status to %s: %s", client_id, e)
  286. disconnected.append(client_id)
  287. # Remove disconnected clients
  288. for client_id in disconnected:
  289. self._clients.pop(client_id, None)
  290. except asyncio.CancelledError:
  291. break
  292. except Exception as e:
  293. logger.error("Periodic status push error: %s", e)
  294. logger.info("Periodic status push task stopped")
  295. async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  296. """Handle an MQTT client connection."""
  297. addr = writer.get_extra_info("peername")
  298. client_id = f"{addr[0]}:{addr[1]}" if addr else "unknown"
  299. logger.info("MQTT client connected: %s", client_id)
  300. authenticated = False
  301. try:
  302. while self._running:
  303. # Read MQTT fixed header
  304. try:
  305. header = await asyncio.wait_for(reader.read(1), timeout=60)
  306. except TimeoutError:
  307. break
  308. if not header:
  309. break
  310. packet_type = (header[0] & 0xF0) >> 4
  311. # Read remaining length
  312. remaining_length = await self._read_remaining_length(reader)
  313. if remaining_length is None:
  314. break
  315. # Read payload
  316. payload = await reader.read(remaining_length) if remaining_length > 0 else b""
  317. # Handle packet types
  318. if packet_type == 1: # CONNECT
  319. authenticated = await self._handle_connect(payload, writer)
  320. if not authenticated:
  321. break
  322. # Register client for periodic status pushes
  323. self._clients[client_id] = writer
  324. elif packet_type == 3: # PUBLISH
  325. if authenticated:
  326. await self._handle_publish(header[0], payload, writer)
  327. elif packet_type == 8: # SUBSCRIBE
  328. if authenticated:
  329. await self._handle_subscribe(payload, writer)
  330. elif packet_type == 12: # PINGREQ
  331. # Send PINGRESP
  332. writer.write(bytes([0xD0, 0x00]))
  333. await writer.drain()
  334. elif packet_type == 14: # DISCONNECT
  335. break
  336. except asyncio.CancelledError:
  337. pass # Expected when server is shutting down and cancels client tasks
  338. except Exception as e:
  339. logger.debug("MQTT client error: %s", e)
  340. finally:
  341. logger.debug("MQTT client disconnected: %s", client_id)
  342. if client_id in self._clients:
  343. del self._clients[client_id]
  344. try:
  345. writer.close()
  346. await writer.wait_closed()
  347. except OSError:
  348. pass # Best-effort socket cleanup on client disconnect
  349. async def _read_remaining_length(self, reader: asyncio.StreamReader) -> int | None:
  350. """Read MQTT remaining length (variable byte integer)."""
  351. multiplier = 1
  352. value = 0
  353. for _ in range(4):
  354. try:
  355. byte = await reader.read(1)
  356. if not byte:
  357. return None
  358. encoded = byte[0]
  359. value += (encoded & 127) * multiplier
  360. if (encoded & 128) == 0:
  361. return value
  362. multiplier *= 128
  363. except OSError:
  364. return None
  365. return None
  366. async def _handle_connect(self, payload: bytes, writer: asyncio.StreamWriter) -> bool:
  367. """Handle MQTT CONNECT packet.
  368. Returns True if authentication successful.
  369. """
  370. try:
  371. # Parse CONNECT packet
  372. # Skip protocol name length and name
  373. idx = 0
  374. proto_len = (payload[idx] << 8) | payload[idx + 1]
  375. idx += 2 + proto_len
  376. # Skip protocol level and connect flags
  377. # connect_flags = payload[idx + 1]
  378. idx += 2
  379. # Skip keepalive
  380. idx += 2
  381. # Read client ID
  382. client_id_len = (payload[idx] << 8) | payload[idx + 1]
  383. idx += 2
  384. # client_id = payload[idx : idx + client_id_len].decode("utf-8")
  385. idx += client_id_len
  386. # Read username
  387. username_len = (payload[idx] << 8) | payload[idx + 1]
  388. idx += 2
  389. username = payload[idx : idx + username_len].decode("utf-8")
  390. idx += username_len
  391. # Read password
  392. password_len = (payload[idx] << 8) | payload[idx + 1]
  393. idx += 2
  394. password = payload[idx : idx + password_len].decode("utf-8")
  395. # Authenticate
  396. if username == "bblp" and password == self.access_code:
  397. # Send CONNACK with success
  398. writer.write(bytes([0x20, 0x02, 0x00, 0x00]))
  399. await writer.drain()
  400. logger.info("MQTT client authenticated successfully")
  401. # Send immediate status report after auth - slicer expects this
  402. await self._send_status_report(writer)
  403. return True
  404. else:
  405. # Send CONNACK with auth failure
  406. writer.write(bytes([0x20, 0x02, 0x00, 0x05])) # Not authorized
  407. await writer.drain()
  408. logger.warning("MQTT auth failed for user '%s'", username)
  409. return False
  410. except (IndexError, ValueError) as e:
  411. logger.debug("MQTT CONNECT parse error: %s", e)
  412. # Send CONNACK with error
  413. writer.write(bytes([0x20, 0x02, 0x00, 0x02])) # Protocol error
  414. await writer.drain()
  415. return False
  416. async def _handle_subscribe(self, payload: bytes, writer: asyncio.StreamWriter) -> None:
  417. """Handle MQTT SUBSCRIBE packet."""
  418. try:
  419. # Parse packet ID
  420. packet_id = (payload[0] << 8) | payload[1]
  421. # Parse topic filters (just acknowledge them)
  422. idx = 2
  423. granted_qos = []
  424. while idx < len(payload):
  425. topic_len = (payload[idx] << 8) | payload[idx + 1]
  426. idx += 2
  427. topic = payload[idx : idx + topic_len].decode("utf-8")
  428. idx += topic_len
  429. requested_qos = payload[idx]
  430. idx += 1
  431. logger.info("MQTT subscribe: %s QoS=%s", topic, requested_qos)
  432. granted_qos.append(min(requested_qos, 1)) # Grant up to QoS 1
  433. # Send SUBACK
  434. suback = bytes([0x90, 2 + len(granted_qos), packet_id >> 8, packet_id & 0xFF])
  435. suback += bytes(granted_qos)
  436. writer.write(suback)
  437. await writer.drain()
  438. # Send initial status report after subscribe
  439. await self._send_status_report(writer)
  440. except (IndexError, ValueError, OSError) as e:
  441. logger.debug("MQTT SUBSCRIBE error: %s", e)
  442. async def _send_status_report(self, writer: asyncio.StreamWriter) -> None:
  443. """Send a status report to the slicer after connection."""
  444. try:
  445. # Build status message matching Bambu printer format
  446. self._sequence_id += 1
  447. status = {
  448. "print": {
  449. "sequence_id": str(self._sequence_id),
  450. "command": "push_status",
  451. "msg": 0,
  452. "gcode_state": self._gcode_state,
  453. "gcode_file": self._current_file,
  454. "gcode_file_prepare_percent": self._prepare_percent,
  455. "subtask_name": self._current_file.replace(".3mf", "") if self._current_file else "",
  456. "mc_print_stage": "",
  457. "mc_percent": 0,
  458. "mc_remaining_time": 0,
  459. "wifi_signal": "-44dBm",
  460. "print_error": 0,
  461. "print_type": "",
  462. "bed_temper": 25.0,
  463. "bed_target_temper": 0.0,
  464. "nozzle_temper": 25.0,
  465. "nozzle_target_temper": 0.0,
  466. "chamber_temper": 25.0,
  467. "cooling_fan_speed": "0",
  468. "big_fan1_speed": "0",
  469. "big_fan2_speed": "0",
  470. "heatbreak_fan_speed": "0",
  471. "spd_lvl": 1,
  472. "spd_mag": 100,
  473. "stg": [],
  474. "stg_cur": 0,
  475. "layer_num": 0,
  476. "total_layer_num": 0,
  477. "home_flag": 256, # Bit 8 = SD card present (HAS_SDCARD_NORMAL)
  478. "hw_switch_state": 0,
  479. "online": {"ahb": False, "rfid": False, "version": 7},
  480. "ams_status": 0,
  481. "sdcard": True,
  482. "storage": {"free": 1000000000, "total": 32000000000},
  483. "upgrade_state": {
  484. "sequence_id": 0,
  485. "progress": "",
  486. "status": "",
  487. "consistency_request": False,
  488. "dis_state": 0,
  489. "err_code": 0,
  490. "force_upgrade": False,
  491. "message": "",
  492. "module": "",
  493. "new_version_state": 2,
  494. "new_ver_list": [],
  495. "ota_new_version_number": "",
  496. "ahb_new_version_number": "",
  497. },
  498. "ipcam": {
  499. "ipcam_dev": "1",
  500. "ipcam_record": "enable",
  501. "timelapse": "disable",
  502. "resolution": "1080p",
  503. "mode_bits": 0,
  504. },
  505. "xcam": {
  506. "allow_skip_parts": False,
  507. "buildplate_marker_detector": True,
  508. "first_layer_inspector": True,
  509. "halt_print_sensitivity": "medium",
  510. "print_halt": True,
  511. "printing_monitor": True,
  512. "spaghetti_detector": True,
  513. },
  514. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  515. "nozzle_diameter": "0.4",
  516. "nozzle_type": "hardened_steel",
  517. }
  518. }
  519. await self._publish_to_report(writer, status, self.serial)
  520. except OSError as e:
  521. logger.error("Failed to send status report: %s", e)
  522. async def _send_version_response(self, writer: asyncio.StreamWriter, sequence_id: str) -> None:
  523. """Send version info response to the slicer."""
  524. try:
  525. product_name = MODEL_PRODUCT_NAMES.get(self.model, self.model or "X1 Carbon")
  526. serial = self.serial
  527. # Build version response matching OrcaSlicer expectations
  528. # Required fields per module: name, product_name, sw_ver, sw_new_ver, sn, hw_ver, flag
  529. version_info = {
  530. "info": {
  531. "command": "get_version",
  532. "sequence_id": sequence_id,
  533. "module": [
  534. {
  535. "name": "ota",
  536. "product_name": product_name,
  537. "sw_ver": "01.07.00.00",
  538. "sw_new_ver": "",
  539. "hw_ver": "OTA",
  540. "sn": serial,
  541. "flag": 0,
  542. },
  543. {
  544. "name": "esp32",
  545. "product_name": product_name,
  546. "sw_ver": "01.07.22.25",
  547. "sw_new_ver": "",
  548. "hw_ver": "AP05",
  549. "sn": serial,
  550. "flag": 0,
  551. },
  552. {
  553. "name": "rv1126",
  554. "product_name": product_name,
  555. "sw_ver": "00.00.27.38",
  556. "sw_new_ver": "",
  557. "hw_ver": "AP05",
  558. "sn": serial,
  559. "flag": 0,
  560. },
  561. {
  562. "name": "th",
  563. "product_name": product_name,
  564. "sw_ver": "00.00.04.00",
  565. "sw_new_ver": "",
  566. "hw_ver": "TH07",
  567. "sn": serial,
  568. "flag": 0,
  569. },
  570. {
  571. "name": "mc",
  572. "product_name": product_name,
  573. "sw_ver": "00.00.10.00",
  574. "sw_new_ver": "",
  575. "hw_ver": "MC07",
  576. "sn": serial,
  577. "flag": 0,
  578. },
  579. ],
  580. }
  581. }
  582. await self._publish_to_report(writer, version_info, serial)
  583. logger.info("Sent version response (product_name=%s)", product_name)
  584. except OSError as e:
  585. logger.error("Failed to send version response: %s", e)
  586. def set_gcode_state(self, state: str, filename: str = "", prepare_percent: str = "0") -> None:
  587. """Update the gcode state reported to connected slicers.
  588. Called by the manager to reflect FTP upload progress/completion.
  589. """
  590. self._gcode_state = state
  591. self._current_file = filename
  592. self._prepare_percent = prepare_percent
  593. async def _publish_to_report(self, writer: asyncio.StreamWriter, payload: dict, serial: str = "") -> None:
  594. """Publish a message on the device report topic."""
  595. topic = f"device/{serial or self.serial}/report"
  596. message = json.dumps(payload)
  597. topic_bytes = topic.encode("utf-8")
  598. message_bytes = message.encode("utf-8")
  599. remaining = 2 + len(topic_bytes) + len(message_bytes)
  600. packet = bytes([0x30]) # PUBLISH, QoS 0
  601. while remaining > 0:
  602. byte = remaining % 128
  603. remaining //= 128
  604. if remaining > 0:
  605. byte |= 0x80
  606. packet += bytes([byte])
  607. packet += bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF])
  608. packet += topic_bytes
  609. packet += message_bytes
  610. writer.write(packet)
  611. # Timeout the drain to prevent blocking the event loop if the
  612. # MQTT client stops reading (e.g. slicer busy with FTP upload).
  613. try:
  614. await asyncio.wait_for(writer.drain(), timeout=5)
  615. except TimeoutError:
  616. logger.debug("MQTT drain timeout for %s — client may be busy", topic)
  617. async def _send_print_response(self, writer: asyncio.StreamWriter, sequence_id: str, filename: str) -> None:
  618. """Send project_file acknowledgment matching real Bambu printer behavior."""
  619. # Update state so periodic status pushes reflect preparation
  620. self._gcode_state = "PREPARE"
  621. self._current_file = filename
  622. self._prepare_percent = "0"
  623. try:
  624. # Send command acknowledgment — slicer expects to see
  625. # command: "project_file" echoed back before starting FTP upload
  626. subtask_name = filename.replace(".3mf", "") if filename else ""
  627. response = {
  628. "print": {
  629. "command": "project_file",
  630. "sequence_id": sequence_id,
  631. "param": "Metadata/plate_1.gcode",
  632. "subtask_name": subtask_name,
  633. "gcode_state": "PREPARE",
  634. "gcode_file": filename,
  635. "gcode_file_prepare_percent": "0",
  636. "result": "SUCCESS",
  637. "msg": 0,
  638. }
  639. }
  640. await self._publish_to_report(writer, response)
  641. logger.info("Sent project_file acknowledgment for %s", filename)
  642. except OSError as e:
  643. logger.error("Failed to send print response: %s", e)
  644. async def _handle_publish(self, header: int, payload: bytes, writer: asyncio.StreamWriter) -> None:
  645. """Handle MQTT PUBLISH packet."""
  646. try:
  647. # Parse topic
  648. idx = 0
  649. topic_len = (payload[idx] << 8) | payload[idx + 1]
  650. idx += 2
  651. topic = payload[idx : idx + topic_len].decode("utf-8")
  652. idx += topic_len
  653. # Check for packet ID (QoS > 0)
  654. qos = (header & 0x06) >> 1
  655. if qos > 0:
  656. # packet_id = (payload[idx] << 8) | payload[idx + 1]
  657. idx += 2
  658. # Parse message
  659. message = payload[idx:].decode("utf-8")
  660. logger.info("MQTT publish to %s: %s...", topic, message[:100])
  661. # Handle commands on device request topic
  662. if f"device/{self.serial}/request" in topic:
  663. try:
  664. data = json.loads(message)
  665. # Handle pushing command (status request)
  666. if "pushing" in data:
  667. pushing_data = data["pushing"]
  668. command = pushing_data.get("command", "")
  669. logger.info("MQTT pushing command: %s", command)
  670. if command == "pushall":
  671. # Slicer is requesting full status - send response
  672. logger.info("Sending status report in response to pushall")
  673. await self._send_status_report(writer)
  674. elif command == "start":
  675. # Slicer wants periodic status updates - send one now
  676. logger.info("Starting status push stream")
  677. await self._send_status_report(writer)
  678. # Handle info commands (get_version, etc.)
  679. if "info" in data:
  680. info_data = data["info"]
  681. command = info_data.get("command", "")
  682. sequence_id = info_data.get("sequence_id", "0")
  683. logger.info("MQTT info command: %s", command)
  684. if command == "get_version":
  685. await self._send_version_response(writer, sequence_id)
  686. # Handle print commands
  687. if "print" in data:
  688. print_data = data["print"]
  689. command = print_data.get("command", "")
  690. filename = print_data.get("subtask_name", "")
  691. sequence_id = print_data.get("sequence_id", "0")
  692. logger.info("MQTT print command: %s for %s", command, filename)
  693. if command == "project_file":
  694. # Respond with PREPARE status so slicer proceeds with FTP upload
  695. file_3mf = print_data.get("file", filename)
  696. await self._send_print_response(writer, sequence_id, file_3mf)
  697. if self.on_print_command:
  698. await self._notify_print_command(filename, print_data)
  699. except json.JSONDecodeError:
  700. pass # Non-JSON payloads on request topic are safely ignored
  701. except (IndexError, ValueError, OSError) as e:
  702. logger.debug("MQTT PUBLISH error: %s", e)
  703. async def _notify_print_command(self, filename: str, data: dict) -> None:
  704. """Notify callback of print command."""
  705. if self.on_print_command:
  706. try:
  707. result = self.on_print_command(filename, data)
  708. if asyncio.iscoroutine(result):
  709. await result
  710. except Exception as e:
  711. logger.error("Print command callback error: %s", e)