test_vp_mqtt_bridge.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. """Tests for the VP MQTT bridge — non-proxy mirror of target printer state to slicer."""
  2. import asyncio
  3. import json
  4. from pathlib import Path
  5. from unittest.mock import AsyncMock, MagicMock, patch
  6. import pytest
  7. from backend.app.services.virtual_printer.mqtt_bridge import MQTTBridge, _ip_to_uint32_le
  8. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  9. H2D_SERIAL = "0948BB540200427"
  10. VP_SERIAL = "09400A391800003"
  11. H2D_IP = "192.168.255.133"
  12. VP_IP = "192.168.255.16"
  13. def _make_server(serial: str = VP_SERIAL, bind_address: str = VP_IP) -> SimpleMQTTServer:
  14. return SimpleMQTTServer(
  15. serial=serial,
  16. access_code="deadbeef",
  17. cert_path=Path("/tmp/unused.crt"), # nosec B108
  18. key_path=Path("/tmp/unused.key"), # nosec B108
  19. model="O1D",
  20. bind_address=bind_address,
  21. )
  22. def _make_paho_client(
  23. serial: str = H2D_SERIAL,
  24. ip: str = H2D_IP,
  25. *,
  26. connected: bool = True,
  27. ) -> MagicMock:
  28. """Build a mock BambuMQTTClient that satisfies MQTTBridge's interface."""
  29. client = MagicMock()
  30. client.serial_number = serial
  31. client.ip_address = ip
  32. client.state = MagicMock()
  33. client.state.connected = connected
  34. client.publish_raw = MagicMock(return_value=True)
  35. client._raw_handlers: list = []
  36. def _register(handler):
  37. client._raw_handlers.append(handler)
  38. def _unregister(handler):
  39. if handler in client._raw_handlers:
  40. client._raw_handlers.remove(handler)
  41. client.register_raw_message_handler.side_effect = _register
  42. client.unregister_raw_message_handler.side_effect = _unregister
  43. # No-op for _request_version / request_status_update so the post-bind nudge doesn't crash.
  44. client._request_version = MagicMock()
  45. client.request_status_update = MagicMock()
  46. return client
  47. def _make_printer_manager(client) -> MagicMock:
  48. pm = MagicMock()
  49. pm.get_client = MagicMock(return_value=client)
  50. return pm
  51. def _make_bridge(server: SimpleMQTTServer, target: MagicMock | None = None) -> MQTTBridge:
  52. target = target if target is not None else _make_paho_client()
  53. pm = _make_printer_manager(target)
  54. return MQTTBridge(
  55. vp_id=1,
  56. vp_name="vp1",
  57. vp_serial=VP_SERIAL,
  58. target_printer_id=42,
  59. mqtt_server=server,
  60. printer_manager=pm,
  61. )
  62. # ---------------------------------------------------------------------------
  63. # Lifecycle
  64. # ---------------------------------------------------------------------------
  65. class TestBridgeLifecycle:
  66. @pytest.mark.asyncio
  67. async def test_start_registers_handler_on_target_client(self):
  68. target = _make_paho_client()
  69. bridge = _make_bridge(_make_server(), target)
  70. await bridge.start()
  71. assert len(target._raw_handlers) == 1
  72. assert bridge.is_active is True
  73. await bridge.stop()
  74. assert len(target._raw_handlers) == 0
  75. @pytest.mark.asyncio
  76. async def test_start_with_no_target_client_does_not_crash(self):
  77. pm = MagicMock()
  78. pm.get_client = MagicMock(return_value=None)
  79. bridge = MQTTBridge(
  80. vp_id=1,
  81. vp_name="vp1",
  82. vp_serial=VP_SERIAL,
  83. target_printer_id=42,
  84. mqtt_server=_make_server(),
  85. printer_manager=pm,
  86. )
  87. await bridge.start()
  88. assert bridge.is_active is False
  89. await bridge.stop()
  90. @pytest.mark.asyncio
  91. async def test_resolve_rebinds_when_paho_client_replaced(self):
  92. """BambuMQTTClient is destroyed and recreated on connect_printer; bridge must rebind."""
  93. old_client = _make_paho_client(serial="REAL_OLD")
  94. new_client = _make_paho_client(serial="REAL_NEW")
  95. pm = _make_printer_manager(old_client)
  96. bridge = MQTTBridge(
  97. vp_id=1,
  98. vp_name="vp1",
  99. vp_serial=VP_SERIAL,
  100. target_printer_id=42,
  101. mqtt_server=_make_server(),
  102. printer_manager=pm,
  103. )
  104. await bridge.start()
  105. assert len(old_client._raw_handlers) == 1
  106. assert bridge._target_serial == "REAL_OLD"
  107. pm.get_client.return_value = new_client
  108. bridge._resolve_client()
  109. assert len(old_client._raw_handlers) == 0
  110. assert len(new_client._raw_handlers) == 1
  111. assert bridge._target_serial == "REAL_NEW"
  112. await bridge.stop()
  113. @pytest.mark.asyncio
  114. async def test_post_bind_nudge_requests_version_and_status(self):
  115. target = _make_paho_client()
  116. bridge = _make_bridge(_make_server(), target)
  117. await bridge.start()
  118. target._request_version.assert_called_once()
  119. target.request_status_update.assert_called_once()
  120. await bridge.stop()
  121. # ---------------------------------------------------------------------------
  122. # Caching: push_status
  123. # ---------------------------------------------------------------------------
  124. class TestPushStatusCache:
  125. """push_status snapshots feed `_send_status_report` via the cache, not a fan-out."""
  126. @pytest.mark.asyncio
  127. async def test_push_status_is_cached_not_fanned_out(self):
  128. server = _make_server()
  129. server.push_raw_to_clients = AsyncMock()
  130. bridge = _make_bridge(server)
  131. await bridge.start()
  132. payload = json.dumps({"print": {"command": "push_status", "ams": {"ams": []}, "gcode_state": "IDLE"}}).encode()
  133. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  134. await asyncio.sleep(0.01)
  135. server.push_raw_to_clients.assert_not_awaited()
  136. cached = bridge.get_latest_print_state()
  137. assert cached is not None
  138. assert cached["command"] == "push_status"
  139. assert cached["gcode_state"] == "IDLE"
  140. await bridge.stop()
  141. @pytest.mark.asyncio
  142. async def test_serial_rewritten_in_cached_push(self):
  143. server = _make_server()
  144. bridge = _make_bridge(server)
  145. await bridge.start()
  146. payload = json.dumps(
  147. {
  148. "print": {
  149. "command": "push_status",
  150. "upgrade_state": {"sn": H2D_SERIAL, "status": "IDLE"},
  151. }
  152. }
  153. ).encode()
  154. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  155. await asyncio.sleep(0.01)
  156. cached = bridge.get_latest_print_state()
  157. assert cached["upgrade_state"]["sn"] == VP_SERIAL
  158. await bridge.stop()
  159. @pytest.mark.asyncio
  160. async def test_net_info_ip_rewritten_to_vp_ip(self):
  161. """BambuStudio reads `net.info[].ip` (LE uint32) for the FTP destination —
  162. must be rewritten to the VP's bind IP or the slicer bypasses the VP."""
  163. server = _make_server(bind_address=VP_IP)
  164. bridge = _make_bridge(server)
  165. await bridge.start()
  166. h2d_le = _ip_to_uint32_le(H2D_IP)
  167. vp_le = _ip_to_uint32_le(VP_IP)
  168. payload = json.dumps(
  169. {
  170. "print": {
  171. "command": "push_status",
  172. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}, {"ip": 0, "mask": 0}]},
  173. }
  174. }
  175. ).encode()
  176. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  177. await asyncio.sleep(0.01)
  178. cached = bridge.get_latest_print_state()
  179. assert cached["net"]["info"][0]["ip"] == vp_le
  180. assert cached["net"]["info"][1]["ip"] == 0 # untouched
  181. await bridge.stop()
  182. @pytest.mark.asyncio
  183. async def test_net_info_ip_rewritten_for_unknown_secondary_interface(self):
  184. """Regression for #1429: real printers (X1C / H2D Pro) report multiple
  185. active interfaces (WiFi + Ethernet) — only ONE matches the IP Bambuddy
  186. tracks. The rewrite must catch every non-zero entry, not just the one
  187. whose IP equals `_target_ip_uint32_le`, or the slicer's FTP fallback
  188. path leaks straight to the real printer."""
  189. server = _make_server(bind_address=VP_IP)
  190. bridge = _make_bridge(server)
  191. await bridge.start()
  192. h2d_le = _ip_to_uint32_le(H2D_IP)
  193. # A second IP Bambuddy never saw (e.g. printer's ethernet interface
  194. # while Bambuddy talks over wifi).
  195. other_le = _ip_to_uint32_le("192.168.99.42")
  196. vp_le = _ip_to_uint32_le(VP_IP)
  197. payload = json.dumps(
  198. {
  199. "print": {
  200. "command": "push_status",
  201. "net": {
  202. "info": [
  203. {"ip": h2d_le, "mask": 0xFFFFFF},
  204. {"ip": other_le, "mask": 0xFFFFFF},
  205. {"ip": 0, "mask": 0},
  206. ]
  207. },
  208. }
  209. }
  210. ).encode()
  211. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  212. await asyncio.sleep(0.01)
  213. cached = bridge.get_latest_print_state()
  214. assert cached["net"]["info"][0]["ip"] == vp_le
  215. assert cached["net"]["info"][1]["ip"] == vp_le # secondary interface also rewritten
  216. assert cached["net"]["info"][2]["ip"] == 0 # placeholder untouched
  217. await bridge.stop()
  218. @pytest.mark.asyncio
  219. async def test_late_arriving_printer_ip_rewrites_existing_cache(self):
  220. """Regression for #1429: if the printer's `ip_address` is empty at
  221. first bind (DB row stale, or the client object exists before the
  222. first SSDP refresh fills it in), the rewrite stays disabled and the
  223. first cached push poisons the cache with the real-printer IP.
  224. Once `ip_address` becomes valid, the next refresh tick must (a) arm
  225. the encoding and (b) sweep the cached `net.info[].ip` so the slicer
  226. sees the rewritten value on its next pull. Without the sweep the
  227. sticky-key preservation keeps the poisoned value alive across
  228. every subsequent incremental push."""
  229. server = _make_server(bind_address=VP_IP)
  230. # Bind to a client whose ip_address is empty at start — simulates the
  231. # late-arrival path.
  232. target = _make_paho_client(ip="")
  233. bridge = _make_bridge(server, target)
  234. await bridge.start()
  235. assert bridge._target_ip_uint32_le is None # not yet armed
  236. h2d_le = _ip_to_uint32_le(H2D_IP)
  237. vp_le = _ip_to_uint32_le(VP_IP)
  238. payload = json.dumps(
  239. {
  240. "print": {
  241. "command": "push_status",
  242. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  243. }
  244. }
  245. ).encode()
  246. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  247. await asyncio.sleep(0.01)
  248. # First push landed before encoding was armed → cache holds real IP.
  249. cached = bridge.get_latest_print_state()
  250. assert cached["net"]["info"][0]["ip"] == h2d_le
  251. # Printer's IP becomes known. Next refresh tick must self-heal.
  252. target.ip_address = H2D_IP
  253. bridge._resolve_client()
  254. cached = bridge.get_latest_print_state()
  255. assert cached["net"]["info"][0]["ip"] == vp_le, (
  256. "cache must be swept once encoding becomes valid; sticky-key "
  257. "preservation would otherwise keep the poisoned IP forever"
  258. )
  259. assert bridge._target_ip_uint32_le == h2d_le
  260. await bridge.stop()
  261. @pytest.mark.asyncio
  262. async def test_request_topic_message_is_ignored(self):
  263. server = _make_server()
  264. bridge = _make_bridge(server)
  265. await bridge.start()
  266. payload = json.dumps({"print": {"command": "push_status"}}).encode()
  267. bridge._on_printer_raw(f"device/{H2D_SERIAL}/request", payload)
  268. await asyncio.sleep(0.01)
  269. assert bridge.get_latest_print_state() is None
  270. await bridge.stop()
  271. @pytest.mark.asyncio
  272. async def test_incremental_push_preserves_ams_from_previous_cache(self):
  273. """Regression for #1371: Bambu firmware sends FULL push_status on
  274. pushall (with AMS/vt_tray/net/etc.) but typically OMITS those fields
  275. from 1 Hz incremental push_status updates. Without preserving the
  276. sticky keys across pushes, the cache forgets AMS info after the first
  277. incremental update, and BambuStudio (which reads the cache via the
  278. VP's 1 Hz status push) sees no AMS info until the user power-cycles
  279. the printer (forcing a fresh pushall).
  280. """
  281. server = _make_server()
  282. bridge = _make_bridge(server)
  283. await bridge.start()
  284. # 1. Initial pushall response with full state, AMS included.
  285. full_push = json.dumps(
  286. {
  287. "print": {
  288. "command": "push_status",
  289. "gcode_state": "IDLE",
  290. "wifi_signal": "-50dBm",
  291. "ams": {
  292. "ams": [
  293. {
  294. "id": "0",
  295. "tray": [
  296. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  297. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  298. ],
  299. }
  300. ],
  301. "tray_exist_bits": "3",
  302. },
  303. "vt_tray": {"id": "254", "tray_type": ""},
  304. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  305. }
  306. }
  307. ).encode()
  308. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", full_push)
  309. await asyncio.sleep(0.01)
  310. cached = bridge.get_latest_print_state()
  311. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  312. assert cached["vt_tray"]["id"] == "254"
  313. assert cached["lights_report"][0]["mode"] == "on"
  314. # 2. Incremental push with only temp/wifi changes — NO ams field.
  315. # This is what the printer sends every ~1 s between full pushalls.
  316. incremental_push = json.dumps(
  317. {
  318. "print": {
  319. "command": "push_status",
  320. "wifi_signal": "-55dBm",
  321. "chamber_temper": 26.0,
  322. }
  323. }
  324. ).encode()
  325. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", incremental_push)
  326. await asyncio.sleep(0.01)
  327. cached = bridge.get_latest_print_state()
  328. # New fields take effect.
  329. assert cached["wifi_signal"] == "-55dBm"
  330. assert cached["chamber_temper"] == 26.0
  331. # Sticky fields preserved from the previous cache (the #1371 fix).
  332. assert "ams" in cached, "AMS field must be preserved across incremental pushes (#1371)"
  333. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  334. assert cached["ams"]["tray_exist_bits"] == "3"
  335. assert cached["vt_tray"]["id"] == "254"
  336. assert cached["lights_report"][0]["mode"] == "on"
  337. await bridge.stop()
  338. @pytest.mark.asyncio
  339. async def test_partial_ams_status_update_preserves_unit_list(self):
  340. """#1387: Bambu firmware also sends `ams` updates where the key is
  341. present but the inner `ams` array is missing — e.g. just
  342. ``{ams_status: 1}`` or a humidity change. Before the deep-merge fix
  343. the bridge would overwrite the cached AMS with this stripped blob,
  344. the slicer would read it on the next 1 Hz push, and BambuStudio
  345. would drop the unit list and fall back to its "no AMS" render
  346. (only the external spool visible — the reporter's exact symptom).
  347. Now the partial update only mutates the fields it carries; the
  348. cached unit list survives.
  349. """
  350. server = _make_server()
  351. bridge = _make_bridge(server)
  352. await bridge.start()
  353. # 1. Pushall with full AMS state.
  354. bridge._on_printer_raw(
  355. f"device/{H2D_SERIAL}/report",
  356. json.dumps(
  357. {
  358. "print": {
  359. "command": "push_status",
  360. "ams": {
  361. "ams": [
  362. {
  363. "id": "0",
  364. "humidity": "1",
  365. "tray": [{"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"}],
  366. }
  367. ],
  368. "tray_exist_bits": "1",
  369. "ams_status": "0",
  370. },
  371. }
  372. }
  373. ).encode(),
  374. )
  375. await asyncio.sleep(0.01)
  376. # 2. Partial AMS update — only `ams_status` and `humidity` changed.
  377. # No `ams.ams` array, so prev's unit list must be preserved.
  378. bridge._on_printer_raw(
  379. f"device/{H2D_SERIAL}/report",
  380. json.dumps(
  381. {
  382. "print": {
  383. "command": "push_status",
  384. "ams": {"ams_status": "1", "humidity": "2"},
  385. }
  386. }
  387. ).encode(),
  388. )
  389. await asyncio.sleep(0.01)
  390. cached = bridge.get_latest_print_state()
  391. # Scalar fields take the new values.
  392. assert cached["ams"]["ams_status"] == "1"
  393. assert cached["ams"]["humidity"] == "2"
  394. # Unit + tray data preserved from the pushall.
  395. assert cached["ams"]["tray_exist_bits"] == "1"
  396. assert len(cached["ams"]["ams"]) == 1
  397. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  398. assert cached["ams"]["ams"][0]["tray"][0]["tray_color"] == "FF0000FF"
  399. await bridge.stop()
  400. @pytest.mark.asyncio
  401. async def test_partial_ams_unit_update_preserves_other_units(self):
  402. """#1387: when multiple AMS units are configured (e.g. H2D with two
  403. AMS), an incremental push during a print typically only carries the
  404. unit / tray that changed state. Naive replacement of `ams.ams` wipes
  405. the other unit. The bridge merges unit-by-unit by id, preserving
  406. units the incremental doesn't mention.
  407. """
  408. server = _make_server()
  409. bridge = _make_bridge(server)
  410. await bridge.start()
  411. # 1. Pushall with two AMS units configured.
  412. bridge._on_printer_raw(
  413. f"device/{H2D_SERIAL}/report",
  414. json.dumps(
  415. {
  416. "print": {
  417. "command": "push_status",
  418. "ams": {
  419. "ams": [
  420. {"id": "0", "tray": [{"id": "0", "tray_type": "PLA"}]},
  421. {"id": "1", "tray": [{"id": "0", "tray_type": "PETG"}]},
  422. ],
  423. "tray_exist_bits": "3",
  424. },
  425. }
  426. }
  427. ).encode(),
  428. )
  429. await asyncio.sleep(0.01)
  430. # 2. Tray-targeted incremental: unit 0 / tray 0 state changed.
  431. # Unit 1 is not in the update — must survive.
  432. bridge._on_printer_raw(
  433. f"device/{H2D_SERIAL}/report",
  434. json.dumps(
  435. {
  436. "print": {
  437. "command": "push_status",
  438. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "state": "11"}]}]},
  439. }
  440. }
  441. ).encode(),
  442. )
  443. await asyncio.sleep(0.01)
  444. cached = bridge.get_latest_print_state()
  445. units = {u["id"]: u for u in cached["ams"]["ams"]}
  446. # Unit 0 keeps its tray_type from the pushall + picks up the new state.
  447. assert units["0"]["tray"][0]["tray_type"] == "PLA"
  448. assert units["0"]["tray"][0]["state"] == "11"
  449. # Unit 1 survives the incremental.
  450. assert "1" in units
  451. assert units["1"]["tray"][0]["tray_type"] == "PETG"
  452. await bridge.stop()
  453. @pytest.mark.asyncio
  454. async def test_partial_ams_tray_update_preserves_other_trays(self):
  455. """Same shape as the unit-level test but at the tray level. AMS
  456. unit 0 has four trays; the incremental only mentions tray 0.
  457. Trays 1-3 must survive intact."""
  458. server = _make_server()
  459. bridge = _make_bridge(server)
  460. await bridge.start()
  461. bridge._on_printer_raw(
  462. f"device/{H2D_SERIAL}/report",
  463. json.dumps(
  464. {
  465. "print": {
  466. "command": "push_status",
  467. "ams": {
  468. "ams": [
  469. {
  470. "id": "0",
  471. "tray": [
  472. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  473. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  474. {"id": "2", "tray_type": "ABS", "tray_color": "0000FFFF"},
  475. {"id": "3", "tray_type": "TPU", "tray_color": "FFFF00FF"},
  476. ],
  477. }
  478. ],
  479. },
  480. }
  481. }
  482. ).encode(),
  483. )
  484. await asyncio.sleep(0.01)
  485. bridge._on_printer_raw(
  486. f"device/{H2D_SERIAL}/report",
  487. json.dumps(
  488. {
  489. "print": {
  490. "command": "push_status",
  491. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "state": "11"}]}]},
  492. }
  493. }
  494. ).encode(),
  495. )
  496. await asyncio.sleep(0.01)
  497. cached = bridge.get_latest_print_state()
  498. trays = {t["id"]: t for t in cached["ams"]["ams"][0]["tray"]}
  499. assert trays["0"]["tray_type"] == "PLA"
  500. assert trays["0"]["state"] == "11"
  501. # Trays not mentioned in the incremental survive intact.
  502. assert trays["1"]["tray_type"] == "PETG"
  503. assert trays["2"]["tray_type"] == "ABS"
  504. assert trays["3"]["tray_type"] == "TPU"
  505. await bridge.stop()
  506. @pytest.mark.asyncio
  507. async def test_incoming_ams_update_replaces_cached_ams(self):
  508. """Counterpart to the #1371 fix: preservation only kicks in when the
  509. incoming push OMITS a sticky key. When the printer DOES send a fresh
  510. `ams` value (e.g. on a pushall, or when AMS state genuinely changes),
  511. that value must take effect — the preservation must not shadow real
  512. updates.
  513. """
  514. server = _make_server()
  515. bridge = _make_bridge(server)
  516. await bridge.start()
  517. # 1. Initial state: PLA in tray 0.
  518. bridge._on_printer_raw(
  519. f"device/{H2D_SERIAL}/report",
  520. json.dumps(
  521. {
  522. "print": {
  523. "command": "push_status",
  524. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "tray_type": "PLA"}]}]},
  525. }
  526. }
  527. ).encode(),
  528. )
  529. await asyncio.sleep(0.01)
  530. # 2. Fresh push with PETG — must replace, not get shadowed by the old PLA.
  531. bridge._on_printer_raw(
  532. f"device/{H2D_SERIAL}/report",
  533. json.dumps(
  534. {
  535. "print": {
  536. "command": "push_status",
  537. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "tray_type": "PETG"}]}]},
  538. }
  539. }
  540. ).encode(),
  541. )
  542. await asyncio.sleep(0.01)
  543. cached = bridge.get_latest_print_state()
  544. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PETG"
  545. await bridge.stop()
  546. # ---------------------------------------------------------------------------
  547. # Caching: get_version response
  548. # ---------------------------------------------------------------------------
  549. class TestVersionCache:
  550. @pytest.mark.asyncio
  551. async def test_get_version_response_caches_modules(self):
  552. server = _make_server()
  553. bridge = _make_bridge(server)
  554. await bridge.start()
  555. payload = json.dumps(
  556. {
  557. "info": {
  558. "command": "get_version",
  559. "module": [
  560. {"name": "ota", "sn": H2D_SERIAL, "sw_ver": "01.03.00.00"},
  561. {"name": "n3f/0", "sn": "AMS_HW_1", "sw_ver": "04.00.21.87"},
  562. ],
  563. }
  564. }
  565. ).encode()
  566. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  567. await asyncio.sleep(0.01)
  568. modules = bridge.get_latest_version_modules()
  569. assert modules is not None
  570. assert len(modules) == 2
  571. # Device-level sn rewritten; AMS-hardware sn left alone.
  572. assert modules[0]["sn"] == VP_SERIAL
  573. assert modules[1]["sn"] == "AMS_HW_1"
  574. await bridge.stop()
  575. # ---------------------------------------------------------------------------
  576. # Selective fan-out (everything that's not push_status / get_version)
  577. # ---------------------------------------------------------------------------
  578. class TestCommandResponseFanout:
  579. @pytest.mark.asyncio
  580. async def test_extrusion_cali_get_response_is_fanned_out(self):
  581. """Slicer's extrusion_cali_get goes to the printer; the printer's response
  582. must reach the slicer or BambuStudio's pre-flight blocks Send."""
  583. server = _make_server()
  584. server.push_raw_to_clients = AsyncMock()
  585. bridge = _make_bridge(server)
  586. await bridge.start()
  587. body = json.dumps({"print": {"command": "extrusion_cali_get", "filaments": []}}).encode()
  588. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", body)
  589. await asyncio.sleep(0.01)
  590. server.push_raw_to_clients.assert_awaited_once()
  591. topic, _payload = server.push_raw_to_clients.await_args.args
  592. assert topic == f"device/{VP_SERIAL}/report"
  593. await bridge.stop()
  594. # ---------------------------------------------------------------------------
  595. # Forwarding: slicer → printer
  596. # ---------------------------------------------------------------------------
  597. class TestForwardToPrinter:
  598. @pytest.mark.asyncio
  599. async def test_forward_publishes_to_real_serial_request_topic(self):
  600. target = _make_paho_client()
  601. bridge = _make_bridge(_make_server(), target)
  602. await bridge.start()
  603. ok = bridge.forward_to_printer({"print": {"command": "stop"}})
  604. assert ok is True
  605. target.publish_raw.assert_called_once()
  606. topic, payload = target.publish_raw.call_args.args
  607. assert topic == f"device/{H2D_SERIAL}/request"
  608. assert json.loads(payload) == {"print": {"command": "stop"}}
  609. await bridge.stop()
  610. @pytest.mark.asyncio
  611. async def test_forward_returns_false_when_not_bound(self):
  612. pm = MagicMock()
  613. pm.get_client = MagicMock(return_value=None)
  614. bridge = MQTTBridge(
  615. vp_id=1,
  616. vp_name="vp1",
  617. vp_serial=VP_SERIAL,
  618. target_printer_id=42,
  619. mqtt_server=_make_server(),
  620. printer_manager=pm,
  621. )
  622. await bridge.start()
  623. assert bridge.forward_to_printer({"print": {"command": "stop"}}) is False
  624. await bridge.stop()
  625. # ---------------------------------------------------------------------------
  626. # SimpleMQTTServer status response: cached-as-base
  627. # ---------------------------------------------------------------------------
  628. class TestStatusReportCachedAsBase:
  629. """`_send_status_report` sends near-byte-identical real data when bridge cache exists."""
  630. def _capture_published(self, server: SimpleMQTTServer):
  631. """Wrap _publish_to_report to capture (topic, payload_dict)."""
  632. published: list = []
  633. async def _capture(writer, payload, serial=""):
  634. published.append((serial or server.serial, payload))
  635. server._publish_to_report = _capture # type: ignore[assignment]
  636. return published
  637. @pytest.mark.asyncio
  638. async def test_uses_real_cache_when_bridge_active(self):
  639. server = _make_server()
  640. bridge = MagicMock()
  641. bridge.get_latest_print_state.return_value = {
  642. "command": "push_status",
  643. "msg": 0,
  644. "ams": {"ams": [{"id": "0"}]},
  645. "device": {"extruder": {"info": [{"id": 0}, {"id": 1}]}},
  646. "nozzle_diameter": "0.4",
  647. "nozzle_type": "HH01", # real H2D value, not synthetic 'hardened_steel'
  648. }
  649. server.set_bridge(bridge)
  650. published = self._capture_published(server)
  651. await server._send_status_report(MagicMock())
  652. assert len(published) == 1
  653. _serial, payload = published[0]
  654. # AMS / device / nozzle_type all from cache
  655. assert payload["print"]["nozzle_type"] == "HH01"
  656. assert payload["print"]["device"]["extruder"]["info"][1]["id"] == 1
  657. # Protocol fields under our control
  658. assert payload["print"]["command"] == "push_status"
  659. assert payload["print"]["gcode_state"] == "IDLE"
  660. @pytest.mark.asyncio
  661. async def test_falls_back_to_synthetic_when_no_cache(self):
  662. server = _make_server()
  663. bridge = MagicMock()
  664. bridge.get_latest_print_state.return_value = None
  665. server.set_bridge(bridge)
  666. published = self._capture_published(server)
  667. await server._send_status_report(MagicMock())
  668. assert len(published) == 1
  669. _serial, payload = published[0]
  670. # Synthetic baseline has stub fields like nozzle_type='hardened_steel'
  671. # and a `storage` field that the real H2D doesn't push.
  672. assert payload["print"]["nozzle_type"] == "hardened_steel"
  673. assert "storage" in payload["print"]
  674. @pytest.mark.asyncio
  675. async def test_storage_indicators_overlaid_for_send_preflight(self):
  676. """#1228: P1S/A1-class firmware doesn't always include the SD/storage
  677. fields BambuStudio's "Send" pre-flight reads. Without these the
  678. slicer rejects with 'storage needs to be inserted' before even
  679. attempting FTP. The cached-as-base path now overlays them so the
  680. pre-flight passes regardless of what the real printer reports.
  681. """
  682. server = _make_server()
  683. bridge = MagicMock()
  684. # Real P1S push without SD card inserted: home_flag has other bits set
  685. # but the SD bit (0x100) is clear; sdcard is False; no storage field.
  686. bridge.get_latest_print_state.return_value = {
  687. "command": "push_status",
  688. "msg": 0,
  689. "home_flag": 0x42,
  690. "sdcard": False,
  691. }
  692. server.set_bridge(bridge)
  693. published = self._capture_published(server)
  694. await server._send_status_report(MagicMock())
  695. _serial, payload = published[0]
  696. # SD bit ORed onto whatever was there — other bits preserved.
  697. assert payload["print"]["home_flag"] & 0x100 == 0x100
  698. assert payload["print"]["home_flag"] & 0x42 == 0x42
  699. # Force-set so a False from the printer doesn't trip the pre-flight.
  700. assert payload["print"]["sdcard"] is True
  701. # storage was missing — the overlay must inject a non-empty default.
  702. assert "storage" in payload["print"]
  703. assert payload["print"]["storage"]["free"] > 0
  704. assert payload["print"]["storage"]["total"] > 0
  705. @pytest.mark.asyncio
  706. async def test_storage_indicators_preserve_real_storage_when_present(self):
  707. """When the real printer DOES report a storage block, pass it through
  708. unchanged (the overlay only fills in the missing field, not overrides).
  709. """
  710. server = _make_server()
  711. bridge = MagicMock()
  712. real_storage = {"free": 12345, "total": 67890}
  713. bridge.get_latest_print_state.return_value = {
  714. "command": "push_status",
  715. "msg": 0,
  716. "home_flag": 0x100, # SD bit already set on the real printer
  717. "sdcard": True,
  718. "storage": real_storage,
  719. }
  720. server.set_bridge(bridge)
  721. published = self._capture_published(server)
  722. await server._send_status_report(MagicMock())
  723. _serial, payload = published[0]
  724. # SD bit OR is idempotent — already-set bit stays set.
  725. assert payload["print"]["home_flag"] == 0x100
  726. assert payload["print"]["sdcard"] is True
  727. # Real values pass through, NOT the synthetic defaults.
  728. assert payload["print"]["storage"] == real_storage
  729. @pytest.mark.asyncio
  730. async def test_overrides_protocol_fields_even_when_cache_present(self):
  731. """Cached value's gcode_state must NOT win over our local upload-state-machine value."""
  732. server = _make_server()
  733. server._gcode_state = "PREPARE"
  734. server._current_file = "foo.3mf"
  735. bridge = MagicMock()
  736. bridge.get_latest_print_state.return_value = {
  737. "command": "push_status",
  738. "gcode_state": "IDLE", # printer is idle; we are mid-FTP-upload
  739. "gcode_file": "",
  740. "gcode_file_prepare_percent": "0",
  741. }
  742. server.set_bridge(bridge)
  743. published = self._capture_published(server)
  744. await server._send_status_report(MagicMock())
  745. _serial, payload = published[0]
  746. assert payload["print"]["gcode_state"] == "PREPARE"
  747. assert payload["print"]["gcode_file"] == "foo.3mf"
  748. @pytest.mark.asyncio
  749. async def test_live_progress_fields_zeroed_in_cached_branch(self):
  750. """#1558: when the real target printer is mid-print, the cached
  751. push_status carries live values for mc_percent / stg_cur / layer_num /
  752. etc. BambuStudio's Send pre-flight reads any of these as "VP busy"
  753. even when gcode_state above is forced to IDLE — blocking Send while
  754. the target prints. The cached branch must override these to the same
  755. idle values the synthetic stub uses.
  756. """
  757. server = _make_server()
  758. bridge = MagicMock()
  759. # Real printer mid-print state: gcode_state may be RUNNING upstream,
  760. # but the VP's own _gcode_state is IDLE (Send is requesting a
  761. # new upload, the VP isn't running anything).
  762. bridge.get_latest_print_state.return_value = {
  763. "command": "push_status",
  764. "msg": 0,
  765. "gcode_state": "RUNNING",
  766. "mc_print_stage": "2",
  767. "mc_percent": 47,
  768. "mc_remaining_time": 3600,
  769. "stg": [1, 2, 3],
  770. "stg_cur": 14,
  771. "layer_num": 120,
  772. "total_layer_num": 250,
  773. "print_error": 0,
  774. }
  775. server.set_bridge(bridge)
  776. published = self._capture_published(server)
  777. await server._send_status_report(MagicMock())
  778. _serial, payload = published[0]
  779. # Every live-progress field must reflect "idle / VP isn't busy".
  780. assert payload["print"]["mc_print_stage"] == ""
  781. assert payload["print"]["mc_percent"] == 0
  782. assert payload["print"]["mc_remaining_time"] == 0
  783. assert payload["print"]["stg"] == []
  784. assert payload["print"]["stg_cur"] == 0
  785. assert payload["print"]["layer_num"] == 0
  786. assert payload["print"]["total_layer_num"] == 0
  787. assert payload["print"]["print_error"] == 0
  788. # ---------------------------------------------------------------------------
  789. # Wire format
  790. # ---------------------------------------------------------------------------
  791. class TestWireFormat:
  792. """BambuStudio's Send pre-flight rejects compact JSON — must match real printer's
  793. indented format (32K bytes for an idle H2D vs 14K compact)."""
  794. @pytest.mark.asyncio
  795. async def test_publish_uses_indent_4_json_format(self):
  796. server = _make_server()
  797. captured: list = []
  798. async def _capture_drain():
  799. pass
  800. writer = MagicMock()
  801. writer.write = lambda data: captured.append(data)
  802. writer.drain = AsyncMock()
  803. await server._publish_to_report(writer, {"print": {"command": "push_status", "ams": {}}})
  804. body = b"".join(captured)
  805. assert b'\n "print"' in body, "publish_to_report must use indent=4 JSON"
  806. # ---------------------------------------------------------------------------
  807. # Routing: _handle_publish
  808. # ---------------------------------------------------------------------------
  809. class TestPublishRouting:
  810. """Slicer-issued commands: project_file/gcode_file handled locally, everything
  811. else forwarded to the real printer."""
  812. def _build_publish_payload(self, topic: str, body: bytes) -> bytes:
  813. topic_bytes = topic.encode("utf-8")
  814. return bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF]) + topic_bytes + body
  815. def _attach_active_bridge(self, server: SimpleMQTTServer) -> MagicMock:
  816. bridge = MagicMock()
  817. bridge.is_active = True
  818. bridge.forward_to_printer = MagicMock(return_value=True)
  819. server.set_bridge(bridge)
  820. return bridge
  821. @pytest.mark.asyncio
  822. async def test_project_file_handled_locally_not_forwarded(self):
  823. server = _make_server()
  824. bridge = self._attach_active_bridge(server)
  825. writer = MagicMock()
  826. writer.write = MagicMock()
  827. writer.drain = AsyncMock()
  828. body = json.dumps({"print": {"command": "project_file", "subtask_name": "f", "sequence_id": "1"}}).encode()
  829. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  830. with patch.object(server, "_send_print_response", new=AsyncMock()) as mock_resp:
  831. await server._handle_publish(0x30, payload, writer, "client1")
  832. bridge.forward_to_printer.assert_not_called()
  833. mock_resp.assert_awaited_once()
  834. @pytest.mark.asyncio
  835. async def test_gcode_file_handled_locally_not_forwarded(self):
  836. server = _make_server()
  837. bridge = self._attach_active_bridge(server)
  838. writer = MagicMock()
  839. writer.write = MagicMock()
  840. writer.drain = AsyncMock()
  841. body = json.dumps({"print": {"command": "gcode_file", "subtask_name": "f.gcode", "sequence_id": "1"}}).encode()
  842. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  843. with patch.object(server, "_send_print_response", new=AsyncMock()):
  844. await server._handle_publish(0x30, payload, writer, "client1")
  845. bridge.forward_to_printer.assert_not_called()
  846. @pytest.mark.asyncio
  847. async def test_pushall_handled_locally_not_forwarded(self):
  848. server = _make_server()
  849. bridge = self._attach_active_bridge(server)
  850. writer = MagicMock()
  851. writer.write = MagicMock()
  852. writer.drain = AsyncMock()
  853. body = json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}).encode()
  854. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  855. with patch.object(server, "_send_status_report", new=AsyncMock()) as mock_status:
  856. await server._handle_publish(0x30, payload, writer, "client1")
  857. # Synthetic answer fires (fast, low latency); no forwarding (the
  858. # cache already mirrors what the printer would respond with).
  859. bridge.forward_to_printer.assert_not_called()
  860. mock_status.assert_awaited_once()
  861. @pytest.mark.asyncio
  862. async def test_get_version_handled_locally_not_forwarded(self):
  863. server = _make_server()
  864. bridge = self._attach_active_bridge(server)
  865. writer = MagicMock()
  866. writer.write = MagicMock()
  867. writer.drain = AsyncMock()
  868. body = json.dumps({"info": {"command": "get_version", "sequence_id": "1"}}).encode()
  869. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  870. with patch.object(server, "_send_version_response", new=AsyncMock()) as mock_ver:
  871. await server._handle_publish(0x30, payload, writer, "client1")
  872. bridge.forward_to_printer.assert_not_called()
  873. mock_ver.assert_awaited_once()
  874. @pytest.mark.asyncio
  875. async def test_extrusion_cali_get_is_forwarded(self):
  876. """extrusion_cali_get fetches per-filament k-profiles — must reach the printer."""
  877. server = _make_server()
  878. bridge = self._attach_active_bridge(server)
  879. writer = MagicMock()
  880. writer.write = MagicMock()
  881. writer.drain = AsyncMock()
  882. body = json.dumps(
  883. {
  884. "print": {
  885. "command": "extrusion_cali_get",
  886. "filament_id": "",
  887. "nozzle_diameter": "0.4",
  888. "sequence_id": "5",
  889. }
  890. }
  891. ).encode()
  892. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  893. await server._handle_publish(0x30, payload, writer, "client1")
  894. bridge.forward_to_printer.assert_called_once()
  895. forwarded = bridge.forward_to_printer.call_args.args[0]
  896. assert forwarded["print"]["command"] == "extrusion_cali_get"
  897. @pytest.mark.asyncio
  898. async def test_print_stop_is_forwarded(self):
  899. server = _make_server()
  900. bridge = self._attach_active_bridge(server)
  901. writer = MagicMock()
  902. writer.write = MagicMock()
  903. writer.drain = AsyncMock()
  904. body = json.dumps({"print": {"command": "stop", "sequence_id": "5"}}).encode()
  905. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  906. await server._handle_publish(0x30, payload, writer, "client1")
  907. bridge.forward_to_printer.assert_called_once()
  908. # ---------------------------------------------------------------------------
  909. # IP encoding helper
  910. # ---------------------------------------------------------------------------
  911. class TestIpEncoding:
  912. def test_le_uint32_matches_real_h2d_capture(self):
  913. # 192.168.255.133 captured from real H2D's net.info[0].ip = 2248124608
  914. assert _ip_to_uint32_le("192.168.255.133") == 2248124608
  915. def test_vp_ip_round_trip(self):
  916. assert _ip_to_uint32_le("192.168.255.16") == 285190336
  917. def test_invalid_ip_raises(self):
  918. with pytest.raises(ValueError):
  919. _ip_to_uint32_le("not.an.ip.actually")