test_vp_mqtt_bridge.py 50 KB

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