test_hms_actions.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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_sends_bambustudio_ignore_command_paused(self, client):
  115. # IGNORE_RESUME dispatches BambuStudio's `command_hms_ignore`
  116. # (DeviceManager.cpp:1450) — `command: "ignore"`, not `resume` and
  117. # not `idle_ignore`. The firmware handles both "skip this check on the
  118. # next attempt" and "resume the paused print" in one operation.
  119. # The previous Bambuddy code redirected to plain resume, which caused
  120. # wrong-plate to re-pause 1-2 s after the user clicked Ignore (#1869).
  121. # `err` is the DECIMAL int representation of the hex error code.
  122. client.state.state = "PAUSE"
  123. client.execute_hms_action("05008051", HMSAction.IGNORE_RESUME, job_id="task-7")
  124. cmds = self._published_commands(client)
  125. assert cmds[0] == {
  126. "print": {
  127. "command": "ignore",
  128. "err": str(0x05008051), # "83918929"
  129. "param": "reserve",
  130. "job_id": "task-7",
  131. "sequence_id": "0",
  132. }
  133. }
  134. def test_ignore_resume_state_independent(self, client):
  135. # BambuStudio's DeviceErrorDialog dispatches IGNORE_RESUME via
  136. # `command_hms_ignore` unconditionally — there's no PAUSE-vs-RUNNING
  137. # branch. Bambuddy's previous code special-cased PAUSE to a plain
  138. # resume; the BambuStudio shape works in both states.
  139. client.state.state = "RUNNING"
  140. client.execute_hms_action("05008051", HMSAction.IGNORE_RESUME)
  141. cmds = self._published_commands(client)
  142. assert cmds[0]["print"]["command"] == "ignore"
  143. assert cmds[0]["print"]["err"] == str(0x05008051)
  144. def test_ignore_no_reminder_uses_ignore_command_not_idle_ignore(self, client):
  145. # BambuStudio routes IGNORE_NO_REMINDER_NEXT_TIME and
  146. # DONT_REMIND_NEXT_TIME to the same `command_hms_ignore` as
  147. # IGNORE_RESUME (DeviceErrorDialog.cpp:596-602) — the "don't remind"
  148. # half is the firmware's responsibility, the wire shape is identical.
  149. client.state.state = "PAUSE"
  150. client.execute_hms_action("03008070", HMSAction.DONT_REMIND_NEXT_TIME, job_id="task-1")
  151. cmds = self._published_commands(client)
  152. assert cmds[0] == {
  153. "print": {
  154. "command": "ignore",
  155. "err": str(0x03008070),
  156. "param": "reserve",
  157. "job_id": "task-1",
  158. "sequence_id": "0",
  159. }
  160. }
  161. def test_no_reminder_next_time_uses_idle_ignore_type_zero(self, client):
  162. # NO_REMINDER_NEXT_TIME (distinct from IGNORE_NO_REMINDER_NEXT_TIME)
  163. # is BambuStudio's `command_hms_idle_ignore` with type=0
  164. # (DeviceErrorDialog.cpp:588-590). Dismisses the dialog without
  165. # resuming. The `err` is the same decimal-int format as the ignore
  166. # command — same `m_error_code` is passed in BambuStudio.
  167. client.state.state = "RUNNING"
  168. client.execute_hms_action("03008070", HMSAction.NO_REMINDER_NEXT_TIME)
  169. cmds = self._published_commands(client)
  170. assert cmds[0] == {
  171. "print": {
  172. "command": "idle_ignore",
  173. "err": str(0x03008070),
  174. "type": 0,
  175. "sequence_id": "0",
  176. }
  177. }
  178. def test_ignore_accepts_16_char_full_code_as_decimal(self, client):
  179. # hms[]-array faults carry a 16-char full identifier. Bambu's firmware
  180. # matches `err` as a numeric string, so the 16-char hex parses to a
  181. # 64-bit int and serializes back as its decimal form.
  182. client.state.state = "PAUSE"
  183. client.execute_hms_action("0C00030000020010", HMSAction.IGNORE_RESUME)
  184. cmds = self._published_commands(client)
  185. assert cmds[0]["print"]["command"] == "ignore"
  186. assert cmds[0]["print"]["err"] == str(0x0C00030000020010)
  187. def test_ignore_with_no_job_id_sends_empty_string(self, client):
  188. # BambuStudio's `command_hms_ignore` always passes `m_obj->job_id_`
  189. # (a `std::string` — empty when there's no active subtask). Match the
  190. # shape: empty string, not None / missing key.
  191. client.state.state = "PAUSE"
  192. client.execute_hms_action("05008051", HMSAction.IGNORE_RESUME, job_id=None)
  193. cmds = self._published_commands(client)
  194. assert cmds[0]["print"]["job_id"] == ""
  195. def test_filament_extruded_sends_ams_done(self, client):
  196. client.execute_hms_action("07008029", HMSAction.FILAMENT_EXTRUDED)
  197. cmds = self._published_commands(client)
  198. assert cmds[0] == {"print": {"command": "ams_control", "param": "done", "sequence_id": "0"}}
  199. def test_retry_sends_ams_resume(self, client):
  200. client.execute_hms_action("07008029", HMSAction.RETRY_FILAMENT_EXTRUDED)
  201. cmds = self._published_commands(client)
  202. assert cmds[0]["print"]["param"] == "resume"
  203. assert cmds[0]["print"]["command"] == "ams_control"
  204. def test_abort_sends_ams_abort(self, client):
  205. client.execute_hms_action("07008029", HMSAction.ABORT)
  206. cmds = self._published_commands(client)
  207. assert cmds[0]["print"]["param"] == "abort"
  208. def test_ok_button_sends_bare_clean_print_error(self, client):
  209. # Matches the existing `clear_hms_errors` shape — no `print_error` body
  210. # field, which the original PR mistakenly added.
  211. client.execute_hms_action("03008070", HMSAction.OK_BUTTON)
  212. cmds = self._published_commands(client)
  213. assert cmds[0] == {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  214. def test_dbl_check_ok_sends_clean_then_uiop_close(self, client):
  215. client.execute_hms_action("03008070", HMSAction.DBL_CHECK_OK)
  216. cmds = self._published_commands(client)
  217. assert len(cmds) == 2
  218. assert cmds[0]["print"]["command"] == "clean_print_error"
  219. assert cmds[1]["system"]["command"] == "uiop"
  220. # `err` is the already-string short code, NOT `f"{x:08X}"` against a
  221. # str (which would TypeError on the old code path).
  222. assert cmds[1]["system"]["err"] == "03008070"
  223. def test_uiop_close_uppercases_lowercase_input(self, client):
  224. # Frontend may send the short code in either case; we normalise.
  225. client.execute_hms_action("0300abcd", HMSAction.DBL_CHECK_OK)
  226. cmds = self._published_commands(client)
  227. assert cmds[1]["system"]["err"] == "0300ABCD"
  228. def test_dbl_check_resume_is_plain_resume(self, client):
  229. # No err/job_id — explicitly different from RESUME_PRINTING.
  230. client.execute_hms_action("03008070", HMSAction.DBL_CHECK_RESUME)
  231. cmds = self._published_commands(client)
  232. assert cmds[0] == {"print": {"command": "resume", "param": "", "sequence_id": "0"}}
  233. assert "err" not in cmds[0]["print"]
  234. def test_refresh_nozzle(self, client):
  235. client.execute_hms_action("03008070", HMSAction.REFRESH_NOZZLE)
  236. cmds = self._published_commands(client)
  237. assert cmds[0] == {"print": {"command": "refresh_nozzle", "sequence_id": "0"}}
  238. def test_turn_off_fire_alarm_sends_buzzer_off(self, client):
  239. client.execute_hms_action("03008044", HMSAction.TURN_OFF_FIRE_ALARM)
  240. cmds = self._published_commands(client)
  241. assert cmds[0]["print"]["command"] == "buzzer_ctrl"
  242. assert cmds[0]["print"]["mode"] == 0
  243. def test_stop_drying_sends_auto_stop_ams_dry(self, client):
  244. client.execute_hms_action("07008017", HMSAction.STOP_DRYING)
  245. cmds = self._published_commands(client)
  246. assert cmds[0]["print"]["command"] == "auto_stop_ams_dry"
  247. def test_disable_purification_sends_close_air_filt(self, client):
  248. client.execute_hms_action("03008063", HMSAction.DISABLE_PURIFICATION)
  249. cmds = self._published_commands(client)
  250. assert cmds[0]["print"]["command"] == "close_air_filt"
  251. @pytest.mark.parametrize(
  252. "action",
  253. [
  254. HMSAction.CHECK_ASSISTANT,
  255. HMSAction.JUMP_TO_LIVEVIEW,
  256. HMSAction.OK_JUMP_RACK,
  257. HMSAction.REMOVE_CLOSE_BTN,
  258. HMSAction.LOAD_VIRTUAL_TRAY,
  259. HMSAction.CANCLE,
  260. HMSAction.DBL_CHECK_CANCEL,
  261. ],
  262. )
  263. def test_ui_only_actions_publish_nothing(self, client, action):
  264. # These actions exist for parity with BambuStudio's modal but have no
  265. # MQTT counterpart — the printer's own screen drives them.
  266. assert client.execute_hms_action("03008070", action) is True
  267. assert self._published_commands(client) == []
  268. def test_every_publish_is_followed_by_pushall(self, client):
  269. # The dispatcher pairs every command with a `pushing.pushall` echo so
  270. # the state stream refreshes on the next tick. Regression guard.
  271. client.execute_hms_action("03008070", HMSAction.RESUME_PRINTING)
  272. payloads = [json.loads(c.args[1]) for c in client._client.publish.call_args_list]
  273. assert any("pushing" in p for p in payloads)