test_nozzle_rack_mapping_2800.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. """Nozzle-rack (H2C) dispatch mapping — #2800.
  2. The H2C mounts one of six rack hotends on its right carriage. Dispatch has to
  3. name the *physical* rack position, not the extruder index every other
  4. dual-nozzle printer uses; get it wrong and the printer cleans and levels with
  5. one nozzle, then prints with another several millimetres off the bed.
  6. Nothing in the queue knew the rack position, so these jobs shipped with no
  7. `nozzle_mapping` at all and the firmware picked for itself.
  8. """
  9. import json
  10. import zipfile
  11. import pytest
  12. from backend.app.services.bambu_mqtt import (
  13. _RACK_WIRE_SLOTS,
  14. BambuMQTTClient,
  15. resolve_rack_nozzle_mapping,
  16. )
  17. from backend.app.utils.printer_models import is_nozzle_rack_model
  18. from backend.app.utils.threemf_tools import extract_slot_extruders_from_3mf
  19. class TestIsNozzleRackModel:
  20. @pytest.mark.parametrize("model", ["H2C", "h2c", " H2C ", "O1C", "O1C2"])
  21. def test_h2c_spellings_and_codes(self, model):
  22. """The printer row may hold either the display name or the SSDP code."""
  23. assert is_nozzle_rack_model(model) is True
  24. @pytest.mark.parametrize("model", ["H2D", "H2D Pro", "H2S", "X2D", "P1S", "O1D", "N6", "", None])
  25. def test_everything_else_is_not_a_rack_model(self, model):
  26. """Other dual-nozzle printers must keep the plain extruder-index wire."""
  27. assert is_nozzle_rack_model(model) is False
  28. class TestResolveRackNozzleMapping:
  29. def test_rack_slot_takes_the_live_rack_position(self):
  30. mapping = resolve_rack_nozzle_mapping([1], rack_nozzle_id=17)
  31. assert mapping is not None
  32. assert len(mapping) == _RACK_WIRE_SLOTS
  33. assert mapping[0] == 17
  34. assert set(mapping[1:]) == {-1}
  35. def test_the_fixed_hotend_takes_its_own_physical_id(self):
  36. """Both carriages are translated; neither extruder index reaches the wire.
  37. Sending the index for the fixed side (0) is what the printer rejected
  38. outright on hardware — it would not start the job at all.
  39. """
  40. mapping = resolve_rack_nozzle_mapping([0, 1], rack_nozzle_id=21)
  41. assert mapping[:2] == [1, 21]
  42. def test_unprinted_slots_stay_unset(self):
  43. mapping = resolve_rack_nozzle_mapping([1, -1, 1], rack_nozzle_id=16)
  44. assert mapping[:3] == [16, -1, 16]
  45. @pytest.mark.parametrize("rack_id", [None, 0, 1, 15, 22, 255])
  46. def test_no_usable_rack_position_omits_the_field(self, rack_id):
  47. """Mid-swap or stale state must fall back to the firmware's own pick.
  48. Guessing here is what prints in mid-air, so returning None (and
  49. omitting nozzle_mapping) is the intended failure mode.
  50. """
  51. assert resolve_rack_nozzle_mapping([1], rack_nozzle_id=rack_id) is None
  52. def test_job_that_never_uses_the_rack_is_left_alone(self):
  53. """BambuStudio omits nozzle_mapping for a fixed-hotend-only plate.
  54. Captured from the reporter's H2C: a plate sliced for the fixed side
  55. alone carries ams_mapping and no nozzle_mapping field at all, so
  56. naming a nozzle here would depart from what the printer expects.
  57. """
  58. assert resolve_rack_nozzle_mapping([0, 0], rack_nozzle_id=17) is None
  59. @pytest.mark.parametrize("unknown", [2, 3, 31])
  60. def test_a_carriage_the_h2c_does_not_have_omits_the_field(self, unknown):
  61. """A third index means the file was mapped for another machine.
  62. Forwarding it raw would name a physical nozzle by a number that does
  63. not identify one, which is the class of mistake #2800 was.
  64. """
  65. assert resolve_rack_nozzle_mapping([unknown, 1], rack_nozzle_id=17) is None
  66. @pytest.mark.parametrize(
  67. "bad_slots",
  68. [
  69. ["a", 1], # non-numeric
  70. [{}, 1], # nested object
  71. [[0], 1], # nested list
  72. [0.5, 1], # fractional
  73. [True, 1], # bool would reach the wire as JSON `true`
  74. "1", # not a list at all
  75. ],
  76. )
  77. def test_junk_input_returns_none_and_never_raises(self, bad_slots):
  78. """Nothing above this raises: `start_print` builds the MQTT command
  79. with no exception handler, and by then the queue item is already
  80. committed as `printing`. A bad value has to degrade to "firmware
  81. picks", not wedge the item in a state no print will leave."""
  82. assert resolve_rack_nozzle_mapping(bad_slots, rack_nozzle_id=17) is None
  83. @pytest.mark.parametrize("bad_rack", [[17], {"id": 17}, "17", 17.0, True])
  84. def test_junk_rack_position_returns_none_and_never_raises(self, bad_rack):
  85. assert resolve_rack_nozzle_mapping([1], rack_nozzle_id=bad_rack) is None
  86. def test_none_entries_read_as_unprinted(self):
  87. assert resolve_rack_nozzle_mapping([None, 1], rack_nozzle_id=17)[:2] == [-1, 17]
  88. def test_hardware_confirmed_mixed_nozzle_plate(self):
  89. """The exact job the reporter ran on an H2C, both ways round.
  90. Dispatched as [17, -1, -1, 1] the rack nozzle printed several
  91. millimetres above the bed; dispatched as [1, -1, -1, 17] the same
  92. sliced file printed correctly on both nozzles and completed. Native
  93. BambuStudio captures of mixed plates on the same machine carry
  94. [1, 17, ...] and [17, 1, ...] depending on filament slot order.
  95. """
  96. wire = resolve_rack_nozzle_mapping([0, -1, -1, 1], rack_nozzle_id=17)
  97. assert wire[:4] == [1, -1, -1, 17]
  98. assert set(wire[4:]) == {-1}
  99. swapped = resolve_rack_nozzle_mapping([1, 0], rack_nozzle_id=17)
  100. assert swapped[:2] == [17, 1]
  101. def test_more_slots_than_the_wire_carries(self):
  102. assert resolve_rack_nozzle_mapping([1] * (_RACK_WIRE_SLOTS + 1), rack_nozzle_id=17) is None
  103. def test_empty_mapping(self):
  104. assert resolve_rack_nozzle_mapping([], rack_nozzle_id=17) is None
  105. class TestRackPositionFromMqtt:
  106. @pytest.fixture
  107. def client(self):
  108. return BambuMQTTClient(
  109. ip_address="192.168.1.100",
  110. serial_number="TEST-H2C",
  111. access_code="12345678",
  112. model="H2C",
  113. )
  114. def test_src_and_tar_are_captured(self, client):
  115. client._update_state({"device": {"nozzle": {"src_id": 16, "tar_id": 19}}})
  116. assert client.state.nozzle_rack_src_id == 16
  117. assert client.state.nozzle_rack_tar_id == 19
  118. def test_absent_key_does_not_clear_the_last_known_value(self, client):
  119. """The firmware only pushes these when they change."""
  120. client._update_state({"device": {"nozzle": {"src_id": 16, "tar_id": 19}}})
  121. client._update_state({"device": {"nozzle": {"info": []}}})
  122. assert client.state.nozzle_rack_tar_id == 19
  123. def test_unparseable_value_is_ignored(self, client):
  124. client._update_state({"device": {"nozzle": {"tar_id": 19}}})
  125. client._update_state({"device": {"nozzle": {"tar_id": "nonsense"}}})
  126. assert client.state.nozzle_rack_tar_id == 19
  127. def test_starts_unknown(self, client):
  128. assert client.state.nozzle_rack_src_id is None
  129. assert client.state.nozzle_rack_tar_id is None
  130. class TestDispatch:
  131. """What actually reaches the wire."""
  132. def _client(self, model):
  133. from unittest.mock import MagicMock
  134. client = BambuMQTTClient(
  135. ip_address="192.168.1.100",
  136. serial_number="TEST-DISPATCH",
  137. access_code="12345678",
  138. model=model,
  139. )
  140. client._client = MagicMock()
  141. client.state.connected = True
  142. client._is_dual_nozzle = True
  143. return client
  144. def _print_cmd(self, client):
  145. return json.loads(client._client.publish.call_args[0][1])["print"]
  146. def test_rack_model_resolves_slot_extruders(self):
  147. client = self._client("H2C")
  148. client.state.nozzle_rack_tar_id = 18
  149. client.start_print("job.3mf", nozzle_slot_extruders=json.dumps([1, -1, 1]))
  150. cmd = self._print_cmd(client)
  151. assert cmd["nozzle_mapping"][:3] == [18, -1, 18]
  152. def test_src_id_used_when_tar_id_is_not_a_rack_position(self):
  153. """Between swaps the printer can report a settled src_id and nothing else."""
  154. client = self._client("H2C")
  155. client.state.nozzle_rack_src_id = 20
  156. client.state.nozzle_rack_tar_id = 0
  157. client.start_print("job.3mf", nozzle_slot_extruders=json.dumps([1]))
  158. assert self._print_cmd(client)["nozzle_mapping"][0] == 20
  159. def test_unknown_rack_position_omits_the_field(self):
  160. client = self._client("H2C")
  161. client.start_print("job.3mf", nozzle_slot_extruders=json.dumps([1]))
  162. assert "nozzle_mapping" not in self._print_cmd(client)
  163. def test_studio_capture_is_never_overridden(self):
  164. """A real capture is authoritative; the derived fallback must stand down."""
  165. client = self._client("H2C")
  166. client.state.nozzle_rack_tar_id = 18
  167. client.start_print(
  168. "job.3mf",
  169. nozzle_mapping=json.dumps([16, -1, -1, 1]),
  170. nozzle_slot_extruders=json.dumps([1, -1, 1]),
  171. )
  172. assert self._print_cmd(client)["nozzle_mapping"] == [16, -1, -1, 1]
  173. def test_other_dual_nozzle_models_are_untouched(self):
  174. """H2D has no rack: its extruder indices are already the wire values."""
  175. client = self._client("H2D")
  176. client.state.nozzle_rack_tar_id = 18
  177. client.start_print("job.3mf", nozzle_slot_extruders=json.dumps([0, 1]))
  178. assert "nozzle_mapping" not in self._print_cmd(client)
  179. def test_malformed_slot_extruders_is_logged_and_omitted(self, caplog):
  180. client = self._client("H2C")
  181. client.state.nozzle_rack_tar_id = 18
  182. with caplog.at_level("WARNING"):
  183. client.start_print("job.3mf", nozzle_slot_extruders="not json {")
  184. assert "nozzle_mapping" not in self._print_cmd(client)
  185. assert any("Invalid nozzle_slot_extruders" in rec.message for rec in caplog.records)
  186. def test_absent_slot_extruders_changes_nothing(self):
  187. client = self._client("H2C")
  188. client.state.nozzle_rack_tar_id = 18
  189. client.start_print("job.3mf")
  190. assert "nozzle_mapping" not in self._print_cmd(client)
  191. def _write_dual_nozzle_3mf(path, group_by_slot):
  192. """Minimal 3MF carrying just what the nozzle extractor reads.
  193. physical_extruder_map is [1, 0] as Bambu ships it, so slicer group 0 comes
  194. out as MQTT extruder index 1 and group 1 as index 0. On the H2C index 1 is
  195. the rack carriage — confirmed on hardware in #2800, and the reason the
  196. rack-side fixture below slices its filaments into group 0.
  197. """
  198. filaments = "".join(f'<filament id="{slot}" group_id="{group}"/>' for slot, group in group_by_slot.items())
  199. with zipfile.ZipFile(path, "w") as zf:
  200. zf.writestr(
  201. "Metadata/project_settings.config",
  202. json.dumps(
  203. {
  204. "physical_extruder_map": [1, 0],
  205. "extruder_nozzle_stats": ["Standard#1", "Standard#1"],
  206. }
  207. ),
  208. )
  209. zf.writestr("Metadata/slice_info.config", f"<config><plate>{filaments}</plate></config>")
  210. return path
  211. class TestSlotExtrudersFromFile:
  212. def test_derives_dense_per_slot_extruders(self, tmp_path):
  213. """Slots 1 and 3 print from the fixed hotend; slot 2 is unused."""
  214. source = _write_dual_nozzle_3mf(tmp_path / "job.3mf", {1: 1, 3: 1})
  215. assert extract_slot_extruders_from_3mf(source) == [0, -1, 0]
  216. def test_end_to_end_reaches_the_rack_position(self, tmp_path):
  217. """The reported failure: a two-slot job that must print from the rack."""
  218. source = _write_dual_nozzle_3mf(tmp_path / "job.3mf", {1: 0, 3: 0})
  219. assert extract_slot_extruders_from_3mf(source) == [1, -1, 1]
  220. wire = resolve_rack_nozzle_mapping(extract_slot_extruders_from_3mf(source), rack_nozzle_id=17)
  221. assert wire[:3] == [17, -1, 17]
  222. def test_both_extruders(self, tmp_path):
  223. """One slot per carriage — the mixed job that printed in mid-air."""
  224. source = _write_dual_nozzle_3mf(tmp_path / "job.3mf", {1: 0, 2: 1})
  225. assert extract_slot_extruders_from_3mf(source) == [1, 0]
  226. wire = resolve_rack_nozzle_mapping(extract_slot_extruders_from_3mf(source), rack_nozzle_id=17)
  227. assert wire[:2] == [17, 1]
  228. def test_single_nozzle_file_yields_nothing(self, tmp_path):
  229. path = tmp_path / "single.3mf"
  230. with zipfile.ZipFile(path, "w") as zf:
  231. zf.writestr("Metadata/project_settings.config", json.dumps({"physical_extruder_map": [0]}))
  232. assert extract_slot_extruders_from_3mf(path) is None
  233. def test_unreadable_file_is_not_fatal(self, tmp_path):
  234. path = tmp_path / "broken.3mf"
  235. path.write_bytes(b"not a zip")
  236. assert extract_slot_extruders_from_3mf(path) is None
  237. @pytest.mark.parametrize("slot_id", [50000000, 65, 0, -3])
  238. def test_out_of_range_slot_ids_are_rejected(self, tmp_path, slot_id):
  239. """Slot IDs are whatever the file claims, and this builds a dense list.
  240. Without a ceiling a corrupt or hostile 3MF declaring
  241. `filament id="50000000"` allocates a fifty-million-entry list on the
  242. dispatch path.
  243. """
  244. source = _write_dual_nozzle_3mf(tmp_path / f"s{abs(slot_id)}.3mf", {slot_id: 1})
  245. assert extract_slot_extruders_from_3mf(source) is None