mqtt_server.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. "3DPrinter-X1-Carbon": "X1 Carbon",
  17. "3DPrinter-X1": "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. # Custom protocol factory to log raw connection attempts
  222. logger.info("Setting up MQTT server with SSL error handling...")
  223. # Add SSL handshake error callback
  224. def handle_ssl_error(loop, context):
  225. exception = context.get("exception")
  226. message = context.get("message", "")
  227. if "ssl" in str(exception).lower() or "ssl" in message.lower():
  228. logger.error("SSL error: %s - %s", message, exception)
  229. else:
  230. logger.debug("Asyncio error: %s", message)
  231. asyncio.get_event_loop().set_exception_handler(handle_ssl_error)
  232. self._server = await asyncio.start_server(
  233. connection_handler,
  234. self.bind_address,
  235. self.port,
  236. ssl=ssl_context,
  237. )
  238. logger.info("Simple MQTT server listening on port %s", self.port)
  239. # Start periodic status push task
  240. self._status_push_task = asyncio.create_task(self._periodic_status_push())
  241. async with self._server:
  242. await self._server.serve_forever()
  243. except OSError as e:
  244. if e.errno == 98: # Address already in use
  245. logger.error("MQTT port %s is already in use", self.port)
  246. else:
  247. logger.error("MQTT server error: %s", e)
  248. except asyncio.CancelledError:
  249. logger.debug("MQTT server task cancelled")
  250. except Exception as e:
  251. logger.error("MQTT server error: %s", e)
  252. finally:
  253. await self.stop()
  254. async def stop(self) -> None:
  255. """Stop the MQTT server."""
  256. logger.info("Stopping simple MQTT server")
  257. self._running = False
  258. # Stop periodic status push
  259. if self._status_push_task:
  260. self._status_push_task.cancel()
  261. try:
  262. await self._status_push_task
  263. except asyncio.CancelledError:
  264. pass # Expected when stopping the periodic status push task
  265. self._status_push_task = None
  266. # Close all client connections (iterate over copy to avoid modification during iteration)
  267. for _client_id, writer in list(self._clients.items()):
  268. try:
  269. writer.close()
  270. await writer.wait_closed()
  271. except OSError:
  272. pass # Best-effort client connection cleanup; client may have disconnected
  273. self._clients.clear()
  274. if self._server:
  275. try:
  276. self._server.close()
  277. await self._server.wait_closed()
  278. except OSError:
  279. pass # Best-effort server shutdown; port may already be released
  280. self._server = None
  281. async def _periodic_status_push(self) -> None:
  282. """Send periodic status updates to all connected clients."""
  283. logger.info("Starting periodic status push task")
  284. while self._running:
  285. try:
  286. await asyncio.sleep(1) # Push every 1 second like real printers
  287. # Send status to all connected clients
  288. disconnected = []
  289. for client_id, writer in list(self._clients.items()):
  290. try:
  291. if writer.is_closing():
  292. disconnected.append(client_id)
  293. continue
  294. await self._send_status_report(writer)
  295. except OSError as e:
  296. logger.debug("Failed to push status to %s: %s", client_id, e)
  297. disconnected.append(client_id)
  298. # Remove disconnected clients
  299. for client_id in disconnected:
  300. self._clients.pop(client_id, None)
  301. except asyncio.CancelledError:
  302. break
  303. except Exception as e:
  304. logger.error("Periodic status push error: %s", e)
  305. logger.info("Periodic status push task stopped")
  306. async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
  307. """Handle an MQTT client connection."""
  308. addr = writer.get_extra_info("peername")
  309. client_id = f"{addr[0]}:{addr[1]}" if addr else "unknown"
  310. logger.info("MQTT client connected: %s", client_id)
  311. authenticated = False
  312. try:
  313. while self._running:
  314. # Read MQTT fixed header
  315. try:
  316. header = await asyncio.wait_for(reader.read(1), timeout=60)
  317. except TimeoutError:
  318. break
  319. if not header:
  320. break
  321. packet_type = (header[0] & 0xF0) >> 4
  322. # Read remaining length
  323. remaining_length = await self._read_remaining_length(reader)
  324. if remaining_length is None:
  325. break
  326. # Read payload
  327. payload = await reader.read(remaining_length) if remaining_length > 0 else b""
  328. # Handle packet types
  329. if packet_type == 1: # CONNECT
  330. authenticated = await self._handle_connect(payload, writer)
  331. if not authenticated:
  332. break
  333. # Register client for periodic status pushes
  334. self._clients[client_id] = writer
  335. elif packet_type == 3: # PUBLISH
  336. if authenticated:
  337. await self._handle_publish(header[0], payload, writer)
  338. elif packet_type == 8: # SUBSCRIBE
  339. if authenticated:
  340. await self._handle_subscribe(payload, writer)
  341. elif packet_type == 12: # PINGREQ
  342. # Send PINGRESP
  343. writer.write(bytes([0xD0, 0x00]))
  344. await writer.drain()
  345. elif packet_type == 14: # DISCONNECT
  346. break
  347. except asyncio.CancelledError:
  348. pass # Expected when server is shutting down and cancels client tasks
  349. except Exception as e:
  350. logger.debug("MQTT client error: %s", e)
  351. finally:
  352. logger.debug("MQTT client disconnected: %s", client_id)
  353. if client_id in self._clients:
  354. del self._clients[client_id]
  355. try:
  356. writer.close()
  357. await writer.wait_closed()
  358. except OSError:
  359. pass # Best-effort socket cleanup on client disconnect
  360. async def _read_remaining_length(self, reader: asyncio.StreamReader) -> int | None:
  361. """Read MQTT remaining length (variable byte integer)."""
  362. multiplier = 1
  363. value = 0
  364. for _ in range(4):
  365. try:
  366. byte = await reader.read(1)
  367. if not byte:
  368. return None
  369. encoded = byte[0]
  370. value += (encoded & 127) * multiplier
  371. if (encoded & 128) == 0:
  372. return value
  373. multiplier *= 128
  374. except OSError:
  375. return None
  376. return None
  377. async def _handle_connect(self, payload: bytes, writer: asyncio.StreamWriter) -> bool:
  378. """Handle MQTT CONNECT packet.
  379. Returns True if authentication successful.
  380. """
  381. try:
  382. # Parse CONNECT packet
  383. # Skip protocol name length and name
  384. idx = 0
  385. proto_len = (payload[idx] << 8) | payload[idx + 1]
  386. idx += 2 + proto_len
  387. # Skip protocol level and connect flags
  388. # connect_flags = payload[idx + 1]
  389. idx += 2
  390. # Skip keepalive
  391. idx += 2
  392. # Read client ID
  393. client_id_len = (payload[idx] << 8) | payload[idx + 1]
  394. idx += 2
  395. # client_id = payload[idx : idx + client_id_len].decode("utf-8")
  396. idx += client_id_len
  397. # Read username
  398. username_len = (payload[idx] << 8) | payload[idx + 1]
  399. idx += 2
  400. username = payload[idx : idx + username_len].decode("utf-8")
  401. idx += username_len
  402. # Read password
  403. password_len = (payload[idx] << 8) | payload[idx + 1]
  404. idx += 2
  405. password = payload[idx : idx + password_len].decode("utf-8")
  406. # Authenticate
  407. if username == "bblp" and password == self.access_code:
  408. # Send CONNACK with success
  409. writer.write(bytes([0x20, 0x02, 0x00, 0x00]))
  410. await writer.drain()
  411. logger.info("MQTT client authenticated successfully")
  412. # Send immediate status report after auth - slicer expects this
  413. await self._send_status_report(writer)
  414. return True
  415. else:
  416. # Send CONNACK with auth failure
  417. writer.write(bytes([0x20, 0x02, 0x00, 0x05])) # Not authorized
  418. await writer.drain()
  419. logger.warning("MQTT auth failed for user '%s'", username)
  420. return False
  421. except (IndexError, ValueError) as e:
  422. logger.debug("MQTT CONNECT parse error: %s", e)
  423. # Send CONNACK with error
  424. writer.write(bytes([0x20, 0x02, 0x00, 0x02])) # Protocol error
  425. await writer.drain()
  426. return False
  427. async def _handle_subscribe(self, payload: bytes, writer: asyncio.StreamWriter) -> None:
  428. """Handle MQTT SUBSCRIBE packet."""
  429. try:
  430. # Parse packet ID
  431. packet_id = (payload[0] << 8) | payload[1]
  432. # Parse topic filters (just acknowledge them)
  433. idx = 2
  434. granted_qos = []
  435. while idx < len(payload):
  436. topic_len = (payload[idx] << 8) | payload[idx + 1]
  437. idx += 2
  438. topic = payload[idx : idx + topic_len].decode("utf-8")
  439. idx += topic_len
  440. requested_qos = payload[idx]
  441. idx += 1
  442. logger.info("MQTT subscribe: %s QoS=%s", topic, requested_qos)
  443. granted_qos.append(min(requested_qos, 1)) # Grant up to QoS 1
  444. # Send SUBACK
  445. suback = bytes([0x90, 2 + len(granted_qos), packet_id >> 8, packet_id & 0xFF])
  446. suback += bytes(granted_qos)
  447. writer.write(suback)
  448. await writer.drain()
  449. # Send initial status report after subscribe
  450. await self._send_status_report(writer)
  451. except (IndexError, ValueError, OSError) as e:
  452. logger.debug("MQTT SUBSCRIBE error: %s", e)
  453. async def _send_status_report(self, writer: asyncio.StreamWriter) -> None:
  454. """Send a status report to the slicer after connection."""
  455. try:
  456. # Build status message matching Bambu printer format
  457. self._sequence_id += 1
  458. status = {
  459. "print": {
  460. "sequence_id": str(self._sequence_id),
  461. "command": "push_status",
  462. "msg": 0,
  463. "gcode_state": self._gcode_state,
  464. "gcode_file": self._current_file,
  465. "gcode_file_prepare_percent": self._prepare_percent,
  466. "subtask_name": self._current_file.replace(".3mf", "") if self._current_file else "",
  467. "mc_print_stage": "",
  468. "mc_percent": 0,
  469. "mc_remaining_time": 0,
  470. "wifi_signal": "-44dBm",
  471. "print_error": 0,
  472. "print_type": "",
  473. "bed_temper": 25.0,
  474. "bed_target_temper": 0.0,
  475. "nozzle_temper": 25.0,
  476. "nozzle_target_temper": 0.0,
  477. "chamber_temper": 25.0,
  478. "cooling_fan_speed": "0",
  479. "big_fan1_speed": "0",
  480. "big_fan2_speed": "0",
  481. "heatbreak_fan_speed": "0",
  482. "spd_lvl": 1,
  483. "spd_mag": 100,
  484. "stg": [],
  485. "stg_cur": 0,
  486. "layer_num": 0,
  487. "total_layer_num": 0,
  488. "home_flag": 256, # Bit 8 = SD card present (HAS_SDCARD_NORMAL)
  489. "hw_switch_state": 0,
  490. "online": {"ahb": False, "rfid": False, "version": 7},
  491. "ams_status": 0,
  492. "sdcard": True,
  493. "storage": {"free": 1000000000, "total": 32000000000},
  494. "upgrade_state": {
  495. "sequence_id": 0,
  496. "progress": "",
  497. "status": "",
  498. "consistency_request": False,
  499. "dis_state": 0,
  500. "err_code": 0,
  501. "force_upgrade": False,
  502. "message": "",
  503. "module": "",
  504. "new_version_state": 2,
  505. "new_ver_list": [],
  506. "ota_new_version_number": "",
  507. "ahb_new_version_number": "",
  508. },
  509. "ipcam": {
  510. "ipcam_dev": "1",
  511. "ipcam_record": "enable",
  512. "timelapse": "disable",
  513. "resolution": "1080p",
  514. "mode_bits": 0,
  515. },
  516. "xcam": {
  517. "allow_skip_parts": False,
  518. "buildplate_marker_detector": True,
  519. "first_layer_inspector": True,
  520. "halt_print_sensitivity": "medium",
  521. "print_halt": True,
  522. "printing_monitor": True,
  523. "spaghetti_detector": True,
  524. },
  525. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  526. "nozzle_diameter": "0.4",
  527. "nozzle_type": "hardened_steel",
  528. }
  529. }
  530. await self._publish_to_report(writer, status, self.serial)
  531. except OSError as e:
  532. logger.error("Failed to send status report: %s", e)
  533. async def _send_version_response(self, writer: asyncio.StreamWriter, sequence_id: str) -> None:
  534. """Send version info response to the slicer."""
  535. try:
  536. product_name = MODEL_PRODUCT_NAMES.get(self.model, self.model or "X1 Carbon")
  537. serial = self.serial
  538. # Build version response matching OrcaSlicer expectations
  539. # Required fields per module: name, product_name, sw_ver, sw_new_ver, sn, hw_ver, flag
  540. version_info = {
  541. "info": {
  542. "command": "get_version",
  543. "sequence_id": sequence_id,
  544. "module": [
  545. {
  546. "name": "ota",
  547. "product_name": product_name,
  548. "sw_ver": "01.07.00.00",
  549. "sw_new_ver": "",
  550. "hw_ver": "OTA",
  551. "sn": serial,
  552. "flag": 0,
  553. },
  554. {
  555. "name": "esp32",
  556. "product_name": product_name,
  557. "sw_ver": "01.07.22.25",
  558. "sw_new_ver": "",
  559. "hw_ver": "AP05",
  560. "sn": serial,
  561. "flag": 0,
  562. },
  563. {
  564. "name": "rv1126",
  565. "product_name": product_name,
  566. "sw_ver": "00.00.27.38",
  567. "sw_new_ver": "",
  568. "hw_ver": "AP05",
  569. "sn": serial,
  570. "flag": 0,
  571. },
  572. {
  573. "name": "th",
  574. "product_name": product_name,
  575. "sw_ver": "00.00.04.00",
  576. "sw_new_ver": "",
  577. "hw_ver": "TH07",
  578. "sn": serial,
  579. "flag": 0,
  580. },
  581. {
  582. "name": "mc",
  583. "product_name": product_name,
  584. "sw_ver": "00.00.10.00",
  585. "sw_new_ver": "",
  586. "hw_ver": "MC07",
  587. "sn": serial,
  588. "flag": 0,
  589. },
  590. ],
  591. }
  592. }
  593. await self._publish_to_report(writer, version_info, serial)
  594. logger.info("Sent version response (product_name=%s)", product_name)
  595. except OSError as e:
  596. logger.error("Failed to send version response: %s", e)
  597. def set_gcode_state(self, state: str, filename: str = "", prepare_percent: str = "0") -> None:
  598. """Update the gcode state reported to connected slicers.
  599. Called by the manager to reflect FTP upload progress/completion.
  600. """
  601. self._gcode_state = state
  602. self._current_file = filename
  603. self._prepare_percent = prepare_percent
  604. async def _publish_to_report(self, writer: asyncio.StreamWriter, payload: dict, serial: str = "") -> None:
  605. """Publish a message on the device report topic."""
  606. topic = f"device/{serial or self.serial}/report"
  607. message = json.dumps(payload)
  608. topic_bytes = topic.encode("utf-8")
  609. message_bytes = message.encode("utf-8")
  610. remaining = 2 + len(topic_bytes) + len(message_bytes)
  611. packet = bytes([0x30]) # PUBLISH, QoS 0
  612. while remaining > 0:
  613. byte = remaining % 128
  614. remaining //= 128
  615. if remaining > 0:
  616. byte |= 0x80
  617. packet += bytes([byte])
  618. packet += bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF])
  619. packet += topic_bytes
  620. packet += message_bytes
  621. writer.write(packet)
  622. # Timeout the drain to prevent blocking the event loop if the
  623. # MQTT client stops reading (e.g. slicer busy with FTP upload).
  624. try:
  625. await asyncio.wait_for(writer.drain(), timeout=5)
  626. except TimeoutError:
  627. logger.debug("MQTT drain timeout for %s — client may be busy", topic)
  628. async def _send_print_response(self, writer: asyncio.StreamWriter, sequence_id: str, filename: str) -> None:
  629. """Send project_file acknowledgment matching real Bambu printer behavior."""
  630. # Update state so periodic status pushes reflect preparation
  631. self._gcode_state = "PREPARE"
  632. self._current_file = filename
  633. self._prepare_percent = "0"
  634. try:
  635. # Send command acknowledgment — slicer expects to see
  636. # command: "project_file" echoed back before starting FTP upload
  637. subtask_name = filename.replace(".3mf", "") if filename else ""
  638. response = {
  639. "print": {
  640. "command": "project_file",
  641. "sequence_id": sequence_id,
  642. "param": "Metadata/plate_1.gcode",
  643. "subtask_name": subtask_name,
  644. "gcode_state": "PREPARE",
  645. "gcode_file": filename,
  646. "gcode_file_prepare_percent": "0",
  647. "result": "SUCCESS",
  648. "msg": 0,
  649. }
  650. }
  651. await self._publish_to_report(writer, response)
  652. logger.info("Sent project_file acknowledgment for %s", filename)
  653. except OSError as e:
  654. logger.error("Failed to send print response: %s", e)
  655. async def _handle_publish(self, header: int, payload: bytes, writer: asyncio.StreamWriter) -> None:
  656. """Handle MQTT PUBLISH packet."""
  657. try:
  658. # Parse topic
  659. idx = 0
  660. topic_len = (payload[idx] << 8) | payload[idx + 1]
  661. idx += 2
  662. topic = payload[idx : idx + topic_len].decode("utf-8")
  663. idx += topic_len
  664. # Check for packet ID (QoS > 0)
  665. qos = (header & 0x06) >> 1
  666. if qos > 0:
  667. # packet_id = (payload[idx] << 8) | payload[idx + 1]
  668. idx += 2
  669. # Parse message
  670. message = payload[idx:].decode("utf-8")
  671. logger.info("MQTT publish to %s: %s...", topic, message[:100])
  672. # Handle commands on device request topic
  673. if f"device/{self.serial}/request" in topic:
  674. try:
  675. data = json.loads(message)
  676. # Handle pushing command (status request)
  677. if "pushing" in data:
  678. pushing_data = data["pushing"]
  679. command = pushing_data.get("command", "")
  680. logger.info("MQTT pushing command: %s", command)
  681. if command == "pushall":
  682. # Slicer is requesting full status - send response
  683. logger.info("Sending status report in response to pushall")
  684. await self._send_status_report(writer)
  685. elif command == "start":
  686. # Slicer wants periodic status updates - send one now
  687. logger.info("Starting status push stream")
  688. await self._send_status_report(writer)
  689. # Handle info commands (get_version, etc.)
  690. if "info" in data:
  691. info_data = data["info"]
  692. command = info_data.get("command", "")
  693. sequence_id = info_data.get("sequence_id", "0")
  694. logger.info("MQTT info command: %s", command)
  695. if command == "get_version":
  696. await self._send_version_response(writer, sequence_id)
  697. # Handle print commands
  698. if "print" in data:
  699. print_data = data["print"]
  700. command = print_data.get("command", "")
  701. filename = print_data.get("subtask_name", "")
  702. sequence_id = print_data.get("sequence_id", "0")
  703. logger.info("MQTT print command: %s for %s", command, filename)
  704. if command == "project_file":
  705. # Respond with PREPARE status so slicer proceeds with FTP upload
  706. file_3mf = print_data.get("file", filename)
  707. await self._send_print_response(writer, sequence_id, file_3mf)
  708. if self.on_print_command:
  709. await self._notify_print_command(filename, print_data)
  710. except json.JSONDecodeError:
  711. pass # Non-JSON payloads on request topic are safely ignored
  712. except (IndexError, ValueError, OSError) as e:
  713. logger.debug("MQTT PUBLISH error: %s", e)
  714. async def _notify_print_command(self, filename: str, data: dict) -> None:
  715. """Notify callback of print command."""
  716. if self.on_print_command:
  717. try:
  718. result = self.on_print_command(filename, data)
  719. if asyncio.iscoroutine(result):
  720. await result
  721. except Exception as e:
  722. logger.error("Print command callback error: %s", e)