test_vp_mqtt_bridge.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  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. @pytest.mark.asyncio
  129. async def test_post_bind_nudge_skipped_when_target_not_connected(self):
  130. """#1721: the bridge can attach before the real printer's MQTT TLS
  131. handshake completes. Calling request_status_update on a disconnected
  132. client logs WARNING (bambu_mqtt.py:3224); on A1 firmware that
  133. reconnects aggressively, every bind cycle pollutes the support bundle
  134. with a benign line. The bridge must check state.connected before
  135. nudging — the next periodic pushall picks up the cache anyway.
  136. """
  137. target = _make_paho_client(connected=False)
  138. bridge = _make_bridge(_make_server(), target)
  139. await bridge.start()
  140. target._request_version.assert_not_called()
  141. target.request_status_update.assert_not_called()
  142. await bridge.stop()
  143. # ---------------------------------------------------------------------------
  144. # Caching: push_status
  145. # ---------------------------------------------------------------------------
  146. class TestPushStatusCache:
  147. """push_status snapshots feed `_send_status_report` via the cache, not a fan-out."""
  148. @pytest.mark.asyncio
  149. async def test_push_status_is_cached_not_fanned_out(self):
  150. server = _make_server()
  151. server.push_raw_to_clients = AsyncMock()
  152. bridge = _make_bridge(server)
  153. await bridge.start()
  154. payload = json.dumps({"print": {"command": "push_status", "ams": {"ams": []}, "gcode_state": "IDLE"}}).encode()
  155. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  156. await asyncio.sleep(0.01)
  157. server.push_raw_to_clients.assert_not_awaited()
  158. cached = bridge.get_latest_print_state()
  159. assert cached is not None
  160. assert cached["command"] == "push_status"
  161. assert cached["gcode_state"] == "IDLE"
  162. await bridge.stop()
  163. @pytest.mark.asyncio
  164. async def test_serial_rewritten_in_cached_push(self):
  165. server = _make_server()
  166. bridge = _make_bridge(server)
  167. await bridge.start()
  168. payload = json.dumps(
  169. {
  170. "print": {
  171. "command": "push_status",
  172. "upgrade_state": {"sn": H2D_SERIAL, "status": "IDLE"},
  173. }
  174. }
  175. ).encode()
  176. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  177. await asyncio.sleep(0.01)
  178. cached = bridge.get_latest_print_state()
  179. assert cached["upgrade_state"]["sn"] == VP_SERIAL
  180. await bridge.stop()
  181. @pytest.mark.asyncio
  182. async def test_net_info_ip_rewritten_to_vp_ip(self):
  183. """BambuStudio reads `net.info[].ip` (LE uint32) for the FTP destination —
  184. must be rewritten to the VP's bind IP or the slicer bypasses the VP."""
  185. server = _make_server(bind_address=VP_IP)
  186. bridge = _make_bridge(server)
  187. await bridge.start()
  188. h2d_le = _ip_to_uint32_le(H2D_IP)
  189. vp_le = _ip_to_uint32_le(VP_IP)
  190. payload = json.dumps(
  191. {
  192. "print": {
  193. "command": "push_status",
  194. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}, {"ip": 0, "mask": 0}]},
  195. }
  196. }
  197. ).encode()
  198. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  199. await asyncio.sleep(0.01)
  200. cached = bridge.get_latest_print_state()
  201. assert cached["net"]["info"][0]["ip"] == vp_le
  202. assert cached["net"]["info"][1]["ip"] == 0 # untouched
  203. await bridge.stop()
  204. @pytest.mark.asyncio
  205. async def test_net_info_ip_rewritten_for_unknown_secondary_interface(self):
  206. """Regression for #1429: real printers (X1C / H2D Pro) report multiple
  207. active interfaces (WiFi + Ethernet) — only ONE matches the IP Bambuddy
  208. tracks. The rewrite must catch every non-zero entry, not just the one
  209. whose IP equals `_target_ip_uint32_le`, or the slicer's FTP fallback
  210. path leaks straight to the real printer."""
  211. server = _make_server(bind_address=VP_IP)
  212. bridge = _make_bridge(server)
  213. await bridge.start()
  214. h2d_le = _ip_to_uint32_le(H2D_IP)
  215. # A second IP Bambuddy never saw (e.g. printer's ethernet interface
  216. # while Bambuddy talks over wifi).
  217. other_le = _ip_to_uint32_le("192.168.99.42")
  218. vp_le = _ip_to_uint32_le(VP_IP)
  219. payload = json.dumps(
  220. {
  221. "print": {
  222. "command": "push_status",
  223. "net": {
  224. "info": [
  225. {"ip": h2d_le, "mask": 0xFFFFFF},
  226. {"ip": other_le, "mask": 0xFFFFFF},
  227. {"ip": 0, "mask": 0},
  228. ]
  229. },
  230. }
  231. }
  232. ).encode()
  233. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  234. await asyncio.sleep(0.01)
  235. cached = bridge.get_latest_print_state()
  236. assert cached["net"]["info"][0]["ip"] == vp_le
  237. assert cached["net"]["info"][1]["ip"] == vp_le # secondary interface also rewritten
  238. assert cached["net"]["info"][2]["ip"] == 0 # placeholder untouched
  239. await bridge.stop()
  240. @pytest.mark.asyncio
  241. async def test_late_arriving_printer_ip_rewrites_existing_cache(self):
  242. """Regression for #1429: if the printer's `ip_address` is empty at
  243. first bind (DB row stale, or the client object exists before the
  244. first SSDP refresh fills it in), the rewrite stays disabled and the
  245. first cached push poisons the cache with the real-printer IP.
  246. Once `ip_address` becomes valid, the next refresh tick must (a) arm
  247. the encoding and (b) sweep the cached `net.info[].ip` so the slicer
  248. sees the rewritten value on its next pull. Without the sweep the
  249. sticky-key preservation keeps the poisoned value alive across
  250. every subsequent incremental push."""
  251. server = _make_server(bind_address=VP_IP)
  252. # Bind to a client whose ip_address is empty at start — simulates the
  253. # late-arrival path.
  254. target = _make_paho_client(ip="")
  255. bridge = _make_bridge(server, target)
  256. await bridge.start()
  257. assert bridge._target_ip_uint32_le is None # not yet armed
  258. h2d_le = _ip_to_uint32_le(H2D_IP)
  259. vp_le = _ip_to_uint32_le(VP_IP)
  260. payload = json.dumps(
  261. {
  262. "print": {
  263. "command": "push_status",
  264. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  265. }
  266. }
  267. ).encode()
  268. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  269. await asyncio.sleep(0.01)
  270. # First push landed before encoding was armed → cache holds real IP.
  271. cached = bridge.get_latest_print_state()
  272. assert cached["net"]["info"][0]["ip"] == h2d_le
  273. # Printer's IP becomes known. Next refresh tick must self-heal.
  274. target.ip_address = H2D_IP
  275. bridge._resolve_client()
  276. cached = bridge.get_latest_print_state()
  277. assert cached["net"]["info"][0]["ip"] == vp_le, (
  278. "cache must be swept once encoding becomes valid; sticky-key "
  279. "preservation would otherwise keep the poisoned IP forever"
  280. )
  281. assert bridge._target_ip_uint32_le == h2d_le
  282. await bridge.stop()
  283. @pytest.mark.asyncio
  284. async def test_request_topic_message_is_ignored(self):
  285. server = _make_server()
  286. bridge = _make_bridge(server)
  287. await bridge.start()
  288. payload = json.dumps({"print": {"command": "push_status"}}).encode()
  289. bridge._on_printer_raw(f"device/{H2D_SERIAL}/request", payload)
  290. await asyncio.sleep(0.01)
  291. assert bridge.get_latest_print_state() is None
  292. await bridge.stop()
  293. @pytest.mark.asyncio
  294. async def test_incremental_push_preserves_ams_from_previous_cache(self):
  295. """Regression for #1371: Bambu firmware sends FULL push_status on
  296. pushall (with AMS/vt_tray/net/etc.) but typically OMITS those fields
  297. from 1 Hz incremental push_status updates. Without preserving the
  298. sticky keys across pushes, the cache forgets AMS info after the first
  299. incremental update, and BambuStudio (which reads the cache via the
  300. VP's 1 Hz status push) sees no AMS info until the user power-cycles
  301. the printer (forcing a fresh pushall).
  302. """
  303. server = _make_server()
  304. bridge = _make_bridge(server)
  305. await bridge.start()
  306. # 1. Initial pushall response with full state, AMS included.
  307. full_push = json.dumps(
  308. {
  309. "print": {
  310. "command": "push_status",
  311. "gcode_state": "IDLE",
  312. "wifi_signal": "-50dBm",
  313. "ams": {
  314. "ams": [
  315. {
  316. "id": "0",
  317. "tray": [
  318. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  319. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  320. ],
  321. }
  322. ],
  323. "tray_exist_bits": "3",
  324. },
  325. "vt_tray": {"id": "254", "tray_type": ""},
  326. "lights_report": [{"node": "chamber_light", "mode": "on"}],
  327. }
  328. }
  329. ).encode()
  330. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", full_push)
  331. await asyncio.sleep(0.01)
  332. cached = bridge.get_latest_print_state()
  333. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  334. assert cached["vt_tray"]["id"] == "254"
  335. assert cached["lights_report"][0]["mode"] == "on"
  336. # 2. Incremental push with only temp/wifi changes — NO ams field.
  337. # This is what the printer sends every ~1 s between full pushalls.
  338. incremental_push = json.dumps(
  339. {
  340. "print": {
  341. "command": "push_status",
  342. "wifi_signal": "-55dBm",
  343. "chamber_temper": 26.0,
  344. }
  345. }
  346. ).encode()
  347. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", incremental_push)
  348. await asyncio.sleep(0.01)
  349. cached = bridge.get_latest_print_state()
  350. # New fields take effect.
  351. assert cached["wifi_signal"] == "-55dBm"
  352. assert cached["chamber_temper"] == 26.0
  353. # Sticky fields preserved from the previous cache (the #1371 fix).
  354. assert "ams" in cached, "AMS field must be preserved across incremental pushes (#1371)"
  355. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  356. assert cached["ams"]["tray_exist_bits"] == "3"
  357. assert cached["vt_tray"]["id"] == "254"
  358. assert cached["lights_report"][0]["mode"] == "on"
  359. await bridge.stop()
  360. @pytest.mark.asyncio
  361. async def test_incremental_push_preserves_non_allowlisted_capability_fields(self):
  362. """Regression for #1622: BambuStudio gates Device-tab UIs (manage
  363. calibration, AMS-slot filament dropdown, ...) on capability /
  364. lifecycle fields (cali_version, print_type, mc_print_stage,
  365. device, ...) it reads off the cached push_status. Before the fix
  366. these fields were not in the allowlist and drained out of the
  367. bridge cache on the first 1 Hz incremental tick, so the slicer's
  368. Device tab would grey out the gated UIs once the cache thinned.
  369. After the fix the cache accumulates everything the printer has
  370. ever sent, dropped only when explicitly overwritten.
  371. """
  372. server = _make_server()
  373. bridge = _make_bridge(server)
  374. await bridge.start()
  375. full_push = json.dumps(
  376. {
  377. "print": {
  378. "command": "push_status",
  379. "cali_version": 2,
  380. "print_type": "idle",
  381. "gcode_state": "IDLE",
  382. "mc_print_stage": "0",
  383. "mc_stage": 0,
  384. "device": {"ext_tool": {"info": []}},
  385. "cfg": "",
  386. "home_flag": 256,
  387. "wifi_signal": "-50dBm",
  388. }
  389. }
  390. ).encode()
  391. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", full_push)
  392. await asyncio.sleep(0.01)
  393. # Incremental push carrying only temps + wifi — none of the
  394. # capability/lifecycle fields above are mentioned.
  395. incremental_push = json.dumps(
  396. {
  397. "print": {
  398. "command": "push_status",
  399. "wifi_signal": "-55dBm",
  400. "nozzle_temper": 24.5,
  401. }
  402. }
  403. ).encode()
  404. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", incremental_push)
  405. await asyncio.sleep(0.01)
  406. cached = bridge.get_latest_print_state()
  407. # Incremental values applied.
  408. assert cached["wifi_signal"] == "-55dBm"
  409. assert cached["nozzle_temper"] == 24.5
  410. # Capability / lifecycle fields preserved from the prior pushall
  411. # — the symptoms in #1622 (Device-tab UIs disabled) trace to these
  412. # exact keys missing.
  413. assert cached["cali_version"] == 2
  414. assert cached["print_type"] == "idle"
  415. assert cached["gcode_state"] == "IDLE"
  416. assert cached["mc_print_stage"] == "0"
  417. assert cached["mc_stage"] == 0
  418. assert cached["device"] == {"ext_tool": {"info": []}}
  419. assert cached["cfg"] == ""
  420. assert cached["home_flag"] == 256
  421. await bridge.stop()
  422. @pytest.mark.asyncio
  423. async def test_partial_vt_tray_update_overlays_onto_cached_full_dict(self):
  424. """Regression for #1622 round 5 (reported by @shaddowlink): right after
  425. the slicer picks a filament for the external spool (vt_tray, ams_id=255),
  426. Bambu firmware pushes a partial vt_tray carrying just the changed
  427. fields — typically ``{tray_info_idx, tray_color}`` — and omits the
  428. ~18 other keys (tray_type, state, k, n, cali_idx, nozzle_temp_min/max,
  429. tray_uuid, xcam_info, ...) the slicer needs to render the slot.
  430. Before this fix the per-field accumulate replaced the cached vt_tray
  431. wholesale (it only carried over prev keys NOT present in new), so the
  432. next 1 Hz cached-as-base push handed the slicer a stripped vt_tray and
  433. BambuStudio rendered the external slot as "invalid" until a reload
  434. triggered a fresh pushall. AMS slots didn't suffer because
  435. `_merge_ams_dict` already deep-merged them. The fix overlays incoming
  436. keys onto the previous dict for every top-level dict-shaped field
  437. (excluding ams, which keeps its own deep merge).
  438. """
  439. server = _make_server()
  440. bridge = _make_bridge(server)
  441. await bridge.start()
  442. # 1. Pushall response with the full ~20-field vt_tray dict a real
  443. # P1S sends to bootstrap the slot.
  444. full_push = json.dumps(
  445. {
  446. "print": {
  447. "command": "push_status",
  448. "vt_tray": {
  449. "id": "254",
  450. "tray_info_idx": "Pea5f68f",
  451. "tray_type": "PLA",
  452. "tray_sub_brands": "",
  453. "tray_color": "F72323FF",
  454. "tray_weight": "0",
  455. "tray_diameter": "0.00",
  456. "tray_temp": "0",
  457. "tray_time": "0",
  458. "bed_temp_type": "0",
  459. "bed_temp": "0",
  460. "nozzle_temp_max": "240",
  461. "nozzle_temp_min": "190",
  462. "xcam_info": "000000000000000000000000",
  463. "tray_uuid": "00000000000000000000000000000000",
  464. "ctype": 0,
  465. "remain": -1,
  466. "k": 0.01999999955296,
  467. "n": 1,
  468. "cali_idx": -1,
  469. "state": 3,
  470. },
  471. }
  472. }
  473. ).encode()
  474. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", full_push)
  475. await asyncio.sleep(0.01)
  476. # 2. Incremental push carrying just the two fields the slicer's pick
  477. # changed — exactly the shape the P1S firmware sends after an
  478. # ams_filament_setting ack. This is what shaddowlink's wire dump
  479. # captured for the failing case.
  480. incremental_push = json.dumps(
  481. {
  482. "print": {
  483. "command": "push_status",
  484. "vt_tray": {
  485. "tray_info_idx": "Pea5f68f",
  486. "tray_color": "76D9F4FF",
  487. },
  488. }
  489. }
  490. ).encode()
  491. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", incremental_push)
  492. await asyncio.sleep(0.01)
  493. cached = bridge.get_latest_print_state()
  494. vt = cached["vt_tray"]
  495. # Incoming fields applied.
  496. assert vt["tray_info_idx"] == "Pea5f68f"
  497. assert vt["tray_color"] == "76D9F4FF"
  498. # All other fields preserved from the prior pushall — without these
  499. # the slicer rendered the slot as invalid.
  500. assert vt["tray_type"] == "PLA"
  501. assert vt["state"] == 3
  502. assert vt["remain"] == -1
  503. assert vt["k"] == 0.01999999955296
  504. assert vt["n"] == 1
  505. assert vt["cali_idx"] == -1
  506. assert vt["nozzle_temp_min"] == "190"
  507. assert vt["nozzle_temp_max"] == "240"
  508. assert vt["tray_uuid"] == "00000000000000000000000000000000"
  509. assert vt["id"] == "254"
  510. await bridge.stop()
  511. @pytest.mark.asyncio
  512. async def test_partial_ams_status_update_preserves_unit_list(self):
  513. """#1387: Bambu firmware also sends `ams` updates where the key is
  514. present but the inner `ams` array is missing — e.g. just
  515. ``{ams_status: 1}`` or a humidity change. Before the deep-merge fix
  516. the bridge would overwrite the cached AMS with this stripped blob,
  517. the slicer would read it on the next 1 Hz push, and BambuStudio
  518. would drop the unit list and fall back to its "no AMS" render
  519. (only the external spool visible — the reporter's exact symptom).
  520. Now the partial update only mutates the fields it carries; the
  521. cached unit list survives.
  522. """
  523. server = _make_server()
  524. bridge = _make_bridge(server)
  525. await bridge.start()
  526. # 1. Pushall with full AMS state.
  527. bridge._on_printer_raw(
  528. f"device/{H2D_SERIAL}/report",
  529. json.dumps(
  530. {
  531. "print": {
  532. "command": "push_status",
  533. "ams": {
  534. "ams": [
  535. {
  536. "id": "0",
  537. "humidity": "1",
  538. "tray": [{"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"}],
  539. }
  540. ],
  541. "tray_exist_bits": "1",
  542. "ams_status": "0",
  543. },
  544. }
  545. }
  546. ).encode(),
  547. )
  548. await asyncio.sleep(0.01)
  549. # 2. Partial AMS update — only `ams_status` and `humidity` changed.
  550. # No `ams.ams` array, so prev's unit list must be preserved.
  551. bridge._on_printer_raw(
  552. f"device/{H2D_SERIAL}/report",
  553. json.dumps(
  554. {
  555. "print": {
  556. "command": "push_status",
  557. "ams": {"ams_status": "1", "humidity": "2"},
  558. }
  559. }
  560. ).encode(),
  561. )
  562. await asyncio.sleep(0.01)
  563. cached = bridge.get_latest_print_state()
  564. # Scalar fields take the new values.
  565. assert cached["ams"]["ams_status"] == "1"
  566. assert cached["ams"]["humidity"] == "2"
  567. # Unit + tray data preserved from the pushall.
  568. assert cached["ams"]["tray_exist_bits"] == "1"
  569. assert len(cached["ams"]["ams"]) == 1
  570. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PLA"
  571. assert cached["ams"]["ams"][0]["tray"][0]["tray_color"] == "FF0000FF"
  572. await bridge.stop()
  573. @pytest.mark.asyncio
  574. async def test_partial_ams_unit_update_preserves_other_units(self):
  575. """#1387: when multiple AMS units are configured (e.g. H2D with two
  576. AMS), an incremental push during a print typically only carries the
  577. unit / tray that changed state. Naive replacement of `ams.ams` wipes
  578. the other unit. The bridge merges unit-by-unit by id, preserving
  579. units the incremental doesn't mention.
  580. """
  581. server = _make_server()
  582. bridge = _make_bridge(server)
  583. await bridge.start()
  584. # 1. Pushall with two AMS units configured.
  585. bridge._on_printer_raw(
  586. f"device/{H2D_SERIAL}/report",
  587. json.dumps(
  588. {
  589. "print": {
  590. "command": "push_status",
  591. "ams": {
  592. "ams": [
  593. {"id": "0", "tray": [{"id": "0", "tray_type": "PLA"}]},
  594. {"id": "1", "tray": [{"id": "0", "tray_type": "PETG"}]},
  595. ],
  596. # bit 0 (AMS 0 slot 0) + bit 4 (AMS 1 slot 0) = 0x11.
  597. # `_on_printer_raw` now applies the #1726 bitmask
  598. # cleanup to the cached state, so the test fixture
  599. # must declare both loaded slots — same shape the
  600. # real printer sends.
  601. "tray_exist_bits": "11",
  602. },
  603. }
  604. }
  605. ).encode(),
  606. )
  607. await asyncio.sleep(0.01)
  608. # 2. Tray-targeted incremental: unit 0 / tray 0 state changed.
  609. # Unit 1 is not in the update — must survive.
  610. bridge._on_printer_raw(
  611. f"device/{H2D_SERIAL}/report",
  612. json.dumps(
  613. {
  614. "print": {
  615. "command": "push_status",
  616. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "state": "11"}]}]},
  617. }
  618. }
  619. ).encode(),
  620. )
  621. await asyncio.sleep(0.01)
  622. cached = bridge.get_latest_print_state()
  623. units = {u["id"]: u for u in cached["ams"]["ams"]}
  624. # Unit 0 keeps its tray_type from the pushall + picks up the new state.
  625. assert units["0"]["tray"][0]["tray_type"] == "PLA"
  626. assert units["0"]["tray"][0]["state"] == "11"
  627. # Unit 1 survives the incremental.
  628. assert "1" in units
  629. assert units["1"]["tray"][0]["tray_type"] == "PETG"
  630. await bridge.stop()
  631. @pytest.mark.asyncio
  632. async def test_tray_exist_bits_clears_empty_slots_in_slicer_cache(self):
  633. """#1726 (reported by @needo37): the bridge cache forwards the real
  634. printer's raw AMS payload to the slicer. Without the empty-slot
  635. cleanup that bambu_mqtt.py applies to Bambuddy's internal state, the
  636. cached units carried stale `tray_type` / `tray_color` /
  637. `tray_info_idx` for slots whose `tray_exist_bits` bit was 0 — and
  638. BambuStudio's Sync rendered those empty slots as phantom loaded
  639. filaments. After the fix the bridge runs the same shared
  640. ``apply_tray_exist_bits`` helper before storing the cache.
  641. """
  642. server = _make_server()
  643. bridge = _make_bridge(server)
  644. await bridge.start()
  645. # Pushall: AMS 0 has slots 0/1/2/3; only slots 1, 2, 3 are loaded.
  646. # Slot 0 carries stale data (RFID/color/material from a previously
  647. # loaded spool). `tray_exist_bits` = 0xe = 0b1110 → bit 0 unset.
  648. bridge._on_printer_raw(
  649. f"device/{H2D_SERIAL}/report",
  650. json.dumps(
  651. {
  652. "print": {
  653. "command": "push_status",
  654. "ams": {
  655. "ams": [
  656. {
  657. "id": "0",
  658. "tray": [
  659. {
  660. "id": "0",
  661. "tray_type": "PLA",
  662. "tray_color": "FF0000FF",
  663. "tray_info_idx": "GFL00",
  664. "tag_uid": "1234567890abcdef",
  665. "tray_uuid": "abcdef1234567890abcdef1234567890",
  666. "remain": 75,
  667. "state": "11",
  668. },
  669. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  670. {"id": "2", "tray_type": "ABS", "tray_color": "0000FFFF"},
  671. {"id": "3", "tray_type": "TPU", "tray_color": "FFFF00FF"},
  672. ],
  673. }
  674. ],
  675. "tray_exist_bits": "e",
  676. },
  677. }
  678. }
  679. ).encode(),
  680. )
  681. await asyncio.sleep(0.01)
  682. cached = bridge.get_latest_print_state()
  683. slot0 = cached["ams"]["ams"][0]["tray"][0]
  684. # Empty slot: stale per-tray fields wiped, state promoted to 9.
  685. assert slot0["state"] == 9, "empty slot must be promoted to state=9"
  686. assert slot0["tray_type"] == ""
  687. assert slot0["tray_color"] == ""
  688. assert slot0["tray_info_idx"] == ""
  689. assert slot0["tag_uid"] == "0000000000000000"
  690. assert slot0["tray_uuid"] == "00000000000000000000000000000000"
  691. assert slot0["remain"] == 0
  692. # Loaded slots preserved.
  693. assert cached["ams"]["ams"][0]["tray"][1]["tray_type"] == "PETG"
  694. assert cached["ams"]["ams"][0]["tray"][2]["tray_type"] == "ABS"
  695. assert cached["ams"]["ams"][0]["tray"][3]["tray_type"] == "TPU"
  696. await bridge.stop()
  697. @pytest.mark.asyncio
  698. async def test_tray_exist_bits_shutdown_guard_preserves_cache(self):
  699. """#765 shutdown guard mirrored at the bridge: when the printer
  700. powers off it sends all-zero `tray_exist_bits` paired with
  701. `power_on_flag=False`. Wiping the cache on that pattern would
  702. propagate phantom empties to every slicer reconnect until the
  703. printer powers back on and pushes a real state. Skip cleanup
  704. on the shutdown-shaped payload."""
  705. server = _make_server()
  706. bridge = _make_bridge(server)
  707. await bridge.start()
  708. # 1. Normal pushall — all four slots loaded.
  709. bridge._on_printer_raw(
  710. f"device/{H2D_SERIAL}/report",
  711. json.dumps(
  712. {
  713. "print": {
  714. "command": "push_status",
  715. "ams": {
  716. "ams": [
  717. {
  718. "id": "0",
  719. "tray": [
  720. {"id": str(i), "tray_type": "PLA", "tray_color": f"{i:02x}{i:02x}{i:02x}FF"}
  721. for i in range(4)
  722. ],
  723. }
  724. ],
  725. "tray_exist_bits": "f",
  726. "power_on_flag": True,
  727. },
  728. }
  729. }
  730. ).encode(),
  731. )
  732. await asyncio.sleep(0.01)
  733. # 2. Shutdown-shaped push: tray_exist_bits=0 + power_on_flag=False.
  734. bridge._on_printer_raw(
  735. f"device/{H2D_SERIAL}/report",
  736. json.dumps(
  737. {
  738. "print": {
  739. "command": "push_status",
  740. "ams": {
  741. "tray_exist_bits": "0",
  742. "power_on_flag": False,
  743. },
  744. }
  745. }
  746. ).encode(),
  747. )
  748. await asyncio.sleep(0.01)
  749. cached = bridge.get_latest_print_state()
  750. for i in range(4):
  751. assert cached["ams"]["ams"][0]["tray"][i]["tray_type"] == "PLA", f"slot {i} must survive the shutdown push"
  752. await bridge.stop()
  753. @pytest.mark.asyncio
  754. async def test_tray_exist_bits_skips_ams_ht_units(self):
  755. """AMS-HT units (id >= 128) use a separate addressing scheme and
  756. must not be touched by the bitmask cleanup — bit math at
  757. global_bit = ams_id * 4 + tray_id would overrun normal AMS bits.
  758. Pin the skip so future AMS-HT support doesn't accidentally wipe
  759. loaded HT slots.
  760. """
  761. server = _make_server()
  762. bridge = _make_bridge(server)
  763. await bridge.start()
  764. bridge._on_printer_raw(
  765. f"device/{H2D_SERIAL}/report",
  766. json.dumps(
  767. {
  768. "print": {
  769. "command": "push_status",
  770. "ams": {
  771. "ams": [
  772. {
  773. "id": "128",
  774. "tray": [
  775. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  776. ],
  777. }
  778. ],
  779. "tray_exist_bits": "0",
  780. "power_on_flag": True,
  781. },
  782. }
  783. }
  784. ).encode(),
  785. )
  786. await asyncio.sleep(0.01)
  787. cached = bridge.get_latest_print_state()
  788. ht_slot = cached["ams"]["ams"][0]["tray"][0]
  789. # tray_exist_bits="0" alone would normally wipe — but AMS-HT is
  790. # skipped, so the HT slot keeps its loaded data.
  791. assert ht_slot["tray_type"] == "PLA"
  792. await bridge.stop()
  793. @pytest.mark.asyncio
  794. async def test_partial_ams_tray_update_preserves_other_trays(self):
  795. """Same shape as the unit-level test but at the tray level. AMS
  796. unit 0 has four trays; the incremental only mentions tray 0.
  797. Trays 1-3 must survive intact."""
  798. server = _make_server()
  799. bridge = _make_bridge(server)
  800. await bridge.start()
  801. bridge._on_printer_raw(
  802. f"device/{H2D_SERIAL}/report",
  803. json.dumps(
  804. {
  805. "print": {
  806. "command": "push_status",
  807. "ams": {
  808. "ams": [
  809. {
  810. "id": "0",
  811. "tray": [
  812. {"id": "0", "tray_type": "PLA", "tray_color": "FF0000FF"},
  813. {"id": "1", "tray_type": "PETG", "tray_color": "00FF00FF"},
  814. {"id": "2", "tray_type": "ABS", "tray_color": "0000FFFF"},
  815. {"id": "3", "tray_type": "TPU", "tray_color": "FFFF00FF"},
  816. ],
  817. }
  818. ],
  819. },
  820. }
  821. }
  822. ).encode(),
  823. )
  824. await asyncio.sleep(0.01)
  825. bridge._on_printer_raw(
  826. f"device/{H2D_SERIAL}/report",
  827. json.dumps(
  828. {
  829. "print": {
  830. "command": "push_status",
  831. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "state": "11"}]}]},
  832. }
  833. }
  834. ).encode(),
  835. )
  836. await asyncio.sleep(0.01)
  837. cached = bridge.get_latest_print_state()
  838. trays = {t["id"]: t for t in cached["ams"]["ams"][0]["tray"]}
  839. assert trays["0"]["tray_type"] == "PLA"
  840. assert trays["0"]["state"] == "11"
  841. # Trays not mentioned in the incremental survive intact.
  842. assert trays["1"]["tray_type"] == "PETG"
  843. assert trays["2"]["tray_type"] == "ABS"
  844. assert trays["3"]["tray_type"] == "TPU"
  845. await bridge.stop()
  846. @pytest.mark.asyncio
  847. async def test_incoming_ams_update_replaces_cached_ams(self):
  848. """Counterpart to the #1371 fix: preservation only kicks in when the
  849. incoming push OMITS a sticky key. When the printer DOES send a fresh
  850. `ams` value (e.g. on a pushall, or when AMS state genuinely changes),
  851. that value must take effect — the preservation must not shadow real
  852. updates.
  853. """
  854. server = _make_server()
  855. bridge = _make_bridge(server)
  856. await bridge.start()
  857. # 1. Initial state: PLA in tray 0.
  858. bridge._on_printer_raw(
  859. f"device/{H2D_SERIAL}/report",
  860. json.dumps(
  861. {
  862. "print": {
  863. "command": "push_status",
  864. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "tray_type": "PLA"}]}]},
  865. }
  866. }
  867. ).encode(),
  868. )
  869. await asyncio.sleep(0.01)
  870. # 2. Fresh push with PETG — must replace, not get shadowed by the old PLA.
  871. bridge._on_printer_raw(
  872. f"device/{H2D_SERIAL}/report",
  873. json.dumps(
  874. {
  875. "print": {
  876. "command": "push_status",
  877. "ams": {"ams": [{"id": "0", "tray": [{"id": "0", "tray_type": "PETG"}]}]},
  878. }
  879. }
  880. ).encode(),
  881. )
  882. await asyncio.sleep(0.01)
  883. cached = bridge.get_latest_print_state()
  884. assert cached["ams"]["ams"][0]["tray"][0]["tray_type"] == "PETG"
  885. await bridge.stop()
  886. # ---------------------------------------------------------------------------
  887. # Caching: get_version response
  888. # ---------------------------------------------------------------------------
  889. class TestVersionCache:
  890. @pytest.mark.asyncio
  891. async def test_get_version_response_caches_modules(self):
  892. server = _make_server()
  893. bridge = _make_bridge(server)
  894. await bridge.start()
  895. payload = json.dumps(
  896. {
  897. "info": {
  898. "command": "get_version",
  899. "module": [
  900. {"name": "ota", "sn": H2D_SERIAL, "sw_ver": "01.03.00.00"},
  901. {"name": "n3f/0", "sn": "AMS_HW_1", "sw_ver": "04.00.21.87"},
  902. ],
  903. }
  904. }
  905. ).encode()
  906. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  907. await asyncio.sleep(0.01)
  908. modules = bridge.get_latest_version_modules()
  909. assert modules is not None
  910. assert len(modules) == 2
  911. # Device-level sn rewritten; AMS-hardware sn left alone.
  912. assert modules[0]["sn"] == VP_SERIAL
  913. assert modules[1]["sn"] == "AMS_HW_1"
  914. await bridge.stop()
  915. # ---------------------------------------------------------------------------
  916. # Selective fan-out (everything that's not push_status / get_version)
  917. # ---------------------------------------------------------------------------
  918. class TestCommandResponseFanout:
  919. @pytest.mark.asyncio
  920. async def test_extrusion_cali_get_response_is_fanned_out(self):
  921. """Slicer's extrusion_cali_get goes to the printer; the printer's response
  922. must reach the slicer or BambuStudio's pre-flight blocks Send."""
  923. server = _make_server()
  924. server.push_raw_to_clients = AsyncMock()
  925. bridge = _make_bridge(server)
  926. await bridge.start()
  927. body = json.dumps({"print": {"command": "extrusion_cali_get", "filaments": []}}).encode()
  928. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", body)
  929. await asyncio.sleep(0.01)
  930. server.push_raw_to_clients.assert_awaited_once()
  931. topic, _payload = server.push_raw_to_clients.await_args.args
  932. assert topic == f"device/{VP_SERIAL}/report"
  933. await bridge.stop()
  934. # ---------------------------------------------------------------------------
  935. # Forwarding: slicer → printer
  936. # ---------------------------------------------------------------------------
  937. class TestForwardToPrinter:
  938. @pytest.mark.asyncio
  939. async def test_forward_publishes_to_real_serial_request_topic(self):
  940. target = _make_paho_client()
  941. bridge = _make_bridge(_make_server(), target)
  942. await bridge.start()
  943. ok = bridge.forward_to_printer({"print": {"command": "stop"}})
  944. assert ok is True
  945. target.publish_raw.assert_called_once()
  946. topic, payload = target.publish_raw.call_args.args
  947. assert topic == f"device/{H2D_SERIAL}/request"
  948. assert json.loads(payload) == {"print": {"command": "stop"}}
  949. await bridge.stop()
  950. @pytest.mark.asyncio
  951. async def test_forward_returns_false_when_not_bound(self):
  952. pm = MagicMock()
  953. pm.get_client = MagicMock(return_value=None)
  954. bridge = MQTTBridge(
  955. vp_id=1,
  956. vp_name="vp1",
  957. vp_serial=VP_SERIAL,
  958. target_printer_id=42,
  959. mqtt_server=_make_server(),
  960. printer_manager=pm,
  961. )
  962. await bridge.start()
  963. assert bridge.forward_to_printer({"print": {"command": "stop"}}) is False
  964. await bridge.stop()
  965. # ---------------------------------------------------------------------------
  966. # SimpleMQTTServer status response: cached-as-base
  967. # ---------------------------------------------------------------------------
  968. class TestStatusReportCachedAsBase:
  969. """`_send_status_report` sends near-byte-identical real data when bridge cache exists."""
  970. def _capture_published(self, server: SimpleMQTTServer):
  971. """Wrap _publish_to_report to capture (topic, payload_dict)."""
  972. published: list = []
  973. async def _capture(writer, payload, serial="", log_event=True):
  974. published.append((serial or server.serial, payload))
  975. server._publish_to_report = _capture # type: ignore[assignment]
  976. return published
  977. @pytest.mark.asyncio
  978. async def test_uses_real_cache_when_bridge_active(self):
  979. server = _make_server()
  980. bridge = MagicMock()
  981. bridge.get_latest_print_state.return_value = {
  982. "command": "push_status",
  983. "msg": 0,
  984. "ams": {"ams": [{"id": "0"}]},
  985. "device": {"extruder": {"info": [{"id": 0}, {"id": 1}]}},
  986. "nozzle_diameter": "0.4",
  987. "nozzle_type": "HH01", # real H2D value, not synthetic 'hardened_steel'
  988. }
  989. server.set_bridge(bridge)
  990. published = self._capture_published(server)
  991. await server._send_status_report(MagicMock())
  992. assert len(published) == 1
  993. _serial, payload = published[0]
  994. # AMS / device / nozzle_type all from cache
  995. assert payload["print"]["nozzle_type"] == "HH01"
  996. assert payload["print"]["device"]["extruder"]["info"][1]["id"] == 1
  997. # Protocol fields under our control
  998. assert payload["print"]["command"] == "push_status"
  999. assert payload["print"]["gcode_state"] == "IDLE"
  1000. @pytest.mark.asyncio
  1001. async def test_falls_back_to_synthetic_when_no_cache(self):
  1002. server = _make_server()
  1003. bridge = MagicMock()
  1004. bridge.get_latest_print_state.return_value = None
  1005. server.set_bridge(bridge)
  1006. published = self._capture_published(server)
  1007. await server._send_status_report(MagicMock())
  1008. assert len(published) == 1
  1009. _serial, payload = published[0]
  1010. # Synthetic baseline has stub fields like nozzle_type='hardened_steel'
  1011. # and a `storage` field that the real H2D doesn't push.
  1012. assert payload["print"]["nozzle_type"] == "hardened_steel"
  1013. assert "storage" in payload["print"]
  1014. @pytest.mark.asyncio
  1015. async def test_storage_indicators_overlaid_for_send_preflight(self):
  1016. """#1228: P1S/A1-class firmware doesn't always include the SD/storage
  1017. fields BambuStudio's "Send" pre-flight reads. Without these the
  1018. slicer rejects with 'storage needs to be inserted' before even
  1019. attempting FTP. The cached-as-base path now overlays them so the
  1020. pre-flight passes regardless of what the real printer reports.
  1021. """
  1022. server = _make_server()
  1023. bridge = MagicMock()
  1024. # Real P1S push without SD card inserted: home_flag has other bits set
  1025. # but the SD bit (0x100) is clear; sdcard is False; no storage field.
  1026. bridge.get_latest_print_state.return_value = {
  1027. "command": "push_status",
  1028. "msg": 0,
  1029. "home_flag": 0x42,
  1030. "sdcard": False,
  1031. }
  1032. server.set_bridge(bridge)
  1033. published = self._capture_published(server)
  1034. await server._send_status_report(MagicMock())
  1035. _serial, payload = published[0]
  1036. # SD bit ORed onto whatever was there — other bits preserved.
  1037. assert payload["print"]["home_flag"] & 0x100 == 0x100
  1038. assert payload["print"]["home_flag"] & 0x42 == 0x42
  1039. # Force-set so a False from the printer doesn't trip the pre-flight.
  1040. assert payload["print"]["sdcard"] is True
  1041. # storage was missing — the overlay must inject a non-empty default.
  1042. assert "storage" in payload["print"]
  1043. assert payload["print"]["storage"]["free"] > 0
  1044. assert payload["print"]["storage"]["total"] > 0
  1045. @pytest.mark.asyncio
  1046. async def test_storage_indicators_preserve_real_storage_when_present(self):
  1047. """When the real printer DOES report a storage block, pass it through
  1048. unchanged (the overlay only fills in the missing field, not overrides).
  1049. """
  1050. server = _make_server()
  1051. bridge = MagicMock()
  1052. real_storage = {"free": 12345, "total": 67890}
  1053. bridge.get_latest_print_state.return_value = {
  1054. "command": "push_status",
  1055. "msg": 0,
  1056. "home_flag": 0x100, # SD bit already set on the real printer
  1057. "sdcard": True,
  1058. "storage": real_storage,
  1059. }
  1060. server.set_bridge(bridge)
  1061. published = self._capture_published(server)
  1062. await server._send_status_report(MagicMock())
  1063. _serial, payload = published[0]
  1064. # SD bit OR is idempotent — already-set bit stays set.
  1065. assert payload["print"]["home_flag"] == 0x100
  1066. assert payload["print"]["sdcard"] is True
  1067. # Real values pass through, NOT the synthetic defaults.
  1068. assert payload["print"]["storage"] == real_storage
  1069. @pytest.mark.asyncio
  1070. async def test_overrides_protocol_fields_even_when_cache_present(self):
  1071. """Cached value's gcode_state must NOT win over our local upload-state-machine value."""
  1072. server = _make_server()
  1073. server._gcode_state = "PREPARE"
  1074. server._current_file = "foo.3mf"
  1075. bridge = MagicMock()
  1076. bridge.get_latest_print_state.return_value = {
  1077. "command": "push_status",
  1078. "gcode_state": "IDLE", # printer is idle; we are mid-FTP-upload
  1079. "gcode_file": "",
  1080. "gcode_file_prepare_percent": "0",
  1081. }
  1082. server.set_bridge(bridge)
  1083. published = self._capture_published(server)
  1084. await server._send_status_report(MagicMock())
  1085. _serial, payload = published[0]
  1086. assert payload["print"]["gcode_state"] == "PREPARE"
  1087. assert payload["print"]["gcode_file"] == "foo.3mf"
  1088. @pytest.mark.asyncio
  1089. async def test_live_progress_fields_zeroed_in_cached_branch(self):
  1090. """#1558: when the real target printer is mid-print, the cached
  1091. push_status carries live values for mc_percent / stg_cur / layer_num /
  1092. etc. BambuStudio's Send pre-flight reads any of these as "VP busy"
  1093. even when gcode_state above is forced to IDLE — blocking Send while
  1094. the target prints. The cached branch must override these to the same
  1095. idle values the synthetic stub uses.
  1096. """
  1097. server = _make_server()
  1098. bridge = MagicMock()
  1099. # Real printer mid-print state: gcode_state may be RUNNING upstream,
  1100. # but the VP's own _gcode_state is IDLE (Send is requesting a
  1101. # new upload, the VP isn't running anything).
  1102. bridge.get_latest_print_state.return_value = {
  1103. "command": "push_status",
  1104. "msg": 0,
  1105. "gcode_state": "RUNNING",
  1106. "mc_print_stage": "2",
  1107. "mc_percent": 47,
  1108. "mc_remaining_time": 3600,
  1109. "stg": [1, 2, 3],
  1110. "stg_cur": 14,
  1111. "layer_num": 120,
  1112. "total_layer_num": 250,
  1113. "print_error": 0,
  1114. }
  1115. server.set_bridge(bridge)
  1116. published = self._capture_published(server)
  1117. await server._send_status_report(MagicMock())
  1118. _serial, payload = published[0]
  1119. # Every live-progress field must reflect "idle / VP isn't busy".
  1120. assert payload["print"]["mc_print_stage"] == ""
  1121. assert payload["print"]["mc_percent"] == 0
  1122. assert payload["print"]["mc_remaining_time"] == 0
  1123. assert payload["print"]["stg"] == []
  1124. assert payload["print"]["stg_cur"] == 0
  1125. assert payload["print"]["layer_num"] == 0
  1126. assert payload["print"]["total_layer_num"] == 0
  1127. assert payload["print"]["print_error"] == 0
  1128. # ---------------------------------------------------------------------------
  1129. # Wire format
  1130. # ---------------------------------------------------------------------------
  1131. class TestWireFormat:
  1132. """BambuStudio's Send pre-flight rejects compact JSON — must match real printer's
  1133. indented format (32K bytes for an idle H2D vs 14K compact)."""
  1134. @pytest.mark.asyncio
  1135. async def test_publish_uses_indent_4_json_format(self):
  1136. server = _make_server()
  1137. captured: list = []
  1138. async def _capture_drain():
  1139. pass
  1140. writer = MagicMock()
  1141. writer.write = lambda data: captured.append(data)
  1142. writer.drain = AsyncMock()
  1143. await server._publish_to_report(writer, {"print": {"command": "push_status", "ams": {}}})
  1144. body = b"".join(captured)
  1145. assert b'\n "print"' in body, "publish_to_report must use indent=4 JSON"
  1146. @pytest.mark.asyncio
  1147. async def test_publish_records_bridge_to_slicer_event_by_default(self, monkeypatch):
  1148. """#1622 round 3: every bridge-synthesised reply (info.get_version answer,
  1149. project_file ack, on-demand pushall response) must show up in the
  1150. cmd.jsonl trace under the ``bridge_to_slicer`` direction so a P1S↔H2D
  1151. diff captures the fingerprint the slicer reads back from us."""
  1152. server = _make_server()
  1153. writer = MagicMock()
  1154. writer.write = lambda data: None
  1155. writer.drain = AsyncMock()
  1156. recorded: list = []
  1157. monkeypatch.setattr(
  1158. "backend.app.services.virtual_printer.mqtt_server.append_event",
  1159. lambda vp_name, direction, topic, payload: recorded.append((vp_name, direction, topic, payload)),
  1160. )
  1161. payload = {"info": {"command": "get_version", "sequence_id": "0"}}
  1162. await server._publish_to_report(writer, payload)
  1163. assert len(recorded) == 1
  1164. vp_name, direction, topic, recorded_payload = recorded[0]
  1165. assert direction == "bridge_to_slicer"
  1166. assert topic.endswith("/report")
  1167. assert recorded_payload == payload
  1168. @pytest.mark.asyncio
  1169. async def test_publish_skips_event_when_log_event_false(self, monkeypatch):
  1170. """The 1Hz periodic-push path passes ``log_event=False`` so dump_wire's
  1171. snapshot stays the canonical record of cache shape and the cmd.jsonl
  1172. isn't flooded with ~60 lines/min per VP."""
  1173. server = _make_server()
  1174. writer = MagicMock()
  1175. writer.write = lambda data: None
  1176. writer.drain = AsyncMock()
  1177. recorded: list = []
  1178. monkeypatch.setattr(
  1179. "backend.app.services.virtual_printer.mqtt_server.append_event",
  1180. lambda *args, **kwargs: recorded.append(args),
  1181. )
  1182. await server._publish_to_report(writer, {"print": {"command": "push_status"}}, log_event=False)
  1183. assert recorded == []
  1184. # ---------------------------------------------------------------------------
  1185. # Routing: _handle_publish
  1186. # ---------------------------------------------------------------------------
  1187. class TestPublishRouting:
  1188. """Slicer-issued commands: project_file/gcode_file handled locally, everything
  1189. else forwarded to the real printer."""
  1190. def _build_publish_payload(self, topic: str, body: bytes) -> bytes:
  1191. topic_bytes = topic.encode("utf-8")
  1192. return bytes([len(topic_bytes) >> 8, len(topic_bytes) & 0xFF]) + topic_bytes + body
  1193. def _attach_active_bridge(self, server: SimpleMQTTServer) -> MagicMock:
  1194. bridge = MagicMock()
  1195. bridge.is_active = True
  1196. bridge.forward_to_printer = MagicMock(return_value=True)
  1197. server.set_bridge(bridge)
  1198. return bridge
  1199. @pytest.mark.asyncio
  1200. async def test_project_file_handled_locally_not_forwarded(self):
  1201. server = _make_server()
  1202. bridge = self._attach_active_bridge(server)
  1203. writer = MagicMock()
  1204. writer.write = MagicMock()
  1205. writer.drain = AsyncMock()
  1206. body = json.dumps({"print": {"command": "project_file", "subtask_name": "f", "sequence_id": "1"}}).encode()
  1207. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1208. with patch.object(server, "_send_print_response", new=AsyncMock()) as mock_resp:
  1209. await server._handle_publish(0x30, payload, writer, "client1")
  1210. bridge.forward_to_printer.assert_not_called()
  1211. mock_resp.assert_awaited_once()
  1212. @pytest.mark.asyncio
  1213. async def test_gcode_file_handled_locally_not_forwarded(self):
  1214. server = _make_server()
  1215. bridge = self._attach_active_bridge(server)
  1216. writer = MagicMock()
  1217. writer.write = MagicMock()
  1218. writer.drain = AsyncMock()
  1219. body = json.dumps({"print": {"command": "gcode_file", "subtask_name": "f.gcode", "sequence_id": "1"}}).encode()
  1220. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1221. with patch.object(server, "_send_print_response", new=AsyncMock()):
  1222. await server._handle_publish(0x30, payload, writer, "client1")
  1223. bridge.forward_to_printer.assert_not_called()
  1224. @pytest.mark.asyncio
  1225. async def test_pushall_handled_locally_not_forwarded(self):
  1226. server = _make_server()
  1227. bridge = self._attach_active_bridge(server)
  1228. writer = MagicMock()
  1229. writer.write = MagicMock()
  1230. writer.drain = AsyncMock()
  1231. body = json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}).encode()
  1232. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1233. with patch.object(server, "_send_status_report", new=AsyncMock()) as mock_status:
  1234. await server._handle_publish(0x30, payload, writer, "client1")
  1235. # Synthetic answer fires (fast, low latency); no forwarding (the
  1236. # cache already mirrors what the printer would respond with).
  1237. bridge.forward_to_printer.assert_not_called()
  1238. mock_status.assert_awaited_once()
  1239. @pytest.mark.asyncio
  1240. async def test_get_version_handled_locally_not_forwarded(self):
  1241. server = _make_server()
  1242. bridge = self._attach_active_bridge(server)
  1243. writer = MagicMock()
  1244. writer.write = MagicMock()
  1245. writer.drain = AsyncMock()
  1246. body = json.dumps({"info": {"command": "get_version", "sequence_id": "1"}}).encode()
  1247. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1248. with patch.object(server, "_send_version_response", new=AsyncMock()) as mock_ver:
  1249. await server._handle_publish(0x30, payload, writer, "client1")
  1250. bridge.forward_to_printer.assert_not_called()
  1251. mock_ver.assert_awaited_once()
  1252. @pytest.mark.asyncio
  1253. async def test_extrusion_cali_get_is_forwarded(self):
  1254. """extrusion_cali_get fetches per-filament k-profiles — must reach the printer."""
  1255. server = _make_server()
  1256. bridge = self._attach_active_bridge(server)
  1257. writer = MagicMock()
  1258. writer.write = MagicMock()
  1259. writer.drain = AsyncMock()
  1260. body = json.dumps(
  1261. {
  1262. "print": {
  1263. "command": "extrusion_cali_get",
  1264. "filament_id": "",
  1265. "nozzle_diameter": "0.4",
  1266. "sequence_id": "5",
  1267. }
  1268. }
  1269. ).encode()
  1270. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1271. await server._handle_publish(0x30, payload, writer, "client1")
  1272. bridge.forward_to_printer.assert_called_once()
  1273. forwarded = bridge.forward_to_printer.call_args.args[0]
  1274. assert forwarded["print"]["command"] == "extrusion_cali_get"
  1275. @pytest.mark.asyncio
  1276. async def test_print_stop_is_forwarded(self):
  1277. server = _make_server()
  1278. bridge = self._attach_active_bridge(server)
  1279. writer = MagicMock()
  1280. writer.write = MagicMock()
  1281. writer.drain = AsyncMock()
  1282. body = json.dumps({"print": {"command": "stop", "sequence_id": "5"}}).encode()
  1283. payload = self._build_publish_payload(f"device/{VP_SERIAL}/request", body)
  1284. await server._handle_publish(0x30, payload, writer, "client1")
  1285. bridge.forward_to_printer.assert_called_once()
  1286. # ---------------------------------------------------------------------------
  1287. # IP encoding helper
  1288. # ---------------------------------------------------------------------------
  1289. class TestIpEncoding:
  1290. def test_le_uint32_matches_real_h2d_capture(self):
  1291. # 192.168.255.133 captured from real H2D's net.info[0].ip = 2248124608
  1292. assert _ip_to_uint32_le("192.168.255.133") == 2248124608
  1293. def test_vp_ip_round_trip(self):
  1294. assert _ip_to_uint32_le("192.168.255.16") == 285190336
  1295. def test_invalid_ip_raises(self):
  1296. with pytest.raises(ValueError):
  1297. _ip_to_uint32_le("not.an.ip.actually")
  1298. class TestHostnameResolution:
  1299. """#1429 follow-up: users who configured the printer by FQDN (common on
  1300. LANs with router-provided DNS like `p1s.fritz.box`) hit `invalid IPv4`
  1301. on the encoder and the rewrite never armed — slicer kept FTPing direct
  1302. to the real printer. The bridge now resolves hostname→IPv4 first."""
  1303. def test_pass_through_for_valid_ipv4(self):
  1304. assert _resolve_target_to_ipv4("192.168.1.50") == "192.168.1.50"
  1305. def test_empty_returns_none(self):
  1306. assert _resolve_target_to_ipv4("") is None
  1307. assert _resolve_target_to_ipv4(None) is None # type: ignore[arg-type]
  1308. def test_hostname_resolves_via_getaddrinfo(self):
  1309. with patch(
  1310. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1311. return_value=[(2, 1, 6, "", ("192.168.3.153", 0))],
  1312. ) as mock_gai:
  1313. assert _resolve_target_to_ipv4("p1s.fritz.box") == "192.168.3.153"
  1314. # AF_INET filter prevents an IPv6-only result from being picked,
  1315. # since net.info[*].ip is a uint32 LE that can't carry v6.
  1316. assert mock_gai.call_args.kwargs.get("family") == socket.AF_INET
  1317. def test_dns_failure_returns_none(self):
  1318. with patch(
  1319. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1320. side_effect=OSError("Name or service not known"),
  1321. ):
  1322. assert _resolve_target_to_ipv4("nope.invalid") is None
  1323. def test_fqdn_target_arms_encoding(self, caplog):
  1324. """End-to-end: a client whose `ip_address` is an FQDN should arm
  1325. the bridge once DNS resolves, and the cached rewrite uses the
  1326. resolved IPv4 (not the hostname string) for the `net.info[].ip`
  1327. encoding."""
  1328. server = _make_server(bind_address=VP_IP)
  1329. bridge = _make_bridge(server)
  1330. client = _make_paho_client(ip="p1s.fritz.box")
  1331. bridge._target_client = client
  1332. with (
  1333. patch(
  1334. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1335. return_value=[(2, 1, 6, "", (H2D_IP, 0))],
  1336. ),
  1337. caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"),
  1338. ):
  1339. bridge._refresh_ip_encoding()
  1340. assert bridge._target_ip_uint32_le == _ip_to_uint32_le(H2D_IP)
  1341. assert bridge._vp_ip_uint32_le == _ip_to_uint32_le(VP_IP)
  1342. armed = [r for r in caplog.records if "MQTT bridge IP encoding armed" in r.getMessage()]
  1343. assert len(armed) == 1
  1344. # Operator should see configured→resolved in the log line so a
  1345. # bad-DNS regression is immediately legible.
  1346. assert "p1s.fritz.box→192.168.255.133" in armed[0].getMessage()
  1347. # ---------------------------------------------------------------------------
  1348. # Auto-resolve fallback for default-config (bind_address = "0.0.0.0")
  1349. # ---------------------------------------------------------------------------
  1350. class TestBindAddressAutoResolve:
  1351. """#1429 residual: VPs created without a dedicated bind IP run on
  1352. `bind_address=0.0.0.0`. The original fix's `_refresh_ip_encoding`
  1353. early-returned on 0.0.0.0, so the rewrite never armed and `net.info[].ip`
  1354. kept leaking the real printer IP. Now the bridge auto-resolves a host
  1355. interface in the printer's subnet and uses that as the VP IP."""
  1356. @pytest.mark.asyncio
  1357. async def test_rewrite_arms_via_auto_resolved_host_ip(self):
  1358. """When bind_address is 0.0.0.0, fall back to the host interface in
  1359. the target printer's subnet and rewrite to that IP."""
  1360. server = _make_server(bind_address="0.0.0.0") # nosec B104
  1361. bridge = _make_bridge(server)
  1362. with patch(
  1363. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1364. return_value=VP_IP,
  1365. ):
  1366. await bridge.start()
  1367. h2d_le = _ip_to_uint32_le(H2D_IP)
  1368. vp_le = _ip_to_uint32_le(VP_IP)
  1369. payload = json.dumps(
  1370. {
  1371. "print": {
  1372. "command": "push_status",
  1373. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  1374. }
  1375. }
  1376. ).encode()
  1377. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  1378. await asyncio.sleep(0.01)
  1379. cached = bridge.get_latest_print_state()
  1380. assert cached["net"]["info"][0]["ip"] == vp_le
  1381. assert bridge._vp_ip_uint32_le == vp_le
  1382. await bridge.stop()
  1383. @pytest.mark.asyncio
  1384. async def test_rewrite_disabled_when_no_matching_host_interface(self):
  1385. """If no host interface shares a subnet with the printer, the bridge
  1386. cannot pick a sensible VP IP — leave encoding unarmed and let the
  1387. push through unrewritten (no crash, no wrong rewrite)."""
  1388. server = _make_server(bind_address="")
  1389. bridge = _make_bridge(server)
  1390. with patch(
  1391. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1392. return_value=None,
  1393. ):
  1394. await bridge.start()
  1395. h2d_le = _ip_to_uint32_le(H2D_IP)
  1396. payload = json.dumps(
  1397. {
  1398. "print": {
  1399. "command": "push_status",
  1400. "net": {"info": [{"ip": h2d_le, "mask": 0xFFFFFF}]},
  1401. }
  1402. }
  1403. ).encode()
  1404. bridge._on_printer_raw(f"device/{H2D_SERIAL}/report", payload)
  1405. await asyncio.sleep(0.01)
  1406. assert bridge._vp_ip_uint32_le is None
  1407. assert bridge._target_ip_uint32_le is None
  1408. await bridge.stop()
  1409. @pytest.mark.asyncio
  1410. async def test_explicit_bind_ip_takes_precedence_over_auto_resolve(self):
  1411. """Auto-resolve only kicks in when bind_address is empty/0.0.0.0; an
  1412. explicitly-set bind IP must be used verbatim even if there's also a
  1413. same-subnet host interface."""
  1414. server = _make_server(bind_address=VP_IP)
  1415. bridge = _make_bridge(server)
  1416. # Auto-resolver would have returned a DIFFERENT IP — we must not use it.
  1417. with patch(
  1418. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1419. return_value="10.99.99.99",
  1420. ):
  1421. await bridge.start()
  1422. assert bridge._vp_ip_uint32_le == _ip_to_uint32_le(VP_IP)
  1423. await bridge.stop()
  1424. def test_resolve_helper_returns_none_for_unreachable_target(self):
  1425. """The helper itself must be defensive — if `find_interface_for_ip`
  1426. raises or returns None, we get None (no crash)."""
  1427. with patch(
  1428. "backend.app.services.network_utils.find_interface_for_ip",
  1429. return_value=None,
  1430. ):
  1431. assert _resolve_host_interface_for_target("203.0.113.1") is None
  1432. class TestNotArmedDiagnosticLogging:
  1433. """#1429 follow-up: every silent early-return in `_refresh_ip_encoding`
  1434. now emits one INFO line explaining WHY the rewrite couldn't arm. Throttled
  1435. to one line per state change so an idle unarmed bridge doesn't spam the
  1436. log every 30s tick. Cleared on arm so a future failure re-emits.
  1437. """
  1438. def test_no_client_logs_once(self, caplog):
  1439. bridge = _make_bridge(_make_server())
  1440. # Force the "no client" path: bridge starts with _target_client=None.
  1441. assert bridge._target_client is None
  1442. with caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"):
  1443. bridge._refresh_ip_encoding()
  1444. bridge._refresh_ip_encoding() # 2nd tick — same reason, must NOT re-log.
  1445. bridge._refresh_ip_encoding()
  1446. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1447. assert len(not_armed) == 1
  1448. assert "target_client is None" in not_armed[0].getMessage()
  1449. def test_missing_target_ip_logs_specific_reason(self, caplog):
  1450. bridge = _make_bridge(_make_server())
  1451. # Manually attach a client with no ip_address (simulates pre-DHCP).
  1452. client = _make_paho_client()
  1453. client.ip_address = ""
  1454. bridge._target_client = client
  1455. with caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"):
  1456. bridge._refresh_ip_encoding()
  1457. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1458. assert len(not_armed) == 1
  1459. assert "no ip_address" in not_armed[0].getMessage()
  1460. def test_no_matching_host_interface_logs_specific_reason(self, caplog):
  1461. server = _make_server(bind_address="0.0.0.0") # nosec B104
  1462. bridge = _make_bridge(server)
  1463. with (
  1464. patch(
  1465. "backend.app.services.virtual_printer.mqtt_bridge._resolve_host_interface_for_target",
  1466. return_value=None,
  1467. ),
  1468. caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"),
  1469. ):
  1470. bridge._target_client = _make_paho_client()
  1471. bridge._refresh_ip_encoding()
  1472. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1473. assert len(not_armed) == 1
  1474. msg = not_armed[0].getMessage()
  1475. assert H2D_IP in msg
  1476. assert "no host interface" in msg
  1477. def test_unresolvable_target_logs_reason(self, caplog):
  1478. """When `ip_address` isn't a valid IPv4 *and* doesn't resolve via DNS,
  1479. the bridge must report a single concrete not-armed reason naming the
  1480. configured value — operator can then see exactly what input failed."""
  1481. server = _make_server(bind_address=VP_IP)
  1482. bridge = _make_bridge(server)
  1483. client = _make_paho_client()
  1484. client.ip_address = "not.an.ip"
  1485. bridge._target_client = client
  1486. with (
  1487. patch(
  1488. "backend.app.services.virtual_printer.mqtt_bridge.socket.getaddrinfo",
  1489. side_effect=OSError("nodename nor servname provided"),
  1490. ),
  1491. caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"),
  1492. ):
  1493. bridge._refresh_ip_encoding()
  1494. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1495. assert len(not_armed) == 1
  1496. assert "could not resolve printer host 'not.an.ip'" in not_armed[0].getMessage()
  1497. def test_successful_arm_clears_dedup_so_future_failure_relogs(self, caplog):
  1498. """After a successful arm, the dedup must reset so a subsequent
  1499. regression (e.g. printer client unbinds) re-emits the diagnostic
  1500. line instead of being silenced by the previous failure reason."""
  1501. bridge = _make_bridge(_make_server(bind_address=VP_IP))
  1502. bridge._target_client = _make_paho_client()
  1503. with caplog.at_level(logging.INFO, logger="backend.app.services.virtual_printer.mqtt_bridge"):
  1504. bridge._refresh_ip_encoding() # arms
  1505. assert bridge._not_armed_reason is None
  1506. # Simulate a regression — target_client drops away.
  1507. bridge._target_client = None
  1508. bridge._refresh_ip_encoding()
  1509. bridge._refresh_ip_encoding() # 2nd same-reason tick must not re-log
  1510. not_armed = [r for r in caplog.records if "NOT armed" in r.getMessage()]
  1511. assert len(not_armed) == 1 # the post-arm failure
  1512. armed = [r for r in caplog.records if "MQTT bridge IP encoding armed" in r.getMessage()]
  1513. assert len(armed) == 1