test_panda_breath.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. """BIQU Panda Breath over MQTT (#1466).
  2. The payloads are the shape firmware 1.0.4 declares in its Home Assistant
  3. discovery messages: one JSON state document per device, "ON"/"OFF" switches,
  4. the three working modes as text, and the bound printer's serial number.
  5. """
  6. import json
  7. from types import SimpleNamespace
  8. from unittest.mock import MagicMock, patch
  9. import pytest
  10. from backend.app.services.panda_breath import PandaBreathService
  11. STATE = {
  12. "chamber_temp": 41.5,
  13. "target_temp": 50,
  14. "work_on": "ON",
  15. "mode": "auto mode",
  16. "filament_drying_mode": "pla",
  17. "drying_running": "OFF",
  18. "drying_remaining_min": 0,
  19. "printer_sn": "01P00A123456789",
  20. "printer_bind": "bind",
  21. "filter_temp": 30,
  22. }
  23. def _service() -> PandaBreathService:
  24. service = PandaBreathService()
  25. service.enabled = True
  26. service.connected = True
  27. return service
  28. @pytest.fixture
  29. def printers():
  30. """printer_manager knows printer 7 by its serial number, printer 8 by another."""
  31. serials = {7: "01P00A123456789", 8: "01P00A999999999"}
  32. pm = MagicMock()
  33. pm.printer_id_for_serial.side_effect = lambda s: next(
  34. (pid for pid, sn in serials.items() if sn.upper() == (s or "").strip().upper()), None
  35. )
  36. pm.get_printer.side_effect = lambda pid: (
  37. SimpleNamespace(serial_number=serials[pid], name=f"P{pid}") if pid in serials else None
  38. )
  39. with patch("backend.app.services.printer_manager.printer_manager", pm):
  40. yield pm
  41. class TestApplyMessage:
  42. def test_state_document_is_read(self, printers):
  43. service = _service()
  44. changed = service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  45. assert changed == {7}
  46. assert service.state_for_printer(7) == {
  47. "device_id": "AABBCC",
  48. "online": True,
  49. "chamber_temp": 41.5,
  50. "target_temp": 50.0,
  51. "work_on": True,
  52. "mode": "auto mode",
  53. "filament_drying_mode": "pla",
  54. "drying_running": False,
  55. "drying_remaining_min": 0.0,
  56. }
  57. def test_same_values_again_change_nothing(self, printers):
  58. service = _service()
  59. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  60. assert service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE)) == set()
  61. def test_partial_document_keeps_the_other_values(self, printers):
  62. service = _service()
  63. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  64. service.apply_message("panda_breath/AABBCC/state", json.dumps({"work_on": "OFF"}))
  65. state = service.state_for_printer(7)
  66. assert state["work_on"] is False
  67. assert state["chamber_temp"] == 41.5
  68. def test_availability_marks_offline(self, printers):
  69. service = _service()
  70. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  71. assert service.apply_message("panda_breath/AABBCC/availability", "offline") == {7}
  72. assert service.state_for_printer(7)["online"] is False
  73. def test_rebinding_updates_both_printers(self, printers):
  74. """Moved to another printer: the old card loses it, the new one gains it."""
  75. service = _service()
  76. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  77. changed = service.apply_message("panda_breath/AABBCC/state", json.dumps({"printer_sn": "01P00A999999999"}))
  78. assert changed == {7, 8}
  79. assert service.state_for_printer(7) is None
  80. assert service.state_for_printer(8)["device_id"] == "AABBCC"
  81. @pytest.mark.parametrize(
  82. ("topic", "payload"),
  83. [
  84. ("panda_breath/AABBCC/state", "not json"),
  85. ("panda_breath/AABBCC/state", "[1, 2]"),
  86. ("panda_breath/AABBCC/command", json.dumps({"work_on": "ON"})),
  87. ("other/AABBCC/state", json.dumps(STATE)),
  88. ("panda_breath/state", json.dumps(STATE)),
  89. ],
  90. )
  91. def test_other_messages_are_ignored(self, printers, topic, payload):
  92. service = _service()
  93. assert service.apply_message(topic, payload) == set()
  94. assert service.devices == {}
  95. def test_unbound_device_reaches_no_printer(self, printers):
  96. service = _service()
  97. state = {**STATE, "printer_sn": ""}
  98. assert service.apply_message("panda_breath/AABBCC/state", json.dumps(state)) == set()
  99. assert service.state_for_printer(7) is None
  100. assert service.get_status({})["devices"][0]["bound"] is False
  101. def test_serial_matches_regardless_of_case(self, printers):
  102. service = _service()
  103. service.apply_message("panda_breath/AABBCC/state", json.dumps({**STATE, "printer_sn": " 01p00a123456789 "}))
  104. assert service.state_for_printer(7)["device_id"] == "AABBCC"
  105. def test_disabled_service_shows_nothing(self, printers):
  106. service = _service()
  107. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  108. service.enabled = False
  109. assert service.state_for_printer(7) is None
  110. # The command route and the status of an offline printer look up by serial.
  111. assert service.device_for_serial("01P00A123456789") is None
  112. assert service.state_for_serial("01P00A123456789") is None
  113. class TestStatus:
  114. def test_lists_devices_with_their_printer(self, printers):
  115. service = _service()
  116. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  117. status = service.get_status({"01P00A123456789": (7, "P7")})
  118. assert status["enabled"] is True
  119. [row] = status["devices"]
  120. assert row["device_id"] == "AABBCC"
  121. assert row["printer_id"] == 7
  122. assert row["printer_name"] == "P7"
  123. assert "printer_sn" not in row
  124. def test_printer_the_caller_may_not_see_is_not_named(self, printers):
  125. service = _service()
  126. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  127. [row] = service.get_status({"01P00A999999999": (8, "P8")})["devices"]
  128. assert row["bound"] is True
  129. assert row["printer_id"] is None
  130. assert row["printer_name"] is None
  131. class TestLostBroker:
  132. def test_devices_count_as_offline_without_the_broker(self, printers):
  133. """Nothing reaches the device then, so its last values are stale."""
  134. service = _service()
  135. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  136. service._on_disconnect(None, None, 0)
  137. assert service.state_for_printer(7)["online"] is False
  138. printers.schedule_status_broadcast.assert_called_with(7)
  139. @pytest.mark.asyncio
  140. async def test_switching_off_refreshes_the_cards(self, printers):
  141. service = _service()
  142. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  143. printers.schedule_status_broadcast.reset_mock()
  144. await service.configure({"mqtt_enabled": True, "panda_breath_enabled": False, "mqtt_broker": "b"})
  145. printers.schedule_status_broadcast.assert_called_once_with(7)
  146. assert service.state_for_printer(7) is None
  147. class TestConfigure:
  148. @pytest.mark.asyncio
  149. @pytest.mark.parametrize(
  150. "settings",
  151. [
  152. {"mqtt_enabled": False, "panda_breath_enabled": True, "mqtt_broker": "b"},
  153. {"mqtt_enabled": True, "panda_breath_enabled": False, "mqtt_broker": "b"},
  154. {"mqtt_enabled": True, "panda_breath_enabled": True, "mqtt_broker": ""},
  155. ],
  156. )
  157. async def test_off_unless_mqtt_and_panda_breath_are_on(self, printers, settings):
  158. service = _service()
  159. service.apply_message("panda_breath/AABBCC/state", json.dumps(STATE))
  160. with patch.object(service, "_connect") as connect:
  161. await service.configure(settings)
  162. connect.assert_not_called()
  163. assert service.enabled is False
  164. assert service.devices == {}
  165. @pytest.mark.asyncio
  166. async def test_on_connects_to_the_relay_broker(self):
  167. service = PandaBreathService()
  168. with patch.object(service, "_connect") as connect:
  169. await service.configure(
  170. {"mqtt_enabled": True, "panda_breath_enabled": True, "mqtt_broker": "broker", "mqtt_port": 1884}
  171. )
  172. connect.assert_called_once()
  173. assert service.enabled is True
  174. assert (service._broker, service._port) == ("broker", 1884)
  175. def test_subscribes_to_state_and_availability(self):
  176. service = PandaBreathService()
  177. client = MagicMock()
  178. service._on_connect(client, None, {}, 0)
  179. topics = [c.args[0] for c in client.subscribe.call_args_list]
  180. assert topics == ["panda_breath/+/state", "panda_breath/+/availability"]
  181. class TestSendCommand:
  182. def test_publishes_one_value_on_the_device_command_topic(self):
  183. service = _service()
  184. service.client = MagicMock()
  185. service.client.publish.return_value = MagicMock(rc=0)
  186. service.connected = True
  187. assert service.send_command("AABBCC", "mode", "filament drying") is True
  188. service.client.publish.assert_called_once_with(
  189. "panda_breath/AABBCC/command", json.dumps({"mode": "filament drying"}), qos=1, retain=False
  190. )
  191. def test_not_connected_sends_nothing(self):
  192. service = _service()
  193. service.client = MagicMock()
  194. service.connected = False
  195. assert service.send_command("AABBCC", "work_on", "OFF") is False
  196. service.client.publish.assert_not_called()
  197. class TestStatusBroadcast:
  198. def test_a_change_pushes_the_printer_status(self, printers):
  199. service = _service()
  200. msg = MagicMock(topic="panda_breath/AABBCC/state", payload=json.dumps(STATE).encode())
  201. service._on_message(None, None, msg)
  202. printers.schedule_status_broadcast.assert_called_once_with(7)
  203. class TestWebSocketStatus:
  204. def test_printer_status_payload_carries_the_device(self):
  205. """The card is fed over the WebSocket; without the key there a merge
  206. would keep a device that has gone away."""
  207. from backend.app.services.bambu_mqtt import PrinterState
  208. from backend.app.services.printer_manager import printer_state_to_dict
  209. with patch("backend.app.services.printer_manager.panda_breath_service") as service:
  210. service.state_for_printer.return_value = {"device_id": "AABBCC"}
  211. assert printer_state_to_dict(PrinterState(), 7)["panda_breath"] == {"device_id": "AABBCC"}
  212. service.state_for_printer.return_value = None
  213. assert printer_state_to_dict(PrinterState(), 7)["panda_breath"] is None
  214. service.state_for_printer.assert_called_with(7)