test_bambu_mqtt.py 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976
  1. """
  2. Tests for the BambuMQTTClient service.
  3. These tests focus on timelapse tracking during prints.
  4. """
  5. import json
  6. import pytest
  7. class TestTimelapseTracking:
  8. """Tests for timelapse state tracking during prints."""
  9. @pytest.fixture
  10. def mqtt_client(self):
  11. """Create a BambuMQTTClient instance for testing."""
  12. from backend.app.services.bambu_mqtt import BambuMQTTClient
  13. client = BambuMQTTClient(
  14. ip_address="192.168.1.100",
  15. serial_number="TEST123",
  16. access_code="12345678",
  17. )
  18. return client
  19. def test_timelapse_flag_initializes_to_false(self, mqtt_client):
  20. """Verify _timelapse_during_print starts as False."""
  21. assert mqtt_client._timelapse_during_print is False
  22. def test_timelapse_flag_set_when_timelapse_active_during_running(self, mqtt_client):
  23. """Verify timelapse flag is set when timelapse is active while printing."""
  24. # Simulate print running
  25. mqtt_client._was_running = True
  26. mqtt_client.state.timelapse = False
  27. # Simulate xcam data showing timelapse is enabled
  28. xcam_data = {"timelapse": "enable"}
  29. mqtt_client._parse_xcam_data(xcam_data)
  30. assert mqtt_client.state.timelapse is True
  31. assert mqtt_client._timelapse_during_print is True
  32. def test_timelapse_flag_not_set_when_not_running(self, mqtt_client):
  33. """Verify timelapse flag is NOT set when printer not running."""
  34. # Printer is idle (not running)
  35. mqtt_client._was_running = False
  36. mqtt_client.state.timelapse = False
  37. # Timelapse is enabled but we're not printing
  38. xcam_data = {"timelapse": "enable"}
  39. mqtt_client._parse_xcam_data(xcam_data)
  40. assert mqtt_client.state.timelapse is True
  41. # Flag should NOT be set since we're not printing
  42. assert mqtt_client._timelapse_during_print is False
  43. def test_timelapse_flag_persists_after_timelapse_stops(self, mqtt_client):
  44. """Verify timelapse flag stays True even after recording stops."""
  45. # Simulate print running with timelapse
  46. mqtt_client._was_running = True
  47. # Enable timelapse during print
  48. xcam_data = {"timelapse": "enable"}
  49. mqtt_client._parse_xcam_data(xcam_data)
  50. assert mqtt_client._timelapse_during_print is True
  51. # Disable timelapse (recording stops at end of print)
  52. xcam_data = {"timelapse": "disable"}
  53. mqtt_client._parse_xcam_data(xcam_data)
  54. # Flag should still be True (persists until reset)
  55. assert mqtt_client.state.timelapse is False
  56. assert mqtt_client._timelapse_during_print is True
  57. def test_timelapse_flag_from_print_data(self, mqtt_client):
  58. """Verify timelapse flag is set from print data (not just xcam)."""
  59. # Simulate print running
  60. mqtt_client._was_running = True
  61. mqtt_client.state.timelapse = False
  62. mqtt_client._timelapse_during_print = False
  63. # Manually test the timelapse parsing logic from _parse_print_data
  64. # This tests the "timelapse" field in the main print data
  65. data = {"timelapse": True}
  66. mqtt_client.state.timelapse = data["timelapse"] is True
  67. if mqtt_client.state.timelapse and mqtt_client._was_running:
  68. mqtt_client._timelapse_during_print = True
  69. assert mqtt_client._timelapse_during_print is True
  70. class TestPrintCompletionWithTimelapse:
  71. """Tests for print completion including timelapse flag."""
  72. @pytest.fixture
  73. def mqtt_client(self):
  74. """Create a BambuMQTTClient instance for testing."""
  75. from backend.app.services.bambu_mqtt import BambuMQTTClient
  76. client = BambuMQTTClient(
  77. ip_address="192.168.1.100",
  78. serial_number="TEST123",
  79. access_code="12345678",
  80. )
  81. return client
  82. def test_print_complete_includes_timelapse_flag(self, mqtt_client):
  83. """Verify print complete callback includes timelapse_was_active."""
  84. # Set up completion callback
  85. callback_data = {}
  86. def on_complete(data):
  87. callback_data.update(data)
  88. mqtt_client.on_print_complete = on_complete
  89. # Simulate a print that had timelapse active
  90. mqtt_client._was_running = True
  91. mqtt_client._completion_triggered = False
  92. mqtt_client._timelapse_during_print = True
  93. mqtt_client._previous_gcode_state = "RUNNING"
  94. mqtt_client._previous_gcode_file = "test.gcode"
  95. mqtt_client.state.subtask_name = "Test Print"
  96. # Simulate print finish
  97. mqtt_client.state.state = "FINISH"
  98. # Manually trigger the completion logic (simplified)
  99. # In real code this happens in _parse_print_data
  100. should_trigger = (
  101. mqtt_client.state.state in ("FINISH", "FAILED")
  102. and not mqtt_client._completion_triggered
  103. and mqtt_client.on_print_complete
  104. and mqtt_client._previous_gcode_state == "RUNNING"
  105. )
  106. if should_trigger:
  107. status = "completed" if mqtt_client.state.state == "FINISH" else "failed"
  108. timelapse_was_active = mqtt_client._timelapse_during_print
  109. mqtt_client._completion_triggered = True
  110. mqtt_client._was_running = False
  111. mqtt_client._timelapse_during_print = False
  112. mqtt_client.on_print_complete(
  113. {
  114. "status": status,
  115. "filename": mqtt_client._previous_gcode_file,
  116. "subtask_name": mqtt_client.state.subtask_name,
  117. "timelapse_was_active": timelapse_was_active,
  118. }
  119. )
  120. assert "timelapse_was_active" in callback_data
  121. assert callback_data["timelapse_was_active"] is True
  122. def test_print_complete_timelapse_flag_false_when_no_timelapse(self, mqtt_client):
  123. """Verify timelapse_was_active is False when no timelapse during print."""
  124. callback_data = {}
  125. def on_complete(data):
  126. callback_data.update(data)
  127. mqtt_client.on_print_complete = on_complete
  128. # Print without timelapse
  129. mqtt_client._was_running = True
  130. mqtt_client._completion_triggered = False
  131. mqtt_client._timelapse_during_print = False # No timelapse
  132. mqtt_client._previous_gcode_state = "RUNNING"
  133. mqtt_client._previous_gcode_file = "test.gcode"
  134. mqtt_client.state.subtask_name = "Test Print"
  135. mqtt_client.state.state = "FINISH"
  136. # Trigger completion
  137. timelapse_was_active = mqtt_client._timelapse_during_print
  138. mqtt_client.on_print_complete(
  139. {
  140. "status": "completed",
  141. "filename": mqtt_client._previous_gcode_file,
  142. "subtask_name": mqtt_client.state.subtask_name,
  143. "timelapse_was_active": timelapse_was_active,
  144. }
  145. )
  146. assert callback_data["timelapse_was_active"] is False
  147. def test_timelapse_flag_reset_after_completion(self, mqtt_client):
  148. """Verify _timelapse_during_print is reset after print completion."""
  149. mqtt_client._timelapse_during_print = True
  150. mqtt_client._was_running = True
  151. mqtt_client._completion_triggered = False
  152. # Simulate completion reset
  153. mqtt_client._completion_triggered = True
  154. mqtt_client._was_running = False
  155. mqtt_client._timelapse_during_print = False
  156. assert mqtt_client._timelapse_during_print is False
  157. class TestRealisticMessageFlow:
  158. """Tests that simulate realistic MQTT message sequences.
  159. These tests process messages through _process_message to test the full flow,
  160. including the order of xcam parsing vs state detection.
  161. """
  162. @pytest.fixture
  163. def mqtt_client(self):
  164. """Create a BambuMQTTClient instance for testing."""
  165. from backend.app.services.bambu_mqtt import BambuMQTTClient
  166. client = BambuMQTTClient(
  167. ip_address="192.168.1.100",
  168. serial_number="TEST123",
  169. access_code="12345678",
  170. )
  171. return client
  172. def test_timelapse_detected_at_print_start_in_same_message(self, mqtt_client):
  173. """Test that timelapse is detected when xcam and state come in same message.
  174. This is the critical race condition test - xcam data is parsed BEFORE
  175. state detection, so the timelapse flag must be set AFTER _was_running is True.
  176. """
  177. # Callbacks to track events
  178. start_callback_data = {}
  179. def on_start(data):
  180. start_callback_data.update(data)
  181. mqtt_client.on_print_start = on_start
  182. # Initial state - idle
  183. mqtt_client._was_running = False
  184. mqtt_client._timelapse_during_print = False
  185. mqtt_client._previous_gcode_state = None
  186. # Simulate first message when print starts - contains both xcam and gcode_state
  187. # This is the realistic scenario from the printer
  188. # NOTE: Real MQTT messages wrap print data inside a "print" key
  189. payload = {
  190. "print": {
  191. "gcode_state": "RUNNING",
  192. "gcode_file": "/data/Metadata/test_print.gcode",
  193. "subtask_name": "Test_Print",
  194. "xcam": {
  195. "timelapse": "enable", # Timelapse is enabled in this print
  196. "printing_monitor": True,
  197. },
  198. "mc_percent": 0,
  199. "mc_remaining_time": 3600,
  200. }
  201. }
  202. # Process the message (this is what happens in real MQTT flow)
  203. mqtt_client._process_message(payload)
  204. # Verify timelapse was detected even though xcam is parsed before state
  205. assert mqtt_client._was_running is True, "_was_running should be True after RUNNING state"
  206. assert mqtt_client.state.timelapse is True, "state.timelapse should be True"
  207. assert mqtt_client._timelapse_during_print is True, (
  208. "timelapse_during_print should be True when timelapse is in the same message as RUNNING state"
  209. )
  210. def test_timelapse_not_detected_when_disabled(self, mqtt_client):
  211. """Test that timelapse is NOT detected when disabled in xcam data."""
  212. mqtt_client.on_print_start = lambda data: None
  213. # Initial state - idle
  214. mqtt_client._was_running = False
  215. mqtt_client._timelapse_during_print = False
  216. mqtt_client._previous_gcode_state = None
  217. # Print starts without timelapse
  218. payload = {
  219. "print": {
  220. "gcode_state": "RUNNING",
  221. "gcode_file": "/data/Metadata/test_print.gcode",
  222. "subtask_name": "Test_Print",
  223. "xcam": {
  224. "timelapse": "disable", # Timelapse is disabled
  225. "printing_monitor": True,
  226. },
  227. }
  228. }
  229. mqtt_client._process_message(payload)
  230. assert mqtt_client._was_running is True
  231. assert mqtt_client.state.timelapse is False
  232. assert mqtt_client._timelapse_during_print is False
  233. def test_timelapse_detected_when_enabled_after_print_start(self, mqtt_client):
  234. """Test timelapse detected when enabled in a message after print starts."""
  235. mqtt_client.on_print_start = lambda data: None
  236. # First message - print starts without timelapse info
  237. payload_start = {
  238. "print": {
  239. "gcode_state": "RUNNING",
  240. "gcode_file": "/data/Metadata/test_print.gcode",
  241. "subtask_name": "Test_Print",
  242. }
  243. }
  244. mqtt_client._process_message(payload_start)
  245. assert mqtt_client._was_running is True
  246. assert mqtt_client._timelapse_during_print is False # Not detected yet
  247. # Second message - xcam data arrives with timelapse enabled
  248. payload_xcam = {
  249. "print": {
  250. "gcode_state": "RUNNING",
  251. "gcode_file": "/data/Metadata/test_print.gcode",
  252. "subtask_name": "Test_Print",
  253. "xcam": {
  254. "timelapse": "enable",
  255. },
  256. }
  257. }
  258. mqtt_client._process_message(payload_xcam)
  259. # Now timelapse should be detected because _was_running is already True
  260. assert mqtt_client._timelapse_during_print is True
  261. def test_print_complete_includes_timelapse_flag_full_flow(self, mqtt_client):
  262. """Test full print lifecycle with timelapse - from start to completion."""
  263. start_data = {}
  264. complete_data = {}
  265. def on_start(data):
  266. start_data.update(data)
  267. def on_complete(data):
  268. complete_data.update(data)
  269. mqtt_client.on_print_start = on_start
  270. mqtt_client.on_print_complete = on_complete
  271. # 1. Print starts with timelapse
  272. mqtt_client._process_message(
  273. {
  274. "print": {
  275. "gcode_state": "RUNNING",
  276. "gcode_file": "/data/Metadata/test.gcode",
  277. "subtask_name": "Test",
  278. "xcam": {"timelapse": "enable"},
  279. }
  280. }
  281. )
  282. assert mqtt_client._timelapse_during_print is True
  283. assert "subtask_name" in start_data
  284. # 2. Print continues (multiple messages)
  285. for _ in range(3):
  286. mqtt_client._process_message(
  287. {
  288. "print": {
  289. "gcode_state": "RUNNING",
  290. "gcode_file": "/data/Metadata/test.gcode",
  291. "subtask_name": "Test",
  292. "mc_percent": 50,
  293. }
  294. }
  295. )
  296. # Timelapse flag should still be True
  297. assert mqtt_client._timelapse_during_print is True
  298. # 3. Print completes
  299. mqtt_client._process_message(
  300. {
  301. "print": {
  302. "gcode_state": "FINISH",
  303. "gcode_file": "/data/Metadata/test.gcode",
  304. "subtask_name": "Test",
  305. }
  306. }
  307. )
  308. # Verify completion callback received timelapse flag
  309. assert "timelapse_was_active" in complete_data
  310. assert complete_data["timelapse_was_active"] is True
  311. assert complete_data["status"] == "completed"
  312. # Flags should be reset after completion
  313. assert mqtt_client._timelapse_during_print is False
  314. assert mqtt_client._was_running is False
  315. def test_print_failed_includes_timelapse_flag(self, mqtt_client):
  316. """Test that failed print also includes timelapse flag."""
  317. complete_data = {}
  318. def on_complete(data):
  319. complete_data.update(data)
  320. mqtt_client.on_print_start = lambda data: None
  321. mqtt_client.on_print_complete = on_complete
  322. # Start with timelapse
  323. mqtt_client._process_message(
  324. {
  325. "print": {
  326. "gcode_state": "RUNNING",
  327. "gcode_file": "/data/Metadata/test.gcode",
  328. "subtask_name": "Test",
  329. "xcam": {"timelapse": "enable"},
  330. }
  331. }
  332. )
  333. # Print fails
  334. mqtt_client._process_message(
  335. {
  336. "print": {
  337. "gcode_state": "FAILED",
  338. "gcode_file": "/data/Metadata/test.gcode",
  339. "subtask_name": "Test",
  340. }
  341. }
  342. )
  343. assert complete_data["timelapse_was_active"] is True
  344. assert complete_data["status"] == "failed"
  345. class TestAMSDataMerging:
  346. """Tests for AMS data merging, particularly handling empty slots."""
  347. @pytest.fixture
  348. def mqtt_client(self):
  349. """Create a BambuMQTTClient instance for testing."""
  350. from backend.app.services.bambu_mqtt import BambuMQTTClient
  351. client = BambuMQTTClient(
  352. ip_address="192.168.1.100",
  353. serial_number="TEST123",
  354. access_code="12345678",
  355. )
  356. return client
  357. def test_empty_slot_clears_tray_type(self, mqtt_client):
  358. """Test that empty slot update clears tray_type (Issue #147).
  359. When a spool is removed from an old AMS, the printer sends empty values.
  360. These must overwrite the previous values to show the slot as empty.
  361. """
  362. # Initial state: AMS unit with a loaded spool
  363. initial_ams = {
  364. "ams": [
  365. {
  366. "id": 0,
  367. "tray": [
  368. {
  369. "id": 0,
  370. "tray_type": "PLA",
  371. "tray_sub_brands": "Bambu PLA Basic",
  372. "tray_color": "FF0000",
  373. "tag_uid": "1234567890ABCDEF",
  374. "remain": 80,
  375. }
  376. ],
  377. }
  378. ]
  379. }
  380. mqtt_client._handle_ams_data(initial_ams)
  381. # Verify initial state
  382. ams_data = mqtt_client.state.raw_data.get("ams", [])
  383. assert len(ams_data) == 1
  384. tray = ams_data[0]["tray"][0]
  385. assert tray["tray_type"] == "PLA"
  386. assert tray["tray_color"] == "FF0000"
  387. # Now simulate spool removal - printer sends empty values
  388. empty_update = {
  389. "ams": [
  390. {
  391. "id": 0,
  392. "tray": [
  393. {
  394. "id": 0,
  395. "tray_type": "", # Empty = slot is empty
  396. "tray_sub_brands": "",
  397. "tray_color": "",
  398. "tag_uid": "0000000000000000", # Zero UID
  399. "remain": 0,
  400. }
  401. ],
  402. }
  403. ]
  404. }
  405. mqtt_client._handle_ams_data(empty_update)
  406. # Verify empty values were applied (not ignored by merge logic)
  407. ams_data = mqtt_client.state.raw_data.get("ams", [])
  408. tray = ams_data[0]["tray"][0]
  409. assert tray["tray_type"] == "", "tray_type should be cleared when slot is empty"
  410. assert tray["tray_color"] == "", "tray_color should be cleared when slot is empty"
  411. assert tray["tray_sub_brands"] == "", "tray_sub_brands should be cleared"
  412. assert tray["tag_uid"] == "0000000000000000", "tag_uid should be cleared"
  413. def test_partial_update_preserves_other_fields(self, mqtt_client):
  414. """Test that partial updates still preserve non-slot-status fields."""
  415. # Initial state with full data
  416. initial_ams = {
  417. "ams": [
  418. {
  419. "id": 0,
  420. "humidity": "3",
  421. "temp": "25.5",
  422. "tray": [
  423. {
  424. "id": 0,
  425. "tray_type": "PLA",
  426. "tray_color": "00FF00",
  427. "remain": 90,
  428. "k": 0.02,
  429. }
  430. ],
  431. }
  432. ]
  433. }
  434. mqtt_client._handle_ams_data(initial_ams)
  435. # Partial update - only remain changes
  436. partial_update = {
  437. "ams": [
  438. {
  439. "id": 0,
  440. "tray": [
  441. {
  442. "id": 0,
  443. "remain": 85, # Only this changed
  444. }
  445. ],
  446. }
  447. ]
  448. }
  449. mqtt_client._handle_ams_data(partial_update)
  450. # Verify remain was updated but other fields preserved
  451. ams_data = mqtt_client.state.raw_data.get("ams", [])
  452. tray = ams_data[0]["tray"][0]
  453. assert tray["remain"] == 85, "remain should be updated"
  454. assert tray["tray_type"] == "PLA", "tray_type should be preserved"
  455. assert tray["tray_color"] == "00FF00", "tray_color should be preserved"
  456. assert tray["k"] == 0.02, "k should be preserved"
  457. def test_tray_exist_bits_clears_empty_slots(self, mqtt_client):
  458. """Test that tray_exist_bits clears slots marked as empty (Issue #147).
  459. New AMS models (AMS 2 Pro) don't send empty tray data when a spool is removed.
  460. Instead, they update tray_exist_bits to indicate which slots have spools.
  461. """
  462. # Initial state: AMS 0 and AMS 1 with loaded spools
  463. initial_ams = {
  464. "ams": [
  465. {
  466. "id": 0,
  467. "tray": [
  468. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  469. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00", "remain": 60},
  470. {"id": 2, "tray_type": "ABS", "tray_color": "0000FF", "remain": 40},
  471. {"id": 3, "tray_type": "TPU", "tray_color": "FFFF00", "remain": 20},
  472. ],
  473. },
  474. {
  475. "id": 1,
  476. "tray": [
  477. {"id": 0, "tray_type": "PLA", "tray_color": "FFFFFF", "remain": 90},
  478. {"id": 1, "tray_type": "PLA", "tray_color": "000000", "remain": 70},
  479. {"id": 2, "tray_type": "PLA", "tray_color": "FF00FF", "remain": 50},
  480. {"id": 3, "tray_type": "PLA", "tray_color": "00FFFF", "remain": 30},
  481. ],
  482. },
  483. ],
  484. "tray_exist_bits": "ff", # All 8 slots have spools (0xFF = 11111111)
  485. }
  486. mqtt_client._handle_ams_data(initial_ams)
  487. # Verify initial state
  488. ams_data = mqtt_client.state.raw_data.get("ams", [])
  489. assert ams_data[1]["tray"][3]["tray_type"] == "PLA" # AMS 1 slot 3 (B4) has spool
  490. # Now simulate spool removal from AMS 1 slot 3 (B4)
  491. # tray_exist_bits: 0x7f = 01111111 (bit 7 = 0 means AMS 1 slot 3 is empty)
  492. update_ams = {
  493. "ams": [
  494. {"id": 0, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]},
  495. {"id": 1, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]},
  496. ],
  497. "tray_exist_bits": "7f", # Bit 7 = 0 -> AMS 1 slot 3 is empty
  498. }
  499. mqtt_client._handle_ams_data(update_ams)
  500. # Verify AMS 1 slot 3 was cleared
  501. ams_data = mqtt_client.state.raw_data.get("ams", [])
  502. b4_tray = ams_data[1]["tray"][3]
  503. assert b4_tray["tray_type"] == "", "tray_type should be cleared for empty slot"
  504. assert b4_tray["remain"] == 0, "remain should be 0 for empty slot"
  505. # Verify other slots are preserved
  506. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "A1 should still have PLA"
  507. assert ams_data[1]["tray"][0]["tray_type"] == "PLA", "B1 should still have PLA"
  508. def test_shutdown_message_preserves_ams_data(self, mqtt_client):
  509. """Printer shutdown (power_on_flag=False) must not wipe AMS slot data (#765).
  510. When a printer shuts down it sends a final MQTT message with
  511. tray_exist_bits='0' and power_on_flag=False. This all-zero value
  512. previously caused every slot to be cleared, which then triggered
  513. auto-unlink of all spool assignments on reconnect.
  514. """
  515. # Initial state: two AMS units with loaded spools
  516. initial_ams = {
  517. "ams": [
  518. {
  519. "id": 0,
  520. "tray": [
  521. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF", "remain": 80},
  522. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00FF", "remain": 60},
  523. ],
  524. },
  525. {
  526. "id": 1,
  527. "tray": [
  528. {"id": 0, "tray_type": "PETG", "tray_color": "DBDDD9FF", "remain": 90},
  529. {"id": 1, "tray_type": "PETG", "tray_color": "67DB25FF", "remain": 70},
  530. ],
  531. },
  532. ],
  533. "tray_exist_bits": "33", # Slots 0,1 of each AMS (0b00110011)
  534. "power_on_flag": True,
  535. }
  536. mqtt_client._handle_ams_data(initial_ams)
  537. # Verify initial state
  538. ams_data = mqtt_client.state.raw_data["ams"]
  539. assert ams_data[0]["tray"][0]["tray_type"] == "PLA"
  540. assert ams_data[1]["tray"][0]["tray_type"] == "PETG"
  541. # Simulate printer shutdown — all-zero bits with power_on_flag=False
  542. shutdown_ams = {
  543. "ams_exist_bits": "0",
  544. "tray_exist_bits": "0",
  545. "power_on_flag": False,
  546. "insert_flag": False,
  547. "tray_now": "0",
  548. "version": 0,
  549. }
  550. mqtt_client._handle_ams_data(shutdown_ams)
  551. # AMS slot data MUST be preserved — shutdown should not clear it
  552. ams_data = mqtt_client.state.raw_data["ams"]
  553. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "Shutdown must not clear AMS 0 slot 0"
  554. assert ams_data[0]["tray"][0]["tray_color"] == "FF0000FF", "Shutdown must not clear AMS 0 slot 0 color"
  555. assert ams_data[0]["tray"][1]["tray_type"] == "PETG", "Shutdown must not clear AMS 0 slot 1"
  556. assert ams_data[1]["tray"][0]["tray_type"] == "PETG", "Shutdown must not clear AMS 1 slot 0"
  557. assert ams_data[1]["tray"][1]["tray_type"] == "PETG", "Shutdown must not clear AMS 1 slot 1"
  558. def test_genuine_removal_still_clears_with_power_on(self, mqtt_client):
  559. """Genuine spool removal (power_on_flag=True) must still clear slot data.
  560. Ensures the #765 fix doesn't break normal spool removal detection.
  561. """
  562. # Initial state: AMS with loaded spool
  563. initial_ams = {
  564. "ams": [
  565. {
  566. "id": 0,
  567. "tray": [
  568. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  569. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00", "remain": 60},
  570. ],
  571. },
  572. ],
  573. "tray_exist_bits": "3", # Both slots occupied (0b11)
  574. "power_on_flag": True,
  575. }
  576. mqtt_client._handle_ams_data(initial_ams)
  577. # Spool removed from slot 1 while printer is running
  578. removal_ams = {
  579. "ams": [
  580. {
  581. "id": 0,
  582. "tray": [{"id": 0}, {"id": 1}],
  583. },
  584. ],
  585. "tray_exist_bits": "1", # Only slot 0 occupied (0b01)
  586. "power_on_flag": True,
  587. }
  588. mqtt_client._handle_ams_data(removal_ams)
  589. # Slot 0 preserved, slot 1 cleared
  590. ams_data = mqtt_client.state.raw_data["ams"]
  591. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "Slot 0 should be preserved"
  592. assert ams_data[0]["tray"][1]["tray_type"] == "", "Slot 1 should be cleared on removal"
  593. assert ams_data[0]["tray"][1]["tray_color"] == "", "Slot 1 color should be cleared"
  594. def test_power_on_flag_defaults_true_when_absent(self, mqtt_client):
  595. """When power_on_flag is not in the MQTT data, clearing must proceed normally.
  596. Ensures backwards compatibility with firmware that doesn't send power_on_flag.
  597. """
  598. # Initial state
  599. initial_ams = {
  600. "ams": [
  601. {
  602. "id": 0,
  603. "tray": [
  604. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  605. ],
  606. },
  607. ],
  608. "tray_exist_bits": "1",
  609. }
  610. mqtt_client._handle_ams_data(initial_ams)
  611. # Update WITHOUT power_on_flag — should still clear when bit=0
  612. update_ams = {
  613. "ams": [{"id": 0, "tray": [{"id": 0}]}],
  614. "tray_exist_bits": "0",
  615. # No power_on_flag key at all
  616. }
  617. mqtt_client._handle_ams_data(update_ams)
  618. ams_data = mqtt_client.state.raw_data["ams"]
  619. assert ams_data[0]["tray"][0]["tray_type"] == "", (
  620. "Without power_on_flag, clearing should proceed (defaults to True)"
  621. )
  622. class TestAMSTrayStateClearning:
  623. """Tests for AMS tray state-based clearing (#784).
  624. Some printers (e.g. H2D) only send {id, state} in incremental MQTT
  625. updates when a tray is not fully loaded. state=11 means loaded;
  626. other values (9=empty, 10=spool present but filament not in feeder)
  627. should clear stale tray data that was set from an earlier pushall.
  628. """
  629. @pytest.fixture
  630. def mqtt_client(self):
  631. from backend.app.services.bambu_mqtt import BambuMQTTClient
  632. client = BambuMQTTClient(
  633. ip_address="192.168.1.100",
  634. serial_number="TEST_H2D",
  635. access_code="12345678",
  636. )
  637. return client
  638. def _seed_loaded_tray(self, mqtt_client):
  639. """Seed AMS 0 with a fully loaded tray (state=11) and an empty slot."""
  640. initial = {
  641. "ams": [
  642. {
  643. "id": 0,
  644. "tray": [
  645. {
  646. "id": 0,
  647. "tray_type": "PETG",
  648. "tray_sub_brands": "PETG HF",
  649. "tray_color": "00FF00FF",
  650. "tray_id_name": "A00-G1",
  651. "tray_info_idx": "GFG99",
  652. "tag_uid": "AABBCCDD11223344",
  653. "tray_uuid": "AABBCCDD11223344AABBCCDD11223344",
  654. "remain": 75,
  655. "k": 0.02,
  656. "cali_idx": 5,
  657. "state": 11,
  658. },
  659. {
  660. "id": 1,
  661. "tray_type": "PLA",
  662. "tray_color": "FF0000FF",
  663. "remain": 50,
  664. "state": 11,
  665. },
  666. ],
  667. }
  668. ],
  669. "power_on_flag": False, # H2D always sends False
  670. }
  671. mqtt_client._handle_ams_data(initial)
  672. ams = mqtt_client.state.raw_data["ams"]
  673. assert ams[0]["tray"][0]["tray_type"] == "PETG"
  674. assert ams[0]["tray"][1]["tray_type"] == "PLA"
  675. def test_state_10_clears_stale_tray_data(self, mqtt_client):
  676. """Incremental update with state=10 (spool present, not loaded) clears tray."""
  677. self._seed_loaded_tray(mqtt_client)
  678. # H2D sends only {id, state} when filament is retracted
  679. update = {
  680. "ams": [
  681. {
  682. "id": 0,
  683. "tray": [
  684. {"id": 0, "state": 10},
  685. {"id": 1, "state": 11}, # slot 1 still loaded
  686. ],
  687. }
  688. ],
  689. "power_on_flag": False,
  690. }
  691. mqtt_client._handle_ams_data(update)
  692. ams = mqtt_client.state.raw_data["ams"]
  693. tray0 = ams[0]["tray"][0]
  694. tray1 = ams[0]["tray"][1]
  695. # Tray 0 should be cleared
  696. assert tray0["tray_type"] == "", "tray_type must be cleared on state=10"
  697. assert tray0["tray_color"] == "", "tray_color must be cleared"
  698. assert tray0["tray_sub_brands"] == "", "tray_sub_brands must be cleared"
  699. assert tray0["tray_id_name"] == "", "tray_id_name must be cleared"
  700. assert tray0["tray_info_idx"] == "", "tray_info_idx must be cleared"
  701. assert tray0["tag_uid"] == "0000000000000000", "tag_uid must be cleared"
  702. assert tray0["tray_uuid"] == "00000000000000000000000000000000", "tray_uuid must be cleared"
  703. assert tray0["remain"] == 0, "remain must be 0"
  704. assert tray0["k"] is None, "k must be cleared"
  705. assert tray0["cali_idx"] is None, "cali_idx must be cleared"
  706. assert tray0["state"] == 10, "state should be preserved"
  707. # Tray 1 should be untouched
  708. assert tray1["tray_type"] == "PLA", "Loaded slot must be preserved"
  709. assert tray1["remain"] == 50
  710. def test_state_9_clears_stale_tray_data(self, mqtt_client):
  711. """Incremental update with state=9 (empty, no spool) clears tray."""
  712. self._seed_loaded_tray(mqtt_client)
  713. update = {
  714. "ams": [
  715. {
  716. "id": 0,
  717. "tray": [
  718. {"id": 0, "state": 9},
  719. {"id": 1, "state": 11},
  720. ],
  721. }
  722. ],
  723. "power_on_flag": False,
  724. }
  725. mqtt_client._handle_ams_data(update)
  726. tray0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  727. assert tray0["tray_type"] == "", "state=9 must clear tray_type"
  728. assert tray0["remain"] == 0
  729. def test_state_11_preserves_tray_data(self, mqtt_client):
  730. """Incremental update with state=11 (loaded) must NOT clear tray."""
  731. self._seed_loaded_tray(mqtt_client)
  732. update = {
  733. "ams": [
  734. {
  735. "id": 0,
  736. "tray": [
  737. {"id": 0, "state": 11},
  738. {"id": 1, "state": 11},
  739. ],
  740. }
  741. ],
  742. "power_on_flag": False,
  743. }
  744. mqtt_client._handle_ams_data(update)
  745. tray0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  746. assert tray0["tray_type"] == "PETG", "state=11 must preserve tray data"
  747. assert tray0["tray_color"] == "00FF00FF"
  748. assert tray0["remain"] == 75
  749. def test_no_clearing_when_tray_type_already_empty(self, mqtt_client):
  750. """Don't re-clear a tray that's already empty (avoids log spam)."""
  751. self._seed_loaded_tray(mqtt_client)
  752. # First unload clears
  753. update = {
  754. "ams": [{"id": 0, "tray": [{"id": 0, "state": 10}, {"id": 1, "state": 11}]}],
  755. "power_on_flag": False,
  756. }
  757. mqtt_client._handle_ams_data(update)
  758. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["tray_type"] == ""
  759. # Second identical update should not trigger clearing again
  760. # (merged_tray.get("tray_type") is already empty/falsy)
  761. mqtt_client._handle_ams_data(update)
  762. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["tray_type"] == ""
  763. def test_reload_after_unload_restores_data(self, mqtt_client):
  764. """After clearing via state=10, a full update with state=11 restores data."""
  765. self._seed_loaded_tray(mqtt_client)
  766. # Unload
  767. mqtt_client._handle_ams_data(
  768. {
  769. "ams": [{"id": 0, "tray": [{"id": 0, "state": 10}, {"id": 1, "state": 11}]}],
  770. "power_on_flag": False,
  771. }
  772. )
  773. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["tray_type"] == ""
  774. # Reload — full tray data arrives again
  775. mqtt_client._handle_ams_data(
  776. {
  777. "ams": [
  778. {
  779. "id": 0,
  780. "tray": [
  781. {
  782. "id": 0,
  783. "tray_type": "PETG",
  784. "tray_sub_brands": "PETG HF",
  785. "tray_color": "00FF00FF",
  786. "remain": 75,
  787. "state": 11,
  788. },
  789. {"id": 1, "state": 11},
  790. ],
  791. }
  792. ],
  793. "power_on_flag": False,
  794. }
  795. )
  796. tray0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  797. assert tray0["tray_type"] == "PETG", "Reload must restore tray data"
  798. assert tray0["tray_color"] == "00FF00FF"
  799. assert tray0["remain"] == 75
  800. class TestNozzleRackData:
  801. """Tests for nozzle rack data parsing from H2 series device.nozzle.info."""
  802. @pytest.fixture
  803. def mqtt_client(self):
  804. """Create a BambuMQTTClient instance for testing."""
  805. from backend.app.services.bambu_mqtt import BambuMQTTClient
  806. client = BambuMQTTClient(
  807. ip_address="192.168.1.100",
  808. serial_number="TEST123",
  809. access_code="12345678",
  810. )
  811. return client
  812. def test_h2c_nozzle_rack_populated_with_8_entries(self, mqtt_client):
  813. """H2C provides 8 nozzle entries: IDs 0,1 (L/R hotend) + 16-21 (rack)."""
  814. payload = {
  815. "print": {
  816. "device": {
  817. "nozzle": {
  818. "info": [
  819. {
  820. "id": 0,
  821. "type": "HS",
  822. "diameter": "0.4",
  823. "wear": 5,
  824. "stat": 1,
  825. "max_temp": 300,
  826. "serial_number": "SN-L",
  827. },
  828. {
  829. "id": 1,
  830. "type": "HS",
  831. "diameter": "0.4",
  832. "wear": 3,
  833. "stat": 0,
  834. "max_temp": 300,
  835. "serial_number": "SN-R",
  836. },
  837. {
  838. "id": 16,
  839. "type": "HS",
  840. "diameter": "0.4",
  841. "wear": 10,
  842. "stat": 0,
  843. "max_temp": 300,
  844. "serial_number": "SN-16",
  845. },
  846. {
  847. "id": 17,
  848. "type": "HH01",
  849. "diameter": "0.6",
  850. "wear": 0,
  851. "stat": 0,
  852. "max_temp": 300,
  853. "serial_number": "SN-17",
  854. },
  855. {
  856. "id": 18,
  857. "type": "HS",
  858. "diameter": "0.4",
  859. "wear": 2,
  860. "stat": 0,
  861. "max_temp": 300,
  862. "serial_number": "SN-18",
  863. },
  864. {
  865. "id": 19,
  866. "type": "",
  867. "diameter": "",
  868. "wear": None,
  869. "stat": None,
  870. "max_temp": 0,
  871. "serial_number": "",
  872. },
  873. {
  874. "id": 20,
  875. "type": "",
  876. "diameter": "",
  877. "wear": None,
  878. "stat": None,
  879. "max_temp": 0,
  880. "serial_number": "",
  881. },
  882. {
  883. "id": 21,
  884. "type": "",
  885. "diameter": "",
  886. "wear": None,
  887. "stat": None,
  888. "max_temp": 0,
  889. "serial_number": "",
  890. },
  891. ]
  892. }
  893. }
  894. }
  895. }
  896. mqtt_client._process_message(payload)
  897. assert len(mqtt_client.state.nozzle_rack) == 8
  898. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  899. assert ids == [0, 1, 16, 17, 18, 19, 20, 21]
  900. def test_h2d_nozzle_rack_populated_with_2_entries(self, mqtt_client):
  901. """H2D provides 2 nozzle entries: IDs 0,1 (L/R hotend) — no rack slots."""
  902. payload = {
  903. "print": {
  904. "device": {
  905. "nozzle": {
  906. "info": [
  907. {
  908. "id": 0,
  909. "type": "HS",
  910. "diameter": "0.4",
  911. "wear": 5,
  912. "stat": 1,
  913. "max_temp": 300,
  914. "serial_number": "SN-L",
  915. },
  916. {
  917. "id": 1,
  918. "type": "HS",
  919. "diameter": "0.4",
  920. "wear": 3,
  921. "stat": 1,
  922. "max_temp": 300,
  923. "serial_number": "SN-R",
  924. },
  925. ]
  926. }
  927. }
  928. }
  929. }
  930. mqtt_client._process_message(payload)
  931. assert len(mqtt_client.state.nozzle_rack) == 2
  932. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  933. assert ids == [0, 1]
  934. def test_single_nozzle_h2s_populated(self, mqtt_client):
  935. """H2S provides 1 nozzle entry: ID 0 only — single nozzle printer."""
  936. payload = {
  937. "print": {
  938. "device": {
  939. "nozzle": {
  940. "info": [
  941. {
  942. "id": 0,
  943. "type": "HS",
  944. "diameter": "0.4",
  945. "wear": 2,
  946. "stat": 1,
  947. "max_temp": 300,
  948. "serial_number": "SN-0",
  949. },
  950. ]
  951. }
  952. }
  953. }
  954. }
  955. mqtt_client._process_message(payload)
  956. assert len(mqtt_client.state.nozzle_rack) == 1
  957. assert mqtt_client.state.nozzle_rack[0]["id"] == 0
  958. def test_empty_nozzle_info_does_not_populate_rack(self, mqtt_client):
  959. """Empty nozzle info list should not populate nozzle_rack."""
  960. payload = {"print": {"device": {"nozzle": {"info": []}}}}
  961. mqtt_client._process_message(payload)
  962. assert mqtt_client.state.nozzle_rack == []
  963. def test_nozzle_rack_sorted_by_id(self, mqtt_client):
  964. """Nozzle rack entries should be sorted by ID regardless of input order."""
  965. payload = {
  966. "print": {
  967. "device": {
  968. "nozzle": {
  969. "info": [
  970. {"id": 17, "type": "HS", "diameter": "0.6"},
  971. {"id": 0, "type": "HS", "diameter": "0.4"},
  972. {"id": 16, "type": "HS", "diameter": "0.4"},
  973. {"id": 1, "type": "HS", "diameter": "0.4"},
  974. ]
  975. }
  976. }
  977. }
  978. }
  979. mqtt_client._process_message(payload)
  980. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  981. assert ids == [0, 1, 16, 17]
  982. def test_nozzle_rack_field_mapping(self, mqtt_client):
  983. """Verify field mapping from MQTT nozzle_info to nozzle_rack dict keys."""
  984. payload = {
  985. "print": {
  986. "device": {
  987. "nozzle": {
  988. "info": [
  989. {
  990. "id": 16,
  991. "type": "HH01",
  992. "diameter": "0.6",
  993. "wear": 15,
  994. "stat": 0,
  995. "max_temp": 320,
  996. "serial_number": "SN-ABC123",
  997. "filament_colour": "FF8800",
  998. "filament_id": "F42",
  999. "tray_type": "ABS",
  1000. }
  1001. ]
  1002. }
  1003. }
  1004. }
  1005. }
  1006. mqtt_client._process_message(payload)
  1007. slot = mqtt_client.state.nozzle_rack[0]
  1008. assert slot["id"] == 16
  1009. assert slot["type"] == "HH01"
  1010. assert slot["diameter"] == "0.6"
  1011. assert slot["wear"] == 15
  1012. assert slot["stat"] == 0
  1013. assert slot["max_temp"] == 320
  1014. assert slot["serial_number"] == "SN-ABC123"
  1015. assert slot["filament_color"] == "FF8800"
  1016. assert slot["filament_id"] == "F42"
  1017. assert slot["filament_type"] == "ABS"
  1018. def test_nozzle_info_updates_nozzle_state(self, mqtt_client):
  1019. """Nozzle info for IDs 0,1 should also update nozzle state (type/diameter)."""
  1020. payload = {
  1021. "print": {
  1022. "device": {
  1023. "nozzle": {
  1024. "info": [
  1025. {"id": 0, "type": "HS", "diameter": "0.4"},
  1026. {"id": 1, "type": "HH01", "diameter": "0.6"},
  1027. ]
  1028. }
  1029. }
  1030. }
  1031. }
  1032. mqtt_client._process_message(payload)
  1033. assert mqtt_client.state.nozzles[0].nozzle_type == "HS"
  1034. assert mqtt_client.state.nozzles[0].nozzle_diameter == "0.4"
  1035. assert mqtt_client.state.nozzles[1].nozzle_type == "HH01"
  1036. assert mqtt_client.state.nozzles[1].nozzle_diameter == "0.6"
  1037. class TestRequestTopicFailSafe:
  1038. """Tests for graceful degradation when broker rejects request topic subscription."""
  1039. @pytest.fixture(autouse=True)
  1040. def clear_request_topic_cache(self):
  1041. """Clear class-level cache before each test to avoid cross-test pollution."""
  1042. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1043. BambuMQTTClient._request_topic_cache.clear()
  1044. @pytest.fixture
  1045. def mqtt_client(self):
  1046. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1047. client = BambuMQTTClient(
  1048. ip_address="192.168.1.100",
  1049. serial_number="TEST123",
  1050. access_code="12345678",
  1051. )
  1052. return client
  1053. def test_request_topic_supported_by_default(self, mqtt_client):
  1054. """Request topic subscription is attempted by default."""
  1055. assert mqtt_client._request_topic_supported is True
  1056. assert mqtt_client._request_topic_confirmed is False
  1057. def test_on_subscribe_confirms_success(self, mqtt_client):
  1058. """Successful SUBACK marks request topic as confirmed."""
  1059. from paho.mqtt.reasoncodes import ReasonCode
  1060. mqtt_client._request_topic_sub_mid = 42
  1061. rc = ReasonCode(9, identifier=0) # SUBACK packetType=9, QoS 0 = success
  1062. mqtt_client._on_subscribe(None, None, 42, [rc], None)
  1063. assert mqtt_client._request_topic_confirmed is True
  1064. assert mqtt_client._request_topic_supported is True
  1065. assert mqtt_client._request_topic_sub_mid is None
  1066. assert mqtt_client._request_topic_sub_time == 0.0
  1067. def test_on_subscribe_detects_rejection(self, mqtt_client):
  1068. """SUBACK with failure code disables request topic."""
  1069. from paho.mqtt.reasoncodes import ReasonCode
  1070. mqtt_client._request_topic_sub_mid = 42
  1071. rc = ReasonCode(9, identifier=0x80) # SUBACK packetType=9, 0x80 = failure
  1072. mqtt_client._on_subscribe(None, None, 42, [rc], None)
  1073. assert mqtt_client._request_topic_supported is False
  1074. assert mqtt_client._request_topic_confirmed is False
  1075. def test_on_subscribe_ignores_other_mids(self, mqtt_client):
  1076. """SUBACK for other subscriptions (e.g. report topic) is ignored."""
  1077. from paho.mqtt.reasoncodes import ReasonCode
  1078. mqtt_client._request_topic_sub_mid = 42
  1079. rc = ReasonCode(9, identifier=0x80)
  1080. mqtt_client._on_subscribe(None, None, 99, [rc], None)
  1081. # Not affected — mid doesn't match
  1082. assert mqtt_client._request_topic_supported is True
  1083. def test_disconnect_after_subscription_disables_topic(self, mqtt_client):
  1084. """Disconnect within 10s of subscription attempt disables request topic."""
  1085. import time
  1086. mqtt_client._request_topic_sub_time = time.time()
  1087. mqtt_client._request_topic_confirmed = False
  1088. mqtt_client._last_message_time = 0.0
  1089. mqtt_client._on_disconnect(None, None)
  1090. assert mqtt_client._request_topic_supported is False
  1091. assert mqtt_client._request_topic_sub_time == 0.0
  1092. def test_disconnect_after_confirmation_does_not_disable(self, mqtt_client):
  1093. """Disconnect after SUBACK confirmation keeps request topic enabled."""
  1094. import time
  1095. mqtt_client._request_topic_sub_time = time.time()
  1096. mqtt_client._request_topic_confirmed = True
  1097. mqtt_client._last_message_time = 0.0
  1098. mqtt_client._on_disconnect(None, None)
  1099. assert mqtt_client._request_topic_supported is True
  1100. def test_late_disconnect_does_not_disable(self, mqtt_client):
  1101. """Disconnect long after subscription (>10s) doesn't blame request topic."""
  1102. import time
  1103. mqtt_client._request_topic_sub_time = time.time() - 30.0
  1104. mqtt_client._request_topic_confirmed = False
  1105. mqtt_client._last_message_time = 0.0
  1106. mqtt_client._on_disconnect(None, None)
  1107. assert mqtt_client._request_topic_supported is True
  1108. def test_on_connect_skips_request_topic_when_unsupported(self, mqtt_client):
  1109. """After marking unsupported, reconnect skips request topic subscription."""
  1110. mqtt_client._request_topic_supported = False
  1111. subscribe_calls = []
  1112. mock_client = type(
  1113. "MockClient",
  1114. (),
  1115. {
  1116. "subscribe": lambda self, topic: subscribe_calls.append(topic) or (0, 1),
  1117. },
  1118. )()
  1119. mqtt_client._on_connect(mock_client, None, None, 0)
  1120. # Only report topic subscribed, not request topic
  1121. assert len(subscribe_calls) == 1
  1122. assert subscribe_calls[0] == mqtt_client.topic_subscribe
  1123. def test_cache_persists_across_instances(self):
  1124. """New client instance inherits request topic unsupported state from cache."""
  1125. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1126. client1 = BambuMQTTClient(
  1127. ip_address="192.168.1.100",
  1128. serial_number="TEST_CACHE",
  1129. access_code="12345678",
  1130. )
  1131. assert client1._request_topic_supported is True
  1132. # Simulate disconnect-after-subscribe disabling the topic
  1133. client1._request_topic_sub_time = __import__("time").time()
  1134. client1._request_topic_confirmed = False
  1135. client1._last_message_time = 0.0
  1136. client1._on_disconnect(None, None)
  1137. assert client1._request_topic_supported is False
  1138. # New instance for same serial should inherit the cached state
  1139. client2 = BambuMQTTClient(
  1140. ip_address="192.168.1.100",
  1141. serial_number="TEST_CACHE",
  1142. access_code="12345678",
  1143. )
  1144. assert client2._request_topic_supported is False
  1145. def test_cache_does_not_affect_different_serial(self):
  1146. """Cache is per-serial — different printer is unaffected."""
  1147. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1148. BambuMQTTClient._request_topic_cache["SERIAL_A"] = False
  1149. client = BambuMQTTClient(
  1150. ip_address="192.168.1.100",
  1151. serial_number="SERIAL_B",
  1152. access_code="12345678",
  1153. )
  1154. assert client._request_topic_supported is True
  1155. def test_cache_updated_on_suback_success(self):
  1156. """Successful SUBACK caches positive confirmation."""
  1157. from paho.mqtt.reasoncodes import ReasonCode
  1158. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1159. client = BambuMQTTClient(
  1160. ip_address="192.168.1.100",
  1161. serial_number="TEST_SUBACK",
  1162. access_code="12345678",
  1163. )
  1164. client._request_topic_sub_mid = 42
  1165. rc = ReasonCode(9, identifier=0) # Success
  1166. client._on_subscribe(None, None, 42, [rc], None)
  1167. assert BambuMQTTClient._request_topic_cache["TEST_SUBACK"] is True
  1168. def test_cache_updated_on_suback_rejection(self):
  1169. """SUBACK rejection caches negative state."""
  1170. from paho.mqtt.reasoncodes import ReasonCode
  1171. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1172. client = BambuMQTTClient(
  1173. ip_address="192.168.1.100",
  1174. serial_number="TEST_REJECT",
  1175. access_code="12345678",
  1176. )
  1177. client._request_topic_sub_mid = 42
  1178. rc = ReasonCode(9, identifier=0x80) # Failure
  1179. client._on_subscribe(None, None, 42, [rc], None)
  1180. assert BambuMQTTClient._request_topic_cache["TEST_REJECT"] is False
  1181. class TestRequestTopicAmsMapping:
  1182. """Tests for capturing ams_mapping from the MQTT request topic."""
  1183. @pytest.fixture
  1184. def mqtt_client(self):
  1185. """Create a BambuMQTTClient instance for testing."""
  1186. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1187. client = BambuMQTTClient(
  1188. ip_address="192.168.1.100",
  1189. serial_number="TEST123",
  1190. access_code="12345678",
  1191. )
  1192. return client
  1193. def test_captured_ams_mapping_initializes_to_none(self, mqtt_client):
  1194. """Verify _captured_ams_mapping starts as None."""
  1195. assert mqtt_client._captured_ams_mapping is None
  1196. def test_handle_request_message_captures_ams_mapping(self, mqtt_client):
  1197. """project_file command with ams_mapping stores the mapping."""
  1198. data = {
  1199. "print": {
  1200. "command": "project_file",
  1201. "ams_mapping": [0, 4, -1, -1],
  1202. "url": "ftp://192.168.1.100/test.3mf",
  1203. }
  1204. }
  1205. mqtt_client._handle_request_message(data)
  1206. assert mqtt_client._captured_ams_mapping == [0, 4, -1, -1]
  1207. def test_handle_request_message_ignores_non_print_commands(self, mqtt_client):
  1208. """Non-project_file commands don't store ams_mapping."""
  1209. data = {
  1210. "print": {
  1211. "command": "pause",
  1212. }
  1213. }
  1214. mqtt_client._handle_request_message(data)
  1215. assert mqtt_client._captured_ams_mapping is None
  1216. def test_handle_request_message_ignores_missing_ams_mapping(self, mqtt_client):
  1217. """project_file command without ams_mapping doesn't store anything."""
  1218. data = {
  1219. "print": {
  1220. "command": "project_file",
  1221. "url": "ftp://192.168.1.100/test.3mf",
  1222. }
  1223. }
  1224. mqtt_client._handle_request_message(data)
  1225. assert mqtt_client._captured_ams_mapping is None
  1226. def test_handle_request_message_ignores_non_dict_print(self, mqtt_client):
  1227. """Non-dict print value is safely ignored."""
  1228. data = {"print": "not_a_dict"}
  1229. mqtt_client._handle_request_message(data)
  1230. assert mqtt_client._captured_ams_mapping is None
  1231. def test_handle_request_message_ignores_missing_print(self, mqtt_client):
  1232. """Message without print key is safely ignored."""
  1233. data = {"pushing": {"command": "pushall"}}
  1234. mqtt_client._handle_request_message(data)
  1235. assert mqtt_client._captured_ams_mapping is None
  1236. def test_captured_mapping_overwrites_previous(self, mqtt_client):
  1237. """A new print command overwrites a previously captured mapping."""
  1238. mqtt_client._captured_ams_mapping = [0, -1, -1, -1]
  1239. data = {
  1240. "print": {
  1241. "command": "project_file",
  1242. "ams_mapping": [4, 8, -1, -1],
  1243. }
  1244. }
  1245. mqtt_client._handle_request_message(data)
  1246. assert mqtt_client._captured_ams_mapping == [4, 8, -1, -1]
  1247. def test_print_start_callback_includes_ams_mapping(self, mqtt_client):
  1248. """on_print_start callback data includes captured ams_mapping."""
  1249. start_data = {}
  1250. def on_start(data):
  1251. start_data.update(data)
  1252. mqtt_client.on_print_start = on_start
  1253. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  1254. # Trigger print start
  1255. mqtt_client._process_message(
  1256. {
  1257. "print": {
  1258. "gcode_state": "RUNNING",
  1259. "gcode_file": "/data/Metadata/test.gcode",
  1260. "subtask_name": "Test",
  1261. }
  1262. }
  1263. )
  1264. assert start_data.get("ams_mapping") == [0, 4, -1, -1]
  1265. def test_print_start_callback_ams_mapping_none_when_not_captured(self, mqtt_client):
  1266. """on_print_start callback has ams_mapping=None when no mapping captured."""
  1267. start_data = {}
  1268. def on_start(data):
  1269. start_data.update(data)
  1270. mqtt_client.on_print_start = on_start
  1271. mqtt_client._process_message(
  1272. {
  1273. "print": {
  1274. "gcode_state": "RUNNING",
  1275. "gcode_file": "/data/Metadata/test.gcode",
  1276. "subtask_name": "Test",
  1277. }
  1278. }
  1279. )
  1280. assert "ams_mapping" in start_data
  1281. assert start_data["ams_mapping"] is None
  1282. def test_print_complete_callback_includes_ams_mapping(self, mqtt_client):
  1283. """on_print_complete callback data includes captured ams_mapping."""
  1284. complete_data = {}
  1285. def on_complete(data):
  1286. complete_data.update(data)
  1287. mqtt_client.on_print_start = lambda d: None
  1288. mqtt_client.on_print_complete = on_complete
  1289. mqtt_client._captured_ams_mapping = [0, 9, -1, -1]
  1290. # Start print
  1291. mqtt_client._process_message(
  1292. {
  1293. "print": {
  1294. "gcode_state": "RUNNING",
  1295. "gcode_file": "/data/Metadata/test.gcode",
  1296. "subtask_name": "Test",
  1297. }
  1298. }
  1299. )
  1300. # Complete print
  1301. mqtt_client._process_message(
  1302. {
  1303. "print": {
  1304. "gcode_state": "FINISH",
  1305. "gcode_file": "/data/Metadata/test.gcode",
  1306. "subtask_name": "Test",
  1307. }
  1308. }
  1309. )
  1310. assert complete_data.get("ams_mapping") == [0, 9, -1, -1]
  1311. def test_captured_mapping_cleared_after_print_complete(self, mqtt_client):
  1312. """_captured_ams_mapping is reset to None after print completion."""
  1313. mqtt_client.on_print_start = lambda d: None
  1314. mqtt_client.on_print_complete = lambda d: None
  1315. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  1316. # Start print
  1317. mqtt_client._process_message(
  1318. {
  1319. "print": {
  1320. "gcode_state": "RUNNING",
  1321. "gcode_file": "/data/Metadata/test.gcode",
  1322. "subtask_name": "Test",
  1323. }
  1324. }
  1325. )
  1326. # Complete print
  1327. mqtt_client._process_message(
  1328. {
  1329. "print": {
  1330. "gcode_state": "FINISH",
  1331. "gcode_file": "/data/Metadata/test.gcode",
  1332. "subtask_name": "Test",
  1333. }
  1334. }
  1335. )
  1336. assert mqtt_client._captured_ams_mapping is None
  1337. def test_full_flow_capture_and_deliver(self, mqtt_client):
  1338. """Full flow: slicer sends print command → MQTT captures mapping → completion delivers it."""
  1339. complete_data = {}
  1340. def on_complete(data):
  1341. complete_data.update(data)
  1342. mqtt_client.on_print_start = lambda d: None
  1343. mqtt_client.on_print_complete = on_complete
  1344. # 1. Slicer sends print command (captured from request topic)
  1345. mqtt_client._handle_request_message(
  1346. {
  1347. "print": {
  1348. "command": "project_file",
  1349. "ams_mapping": [4, 9, -1, -1],
  1350. "url": "ftp://192.168.1.100/model.3mf",
  1351. }
  1352. }
  1353. )
  1354. assert mqtt_client._captured_ams_mapping == [4, 9, -1, -1]
  1355. # 2. Printer reports RUNNING
  1356. mqtt_client._process_message(
  1357. {
  1358. "print": {
  1359. "gcode_state": "RUNNING",
  1360. "gcode_file": "/data/Metadata/model.gcode",
  1361. "subtask_name": "Model",
  1362. }
  1363. }
  1364. )
  1365. # 3. Printer reports FINISH
  1366. mqtt_client._process_message(
  1367. {
  1368. "print": {
  1369. "gcode_state": "FINISH",
  1370. "gcode_file": "/data/Metadata/model.gcode",
  1371. "subtask_name": "Model",
  1372. }
  1373. }
  1374. )
  1375. assert complete_data["ams_mapping"] == [4, 9, -1, -1]
  1376. assert complete_data["status"] == "completed"
  1377. # Mapping cleared after completion
  1378. assert mqtt_client._captured_ams_mapping is None
  1379. # ---------------------------------------------------------------------------
  1380. # tray_now disambiguation helpers
  1381. # ---------------------------------------------------------------------------
  1382. def _ams_payload(tray_now, ams_units=None, tray_exist_bits=None, ams_exist_bits=None):
  1383. """Build minimal print.ams payload for tray_now disambiguation tests."""
  1384. ams = {"tray_now": str(tray_now)}
  1385. if ams_units is not None:
  1386. ams["ams"] = ams_units
  1387. if tray_exist_bits is not None:
  1388. ams["tray_exist_bits"] = tray_exist_bits
  1389. if ams_exist_bits is not None:
  1390. ams["ams_exist_bits"] = ams_exist_bits
  1391. return {"print": {"ams": ams}}
  1392. def _extruder_info_payload(extruders):
  1393. """Build device.extruder.info payload (dual-nozzle detection + snow).
  1394. Each entry in *extruders* is a dict with at least ``id`` and ``snow``.
  1395. """
  1396. return {
  1397. "print": {
  1398. "device": {
  1399. "extruder": {
  1400. "info": extruders,
  1401. }
  1402. }
  1403. }
  1404. }
  1405. def _extruder_state_payload(state_val):
  1406. """Build device.extruder.state payload (active extruder via bit 8)."""
  1407. return {
  1408. "print": {
  1409. "device": {
  1410. "extruder": {
  1411. "state": state_val,
  1412. }
  1413. }
  1414. }
  1415. }
  1416. # ---------------------------------------------------------------------------
  1417. # 1. Single-nozzle X1E — direct passthrough
  1418. # ---------------------------------------------------------------------------
  1419. class TestTrayNowSingleNozzleX1E:
  1420. """Single-nozzle, 1 AMS — tray_now is a direct passthrough."""
  1421. @pytest.fixture
  1422. def mqtt_client(self):
  1423. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1424. return BambuMQTTClient(
  1425. ip_address="192.168.1.100",
  1426. serial_number="TEST_X1E",
  1427. access_code="12345678",
  1428. )
  1429. def test_tray_now_direct_passthrough_slot_0_to_3(self, mqtt_client):
  1430. """Each tray_now 0-3 maps 1:1 on single-nozzle printers."""
  1431. for slot in range(4):
  1432. mqtt_client._process_message(_ams_payload(slot))
  1433. assert mqtt_client.state.tray_now == slot
  1434. def test_tray_now_255_means_unloaded(self, mqtt_client):
  1435. """tray_now=255 means no filament loaded."""
  1436. mqtt_client._process_message(_ams_payload(255))
  1437. assert mqtt_client.state.tray_now == 255
  1438. def test_single_extruder_does_not_trigger_dual_nozzle(self, mqtt_client):
  1439. """device.extruder.info with 1 entry must NOT set _is_dual_nozzle."""
  1440. mqtt_client._process_message(_extruder_info_payload([{"id": 0, "snow": 0xFF00FF}]))
  1441. assert mqtt_client._is_dual_nozzle is False
  1442. def test_last_loaded_tray_survives_unload(self, mqtt_client):
  1443. """Load tray 2, unload → last_loaded_tray stays 2."""
  1444. mqtt_client._process_message(_ams_payload(2))
  1445. assert mqtt_client.state.last_loaded_tray == 2
  1446. mqtt_client._process_message(_ams_payload(255))
  1447. assert mqtt_client.state.tray_now == 255
  1448. assert mqtt_client.state.last_loaded_tray == 2
  1449. # ---------------------------------------------------------------------------
  1450. # 2. Single-nozzle P2S — multiple AMS, global IDs pass through
  1451. # ---------------------------------------------------------------------------
  1452. class TestTrayNowSingleNozzleP2S:
  1453. """Single-nozzle, 2 AMS — tray_now > 3 passes through as global ID."""
  1454. @pytest.fixture
  1455. def mqtt_client(self):
  1456. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1457. return BambuMQTTClient(
  1458. ip_address="192.168.1.100",
  1459. serial_number="TEST_P2S",
  1460. access_code="12345678",
  1461. )
  1462. def test_tray_now_ams1_global_ids_4_to_7(self, mqtt_client):
  1463. """tray_now 4-7 are global IDs for AMS 1 on single-nozzle printers."""
  1464. for global_id in range(4, 8):
  1465. mqtt_client._process_message(_ams_payload(global_id))
  1466. assert mqtt_client.state.tray_now == global_id
  1467. def test_tray_change_across_ams_units(self, mqtt_client):
  1468. """Switch from AMS 0 slot 1 → AMS 1 slot 2 (global 6)."""
  1469. mqtt_client._process_message(_ams_payload(1))
  1470. assert mqtt_client.state.tray_now == 1
  1471. mqtt_client._process_message(_ams_payload(6))
  1472. assert mqtt_client.state.tray_now == 6
  1473. # ---------------------------------------------------------------------------
  1474. # 2b. Single-nozzle P2S — multi-AMS local slot disambiguation (#420)
  1475. # ---------------------------------------------------------------------------
  1476. class TestTrayNowP2SMultiAmsDisambiguation:
  1477. """P2S firmware sends local slot IDs (0-3) in tray_now even with dual AMS.
  1478. When ams_exist_bits indicates >1 AMS unit and tray_now is 0-3, the backend
  1479. should use the MQTT mapping field (snow-encoded) to resolve the correct
  1480. global tray ID.
  1481. """
  1482. @pytest.fixture
  1483. def mqtt_client(self):
  1484. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1485. client = BambuMQTTClient(
  1486. ip_address="192.168.1.100",
  1487. serial_number="TEST_P2S_DUAL",
  1488. access_code="12345678",
  1489. )
  1490. return client
  1491. def test_resolves_ams1_slot1_from_mapping(self, mqtt_client):
  1492. """tray_now=1 with mapping=[257] → global ID 5 (AMS1-T1).
  1493. 257 snow-decoded: ams_hw_id=1, slot=1 → global 1*4+1=5.
  1494. """
  1495. # Set mapping field in raw_data (as the MQTT handler would)
  1496. mqtt_client.state.raw_data["mapping"] = [257]
  1497. mqtt_client._process_message(
  1498. _ams_payload(1, ams_exist_bits="3") # '3' = 0b11 → AMS 0 and 1
  1499. )
  1500. assert mqtt_client.state.tray_now == 5
  1501. def test_resolves_ams1_slot0_from_mapping(self, mqtt_client):
  1502. """tray_now=0 with mapping=[256] → global ID 4 (AMS1-T0).
  1503. 256 snow-decoded: ams_hw_id=1, slot=0 → global 1*4+0=4.
  1504. """
  1505. mqtt_client.state.raw_data["mapping"] = [256]
  1506. mqtt_client._process_message(_ams_payload(0, ams_exist_bits="3"))
  1507. assert mqtt_client.state.tray_now == 4
  1508. def test_resolves_ams1_slot3_from_mapping(self, mqtt_client):
  1509. """tray_now=3 with mapping=[259] → global ID 7 (AMS1-T3).
  1510. 259 snow-decoded: ams_hw_id=1, slot=3 → global 1*4+3=7.
  1511. """
  1512. mqtt_client.state.raw_data["mapping"] = [259]
  1513. mqtt_client._process_message(_ams_payload(3, ams_exist_bits="3"))
  1514. assert mqtt_client.state.tray_now == 7
  1515. def test_ams0_slot_unchanged_when_mapping_confirms_ams0(self, mqtt_client):
  1516. """tray_now=1 with mapping=[1] → stays 1 (AMS0-T1).
  1517. 1 snow-decoded: ams_hw_id=0, slot=1 → global 0*4+1=1.
  1518. """
  1519. mqtt_client.state.raw_data["mapping"] = [1]
  1520. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1521. assert mqtt_client.state.tray_now == 1
  1522. def test_multicolor_resolves_ams1_from_multi_entry_mapping(self, mqtt_client):
  1523. """Multi-color print: mapping=[0, 257] → tray_now=1 resolves to AMS1-T1 (5).
  1524. Entry 0: ams_hw_id=0, slot=0 (local 0) — doesn't match tray_now=1.
  1525. Entry 257: ams_hw_id=1, slot=1 (local 1) — matches tray_now=1 → global 5.
  1526. """
  1527. mqtt_client.state.raw_data["mapping"] = [0, 257]
  1528. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1529. assert mqtt_client.state.tray_now == 5
  1530. def test_multicolor_four_slot_mapping(self, mqtt_client):
  1531. """mapping=[65535, 65535, 65535, 257] → tray_now=1 resolves to global 5.
  1532. Only entry 257 has local slot=1, other entries are unmapped (65535).
  1533. Reproduces exact data from issue #420 support package.
  1534. """
  1535. mqtt_client.state.raw_data["mapping"] = [65535, 65535, 65535, 257]
  1536. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1537. assert mqtt_client.state.tray_now == 5
  1538. def test_ambiguous_mapping_falls_back_to_local_slot(self, mqtt_client):
  1539. """Two AMS units with same local slot in mapping → ambiguous, keep local slot.
  1540. mapping=[1, 257]: both have local slot 1 (AMS0-T1 and AMS1-T1).
  1541. Cannot disambiguate → fall back to tray_now=1.
  1542. """
  1543. mqtt_client.state.raw_data["mapping"] = [1, 257]
  1544. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1545. assert mqtt_client.state.tray_now == 1
  1546. def test_no_mapping_falls_back_to_local_slot(self, mqtt_client):
  1547. """No mapping field available → fall back to raw tray_now."""
  1548. # No mapping in raw_data (e.g. manual filament load, not during print)
  1549. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1550. assert mqtt_client.state.tray_now == 1
  1551. def test_empty_mapping_falls_back_to_local_slot(self, mqtt_client):
  1552. """Empty mapping list → fall back to raw tray_now."""
  1553. mqtt_client.state.raw_data["mapping"] = []
  1554. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1555. assert mqtt_client.state.tray_now == 1
  1556. def test_single_ams_passthrough(self, mqtt_client):
  1557. """Single AMS (ams_exist_bits='1') → tray_now 0-3 is direct global ID."""
  1558. mqtt_client._process_message(_ams_payload(2, ams_exist_bits="1"))
  1559. assert mqtt_client.state.tray_now == 2
  1560. def test_no_ams_exist_bits_passthrough(self, mqtt_client):
  1561. """No ams_exist_bits in payload → fall back to raw tray_now."""
  1562. mqtt_client._process_message(_ams_payload(1))
  1563. assert mqtt_client.state.tray_now == 1
  1564. def test_tray_now_255_unaffected_by_multi_ams(self, mqtt_client):
  1565. """tray_now=255 (unloaded) passes through regardless of AMS count."""
  1566. mqtt_client.state.raw_data["mapping"] = [257]
  1567. mqtt_client._process_message(_ams_payload(255, ams_exist_bits="3"))
  1568. assert mqtt_client.state.tray_now == 255
  1569. def test_tray_now_above_3_unaffected(self, mqtt_client):
  1570. """tray_now > 3 is already a global ID and passes through directly."""
  1571. mqtt_client._process_message(_ams_payload(6, ams_exist_bits="3"))
  1572. assert mqtt_client.state.tray_now == 6
  1573. def test_last_loaded_tray_uses_resolved_global_id(self, mqtt_client):
  1574. """last_loaded_tray should reflect the resolved global ID, not local slot."""
  1575. mqtt_client.state.raw_data["mapping"] = [257]
  1576. mqtt_client.state.state = "RUNNING"
  1577. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1578. assert mqtt_client.state.tray_now == 5
  1579. assert mqtt_client.state.last_loaded_tray == 5
  1580. class TestResolveLocalSlotFromMapping:
  1581. """Unit tests for _resolve_local_slot_from_mapping static method."""
  1582. def test_single_match_ams0(self):
  1583. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1584. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [1]) == 1
  1585. def test_single_match_ams1(self):
  1586. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1587. # 257 = 1*256 + 1 → AMS1 slot1 → global 5
  1588. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [257]) == 5
  1589. def test_single_match_ams2(self):
  1590. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1591. # 514 = 2*256 + 2 → AMS2 slot2 → global 10
  1592. assert BambuMQTTClient._resolve_local_slot_from_mapping(2, [514]) == 10
  1593. def test_unmapped_entries_skipped(self):
  1594. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1595. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [65535, 65535, 65535, 257]) == 5
  1596. def test_no_match_returns_none(self):
  1597. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1598. # mapping has slot 0 only, looking for slot 2
  1599. assert BambuMQTTClient._resolve_local_slot_from_mapping(2, [0]) is None
  1600. def test_ambiguous_returns_none(self):
  1601. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1602. # Both AMS0 slot1 (1) and AMS1 slot1 (257) → ambiguous
  1603. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [1, 257]) is None
  1604. def test_none_mapping_returns_none(self):
  1605. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1606. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, None) is None
  1607. def test_empty_mapping_returns_none(self):
  1608. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1609. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, []) is None
  1610. def test_ams_ht_slot0_match(self):
  1611. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1612. # AMS-HT id=128: snow = 128*256 + 0 = 32768
  1613. assert BambuMQTTClient._resolve_local_slot_from_mapping(0, [32768]) == 128
  1614. # ---------------------------------------------------------------------------
  1615. # 3. H2D Pro — initial state detection
  1616. # ---------------------------------------------------------------------------
  1617. class TestTrayNowDualNozzleH2DSetup:
  1618. """H2D Pro initial state detection."""
  1619. @pytest.fixture
  1620. def mqtt_client(self):
  1621. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1622. return BambuMQTTClient(
  1623. ip_address="192.168.1.100",
  1624. serial_number="TEST_H2D",
  1625. access_code="12345678",
  1626. )
  1627. def test_dual_nozzle_detected_from_extruder_info(self, mqtt_client):
  1628. """2 entries in device.extruder.info → _is_dual_nozzle=True."""
  1629. mqtt_client._process_message(
  1630. _extruder_info_payload(
  1631. [
  1632. {"id": 0, "snow": 0xFF00FF},
  1633. {"id": 1, "snow": 0xFF00FF},
  1634. ]
  1635. )
  1636. )
  1637. assert mqtt_client._is_dual_nozzle is True
  1638. def test_ams_extruder_map_parsed_from_info_field(self, mqtt_client):
  1639. """AMS info field is hex: 0x2003 → ext 0 (right), 0x2104 → ext 1 (left)."""
  1640. # MQTT sends info as string; BambuStudio parses as hex via stoull(str, 16)
  1641. ams_units = [
  1642. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  1643. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  1644. ]
  1645. payload = {
  1646. "print": {
  1647. "ams": {
  1648. "ams": ams_units,
  1649. "tray_now": "255",
  1650. "tray_exist_bits": "1000f",
  1651. },
  1652. }
  1653. }
  1654. mqtt_client._process_message(payload)
  1655. # 0x2003: bits 8-11 = (0x2003 >> 8) & 0xF = 0x20 & 0xF = 0 → extruder 0 (right)
  1656. # 0x2104: bits 8-11 = (0x2104 >> 8) & 0xF = 0x21 & 0xF = 1 → extruder 1 (left)
  1657. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  1658. def test_ams_extruder_map_real_h2d_values(self, mqtt_client):
  1659. """Real H2D MQTT values: AMS2 Pro on right, AMS-HT on left."""
  1660. ams_units = [
  1661. {"id": 0, "info": "10001003", "tray": [{"id": i} for i in range(4)]},
  1662. {"id": 128, "info": "10002104", "tray": [{"id": 0}]},
  1663. ]
  1664. payload = {
  1665. "print": {
  1666. "ams": {
  1667. "ams": ams_units,
  1668. "tray_now": "255",
  1669. "tray_exist_bits": "1000a",
  1670. },
  1671. }
  1672. }
  1673. mqtt_client._process_message(payload)
  1674. # 0x10001003: bits 8-11 = (0x10001003 >> 8) & 0xF = 0x10 & 0xF = 0 → right
  1675. # 0x10002104: bits 8-11 = (0x10002104 >> 8) & 0xF = 0x21 & 0xF = 1 → left
  1676. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  1677. def test_ams_extruder_map_skips_uninitialized(self, mqtt_client):
  1678. """extruder_id 0xE means uninitialized AMS — should be skipped."""
  1679. ams_units = [
  1680. {"id": 0, "info": "e03", "tray": [{"id": i} for i in range(4)]},
  1681. ]
  1682. payload = {
  1683. "print": {
  1684. "ams": {
  1685. "ams": ams_units,
  1686. "tray_now": "255",
  1687. "tray_exist_bits": "f",
  1688. },
  1689. }
  1690. }
  1691. mqtt_client._process_message(payload)
  1692. assert mqtt_client.state.ams_extruder_map == {}
  1693. def test_ams_extruder_map_partial_update_preserves_entries(self, mqtt_client):
  1694. """Partial MQTT update with one AMS should not overwrite other entries."""
  1695. # First: full update with both AMS units
  1696. full_payload = {
  1697. "print": {
  1698. "ams": {
  1699. "ams": [
  1700. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  1701. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  1702. ],
  1703. "tray_now": "255",
  1704. "tray_exist_bits": "1000f",
  1705. },
  1706. }
  1707. }
  1708. mqtt_client._process_message(full_payload)
  1709. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  1710. # Then: partial update with only AMS 0 (no info field this time)
  1711. partial_payload = {
  1712. "print": {
  1713. "ams": {
  1714. "ams": [
  1715. {"id": 0, "tray": [{"id": 0, "remain": 50}]},
  1716. ],
  1717. "tray_now": "0",
  1718. "tray_exist_bits": "1000f",
  1719. },
  1720. }
  1721. }
  1722. mqtt_client._process_message(partial_payload)
  1723. # Both entries should still be present
  1724. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  1725. def test_dual_nozzle_detection_before_ams_in_same_message(self, mqtt_client):
  1726. """Dual-nozzle detection at line 538 happens before _handle_ams_data() at line 549.
  1727. If both arrive in the same message, tray_now disambiguation already uses dual-nozzle logic.
  1728. """
  1729. payload = {
  1730. "print": {
  1731. "device": {
  1732. "extruder": {
  1733. "info": [
  1734. {"id": 0, "snow": 0xFF00FF},
  1735. {"id": 1, "snow": 0xFF00FF},
  1736. ],
  1737. "state": 0x0001,
  1738. }
  1739. },
  1740. "ams": {
  1741. "ams": [
  1742. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  1743. ],
  1744. "tray_now": "2",
  1745. "tray_exist_bits": "f",
  1746. },
  1747. }
  1748. }
  1749. mqtt_client._process_message(payload)
  1750. # Dual-nozzle was detected; AMS 0 on right extruder (active by default);
  1751. # snow is 0xFF00FF (unloaded), so falls through to ams_extruder_map fallback.
  1752. # Single AMS on extruder 0 → global_id = 0*4+2 = 2
  1753. assert mqtt_client._is_dual_nozzle is True
  1754. assert mqtt_client.state.tray_now == 2
  1755. # ---------------------------------------------------------------------------
  1756. # Shared H2D fixture for classes 4-8
  1757. # ---------------------------------------------------------------------------
  1758. class _H2DFixtureMixin:
  1759. """Mixin providing a pre-configured H2D Pro client."""
  1760. @pytest.fixture
  1761. def mqtt_client(self):
  1762. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1763. return BambuMQTTClient(
  1764. ip_address="192.168.1.100",
  1765. serial_number="TEST_H2D",
  1766. access_code="12345678",
  1767. )
  1768. @pytest.fixture
  1769. def h2d_client(self, mqtt_client):
  1770. """Pre-configure as H2D Pro: dual-nozzle + ams_extruder_map."""
  1771. mqtt_client._process_message(
  1772. {
  1773. "print": {
  1774. "device": {
  1775. "extruder": {
  1776. "info": [
  1777. {"id": 0, "snow": 0xFF00FF},
  1778. {"id": 1, "snow": 0xFF00FF},
  1779. ],
  1780. "state": 0x0001, # right extruder active
  1781. }
  1782. },
  1783. "ams": {
  1784. "ams": [
  1785. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  1786. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  1787. ],
  1788. "tray_now": "255",
  1789. "tray_exist_bits": "1000f",
  1790. },
  1791. }
  1792. }
  1793. )
  1794. assert mqtt_client._is_dual_nozzle is True
  1795. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  1796. return mqtt_client
  1797. # ---------------------------------------------------------------------------
  1798. # 4. H2D Snow field disambiguation
  1799. # ---------------------------------------------------------------------------
  1800. class TestTrayNowDualNozzleH2DSnow(_H2DFixtureMixin):
  1801. """Snow field disambiguation (primary path)."""
  1802. def test_snow_disambiguates_ams0_slot(self, h2d_client):
  1803. """snow ext[0]=AMS 0 slot 2, tray_now='2' → global 2."""
  1804. # Send snow update FIRST (snow is parsed AFTER tray_now in the same message,
  1805. # so we need it in a prior message).
  1806. snow_val = 0 << 8 | 2 # AMS 0 slot 2 = raw 2
  1807. h2d_client._process_message(
  1808. _extruder_info_payload(
  1809. [
  1810. {"id": 0, "snow": snow_val},
  1811. {"id": 1, "snow": 0xFF00FF},
  1812. ]
  1813. )
  1814. )
  1815. assert h2d_client.state.h2d_extruder_snow.get(0) == 2
  1816. # Now send tray_now=2
  1817. h2d_client._process_message(_ams_payload(2))
  1818. assert h2d_client.state.tray_now == 2
  1819. def test_snow_disambiguates_ams_ht_to_128(self, h2d_client):
  1820. """snow ext[1]=AMS HT (128), left active, tray_now='0' → global 128."""
  1821. # Snow: extruder 1 → AMS 128 slot 0
  1822. snow_val = 128 << 8 | 0 # = 32768
  1823. h2d_client._process_message(
  1824. _extruder_info_payload(
  1825. [
  1826. {"id": 0, "snow": 0xFF00FF},
  1827. {"id": 1, "snow": snow_val},
  1828. ]
  1829. )
  1830. )
  1831. assert h2d_client.state.h2d_extruder_snow.get(1) == 128
  1832. # Switch to left extruder
  1833. h2d_client._process_message(_extruder_state_payload(0x0100))
  1834. assert h2d_client.state.active_extruder == 1
  1835. # tray_now="0" with left extruder active, snow says AMS HT (128)
  1836. # AMS HT snow_slot = 0 (single slot), parsed_tray_now = 0 → match
  1837. h2d_client._process_message(_ams_payload(0))
  1838. assert h2d_client.state.tray_now == 128
  1839. def test_snow_updates_h2d_extruder_snow_state(self, h2d_client):
  1840. """Verify state.h2d_extruder_snow dict is populated correctly."""
  1841. snow_ext0 = 1 << 8 | 3 # AMS 1 slot 3 → global 7
  1842. snow_ext1 = 0 << 8 | 0 # AMS 0 slot 0 → global 0
  1843. h2d_client._process_message(
  1844. _extruder_info_payload(
  1845. [
  1846. {"id": 0, "snow": snow_ext0},
  1847. {"id": 1, "snow": snow_ext1},
  1848. ]
  1849. )
  1850. )
  1851. assert h2d_client.state.h2d_extruder_snow[0] == 7
  1852. assert h2d_client.state.h2d_extruder_snow[1] == 0
  1853. def test_snow_unloaded_value(self, h2d_client):
  1854. """snow=0xFFFF (ams_id=255, slot=255) → 255 (unloaded)."""
  1855. h2d_client._process_message(
  1856. _extruder_info_payload(
  1857. [
  1858. {"id": 0, "snow": 0xFFFF},
  1859. {"id": 1, "snow": 0xFFFF},
  1860. ]
  1861. )
  1862. )
  1863. assert h2d_client.state.h2d_extruder_snow[0] == 255
  1864. assert h2d_client.state.h2d_extruder_snow[1] == 255
  1865. def test_snow_initial_sentinel_not_stored(self, h2d_client):
  1866. """snow=0xFF00FF (firmware initial sentinel) is not parsed into h2d_extruder_snow."""
  1867. # 0xFF00FF has ams_id=0xFF00=65280 which doesn't match any branch
  1868. h2d_client._process_message(
  1869. _extruder_info_payload(
  1870. [
  1871. {"id": 0, "snow": 0xFF00FF},
  1872. {"id": 1, "snow": 0xFF00FF},
  1873. ]
  1874. )
  1875. )
  1876. # Snow dict should remain empty (no matching branch)
  1877. assert h2d_client.state.h2d_extruder_snow == {}
  1878. # ---------------------------------------------------------------------------
  1879. # 5. H2D Pending target disambiguation
  1880. # ---------------------------------------------------------------------------
  1881. class TestTrayNowDualNozzleH2DPendingTarget(_H2DFixtureMixin):
  1882. """Pending target disambiguation (when Bambuddy initiates load)."""
  1883. def test_pending_target_matches_slot(self, h2d_client):
  1884. """pending=5, tray_now='1' (5%4=1 matches) → tray_now=5."""
  1885. h2d_client.state.pending_tray_target = 5
  1886. h2d_client._process_message(_ams_payload(1))
  1887. assert h2d_client.state.tray_now == 5
  1888. assert h2d_client.state.pending_tray_target is None # cleared
  1889. def test_pending_target_slot_mismatch(self, h2d_client):
  1890. """pending=5, tray_now='2' → uses raw slot, clears pending."""
  1891. h2d_client.state.pending_tray_target = 5
  1892. h2d_client._process_message(_ams_payload(2))
  1893. # Slot 2 != 5%4=1 → mismatch, uses raw slot 2
  1894. assert h2d_client.state.tray_now == 2
  1895. assert h2d_client.state.pending_tray_target is None
  1896. def test_pending_target_takes_priority_over_snow(self, h2d_client):
  1897. """When both pending and snow are set, pending wins."""
  1898. # Set up snow for extruder 0 → AMS 0 slot 1 → global 1
  1899. snow_val = 0 << 8 | 1
  1900. h2d_client._process_message(
  1901. _extruder_info_payload(
  1902. [
  1903. {"id": 0, "snow": snow_val},
  1904. {"id": 1, "snow": 0xFF00FF},
  1905. ]
  1906. )
  1907. )
  1908. assert h2d_client.state.h2d_extruder_snow.get(0) == 1
  1909. # Set pending target to AMS 1 slot 1 (global 5)
  1910. h2d_client.state.pending_tray_target = 5
  1911. # tray_now="1" — matches pending (5%4=1), pending should win over snow
  1912. h2d_client._process_message(_ams_payload(1))
  1913. assert h2d_client.state.tray_now == 5
  1914. # ---------------------------------------------------------------------------
  1915. # 6. H2D ams_extruder_map fallback
  1916. # ---------------------------------------------------------------------------
  1917. class TestTrayNowDualNozzleH2DFallback(_H2DFixtureMixin):
  1918. """ams_extruder_map fallback (no pending, no snow)."""
  1919. def test_single_ams_on_extruder_computes_global_id(self, h2d_client):
  1920. """AMS 0 on right extruder, tray_now='2' → 0*4+2=2."""
  1921. # h2d_client has snow=0xFF00FF (unloaded) by default, so snow path skips
  1922. h2d_client._process_message(_ams_payload(2))
  1923. # AMS 0 is the only AMS on extruder 0 (right, active by default)
  1924. # Fallback: single AMS → global = 0*4+2 = 2
  1925. assert h2d_client.state.tray_now == 2
  1926. def test_multiple_ams_keeps_current_if_valid(self, h2d_client):
  1927. """Current tray matches slot → keeps it (multi-AMS on same extruder)."""
  1928. # Set up: two AMS units on the same extruder (right, ext 0)
  1929. h2d_client.state.ams_extruder_map = {"0": 0, "1": 0}
  1930. # Pre-set tray_now=5 (AMS 1 slot 1) — current_ams=1 which is in ams_on_extruder
  1931. h2d_client.state.tray_now = 5
  1932. # tray_now="1" → 5%4=1 matches → keep current=5
  1933. h2d_client._process_message(_ams_payload(1))
  1934. assert h2d_client.state.tray_now == 5
  1935. def test_no_ams_on_extruder_uses_raw_slot(self, h2d_client):
  1936. """No AMS mapped to the active extruder → raw slot as global ID."""
  1937. # All AMS on left extruder, but right is active
  1938. h2d_client.state.ams_extruder_map = {"0": 1, "128": 1}
  1939. h2d_client._process_message(_ams_payload(2))
  1940. assert h2d_client.state.tray_now == 2
  1941. def test_single_ams_ht_on_extruder_returns_unit_id(self, h2d_client):
  1942. """AMS-HT 128 alone on left extruder, slot 0 → global ID 128 (not 512)."""
  1943. # Switch to left extruder (where AMS-HT 128 is mapped)
  1944. h2d_client._process_message(_extruder_state_payload(0x0100))
  1945. # Only AMS-HT 128 on left extruder; no snow available
  1946. h2d_client._process_message(_ams_payload(0))
  1947. assert h2d_client.state.tray_now == 128
  1948. def test_single_ams_ht_ignores_nonzero_slot(self, h2d_client):
  1949. """AMS-HT has single slot; even if printer reports slot 1, global ID = unit ID."""
  1950. h2d_client.state.ams_extruder_map = {"129": 0}
  1951. h2d_client._process_message(_ams_payload(1))
  1952. # AMS-HT 129: global ID = 129, not 129*4+1=517
  1953. assert h2d_client.state.tray_now == 129
  1954. def test_multiple_ams_keeps_current_ams_ht(self, h2d_client):
  1955. """Current tray is AMS-HT 128, slot 0 reported → keeps 128."""
  1956. h2d_client.state.ams_extruder_map = {"0": 0, "128": 0}
  1957. h2d_client.state.tray_now = 128
  1958. h2d_client._process_message(_ams_payload(0))
  1959. assert h2d_client.state.tray_now == 128
  1960. def test_multiple_ams_slot_nonzero_excludes_ams_ht(self, h2d_client):
  1961. """Slot > 0 eliminates AMS-HT candidates; single regular AMS left → resolves."""
  1962. # AMS 0 + AMS-HT 128 both on right extruder
  1963. h2d_client.state.ams_extruder_map = {"0": 0, "128": 0}
  1964. h2d_client.state.tray_now = 255 # no current match
  1965. # Slot 2 → can't be AMS-HT → only AMS 0 → global = 0*4+2 = 2
  1966. h2d_client._process_message(_ams_payload(2))
  1967. assert h2d_client.state.tray_now == 2
  1968. def test_multiple_ams_slot_nonzero_narrows_to_single_ht_excluded(self, h2d_client):
  1969. """Two regular AMS + one AMS-HT, slot > 0 → AMS-HT excluded but still ambiguous."""
  1970. h2d_client.state.ams_extruder_map = {"0": 0, "1": 0, "128": 0}
  1971. h2d_client.state.tray_now = 255
  1972. # Slot 3 → excludes AMS-HT, but AMS 0 and AMS 1 both remain → ambiguous
  1973. h2d_client._process_message(_ams_payload(3))
  1974. assert h2d_client.state.tray_now == 3 # raw slot fallback
  1975. # ---------------------------------------------------------------------------
  1976. # 6b. H2D last_loaded_tray validation
  1977. # ---------------------------------------------------------------------------
  1978. class TestLastLoadedTrayValidation(_H2DFixtureMixin):
  1979. """last_loaded_tray only stores physically valid tray IDs."""
  1980. def test_regular_ams_tray_stored(self, h2d_client):
  1981. """Valid regular AMS tray (0-15) → stored in last_loaded_tray."""
  1982. h2d_client.state.tray_now = 7
  1983. # Trigger tray_now processing via AMS message
  1984. h2d_client._process_message(
  1985. _extruder_info_payload(
  1986. [
  1987. {"id": 0, "snow": 1 << 8 | 3}, # AMS 1 slot 3 → global 7
  1988. {"id": 1, "snow": 0xFF00FF},
  1989. ]
  1990. )
  1991. )
  1992. h2d_client._process_message(_ams_payload(3))
  1993. assert h2d_client.state.tray_now == 7
  1994. assert h2d_client.state.last_loaded_tray == 7
  1995. def test_ams_ht_tray_stored(self, h2d_client):
  1996. """Valid AMS-HT tray (128-135) → stored in last_loaded_tray."""
  1997. h2d_client._process_message(_extruder_state_payload(0x0100))
  1998. h2d_client._process_message(
  1999. _extruder_info_payload(
  2000. [
  2001. {"id": 0, "snow": 0xFF00FF},
  2002. {"id": 1, "snow": 128 << 8 | 0},
  2003. ]
  2004. )
  2005. )
  2006. h2d_client._process_message(_ams_payload(0))
  2007. assert h2d_client.state.tray_now == 128
  2008. assert h2d_client.state.last_loaded_tray == 128
  2009. def test_unloaded_not_stored(self, h2d_client):
  2010. """tray_now=255 (unloaded) → last_loaded_tray unchanged."""
  2011. h2d_client.state.last_loaded_tray = 5
  2012. h2d_client._process_message(_ams_payload(255))
  2013. assert h2d_client.state.tray_now == 255
  2014. assert h2d_client.state.last_loaded_tray == 5
  2015. # ---------------------------------------------------------------------------
  2016. # 7. H2D Active extruder switching
  2017. # ---------------------------------------------------------------------------
  2018. class TestTrayNowDualNozzleH2DActiveExtruder(_H2DFixtureMixin):
  2019. """Active extruder switching via device.extruder.state bit 8."""
  2020. def test_active_extruder_right_by_default(self, h2d_client):
  2021. """Initial state.active_extruder == 0 (right)."""
  2022. assert h2d_client.state.active_extruder == 0
  2023. def test_extruder_state_bit8_switches_to_left(self, h2d_client):
  2024. """state=0x100 → active_extruder=1 (left)."""
  2025. h2d_client._process_message(_extruder_state_payload(0x0100))
  2026. assert h2d_client.state.active_extruder == 1
  2027. def test_extruder_state_bit8_switches_back_to_right(self, h2d_client):
  2028. """Cycle 0 → 1 → 0."""
  2029. h2d_client._process_message(_extruder_state_payload(0x0100))
  2030. assert h2d_client.state.active_extruder == 1
  2031. h2d_client._process_message(_extruder_state_payload(0x0001))
  2032. assert h2d_client.state.active_extruder == 0
  2033. def test_extruder_switch_changes_tray_disambiguation(self, h2d_client):
  2034. """Snow on both extruders; switching active changes which snow is used."""
  2035. # Snow: ext 0 → AMS 0 slot 1 (global 1), ext 1 → AMS 128 slot 0 (global 128)
  2036. h2d_client._process_message(
  2037. _extruder_info_payload(
  2038. [
  2039. {"id": 0, "snow": 0 << 8 | 1}, # AMS 0 slot 1 → global 1
  2040. {"id": 1, "snow": 128 << 8 | 0}, # AMS HT → global 128
  2041. ]
  2042. )
  2043. )
  2044. # Right active (default) — tray_now="1" → snow ext[0] says global 1
  2045. h2d_client._process_message(_ams_payload(1))
  2046. assert h2d_client.state.tray_now == 1
  2047. # Switch to left
  2048. h2d_client._process_message(_extruder_state_payload(0x0100))
  2049. # Left active — tray_now="0" → snow ext[1] says AMS HT (128), slot 0 matches
  2050. h2d_client._process_message(_ams_payload(0))
  2051. assert h2d_client.state.tray_now == 128
  2052. # ---------------------------------------------------------------------------
  2053. # 8. H2D Full multi-message sequences
  2054. # ---------------------------------------------------------------------------
  2055. class TestTrayNowDualNozzleH2DFullSequence(_H2DFixtureMixin):
  2056. """Multi-message sequences simulating real H2D Pro prints."""
  2057. def test_h2d_right_nozzle_ams0_lifecycle(self, h2d_client):
  2058. """Setup → load AMS 0 slot 1 → verify tray_now=1."""
  2059. # Snow update: extruder 0 loading AMS 0 slot 1
  2060. h2d_client._process_message(
  2061. _extruder_info_payload(
  2062. [
  2063. {"id": 0, "snow": 0 << 8 | 1},
  2064. {"id": 1, "snow": 0xFF00FF},
  2065. ]
  2066. )
  2067. )
  2068. # Printer reports tray_now="1"
  2069. h2d_client._process_message(_ams_payload(1))
  2070. assert h2d_client.state.tray_now == 1
  2071. assert h2d_client.state.last_loaded_tray == 1
  2072. def test_h2d_left_nozzle_ams_ht_lifecycle(self, h2d_client):
  2073. """Setup → switch left → load AMS HT → verify tray_now=128."""
  2074. # Switch to left extruder
  2075. h2d_client._process_message(_extruder_state_payload(0x0100))
  2076. # Snow: ext 1 → AMS HT slot 0
  2077. h2d_client._process_message(
  2078. _extruder_info_payload(
  2079. [
  2080. {"id": 0, "snow": 0xFF00FF},
  2081. {"id": 1, "snow": 128 << 8 | 0},
  2082. ]
  2083. )
  2084. )
  2085. # Printer reports tray_now="0" (AMS HT single slot)
  2086. h2d_client._process_message(_ams_payload(0))
  2087. assert h2d_client.state.tray_now == 128
  2088. assert h2d_client.state.last_loaded_tray == 128
  2089. def test_h2d_multi_color_alternating_nozzles(self, h2d_client):
  2090. """Multi-color print alternating between right and left nozzles.
  2091. Sequence:
  2092. 1. Right loads AMS 0 slot 0 (tray=0)
  2093. 2. Switch left, load AMS HT (tray=128)
  2094. 3. Switch right, snow updates, load AMS 0 slot 2 (tray=2)
  2095. 4. Unload (255)
  2096. """
  2097. # Step 1: Right extruder loads AMS 0 slot 0
  2098. h2d_client._process_message(
  2099. _extruder_info_payload(
  2100. [
  2101. {"id": 0, "snow": 0 << 8 | 0},
  2102. {"id": 1, "snow": 0xFF00FF},
  2103. ]
  2104. )
  2105. )
  2106. h2d_client._process_message(_ams_payload(0))
  2107. assert h2d_client.state.tray_now == 0
  2108. # Step 2: Switch to left, load AMS HT
  2109. h2d_client._process_message(_extruder_state_payload(0x0100))
  2110. h2d_client._process_message(
  2111. _extruder_info_payload(
  2112. [
  2113. {"id": 0, "snow": 0 << 8 | 0},
  2114. {"id": 1, "snow": 128 << 8 | 0},
  2115. ]
  2116. )
  2117. )
  2118. h2d_client._process_message(_ams_payload(0))
  2119. assert h2d_client.state.tray_now == 128
  2120. # Step 3: Switch back to right, load AMS 0 slot 2
  2121. h2d_client._process_message(_extruder_state_payload(0x0001))
  2122. h2d_client._process_message(
  2123. _extruder_info_payload(
  2124. [
  2125. {"id": 0, "snow": 0 << 8 | 2},
  2126. {"id": 1, "snow": 128 << 8 | 0},
  2127. ]
  2128. )
  2129. )
  2130. h2d_client._process_message(_ams_payload(2))
  2131. assert h2d_client.state.tray_now == 2
  2132. # Step 4: Unload
  2133. h2d_client._process_message(_ams_payload(255))
  2134. assert h2d_client.state.tray_now == 255
  2135. assert h2d_client.state.last_loaded_tray == 2
  2136. class TestTrayChangeLog:
  2137. """Tests for tray_change_log tracking during prints (mid-print tray switch)."""
  2138. @pytest.fixture
  2139. def mqtt_client(self):
  2140. """Create a BambuMQTTClient instance for testing."""
  2141. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2142. client = BambuMQTTClient(
  2143. ip_address="192.168.1.100",
  2144. serial_number="TRAYLOG1",
  2145. access_code="12345678",
  2146. )
  2147. return client
  2148. def test_tray_change_log_defaults_empty(self, mqtt_client):
  2149. """tray_change_log starts as an empty list."""
  2150. assert mqtt_client.state.tray_change_log == []
  2151. def test_tray_change_log_seeded_on_print_start(self, mqtt_client):
  2152. """Print start clears log and seeds with initial tray at layer 0."""
  2153. mqtt_client.state.tray_now = 2
  2154. mqtt_client.state.last_loaded_tray = 2
  2155. mqtt_client._previous_gcode_state = "IDLE"
  2156. # Transition to RUNNING via _process_message
  2157. mqtt_client._process_message(
  2158. {
  2159. "print": {
  2160. "gcode_state": "RUNNING",
  2161. "gcode_file": "test.3mf",
  2162. }
  2163. }
  2164. )
  2165. assert mqtt_client.state.tray_change_log == [(2, 0)]
  2166. def test_tray_change_log_cleared_on_new_print(self, mqtt_client):
  2167. """Old log entries are cleared when a new print starts."""
  2168. mqtt_client.state.tray_change_log = [(5, 0), (3, 100)]
  2169. mqtt_client.state.tray_now = 1
  2170. mqtt_client.state.last_loaded_tray = 1
  2171. mqtt_client._previous_gcode_state = "IDLE"
  2172. mqtt_client._process_message(
  2173. {
  2174. "print": {
  2175. "gcode_state": "RUNNING",
  2176. "gcode_file": "new.3mf",
  2177. }
  2178. }
  2179. )
  2180. assert mqtt_client.state.tray_change_log == [(1, 0)]
  2181. def test_tray_change_recorded_during_running(self, mqtt_client):
  2182. """Tray change while RUNNING is appended to the log."""
  2183. mqtt_client.state.state = "RUNNING"
  2184. mqtt_client.state.layer_num = 50
  2185. mqtt_client.state.last_loaded_tray = 0
  2186. mqtt_client.state.tray_change_log = [(0, 0)]
  2187. # Simulate tray_now update via AMS data
  2188. mqtt_client.state.tray_now = 1
  2189. # Trigger the tracking code path
  2190. tn = mqtt_client.state.tray_now
  2191. if tn != mqtt_client.state.last_loaded_tray and mqtt_client.state.state in ("RUNNING", "PAUSE"):
  2192. mqtt_client.state.tray_change_log.append((tn, mqtt_client.state.layer_num))
  2193. mqtt_client.state.last_loaded_tray = tn
  2194. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50)]
  2195. def test_tray_change_not_recorded_when_idle(self, mqtt_client):
  2196. """Tray changes while IDLE are NOT logged."""
  2197. mqtt_client.state.state = "IDLE"
  2198. mqtt_client.state.layer_num = 0
  2199. mqtt_client.state.last_loaded_tray = 0
  2200. mqtt_client.state.tray_change_log = []
  2201. mqtt_client.state.tray_now = 3
  2202. tn = mqtt_client.state.tray_now
  2203. if tn != mqtt_client.state.last_loaded_tray and mqtt_client.state.state in ("RUNNING", "PAUSE"):
  2204. mqtt_client.state.tray_change_log.append((tn, mqtt_client.state.layer_num))
  2205. mqtt_client.state.last_loaded_tray = tn
  2206. assert mqtt_client.state.tray_change_log == []
  2207. def test_tray_change_recorded_during_pause(self, mqtt_client):
  2208. """Tray change while PAUSE is also logged (AMS can swap during pause)."""
  2209. mqtt_client.state.state = "PAUSE"
  2210. mqtt_client.state.layer_num = 75
  2211. mqtt_client.state.last_loaded_tray = 2
  2212. mqtt_client.state.tray_change_log = [(2, 0)]
  2213. mqtt_client.state.tray_now = 5
  2214. tn = mqtt_client.state.tray_now
  2215. if tn != mqtt_client.state.last_loaded_tray and mqtt_client.state.state in ("RUNNING", "PAUSE"):
  2216. mqtt_client.state.tray_change_log.append((tn, mqtt_client.state.layer_num))
  2217. mqtt_client.state.last_loaded_tray = tn
  2218. assert mqtt_client.state.tray_change_log == [(2, 0), (5, 75)]
  2219. def test_same_tray_not_logged_twice(self, mqtt_client):
  2220. """Same tray value doesn't create duplicate log entries."""
  2221. mqtt_client.state.state = "RUNNING"
  2222. mqtt_client.state.layer_num = 30
  2223. mqtt_client.state.last_loaded_tray = 2
  2224. mqtt_client.state.tray_change_log = [(2, 0)]
  2225. # Same tray again
  2226. mqtt_client.state.tray_now = 2
  2227. tn = mqtt_client.state.tray_now
  2228. if tn != mqtt_client.state.last_loaded_tray and mqtt_client.state.state in ("RUNNING", "PAUSE"):
  2229. mqtt_client.state.tray_change_log.append((tn, mqtt_client.state.layer_num))
  2230. mqtt_client.state.last_loaded_tray = tn
  2231. assert mqtt_client.state.tray_change_log == [(2, 0)]
  2232. def test_multiple_tray_changes(self, mqtt_client):
  2233. """Multiple tray changes create a full history."""
  2234. mqtt_client.state.state = "RUNNING"
  2235. mqtt_client.state.last_loaded_tray = 0
  2236. mqtt_client.state.tray_change_log = [(0, 0)]
  2237. changes = [(1, 50), (3, 120), (0, 200)]
  2238. for tray, layer in changes:
  2239. mqtt_client.state.tray_now = tray
  2240. mqtt_client.state.layer_num = layer
  2241. tn = mqtt_client.state.tray_now
  2242. if tn != mqtt_client.state.last_loaded_tray and mqtt_client.state.state in ("RUNNING", "PAUSE"):
  2243. mqtt_client.state.tray_change_log.append((tn, mqtt_client.state.layer_num))
  2244. mqtt_client.state.last_loaded_tray = tn
  2245. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50), (3, 120), (0, 200)]
  2246. class TestDeveloperModeDetection:
  2247. """Tests for developer LAN mode detection from MQTT 'fun' field."""
  2248. @pytest.fixture
  2249. def mqtt_client(self):
  2250. """Create a BambuMQTTClient instance for testing."""
  2251. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2252. client = BambuMQTTClient(
  2253. ip_address="192.168.1.100",
  2254. serial_number="TEST123",
  2255. access_code="12345678",
  2256. )
  2257. return client
  2258. def test_developer_mode_initially_none(self, mqtt_client):
  2259. """Verify developer_mode starts as None (unknown)."""
  2260. assert mqtt_client.state.developer_mode is None
  2261. def test_developer_mode_on_when_bit_clear(self, mqtt_client):
  2262. """Verify developer_mode is True when bit 0x20000000 is clear."""
  2263. # Bit 29 clear in lower 32 bits = developer mode ON
  2264. payload = {
  2265. "print": {
  2266. "gcode_state": "IDLE",
  2267. "fun": "1C8187FF9CFF",
  2268. }
  2269. }
  2270. mqtt_client._process_message(payload)
  2271. assert mqtt_client.state.developer_mode is True
  2272. def test_developer_mode_off_when_bit_set(self, mqtt_client):
  2273. """Verify developer_mode is False when bit 0x20000000 is set."""
  2274. # Bit 29 set in lower 32 bits = developer mode OFF (encryption required)
  2275. payload = {
  2276. "print": {
  2277. "gcode_state": "IDLE",
  2278. "fun": "1C81A7FF9CFF",
  2279. }
  2280. }
  2281. mqtt_client._process_message(payload)
  2282. assert mqtt_client.state.developer_mode is False
  2283. def test_developer_mode_exact_bit_check(self, mqtt_client):
  2284. """Verify only bit 0x20000000 matters, not other bits."""
  2285. # 0x20000000 in hex = bit 29. Set ONLY that bit.
  2286. payload = {
  2287. "print": {
  2288. "gcode_state": "IDLE",
  2289. "fun": "000020000000",
  2290. }
  2291. }
  2292. mqtt_client._process_message(payload)
  2293. assert mqtt_client.state.developer_mode is False
  2294. # All zeros = all bits clear = developer mode ON
  2295. payload["print"]["fun"] = "000000000000"
  2296. mqtt_client._process_message(payload)
  2297. assert mqtt_client.state.developer_mode is True
  2298. def test_developer_mode_invalid_fun_ignored(self, mqtt_client):
  2299. """Verify invalid fun values don't crash or change state."""
  2300. mqtt_client.state.developer_mode = True
  2301. payload = {
  2302. "print": {
  2303. "gcode_state": "IDLE",
  2304. "fun": "not_a_hex_value",
  2305. }
  2306. }
  2307. mqtt_client._process_message(payload)
  2308. # Should remain unchanged
  2309. assert mqtt_client.state.developer_mode is True
  2310. def test_developer_mode_missing_fun_preserves_state(self, mqtt_client):
  2311. """Verify messages without fun field don't reset developer_mode."""
  2312. mqtt_client.state.developer_mode = False
  2313. payload = {
  2314. "print": {
  2315. "gcode_state": "RUNNING",
  2316. "mc_percent": 50,
  2317. }
  2318. }
  2319. mqtt_client._process_message(payload)
  2320. assert mqtt_client.state.developer_mode is False
  2321. def test_developer_mode_persists_across_messages(self, mqtt_client):
  2322. """Verify developer_mode set by fun persists across messages without fun."""
  2323. # First message sets developer_mode
  2324. mqtt_client._process_message(
  2325. {
  2326. "print": {
  2327. "gcode_state": "IDLE",
  2328. "fun": "3EC1AFFF9CFF",
  2329. }
  2330. }
  2331. )
  2332. assert mqtt_client.state.developer_mode is False
  2333. # Subsequent messages without fun don't change it
  2334. for _ in range(3):
  2335. mqtt_client._process_message(
  2336. {
  2337. "print": {
  2338. "gcode_state": "RUNNING",
  2339. "mc_percent": 50,
  2340. }
  2341. }
  2342. )
  2343. assert mqtt_client.state.developer_mode is False
  2344. class TestSendDryingCommand:
  2345. """Tests for send_drying_command MQTT payload construction."""
  2346. @pytest.fixture
  2347. def mqtt_client(self):
  2348. """Create a BambuMQTTClient with a mock MQTT client."""
  2349. from unittest.mock import MagicMock
  2350. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2351. client = BambuMQTTClient(
  2352. ip_address="192.168.1.100",
  2353. serial_number="TEST123",
  2354. access_code="12345678",
  2355. )
  2356. client._client = MagicMock()
  2357. return client
  2358. def test_rotate_tray_false_by_default(self, mqtt_client):
  2359. """Verify rotate_tray defaults to False in the MQTT payload."""
  2360. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  2361. call_args = mqtt_client._client.publish.call_args
  2362. payload = json.loads(call_args[0][1])
  2363. assert payload["print"]["rotate_tray"] is False
  2364. def test_rotate_tray_true_when_enabled(self, mqtt_client):
  2365. """Verify rotate_tray is True when explicitly enabled."""
  2366. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA", rotate_tray=True)
  2367. call_args = mqtt_client._client.publish.call_args
  2368. payload = json.loads(call_args[0][1])
  2369. assert payload["print"]["rotate_tray"] is True
  2370. def test_rotate_tray_false_on_stop(self, mqtt_client):
  2371. """Verify rotate_tray is False when stopping drying (mode=0)."""
  2372. mqtt_client.send_drying_command(ams_id=0, temp=0, duration=0, mode=0)
  2373. call_args = mqtt_client._client.publish.call_args
  2374. payload = json.loads(call_args[0][1])
  2375. assert payload["print"]["rotate_tray"] is False
  2376. def test_all_required_fields_present(self, mqtt_client):
  2377. """Verify all required MQTT fields are present in the drying command."""
  2378. mqtt_client.send_drying_command(ams_id=128, temp=75, duration=8, mode=1, filament="ABS", rotate_tray=True)
  2379. call_args = mqtt_client._client.publish.call_args
  2380. payload = json.loads(call_args[0][1])
  2381. cmd = payload["print"]
  2382. assert cmd["command"] == "ams_filament_drying"
  2383. assert cmd["ams_id"] == 128
  2384. assert cmd["temp"] == 75
  2385. assert cmd["duration"] == 8
  2386. assert cmd["mode"] == 1
  2387. assert cmd["rotate_tray"] is True
  2388. assert cmd["filament"] == "ABS"
  2389. assert cmd["cooling_temp"] == 20
  2390. assert cmd["humidity"] == 0
  2391. assert cmd["close_power_conflict"] is False
  2392. assert "sequence_id" in cmd
  2393. def test_publishes_with_qos_1(self, mqtt_client):
  2394. """Verify drying commands are published with QoS 1."""
  2395. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4)
  2396. call_args = mqtt_client._client.publish.call_args
  2397. # qos may be positional arg [2] or keyword
  2398. qos = call_args.kwargs.get("qos", call_args[0][2] if len(call_args[0]) > 2 else None)
  2399. assert qos == 1
  2400. class TestStartPrintAmsMapping:
  2401. """Tests for ams_mapping/ams_mapping2 construction in start_print().
  2402. BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  2403. ams_mapping and puts the real external spool info only in ams_mapping2.
  2404. Passing raw 254/255 in the flat array causes H2D firmware to fail
  2405. with 0700_8012 "Failed to get AMS mapping table".
  2406. """
  2407. @pytest.fixture
  2408. def mqtt_client(self):
  2409. from unittest.mock import MagicMock
  2410. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2411. client = BambuMQTTClient(
  2412. ip_address="192.168.1.100",
  2413. serial_number="TEST123",
  2414. access_code="12345678",
  2415. )
  2416. client._client = MagicMock()
  2417. client.state.connected = True
  2418. return client
  2419. def _get_published_command(self, mqtt_client):
  2420. """Extract the parsed print command from the last publish call."""
  2421. call_args = mqtt_client._client.publish.call_args
  2422. return json.loads(call_args[0][1])["print"]
  2423. def test_regular_ams_trays_preserved_in_flat_mapping(self, mqtt_client):
  2424. """Regular AMS tray IDs pass through unchanged in flat ams_mapping."""
  2425. mqtt_client.start_print("test.3mf", ams_mapping=[0, 5, 11])
  2426. cmd = self._get_published_command(mqtt_client)
  2427. assert cmd["ams_mapping"] == [0, 5, 11]
  2428. assert cmd["ams_mapping2"] == [
  2429. {"ams_id": 0, "slot_id": 0},
  2430. {"ams_id": 1, "slot_id": 1},
  2431. {"ams_id": 2, "slot_id": 3},
  2432. ]
  2433. def test_unmapped_slots(self, mqtt_client):
  2434. """Unmapped slots (-1) produce -1 in flat and 0xFF/0xFF in mapping2."""
  2435. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1])
  2436. cmd = self._get_published_command(mqtt_client)
  2437. assert cmd["ams_mapping"] == [-1, -1]
  2438. assert cmd["ams_mapping2"] == [
  2439. {"ams_id": 255, "slot_id": 255},
  2440. {"ams_id": 255, "slot_id": 255},
  2441. ]
  2442. def test_external_main_nozzle_becomes_minus_one_in_flat(self, mqtt_client):
  2443. """Virtual tray 255 (main nozzle) must be -1 in flat mapping."""
  2444. mqtt_client.start_print("test.3mf", ams_mapping=[255])
  2445. cmd = self._get_published_command(mqtt_client)
  2446. assert cmd["ams_mapping"] == [-1]
  2447. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  2448. def test_external_deputy_nozzle_becomes_minus_one_in_flat(self, mqtt_client):
  2449. """Virtual tray 254 (deputy nozzle) must be -1 in flat mapping."""
  2450. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  2451. cmd = self._get_published_command(mqtt_client)
  2452. assert cmd["ams_mapping"] == [-1]
  2453. assert cmd["ams_mapping2"] == [{"ams_id": 254, "slot_id": 0}]
  2454. def test_h2d_external_spool_mixed_with_ams(self, mqtt_client):
  2455. """H2D scenario: AMS trays + unmapped + external deputy nozzle."""
  2456. # Reproduces the exact scenario from issue #797:
  2457. # 5-slot 3MF, only slot 5 assigned to external deputy nozzle (254)
  2458. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1, -1, -1, 255])
  2459. cmd = self._get_published_command(mqtt_client)
  2460. # Flat mapping: all -1 (external converted, unmapped stay -1)
  2461. assert cmd["ams_mapping"] == [-1, -1, -1, -1, -1]
  2462. # Detailed mapping: unmapped slots use 0xFF, external uses real ams_id
  2463. assert cmd["ams_mapping2"] == [
  2464. {"ams_id": 255, "slot_id": 255},
  2465. {"ams_id": 255, "slot_id": 255},
  2466. {"ams_id": 255, "slot_id": 255},
  2467. {"ams_id": 255, "slot_id": 255},
  2468. {"ams_id": 255, "slot_id": 0},
  2469. ]
  2470. def test_ams_ht_trays_preserved_in_flat_mapping(self, mqtt_client):
  2471. """AMS-HT tray IDs (>=128) pass through in flat mapping."""
  2472. mqtt_client.start_print("test.3mf", ams_mapping=[128, 131])
  2473. cmd = self._get_published_command(mqtt_client)
  2474. assert cmd["ams_mapping"] == [128, 131]
  2475. assert cmd["ams_mapping2"] == [
  2476. {"ams_id": 128, "slot_id": 0},
  2477. {"ams_id": 131, "slot_id": 0},
  2478. ]
  2479. def test_dual_nozzle_both_external(self, mqtt_client):
  2480. """Both nozzles using external spools: 254 (deputy) + 255 (main)."""
  2481. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  2482. cmd = self._get_published_command(mqtt_client)
  2483. assert cmd["ams_mapping"] == [-1, -1]
  2484. assert cmd["ams_mapping2"] == [
  2485. {"ams_id": 254, "slot_id": 0},
  2486. {"ams_id": 255, "slot_id": 0},
  2487. ]
  2488. def test_no_ams_mapping_omits_fields(self, mqtt_client):
  2489. """When ams_mapping is None, neither field is in the command."""
  2490. mqtt_client.start_print("test.3mf", ams_mapping=None)
  2491. cmd = self._get_published_command(mqtt_client)
  2492. assert "ams_mapping" not in cmd
  2493. assert "ams_mapping2" not in cmd