test_vp_mqtt_bridge.py 53 KB

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