test_hms_actions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. """Tests for HMS-action lookup and the MQTT dispatcher in execute_hms_action.
  2. The lookup tests confirm the bundled catalog round-trips correctly. The
  3. dispatcher tests are payload-shape contracts — wrong shape sends a bogus
  4. command to the printer, which is the failure mode this PR is most exposed to,
  5. so each HMSAction case publishes the expected JSON.
  6. """
  7. import json
  8. from unittest.mock import MagicMock
  9. import pytest
  10. from backend.app.services.bambu_mqtt import BambuMQTTClient
  11. from backend.app.services.hms_actions import (
  12. HMSAction,
  13. get_actions_for_error_code,
  14. )
  15. class TestActionLookup:
  16. def test_known_a1_error_returns_actions(self):
  17. # 03W is the A1 model code; 03008070 is "Heat the nozzle…" and Bambu's
  18. # catalog lists CHECK_ASSISTANT for it.
  19. actions = get_actions_for_error_code("03W", "03008070")
  20. assert isinstance(actions, list)
  21. assert len(actions) > 0
  22. for a in actions:
  23. assert isinstance(a, str)
  24. def test_unknown_device_returns_empty_list(self):
  25. assert get_actions_for_error_code("ZZZ", "03008070") == []
  26. def test_unknown_error_returns_empty_list(self):
  27. # Real model code, made-up error.
  28. assert get_actions_for_error_code("03W", "DEADBEEF") == []
  29. def test_underscore_form_does_not_match(self):
  30. # Caller is responsible for stripping the `_` before lookup. Guards
  31. # against accidental rewires that pass the underscore form.
  32. assert get_actions_for_error_code("03W", "0300_8070") == []
  33. def test_action_enum_values_are_uppercase_strings(self):
  34. # The catalog stores actions verbatim from BambuStudio. Drift here
  35. # silently breaks the dispatcher's `match` because StrEnum compares
  36. # by value.
  37. assert HMSAction.RESUME_PRINTING == "RESUME_PRINTING"
  38. assert HMSAction.CANCLE == "CANCLE" # sic — kept from BambuStudio
  39. class TestExecuteHmsActionDispatch:
  40. """Each case in the `match` publishes a specific JSON shape. These tests
  41. pin those shapes so silent regressions surface as test failures, not as
  42. a printer receiving a malformed command on a live print.
  43. """
  44. @pytest.fixture
  45. def client(self):
  46. c = BambuMQTTClient(
  47. ip_address="192.168.1.100",
  48. serial_number="03W-TEST",
  49. access_code="12345678",
  50. )
  51. c._client = MagicMock()
  52. c.state.connected = True
  53. return c
  54. def _published_commands(self, client):
  55. """Return the list of `print`/`system` command dicts from publish calls,
  56. skipping the `pushing.pushall` echoes that follow every action."""
  57. out = []
  58. for call in client._client.publish.call_args_list:
  59. _topic, payload = call.args[0], call.args[1]
  60. data = json.loads(payload)
  61. if "pushing" in data:
  62. continue
  63. out.append(data)
  64. return out
  65. def test_returns_false_when_disconnected(self, client):
  66. client.state.connected = False
  67. assert client.execute_hms_action("03008070", HMSAction.OK_BUTTON) is False
  68. client._client.publish.assert_not_called()
  69. def test_returns_false_on_unknown_action(self, client):
  70. assert client.execute_hms_action("03008070", "DOES_NOT_EXIST") is False
  71. # No printer command, but the publish-list check tolerates the pushall
  72. # tail — just confirm no command went out by inspecting the helper.
  73. assert self._published_commands(client) == []
  74. def test_resume_is_plain_no_err_no_job_id(self, client):
  75. # Verified against a live H2D — the `err`-bearing shape is silently
  76. # rejected by Bambu firmware. BambuStudio sends a plain resume; we
  77. # match that. job_id is accepted on the call for symmetry with the
  78. # catalog but deliberately dropped from the wire. See #1830 §(2).
  79. ok = client.execute_hms_action("03008070", HMSAction.RESUME_PRINTING, job_id="task-42")
  80. assert ok is True
  81. cmds = self._published_commands(client)
  82. assert cmds == [
  83. {
  84. "print": {
  85. "command": "resume",
  86. "param": "",
  87. "sequence_id": "0",
  88. }
  89. }
  90. ]
  91. assert "err" not in cmds[0]["print"]
  92. assert "job_id" not in cmds[0]["print"]
  93. def test_proceed_falls_through_to_resume(self, client):
  94. client.execute_hms_action("03008070", HMSAction.PROCEED, job_id="task-1")
  95. cmds = self._published_commands(client)
  96. assert cmds[0]["print"]["command"] == "resume"
  97. # Same plain shape as RESUME_PRINTING — no err.
  98. assert "err" not in cmds[0]["print"]
  99. def test_stop_is_plain_no_err_no_job_id(self, client):
  100. # Same firmware silent-rejection class as resume — the `err` variant
  101. # was confirmed broken on H2D-1 (PAUSE → PAUSE), the plain shape
  102. # transitions to FAILED within ~2s.
  103. client.execute_hms_action("03008070", HMSAction.STOP_PRINTING, job_id="task-1")
  104. cmds = self._published_commands(client)
  105. assert cmds[0] == {
  106. "print": {
  107. "command": "stop",
  108. "param": "",
  109. "sequence_id": "0",
  110. }
  111. }
  112. assert "err" not in cmds[0]["print"]
  113. assert "job_id" not in cmds[0]["print"]
  114. def test_ignore_resume_dispatches_resume_when_print_paused(self, client):
  115. # Verified on H2D: idle_ignore is silently rejected while gcode_state
  116. # is PAUSE. The user's intent on a paused HMS modal is to continue,
  117. # so IGNORE_RESUME dispatches a plain resume instead. See #1830 §(2).
  118. client.state.state = "PAUSE"
  119. client.execute_hms_action("03008070", HMSAction.IGNORE_RESUME)
  120. cmds = self._published_commands(client)
  121. assert cmds[0] == {
  122. "print": {
  123. "command": "resume",
  124. "param": "",
  125. "sequence_id": "0",
  126. }
  127. }
  128. def test_ignore_resume_uses_idle_ignore_when_not_paused(self, client):
  129. # For non-pause warnings (e.g. AMS-side prompts during printing),
  130. # idle_ignore IS the correct command and the firmware honours it.
  131. client.state.state = "RUNNING"
  132. client.execute_hms_action("03008070", HMSAction.IGNORE_RESUME)
  133. cmds = self._published_commands(client)
  134. assert cmds[0] == {
  135. "print": {
  136. "command": "idle_ignore",
  137. "err": "03008070",
  138. "type": 0,
  139. "sequence_id": "0",
  140. }
  141. }
  142. def test_dont_remind_dispatches_resume_when_paused(self, client):
  143. # The persistent variant still degrades to resume on a paused print —
  144. # the "don't remind" flag can't ride along on a resume, but the user
  145. # clicked an action whose top-level intent is to continue, so we
  146. # honour that. The behavioural contract is documented in hms_ignore.
  147. client.state.state = "PAUSE"
  148. client.execute_hms_action("03008070", HMSAction.DONT_REMIND_NEXT_TIME)
  149. cmds = self._published_commands(client)
  150. assert cmds[0]["print"]["command"] == "resume"
  151. def test_dont_remind_uses_idle_ignore_type_one_when_not_paused(self, client):
  152. client.state.state = "RUNNING"
  153. client.execute_hms_action("03008070", HMSAction.DONT_REMIND_NEXT_TIME)
  154. cmds = self._published_commands(client)
  155. assert cmds[0]["print"]["command"] == "idle_ignore"
  156. assert cmds[0]["print"]["type"] == 1
  157. def test_idle_ignore_accepts_16_char_full_code(self, client):
  158. # hms[]-array faults carry a 16-char full identifier. The firmware
  159. # matches against the full 64-bit code; the truncated 8-char form
  160. # (used pre-#1830) was silently rejected on H2C.
  161. client.state.state = "RUNNING"
  162. client.execute_hms_action("0C00030000020010", HMSAction.IGNORE_RESUME)
  163. cmds = self._published_commands(client)
  164. assert cmds[0]["print"]["err"] == "0C00030000020010"
  165. def test_filament_extruded_sends_ams_done(self, client):
  166. client.execute_hms_action("07008029", HMSAction.FILAMENT_EXTRUDED)
  167. cmds = self._published_commands(client)
  168. assert cmds[0] == {"print": {"command": "ams_control", "param": "done", "sequence_id": "0"}}
  169. def test_retry_sends_ams_resume(self, client):
  170. client.execute_hms_action("07008029", HMSAction.RETRY_FILAMENT_EXTRUDED)
  171. cmds = self._published_commands(client)
  172. assert cmds[0]["print"]["param"] == "resume"
  173. assert cmds[0]["print"]["command"] == "ams_control"
  174. def test_abort_sends_ams_abort(self, client):
  175. client.execute_hms_action("07008029", HMSAction.ABORT)
  176. cmds = self._published_commands(client)
  177. assert cmds[0]["print"]["param"] == "abort"
  178. def test_ok_button_sends_bare_clean_print_error(self, client):
  179. # Matches the existing `clear_hms_errors` shape — no `print_error` body
  180. # field, which the original PR mistakenly added.
  181. client.execute_hms_action("03008070", HMSAction.OK_BUTTON)
  182. cmds = self._published_commands(client)
  183. assert cmds[0] == {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  184. def test_dbl_check_ok_sends_clean_then_uiop_close(self, client):
  185. client.execute_hms_action("03008070", HMSAction.DBL_CHECK_OK)
  186. cmds = self._published_commands(client)
  187. assert len(cmds) == 2
  188. assert cmds[0]["print"]["command"] == "clean_print_error"
  189. assert cmds[1]["system"]["command"] == "uiop"
  190. # `err` is the already-string short code, NOT `f"{x:08X}"` against a
  191. # str (which would TypeError on the old code path).
  192. assert cmds[1]["system"]["err"] == "03008070"
  193. def test_uiop_close_uppercases_lowercase_input(self, client):
  194. # Frontend may send the short code in either case; we normalise.
  195. client.execute_hms_action("0300abcd", HMSAction.DBL_CHECK_OK)
  196. cmds = self._published_commands(client)
  197. assert cmds[1]["system"]["err"] == "0300ABCD"
  198. def test_dbl_check_resume_is_plain_resume(self, client):
  199. # No err/job_id — explicitly different from RESUME_PRINTING.
  200. client.execute_hms_action("03008070", HMSAction.DBL_CHECK_RESUME)
  201. cmds = self._published_commands(client)
  202. assert cmds[0] == {"print": {"command": "resume", "param": "", "sequence_id": "0"}}
  203. assert "err" not in cmds[0]["print"]
  204. def test_refresh_nozzle(self, client):
  205. client.execute_hms_action("03008070", HMSAction.REFRESH_NOZZLE)
  206. cmds = self._published_commands(client)
  207. assert cmds[0] == {"print": {"command": "refresh_nozzle", "sequence_id": "0"}}
  208. def test_turn_off_fire_alarm_sends_buzzer_off(self, client):
  209. client.execute_hms_action("03008044", HMSAction.TURN_OFF_FIRE_ALARM)
  210. cmds = self._published_commands(client)
  211. assert cmds[0]["print"]["command"] == "buzzer_ctrl"
  212. assert cmds[0]["print"]["mode"] == 0
  213. def test_stop_drying_sends_auto_stop_ams_dry(self, client):
  214. client.execute_hms_action("07008017", HMSAction.STOP_DRYING)
  215. cmds = self._published_commands(client)
  216. assert cmds[0]["print"]["command"] == "auto_stop_ams_dry"
  217. def test_disable_purification_sends_close_air_filt(self, client):
  218. client.execute_hms_action("03008063", HMSAction.DISABLE_PURIFICATION)
  219. cmds = self._published_commands(client)
  220. assert cmds[0]["print"]["command"] == "close_air_filt"
  221. @pytest.mark.parametrize(
  222. "action",
  223. [
  224. HMSAction.CHECK_ASSISTANT,
  225. HMSAction.JUMP_TO_LIVEVIEW,
  226. HMSAction.OK_JUMP_RACK,
  227. HMSAction.REMOVE_CLOSE_BTN,
  228. HMSAction.LOAD_VIRTUAL_TRAY,
  229. HMSAction.CANCLE,
  230. HMSAction.DBL_CHECK_CANCEL,
  231. ],
  232. )
  233. def test_ui_only_actions_publish_nothing(self, client, action):
  234. # These actions exist for parity with BambuStudio's modal but have no
  235. # MQTT counterpart — the printer's own screen drives them.
  236. assert client.execute_hms_action("03008070", action) is True
  237. assert self._published_commands(client) == []
  238. def test_every_publish_is_followed_by_pushall(self, client):
  239. # The dispatcher pairs every command with a `pushing.pushall` echo so
  240. # the state stream refreshes on the next tick. Regression guard.
  241. client.execute_hms_action("03008070", HMSAction.RESUME_PRINTING)
  242. payloads = [json.loads(c.args[1]) for c in client._client.publish.call_args_list]
  243. assert any("pushing" in p for p in payloads)