test_plate_clear_mqtt_notification.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. """Tests for the plate-clear gate reaching MQTT and notifications (#2525).
  2. ``awaiting_plate_clear`` is a Bambuddy-side flag (#961) — the printer's own MQTT
  3. push only ever reports RUNNING/PAUSE/FAILED/FINISH/IDLE, so an external
  4. automation had no way to tell "finished" from "finished and still waiting for
  5. someone to clear the bed". It now rides along on the retained per-printer status
  6. topic, gets its own retained topic on every transition, and can raise a
  7. notification on the rising edge.
  8. """
  9. from types import SimpleNamespace
  10. from unittest.mock import AsyncMock, MagicMock, patch
  11. import pytest
  12. from backend.app.services.bambu_mqtt import PrinterState
  13. from backend.app.services.mqtt_relay import MQTTRelayService
  14. from backend.app.services.printer_manager import PrinterManager
  15. def _relay() -> MQTTRelayService:
  16. relay = MQTTRelayService()
  17. relay.enabled = True
  18. relay.connected = True
  19. relay.client = MagicMock()
  20. return relay
  21. def _state() -> PrinterState:
  22. return PrinterState(
  23. connected=True,
  24. state="FINISH",
  25. progress=100,
  26. remaining_time=0,
  27. layer_num=250,
  28. total_layers=250,
  29. current_print="benchy.gcode.3mf",
  30. subtask_name="benchy",
  31. gcode_file="benchy.gcode",
  32. temperatures={"nozzle": 40, "bed": 30},
  33. wifi_signal="-50dBm",
  34. chamber_light="off",
  35. speed_level=2,
  36. cooling_fan_speed=0,
  37. big_fan1_speed=0,
  38. big_fan2_speed=0,
  39. heatbreak_fan_speed=0,
  40. left_aux_fan_speed=None,
  41. exhaust_fan_present=False,
  42. )
  43. def _published(relay: MQTTRelayService) -> list[tuple[str, dict, bool]]:
  44. """Decode every publish as (topic, payload, retain)."""
  45. import json
  46. calls = []
  47. for call in relay.client.publish.call_args_list:
  48. topic = call.args[0]
  49. payload = json.loads(call.args[1])
  50. calls.append((topic, payload, call.kwargs.get("retain", False)))
  51. return calls
  52. class TestStatusPayload:
  53. @pytest.mark.asyncio
  54. async def test_status_payload_carries_awaiting_plate_clear(self):
  55. relay = _relay()
  56. await relay.on_printer_status(1, _state(), "X1C", "01P00A000000001", True)
  57. topic, payload, retain = _published(relay)[0]
  58. assert topic == "bambuddy/printers/01P00A000000001/status"
  59. assert payload["awaiting_plate_clear"] is True
  60. assert retain is True
  61. @pytest.mark.asyncio
  62. async def test_status_payload_defaults_to_not_awaiting(self):
  63. relay = _relay()
  64. await relay.on_printer_status(1, _state(), "X1C", "01P00A000000001")
  65. _, payload, _ = _published(relay)[0]
  66. assert payload["awaiting_plate_clear"] is False
  67. # The pre-existing telemetry fields must survive the addition.
  68. assert payload["state"] == "FINISH"
  69. assert payload["progress"] == 100
  70. class TestPlateClearTopic:
  71. @pytest.mark.asyncio
  72. async def test_publishes_retained_state_on_its_own_topic(self):
  73. relay = _relay()
  74. await relay.on_plate_clear_state(3, "P1S", "01S00C000000003", True)
  75. topic, payload, retain = _published(relay)[0]
  76. assert topic == "bambuddy/printers/01S00C000000003/plate_clear"
  77. assert payload["awaiting"] is True
  78. assert payload["printer_id"] == 3
  79. assert payload["printer_name"] == "P1S"
  80. assert payload["printer_serial"] == "01S00C000000003"
  81. # Retained so a subscriber that connects later learns the current state
  82. # instead of waiting for the next transition.
  83. assert retain is True
  84. @pytest.mark.asyncio
  85. async def test_honours_the_configured_topic_prefix(self):
  86. relay = _relay()
  87. relay.topic_prefix = "farm/bambuddy"
  88. await relay.on_plate_clear_state(3, "P1S", "01S00C000000003", False)
  89. topic, payload, _ = _published(relay)[0]
  90. assert topic == "farm/bambuddy/printers/01S00C000000003/plate_clear"
  91. assert payload["awaiting"] is False
  92. @pytest.mark.asyncio
  93. async def test_silent_when_relay_is_disabled(self):
  94. relay = _relay()
  95. relay.enabled = False
  96. await relay.on_plate_clear_state(3, "P1S", "01S00C000000003", True)
  97. relay.client.publish.assert_not_called()
  98. class TestEdgeTriggering:
  99. """The setter is re-asserted routinely (the queue clears the gate on every
  100. dispatch), so outward-facing emissions must fire on transitions only."""
  101. def _manager(self) -> PrinterManager:
  102. manager = PrinterManager()
  103. loop = MagicMock()
  104. loop.is_running.return_value = True
  105. manager._loop = loop
  106. return manager
  107. def test_emits_on_the_rising_edge(self):
  108. manager = self._manager()
  109. with patch.object(manager, "_schedule_async") as scheduled:
  110. manager.set_awaiting_plate_clear(7, True)
  111. emitted = [c for c in scheduled.call_args_list if "_emit_plate_clear_change" in repr(c.args[0])]
  112. assert len(emitted) == 1
  113. for call in scheduled.call_args_list:
  114. call.args[0].close()
  115. def test_does_not_re_emit_when_already_awaiting(self):
  116. manager = self._manager()
  117. manager._awaiting_plate_clear.add(7)
  118. with patch.object(manager, "_schedule_async") as scheduled:
  119. manager.set_awaiting_plate_clear(7, True)
  120. emitted = [c for c in scheduled.call_args_list if "_emit_plate_clear_change" in repr(c.args[0])]
  121. assert emitted == []
  122. # Persistence and the WebSocket broadcast are idempotent and stay unconditional.
  123. assert len(scheduled.call_args_list) == 2
  124. for call in scheduled.call_args_list:
  125. call.args[0].close()
  126. def test_does_not_emit_when_clearing_a_gate_that_was_never_up(self):
  127. manager = self._manager()
  128. with patch.object(manager, "_schedule_async") as scheduled:
  129. manager.set_awaiting_plate_clear(7, False)
  130. emitted = [c for c in scheduled.call_args_list if "_emit_plate_clear_change" in repr(c.args[0])]
  131. assert emitted == []
  132. for call in scheduled.call_args_list:
  133. call.args[0].close()
  134. def test_emits_on_the_falling_edge(self):
  135. manager = self._manager()
  136. manager._awaiting_plate_clear.add(7)
  137. with patch.object(manager, "_schedule_async") as scheduled:
  138. manager.set_awaiting_plate_clear(7, False)
  139. emitted = [c for c in scheduled.call_args_list if "_emit_plate_clear_change" in repr(c.args[0])]
  140. assert len(emitted) == 1
  141. for call in scheduled.call_args_list:
  142. call.args[0].close()
  143. def _gate_setting(value: str | None):
  144. """The app setting require_plate_clear, as the emit path reads it."""
  145. return patch("backend.app.api.routes.settings.get_setting", AsyncMock(return_value=value))
  146. @pytest.fixture
  147. def no_overrides():
  148. from backend.app.services import plate_clear
  149. plate_clear.load_overrides({})
  150. yield plate_clear
  151. plate_clear.load_overrides({})
  152. class TestEmitFanOut:
  153. @pytest.mark.asyncio
  154. async def test_rising_edge_publishes_and_notifies(self, no_overrides):
  155. manager = PrinterManager()
  156. manager._printer_info[7] = SimpleNamespace(name="X1C", serial_number="01P00A000000001")
  157. publish = AsyncMock()
  158. notify = AsyncMock()
  159. with (
  160. patch("backend.app.services.mqtt_relay.mqtt_relay.on_plate_clear_state", publish),
  161. patch(
  162. "backend.app.services.notification_service.notification_service.on_plate_clear_required",
  163. notify,
  164. ),
  165. _gate_setting("true"),
  166. ):
  167. await manager._emit_plate_clear_change(7, True)
  168. publish.assert_awaited_once_with(7, "X1C", "01P00A000000001", True)
  169. assert notify.await_count == 1
  170. assert notify.await_args.args[:2] == (7, "X1C")
  171. @pytest.mark.asyncio
  172. async def test_falling_edge_publishes_but_does_not_notify(self):
  173. manager = PrinterManager()
  174. manager._printer_info[7] = SimpleNamespace(name="X1C", serial_number="01P00A000000001")
  175. publish = AsyncMock()
  176. notify = AsyncMock()
  177. with (
  178. patch("backend.app.services.mqtt_relay.mqtt_relay.on_plate_clear_state", publish),
  179. patch(
  180. "backend.app.services.notification_service.notification_service.on_plate_clear_required",
  181. notify,
  182. ),
  183. ):
  184. await manager._emit_plate_clear_change(7, False)
  185. publish.assert_awaited_once_with(7, "X1C", "01P00A000000001", False)
  186. notify.assert_not_awaited()
  187. @pytest.mark.asyncio
  188. async def test_unknown_printer_is_a_no_op(self):
  189. manager = PrinterManager()
  190. publish = AsyncMock()
  191. with patch("backend.app.services.mqtt_relay.mqtt_relay.on_plate_clear_state", publish):
  192. await manager._emit_plate_clear_change(999, True)
  193. publish.assert_not_awaited()
  194. @pytest.mark.asyncio
  195. async def test_falls_back_to_the_db_when_no_client_is_registered(self):
  196. """A printer disconnected outright has no cached info, but the gate can
  197. still be released through the API (#2864) — the retained topic must not
  198. be left asserting a state that is no longer true."""
  199. manager = PrinterManager()
  200. publish = AsyncMock()
  201. with (
  202. patch("backend.app.services.mqtt_relay.mqtt_relay.on_plate_clear_state", publish),
  203. patch.object(
  204. PrinterManager,
  205. "_printer_info_from_db",
  206. AsyncMock(return_value=SimpleNamespace(name="Powered-off X1C", serial_number="01P00A000000009")),
  207. ),
  208. ):
  209. await manager._emit_plate_clear_change(9, False)
  210. publish.assert_awaited_once_with(9, "Powered-off X1C", "01P00A000000009", False)
  211. @pytest.mark.asyncio
  212. async def test_mqtt_failure_does_not_block_the_notification(self, no_overrides):
  213. manager = PrinterManager()
  214. manager._printer_info[7] = SimpleNamespace(name="X1C", serial_number="01P00A000000001")
  215. notify = AsyncMock()
  216. with (
  217. patch(
  218. "backend.app.services.mqtt_relay.mqtt_relay.on_plate_clear_state",
  219. AsyncMock(side_effect=RuntimeError("broker down")),
  220. ),
  221. patch(
  222. "backend.app.services.notification_service.notification_service.on_plate_clear_required",
  223. notify,
  224. ),
  225. _gate_setting("true"),
  226. ):
  227. await manager._emit_plate_clear_change(7, True)
  228. assert notify.await_count == 1
  229. class TestNotifyOnlyWhereTheGateApplies:
  230. """The flag goes up after every print, but a printer the gate does not
  231. apply to holds no queue, so nobody has anything to clear (#2860)."""
  232. @staticmethod
  233. async def _notified(setting: str | None) -> bool:
  234. manager = PrinterManager()
  235. manager._printer_info[7] = SimpleNamespace(name="A1 mini", serial_number="0300AA000000007")
  236. publish = AsyncMock()
  237. notify = AsyncMock()
  238. with (
  239. patch("backend.app.services.mqtt_relay.mqtt_relay.on_plate_clear_state", publish),
  240. patch(
  241. "backend.app.services.notification_service.notification_service.on_plate_clear_required",
  242. notify,
  243. ),
  244. _gate_setting(setting),
  245. ):
  246. await manager._emit_plate_clear_change(7, True)
  247. # The retained MQTT topic reports the flag either way.
  248. publish.assert_awaited_once_with(7, "A1 mini", "0300AA000000007", True)
  249. return notify.await_count == 1
  250. @pytest.mark.asyncio
  251. async def test_silent_with_the_setting_off(self, no_overrides):
  252. assert await self._notified("false") is False
  253. @pytest.mark.asyncio
  254. async def test_silent_with_no_setting_row(self, no_overrides):
  255. assert await self._notified(None) is False
  256. @pytest.mark.asyncio
  257. async def test_printer_turned_on_notifies_with_the_setting_off(self, no_overrides):
  258. no_overrides.set_override(7, True)
  259. assert await self._notified("false") is True
  260. @pytest.mark.asyncio
  261. async def test_printer_turned_off_is_silent_with_the_setting_on(self, no_overrides):
  262. no_overrides.set_override(7, False)
  263. assert await self._notified("true") is False
  264. @pytest.mark.asyncio
  265. async def test_another_printers_override_does_not_count(self, no_overrides):
  266. no_overrides.set_override(8, False)
  267. assert await self._notified("true") is True