mqtt_server.py 31 KB

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