test_status_broadcast_ams_slot_config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. """Configuring an AMS slot must reach the printer card without a page reload.
  2. `on_printer_status_change` deduplicates WebSocket broadcasts against a
  3. `status_key`. Its AMS component used to carry only id / tray_type / state, so
  4. re-configuring a slot to a different brand or colour of the SAME material
  5. produced an identical key: the printer's pushall arrived with the new values,
  6. the handler compared, found no change, and returned without broadcasting. The
  7. card then showed the old filament until the 30s fallback poll or an F5.
  8. Reset never had the bug — it clears tray_type, which was always in the key.
  9. That asymmetry is what these tests pin: every field Configure Slot writes has
  10. to move the key, and the fields that churn every second still must not.
  11. """
  12. from types import SimpleNamespace
  13. from unittest.mock import AsyncMock, MagicMock, patch
  14. import pytest
  15. from backend.app import main as main_module
  16. def _spawn_patch():
  17. """Close the reconcile coroutine the handler builds as a call argument.
  18. Same reason as test_printer_offline_notification.py: a bare MagicMock keeps
  19. it alive in call_args and it finalises unawaited during a later test's GC.
  20. """
  21. return patch(
  22. "backend.app.main.spawn_background_task",
  23. side_effect=lambda coro, **kwargs: coro.close(),
  24. )
  25. def _tray(**overrides) -> dict:
  26. """One AMS tray as the firmware reports it, mid-way through a print job.
  27. Defaults describe a configured slot: Bambu PLA Basic in black, bound to
  28. calibration slot 3.
  29. """
  30. tray = {
  31. "id": "0",
  32. "tray_type": "PLA",
  33. "state": 10,
  34. "tray_color": "000000FF",
  35. "tray_info_idx": "GFA00",
  36. "tray_sub_brands": "PLA Basic",
  37. "cali_idx": 3,
  38. "remain": 42,
  39. }
  40. tray.update(overrides)
  41. return tray
  42. def _state(trays: list[dict], ams_extra: dict | None = None) -> SimpleNamespace:
  43. """Minimal PrinterState stub carrying one AMS unit.
  44. Idle and unheated, so the handler runs straight from the dedup check to the
  45. broadcast without touching progress milestones, HMS notifications or the DB.
  46. ``ams_extra`` sets unit-level (not per-tray) fields such as the drying pair
  47. ``dry_time`` / ``dry_countdown_stalled``.
  48. """
  49. ams_unit = {"id": "0", "dry_time": 0, "tray": trays}
  50. ams_unit.update(ams_extra or {})
  51. return SimpleNamespace(
  52. connected=True,
  53. state="IDLE",
  54. progress=0,
  55. layer_num=0,
  56. temperatures={},
  57. nozzles=[],
  58. raw_data={"ams": [ams_unit]},
  59. stg_cur=0,
  60. # Real PrinterState always carries these; the status-broadcast dedup
  61. # key reads them so a Filament Track Switch rebind reaches the card.
  62. fila_switch=None,
  63. ams_switch_inlet={},
  64. extruder_slots={},
  65. cooling_fan_speed=0,
  66. big_fan1_speed=0,
  67. big_fan2_speed=0,
  68. chamber_light="",
  69. active_extruder=0,
  70. tray_now=0,
  71. door_open=False,
  72. subtask_name="",
  73. gcode_file="",
  74. remaining_time=None,
  75. hms_errors=[],
  76. ams_filament_backup=None,
  77. )
  78. @pytest.fixture(autouse=True)
  79. def _reset_edge_state():
  80. main_module._last_status_broadcast.clear()
  81. main_module._printer_last_connected.clear()
  82. main_module._printer_reconciled_since_connect.clear()
  83. yield
  84. main_module._last_status_broadcast.clear()
  85. main_module._printer_last_connected.clear()
  86. main_module._printer_reconciled_since_connect.clear()
  87. async def _push(ws_mgr, trays: list[dict], ams_extra: dict | None = None) -> None:
  88. """Deliver one status push to the handler."""
  89. relay = MagicMock()
  90. relay.on_printer_status = AsyncMock()
  91. pm = MagicMock()
  92. pm.get_printer.return_value = None # Skip the relay payload branch.
  93. pm.get_model.return_value = ""
  94. with (
  95. patch("backend.app.main.ws_manager", ws_mgr),
  96. patch("backend.app.main.mqtt_relay", relay),
  97. patch("backend.app.main.printer_manager", pm),
  98. _spawn_patch(),
  99. patch("backend.app.main.printer_state_to_dict", return_value={}),
  100. ):
  101. await main_module.on_printer_status_change(1, _state(trays, ams_extra))
  102. @pytest.fixture
  103. def ws_mgr():
  104. mgr = MagicMock()
  105. mgr.send_printer_status = AsyncMock()
  106. return mgr
  107. class TestConfigureSlotBroadcasts:
  108. """Each field Configure Slot writes must break the dedup on its own —
  109. the user may change only the colour, or only the K-profile."""
  110. @pytest.mark.asyncio
  111. @pytest.mark.parametrize(
  112. "field,new_value",
  113. [
  114. ("tray_color", "FF0000FF"),
  115. ("tray_info_idx", "GFA01"),
  116. ("tray_sub_brands", "PLA Matte"),
  117. ("cali_idx", 7),
  118. ],
  119. )
  120. async def test_a_changed_filament_field_broadcasts(self, ws_mgr, field, new_value):
  121. await _push(ws_mgr, [_tray()])
  122. assert ws_mgr.send_printer_status.await_count == 1
  123. await _push(ws_mgr, [_tray(**{field: new_value})])
  124. assert ws_mgr.send_printer_status.await_count == 2, (
  125. f"changing {field} did not reach the frontend — the card would keep "
  126. "showing the old filament until the fallback poll"
  127. )
  128. @pytest.mark.asyncio
  129. async def test_the_realistic_reconfigure_broadcasts(self, ws_mgr):
  130. """Black Bambu PLA Basic → red eSUN PLA+ with its own K-profile.
  131. The whole point of the report: same material, so every field the old key
  132. looked at is unchanged.
  133. """
  134. await _push(ws_mgr, [_tray()])
  135. await _push(
  136. ws_mgr,
  137. [
  138. _tray(
  139. tray_color="C1121FFF",
  140. tray_info_idx="GFL99",
  141. tray_sub_brands="eSUN PLA+",
  142. cali_idx=5,
  143. )
  144. ],
  145. )
  146. assert ws_mgr.send_printer_status.await_count == 2
  147. @pytest.mark.asyncio
  148. async def test_a_second_slot_is_watched_too(self, ws_mgr):
  149. """The key spans every tray, so configuring slot 2 must broadcast even
  150. though slot 1 is untouched."""
  151. trays = [_tray(id="0"), _tray(id="1", tray_type="PETG", tray_info_idx="GFG00")]
  152. await _push(ws_mgr, trays)
  153. changed = [_tray(id="0"), _tray(id="1", tray_type="PETG", tray_info_idx="GFG01")]
  154. await _push(ws_mgr, changed)
  155. assert ws_mgr.send_printer_status.await_count == 2
  156. class TestDedupStillHolds:
  157. """The dedup exists to keep a printing machine from flooding the socket.
  158. Widening the key must not have cost that."""
  159. @pytest.mark.asyncio
  160. async def test_an_identical_push_is_still_suppressed(self, ws_mgr):
  161. await _push(ws_mgr, [_tray()])
  162. await _push(ws_mgr, [_tray()])
  163. assert ws_mgr.send_printer_status.await_count == 1
  164. @pytest.mark.asyncio
  165. async def test_remaining_filament_does_not_broadcast(self, ws_mgr):
  166. """`remain` ticks down throughout a print and is deliberately absent
  167. from the key. It sits in the same tray dict as the fields we added, so
  168. this pins that we widened the key rather than hashing the whole tray."""
  169. await _push(ws_mgr, [_tray(remain=42)])
  170. await _push(ws_mgr, [_tray(remain=41)])
  171. assert ws_mgr.send_printer_status.await_count == 1
  172. class TestExistingBehaviourUnchanged:
  173. """The cases that already worked, kept working."""
  174. @pytest.mark.asyncio
  175. async def test_a_load_unload_transition_still_broadcasts(self, ws_mgr):
  176. """#784 — tray state 11→10."""
  177. await _push(ws_mgr, [_tray(state=11)])
  178. await _push(ws_mgr, [_tray(state=10)])
  179. assert ws_mgr.send_printer_status.await_count == 2
  180. @pytest.mark.asyncio
  181. async def test_resetting_a_slot_still_broadcasts(self, ws_mgr):
  182. """Reset clears the filament identity outright."""
  183. await _push(ws_mgr, [_tray()])
  184. await _push(
  185. ws_mgr,
  186. [_tray(tray_type="", tray_color="", tray_info_idx="", tray_sub_brands="", cali_idx=-1)],
  187. )
  188. assert ws_mgr.send_printer_status.await_count == 2
  189. @pytest.mark.asyncio
  190. async def test_a_printer_with_no_ams_still_broadcasts_once(self, ws_mgr):
  191. """The `else ()` branch — an AMS-less printer must not crash or
  192. double-broadcast."""
  193. relay = MagicMock()
  194. relay.on_printer_status = AsyncMock()
  195. pm = MagicMock()
  196. pm.get_printer.return_value = None
  197. pm.get_model.return_value = ""
  198. state = _state([])
  199. state.raw_data = {}
  200. for _ in range(2):
  201. with (
  202. patch("backend.app.main.ws_manager", ws_mgr),
  203. patch("backend.app.main.mqtt_relay", relay),
  204. patch("backend.app.main.printer_manager", pm),
  205. _spawn_patch(),
  206. patch("backend.app.main.printer_state_to_dict", return_value={}),
  207. ):
  208. await main_module.on_printer_status_change(1, state)
  209. assert ws_mgr.send_printer_status.await_count == 1
  210. class TestFilamentTrackSwitchBroadcasts:
  211. """Moving an AMS to the other switch inlet has to reach the printer card.
  212. The inlet binding lives in AMS ``info`` bits, so it is in neither the tray
  213. component of this key nor the AMS change-hash (which covers tray fields only
  214. — widening that would fire spurious Spoolman syncs). Without its own term
  215. here, "Join IN-B" on the printer's Manual AMS Setup screen moved no key at
  216. all and the card's inlet badges stayed stale until a page reload.
  217. """
  218. @staticmethod
  219. def _fts_state(inlets: dict[str, str], installed: bool = True):
  220. from backend.app.services.bambu_mqtt import FilaSwitchState
  221. state = _state([_tray()])
  222. state.fila_switch = FilaSwitchState(installed=installed)
  223. state.ams_switch_inlet = inlets
  224. return state
  225. async def _push_state(self, ws_mgr, state) -> None:
  226. relay = MagicMock()
  227. relay.on_printer_status = AsyncMock()
  228. pm = MagicMock()
  229. pm.get_printer.return_value = None
  230. pm.get_model.return_value = ""
  231. with (
  232. patch("backend.app.main.ws_manager", ws_mgr),
  233. patch("backend.app.main.mqtt_relay", relay),
  234. patch("backend.app.main.printer_manager", pm),
  235. _spawn_patch(),
  236. patch("backend.app.main.printer_state_to_dict", return_value={}),
  237. ):
  238. await main_module.on_printer_status_change(1, state)
  239. @pytest.mark.asyncio
  240. async def test_a_rebind_broadcasts(self, ws_mgr):
  241. await self._push_state(ws_mgr, self._fts_state({"0": "A", "1": "B"}))
  242. assert ws_mgr.send_printer_status.await_count == 1
  243. await self._push_state(ws_mgr, self._fts_state({"0": "B", "1": "B"}))
  244. assert ws_mgr.send_printer_status.await_count == 2, (
  245. "moving an AMS to the other inlet did not reach the frontend — the "
  246. "card would keep showing the old inlet badge until a page reload"
  247. )
  248. @pytest.mark.asyncio
  249. async def test_fitting_the_accessory_broadcasts(self, ws_mgr):
  250. await self._push_state(ws_mgr, self._fts_state({}, installed=False))
  251. await self._push_state(ws_mgr, self._fts_state({}, installed=True))
  252. assert ws_mgr.send_printer_status.await_count == 2
  253. @pytest.mark.asyncio
  254. async def test_an_unchanged_binding_is_still_suppressed(self, ws_mgr):
  255. """The binding only moves when someone reconfigures the machine, so it
  256. must not add a broadcast to every push mid-print."""
  257. for _ in range(3):
  258. await self._push_state(ws_mgr, self._fts_state({"0": "A", "1": "B"}))
  259. assert ws_mgr.send_printer_status.await_count == 1
  260. @pytest.mark.asyncio
  261. async def test_key_order_does_not_matter(self, ws_mgr):
  262. """Dict iteration order must not masquerade as a rebind."""
  263. await self._push_state(ws_mgr, self._fts_state({"0": "A", "1": "B"}))
  264. await self._push_state(ws_mgr, self._fts_state({"1": "B", "0": "A"}))
  265. assert ws_mgr.send_printer_status.await_count == 1
  266. class TestDryCountdownStallBroadcasts:
  267. """#2896: a parked drying command must be able to reach the card.
  268. ``dry_countdown_stalled`` is the one drying signal the countdown cannot
  269. carry, because the MQTT layer raises it exactly when ``dry_time`` has
  270. STOPPED moving. On the frame that flips it, every other member of the dedup
  271. key is identical, so unless the flag is itself in the key the handler
  272. returns before broadcasting. Mid-print a temperature change would eventually
  273. break the tie, but a command parked on an idle machine moves nothing else —
  274. AMS temp and humidity are not in the key — so the grey "Drying not started"
  275. badge would sit unreachable.
  276. """
  277. @pytest.mark.asyncio
  278. async def test_the_stall_flip_broadcasts(self, ws_mgr):
  279. await _push(ws_mgr, [_tray()], {"dry_time": 720})
  280. assert ws_mgr.send_printer_status.await_count == 1
  281. # Same frozen countdown again: genuinely nothing changed.
  282. await _push(ws_mgr, [_tray()], {"dry_time": 720})
  283. assert ws_mgr.send_printer_status.await_count == 1
  284. # 150s of no tick later the MQTT layer stamps the stall. dry_time is
  285. # unchanged by definition — only the flag can break the key.
  286. await _push(ws_mgr, [_tray()], {"dry_time": 720, "dry_countdown_stalled": True})
  287. assert ws_mgr.send_printer_status.await_count == 2, (
  288. "the stall flag did not reach the frontend — the card would keep "
  289. "claiming an active 12h drying cycle that is not running"
  290. )
  291. @pytest.mark.asyncio
  292. async def test_clearing_the_stall_broadcasts(self, ws_mgr):
  293. """The recovery edge matters too: the firmware finally starts the cycle,
  294. the countdown ticks, and the badge must go back to amber."""
  295. await _push(ws_mgr, [_tray()], {"dry_time": 720, "dry_countdown_stalled": True})
  296. await _push(ws_mgr, [_tray()], {"dry_time": 719})
  297. assert ws_mgr.send_printer_status.await_count == 2
  298. @pytest.mark.asyncio
  299. async def test_a_steady_stalled_unit_does_not_reflood(self, ws_mgr):
  300. """Once flagged, repeats of the flagged frame stay deduplicated — the
  301. flag flips once per cycle, so widening the key costs no traffic."""
  302. await _push(ws_mgr, [_tray()], {"dry_time": 720, "dry_countdown_stalled": True})
  303. await _push(ws_mgr, [_tray()], {"dry_time": 720, "dry_countdown_stalled": True})
  304. assert ws_mgr.send_printer_status.await_count == 1