test_bambu_mqtt.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. """
  2. Tests for the BambuMQTTClient service.
  3. These tests focus on timelapse tracking during prints.
  4. """
  5. import pytest
  6. class TestTimelapseTracking:
  7. """Tests for timelapse state tracking during prints."""
  8. @pytest.fixture
  9. def mqtt_client(self):
  10. """Create a BambuMQTTClient instance for testing."""
  11. from backend.app.services.bambu_mqtt import BambuMQTTClient
  12. client = BambuMQTTClient(
  13. ip_address="192.168.1.100",
  14. serial_number="TEST123",
  15. access_code="12345678",
  16. )
  17. return client
  18. def test_timelapse_flag_initializes_to_false(self, mqtt_client):
  19. """Verify _timelapse_during_print starts as False."""
  20. assert mqtt_client._timelapse_during_print is False
  21. def test_timelapse_flag_set_when_timelapse_active_during_running(self, mqtt_client):
  22. """Verify timelapse flag is set when timelapse is active while printing."""
  23. # Simulate print running
  24. mqtt_client._was_running = True
  25. mqtt_client.state.timelapse = False
  26. # Simulate xcam data showing timelapse is enabled
  27. xcam_data = {"timelapse": "enable"}
  28. mqtt_client._parse_xcam_data(xcam_data)
  29. assert mqtt_client.state.timelapse is True
  30. assert mqtt_client._timelapse_during_print is True
  31. def test_timelapse_flag_not_set_when_not_running(self, mqtt_client):
  32. """Verify timelapse flag is NOT set when printer not running."""
  33. # Printer is idle (not running)
  34. mqtt_client._was_running = False
  35. mqtt_client.state.timelapse = False
  36. # Timelapse is enabled but we're not printing
  37. xcam_data = {"timelapse": "enable"}
  38. mqtt_client._parse_xcam_data(xcam_data)
  39. assert mqtt_client.state.timelapse is True
  40. # Flag should NOT be set since we're not printing
  41. assert mqtt_client._timelapse_during_print is False
  42. def test_timelapse_flag_persists_after_timelapse_stops(self, mqtt_client):
  43. """Verify timelapse flag stays True even after recording stops."""
  44. # Simulate print running with timelapse
  45. mqtt_client._was_running = True
  46. # Enable timelapse during print
  47. xcam_data = {"timelapse": "enable"}
  48. mqtt_client._parse_xcam_data(xcam_data)
  49. assert mqtt_client._timelapse_during_print is True
  50. # Disable timelapse (recording stops at end of print)
  51. xcam_data = {"timelapse": "disable"}
  52. mqtt_client._parse_xcam_data(xcam_data)
  53. # Flag should still be True (persists until reset)
  54. assert mqtt_client.state.timelapse is False
  55. assert mqtt_client._timelapse_during_print is True
  56. def test_timelapse_flag_from_print_data(self, mqtt_client):
  57. """Verify timelapse flag is set from print data (not just xcam)."""
  58. # Simulate print running
  59. mqtt_client._was_running = True
  60. mqtt_client.state.timelapse = False
  61. mqtt_client._timelapse_during_print = False
  62. # Manually test the timelapse parsing logic from _parse_print_data
  63. # This tests the "timelapse" field in the main print data
  64. data = {"timelapse": True}
  65. mqtt_client.state.timelapse = data["timelapse"] is True
  66. if mqtt_client.state.timelapse and mqtt_client._was_running:
  67. mqtt_client._timelapse_during_print = True
  68. assert mqtt_client._timelapse_during_print is True
  69. class TestPrintCompletionWithTimelapse:
  70. """Tests for print completion including timelapse flag."""
  71. @pytest.fixture
  72. def mqtt_client(self):
  73. """Create a BambuMQTTClient instance for testing."""
  74. from backend.app.services.bambu_mqtt import BambuMQTTClient
  75. client = BambuMQTTClient(
  76. ip_address="192.168.1.100",
  77. serial_number="TEST123",
  78. access_code="12345678",
  79. )
  80. return client
  81. def test_print_complete_includes_timelapse_flag(self, mqtt_client):
  82. """Verify print complete callback includes timelapse_was_active."""
  83. # Set up completion callback
  84. callback_data = {}
  85. def on_complete(data):
  86. callback_data.update(data)
  87. mqtt_client.on_print_complete = on_complete
  88. # Simulate a print that had timelapse active
  89. mqtt_client._was_running = True
  90. mqtt_client._completion_triggered = False
  91. mqtt_client._timelapse_during_print = True
  92. mqtt_client._previous_gcode_state = "RUNNING"
  93. mqtt_client._previous_gcode_file = "test.gcode"
  94. mqtt_client.state.subtask_name = "Test Print"
  95. # Simulate print finish
  96. mqtt_client.state.state = "FINISH"
  97. # Manually trigger the completion logic (simplified)
  98. # In real code this happens in _parse_print_data
  99. should_trigger = (
  100. mqtt_client.state.state in ("FINISH", "FAILED")
  101. and not mqtt_client._completion_triggered
  102. and mqtt_client.on_print_complete
  103. and mqtt_client._previous_gcode_state == "RUNNING"
  104. )
  105. if should_trigger:
  106. status = "completed" if mqtt_client.state.state == "FINISH" else "failed"
  107. timelapse_was_active = mqtt_client._timelapse_during_print
  108. mqtt_client._completion_triggered = True
  109. mqtt_client._was_running = False
  110. mqtt_client._timelapse_during_print = False
  111. mqtt_client.on_print_complete(
  112. {
  113. "status": status,
  114. "filename": mqtt_client._previous_gcode_file,
  115. "subtask_name": mqtt_client.state.subtask_name,
  116. "timelapse_was_active": timelapse_was_active,
  117. }
  118. )
  119. assert "timelapse_was_active" in callback_data
  120. assert callback_data["timelapse_was_active"] is True
  121. def test_print_complete_timelapse_flag_false_when_no_timelapse(self, mqtt_client):
  122. """Verify timelapse_was_active is False when no timelapse during print."""
  123. callback_data = {}
  124. def on_complete(data):
  125. callback_data.update(data)
  126. mqtt_client.on_print_complete = on_complete
  127. # Print without timelapse
  128. mqtt_client._was_running = True
  129. mqtt_client._completion_triggered = False
  130. mqtt_client._timelapse_during_print = False # No timelapse
  131. mqtt_client._previous_gcode_state = "RUNNING"
  132. mqtt_client._previous_gcode_file = "test.gcode"
  133. mqtt_client.state.subtask_name = "Test Print"
  134. mqtt_client.state.state = "FINISH"
  135. # Trigger completion
  136. timelapse_was_active = mqtt_client._timelapse_during_print
  137. mqtt_client.on_print_complete(
  138. {
  139. "status": "completed",
  140. "filename": mqtt_client._previous_gcode_file,
  141. "subtask_name": mqtt_client.state.subtask_name,
  142. "timelapse_was_active": timelapse_was_active,
  143. }
  144. )
  145. assert callback_data["timelapse_was_active"] is False
  146. def test_timelapse_flag_reset_after_completion(self, mqtt_client):
  147. """Verify _timelapse_during_print is reset after print completion."""
  148. mqtt_client._timelapse_during_print = True
  149. mqtt_client._was_running = True
  150. mqtt_client._completion_triggered = False
  151. # Simulate completion reset
  152. mqtt_client._completion_triggered = True
  153. mqtt_client._was_running = False
  154. mqtt_client._timelapse_during_print = False
  155. assert mqtt_client._timelapse_during_print is False
  156. class TestRealisticMessageFlow:
  157. """Tests that simulate realistic MQTT message sequences.
  158. These tests process messages through _process_message to test the full flow,
  159. including the order of xcam parsing vs state detection.
  160. """
  161. @pytest.fixture
  162. def mqtt_client(self):
  163. """Create a BambuMQTTClient instance for testing."""
  164. from backend.app.services.bambu_mqtt import BambuMQTTClient
  165. client = BambuMQTTClient(
  166. ip_address="192.168.1.100",
  167. serial_number="TEST123",
  168. access_code="12345678",
  169. )
  170. return client
  171. def test_timelapse_detected_at_print_start_in_same_message(self, mqtt_client):
  172. """Test that timelapse is detected when xcam and state come in same message.
  173. This is the critical race condition test - xcam data is parsed BEFORE
  174. state detection, so the timelapse flag must be set AFTER _was_running is True.
  175. """
  176. # Callbacks to track events
  177. start_callback_data = {}
  178. def on_start(data):
  179. start_callback_data.update(data)
  180. mqtt_client.on_print_start = on_start
  181. # Initial state - idle
  182. mqtt_client._was_running = False
  183. mqtt_client._timelapse_during_print = False
  184. mqtt_client._previous_gcode_state = None
  185. # Simulate first message when print starts - contains both xcam and gcode_state
  186. # This is the realistic scenario from the printer
  187. # NOTE: Real MQTT messages wrap print data inside a "print" key
  188. payload = {
  189. "print": {
  190. "gcode_state": "RUNNING",
  191. "gcode_file": "/data/Metadata/test_print.gcode",
  192. "subtask_name": "Test_Print",
  193. "xcam": {
  194. "timelapse": "enable", # Timelapse is enabled in this print
  195. "printing_monitor": True,
  196. },
  197. "mc_percent": 0,
  198. "mc_remaining_time": 3600,
  199. }
  200. }
  201. # Process the message (this is what happens in real MQTT flow)
  202. mqtt_client._process_message(payload)
  203. # Verify timelapse was detected even though xcam is parsed before state
  204. assert mqtt_client._was_running is True, "_was_running should be True after RUNNING state"
  205. assert mqtt_client.state.timelapse is True, "state.timelapse should be True"
  206. assert mqtt_client._timelapse_during_print is True, (
  207. "timelapse_during_print should be True when timelapse is in the same message as RUNNING state"
  208. )
  209. def test_timelapse_not_detected_when_disabled(self, mqtt_client):
  210. """Test that timelapse is NOT detected when disabled in xcam data."""
  211. mqtt_client.on_print_start = lambda data: None
  212. # Initial state - idle
  213. mqtt_client._was_running = False
  214. mqtt_client._timelapse_during_print = False
  215. mqtt_client._previous_gcode_state = None
  216. # Print starts without timelapse
  217. payload = {
  218. "print": {
  219. "gcode_state": "RUNNING",
  220. "gcode_file": "/data/Metadata/test_print.gcode",
  221. "subtask_name": "Test_Print",
  222. "xcam": {
  223. "timelapse": "disable", # Timelapse is disabled
  224. "printing_monitor": True,
  225. },
  226. }
  227. }
  228. mqtt_client._process_message(payload)
  229. assert mqtt_client._was_running is True
  230. assert mqtt_client.state.timelapse is False
  231. assert mqtt_client._timelapse_during_print is False
  232. def test_timelapse_detected_when_enabled_after_print_start(self, mqtt_client):
  233. """Test timelapse detected when enabled in a message after print starts."""
  234. mqtt_client.on_print_start = lambda data: None
  235. # First message - print starts without timelapse info
  236. payload_start = {
  237. "print": {
  238. "gcode_state": "RUNNING",
  239. "gcode_file": "/data/Metadata/test_print.gcode",
  240. "subtask_name": "Test_Print",
  241. }
  242. }
  243. mqtt_client._process_message(payload_start)
  244. assert mqtt_client._was_running is True
  245. assert mqtt_client._timelapse_during_print is False # Not detected yet
  246. # Second message - xcam data arrives with timelapse enabled
  247. payload_xcam = {
  248. "print": {
  249. "gcode_state": "RUNNING",
  250. "gcode_file": "/data/Metadata/test_print.gcode",
  251. "subtask_name": "Test_Print",
  252. "xcam": {
  253. "timelapse": "enable",
  254. },
  255. }
  256. }
  257. mqtt_client._process_message(payload_xcam)
  258. # Now timelapse should be detected because _was_running is already True
  259. assert mqtt_client._timelapse_during_print is True
  260. def test_print_complete_includes_timelapse_flag_full_flow(self, mqtt_client):
  261. """Test full print lifecycle with timelapse - from start to completion."""
  262. start_data = {}
  263. complete_data = {}
  264. def on_start(data):
  265. start_data.update(data)
  266. def on_complete(data):
  267. complete_data.update(data)
  268. mqtt_client.on_print_start = on_start
  269. mqtt_client.on_print_complete = on_complete
  270. # 1. Print starts with timelapse
  271. mqtt_client._process_message(
  272. {
  273. "print": {
  274. "gcode_state": "RUNNING",
  275. "gcode_file": "/data/Metadata/test.gcode",
  276. "subtask_name": "Test",
  277. "xcam": {"timelapse": "enable"},
  278. }
  279. }
  280. )
  281. assert mqtt_client._timelapse_during_print is True
  282. assert "subtask_name" in start_data
  283. # 2. Print continues (multiple messages)
  284. for _ in range(3):
  285. mqtt_client._process_message(
  286. {
  287. "print": {
  288. "gcode_state": "RUNNING",
  289. "gcode_file": "/data/Metadata/test.gcode",
  290. "subtask_name": "Test",
  291. "mc_percent": 50,
  292. }
  293. }
  294. )
  295. # Timelapse flag should still be True
  296. assert mqtt_client._timelapse_during_print is True
  297. # 3. Print completes
  298. mqtt_client._process_message(
  299. {
  300. "print": {
  301. "gcode_state": "FINISH",
  302. "gcode_file": "/data/Metadata/test.gcode",
  303. "subtask_name": "Test",
  304. }
  305. }
  306. )
  307. # Verify completion callback received timelapse flag
  308. assert "timelapse_was_active" in complete_data
  309. assert complete_data["timelapse_was_active"] is True
  310. assert complete_data["status"] == "completed"
  311. # Flags should be reset after completion
  312. assert mqtt_client._timelapse_during_print is False
  313. assert mqtt_client._was_running is False
  314. def test_print_failed_includes_timelapse_flag(self, mqtt_client):
  315. """Test that failed print also includes timelapse flag."""
  316. complete_data = {}
  317. def on_complete(data):
  318. complete_data.update(data)
  319. mqtt_client.on_print_start = lambda data: None
  320. mqtt_client.on_print_complete = on_complete
  321. # Start with timelapse
  322. mqtt_client._process_message(
  323. {
  324. "print": {
  325. "gcode_state": "RUNNING",
  326. "gcode_file": "/data/Metadata/test.gcode",
  327. "subtask_name": "Test",
  328. "xcam": {"timelapse": "enable"},
  329. }
  330. }
  331. )
  332. # Print fails
  333. mqtt_client._process_message(
  334. {
  335. "print": {
  336. "gcode_state": "FAILED",
  337. "gcode_file": "/data/Metadata/test.gcode",
  338. "subtask_name": "Test",
  339. }
  340. }
  341. )
  342. assert complete_data["timelapse_was_active"] is True
  343. assert complete_data["status"] == "failed"
  344. class TestAMSDataMerging:
  345. """Tests for AMS data merging, particularly handling empty slots."""
  346. @pytest.fixture
  347. def mqtt_client(self):
  348. """Create a BambuMQTTClient instance for testing."""
  349. from backend.app.services.bambu_mqtt import BambuMQTTClient
  350. client = BambuMQTTClient(
  351. ip_address="192.168.1.100",
  352. serial_number="TEST123",
  353. access_code="12345678",
  354. )
  355. return client
  356. def test_empty_slot_clears_tray_type(self, mqtt_client):
  357. """Test that empty slot update clears tray_type (Issue #147).
  358. When a spool is removed from an old AMS, the printer sends empty values.
  359. These must overwrite the previous values to show the slot as empty.
  360. """
  361. # Initial state: AMS unit with a loaded spool
  362. initial_ams = {
  363. "ams": [
  364. {
  365. "id": 0,
  366. "tray": [
  367. {
  368. "id": 0,
  369. "tray_type": "PLA",
  370. "tray_sub_brands": "Bambu PLA Basic",
  371. "tray_color": "FF0000",
  372. "tag_uid": "1234567890ABCDEF",
  373. "remain": 80,
  374. }
  375. ],
  376. }
  377. ]
  378. }
  379. mqtt_client._handle_ams_data(initial_ams)
  380. # Verify initial state
  381. ams_data = mqtt_client.state.raw_data.get("ams", [])
  382. assert len(ams_data) == 1
  383. tray = ams_data[0]["tray"][0]
  384. assert tray["tray_type"] == "PLA"
  385. assert tray["tray_color"] == "FF0000"
  386. # Now simulate spool removal - printer sends empty values
  387. empty_update = {
  388. "ams": [
  389. {
  390. "id": 0,
  391. "tray": [
  392. {
  393. "id": 0,
  394. "tray_type": "", # Empty = slot is empty
  395. "tray_sub_brands": "",
  396. "tray_color": "",
  397. "tag_uid": "0000000000000000", # Zero UID
  398. "remain": 0,
  399. }
  400. ],
  401. }
  402. ]
  403. }
  404. mqtt_client._handle_ams_data(empty_update)
  405. # Verify empty values were applied (not ignored by merge logic)
  406. ams_data = mqtt_client.state.raw_data.get("ams", [])
  407. tray = ams_data[0]["tray"][0]
  408. assert tray["tray_type"] == "", "tray_type should be cleared when slot is empty"
  409. assert tray["tray_color"] == "", "tray_color should be cleared when slot is empty"
  410. assert tray["tray_sub_brands"] == "", "tray_sub_brands should be cleared"
  411. assert tray["tag_uid"] == "0000000000000000", "tag_uid should be cleared"
  412. def test_partial_update_preserves_other_fields(self, mqtt_client):
  413. """Test that partial updates still preserve non-slot-status fields."""
  414. # Initial state with full data
  415. initial_ams = {
  416. "ams": [
  417. {
  418. "id": 0,
  419. "humidity": "3",
  420. "temp": "25.5",
  421. "tray": [
  422. {
  423. "id": 0,
  424. "tray_type": "PLA",
  425. "tray_color": "00FF00",
  426. "remain": 90,
  427. "k": 0.02,
  428. }
  429. ],
  430. }
  431. ]
  432. }
  433. mqtt_client._handle_ams_data(initial_ams)
  434. # Partial update - only remain changes
  435. partial_update = {
  436. "ams": [
  437. {
  438. "id": 0,
  439. "tray": [
  440. {
  441. "id": 0,
  442. "remain": 85, # Only this changed
  443. }
  444. ],
  445. }
  446. ]
  447. }
  448. mqtt_client._handle_ams_data(partial_update)
  449. # Verify remain was updated but other fields preserved
  450. ams_data = mqtt_client.state.raw_data.get("ams", [])
  451. tray = ams_data[0]["tray"][0]
  452. assert tray["remain"] == 85, "remain should be updated"
  453. assert tray["tray_type"] == "PLA", "tray_type should be preserved"
  454. assert tray["tray_color"] == "00FF00", "tray_color should be preserved"
  455. assert tray["k"] == 0.02, "k should be preserved"
  456. def test_tray_exist_bits_clears_empty_slots(self, mqtt_client):
  457. """Test that tray_exist_bits clears slots marked as empty (Issue #147).
  458. New AMS models (AMS 2 Pro) don't send empty tray data when a spool is removed.
  459. Instead, they update tray_exist_bits to indicate which slots have spools.
  460. """
  461. # Initial state: AMS 0 and AMS 1 with loaded spools
  462. initial_ams = {
  463. "ams": [
  464. {
  465. "id": 0,
  466. "tray": [
  467. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  468. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00", "remain": 60},
  469. {"id": 2, "tray_type": "ABS", "tray_color": "0000FF", "remain": 40},
  470. {"id": 3, "tray_type": "TPU", "tray_color": "FFFF00", "remain": 20},
  471. ],
  472. },
  473. {
  474. "id": 1,
  475. "tray": [
  476. {"id": 0, "tray_type": "PLA", "tray_color": "FFFFFF", "remain": 90},
  477. {"id": 1, "tray_type": "PLA", "tray_color": "000000", "remain": 70},
  478. {"id": 2, "tray_type": "PLA", "tray_color": "FF00FF", "remain": 50},
  479. {"id": 3, "tray_type": "PLA", "tray_color": "00FFFF", "remain": 30},
  480. ],
  481. },
  482. ],
  483. "tray_exist_bits": "ff", # All 8 slots have spools (0xFF = 11111111)
  484. }
  485. mqtt_client._handle_ams_data(initial_ams)
  486. # Verify initial state
  487. ams_data = mqtt_client.state.raw_data.get("ams", [])
  488. assert ams_data[1]["tray"][3]["tray_type"] == "PLA" # AMS 1 slot 3 (B4) has spool
  489. # Now simulate spool removal from AMS 1 slot 3 (B4)
  490. # tray_exist_bits: 0x7f = 01111111 (bit 7 = 0 means AMS 1 slot 3 is empty)
  491. update_ams = {
  492. "ams": [
  493. {"id": 0, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]},
  494. {"id": 1, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]},
  495. ],
  496. "tray_exist_bits": "7f", # Bit 7 = 0 -> AMS 1 slot 3 is empty
  497. }
  498. mqtt_client._handle_ams_data(update_ams)
  499. # Verify AMS 1 slot 3 was cleared
  500. ams_data = mqtt_client.state.raw_data.get("ams", [])
  501. b4_tray = ams_data[1]["tray"][3]
  502. assert b4_tray["tray_type"] == "", "tray_type should be cleared for empty slot"
  503. assert b4_tray["remain"] == 0, "remain should be 0 for empty slot"
  504. # Verify other slots are preserved
  505. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "A1 should still have PLA"
  506. assert ams_data[1]["tray"][0]["tray_type"] == "PLA", "B1 should still have PLA"
  507. class TestNozzleRackData:
  508. """Tests for nozzle rack data parsing from H2 series device.nozzle.info."""
  509. @pytest.fixture
  510. def mqtt_client(self):
  511. """Create a BambuMQTTClient instance for testing."""
  512. from backend.app.services.bambu_mqtt import BambuMQTTClient
  513. client = BambuMQTTClient(
  514. ip_address="192.168.1.100",
  515. serial_number="TEST123",
  516. access_code="12345678",
  517. )
  518. return client
  519. def test_h2c_nozzle_rack_populated_with_8_entries(self, mqtt_client):
  520. """H2C provides 8 nozzle entries: IDs 0,1 (L/R hotend) + 16-21 (rack)."""
  521. payload = {
  522. "print": {
  523. "device": {
  524. "nozzle": {
  525. "info": [
  526. {
  527. "id": 0,
  528. "type": "HS",
  529. "diameter": "0.4",
  530. "wear": 5,
  531. "stat": 1,
  532. "max_temp": 300,
  533. "serial_number": "SN-L",
  534. },
  535. {
  536. "id": 1,
  537. "type": "HS",
  538. "diameter": "0.4",
  539. "wear": 3,
  540. "stat": 0,
  541. "max_temp": 300,
  542. "serial_number": "SN-R",
  543. },
  544. {
  545. "id": 16,
  546. "type": "HS",
  547. "diameter": "0.4",
  548. "wear": 10,
  549. "stat": 0,
  550. "max_temp": 300,
  551. "serial_number": "SN-16",
  552. },
  553. {
  554. "id": 17,
  555. "type": "HH01",
  556. "diameter": "0.6",
  557. "wear": 0,
  558. "stat": 0,
  559. "max_temp": 300,
  560. "serial_number": "SN-17",
  561. },
  562. {
  563. "id": 18,
  564. "type": "HS",
  565. "diameter": "0.4",
  566. "wear": 2,
  567. "stat": 0,
  568. "max_temp": 300,
  569. "serial_number": "SN-18",
  570. },
  571. {
  572. "id": 19,
  573. "type": "",
  574. "diameter": "",
  575. "wear": None,
  576. "stat": None,
  577. "max_temp": 0,
  578. "serial_number": "",
  579. },
  580. {
  581. "id": 20,
  582. "type": "",
  583. "diameter": "",
  584. "wear": None,
  585. "stat": None,
  586. "max_temp": 0,
  587. "serial_number": "",
  588. },
  589. {
  590. "id": 21,
  591. "type": "",
  592. "diameter": "",
  593. "wear": None,
  594. "stat": None,
  595. "max_temp": 0,
  596. "serial_number": "",
  597. },
  598. ]
  599. }
  600. }
  601. }
  602. }
  603. mqtt_client._process_message(payload)
  604. assert len(mqtt_client.state.nozzle_rack) == 8
  605. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  606. assert ids == [0, 1, 16, 17, 18, 19, 20, 21]
  607. def test_h2d_nozzle_rack_populated_with_2_entries(self, mqtt_client):
  608. """H2D provides 2 nozzle entries: IDs 0,1 (L/R hotend) — no rack slots."""
  609. payload = {
  610. "print": {
  611. "device": {
  612. "nozzle": {
  613. "info": [
  614. {
  615. "id": 0,
  616. "type": "HS",
  617. "diameter": "0.4",
  618. "wear": 5,
  619. "stat": 1,
  620. "max_temp": 300,
  621. "serial_number": "SN-L",
  622. },
  623. {
  624. "id": 1,
  625. "type": "HS",
  626. "diameter": "0.4",
  627. "wear": 3,
  628. "stat": 1,
  629. "max_temp": 300,
  630. "serial_number": "SN-R",
  631. },
  632. ]
  633. }
  634. }
  635. }
  636. }
  637. mqtt_client._process_message(payload)
  638. assert len(mqtt_client.state.nozzle_rack) == 2
  639. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  640. assert ids == [0, 1]
  641. def test_single_nozzle_h2s_populated(self, mqtt_client):
  642. """H2S provides 1 nozzle entry: ID 0 only — single nozzle printer."""
  643. payload = {
  644. "print": {
  645. "device": {
  646. "nozzle": {
  647. "info": [
  648. {
  649. "id": 0,
  650. "type": "HS",
  651. "diameter": "0.4",
  652. "wear": 2,
  653. "stat": 1,
  654. "max_temp": 300,
  655. "serial_number": "SN-0",
  656. },
  657. ]
  658. }
  659. }
  660. }
  661. }
  662. mqtt_client._process_message(payload)
  663. assert len(mqtt_client.state.nozzle_rack) == 1
  664. assert mqtt_client.state.nozzle_rack[0]["id"] == 0
  665. def test_empty_nozzle_info_does_not_populate_rack(self, mqtt_client):
  666. """Empty nozzle info list should not populate nozzle_rack."""
  667. payload = {"print": {"device": {"nozzle": {"info": []}}}}
  668. mqtt_client._process_message(payload)
  669. assert mqtt_client.state.nozzle_rack == []
  670. def test_nozzle_rack_sorted_by_id(self, mqtt_client):
  671. """Nozzle rack entries should be sorted by ID regardless of input order."""
  672. payload = {
  673. "print": {
  674. "device": {
  675. "nozzle": {
  676. "info": [
  677. {"id": 17, "type": "HS", "diameter": "0.6"},
  678. {"id": 0, "type": "HS", "diameter": "0.4"},
  679. {"id": 16, "type": "HS", "diameter": "0.4"},
  680. {"id": 1, "type": "HS", "diameter": "0.4"},
  681. ]
  682. }
  683. }
  684. }
  685. }
  686. mqtt_client._process_message(payload)
  687. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  688. assert ids == [0, 1, 16, 17]
  689. def test_nozzle_rack_field_mapping(self, mqtt_client):
  690. """Verify field mapping from MQTT nozzle_info to nozzle_rack dict keys."""
  691. payload = {
  692. "print": {
  693. "device": {
  694. "nozzle": {
  695. "info": [
  696. {
  697. "id": 16,
  698. "type": "HH01",
  699. "diameter": "0.6",
  700. "wear": 15,
  701. "stat": 0,
  702. "max_temp": 320,
  703. "serial_number": "SN-ABC123",
  704. "filament_colour": "FF8800",
  705. "filament_id": "F42",
  706. "tray_type": "ABS",
  707. }
  708. ]
  709. }
  710. }
  711. }
  712. }
  713. mqtt_client._process_message(payload)
  714. slot = mqtt_client.state.nozzle_rack[0]
  715. assert slot["id"] == 16
  716. assert slot["type"] == "HH01"
  717. assert slot["diameter"] == "0.6"
  718. assert slot["wear"] == 15
  719. assert slot["stat"] == 0
  720. assert slot["max_temp"] == 320
  721. assert slot["serial_number"] == "SN-ABC123"
  722. assert slot["filament_color"] == "FF8800"
  723. assert slot["filament_id"] == "F42"
  724. assert slot["filament_type"] == "ABS"
  725. def test_nozzle_info_updates_nozzle_state(self, mqtt_client):
  726. """Nozzle info for IDs 0,1 should also update nozzle state (type/diameter)."""
  727. payload = {
  728. "print": {
  729. "device": {
  730. "nozzle": {
  731. "info": [
  732. {"id": 0, "type": "HS", "diameter": "0.4"},
  733. {"id": 1, "type": "HH01", "diameter": "0.6"},
  734. ]
  735. }
  736. }
  737. }
  738. }
  739. mqtt_client._process_message(payload)
  740. assert mqtt_client.state.nozzles[0].nozzle_type == "HS"
  741. assert mqtt_client.state.nozzles[0].nozzle_diameter == "0.4"
  742. assert mqtt_client.state.nozzles[1].nozzle_type == "HH01"
  743. assert mqtt_client.state.nozzles[1].nozzle_diameter == "0.6"
  744. class TestRequestTopicAmsMapping:
  745. """Tests for capturing ams_mapping from the MQTT request topic."""
  746. @pytest.fixture
  747. def mqtt_client(self):
  748. """Create a BambuMQTTClient instance for testing."""
  749. from backend.app.services.bambu_mqtt import BambuMQTTClient
  750. client = BambuMQTTClient(
  751. ip_address="192.168.1.100",
  752. serial_number="TEST123",
  753. access_code="12345678",
  754. )
  755. return client
  756. def test_captured_ams_mapping_initializes_to_none(self, mqtt_client):
  757. """Verify _captured_ams_mapping starts as None."""
  758. assert mqtt_client._captured_ams_mapping is None
  759. def test_handle_request_message_captures_ams_mapping(self, mqtt_client):
  760. """project_file command with ams_mapping stores the mapping."""
  761. data = {
  762. "print": {
  763. "command": "project_file",
  764. "ams_mapping": [0, 4, -1, -1],
  765. "url": "ftp://192.168.1.100/test.3mf",
  766. }
  767. }
  768. mqtt_client._handle_request_message(data)
  769. assert mqtt_client._captured_ams_mapping == [0, 4, -1, -1]
  770. def test_handle_request_message_ignores_non_print_commands(self, mqtt_client):
  771. """Non-project_file commands don't store ams_mapping."""
  772. data = {
  773. "print": {
  774. "command": "pause",
  775. }
  776. }
  777. mqtt_client._handle_request_message(data)
  778. assert mqtt_client._captured_ams_mapping is None
  779. def test_handle_request_message_ignores_missing_ams_mapping(self, mqtt_client):
  780. """project_file command without ams_mapping doesn't store anything."""
  781. data = {
  782. "print": {
  783. "command": "project_file",
  784. "url": "ftp://192.168.1.100/test.3mf",
  785. }
  786. }
  787. mqtt_client._handle_request_message(data)
  788. assert mqtt_client._captured_ams_mapping is None
  789. def test_handle_request_message_ignores_non_dict_print(self, mqtt_client):
  790. """Non-dict print value is safely ignored."""
  791. data = {"print": "not_a_dict"}
  792. mqtt_client._handle_request_message(data)
  793. assert mqtt_client._captured_ams_mapping is None
  794. def test_handle_request_message_ignores_missing_print(self, mqtt_client):
  795. """Message without print key is safely ignored."""
  796. data = {"pushing": {"command": "pushall"}}
  797. mqtt_client._handle_request_message(data)
  798. assert mqtt_client._captured_ams_mapping is None
  799. def test_captured_mapping_overwrites_previous(self, mqtt_client):
  800. """A new print command overwrites a previously captured mapping."""
  801. mqtt_client._captured_ams_mapping = [0, -1, -1, -1]
  802. data = {
  803. "print": {
  804. "command": "project_file",
  805. "ams_mapping": [4, 8, -1, -1],
  806. }
  807. }
  808. mqtt_client._handle_request_message(data)
  809. assert mqtt_client._captured_ams_mapping == [4, 8, -1, -1]
  810. def test_print_start_callback_includes_ams_mapping(self, mqtt_client):
  811. """on_print_start callback data includes captured ams_mapping."""
  812. start_data = {}
  813. def on_start(data):
  814. start_data.update(data)
  815. mqtt_client.on_print_start = on_start
  816. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  817. # Trigger print start
  818. mqtt_client._process_message(
  819. {
  820. "print": {
  821. "gcode_state": "RUNNING",
  822. "gcode_file": "/data/Metadata/test.gcode",
  823. "subtask_name": "Test",
  824. }
  825. }
  826. )
  827. assert start_data.get("ams_mapping") == [0, 4, -1, -1]
  828. def test_print_start_callback_ams_mapping_none_when_not_captured(self, mqtt_client):
  829. """on_print_start callback has ams_mapping=None when no mapping captured."""
  830. start_data = {}
  831. def on_start(data):
  832. start_data.update(data)
  833. mqtt_client.on_print_start = on_start
  834. mqtt_client._process_message(
  835. {
  836. "print": {
  837. "gcode_state": "RUNNING",
  838. "gcode_file": "/data/Metadata/test.gcode",
  839. "subtask_name": "Test",
  840. }
  841. }
  842. )
  843. assert "ams_mapping" in start_data
  844. assert start_data["ams_mapping"] is None
  845. def test_print_complete_callback_includes_ams_mapping(self, mqtt_client):
  846. """on_print_complete callback data includes captured ams_mapping."""
  847. complete_data = {}
  848. def on_complete(data):
  849. complete_data.update(data)
  850. mqtt_client.on_print_start = lambda d: None
  851. mqtt_client.on_print_complete = on_complete
  852. mqtt_client._captured_ams_mapping = [0, 9, -1, -1]
  853. # Start print
  854. mqtt_client._process_message(
  855. {
  856. "print": {
  857. "gcode_state": "RUNNING",
  858. "gcode_file": "/data/Metadata/test.gcode",
  859. "subtask_name": "Test",
  860. }
  861. }
  862. )
  863. # Complete print
  864. mqtt_client._process_message(
  865. {
  866. "print": {
  867. "gcode_state": "FINISH",
  868. "gcode_file": "/data/Metadata/test.gcode",
  869. "subtask_name": "Test",
  870. }
  871. }
  872. )
  873. assert complete_data.get("ams_mapping") == [0, 9, -1, -1]
  874. def test_captured_mapping_cleared_after_print_complete(self, mqtt_client):
  875. """_captured_ams_mapping is reset to None after print completion."""
  876. mqtt_client.on_print_start = lambda d: None
  877. mqtt_client.on_print_complete = lambda d: None
  878. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  879. # Start print
  880. mqtt_client._process_message(
  881. {
  882. "print": {
  883. "gcode_state": "RUNNING",
  884. "gcode_file": "/data/Metadata/test.gcode",
  885. "subtask_name": "Test",
  886. }
  887. }
  888. )
  889. # Complete print
  890. mqtt_client._process_message(
  891. {
  892. "print": {
  893. "gcode_state": "FINISH",
  894. "gcode_file": "/data/Metadata/test.gcode",
  895. "subtask_name": "Test",
  896. }
  897. }
  898. )
  899. assert mqtt_client._captured_ams_mapping is None
  900. def test_full_flow_capture_and_deliver(self, mqtt_client):
  901. """Full flow: slicer sends print command → MQTT captures mapping → completion delivers it."""
  902. complete_data = {}
  903. def on_complete(data):
  904. complete_data.update(data)
  905. mqtt_client.on_print_start = lambda d: None
  906. mqtt_client.on_print_complete = on_complete
  907. # 1. Slicer sends print command (captured from request topic)
  908. mqtt_client._handle_request_message(
  909. {
  910. "print": {
  911. "command": "project_file",
  912. "ams_mapping": [4, 9, -1, -1],
  913. "url": "ftp://192.168.1.100/model.3mf",
  914. }
  915. }
  916. )
  917. assert mqtt_client._captured_ams_mapping == [4, 9, -1, -1]
  918. # 2. Printer reports RUNNING
  919. mqtt_client._process_message(
  920. {
  921. "print": {
  922. "gcode_state": "RUNNING",
  923. "gcode_file": "/data/Metadata/model.gcode",
  924. "subtask_name": "Model",
  925. }
  926. }
  927. )
  928. # 3. Printer reports FINISH
  929. mqtt_client._process_message(
  930. {
  931. "print": {
  932. "gcode_state": "FINISH",
  933. "gcode_file": "/data/Metadata/model.gcode",
  934. "subtask_name": "Model",
  935. }
  936. }
  937. )
  938. assert complete_data["ams_mapping"] == [4, 9, -1, -1]
  939. assert complete_data["status"] == "completed"
  940. # Mapping cleared after completion
  941. assert mqtt_client._captured_ams_mapping is None