test_vp_mqtt_bridge.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. """Tests for the VP MQTT bridge — non-proxy mirror of target printer state to slicer."""
  2. import asyncio
  3. import json
  4. import logging
  5. import socket
  6. from pathlib import Path
  7. from unittest.mock import AsyncMock, MagicMock, patch
  8. import pytest
  9. from backend.app.services.virtual_printer.mqtt_bridge import (
  10. MQTTBridge,
  11. _ip_to_uint32_le,
  12. _resolve_host_interface_for_target,
  13. _resolve_target_to_ipv4,
  14. )
  15. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  16. H2D_SERIAL = "0948BB540200427"
  17. VP_SERIAL = "09400A391800003"
  18. H2D_IP = "192.168.255.133"
  19. VP_IP = "192.168.255.16"
  20. def _make_server(serial: str = VP_SERIAL, bind_address: str = VP_IP) -> SimpleMQTTServer:
  21. return SimpleMQTTServer(
  22. serial=serial,
  23. access_code="deadbeef",
  24. cert_path=Path("/tmp/unused.crt"), # nosec B108
  25. key_path=Path("/tmp/unused.key"), # nosec B108
  26. model="O1D",
  27. bind_address=bind_address,
  28. )
  29. def _make_paho_client(
  30. serial: str = H2D_SERIAL,
  31. ip: str = H2D_IP,
  32. *,
  33. connected: bool = True,
  34. ) -> MagicMock:
  35. """Build a mock BambuMQTTClient that satisfies MQTTBridge's interface."""
  36. client = MagicMock()
  37. client.serial_number = serial
  38. client.ip_address = ip
  39. client.state = MagicMock()
  40. client.state.connected = connected
  41. client.publish_raw = MagicMock(return_value=True)
  42. client._raw_handlers: list = []
  43. def _register(handler):
  44. client._raw_handlers.append(handler)
  45. def _unregister(handler):
  46. if handler in client._raw_handlers:
  47. client._raw_handlers.remove(handler)
  48. client.register_raw_message_handler.side_effect = _register
  49. client.unregister_raw_message_handler.side_effect = _unregister
  50. # No-op for _request_version / request_status_update so the post-bind nudge doesn't crash.
  51. client._request_version = MagicMock()
  52. client.request_status_update = MagicMock()
  53. return client
  54. def _make_printer_manager(client) -> MagicMock:
  55. pm = MagicMock()
  56. pm.get_client = MagicMock(return_value=client)
  57. return pm
  58. def _make_bridge(server: SimpleMQTTServer, target: MagicMock | None = None) -> MQTTBridge:
  59. target = target if target is not None else _make_paho_client()
  60. pm = _make_printer_manager(target)
  61. return MQTTBridge(
  62. vp_id=1,
  63. vp_name="vp1",
  64. vp_serial=VP_SERIAL,
  65. target_printer_id=42,
  66. mqtt_server=server,
  67. printer_manager=pm,
  68. )
  69. # ---------------------------------------------------------------------------
  70. # Lifecycle
  71. # ---------------------------------------------------------------------------
  72. class TestBridgeLifecycle:
  73. @pytest.mark.asyncio
  74. async def test_start_registers_handler_on_target_client(self):
  75. target = _make_paho_client()
  76. bridge = _make_bridge(_make_server(), target)
  77. await bridge.start()
  78. assert len(target._raw_handlers) == 1
  79. assert bridge.is_active is True
  80. await bridge.stop()
  81. assert len(target._raw_handlers) == 0
  82. @pytest.mark.asyncio
  83. async def test_start_with_no_target_client_does_not_crash(self):
  84. pm = MagicMock()
  85. pm.get_client = MagicMock(return_value=None)
  86. bridge = MQTTBridge(
  87. vp_id=1,
  88. vp_name="vp1",
  89. vp_serial=VP_SERIAL,
  90. target_printer_id=42,
  91. mqtt_server=_make_server(),
  92. printer_manager=pm,
  93. )
  94. await bridge.start()
  95. assert bridge.is_active is False
  96. await bridge.stop()
  97. @pytest.mark.asyncio
  98. async def test_resolve_rebinds_when_paho_client_replaced(self):
  99. """BambuMQTTClient is destroyed and recreated on connect_printer; bridge must rebind."""
  100. old_client = _make_paho_client(serial="REAL_OLD")
  101. new_client = _make_paho_client(serial="REAL_NEW")
  102. pm = _make_printer_manager(old_client)
  103. bridge = MQTTBridge(
  104. vp_id=1,
  105. vp_name="vp1",
  106. vp_serial=VP_SERIAL,
  107. target_printer_id=42,
  108. mqtt_server=_make_server(),
  109. printer_manager=pm,
  110. )
  111. await bridge.start()
  112. assert len(old_client._raw_handlers) == 1
  113. assert bridge._target_serial == "REAL_OLD"
  114. pm.get_client.return_value = new_client
  115. bridge._resolve_client()
  116. assert len(old_client._raw_handlers) == 0
  117. assert len(new_client._raw_handlers) == 1
  118. assert bridge._target_serial == "REAL_NEW"
  119. await bridge.stop()
  120. @pytest.mark.asyncio
  121. async def test_post_bind_nudge_requests_version_and_status(self):
  122. target = _make_paho_client()
  123. bridge = _make_bridge(_make_server(), target)
  124. await bridge.start()
  125. target._request_version.assert_called_once()
  126. target.request_status_update.assert_called_once()
  127. await bridge.stop()
  128. # ---------------------------------------------------------------------------
  129. # Caching: push_status
  130. # ---------------------------------------------------------------------------
  131. class TestPushStatusCache:
  132. """push_status snapshots feed `_send_status_report` via the cache, not a fan-out."""
  133. @pytest.mark.asyncio
  134. async def test_push_status_is_cached_not_fanned_out(self):
  135. server = _make_server()
  136. server.push_raw_to_clients = AsyncMock()
  137. bridge = _make_bridge(server)
  138. await bridge.start()
  139. payload = json.dumps({"print": {"command": "push_status", "ams": {"ams": []}, "gcode_state": "IDLE"}}).encode()
  140. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  141. await asyncio.sleep(0.01)
  142. server.push_raw_to_clients.assert_not_awaited()
  143. cached = bridge.get_latest_print_state()
  144. assert cached is not None
  145. assert cached["command"] == "push_status"
  146. assert cached["gcode_state"] == "IDLE"
  147. await bridge.stop()
  148. @pytest.mark.asyncio
  149. async def test_serial_rewritten_in_cached_push(self):
  150. server = _make_server()
  151. bridge = _make_bridge(server)
  152. await bridge.start()
  153. payload = json.dumps(
  154. {
  155. "print": {
  156. "command": "push_status",
  157. "upgrade_state": {"sn": H2D_SERIAL, "status": "IDLE"},
  158. }
  159. }
  160. ).encode()
  161. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  162. await asyncio.sleep(0.01)
  163. cached = bridge.get_latest_print_state()
  164. assert cached["upgrade_state"]["sn"] == VP_SERIAL
  165. await bridge.stop()
  166. @pytest.mark.asyncio
  167. async def test_net_info_ip_rewritten_to_vp_ip(self):
  168. """BambuStudio reads `net.info[].ip` (LE uint32) for the FTP destination —
  169. must be rewritten to the VP's bind IP or the slicer bypasses the VP."""
  170. server = _make_server(bind_address=VP_IP)
  171. bridge = _make_bridge(server)
  172. await bridge.start()
  173. h2d_le = _ip_to_uint32_le(H2D_IP)
  174. vp_le = _ip_to_uint32_le(VP_IP)
  175. payload = json.dumps(
  176. {
  177. "print": {
  178. "command": "push_status",
  179. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}, {"ip": 0, "mask": 0}]},
  180. }
  181. }
  182. ).encode()
  183. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  184. await asyncio.sleep(0.01)
  185. cached = bridge.get_latest_print_state()
  186. assert cached["net"]["info"][0]["ip"] == vp_le
  187. assert cached["net"]["info"][1]["ip"] == 0 # untouched
  188. await bridge.stop()
  189. @pytest.mark.asyncio
  190. async def test_net_info_ip_rewritten_for_unknown_secondary_interface(self):
  191. """Regression for #1429: real printers (X1C / H2D Pro) report multiple
  192. active interfaces (WiFi + Ethernet) — only ONE matches the IP Bambuddy
  193. tracks. The rewrite must catch every non-zero entry, not just the one
  194. whose IP equals `_target_ip_uint32_le`, or the slicer's FTP fallback
  195. path leaks straight to the real printer."""
  196. server = _make_server(bind_address=VP_IP)
  197. bridge = _make_bridge(server)
  198. await bridge.start()
  199. h2d_le = _ip_to_uint32_le(H2D_IP)
  200. # A second IP Bambuddy never saw (e.g. printer's ethernet interface
  201. # while Bambuddy talks over wifi).
  202. other_le = _ip_to_uint32_le("192.168.99.42")
  203. vp_le = _ip_to_uint32_le(VP_IP)
  204. payload = json.dumps(
  205. {
  206. "print": {
  207. "command": "push_status",
  208. "net": {
  209. "info": [
  210. {"ip": h2d_le, "mask": 0xFFFFFF},
  211. {"ip": other_le, "mask": 0xFFFFFF},
  212. {"ip": 0, "mask": 0},
  213. ]
  214. },
  215. }
  216. }
  217. ).encode()
  218. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  219. await asyncio.sleep(0.01)
  220. cached = bridge.get_latest_print_state()
  221. assert cached["net"]["info"][0]["ip"] == vp_le
  222. assert cached["net"]["info"][1]["ip"] == vp_le # secondary interface also rewritten
  223. assert cached["net"]["info"][2]["ip"] == 0 # placeholder untouched
  224. await bridge.stop()
  225. @pytest.mark.asyncio
  226. async def test_late_arriving_printer_ip_rewrites_existing_cache(self):
  227. """Regression for #1429: if the printer's `ip_address` is empty at
  228. first bind (DB row stale, or the client object exists before the
  229. first SSDP refresh fills it in), the rewrite stays disabled and the
  230. first cached push poisons the cache with the real-printer IP.
  231. Once `ip_address` becomes valid, the next refresh tick must (a) arm
  232. the encoding and (b) sweep the cached `net.info[].ip` so the slicer
  233. sees the rewritten value on its next pull. Without the sweep the
  234. sticky-key preservation keeps the poisoned value alive across
  235. every subsequent incremental push."""
  236. server = _make_server(bind_address=VP_IP)
  237. # Bind to a client whose ip_address is empty at start — simulates the
  238. # late-arrival path.
  239. target = _make_paho_client(ip="")
  240. bridge = _make_bridge(server, target)
  241. await bridge.start()
  242. assert bridge._target_ip_uint32_le is None # not yet armed
  243. h2d_le = _ip_to_uint32_le(H2D_IP)
  244. vp_le = _ip_to_uint32_le(VP_IP)
  245. payload = json.dumps(
  246. {
  247. "print": {
  248. "command": "push_status",
  249. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  250. }
  251. }
  252. ).encode()
  253. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  254. await asyncio.sleep(0.01)
  255. # First push landed before encoding was armed → cache holds real IP.
  256. cached = bridge.get_latest_print_state()
  257. assert cached["net"]["info"][0]["ip"] == h2d_le
  258. # Printer's IP becomes known. Next refresh tick must self-heal.
  259. target.ip_address = H2D_IP
  260. bridge._resolve_client()
  261. cached = bridge.get_latest_print_state()
  262. assert cached["net"]["info"][0]["ip"] == vp_le, (
  263. "cache must be swept once encoding becomes valid; sticky-key "
  264. "preservation would otherwise keep the poisoned IP forever"
  265. )
  266. assert bridge._target_ip_uint32_le == h2d_le
  267. await bridge.stop()
  268. @pytest.mark.asyncio
  269. async def test_request_topic_message_is_ignored(self):
  270. server = _make_server()
  271. bridge = _make_bridge(server)
  272. await bridge.start()
  273. payload = json.dumps({"print": {"command": "push_status"}}).encode()
  274. bridge._on_printer_raw(f"device/{H2D_SERIAL}/request", payload)
  275. await asyncio.sleep(0.01)
  276. assert bridge.get_latest_print_state() is None
  277. await bridge.stop()
  278. @pytest.mark.asyncio
  279. async def test_incremental_push_preserves_ams_from_previous_cache(self):
  280. """Regression for #1371: Bambu firmware sends FULL push_status on
  281. pushall (with AMS/vt_tray/net/etc.) but typically OMITS those fields
  282. from 1 Hz incremental push_status updates. Without preserving the
  283. sticky keys across pushes, the cache forgets AMS info after the first
  284. incremental update, and BambuStudio (which reads the cache via the
  285. VP's 1 Hz status push) sees no AMS info until the user power-cycles
  286. the printer (forcing a fresh pushall).
  287. """
  288. server = _make_server()
  289. bridge = _make_bridge(server)
  290. await bridge.start()
  291. # 1. Initial pushall response with full state, AMS included.
  292. full_push = json.dumps(
  293. {
  294. "print": {
  295. "command": "push_status",
  296. "gcode_state": "IDLE",
  297. "wifi_signal": "-50dBm",
  298. "ams": {
  299. "ams": [
  300. {
  301. "id": "0",
  302. "tray": [
  303. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  304. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  305. ],
  306. }
  307. ],
  308. "tray_exist_bits": "3",
  309. },
  310. "vt_tray": {"id": "254", "tray_type": ""},
  311. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  312. }
  313. }
  314. ).encode()
  315. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", full_push)
  316. await asyncio.sleep(0.01)
  317. cached = bridge.get_latest_print_state()
  318. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  319. assert cached["vt_tray"]["id"] == "254"
  320. assert cached["lights_report"][0]["mode"] == "on"
  321. # 2. Incremental push with only temp/wifi changes — NO ams field.
  322. # This is what the printer sends every ~1 s between full pushalls.
  323. incremental_push = json.dumps(
  324. {
  325. "print": {
  326. "command": "push_status",
  327. "wifi_signal": "-55dBm",
  328. "chamber_temper": 26.0,
  329. }
  330. }
  331. ).encode()
  332. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", incremental_push)
  333. await asyncio.sleep(0.01)
  334. cached = bridge.get_latest_print_state()
  335. # New fields take effect.
  336. assert cached["wifi_signal"] == "-55dBm"
  337. assert cached["chamber_temper"] == 26.0
  338. # Sticky fields preserved from the previous cache (the #1371 fix).
  339. assert "ams" in cached, "AMS field must be preserved across incremental pushes (#1371)"
  340. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  341. assert cached["ams"]["tray_exist_bits"] == "3"
  342. assert cached["vt_tray"]["id"] == "254"
  343. assert cached["lights_report"][0]["mode"] == "on"
  344. await bridge.stop()
  345. @pytest.mark.asyncio
  346. async def test_incremental_push_preserves_non_allowlisted_capability_fields(self):
  347. """Regression for #1622: BambuStudio gates Device-tab UIs (manage
  348. calibration, AMS-slot filament dropdown, ...) on capability /
  349. lifecycle fields (cali_version, print_type, mc_print_stage,
  350. device, ...) it reads off the cached push_status. Before the fix
  351. these fields were not in the allowlist and drained out of the
  352. bridge cache on the first 1 Hz incremental tick, so the slicer's
  353. Device tab would grey out the gated UIs once the cache thinned.
  354. After the fix the cache accumulates everything the printer has
  355. ever sent, dropped only when explicitly overwritten.
  356. """
  357. server = _make_server()
  358. bridge = _make_bridge(server)
  359. await bridge.start()
  360. full_push = json.dumps(
  361. {
  362. "print": {
  363. "command": "push_status",
  364. "cali_version": 2,
  365. "print_type": "idle",
  366. "gcode_state": "IDLE",
  367. "mc_print_stage": "0",
  368. "mc_stage": 0,
  369. "device": {"ext_tool": {"info": []}},
  370. "cfg": "",
  371. "home_flag": 256,
  372. "wifi_signal": "-50dBm",
  373. }
  374. }
  375. ).encode()
  376. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", full_push)
  377. await asyncio.sleep(0.01)
  378. # Incremental push carrying only temps + wifi — none of the
  379. # capability/lifecycle fields above are mentioned.
  380. incremental_push = json.dumps(
  381. {
  382. "print": {
  383. "command": "push_status",
  384. "wifi_signal": "-55dBm",
  385. "nozzle_temper": 24.5,
  386. }
  387. }
  388. ).encode()
  389. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", incremental_push)
  390. await asyncio.sleep(0.01)
  391. cached = bridge.get_latest_print_state()
  392. # Incremental values applied.
  393. assert cached["wifi_signal"] == "-55dBm"
  394. assert cached["nozzle_temper"] == 24.5
  395. # Capability / lifecycle fields preserved from the prior pushall
  396. # — the symptoms in #1622 (Device-tab UIs disabled) trace to these
  397. # exact keys missing.
  398. assert cached["cali_version"] == 2
  399. assert cached["print_type"] == "idle"
  400. assert cached["gcode_state"] == "IDLE"
  401. assert cached["mc_print_stage"] == "0"
  402. assert cached["mc_stage"] == 0
  403. assert cached["device"] == {"ext_tool": {"info": []}}
  404. assert cached["cfg"] == ""
  405. assert cached["home_flag"] == 256
  406. await bridge.stop()
  407. @pytest.mark.asyncio
  408. async def test_partial_ams_status_update_preserves_unit_list(self):
  409. """#1387: Bambu firmware also sends `ams` updates where the key is
  410. present but the inner `ams` array is missing — e.g. just
  411. ``{ams_status: 1}`` or a humidity change. Before the deep-merge fix
  412. the bridge would overwrite the cached AMS with this stripped blob,
  413. the slicer would read it on the next 1 Hz push, and BambuStudio
  414. would drop the unit list and fall back to its "no AMS" render
  415. (only the external spool visible — the reporter's exact symptom).
  416. Now the partial update only mutates the fields it carries; the
  417. cached unit list survives.
  418. """
  419. server = _make_server()
  420. bridge = _make_bridge(server)
  421. await bridge.start()
  422. # 1. Pushall with full AMS state.
  423. bridge._on_printer_raw(
  424. f"device/{H2D_SERIAL}/report",
  425. json.dumps(
  426. {
  427. "print": {
  428. "command": "push_status",
  429. "ams": {
  430. "ams": [
  431. {
  432. "id": "0",
  433. "humidity": "1",
  434. "tray": [{"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"}],
  435. }
  436. ],
  437. "tray_exist_bits": "1",
  438. "ams_status": "0",
  439. },
  440. }
  441. }
  442. ).encode(),
  443. )
  444. await asyncio.sleep(0.01)
  445. # 2. Partial AMS update — only `ams_status` and `humidity` changed.
  446. # No `ams.ams` array, so prev's unit list must be preserved.
  447. bridge._on_printer_raw(
  448. f"device/{H2D_SERIAL}/report",
  449. json.dumps(
  450. {
  451. "print": {
  452. "command": "push_status",
  453. "ams": {"ams_status": "1", "humidity": "2"},
  454. }
  455. }
  456. ).encode(),
  457. )
  458. await asyncio.sleep(0.01)
  459. cached = bridge.get_latest_print_state()
  460. # Scalar fields take the new values.
  461. assert cached["ams"]["ams_status"] == "1"
  462. assert cached["ams"]["humidity"] == "2"
  463. # Unit + tray data preserved from the pushall.
  464. assert cached["ams"]["tray_exist_bits"] == "1"
  465. assert len(cached["ams"]["ams"]) == 1
  466. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  467. assert cached["ams"]["ams"][0]["tray"][0]["tray_color"] == "FF0000FF"
  468. await bridge.stop()
  469. @pytest.mark.asyncio
  470. async def test_partial_ams_unit_update_preserves_other_units(self):
  471. """#1387: when multiple AMS units are configured (e.g. H2D with two
  472. AMS), an incremental push during a print typically only carries the
  473. unit / tray that changed state. Naive replacement of `ams.ams` wipes
  474. the other unit. The bridge merges unit-by-unit by id, preserving
  475. units the incremental doesn't mention.
  476. """
  477. server = _make_server()
  478. bridge = _make_bridge(server)
  479. await bridge.start()
  480. # 1. Pushall with two AMS units configured.
  481. bridge._on_printer_raw(
  482. f"device/{H2D_SERIAL}/report",
  483. json.dumps(
  484. {
  485. "print": {
  486. "command": "push_status",
  487. "ams": {
  488. "ams": [
  489. {"id": "0", "tray": [{"id": "0", "tray_type": "PLA"}]},
  490. {"id": "1", "tray": [{"id": "0", "tray_type": "PETG"}]},
  491. ],
  492. "tray_exist_bits": "3",
  493. },
  494. }
  495. }
  496. ).encode(),
  497. )
  498. await asyncio.sleep(0.01)
  499. # 2. Tray-targeted incremental: unit 0 / tray 0 state changed.
  500. # Unit 1 is not in the update — must survive.
  501. bridge._on_printer_raw(
  502. f"device/{H2D_SERIAL}/report",
  503. json.dumps(
  504. {
  505. "print": {
  506. "command": "push_status",
  507. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "state": "11"}]}]},
  508. }
  509. }
  510. ).encode(),
  511. )
  512. await asyncio.sleep(0.01)
  513. cached = bridge.get_latest_print_state()
  514. units = {u["id"]: u for u in cached["ams"]["ams"]}
  515. # Unit 0 keeps its tray_type from the pushall + picks up the new state.
  516. assert units["0"]["tray"][0]["tray_type"] == "PLA"
  517. assert units["0"]["tray"][0]["state"] == "11"
  518. # Unit 1 survives the incremental.
  519. assert "1" in units
  520. assert units["1"]["tray"][0]["tray_type"] == "PETG"
  521. await bridge.stop()
  522. @pytest.mark.asyncio
  523. async def test_partial_ams_tray_update_preserves_other_trays(self):
  524. """Same shape as the unit-level test but at the tray level. AMS
  525. unit 0 has four trays; the incremental only mentions tray 0.
  526. Trays 1-3 must survive intact."""
  527. server = _make_server()
  528. bridge = _make_bridge(server)
  529. await bridge.start()
  530. bridge._on_printer_raw(
  531. f"device/{H2D_SERIAL}/report",
  532. json.dumps(
  533. {
  534. "print": {
  535. "command": "push_status",
  536. "ams": {
  537. "ams": [
  538. {
  539. "id": "0",
  540. "tray": [
  541. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  542. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  543. {"id": "2", "tray_type": "ABS", "tray_color": "0000FFFF"},
  544. {"id": "3", "tray_type": "TPU", "tray_color": "FFFF00FF"},
  545. ],
  546. }
  547. ],
  548. },
  549. }
  550. }
  551. ).encode(),
  552. )
  553. await asyncio.sleep(0.01)
  554. bridge._on_printer_raw(
  555. f"device/{H2D_SERIAL}/report",
  556. json.dumps(
  557. {
  558. "print": {
  559. "command": "push_status",
  560. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "state": "11"}]}]},
  561. }
  562. }
  563. ).encode(),
  564. )
  565. await asyncio.sleep(0.01)
  566. cached = bridge.get_latest_print_state()
  567. trays = {t["id"]: t for t in cached["ams"]["ams"][0]["tray"]}
  568. assert trays["0"]["tray_type"] == "PLA"
  569. assert trays["0"]["state"] == "11"
  570. # Trays not mentioned in the incremental survive intact.
  571. assert trays["1"]["tray_type"] == "PETG"
  572. assert trays["2"]["tray_type"] == "ABS"
  573. assert trays["3"]["tray_type"] == "TPU"
  574. await bridge.stop()
  575. @pytest.mark.asyncio
  576. async def test_incoming_ams_update_replaces_cached_ams(self):
  577. """Counterpart to the #1371 fix: preservation only kicks in when the
  578. incoming push OMITS a sticky key. When the printer DOES send a fresh
  579. `ams` value (e.g. on a pushall, or when AMS state genuinely changes),
  580. that value must take effect — the preservation must not shadow real
  581. updates.
  582. """
  583. server = _make_server()
  584. bridge = _make_bridge(server)
  585. await bridge.start()
  586. # 1. Initial state: PLA in tray 0.
  587. bridge._on_printer_raw(
  588. f"device/{H2D_SERIAL}/report",
  589. json.dumps(
  590. {
  591. "print": {
  592. "command": "push_status",
  593. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "tray_type": "PLA"}]}]},
  594. }
  595. }
  596. ).encode(),
  597. )
  598. await asyncio.sleep(0.01)
  599. # 2. Fresh push with PETG — must replace, not get shadowed by the old PLA.
  600. bridge._on_printer_raw(
  601. f"device/{H2D_SERIAL}/report",
  602. json.dumps(
  603. {
  604. "print": {
  605. "command": "push_status",
  606. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "tray_type": "PETG"}]}]},
  607. }
  608. }
  609. ).encode(),
  610. )
  611. await asyncio.sleep(0.01)
  612. cached = bridge.get_latest_print_state()
  613. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PETG"
  614. await bridge.stop()
  615. # ---------------------------------------------------------------------------
  616. # Caching: get_version response
  617. # ---------------------------------------------------------------------------
  618. class TestVersionCache:
  619. @pytest.mark.asyncio
  620. async def test_get_version_response_caches_modules(self):
  621. server = _make_server()
  622. bridge = _make_bridge(server)
  623. await bridge.start()
  624. payload = json.dumps(
  625. {
  626. "info": {
  627. "command": "get_version",
  628. "module": [
  629. {"name": "ota", "sn": H2D_SERIAL, "sw_ver": "01.03.00.00"},
  630. {"name": "n3f/0", "sn": "AMS_HW_1", "sw_ver": "04.00.21.87"},
  631. ],
  632. }
  633. }
  634. ).encode()
  635. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  636. await asyncio.sleep(0.01)
  637. modules = bridge.get_latest_version_modules()
  638. assert modules is not None
  639. assert len(modules) == 2
  640. # Device-level sn rewritten; AMS-hardware sn left alone.
  641. assert modules[0]["sn"] == VP_SERIAL
  642. assert modules[1]["sn"] == "AMS_HW_1"
  643. await bridge.stop()
  644. # ---------------------------------------------------------------------------
  645. # Selective fan-out (everything that's not push_status / get_version)
  646. # ---------------------------------------------------------------------------
  647. class TestCommandResponseFanout:
  648. @pytest.mark.asyncio
  649. async def test_extrusion_cali_get_response_is_fanned_out(self):
  650. """Slicer's extrusion_cali_get goes to the printer; the printer's response
  651. must reach the slicer or BambuStudio's pre-flight blocks Send."""
  652. server = _make_server()
  653. server.push_raw_to_clients = AsyncMock()
  654. bridge = _make_bridge(server)
  655. await bridge.start()
  656. body = json.dumps({"print": {"command": "extrusion_cali_get", "filaments": []}}).encode()
  657. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", body)
  658. await asyncio.sleep(0.01)
  659. server.push_raw_to_clients.assert_awaited_once()
  660. topic, _payload = server.push_raw_to_clients.await_args.args
  661. assert topic == f"device/{VP_SERIAL}/report"
  662. await bridge.stop()
  663. # ---------------------------------------------------------------------------
  664. # Forwarding: slicer → printer
  665. # ---------------------------------------------------------------------------
  666. class TestForwardToPrinter:
  667. @pytest.mark.asyncio
  668. async def test_forward_publishes_to_real_serial_request_topic(self):
  669. target = _make_paho_client()
  670. bridge = _make_bridge(_make_server(), target)
  671. await bridge.start()
  672. ok = bridge.forward_to_printer({"print": {"command": "stop"}})
  673. assert ok is True
  674. target.publish_raw.assert_called_once()
  675. topic, payload = target.publish_raw.call_args.args
  676. assert topic == f"device/{H2D_SERIAL}/request"
  677. assert json.loads(payload) == {"print": {"command": "stop"}}
  678. await bridge.stop()
  679. @pytest.mark.asyncio
  680. async def test_forward_returns_false_when_not_bound(self):
  681. pm = MagicMock()
  682. pm.get_client = MagicMock(return_value=None)
  683. bridge = MQTTBridge(
  684. vp_id=1,
  685. vp_name="vp1",
  686. vp_serial=VP_SERIAL,
  687. target_printer_id=42,
  688. mqtt_server=_make_server(),
  689. printer_manager=pm,
  690. )
  691. await bridge.start()
  692. assert bridge.forward_to_printer({"print": {"command": "stop"}}) is False
  693. await bridge.stop()
  694. # ---------------------------------------------------------------------------
  695. # SimpleMQTTServer status response: cached-as-base
  696. # ---------------------------------------------------------------------------
  697. class TestStatusReportCachedAsBase:
  698. """`_send_status_report` sends near-byte-identical real data when bridge cache exists."""
  699. def _capture_published(self, server: SimpleMQTTServer):
  700. """Wrap _publish_to_report to capture (topic, payload_dict)."""
  701. published: list = []
  702. async def _capture(writer, payload, serial="", log_event=True):
  703. published.append((serial or server.serial, payload))
  704. server._publish_to_report = _capture # type: ignore[assignment]
  705. return published
  706. @pytest.mark.asyncio
  707. async def test_uses_real_cache_when_bridge_active(self):
  708. server = _make_server()
  709. bridge = MagicMock()
  710. bridge.get_latest_print_state.return_value = {
  711. "command": "push_status",
  712. "msg": 0,
  713. "ams": {"ams": [{"id": "0"}]},
  714. "device": {"extruder": {"info": [{"id": 0}, {"id": 1}]}},
  715. "nozzle_diameter": "0.4",
  716. "nozzle_type": "HH01", # real H2D value, not synthetic 'hardened_steel'
  717. }
  718. server.set_bridge(bridge)
  719. published = self._capture_published(server)
  720. await server._send_status_report(MagicMock())
  721. assert len(published) == 1
  722. _serial, payload = published[0]
  723. # AMS / device / nozzle_type all from cache
  724. assert payload["print"]["nozzle_type"] == "HH01"
  725. assert payload["print"]["device"]["extruder"]["info"][1]["id"] == 1
  726. # Protocol fields under our control
  727. assert payload["print"]["command"] == "push_status"
  728. assert payload["print"]["gcode_state"] == "IDLE"
  729. @pytest.mark.asyncio
  730. async def test_falls_back_to_synthetic_when_no_cache(self):
  731. server = _make_server()
  732. bridge = MagicMock()
  733. bridge.get_latest_print_state.return_value = None
  734. server.set_bridge(bridge)
  735. published = self._capture_published(server)
  736. await server._send_status_report(MagicMock())
  737. assert len(published) == 1
  738. _serial, payload = published[0]
  739. # Synthetic baseline has stub fields like nozzle_type='hardened_steel'
  740. # and a `storage` field that the real H2D doesn't push.
  741. assert payload["print"]["nozzle_type"] == "hardened_steel"
  742. assert "storage" in payload["print"]
  743. @pytest.mark.asyncio
  744. async def test_storage_indicators_overlaid_for_send_preflight(self):
  745. """#1228: P1S/A1-class firmware doesn't always include the SD/storage
  746. fields BambuStudio's "Send" pre-flight reads. Without these the
  747. slicer rejects with 'storage needs to be inserted' before even
  748. attempting FTP. The cached-as-base path now overlays them so the
  749. pre-flight passes regardless of what the real printer reports.
  750. """
  751. server = _make_server()
  752. bridge = MagicMock()
  753. # Real P1S push without SD card inserted: home_flag has other bits set
  754. # but the SD bit (0x100) is clear; sdcard is False; no storage field.
  755. bridge.get_latest_print_state.return_value = {
  756. "command": "push_status",
  757. "msg": 0,
  758. "home_flag": 0x42,
  759. "sdcard": False,
  760. }
  761. server.set_bridge(bridge)
  762. published = self._capture_published(server)
  763. await server._send_status_report(MagicMock())
  764. _serial, payload = published[0]
  765. # SD bit ORed onto whatever was there — other bits preserved.
  766. assert payload["print"]["home_flag"] & 0x100 == 0x100
  767. assert payload["print"]["home_flag"] & 0x42 == 0x42
  768. # Force-set so a False from the printer doesn't trip the pre-flight.
  769. assert payload["print"]["sdcard"] is True
  770. # storage was missing — the overlay must inject a non-empty default.
  771. assert "storage" in payload["print"]
  772. assert payload["print"]["storage"]["free"] > 0
  773. assert payload["print"]["storage"]["total"] > 0
  774. @pytest.mark.asyncio
  775. async def test_storage_indicators_preserve_real_storage_when_present(self):
  776. """When the real printer DOES report a storage block, pass it through
  777. unchanged (the overlay only fills in the missing field, not overrides).
  778. """
  779. server = _make_server()
  780. bridge = MagicMock()
  781. real_storage = {"free": 12345, "total": 67890}
  782. bridge.get_latest_print_state.return_value = {
  783. "command": "push_status",
  784. "msg": 0,
  785. "home_flag": 0x100, # SD bit already set on the real printer
  786. "sdcard": True,
  787. "storage": real_storage,
  788. }
  789. server.set_bridge(bridge)
  790. published = self._capture_published(server)
  791. await server._send_status_report(MagicMock())
  792. _serial, payload = published[0]
  793. # SD bit OR is idempotent — already-set bit stays set.
  794. assert payload["print"]["home_flag"] == 0x100
  795. assert payload["print"]["sdcard"] is True
  796. # Real values pass through, NOT the synthetic defaults.
  797. assert payload["print"]["storage"] == real_storage
  798. @pytest.mark.asyncio
  799. async def test_overrides_protocol_fields_even_when_cache_present(self):
  800. """Cached value's gcode_state must NOT win over our local upload-state-machine value."""
  801. server = _make_server()
  802. server._gcode_state = "PREPARE"
  803. server._current_file = "foo.3mf"
  804. bridge = MagicMock()
  805. bridge.get_latest_print_state.return_value = {
  806. "command": "push_status",
  807. "gcode_state": "IDLE", # printer is idle; we are mid-FTP-upload
  808. "gcode_file": "",
  809. "gcode_file_prepare_percent": "0",
  810. }
  811. server.set_bridge(bridge)
  812. published = self._capture_published(server)
  813. await server._send_status_report(MagicMock())
  814. _serial, payload = published[0]
  815. assert payload["print"]["gcode_state"] == "PREPARE"
  816. assert payload["print"]["gcode_file"] == "foo.3mf"
  817. @pytest.mark.asyncio
  818. async def test_live_progress_fields_zeroed_in_cached_branch(self):
  819. """#1558: when the real target printer is mid-print, the cached
  820. push_status carries live values for mc_percent / stg_cur / layer_num /
  821. etc. BambuStudio's Send pre-flight reads any of these as "VP busy"
  822. even when gcode_state above is forced to IDLE — blocking Send while
  823. the target prints. The cached branch must override these to the same
  824. idle values the synthetic stub uses.
  825. """
  826. server = _make_server()
  827. bridge = MagicMock()
  828. # Real printer mid-print state: gcode_state may be RUNNING upstream,
  829. # but the VP's own _gcode_state is IDLE (Send is requesting a
  830. # new upload, the VP isn't running anything).
  831. bridge.get_latest_print_state.return_value = {
  832. "command": "push_status",
  833. "msg": 0,
  834. "gcode_state": "RUNNING",
  835. "mc_print_stage": "2",
  836. "mc_percent": 47,
  837. "mc_remaining_time": 3600,
  838. "stg": [1, 2, 3],
  839. "stg_cur": 14,
  840. "layer_num": 120,
  841. "total_layer_num": 250,
  842. "print_error": 0,
  843. }
  844. server.set_bridge(bridge)
  845. published = self._capture_published(server)
  846. await server._send_status_report(MagicMock())
  847. _serial, payload = published[0]
  848. # Every live-progress field must reflect "idle / VP isn't busy".
  849. assert payload["print"]["mc_print_stage"] == ""
  850. assert payload["print"]["mc_percent"] == 0
  851. assert payload["print"]["mc_remaining_time"] == 0
  852. assert payload["print"]["stg"] == []
  853. assert payload["print"]["stg_cur"] == 0
  854. assert payload["print"]["layer_num"] == 0
  855. assert payload["print"]["total_layer_num"] == 0
  856. assert payload["print"]["print_error"] == 0
  857. # ---------------------------------------------------------------------------
  858. # Wire format
  859. # ---------------------------------------------------------------------------
  860. class TestWireFormat:
  861. """BambuStudio's Send pre-flight rejects compact JSON — must match real printer's
  862. indented format (32K bytes for an idle H2D vs 14K compact)."""
  863. @pytest.mark.asyncio
  864. async def test_publish_uses_indent_4_json_format(self):
  865. server = _make_server()
  866. captured: list = []
  867. async def _capture_drain():
  868. pass
  869. writer = MagicMock()
  870. writer.write = lambda data: captured.append(data)
  871. writer.drain = AsyncMock()
  872. await server._publish_to_report(writer, {"print": {"command": "push_status", "ams": {}}})
  873. body = b"".join(captured)
  874. assert b'\n "print"' in body, "publish_to_report must use indent=4 JSON"
  875. @pytest.mark.asyncio
  876. async def test_publish_records_bridge_to_slicer_event_by_default(self, monkeypatch):
  877. """#1622 round 3: every bridge-synthesised reply (info.get_version answer,
  878. project_file ack, on-demand pushall response) must show up in the
  879. cmd.jsonl trace under the ``bridge_to_slicer`` direction so a P1S↔H2D
  880. diff captures the fingerprint the slicer reads back from us."""
  881. server = _make_server()
  882. writer = MagicMock()
  883. writer.write = lambda data: None
  884. writer.drain = AsyncMock()
  885. recorded: list = []
  886. monkeypatch.setattr(
  887. "backend.app.services.virtual_printer.mqtt_server.append_event",
  888. lambda vp_name, direction, topic, payload: recorded.append((vp_name, direction, topic, payload)),
  889. )
  890. payload = {"info": {"command": "get_version", "sequence_id": "0"}}
  891. await server._publish_to_report(writer, payload)
  892. assert len(recorded) == 1
  893. vp_name, direction, topic, recorded_payload = recorded[0]
  894. assert direction == "bridge_to_slicer"
  895. assert topic.endswith("/report")
  896. assert recorded_payload == payload
  897. @pytest.mark.asyncio
  898. async def test_publish_skips_event_when_log_event_false(self, monkeypatch):
  899. """The 1Hz periodic-push path passes ``log_event=False`` so dump_wire's
  900. snapshot stays the canonical record of cache shape and the cmd.jsonl
  901. isn't flooded with ~60 lines/min per VP."""
  902. server = _make_server()
  903. writer = MagicMock()
  904. writer.write = lambda data: None
  905. writer.drain = AsyncMock()
  906. recorded: list = []
  907. monkeypatch.setattr(
  908. "backend.app.services.virtual_printer.mqtt_server.append_event",
  909. lambda *args, **kwargs: recorded.append(args),
  910. )
  911. await server._publish_to_report(writer, {"print": {"command": "push_status"}}, log_event=False)
  912. assert recorded == []
  913. # ---------------------------------------------------------------------------
  914. # Routing: _handle_publish
  915. # ---------------------------------------------------------------------------
  916. class TestPublishRouting:
  917. """Slicer-issued commands: project_file/gcode_file handled locally, everything
  918. else forwarded to the real printer."""
  919. def _build_publish_payload(self, topic: str, body: bytes) -> bytes:
  920. topic_bytes = topic.encode("utf-8")
  921. return bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF]) + topic_bytes + body
  922. def _attach_active_bridge(self, server: SimpleMQTTServer) -> MagicMock:
  923. bridge = MagicMock()
  924. bridge.is_active = True
  925. bridge.forward_to_printer = MagicMock(return_value=True)
  926. server.set_bridge(bridge)
  927. return bridge
  928. @pytest.mark.asyncio
  929. async def test_project_file_handled_locally_not_forwarded(self):
  930. server = _make_server()
  931. bridge = self._attach_active_bridge(server)
  932. writer = MagicMock()
  933. writer.write = MagicMock()
  934. writer.drain = AsyncMock()
  935. body = json.dumps({"print": {"command": "project_file", "subtask_name": "f", "sequence_id": "1"}}).encode()
  936. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  937. with patch.object(server, "_send_print_response", new=AsyncMock()) as mock_resp:
  938. await server._handle_publish(0x30, payload, writer, "client1")
  939. bridge.forward_to_printer.assert_not_called()
  940. mock_resp.assert_awaited_once()
  941. @pytest.mark.asyncio
  942. async def test_gcode_file_handled_locally_not_forwarded(self):
  943. server = _make_server()
  944. bridge = self._attach_active_bridge(server)
  945. writer = MagicMock()
  946. writer.write = MagicMock()
  947. writer.drain = AsyncMock()
  948. body = json.dumps({"print": {"command": "gcode_file", "subtask_name": "f.gcode", "sequence_id": "1"}}).encode()
  949. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  950. with patch.object(server, "_send_print_response", new=AsyncMock()):
  951. await server._handle_publish(0x30, payload, writer, "client1")
  952. bridge.forward_to_printer.assert_not_called()
  953. @pytest.mark.asyncio
  954. async def test_pushall_handled_locally_not_forwarded(self):
  955. server = _make_server()
  956. bridge = self._attach_active_bridge(server)
  957. writer = MagicMock()
  958. writer.write = MagicMock()
  959. writer.drain = AsyncMock()
  960. body = json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}).encode()
  961. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  962. with patch.object(server, "_send_status_report", new=AsyncMock()) as mock_status:
  963. await server._handle_publish(0x30, payload, writer, "client1")
  964. # Synthetic answer fires (fast, low latency); no forwarding (the
  965. # cache already mirrors what the printer would respond with).
  966. bridge.forward_to_printer.assert_not_called()
  967. mock_status.assert_awaited_once()
  968. @pytest.mark.asyncio
  969. async def test_get_version_handled_locally_not_forwarded(self):
  970. server = _make_server()
  971. bridge = self._attach_active_bridge(server)
  972. writer = MagicMock()
  973. writer.write = MagicMock()
  974. writer.drain = AsyncMock()
  975. body = json.dumps({"info": {"command": "get_version", "sequence_id": "1"}}).encode()
  976. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  977. with patch.object(server, "_send_version_response", new=AsyncMock()) as mock_ver:
  978. await server._handle_publish(0x30, payload, writer, "client1")
  979. bridge.forward_to_printer.assert_not_called()
  980. mock_ver.assert_awaited_once()
  981. @pytest.mark.asyncio
  982. async def test_extrusion_cali_get_is_forwarded(self):
  983. """extrusion_cali_get fetches per-filament k-profiles — must reach the printer."""
  984. server = _make_server()
  985. bridge = self._attach_active_bridge(server)
  986. writer = MagicMock()
  987. writer.write = MagicMock()
  988. writer.drain = AsyncMock()
  989. body = json.dumps(
  990. {
  991. "print": {
  992. "command": "extrusion_cali_get",
  993. "filament_id": "",
  994. "nozzle_diameter": "0.4",
  995. "sequence_id": "5",
  996. }
  997. }
  998. ).encode()
  999. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1000. await server._handle_publish(0x30, payload, writer, "client1")
  1001. bridge.forward_to_printer.assert_called_once()
  1002. forwarded = bridge.forward_to_printer.call_args.args[0]
  1003. assert forwarded["print"]["command"] == "extrusion_cali_get"
  1004. @pytest.mark.asyncio
  1005. async def test_print_stop_is_forwarded(self):
  1006. server = _make_server()
  1007. bridge = self._attach_active_bridge(server)
  1008. writer = MagicMock()
  1009. writer.write = MagicMock()
  1010. writer.drain = AsyncMock()
  1011. body = json.dumps({"print": {"command": "stop", "sequence_id": "5"}}).encode()
  1012. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1013. await server._handle_publish(0x30, payload, writer, "client1")
  1014. bridge.forward_to_printer.assert_called_once()
  1015. # ---------------------------------------------------------------------------
  1016. # IP encoding helper
  1017. # ---------------------------------------------------------------------------
  1018. class TestIpEncoding:
  1019. def test_le_uint32_matches_real_h2d_capture(self):
  1020. # 192.168.255.133 captured from real H2D's net.info[0].ip = 2248124608
  1021. assert _ip_to_uint32_le("192.168.255.133") == 2248124608
  1022. def test_vp_ip_round_trip(self):
  1023. assert _ip_to_uint32_le("192.168.255.16") == 285190336
  1024. def test_invalid_ip_raises(self):
  1025. with pytest.raises(ValueError):
  1026. _ip_to_uint32_le("not.an.ip.actually")
  1027. class TestHostnameResolution:
  1028. """#1429 follow-up: users who configured the printer by FQDN (common on
  1029. LANs with router-provided DNS like `p1s.fritz.box`) hit `invalid IPv4`
  1030. on the encoder and the rewrite never armed — slicer kept FTPing direct
  1031. to the real printer. The bridge now resolves hostname→IPv4 first."""
  1032. def test_pass_through_for_valid_ipv4(self):
  1033. assert _resolve_target_to_ipv4("192.168.1.50") == "192.168.1.50"
  1034. def test_empty_returns_none(self):
  1035. assert _resolve_target_to_ipv4("") is None
  1036. assert _resolve_target_to_ipv4(None) is None # type: ignore[arg-type]
  1037. def test_hostname_resolves_via_getaddrinfo(self):
  1038. with patch(
  1039. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1040. return_value=[(2, 1, 6, "", ("192.168.3.153", 0))],
  1041. ) as mock_gai:
  1042. assert _resolve_target_to_ipv4("p1s.fritz.box") == "192.168.3.153"
  1043. # AF_INET filter prevents an IPv6-only result from being picked,
  1044. # since net.info[*].ip is a uint32 LE that can't carry v6.
  1045. assert mock_gai.call_args.kwargs.get("family") == socket.AF_INET
  1046. def test_dns_failure_returns_none(self):
  1047. with patch(
  1048. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1049. side_effect=OSError("Name or service not known"),
  1050. ):
  1051. assert _resolve_target_to_ipv4("nope.invalid") is None
  1052. def test_fqdn_target_arms_encoding(self, caplog):
  1053. """End-to-end: a client whose `ip_address` is an FQDN should arm
  1054. the bridge once DNS resolves, and the cached rewrite uses the
  1055. resolved IPv4 (not the hostname string) for the `net.info[].ip`
  1056. encoding."""
  1057. server = _make_server(bind_address=VP_IP)
  1058. bridge = _make_bridge(server)
  1059. client = _make_paho_client(ip="p1s.fritz.box")
  1060. bridge._target_client = client
  1061. with (
  1062. patch(
  1063. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1064. return_value=[(2, 1, 6, "", (H2D_IP, 0))],
  1065. ),
  1066. caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"),
  1067. ):
  1068. bridge._refresh_ip_encoding()
  1069. assert bridge._target_ip_uint32_le == _ip_to_uint32_le(H2D_IP)
  1070. assert bridge._vp_ip_uint32_le == _ip_to_uint32_le(VP_IP)
  1071. armed = [r for r in caplog.records if "MQTT bridge IP encoding armed" in r.getMessage()]
  1072. assert len(armed) == 1
  1073. # Operator should see configured→resolved in the log line so a
  1074. # bad-DNS regression is immediately legible.
  1075. assert "p1s.fritz.box→192.168.255.133" in armed[0].getMessage()
  1076. # ---------------------------------------------------------------------------
  1077. # Auto-resolve fallback for default-config (bind_address = "0.0.0.0")
  1078. # ---------------------------------------------------------------------------
  1079. class TestBindAddressAutoResolve:
  1080. """#1429 residual: VPs created without a dedicated bind IP run on
  1081. `bind_address=0.0.0.0`. The original fix's `_refresh_ip_encoding`
  1082. early-returned on 0.0.0.0, so the rewrite never armed and `net.info[].ip`
  1083. kept leaking the real printer IP. Now the bridge auto-resolves a host
  1084. interface in the printer's subnet and uses that as the VP IP."""
  1085. @pytest.mark.asyncio
  1086. async def test_rewrite_arms_via_auto_resolved_host_ip(self):
  1087. """When bind_address is 0.0.0.0, fall back to the host interface in
  1088. the target printer's subnet and rewrite to that IP."""
  1089. server = _make_server(bind_address="0.0.0.0")
  1090. bridge = _make_bridge(server)
  1091. with patch(
  1092. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1093. return_value=VP_IP,
  1094. ):
  1095. await bridge.start()
  1096. h2d_le = _ip_to_uint32_le(H2D_IP)
  1097. vp_le = _ip_to_uint32_le(VP_IP)
  1098. payload = json.dumps(
  1099. {
  1100. "print": {
  1101. "command": "push_status",
  1102. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  1103. }
  1104. }
  1105. ).encode()
  1106. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  1107. await asyncio.sleep(0.01)
  1108. cached = bridge.get_latest_print_state()
  1109. assert cached["net"]["info"][0]["ip"] == vp_le
  1110. assert bridge._vp_ip_uint32_le == vp_le
  1111. await bridge.stop()
  1112. @pytest.mark.asyncio
  1113. async def test_rewrite_disabled_when_no_matching_host_interface(self):
  1114. """If no host interface shares a subnet with the printer, the bridge
  1115. cannot pick a sensible VP IP — leave encoding unarmed and let the
  1116. push through unrewritten (no crash, no wrong rewrite)."""
  1117. server = _make_server(bind_address="")
  1118. bridge = _make_bridge(server)
  1119. with patch(
  1120. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1121. return_value=None,
  1122. ):
  1123. await bridge.start()
  1124. h2d_le = _ip_to_uint32_le(H2D_IP)
  1125. payload = json.dumps(
  1126. {
  1127. "print": {
  1128. "command": "push_status",
  1129. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  1130. }
  1131. }
  1132. ).encode()
  1133. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  1134. await asyncio.sleep(0.01)
  1135. assert bridge._vp_ip_uint32_le is None
  1136. assert bridge._target_ip_uint32_le is None
  1137. await bridge.stop()
  1138. @pytest.mark.asyncio
  1139. async def test_explicit_bind_ip_takes_precedence_over_auto_resolve(self):
  1140. """Auto-resolve only kicks in when bind_address is empty/0.0.0.0; an
  1141. explicitly-set bind IP must be used verbatim even if there's also a
  1142. same-subnet host interface."""
  1143. server = _make_server(bind_address=VP_IP)
  1144. bridge = _make_bridge(server)
  1145. # Auto-resolver would have returned a DIFFERENT IP — we must not use it.
  1146. with patch(
  1147. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1148. return_value="10.99.99.99",
  1149. ):
  1150. await bridge.start()
  1151. assert bridge._vp_ip_uint32_le == _ip_to_uint32_le(VP_IP)
  1152. await bridge.stop()
  1153. def test_resolve_helper_returns_none_for_unreachable_target(self):
  1154. """The helper itself must be defensive — if `find_interface_for_ip`
  1155. raises or returns None, we get None (no crash)."""
  1156. with patch(
  1157. "backend.app.services.network_utils.find_interface_for_ip",
  1158. return_value=None,
  1159. ):
  1160. assert _resolve_host_interface_for_target("203.0.113.1") is None
  1161. class TestNotArmedDiagnosticLogging:
  1162. """#1429 follow-up: every silent early-return in `_refresh_ip_encoding`
  1163. now emits one INFO line explaining WHY the rewrite couldn't arm. Throttled
  1164. to one line per state change so an idle unarmed bridge doesn't spam the
  1165. log every 30s tick. Cleared on arm so a future failure re-emits.
  1166. """
  1167. def test_no_client_logs_once(self, caplog):
  1168. bridge = _make_bridge(_make_server())
  1169. # Force the "no client" path: bridge starts with _target_client=None.
  1170. assert bridge._target_client is None
  1171. with caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"):
  1172. bridge._refresh_ip_encoding()
  1173. bridge._refresh_ip_encoding() # 2nd tick — same reason, must NOT re-log.
  1174. bridge._refresh_ip_encoding()
  1175. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1176. assert len(not_armed) == 1
  1177. assert "target_client is None" in not_armed[0].getMessage()
  1178. def test_missing_target_ip_logs_specific_reason(self, caplog):
  1179. bridge = _make_bridge(_make_server())
  1180. # Manually attach a client with no ip_address (simulates pre-DHCP).
  1181. client = _make_paho_client()
  1182. client.ip_address = ""
  1183. bridge._target_client = client
  1184. with caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"):
  1185. bridge._refresh_ip_encoding()
  1186. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1187. assert len(not_armed) == 1
  1188. assert "no ip_address" in not_armed[0].getMessage()
  1189. def test_no_matching_host_interface_logs_specific_reason(self, caplog):
  1190. server = _make_server(bind_address="0.0.0.0")
  1191. bridge = _make_bridge(server)
  1192. with (
  1193. patch(
  1194. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1195. return_value=None,
  1196. ),
  1197. caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"),
  1198. ):
  1199. bridge._target_client = _make_paho_client()
  1200. bridge._refresh_ip_encoding()
  1201. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1202. assert len(not_armed) == 1
  1203. msg = not_armed[0].getMessage()
  1204. assert H2D_IP in msg
  1205. assert "no host interface" in msg
  1206. def test_unresolvable_target_logs_reason(self, caplog):
  1207. """When `ip_address` isn't a valid IPv4 *and* doesn't resolve via DNS,
  1208. the bridge must report a single concrete not-armed reason naming the
  1209. configured value — operator can then see exactly what input failed."""
  1210. server = _make_server(bind_address=VP_IP)
  1211. bridge = _make_bridge(server)
  1212. client = _make_paho_client()
  1213. client.ip_address = "not.an.ip"
  1214. bridge._target_client = client
  1215. with (
  1216. patch(
  1217. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1218. side_effect=OSError("nodename nor servname provided"),
  1219. ),
  1220. caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"),
  1221. ):
  1222. bridge._refresh_ip_encoding()
  1223. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1224. assert len(not_armed) == 1
  1225. assert "could not resolve printer host 'not.an.ip'" in not_armed[0].getMessage()
  1226. def test_successful_arm_clears_dedup_so_future_failure_relogs(self, caplog):
  1227. """After a successful arm, the dedup must reset so a subsequent
  1228. regression (e.g. printer client unbinds) re-emits the diagnostic
  1229. line instead of being silenced by the previous failure reason."""
  1230. bridge = _make_bridge(_make_server(bind_address=VP_IP))
  1231. bridge._target_client = _make_paho_client()
  1232. with caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"):
  1233. bridge._refresh_ip_encoding() # arms
  1234. assert bridge._not_armed_reason is None
  1235. # Simulate a regression — target_client drops away.
  1236. bridge._target_client = None
  1237. bridge._refresh_ip_encoding()
  1238. bridge._refresh_ip_encoding() # 2nd same-reason tick must not re-log
  1239. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1240. assert len(not_armed) == 1 # the post-arm failure
  1241. armed = [r for r in caplog.records if "MQTT bridge IP encoding armed" in r.getMessage()]
  1242. assert len(armed) == 1