test_bambu_mqtt.py 244 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072
  1. """
  2. Tests for the BambuMQTTClient service.
  3. These tests focus on timelapse tracking during prints.
  4. """
  5. import json
  6. import time
  7. import pytest
  8. class TestTimelapseTracking:
  9. """Tests for timelapse state tracking during prints."""
  10. @pytest.fixture
  11. def mqtt_client(self):
  12. """Create a BambuMQTTClient instance for testing."""
  13. from backend.app.services.bambu_mqtt import BambuMQTTClient
  14. client = BambuMQTTClient(
  15. ip_address="192.168.1.100",
  16. serial_number="TEST123",
  17. access_code="12345678",
  18. )
  19. return client
  20. def test_timelapse_flag_initializes_to_false(self, mqtt_client):
  21. """Verify _timelapse_during_print starts as False."""
  22. assert mqtt_client._timelapse_during_print is False
  23. def test_timelapse_flag_set_when_timelapse_active_during_running(self, mqtt_client):
  24. """Verify timelapse flag is set when timelapse is active while printing."""
  25. # Simulate print running
  26. mqtt_client._was_running = True
  27. mqtt_client.state.timelapse = False
  28. # Simulate xcam data showing timelapse is enabled
  29. xcam_data = {"timelapse": "enable"}
  30. mqtt_client._parse_xcam_data(xcam_data)
  31. assert mqtt_client.state.timelapse is True
  32. assert mqtt_client._timelapse_during_print is True
  33. def test_timelapse_flag_not_set_when_not_running(self, mqtt_client):
  34. """Verify timelapse flag is NOT set when printer not running."""
  35. # Printer is idle (not running)
  36. mqtt_client._was_running = False
  37. mqtt_client.state.timelapse = False
  38. # Timelapse is enabled but we're not printing
  39. xcam_data = {"timelapse": "enable"}
  40. mqtt_client._parse_xcam_data(xcam_data)
  41. assert mqtt_client.state.timelapse is True
  42. # Flag should NOT be set since we're not printing
  43. assert mqtt_client._timelapse_during_print is False
  44. def test_timelapse_flag_persists_after_timelapse_stops(self, mqtt_client):
  45. """Verify timelapse flag stays True even after recording stops."""
  46. # Simulate print running with timelapse
  47. mqtt_client._was_running = True
  48. # Enable timelapse during print
  49. xcam_data = {"timelapse": "enable"}
  50. mqtt_client._parse_xcam_data(xcam_data)
  51. assert mqtt_client._timelapse_during_print is True
  52. # Disable timelapse (recording stops at end of print)
  53. xcam_data = {"timelapse": "disable"}
  54. mqtt_client._parse_xcam_data(xcam_data)
  55. # Flag should still be True (persists until reset)
  56. assert mqtt_client.state.timelapse is False
  57. assert mqtt_client._timelapse_during_print is True
  58. def test_timelapse_flag_from_print_data(self, mqtt_client):
  59. """Verify timelapse flag is set from print data (not just xcam)."""
  60. # Simulate print running
  61. mqtt_client._was_running = True
  62. mqtt_client.state.timelapse = False
  63. mqtt_client._timelapse_during_print = False
  64. # Manually test the timelapse parsing logic from _parse_print_data
  65. # This tests the "timelapse" field in the main print data
  66. data = {"timelapse": True}
  67. mqtt_client.state.timelapse = data["timelapse"] is True
  68. if mqtt_client.state.timelapse and mqtt_client._was_running:
  69. mqtt_client._timelapse_during_print = True
  70. assert mqtt_client._timelapse_during_print is True
  71. class TestPrintCompletionWithTimelapse:
  72. """Tests for print completion including timelapse flag."""
  73. @pytest.fixture
  74. def mqtt_client(self):
  75. """Create a BambuMQTTClient instance for testing."""
  76. from backend.app.services.bambu_mqtt import BambuMQTTClient
  77. client = BambuMQTTClient(
  78. ip_address="192.168.1.100",
  79. serial_number="TEST123",
  80. access_code="12345678",
  81. )
  82. return client
  83. def test_print_complete_includes_timelapse_flag(self, mqtt_client):
  84. """Verify print complete callback includes timelapse_was_active."""
  85. # Set up completion callback
  86. callback_data = {}
  87. def on_complete(data):
  88. callback_data.update(data)
  89. mqtt_client.on_print_complete = on_complete
  90. # Simulate a print that had timelapse active
  91. mqtt_client._was_running = True
  92. mqtt_client._completion_triggered = False
  93. mqtt_client._timelapse_during_print = True
  94. mqtt_client._previous_gcode_state = "RUNNING"
  95. mqtt_client._previous_gcode_file = "test.gcode"
  96. mqtt_client.state.subtask_name = "Test Print"
  97. # Simulate print finish
  98. mqtt_client.state.state = "FINISH"
  99. # Manually trigger the completion logic (simplified)
  100. # In real code this happens in _parse_print_data
  101. should_trigger = (
  102. mqtt_client.state.state in ("FINISH", "FAILED")
  103. and not mqtt_client._completion_triggered
  104. and mqtt_client.on_print_complete
  105. and mqtt_client._previous_gcode_state == "RUNNING"
  106. )
  107. if should_trigger:
  108. status = "completed" if mqtt_client.state.state == "FINISH" else "failed"
  109. timelapse_was_active = mqtt_client._timelapse_during_print
  110. mqtt_client._completion_triggered = True
  111. mqtt_client._was_running = False
  112. mqtt_client._timelapse_during_print = False
  113. mqtt_client.on_print_complete(
  114. {
  115. "status": status,
  116. "filename": mqtt_client._previous_gcode_file,
  117. "subtask_name": mqtt_client.state.subtask_name,
  118. "timelapse_was_active": timelapse_was_active,
  119. }
  120. )
  121. assert "timelapse_was_active" in callback_data
  122. assert callback_data["timelapse_was_active"] is True
  123. def test_print_complete_timelapse_flag_false_when_no_timelapse(self, mqtt_client):
  124. """Verify timelapse_was_active is False when no timelapse during print."""
  125. callback_data = {}
  126. def on_complete(data):
  127. callback_data.update(data)
  128. mqtt_client.on_print_complete = on_complete
  129. # Print without timelapse
  130. mqtt_client._was_running = True
  131. mqtt_client._completion_triggered = False
  132. mqtt_client._timelapse_during_print = False # No timelapse
  133. mqtt_client._previous_gcode_state = "RUNNING"
  134. mqtt_client._previous_gcode_file = "test.gcode"
  135. mqtt_client.state.subtask_name = "Test Print"
  136. mqtt_client.state.state = "FINISH"
  137. # Trigger completion
  138. timelapse_was_active = mqtt_client._timelapse_during_print
  139. mqtt_client.on_print_complete(
  140. {
  141. "status": "completed",
  142. "filename": mqtt_client._previous_gcode_file,
  143. "subtask_name": mqtt_client.state.subtask_name,
  144. "timelapse_was_active": timelapse_was_active,
  145. }
  146. )
  147. assert callback_data["timelapse_was_active"] is False
  148. def test_timelapse_flag_reset_after_completion(self, mqtt_client):
  149. """Verify _timelapse_during_print is reset after print completion."""
  150. mqtt_client._timelapse_during_print = True
  151. mqtt_client._was_running = True
  152. mqtt_client._completion_triggered = False
  153. # Simulate completion reset
  154. mqtt_client._completion_triggered = True
  155. mqtt_client._was_running = False
  156. mqtt_client._timelapse_during_print = False
  157. assert mqtt_client._timelapse_during_print is False
  158. class TestRealisticMessageFlow:
  159. """Tests that simulate realistic MQTT message sequences.
  160. These tests process messages through _process_message to test the full flow,
  161. including the order of xcam parsing vs state detection.
  162. """
  163. @pytest.fixture
  164. def mqtt_client(self):
  165. """Create a BambuMQTTClient instance for testing."""
  166. from backend.app.services.bambu_mqtt import BambuMQTTClient
  167. client = BambuMQTTClient(
  168. ip_address="192.168.1.100",
  169. serial_number="TEST123",
  170. access_code="12345678",
  171. )
  172. return client
  173. def test_timelapse_detected_at_print_start_in_same_message(self, mqtt_client):
  174. """Test that timelapse is detected when xcam and state come in same message.
  175. This is the critical race condition test - xcam data is parsed BEFORE
  176. state detection, so the timelapse flag must be set AFTER _was_running is True.
  177. """
  178. # Callbacks to track events
  179. start_callback_data = {}
  180. def on_start(data):
  181. start_callback_data.update(data)
  182. mqtt_client.on_print_start = on_start
  183. # Initial state - idle
  184. mqtt_client._was_running = False
  185. mqtt_client._timelapse_during_print = False
  186. mqtt_client._previous_gcode_state = None
  187. # Simulate first message when print starts - contains both xcam and gcode_state
  188. # This is the realistic scenario from the printer
  189. # NOTE: Real MQTT messages wrap print data inside a "print" key
  190. payload = {
  191. "print": {
  192. "gcode_state": "RUNNING",
  193. "gcode_file": "/data/Metadata/test_print.gcode",
  194. "subtask_name": "Test_Print",
  195. "xcam": {
  196. "timelapse": "enable", # Timelapse is enabled in this print
  197. "printing_monitor": True,
  198. },
  199. "mc_percent": 0,
  200. "mc_remaining_time": 3600,
  201. }
  202. }
  203. # Process the message (this is what happens in real MQTT flow)
  204. mqtt_client._process_message(payload)
  205. # Verify timelapse was detected even though xcam is parsed before state
  206. assert mqtt_client._was_running is True, "_was_running should be True after RUNNING state"
  207. assert mqtt_client.state.timelapse is True, "state.timelapse should be True"
  208. assert mqtt_client._timelapse_during_print is True, (
  209. "timelapse_during_print should be True when timelapse is in the same message as RUNNING state"
  210. )
  211. def test_timelapse_not_detected_when_disabled(self, mqtt_client):
  212. """Test that timelapse is NOT detected when disabled in xcam data."""
  213. mqtt_client.on_print_start = lambda data: None
  214. # Initial state - idle
  215. mqtt_client._was_running = False
  216. mqtt_client._timelapse_during_print = False
  217. mqtt_client._previous_gcode_state = None
  218. # Print starts without timelapse
  219. payload = {
  220. "print": {
  221. "gcode_state": "RUNNING",
  222. "gcode_file": "/data/Metadata/test_print.gcode",
  223. "subtask_name": "Test_Print",
  224. "xcam": {
  225. "timelapse": "disable", # Timelapse is disabled
  226. "printing_monitor": True,
  227. },
  228. }
  229. }
  230. mqtt_client._process_message(payload)
  231. assert mqtt_client._was_running is True
  232. assert mqtt_client.state.timelapse is False
  233. assert mqtt_client._timelapse_during_print is False
  234. def test_timelapse_detected_when_enabled_after_print_start(self, mqtt_client):
  235. """Test timelapse detected when enabled in a message after print starts."""
  236. mqtt_client.on_print_start = lambda data: None
  237. # First message - print starts without timelapse info
  238. payload_start = {
  239. "print": {
  240. "gcode_state": "RUNNING",
  241. "gcode_file": "/data/Metadata/test_print.gcode",
  242. "subtask_name": "Test_Print",
  243. }
  244. }
  245. mqtt_client._process_message(payload_start)
  246. assert mqtt_client._was_running is True
  247. assert mqtt_client._timelapse_during_print is False # Not detected yet
  248. # Second message - xcam data arrives with timelapse enabled
  249. payload_xcam = {
  250. "print": {
  251. "gcode_state": "RUNNING",
  252. "gcode_file": "/data/Metadata/test_print.gcode",
  253. "subtask_name": "Test_Print",
  254. "xcam": {
  255. "timelapse": "enable",
  256. },
  257. }
  258. }
  259. mqtt_client._process_message(payload_xcam)
  260. # Now timelapse should be detected because _was_running is already True
  261. assert mqtt_client._timelapse_during_print is True
  262. def test_print_complete_includes_timelapse_flag_full_flow(self, mqtt_client):
  263. """Test full print lifecycle with timelapse - from start to completion."""
  264. start_data = {}
  265. complete_data = {}
  266. def on_start(data):
  267. start_data.update(data)
  268. def on_complete(data):
  269. complete_data.update(data)
  270. mqtt_client.on_print_start = on_start
  271. mqtt_client.on_print_complete = on_complete
  272. # Seed a prior state so the first RUNNING push is treated as a real
  273. # state transition rather than a Bambuddy-restart catch-up (#1304).
  274. mqtt_client._previous_gcode_state = "IDLE"
  275. # 1. Print starts with timelapse
  276. mqtt_client._process_message(
  277. {
  278. "print": {
  279. "gcode_state": "RUNNING",
  280. "gcode_file": "/data/Metadata/test.gcode",
  281. "subtask_name": "Test",
  282. "xcam": {"timelapse": "enable"},
  283. }
  284. }
  285. )
  286. assert mqtt_client._timelapse_during_print is True
  287. assert "subtask_name" in start_data
  288. # 2. Print continues (multiple messages)
  289. for _ in range(3):
  290. mqtt_client._process_message(
  291. {
  292. "print": {
  293. "gcode_state": "RUNNING",
  294. "gcode_file": "/data/Metadata/test.gcode",
  295. "subtask_name": "Test",
  296. "mc_percent": 50,
  297. }
  298. }
  299. )
  300. # Timelapse flag should still be True
  301. assert mqtt_client._timelapse_during_print is True
  302. # 3. Print completes
  303. mqtt_client._process_message(
  304. {
  305. "print": {
  306. "gcode_state": "FINISH",
  307. "gcode_file": "/data/Metadata/test.gcode",
  308. "subtask_name": "Test",
  309. }
  310. }
  311. )
  312. # Verify completion callback received timelapse flag
  313. assert "timelapse_was_active" in complete_data
  314. assert complete_data["timelapse_was_active"] is True
  315. assert complete_data["status"] == "completed"
  316. # Flags should be reset after completion
  317. assert mqtt_client._timelapse_during_print is False
  318. assert mqtt_client._was_running is False
  319. def test_print_failed_includes_timelapse_flag(self, mqtt_client):
  320. """Test that failed print also includes timelapse flag."""
  321. complete_data = {}
  322. def on_complete(data):
  323. complete_data.update(data)
  324. mqtt_client.on_print_start = lambda data: None
  325. mqtt_client.on_print_complete = on_complete
  326. # Start with timelapse
  327. mqtt_client._process_message(
  328. {
  329. "print": {
  330. "gcode_state": "RUNNING",
  331. "gcode_file": "/data/Metadata/test.gcode",
  332. "subtask_name": "Test",
  333. "xcam": {"timelapse": "enable"},
  334. }
  335. }
  336. )
  337. # Print fails
  338. mqtt_client._process_message(
  339. {
  340. "print": {
  341. "gcode_state": "FAILED",
  342. "gcode_file": "/data/Metadata/test.gcode",
  343. "subtask_name": "Test",
  344. }
  345. }
  346. )
  347. assert complete_data["timelapse_was_active"] is True
  348. assert complete_data["status"] == "failed"
  349. class TestPrePrintFailureCompletion:
  350. """Tests for completion detection when the print errors before reaching RUNNING (#1111).
  351. Common trigger: a file sliced for the wrong nozzle diameter is dispatched. The
  352. printer transitions IDLE -> PREPARE -> FAILED without ever entering RUNNING, so
  353. the legacy completion detection (which required _previous_gcode_state == 'RUNNING'
  354. or _was_running == True) left the queue item stuck at 'printing' forever.
  355. """
  356. @pytest.fixture
  357. def mqtt_client(self):
  358. from backend.app.services.bambu_mqtt import BambuMQTTClient
  359. return BambuMQTTClient(
  360. ip_address="192.168.1.100",
  361. serial_number="TEST123",
  362. access_code="12345678",
  363. )
  364. def test_prepare_to_failed_triggers_completion(self, mqtt_client):
  365. """PREPARE -> FAILED must fire on_print_complete (wrong nozzle size etc.)."""
  366. complete_data = {}
  367. mqtt_client.on_print_start = lambda data: None
  368. mqtt_client.on_print_complete = lambda data: complete_data.update(data)
  369. mqtt_client._previous_gcode_state = "PREPARE"
  370. mqtt_client._was_running = False
  371. mqtt_client._completion_triggered = False
  372. mqtt_client._process_message(
  373. {
  374. "print": {
  375. "gcode_state": "FAILED",
  376. "gcode_file": "/data/Metadata/plate_1.gcode",
  377. "subtask_name": "WrongNozzle",
  378. }
  379. }
  380. )
  381. assert complete_data.get("status") == "failed"
  382. def test_slicing_to_failed_triggers_completion(self, mqtt_client):
  383. """SLICING -> FAILED also treated as a pre-print failure."""
  384. complete_data = {}
  385. mqtt_client.on_print_start = lambda data: None
  386. mqtt_client.on_print_complete = lambda data: complete_data.update(data)
  387. mqtt_client._previous_gcode_state = "SLICING"
  388. mqtt_client._was_running = False
  389. mqtt_client._completion_triggered = False
  390. mqtt_client._process_message(
  391. {
  392. "print": {
  393. "gcode_state": "FAILED",
  394. "gcode_file": "/data/Metadata/plate_1.gcode",
  395. "subtask_name": "WrongNozzle",
  396. }
  397. }
  398. )
  399. assert complete_data.get("status") == "failed"
  400. def test_initial_failed_does_not_trigger_completion(self, mqtt_client):
  401. """First message arriving with FAILED (no prior state) must NOT fire completion.
  402. Protects against a stale FAILED on reconnect being mistaken for a fresh failure
  403. and marking an unrelated queue item as failed.
  404. """
  405. calls = []
  406. mqtt_client.on_print_start = lambda data: None
  407. mqtt_client.on_print_complete = lambda data: calls.append(data)
  408. assert mqtt_client._previous_gcode_state is None
  409. assert mqtt_client._was_running is False
  410. mqtt_client._process_message(
  411. {
  412. "print": {
  413. "gcode_state": "FAILED",
  414. "gcode_file": "/data/Metadata/plate_1.gcode",
  415. "subtask_name": "Stale",
  416. }
  417. }
  418. )
  419. assert calls == []
  420. def test_idle_to_failed_does_not_trigger_completion(self, mqtt_client):
  421. """IDLE -> FAILED (no print ever dispatched) must NOT fire completion."""
  422. calls = []
  423. mqtt_client.on_print_start = lambda data: None
  424. mqtt_client.on_print_complete = lambda data: calls.append(data)
  425. mqtt_client._previous_gcode_state = "IDLE"
  426. mqtt_client._was_running = False
  427. mqtt_client._completion_triggered = False
  428. mqtt_client._process_message(
  429. {
  430. "print": {
  431. "gcode_state": "FAILED",
  432. "subtask_name": "Stale",
  433. }
  434. }
  435. )
  436. assert calls == []
  437. def test_prepare_to_failed_includes_hms_errors_in_callback(self, mqtt_client):
  438. """Pre-print FAILED callback should carry the current HMS error list so the
  439. queue handler can populate a meaningful error_message."""
  440. complete_data = {}
  441. mqtt_client.on_print_start = lambda data: None
  442. mqtt_client.on_print_complete = lambda data: complete_data.update(data)
  443. mqtt_client._previous_gcode_state = "PREPARE"
  444. mqtt_client._was_running = False
  445. # Message carries HMS data for a nozzle-size mismatch (0500_4038) and the
  446. # PREPARE -> FAILED gcode_state transition in a single update.
  447. mqtt_client._process_message(
  448. {
  449. "print": {
  450. "gcode_state": "FAILED",
  451. "gcode_file": "/data/Metadata/plate_1.gcode",
  452. "hms": [{"attr": 0x05000000, "code": 0x4038}],
  453. }
  454. }
  455. )
  456. assert complete_data.get("status") == "failed"
  457. errs = complete_data.get("hms_errors") or []
  458. assert any(e.get("code") == "0x4038" for e in errs)
  459. class TestAMSDataMerging:
  460. """Tests for AMS data merging, particularly handling empty slots."""
  461. @pytest.fixture
  462. def mqtt_client(self):
  463. """Create a BambuMQTTClient instance for testing."""
  464. from backend.app.services.bambu_mqtt import BambuMQTTClient
  465. client = BambuMQTTClient(
  466. ip_address="192.168.1.100",
  467. serial_number="TEST123",
  468. access_code="12345678",
  469. )
  470. return client
  471. def test_empty_slot_clears_tray_type(self, mqtt_client):
  472. """Test that empty slot update clears tray_type (Issue #147).
  473. When a spool is removed from an old AMS, the printer sends empty values.
  474. These must overwrite the previous values to show the slot as empty.
  475. """
  476. # Initial state: AMS unit with a loaded spool
  477. initial_ams = {
  478. "ams": [
  479. {
  480. "id": 0,
  481. "tray": [
  482. {
  483. "id": 0,
  484. "tray_type": "PLA",
  485. "tray_sub_brands": "Bambu PLA Basic",
  486. "tray_color": "FF0000",
  487. "tag_uid": "1234567890ABCDEF",
  488. "remain": 80,
  489. }
  490. ],
  491. }
  492. ]
  493. }
  494. mqtt_client._handle_ams_data(initial_ams)
  495. # Verify initial state
  496. ams_data = mqtt_client.state.raw_data.get("ams", [])
  497. assert len(ams_data) == 1
  498. tray = ams_data[0]["tray"][0]
  499. assert tray["tray_type"] == "PLA"
  500. assert tray["tray_color"] == "FF0000"
  501. # Now simulate spool removal - printer sends empty values
  502. empty_update = {
  503. "ams": [
  504. {
  505. "id": 0,
  506. "tray": [
  507. {
  508. "id": 0,
  509. "tray_type": "", # Empty = slot is empty
  510. "tray_sub_brands": "",
  511. "tray_color": "",
  512. "tag_uid": "0000000000000000", # Zero UID
  513. "remain": 0,
  514. }
  515. ],
  516. }
  517. ]
  518. }
  519. mqtt_client._handle_ams_data(empty_update)
  520. # Verify empty values were applied (not ignored by merge logic)
  521. ams_data = mqtt_client.state.raw_data.get("ams", [])
  522. tray = ams_data[0]["tray"][0]
  523. assert tray["tray_type"] == "", "tray_type should be cleared when slot is empty"
  524. assert tray["tray_color"] == "", "tray_color should be cleared when slot is empty"
  525. assert tray["tray_sub_brands"] == "", "tray_sub_brands should be cleared"
  526. assert tray["tag_uid"] == "0000000000000000", "tag_uid should be cleared"
  527. def test_partial_update_preserves_other_fields(self, mqtt_client):
  528. """Test that partial updates still preserve non-slot-status fields."""
  529. # Initial state with full data
  530. initial_ams = {
  531. "ams": [
  532. {
  533. "id": 0,
  534. "humidity": "3",
  535. "temp": "25.5",
  536. "tray": [
  537. {
  538. "id": 0,
  539. "tray_type": "PLA",
  540. "tray_color": "00FF00",
  541. "remain": 90,
  542. "k": 0.02,
  543. }
  544. ],
  545. }
  546. ]
  547. }
  548. mqtt_client._handle_ams_data(initial_ams)
  549. # Partial update - only remain changes
  550. partial_update = {
  551. "ams": [
  552. {
  553. "id": 0,
  554. "tray": [
  555. {
  556. "id": 0,
  557. "remain": 85, # Only this changed
  558. }
  559. ],
  560. }
  561. ]
  562. }
  563. mqtt_client._handle_ams_data(partial_update)
  564. # Verify remain was updated but other fields preserved
  565. ams_data = mqtt_client.state.raw_data.get("ams", [])
  566. tray = ams_data[0]["tray"][0]
  567. assert tray["remain"] == 85, "remain should be updated"
  568. assert tray["tray_type"] == "PLA", "tray_type should be preserved"
  569. assert tray["tray_color"] == "00FF00", "tray_color should be preserved"
  570. assert tray["k"] == 0.02, "k should be preserved"
  571. def test_tray_exist_bits_clears_empty_slots(self, mqtt_client):
  572. """Test that tray_exist_bits clears slots marked as empty (Issue #147).
  573. New AMS models (AMS 2 Pro) don't send empty tray data when a spool is removed.
  574. Instead, they update tray_exist_bits to indicate which slots have spools.
  575. """
  576. # Initial state: AMS 0 and AMS 1 with loaded spools
  577. initial_ams = {
  578. "ams": [
  579. {
  580. "id": 0,
  581. "tray": [
  582. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  583. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00", "remain": 60},
  584. {"id": 2, "tray_type": "ABS", "tray_color": "0000FF", "remain": 40},
  585. {"id": 3, "tray_type": "TPU", "tray_color": "FFFF00", "remain": 20},
  586. ],
  587. },
  588. {
  589. "id": 1,
  590. "tray": [
  591. {"id": 0, "tray_type": "PLA", "tray_color": "FFFFFF", "remain": 90},
  592. {"id": 1, "tray_type": "PLA", "tray_color": "000000", "remain": 70},
  593. {"id": 2, "tray_type": "PLA", "tray_color": "FF00FF", "remain": 50},
  594. {"id": 3, "tray_type": "PLA", "tray_color": "00FFFF", "remain": 30},
  595. ],
  596. },
  597. ],
  598. "tray_exist_bits": "ff", # All 8 slots have spools (0xFF = 11111111)
  599. }
  600. mqtt_client._handle_ams_data(initial_ams)
  601. # Verify initial state
  602. ams_data = mqtt_client.state.raw_data.get("ams", [])
  603. assert ams_data[1]["tray"][3]["tray_type"] == "PLA" # AMS 1 slot 3 (B4) has spool
  604. # Now simulate spool removal from AMS 1 slot 3 (B4)
  605. # tray_exist_bits: 0x7f = 01111111 (bit 7 = 0 means AMS 1 slot 3 is empty)
  606. update_ams = {
  607. "ams": [
  608. {"id": 0, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]},
  609. {"id": 1, "tray": [{"id": 0}, {"id": 1}, {"id": 2}, {"id": 3}]},
  610. ],
  611. "tray_exist_bits": "7f", # Bit 7 = 0 -> AMS 1 slot 3 is empty
  612. }
  613. mqtt_client._handle_ams_data(update_ams)
  614. # Verify AMS 1 slot 3 was cleared
  615. ams_data = mqtt_client.state.raw_data.get("ams", [])
  616. b4_tray = ams_data[1]["tray"][3]
  617. assert b4_tray["tray_type"] == "", "tray_type should be cleared for empty slot"
  618. assert b4_tray["remain"] == 0, "remain should be 0 for empty slot"
  619. # Verify other slots are preserved
  620. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "A1 should still have PLA"
  621. assert ams_data[1]["tray"][0]["tray_type"] == "PLA", "B1 should still have PLA"
  622. def test_tray_exist_bits_promotes_empty_slot_to_state_9(self, mqtt_client):
  623. """#1322 follow-up by @RosdasHH: the previous fix only caught the bare
  624. {"id": N} payload firmware sends right after a printer restart. In
  625. steady-state operation firmware sends a populated payload and signals
  626. emptiness via tray_exist_bits — the canonical BambuStudio detection.
  627. The bitmask handler now promotes empty slots to state=9 so the rest
  628. of the app (API serializer, inventory short-circuit, AMS card) sees
  629. one signal instead of guessing from payload shape.
  630. State must be int 9, not "9" — `tray_state in {9, 10}` downstream
  631. uses `==` comparison and would silently miss a string.
  632. """
  633. initial_ams = {
  634. "ams": [
  635. {
  636. "id": 0,
  637. "tray": [
  638. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "state": 11, "remain": 80},
  639. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00", "state": 11, "remain": 60},
  640. ],
  641. }
  642. ],
  643. "tray_exist_bits": "3", # both slots occupied (0b11)
  644. }
  645. mqtt_client._handle_ams_data(initial_ams)
  646. # Slot 1 goes empty — populated payload, only the bitmask says so.
  647. update_ams = {
  648. "ams": [{"id": 0, "tray": [{"id": 0}, {"id": 1}]}],
  649. "tray_exist_bits": "1", # slot 1 now empty (0b01)
  650. }
  651. mqtt_client._handle_ams_data(update_ams)
  652. slot1 = mqtt_client.state.raw_data["ams"][0]["tray"][1]
  653. assert slot1["state"] == 9, "empty-by-bitmask slot must report state=9"
  654. assert isinstance(slot1["state"], int), "state must be int for downstream == comparison"
  655. # Loaded slot keeps its firmware state unchanged.
  656. slot0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  657. assert slot0["state"] == 11, "loaded slot must keep its firmware state"
  658. def test_tray_exist_bits_does_not_change_state_on_loaded_slots(self, mqtt_client):
  659. """Belt and suspenders for the negative path: the new state=9
  660. promotion must fire ONLY when the bitmask bit is 0. A loaded slot
  661. with state=3 (or any other non-9 firmware value) must pass through
  662. untouched, or we'd corrupt every printer that sends transitional
  663. states like 'unloading'."""
  664. initial_ams = {
  665. "ams": [
  666. {
  667. "id": 0,
  668. "tray": [
  669. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "state": 3, "remain": 80},
  670. ],
  671. }
  672. ],
  673. "tray_exist_bits": "1", # slot occupied
  674. }
  675. mqtt_client._handle_ams_data(initial_ams)
  676. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["state"] == 3
  677. def test_shutdown_message_preserves_ams_data(self, mqtt_client):
  678. """Printer shutdown (power_on_flag=False) must not wipe AMS slot data (#765).
  679. When a printer shuts down it sends a final MQTT message with
  680. tray_exist_bits='0' and power_on_flag=False. This all-zero value
  681. previously caused every slot to be cleared, which then triggered
  682. auto-unlink of all spool assignments on reconnect.
  683. """
  684. # Initial state: two AMS units with loaded spools
  685. initial_ams = {
  686. "ams": [
  687. {
  688. "id": 0,
  689. "tray": [
  690. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF", "remain": 80},
  691. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00FF", "remain": 60},
  692. ],
  693. },
  694. {
  695. "id": 1,
  696. "tray": [
  697. {"id": 0, "tray_type": "PETG", "tray_color": "DBDDD9FF", "remain": 90},
  698. {"id": 1, "tray_type": "PETG", "tray_color": "67DB25FF", "remain": 70},
  699. ],
  700. },
  701. ],
  702. "tray_exist_bits": "33", # Slots 0,1 of each AMS (0b00110011)
  703. "power_on_flag": True,
  704. }
  705. mqtt_client._handle_ams_data(initial_ams)
  706. # Verify initial state
  707. ams_data = mqtt_client.state.raw_data["ams"]
  708. assert ams_data[0]["tray"][0]["tray_type"] == "PLA"
  709. assert ams_data[1]["tray"][0]["tray_type"] == "PETG"
  710. # Simulate printer shutdown — all-zero bits with power_on_flag=False
  711. shutdown_ams = {
  712. "ams_exist_bits": "0",
  713. "tray_exist_bits": "0",
  714. "power_on_flag": False,
  715. "insert_flag": False,
  716. "tray_now": "0",
  717. "version": 0,
  718. }
  719. mqtt_client._handle_ams_data(shutdown_ams)
  720. # AMS slot data MUST be preserved — shutdown should not clear it
  721. ams_data = mqtt_client.state.raw_data["ams"]
  722. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "Shutdown must not clear AMS 0 slot 0"
  723. assert ams_data[0]["tray"][0]["tray_color"] == "FF0000FF", "Shutdown must not clear AMS 0 slot 0 color"
  724. assert ams_data[0]["tray"][1]["tray_type"] == "PETG", "Shutdown must not clear AMS 0 slot 1"
  725. assert ams_data[1]["tray"][0]["tray_type"] == "PETG", "Shutdown must not clear AMS 1 slot 0"
  726. assert ams_data[1]["tray"][1]["tray_type"] == "PETG", "Shutdown must not clear AMS 1 slot 1"
  727. def test_genuine_removal_still_clears_with_power_on(self, mqtt_client):
  728. """Genuine spool removal (power_on_flag=True) must still clear slot data.
  729. Ensures the #765 fix doesn't break normal spool removal detection.
  730. """
  731. # Initial state: AMS with loaded spool
  732. initial_ams = {
  733. "ams": [
  734. {
  735. "id": 0,
  736. "tray": [
  737. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  738. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00", "remain": 60},
  739. ],
  740. },
  741. ],
  742. "tray_exist_bits": "3", # Both slots occupied (0b11)
  743. "power_on_flag": True,
  744. }
  745. mqtt_client._handle_ams_data(initial_ams)
  746. # Spool removed from slot 1 while printer is running
  747. removal_ams = {
  748. "ams": [
  749. {
  750. "id": 0,
  751. "tray": [{"id": 0}, {"id": 1}],
  752. },
  753. ],
  754. "tray_exist_bits": "1", # Only slot 0 occupied (0b01)
  755. "power_on_flag": True,
  756. }
  757. mqtt_client._handle_ams_data(removal_ams)
  758. # Slot 0 preserved, slot 1 cleared
  759. ams_data = mqtt_client.state.raw_data["ams"]
  760. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "Slot 0 should be preserved"
  761. assert ams_data[0]["tray"][1]["tray_type"] == "", "Slot 1 should be cleared on removal"
  762. assert ams_data[0]["tray"][1]["tray_color"] == "", "Slot 1 color should be cleared"
  763. def test_power_on_flag_defaults_true_when_absent(self, mqtt_client):
  764. """When power_on_flag is not in the MQTT data, clearing must proceed normally.
  765. Ensures backwards compatibility with firmware that doesn't send power_on_flag.
  766. """
  767. # Initial state
  768. initial_ams = {
  769. "ams": [
  770. {
  771. "id": 0,
  772. "tray": [
  773. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000", "remain": 80},
  774. ],
  775. },
  776. ],
  777. "tray_exist_bits": "1",
  778. }
  779. mqtt_client._handle_ams_data(initial_ams)
  780. # Update WITHOUT power_on_flag — should still clear when bit=0
  781. update_ams = {
  782. "ams": [{"id": 0, "tray": [{"id": 0}]}],
  783. "tray_exist_bits": "0",
  784. # No power_on_flag key at all
  785. }
  786. mqtt_client._handle_ams_data(update_ams)
  787. ams_data = mqtt_client.state.raw_data["ams"]
  788. assert ams_data[0]["tray"][0]["tray_type"] == "", (
  789. "Without power_on_flag, clearing should proceed (defaults to True)"
  790. )
  791. def test_idle_printer_with_power_off_and_nonzero_bits_clears_removed_slot(self, mqtt_client):
  792. """Spool removal on an idle X1C must be detected even when power_on_flag=False (#1365).
  793. On some X1C firmware (e.g. 01.08.02.00 reported by an3k) the AMS keeps
  794. publishing push_status with `power_on_flag: False` while the printer
  795. sits idle between prints — but `tray_exist_bits` continues to reflect
  796. the real slot inventory. The original #765 guard skipped clearing
  797. whenever power_on_flag was false, so the bit transition that would
  798. mark a slot empty was discarded and the only way to refresh state
  799. was a manual reconnect (pushall). The guard now skips clearing only
  800. on the exact shutdown pattern (zero bits + power_on_flag=False).
  801. """
  802. # Initial state: two AMS units, slot 1 of AMS 0 loaded (the one
  803. # we'll later remove).
  804. initial_ams = {
  805. "ams": [
  806. {
  807. "id": 0,
  808. "tray": [
  809. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF", "remain": 80},
  810. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00FF", "remain": 60},
  811. ],
  812. },
  813. {
  814. "id": 1,
  815. "tray": [
  816. {"id": 0, "tray_type": "PETG", "tray_color": "DBDDD9FF", "remain": 90},
  817. ],
  818. },
  819. ],
  820. "tray_exist_bits": "13", # 0b00010011 — AMS0 slots 0+1, AMS1 slot 0
  821. "power_on_flag": True,
  822. }
  823. mqtt_client._handle_ams_data(initial_ams)
  824. assert mqtt_client.state.raw_data["ams"][0]["tray"][1]["tray_type"] == "PETG"
  825. # Spool pulled from AMS 0 slot 1 while the printer is idle.
  826. # tray_exist_bits goes from 0x13 -> 0x11, but firmware still reports
  827. # power_on_flag=False because the printer is between prints. The real
  828. # push_status payloads on the affected X1C still carry the full `ams`
  829. # list (matches the bug-report log) — the slot inventory shrinks via
  830. # the bitfield rather than via per-tray content updates.
  831. removal_ams = {
  832. "ams": [
  833. {"id": 0, "tray": [{"id": 0}, {"id": 1}]},
  834. {"id": 1, "tray": [{"id": 0}]},
  835. ],
  836. "tray_exist_bits": "11", # 0b00010001 — slot 1 now empty
  837. "power_on_flag": False,
  838. "insert_flag": True,
  839. }
  840. mqtt_client._handle_ams_data(removal_ams)
  841. ams_data = mqtt_client.state.raw_data["ams"]
  842. assert ams_data[0]["tray"][1]["tray_type"] == "", (
  843. "Removal must be detected even with power_on_flag=False when bits are non-zero (#1365)"
  844. )
  845. assert ams_data[0]["tray"][1]["tray_color"] == "", "Removed slot color must be cleared"
  846. # Other slots untouched.
  847. assert ams_data[0]["tray"][0]["tray_type"] == "PLA", "AMS0 slot 0 preserved"
  848. assert ams_data[1]["tray"][0]["tray_type"] == "PETG", "AMS1 slot 0 preserved"
  849. class TestAMSTrayStateClearning:
  850. """Tests for AMS tray state-based clearing (#784).
  851. Some printers (e.g. H2D) only send {id, state} in incremental MQTT
  852. updates when a tray is not fully loaded. state=11 means loaded;
  853. other values (9=empty, 10=spool present but filament not in feeder)
  854. should clear stale tray data that was set from an earlier pushall.
  855. """
  856. @pytest.fixture
  857. def mqtt_client(self):
  858. from backend.app.services.bambu_mqtt import BambuMQTTClient
  859. client = BambuMQTTClient(
  860. ip_address="192.168.1.100",
  861. serial_number="TEST_H2D",
  862. access_code="12345678",
  863. )
  864. return client
  865. def _seed_loaded_tray(self, mqtt_client):
  866. """Seed AMS 0 with a fully loaded tray (state=11) and an empty slot."""
  867. initial = {
  868. "ams": [
  869. {
  870. "id": 0,
  871. "tray": [
  872. {
  873. "id": 0,
  874. "tray_type": "PETG",
  875. "tray_sub_brands": "PETG HF",
  876. "tray_color": "00FF00FF",
  877. "tray_id_name": "A00-G1",
  878. "tray_info_idx": "GFG99",
  879. "tag_uid": "AABBCCDD11223344",
  880. "tray_uuid": "AABBCCDD11223344AABBCCDD11223344",
  881. "remain": 75,
  882. "k": 0.02,
  883. "cali_idx": 5,
  884. "state": 11,
  885. },
  886. {
  887. "id": 1,
  888. "tray_type": "PLA",
  889. "tray_color": "FF0000FF",
  890. "remain": 50,
  891. "state": 11,
  892. },
  893. ],
  894. }
  895. ],
  896. "power_on_flag": False, # H2D always sends False
  897. }
  898. mqtt_client._handle_ams_data(initial)
  899. ams = mqtt_client.state.raw_data["ams"]
  900. assert ams[0]["tray"][0]["tray_type"] == "PETG"
  901. assert ams[0]["tray"][1]["tray_type"] == "PLA"
  902. def test_state_10_clears_stale_tray_data(self, mqtt_client):
  903. """Incremental update with state=10 (spool present, not loaded) clears tray."""
  904. self._seed_loaded_tray(mqtt_client)
  905. # H2D sends only {id, state} when filament is retracted
  906. update = {
  907. "ams": [
  908. {
  909. "id": 0,
  910. "tray": [
  911. {"id": 0, "state": 10},
  912. {"id": 1, "state": 11}, # slot 1 still loaded
  913. ],
  914. }
  915. ],
  916. "power_on_flag": False,
  917. }
  918. mqtt_client._handle_ams_data(update)
  919. ams = mqtt_client.state.raw_data["ams"]
  920. tray0 = ams[0]["tray"][0]
  921. tray1 = ams[0]["tray"][1]
  922. # Tray 0 should be cleared
  923. assert tray0["tray_type"] == "", "tray_type must be cleared on state=10"
  924. assert tray0["tray_color"] == "", "tray_color must be cleared"
  925. assert tray0["tray_sub_brands"] == "", "tray_sub_brands must be cleared"
  926. assert tray0["tray_id_name"] == "", "tray_id_name must be cleared"
  927. assert tray0["tray_info_idx"] == "", "tray_info_idx must be cleared"
  928. assert tray0["tag_uid"] == "0000000000000000", "tag_uid must be cleared"
  929. assert tray0["tray_uuid"] == "00000000000000000000000000000000", "tray_uuid must be cleared"
  930. assert tray0["remain"] == 0, "remain must be 0"
  931. assert tray0["k"] is None, "k must be cleared"
  932. assert tray0["cali_idx"] is None, "cali_idx must be cleared"
  933. assert tray0["state"] == 10, "state should be preserved"
  934. # Tray 1 should be untouched
  935. assert tray1["tray_type"] == "PLA", "Loaded slot must be preserved"
  936. assert tray1["remain"] == 50
  937. def test_state_9_clears_stale_tray_data(self, mqtt_client):
  938. """Incremental update with state=9 (empty, no spool) clears tray."""
  939. self._seed_loaded_tray(mqtt_client)
  940. update = {
  941. "ams": [
  942. {
  943. "id": 0,
  944. "tray": [
  945. {"id": 0, "state": 9},
  946. {"id": 1, "state": 11},
  947. ],
  948. }
  949. ],
  950. "power_on_flag": False,
  951. }
  952. mqtt_client._handle_ams_data(update)
  953. tray0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  954. assert tray0["tray_type"] == "", "state=9 must clear tray_type"
  955. assert tray0["remain"] == 0
  956. def test_state_11_preserves_tray_data(self, mqtt_client):
  957. """Incremental update with state=11 (loaded) must NOT clear tray."""
  958. self._seed_loaded_tray(mqtt_client)
  959. update = {
  960. "ams": [
  961. {
  962. "id": 0,
  963. "tray": [
  964. {"id": 0, "state": 11},
  965. {"id": 1, "state": 11},
  966. ],
  967. }
  968. ],
  969. "power_on_flag": False,
  970. }
  971. mqtt_client._handle_ams_data(update)
  972. tray0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  973. assert tray0["tray_type"] == "PETG", "state=11 must preserve tray data"
  974. assert tray0["tray_color"] == "00FF00FF"
  975. assert tray0["remain"] == 75
  976. def test_no_clearing_when_tray_type_already_empty(self, mqtt_client):
  977. """Don't re-clear a tray that's already empty (avoids log spam)."""
  978. self._seed_loaded_tray(mqtt_client)
  979. # First unload clears
  980. update = {
  981. "ams": [{"id": 0, "tray": [{"id": 0, "state": 10}, {"id": 1, "state": 11}]}],
  982. "power_on_flag": False,
  983. }
  984. mqtt_client._handle_ams_data(update)
  985. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["tray_type"] == ""
  986. # Second identical update should not trigger clearing again
  987. # (merged_tray.get("tray_type") is already empty/falsy)
  988. mqtt_client._handle_ams_data(update)
  989. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["tray_type"] == ""
  990. def test_reload_after_unload_restores_data(self, mqtt_client):
  991. """After clearing via state=10, a full update with state=11 restores data."""
  992. self._seed_loaded_tray(mqtt_client)
  993. # Unload
  994. mqtt_client._handle_ams_data(
  995. {
  996. "ams": [{"id": 0, "tray": [{"id": 0, "state": 10}, {"id": 1, "state": 11}]}],
  997. "power_on_flag": False,
  998. }
  999. )
  1000. assert mqtt_client.state.raw_data["ams"][0]["tray"][0]["tray_type"] == ""
  1001. # Reload — full tray data arrives again
  1002. mqtt_client._handle_ams_data(
  1003. {
  1004. "ams": [
  1005. {
  1006. "id": 0,
  1007. "tray": [
  1008. {
  1009. "id": 0,
  1010. "tray_type": "PETG",
  1011. "tray_sub_brands": "PETG HF",
  1012. "tray_color": "00FF00FF",
  1013. "remain": 75,
  1014. "state": 11,
  1015. },
  1016. {"id": 1, "state": 11},
  1017. ],
  1018. }
  1019. ],
  1020. "power_on_flag": False,
  1021. }
  1022. )
  1023. tray0 = mqtt_client.state.raw_data["ams"][0]["tray"][0]
  1024. assert tray0["tray_type"] == "PETG", "Reload must restore tray data"
  1025. assert tray0["tray_color"] == "00FF00FF"
  1026. assert tray0["remain"] == 75
  1027. class TestApplyTrayExistBitsHelper:
  1028. """Direct contract pinning for the shared ``apply_tray_exist_bits`` helper.
  1029. The same logic is exercised end-to-end via ``_handle_ams_data`` in the
  1030. internal-state suite and via ``_on_printer_raw`` in the bridge suite,
  1031. but those go through the merge / cache layers — the helper itself
  1032. deserves direct coverage so future refactors don't silently change
  1033. the contract both callers depend on (#1726).
  1034. """
  1035. def test_returns_zero_on_missing_bits(self):
  1036. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1037. units = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA"}]}]
  1038. assert apply_tray_exist_bits(units, None) == 0
  1039. assert apply_tray_exist_bits(units, "") == 0
  1040. # Untouched.
  1041. assert units[0]["tray"][0]["tray_type"] == "PLA"
  1042. def test_returns_zero_on_unparseable_bits(self):
  1043. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1044. units = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA"}]}]
  1045. assert apply_tray_exist_bits(units, "garbage") == 0
  1046. assert units[0]["tray"][0]["tray_type"] == "PLA"
  1047. def test_shutdown_guard_zero_bits_with_power_off_skips(self):
  1048. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1049. units = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF"}]}]
  1050. cleared = apply_tray_exist_bits(units, "0", power_on_flag=False)
  1051. assert cleared == 0
  1052. # Slot preserved — wiping here would propagate phantom empties on
  1053. # every printer-off push.
  1054. assert units[0]["tray"][0]["tray_type"] == "PLA"
  1055. def test_zero_bits_with_power_on_still_clears(self):
  1056. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1057. units = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF"}]}]
  1058. cleared = apply_tray_exist_bits(units, "0", power_on_flag=True)
  1059. # Slot is genuinely empty per the printer's report.
  1060. assert cleared == 1
  1061. assert units[0]["tray"][0]["state"] == 9
  1062. assert units[0]["tray"][0]["tray_type"] == ""
  1063. def test_nonzero_bits_with_power_off_still_clears_removed_slot(self):
  1064. """#1365: X1C reports power_on_flag=False between prints while the
  1065. AMS keeps reporting its actual slot inventory. The guard must skip
  1066. ONLY the all-zero + power-off combination, not nonzero + power-off.
  1067. """
  1068. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1069. units = [
  1070. {
  1071. "id": 0,
  1072. "tray": [
  1073. {"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF"},
  1074. {"id": 1, "tray_type": "PETG", "tray_color": "00FF00FF"},
  1075. ],
  1076. }
  1077. ]
  1078. # 0x1 = slot 0 loaded, slot 1 empty. Power off (steady-state idle).
  1079. cleared = apply_tray_exist_bits(units, "1", power_on_flag=False)
  1080. assert cleared == 1
  1081. assert units[0]["tray"][0]["tray_type"] == "PLA"
  1082. assert units[0]["tray"][1]["tray_type"] == ""
  1083. def test_promotes_state_to_int_nine(self):
  1084. """Downstream `tray_state in {9, 10}` uses `==` — int 9, not "9"."""
  1085. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1086. units = [{"id": 0, "tray": [{"id": 0, "state": "11"}]}]
  1087. apply_tray_exist_bits(units, "0", power_on_flag=True)
  1088. assert units[0]["tray"][0]["state"] == 9
  1089. assert isinstance(units[0]["tray"][0]["state"], int)
  1090. def test_ams_ht_unit_skipped(self):
  1091. """AMS-HT (id >= 128) uses a different addressing scheme."""
  1092. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1093. units = [{"id": 128, "tray": [{"id": 0, "tray_type": "PLA"}]}]
  1094. cleared = apply_tray_exist_bits(units, "0", power_on_flag=True)
  1095. assert cleared == 0
  1096. assert units[0]["tray"][0]["tray_type"] == "PLA"
  1097. def test_string_ids_handled(self):
  1098. """Bridge cache stores ids as strings (JSON wire format)."""
  1099. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1100. units = [
  1101. {
  1102. "id": "0",
  1103. "tray": [
  1104. {"id": "0", "tray_type": "PLA"},
  1105. {"id": "1", "tray_type": "PETG"},
  1106. ],
  1107. }
  1108. ]
  1109. # 0x1 = bit 0 set (slot 0), bit 1 clear (slot 1 empty).
  1110. cleared = apply_tray_exist_bits(units, "1", power_on_flag=True)
  1111. assert cleared == 1
  1112. assert units[0]["tray"][0]["tray_type"] == "PLA"
  1113. assert units[0]["tray"][1]["tray_type"] == ""
  1114. def test_multi_ams_global_bit_math(self):
  1115. """global_bit = ams_id * 4 + tray_id. Verify AMS 1 slots use
  1116. bits 4-7 of the mask, not bits 0-3."""
  1117. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1118. units = [
  1119. {"id": 0, "tray": [{"id": i, "tray_type": "PLA"} for i in range(4)]},
  1120. {"id": 1, "tray": [{"id": i, "tray_type": "PETG"} for i in range(4)]},
  1121. ]
  1122. # 0x0f: all slots of AMS 0 loaded, all slots of AMS 1 empty.
  1123. cleared = apply_tray_exist_bits(units, "f", power_on_flag=True)
  1124. assert cleared == 4
  1125. for i in range(4):
  1126. assert units[0]["tray"][i]["tray_type"] == "PLA"
  1127. assert units[1]["tray"][i]["tray_type"] == ""
  1128. def test_state_promoted_even_when_no_stale_data(self):
  1129. """Slot without `tray_type` still gets state=9 — the bitmask is
  1130. authoritative, the field wipe just avoids extra log lines.
  1131. """
  1132. from backend.app.services.bambu_mqtt import apply_tray_exist_bits
  1133. units = [{"id": 0, "tray": [{"id": 0, "state": "11"}]}]
  1134. cleared = apply_tray_exist_bits(units, "0", power_on_flag=True)
  1135. # No tray_type to clear → cleared counter stays 0 but state is set.
  1136. assert cleared == 0
  1137. assert units[0]["tray"][0]["state"] == 9
  1138. class TestNozzleRackData:
  1139. """Tests for nozzle rack data parsing from H2 series device.nozzle.info."""
  1140. @pytest.fixture
  1141. def mqtt_client(self):
  1142. """Create a BambuMQTTClient instance for testing."""
  1143. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1144. client = BambuMQTTClient(
  1145. ip_address="192.168.1.100",
  1146. serial_number="TEST123",
  1147. access_code="12345678",
  1148. )
  1149. return client
  1150. def test_h2c_nozzle_rack_populated_with_8_entries(self, mqtt_client):
  1151. """H2C provides 8 nozzle entries: IDs 0,1 (L/R hotend) + 16-21 (rack)."""
  1152. payload = {
  1153. "print": {
  1154. "device": {
  1155. "nozzle": {
  1156. "info": [
  1157. {
  1158. "id": 0,
  1159. "type": "HS",
  1160. "diameter": "0.4",
  1161. "wear": 5,
  1162. "stat": 1,
  1163. "max_temp": 300,
  1164. "serial_number": "SN-L",
  1165. },
  1166. {
  1167. "id": 1,
  1168. "type": "HS",
  1169. "diameter": "0.4",
  1170. "wear": 3,
  1171. "stat": 0,
  1172. "max_temp": 300,
  1173. "serial_number": "SN-R",
  1174. },
  1175. {
  1176. "id": 16,
  1177. "type": "HS",
  1178. "diameter": "0.4",
  1179. "wear": 10,
  1180. "stat": 0,
  1181. "max_temp": 300,
  1182. "serial_number": "SN-16",
  1183. },
  1184. {
  1185. "id": 17,
  1186. "type": "HH01",
  1187. "diameter": "0.6",
  1188. "wear": 0,
  1189. "stat": 0,
  1190. "max_temp": 300,
  1191. "serial_number": "SN-17",
  1192. },
  1193. {
  1194. "id": 18,
  1195. "type": "HS",
  1196. "diameter": "0.4",
  1197. "wear": 2,
  1198. "stat": 0,
  1199. "max_temp": 300,
  1200. "serial_number": "SN-18",
  1201. },
  1202. {
  1203. "id": 19,
  1204. "type": "",
  1205. "diameter": "",
  1206. "wear": None,
  1207. "stat": None,
  1208. "max_temp": 0,
  1209. "serial_number": "",
  1210. },
  1211. {
  1212. "id": 20,
  1213. "type": "",
  1214. "diameter": "",
  1215. "wear": None,
  1216. "stat": None,
  1217. "max_temp": 0,
  1218. "serial_number": "",
  1219. },
  1220. {
  1221. "id": 21,
  1222. "type": "",
  1223. "diameter": "",
  1224. "wear": None,
  1225. "stat": None,
  1226. "max_temp": 0,
  1227. "serial_number": "",
  1228. },
  1229. ]
  1230. }
  1231. }
  1232. }
  1233. }
  1234. mqtt_client._process_message(payload)
  1235. assert len(mqtt_client.state.nozzle_rack) == 8
  1236. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  1237. assert ids == [0, 1, 16, 17, 18, 19, 20, 21]
  1238. def test_h2d_nozzle_rack_populated_with_2_entries(self, mqtt_client):
  1239. """H2D provides 2 nozzle entries: IDs 0,1 (L/R hotend) — no rack slots."""
  1240. payload = {
  1241. "print": {
  1242. "device": {
  1243. "nozzle": {
  1244. "info": [
  1245. {
  1246. "id": 0,
  1247. "type": "HS",
  1248. "diameter": "0.4",
  1249. "wear": 5,
  1250. "stat": 1,
  1251. "max_temp": 300,
  1252. "serial_number": "SN-L",
  1253. },
  1254. {
  1255. "id": 1,
  1256. "type": "HS",
  1257. "diameter": "0.4",
  1258. "wear": 3,
  1259. "stat": 1,
  1260. "max_temp": 300,
  1261. "serial_number": "SN-R",
  1262. },
  1263. ]
  1264. }
  1265. }
  1266. }
  1267. }
  1268. mqtt_client._process_message(payload)
  1269. assert len(mqtt_client.state.nozzle_rack) == 2
  1270. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  1271. assert ids == [0, 1]
  1272. def test_single_nozzle_h2s_populated(self, mqtt_client):
  1273. """H2S provides 1 nozzle entry: ID 0 only — single nozzle printer."""
  1274. payload = {
  1275. "print": {
  1276. "device": {
  1277. "nozzle": {
  1278. "info": [
  1279. {
  1280. "id": 0,
  1281. "type": "HS",
  1282. "diameter": "0.4",
  1283. "wear": 2,
  1284. "stat": 1,
  1285. "max_temp": 300,
  1286. "serial_number": "SN-0",
  1287. },
  1288. ]
  1289. }
  1290. }
  1291. }
  1292. }
  1293. mqtt_client._process_message(payload)
  1294. assert len(mqtt_client.state.nozzle_rack) == 1
  1295. assert mqtt_client.state.nozzle_rack[0]["id"] == 0
  1296. def test_empty_nozzle_info_does_not_populate_rack(self, mqtt_client):
  1297. """Empty nozzle info list should not populate nozzle_rack."""
  1298. payload = {"print": {"device": {"nozzle": {"info": []}}}}
  1299. mqtt_client._process_message(payload)
  1300. assert mqtt_client.state.nozzle_rack == []
  1301. def test_nozzle_rack_sorted_by_id(self, mqtt_client):
  1302. """Nozzle rack entries should be sorted by ID regardless of input order."""
  1303. payload = {
  1304. "print": {
  1305. "device": {
  1306. "nozzle": {
  1307. "info": [
  1308. {"id": 17, "type": "HS", "diameter": "0.6"},
  1309. {"id": 0, "type": "HS", "diameter": "0.4"},
  1310. {"id": 16, "type": "HS", "diameter": "0.4"},
  1311. {"id": 1, "type": "HS", "diameter": "0.4"},
  1312. ]
  1313. }
  1314. }
  1315. }
  1316. }
  1317. mqtt_client._process_message(payload)
  1318. ids = [n["id"] for n in mqtt_client.state.nozzle_rack]
  1319. assert ids == [0, 1, 16, 17]
  1320. def test_nozzle_rack_field_mapping(self, mqtt_client):
  1321. """Verify field mapping from MQTT nozzle_info to nozzle_rack dict keys."""
  1322. payload = {
  1323. "print": {
  1324. "device": {
  1325. "nozzle": {
  1326. "info": [
  1327. {
  1328. "id": 16,
  1329. "type": "HH01",
  1330. "diameter": "0.6",
  1331. "wear": 15,
  1332. "stat": 0,
  1333. "max_temp": 320,
  1334. "serial_number": "SN-ABC123",
  1335. "filament_colour": "FF8800",
  1336. "filament_id": "F42",
  1337. "tray_type": "ABS",
  1338. }
  1339. ]
  1340. }
  1341. }
  1342. }
  1343. }
  1344. mqtt_client._process_message(payload)
  1345. slot = mqtt_client.state.nozzle_rack[0]
  1346. assert slot["id"] == 16
  1347. assert slot["type"] == "HH01"
  1348. assert slot["diameter"] == "0.6"
  1349. assert slot["wear"] == 15
  1350. assert slot["stat"] == 0
  1351. assert slot["max_temp"] == 320
  1352. assert slot["serial_number"] == "SN-ABC123"
  1353. assert slot["filament_color"] == "FF8800"
  1354. assert slot["filament_id"] == "F42"
  1355. assert slot["filament_type"] == "ABS"
  1356. def test_nozzle_info_updates_nozzle_state(self, mqtt_client):
  1357. """Nozzle info for IDs 0,1 should also update nozzle state (type/diameter)."""
  1358. payload = {
  1359. "print": {
  1360. "device": {
  1361. "nozzle": {
  1362. "info": [
  1363. {"id": 0, "type": "HS", "diameter": "0.4"},
  1364. {"id": 1, "type": "HH01", "diameter": "0.6"},
  1365. ]
  1366. }
  1367. }
  1368. }
  1369. }
  1370. mqtt_client._process_message(payload)
  1371. assert mqtt_client.state.nozzles[0].nozzle_type == "HS"
  1372. assert mqtt_client.state.nozzles[0].nozzle_diameter == "0.4"
  1373. assert mqtt_client.state.nozzles[1].nozzle_type == "HH01"
  1374. assert mqtt_client.state.nozzles[1].nozzle_diameter == "0.6"
  1375. class TestRequestTopicFailSafe:
  1376. """Tests for graceful degradation when broker rejects request topic subscription."""
  1377. @pytest.fixture(autouse=True)
  1378. def clear_request_topic_cache(self):
  1379. """Clear class-level cache before each test to avoid cross-test pollution."""
  1380. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1381. BambuMQTTClient._request_topic_cache.clear()
  1382. @pytest.fixture
  1383. def mqtt_client(self):
  1384. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1385. client = BambuMQTTClient(
  1386. ip_address="192.168.1.100",
  1387. serial_number="TEST123",
  1388. access_code="12345678",
  1389. )
  1390. return client
  1391. def test_request_topic_supported_by_default(self, mqtt_client):
  1392. """Request topic subscription is attempted by default."""
  1393. assert mqtt_client._request_topic_supported is True
  1394. assert mqtt_client._request_topic_confirmed is False
  1395. def test_on_subscribe_confirms_success(self, mqtt_client):
  1396. """Successful SUBACK marks request topic as confirmed."""
  1397. from paho.mqtt.reasoncodes import ReasonCode
  1398. mqtt_client._request_topic_sub_mid = 42
  1399. rc = ReasonCode(9, identifier=0) # SUBACK packetType=9, QoS 0 = success
  1400. mqtt_client._on_subscribe(None, None, 42, [rc], None)
  1401. assert mqtt_client._request_topic_confirmed is True
  1402. assert mqtt_client._request_topic_supported is True
  1403. assert mqtt_client._request_topic_sub_mid is None
  1404. assert mqtt_client._request_topic_sub_time == 0.0
  1405. def test_on_subscribe_detects_rejection(self, mqtt_client):
  1406. """SUBACK with failure code disables request topic."""
  1407. from paho.mqtt.reasoncodes import ReasonCode
  1408. mqtt_client._request_topic_sub_mid = 42
  1409. rc = ReasonCode(9, identifier=0x80) # SUBACK packetType=9, 0x80 = failure
  1410. mqtt_client._on_subscribe(None, None, 42, [rc], None)
  1411. assert mqtt_client._request_topic_supported is False
  1412. assert mqtt_client._request_topic_confirmed is False
  1413. def test_on_subscribe_ignores_other_mids(self, mqtt_client):
  1414. """SUBACK for other subscriptions (e.g. report topic) is ignored."""
  1415. from paho.mqtt.reasoncodes import ReasonCode
  1416. mqtt_client._request_topic_sub_mid = 42
  1417. rc = ReasonCode(9, identifier=0x80)
  1418. mqtt_client._on_subscribe(None, None, 99, [rc], None)
  1419. # Not affected — mid doesn't match
  1420. assert mqtt_client._request_topic_supported is True
  1421. def test_disconnect_after_subscription_disables_topic(self, mqtt_client):
  1422. """Disconnect within 10s of subscription attempt disables request topic."""
  1423. import time
  1424. mqtt_client._request_topic_sub_time = time.time()
  1425. mqtt_client._request_topic_confirmed = False
  1426. mqtt_client._last_message_time = 0.0
  1427. mqtt_client._on_disconnect(None, None)
  1428. assert mqtt_client._request_topic_supported is False
  1429. assert mqtt_client._request_topic_sub_time == 0.0
  1430. def test_disconnect_after_confirmation_does_not_disable(self, mqtt_client):
  1431. """Disconnect after SUBACK confirmation keeps request topic enabled."""
  1432. import time
  1433. mqtt_client._request_topic_sub_time = time.time()
  1434. mqtt_client._request_topic_confirmed = True
  1435. mqtt_client._last_message_time = 0.0
  1436. mqtt_client._on_disconnect(None, None)
  1437. assert mqtt_client._request_topic_supported is True
  1438. def test_late_disconnect_does_not_disable(self, mqtt_client):
  1439. """Disconnect long after subscription (>10s) doesn't blame request topic."""
  1440. import time
  1441. mqtt_client._request_topic_sub_time = time.time() - 30.0
  1442. mqtt_client._request_topic_confirmed = False
  1443. mqtt_client._last_message_time = 0.0
  1444. mqtt_client._on_disconnect(None, None)
  1445. assert mqtt_client._request_topic_supported is True
  1446. def test_on_connect_skips_request_topic_when_unsupported(self, mqtt_client):
  1447. """After marking unsupported, reconnect skips request topic subscription."""
  1448. mqtt_client._request_topic_supported = False
  1449. subscribe_calls = []
  1450. mock_client = type(
  1451. "MockClient",
  1452. (),
  1453. {
  1454. "subscribe": lambda self, topic: subscribe_calls.append(topic) or (0, 1),
  1455. },
  1456. )()
  1457. mqtt_client._on_connect(mock_client, None, None, 0)
  1458. # Only report topic subscribed, not request topic
  1459. assert len(subscribe_calls) == 1
  1460. assert subscribe_calls[0] == mqtt_client.topic_subscribe
  1461. def test_cache_persists_across_instances(self):
  1462. """New client instance inherits request topic unsupported state from cache."""
  1463. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1464. client1 = BambuMQTTClient(
  1465. ip_address="192.168.1.100",
  1466. serial_number="TEST_CACHE",
  1467. access_code="12345678",
  1468. )
  1469. assert client1._request_topic_supported is True
  1470. # Simulate disconnect-after-subscribe disabling the topic
  1471. client1._request_topic_sub_time = __import__("time").time()
  1472. client1._request_topic_confirmed = False
  1473. client1._last_message_time = 0.0
  1474. client1._on_disconnect(None, None)
  1475. assert client1._request_topic_supported is False
  1476. # New instance for same serial should inherit the cached state
  1477. client2 = BambuMQTTClient(
  1478. ip_address="192.168.1.100",
  1479. serial_number="TEST_CACHE",
  1480. access_code="12345678",
  1481. )
  1482. assert client2._request_topic_supported is False
  1483. def test_cache_does_not_affect_different_serial(self):
  1484. """Cache is per-serial — different printer is unaffected."""
  1485. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1486. BambuMQTTClient._request_topic_cache["SERIAL_A"] = False
  1487. client = BambuMQTTClient(
  1488. ip_address="192.168.1.100",
  1489. serial_number="SERIAL_B",
  1490. access_code="12345678",
  1491. )
  1492. assert client._request_topic_supported is True
  1493. def test_cache_updated_on_suback_success(self):
  1494. """Successful SUBACK caches positive confirmation."""
  1495. from paho.mqtt.reasoncodes import ReasonCode
  1496. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1497. client = BambuMQTTClient(
  1498. ip_address="192.168.1.100",
  1499. serial_number="TEST_SUBACK",
  1500. access_code="12345678",
  1501. )
  1502. client._request_topic_sub_mid = 42
  1503. rc = ReasonCode(9, identifier=0) # Success
  1504. client._on_subscribe(None, None, 42, [rc], None)
  1505. assert BambuMQTTClient._request_topic_cache["TEST_SUBACK"] is True
  1506. def test_cache_updated_on_suback_rejection(self):
  1507. """SUBACK rejection caches negative state."""
  1508. from paho.mqtt.reasoncodes import ReasonCode
  1509. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1510. client = BambuMQTTClient(
  1511. ip_address="192.168.1.100",
  1512. serial_number="TEST_REJECT",
  1513. access_code="12345678",
  1514. )
  1515. client._request_topic_sub_mid = 42
  1516. rc = ReasonCode(9, identifier=0x80) # Failure
  1517. client._on_subscribe(None, None, 42, [rc], None)
  1518. assert BambuMQTTClient._request_topic_cache["TEST_REJECT"] is False
  1519. class TestRequestTopicAmsMapping:
  1520. """Tests for capturing ams_mapping from the MQTT request topic."""
  1521. @pytest.fixture
  1522. def mqtt_client(self):
  1523. """Create a BambuMQTTClient instance for testing."""
  1524. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1525. client = BambuMQTTClient(
  1526. ip_address="192.168.1.100",
  1527. serial_number="TEST123",
  1528. access_code="12345678",
  1529. )
  1530. return client
  1531. def test_captured_ams_mapping_initializes_to_none(self, mqtt_client):
  1532. """Verify _captured_ams_mapping starts as None."""
  1533. assert mqtt_client._captured_ams_mapping is None
  1534. def test_handle_request_message_captures_ams_mapping(self, mqtt_client):
  1535. """project_file command with ams_mapping stores the mapping."""
  1536. data = {
  1537. "print": {
  1538. "command": "project_file",
  1539. "ams_mapping": [0, 4, -1, -1],
  1540. "url": "ftp://192.168.1.100/test.3mf",
  1541. }
  1542. }
  1543. mqtt_client._handle_request_message(data)
  1544. assert mqtt_client._captured_ams_mapping == [0, 4, -1, -1]
  1545. def test_handle_request_message_ignores_non_print_commands(self, mqtt_client):
  1546. """Non-project_file commands don't store ams_mapping."""
  1547. data = {
  1548. "print": {
  1549. "command": "pause",
  1550. }
  1551. }
  1552. mqtt_client._handle_request_message(data)
  1553. assert mqtt_client._captured_ams_mapping is None
  1554. def test_handle_request_message_ignores_missing_ams_mapping(self, mqtt_client):
  1555. """project_file command without ams_mapping doesn't store anything."""
  1556. data = {
  1557. "print": {
  1558. "command": "project_file",
  1559. "url": "ftp://192.168.1.100/test.3mf",
  1560. }
  1561. }
  1562. mqtt_client._handle_request_message(data)
  1563. assert mqtt_client._captured_ams_mapping is None
  1564. def test_handle_request_message_ignores_non_dict_print(self, mqtt_client):
  1565. """Non-dict print value is safely ignored."""
  1566. data = {"print": "not_a_dict"}
  1567. mqtt_client._handle_request_message(data)
  1568. assert mqtt_client._captured_ams_mapping is None
  1569. def test_handle_request_message_ignores_missing_print(self, mqtt_client):
  1570. """Message without print key is safely ignored."""
  1571. data = {"pushing": {"command": "pushall"}}
  1572. mqtt_client._handle_request_message(data)
  1573. assert mqtt_client._captured_ams_mapping is None
  1574. def test_captured_mapping_overwrites_previous(self, mqtt_client):
  1575. """A new print command overwrites a previously captured mapping."""
  1576. mqtt_client._captured_ams_mapping = [0, -1, -1, -1]
  1577. data = {
  1578. "print": {
  1579. "command": "project_file",
  1580. "ams_mapping": [4, 8, -1, -1],
  1581. }
  1582. }
  1583. mqtt_client._handle_request_message(data)
  1584. assert mqtt_client._captured_ams_mapping == [4, 8, -1, -1]
  1585. def test_print_start_callback_includes_ams_mapping(self, mqtt_client):
  1586. """on_print_start callback data includes captured ams_mapping."""
  1587. start_data = {}
  1588. def on_start(data):
  1589. start_data.update(data)
  1590. mqtt_client.on_print_start = on_start
  1591. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  1592. # Seed a prior state so the first RUNNING push is treated as a real
  1593. # state transition rather than a Bambuddy-restart catch-up (#1304).
  1594. mqtt_client._previous_gcode_state = "IDLE"
  1595. # Trigger print start
  1596. mqtt_client._process_message(
  1597. {
  1598. "print": {
  1599. "gcode_state": "RUNNING",
  1600. "gcode_file": "/data/Metadata/test.gcode",
  1601. "subtask_name": "Test",
  1602. }
  1603. }
  1604. )
  1605. assert start_data.get("ams_mapping") == [0, 4, -1, -1]
  1606. def test_print_start_callback_ams_mapping_none_when_not_captured(self, mqtt_client):
  1607. """on_print_start callback has ams_mapping=None when no mapping captured."""
  1608. start_data = {}
  1609. def on_start(data):
  1610. start_data.update(data)
  1611. mqtt_client.on_print_start = on_start
  1612. # Seed a prior state so the first RUNNING push is treated as a real
  1613. # state transition rather than a Bambuddy-restart catch-up (#1304).
  1614. mqtt_client._previous_gcode_state = "IDLE"
  1615. mqtt_client._process_message(
  1616. {
  1617. "print": {
  1618. "gcode_state": "RUNNING",
  1619. "gcode_file": "/data/Metadata/test.gcode",
  1620. "subtask_name": "Test",
  1621. }
  1622. }
  1623. )
  1624. assert "ams_mapping" in start_data
  1625. assert start_data["ams_mapping"] is None
  1626. def test_first_running_push_after_bambuddy_restart_does_not_fire_print_start(self, mqtt_client):
  1627. """Regression for #1304: Bambuddy restart mid-print misfired plate check + archive.
  1628. When Bambuddy restarts while a print is already in progress, the freshly
  1629. constructed BambuMQTTClient has `_previous_gcode_state = None`. The first
  1630. push_status the printer sends reports `gcode_state: RUNNING`. Before the
  1631. fix, the (None → RUNNING) transition satisfied is_new_print's guard and
  1632. fired on_print_start, which then ran plate detection (objects on plate →
  1633. paused the live print) AND re-archived the file (duplicate archive).
  1634. With the fix in place the on_print_start callback must NOT be called for
  1635. this catch-up push, but `_was_running` still tracks the print so
  1636. completion detection works the same way as before.
  1637. """
  1638. start_data = {}
  1639. def on_start(data):
  1640. start_data.update(data)
  1641. mqtt_client.on_print_start = on_start
  1642. # Explicit: this simulates a fresh Bambuddy process attaching to a
  1643. # printer that's already in the middle of a print.
  1644. mqtt_client._previous_gcode_state = None
  1645. mqtt_client._was_running = False
  1646. mqtt_client._process_message(
  1647. {
  1648. "print": {
  1649. "gcode_state": "RUNNING",
  1650. "gcode_file": "/data/Metadata/big_print.gcode",
  1651. "subtask_name": "big_print",
  1652. }
  1653. }
  1654. )
  1655. assert start_data == {}, "on_print_start must not fire on Bambuddy-restart catch-up"
  1656. # Completion detection still needs to know we're tracking a running job.
  1657. assert mqtt_client._was_running is True
  1658. # And the state-update bookkeeping ran so the NEXT push won't keep
  1659. # treating the first RUNNING as fresh.
  1660. assert mqtt_client._previous_gcode_state == "RUNNING"
  1661. def test_print_complete_callback_includes_ams_mapping(self, mqtt_client):
  1662. """on_print_complete callback data includes captured ams_mapping."""
  1663. complete_data = {}
  1664. def on_complete(data):
  1665. complete_data.update(data)
  1666. mqtt_client.on_print_start = lambda d: None
  1667. mqtt_client.on_print_complete = on_complete
  1668. mqtt_client._captured_ams_mapping = [0, 9, -1, -1]
  1669. # Start print
  1670. mqtt_client._process_message(
  1671. {
  1672. "print": {
  1673. "gcode_state": "RUNNING",
  1674. "gcode_file": "/data/Metadata/test.gcode",
  1675. "subtask_name": "Test",
  1676. }
  1677. }
  1678. )
  1679. # Complete print
  1680. mqtt_client._process_message(
  1681. {
  1682. "print": {
  1683. "gcode_state": "FINISH",
  1684. "gcode_file": "/data/Metadata/test.gcode",
  1685. "subtask_name": "Test",
  1686. }
  1687. }
  1688. )
  1689. assert complete_data.get("ams_mapping") == [0, 9, -1, -1]
  1690. def test_captured_mapping_cleared_after_print_complete(self, mqtt_client):
  1691. """_captured_ams_mapping is reset to None after print completion."""
  1692. mqtt_client.on_print_start = lambda d: None
  1693. mqtt_client.on_print_complete = lambda d: None
  1694. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  1695. # Start print
  1696. mqtt_client._process_message(
  1697. {
  1698. "print": {
  1699. "gcode_state": "RUNNING",
  1700. "gcode_file": "/data/Metadata/test.gcode",
  1701. "subtask_name": "Test",
  1702. }
  1703. }
  1704. )
  1705. # Complete print
  1706. mqtt_client._process_message(
  1707. {
  1708. "print": {
  1709. "gcode_state": "FINISH",
  1710. "gcode_file": "/data/Metadata/test.gcode",
  1711. "subtask_name": "Test",
  1712. }
  1713. }
  1714. )
  1715. assert mqtt_client._captured_ams_mapping is None
  1716. def test_full_flow_capture_and_deliver(self, mqtt_client):
  1717. """Full flow: slicer sends print command → MQTT captures mapping → completion delivers it."""
  1718. complete_data = {}
  1719. def on_complete(data):
  1720. complete_data.update(data)
  1721. mqtt_client.on_print_start = lambda d: None
  1722. mqtt_client.on_print_complete = on_complete
  1723. # 1. Slicer sends print command (captured from request topic)
  1724. mqtt_client._handle_request_message(
  1725. {
  1726. "print": {
  1727. "command": "project_file",
  1728. "ams_mapping": [4, 9, -1, -1],
  1729. "url": "ftp://192.168.1.100/model.3mf",
  1730. }
  1731. }
  1732. )
  1733. assert mqtt_client._captured_ams_mapping == [4, 9, -1, -1]
  1734. # 2. Printer reports RUNNING
  1735. mqtt_client._process_message(
  1736. {
  1737. "print": {
  1738. "gcode_state": "RUNNING",
  1739. "gcode_file": "/data/Metadata/model.gcode",
  1740. "subtask_name": "Model",
  1741. }
  1742. }
  1743. )
  1744. # 3. Printer reports FINISH
  1745. mqtt_client._process_message(
  1746. {
  1747. "print": {
  1748. "gcode_state": "FINISH",
  1749. "gcode_file": "/data/Metadata/model.gcode",
  1750. "subtask_name": "Model",
  1751. }
  1752. }
  1753. )
  1754. assert complete_data["ams_mapping"] == [4, 9, -1, -1]
  1755. assert complete_data["status"] == "completed"
  1756. # Mapping cleared after completion
  1757. assert mqtt_client._captured_ams_mapping is None
  1758. # ---------------------------------------------------------------------------
  1759. # tray_now disambiguation helpers
  1760. # ---------------------------------------------------------------------------
  1761. def _ams_payload(tray_now, ams_units=None, tray_exist_bits=None, ams_exist_bits=None):
  1762. """Build minimal print.ams payload for tray_now disambiguation tests."""
  1763. ams = {"tray_now": str(tray_now)}
  1764. if ams_units is not None:
  1765. ams["ams"] = ams_units
  1766. if tray_exist_bits is not None:
  1767. ams["tray_exist_bits"] = tray_exist_bits
  1768. if ams_exist_bits is not None:
  1769. ams["ams_exist_bits"] = ams_exist_bits
  1770. return {"print": {"ams": ams}}
  1771. def _extruder_info_payload(extruders):
  1772. """Build device.extruder.info payload (dual-nozzle detection + snow).
  1773. Each entry in *extruders* is a dict with at least ``id`` and ``snow``.
  1774. """
  1775. return {
  1776. "print": {
  1777. "device": {
  1778. "extruder": {
  1779. "info": extruders,
  1780. }
  1781. }
  1782. }
  1783. }
  1784. def _extruder_state_payload(state_val):
  1785. """Build device.extruder.state payload (active extruder via bit 8)."""
  1786. return {
  1787. "print": {
  1788. "device": {
  1789. "extruder": {
  1790. "state": state_val,
  1791. }
  1792. }
  1793. }
  1794. }
  1795. # ---------------------------------------------------------------------------
  1796. # 1. Single-nozzle X1E — direct passthrough
  1797. # ---------------------------------------------------------------------------
  1798. class TestTrayNowSingleNozzleX1E:
  1799. """Single-nozzle, 1 AMS — tray_now is a direct passthrough."""
  1800. @pytest.fixture
  1801. def mqtt_client(self):
  1802. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1803. return BambuMQTTClient(
  1804. ip_address="192.168.1.100",
  1805. serial_number="TEST_X1E",
  1806. access_code="12345678",
  1807. )
  1808. def test_tray_now_direct_passthrough_slot_0_to_3(self, mqtt_client):
  1809. """Each tray_now 0-3 maps 1:1 on single-nozzle printers."""
  1810. for slot in range(4):
  1811. mqtt_client._process_message(_ams_payload(slot))
  1812. assert mqtt_client.state.tray_now == slot
  1813. def test_tray_now_255_means_unloaded(self, mqtt_client):
  1814. """tray_now=255 means no filament loaded."""
  1815. mqtt_client._process_message(_ams_payload(255))
  1816. assert mqtt_client.state.tray_now == 255
  1817. def test_single_extruder_does_not_trigger_dual_nozzle(self, mqtt_client):
  1818. """device.extruder.info with 1 entry must NOT set _is_dual_nozzle."""
  1819. mqtt_client._process_message(_extruder_info_payload([{"id": 0, "snow": 0xFF00FF}]))
  1820. assert mqtt_client._is_dual_nozzle is False
  1821. def test_last_loaded_tray_survives_unload(self, mqtt_client):
  1822. """Load tray 2, unload → last_loaded_tray stays 2."""
  1823. mqtt_client._process_message(_ams_payload(2))
  1824. assert mqtt_client.state.last_loaded_tray == 2
  1825. mqtt_client._process_message(_ams_payload(255))
  1826. assert mqtt_client.state.tray_now == 255
  1827. assert mqtt_client.state.last_loaded_tray == 2
  1828. # ---------------------------------------------------------------------------
  1829. # 2. Single-nozzle P2S — multiple AMS, global IDs pass through
  1830. # ---------------------------------------------------------------------------
  1831. class TestTrayNowSingleNozzleP2S:
  1832. """Single-nozzle, 2 AMS — tray_now > 3 passes through as global ID."""
  1833. @pytest.fixture
  1834. def mqtt_client(self):
  1835. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1836. return BambuMQTTClient(
  1837. ip_address="192.168.1.100",
  1838. serial_number="TEST_P2S",
  1839. access_code="12345678",
  1840. )
  1841. def test_tray_now_ams1_global_ids_4_to_7(self, mqtt_client):
  1842. """tray_now 4-7 are global IDs for AMS 1 on single-nozzle printers."""
  1843. for global_id in range(4, 8):
  1844. mqtt_client._process_message(_ams_payload(global_id))
  1845. assert mqtt_client.state.tray_now == global_id
  1846. def test_tray_change_across_ams_units(self, mqtt_client):
  1847. """Switch from AMS 0 slot 1 → AMS 1 slot 2 (global 6)."""
  1848. mqtt_client._process_message(_ams_payload(1))
  1849. assert mqtt_client.state.tray_now == 1
  1850. mqtt_client._process_message(_ams_payload(6))
  1851. assert mqtt_client.state.tray_now == 6
  1852. # ---------------------------------------------------------------------------
  1853. # 2b. Single-nozzle P2S — multi-AMS local slot disambiguation (#420)
  1854. # ---------------------------------------------------------------------------
  1855. class TestTrayNowP2SMultiAmsDisambiguation:
  1856. """P2S firmware sends local slot IDs (0-3) in tray_now even with dual AMS.
  1857. When ams_exist_bits indicates >1 AMS unit and tray_now is 0-3, the backend
  1858. should use the MQTT mapping field (snow-encoded) to resolve the correct
  1859. global tray ID.
  1860. """
  1861. @pytest.fixture
  1862. def mqtt_client(self):
  1863. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1864. client = BambuMQTTClient(
  1865. ip_address="192.168.1.100",
  1866. serial_number="TEST_P2S_DUAL",
  1867. access_code="12345678",
  1868. )
  1869. return client
  1870. def test_resolves_ams1_slot1_from_mapping(self, mqtt_client):
  1871. """tray_now=1 with mapping=[257] → global ID 5 (AMS1-T1).
  1872. 257 snow-decoded: ams_hw_id=1, slot=1 → global 1*4+1=5.
  1873. """
  1874. # Set mapping field in raw_data (as the MQTT handler would)
  1875. mqtt_client.state.raw_data["mapping"] = [257]
  1876. mqtt_client._process_message(
  1877. _ams_payload(1, ams_exist_bits="3") # '3' = 0b11 → AMS 0 and 1
  1878. )
  1879. assert mqtt_client.state.tray_now == 5
  1880. def test_resolves_ams1_slot0_from_mapping(self, mqtt_client):
  1881. """tray_now=0 with mapping=[256] → global ID 4 (AMS1-T0).
  1882. 256 snow-decoded: ams_hw_id=1, slot=0 → global 1*4+0=4.
  1883. """
  1884. mqtt_client.state.raw_data["mapping"] = [256]
  1885. mqtt_client._process_message(_ams_payload(0, ams_exist_bits="3"))
  1886. assert mqtt_client.state.tray_now == 4
  1887. def test_resolves_ams1_slot3_from_mapping(self, mqtt_client):
  1888. """tray_now=3 with mapping=[259] → global ID 7 (AMS1-T3).
  1889. 259 snow-decoded: ams_hw_id=1, slot=3 → global 1*4+3=7.
  1890. """
  1891. mqtt_client.state.raw_data["mapping"] = [259]
  1892. mqtt_client._process_message(_ams_payload(3, ams_exist_bits="3"))
  1893. assert mqtt_client.state.tray_now == 7
  1894. def test_ams0_slot_unchanged_when_mapping_confirms_ams0(self, mqtt_client):
  1895. """tray_now=1 with mapping=[1] → stays 1 (AMS0-T1).
  1896. 1 snow-decoded: ams_hw_id=0, slot=1 → global 0*4+1=1.
  1897. """
  1898. mqtt_client.state.raw_data["mapping"] = [1]
  1899. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1900. assert mqtt_client.state.tray_now == 1
  1901. def test_multicolor_resolves_ams1_from_multi_entry_mapping(self, mqtt_client):
  1902. """Multi-color print: mapping=[0, 257] → tray_now=1 resolves to AMS1-T1 (5).
  1903. Entry 0: ams_hw_id=0, slot=0 (local 0) — doesn't match tray_now=1.
  1904. Entry 257: ams_hw_id=1, slot=1 (local 1) — matches tray_now=1 → global 5.
  1905. """
  1906. mqtt_client.state.raw_data["mapping"] = [0, 257]
  1907. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1908. assert mqtt_client.state.tray_now == 5
  1909. def test_multicolor_four_slot_mapping(self, mqtt_client):
  1910. """mapping=[65535, 65535, 65535, 257] → tray_now=1 resolves to global 5.
  1911. Only entry 257 has local slot=1, other entries are unmapped (65535).
  1912. Reproduces exact data from issue #420 support package.
  1913. """
  1914. mqtt_client.state.raw_data["mapping"] = [65535, 65535, 65535, 257]
  1915. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1916. assert mqtt_client.state.tray_now == 5
  1917. def test_ambiguous_mapping_falls_back_to_local_slot(self, mqtt_client):
  1918. """Two AMS units with same local slot in mapping → ambiguous, keep local slot.
  1919. mapping=[1, 257]: both have local slot 1 (AMS0-T1 and AMS1-T1).
  1920. Cannot disambiguate → fall back to tray_now=1.
  1921. """
  1922. mqtt_client.state.raw_data["mapping"] = [1, 257]
  1923. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1924. assert mqtt_client.state.tray_now == 1
  1925. def test_no_mapping_falls_back_to_local_slot(self, mqtt_client):
  1926. """No mapping field available → fall back to raw tray_now."""
  1927. # No mapping in raw_data (e.g. manual filament load, not during print)
  1928. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1929. assert mqtt_client.state.tray_now == 1
  1930. def test_empty_mapping_falls_back_to_local_slot(self, mqtt_client):
  1931. """Empty mapping list → fall back to raw tray_now."""
  1932. mqtt_client.state.raw_data["mapping"] = []
  1933. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1934. assert mqtt_client.state.tray_now == 1
  1935. def test_single_ams_passthrough(self, mqtt_client):
  1936. """Single AMS (ams_exist_bits='1') → tray_now 0-3 is direct global ID."""
  1937. mqtt_client._process_message(_ams_payload(2, ams_exist_bits="1"))
  1938. assert mqtt_client.state.tray_now == 2
  1939. def test_no_ams_exist_bits_passthrough(self, mqtt_client):
  1940. """No ams_exist_bits in payload → fall back to raw tray_now."""
  1941. mqtt_client._process_message(_ams_payload(1))
  1942. assert mqtt_client.state.tray_now == 1
  1943. def test_tray_now_255_unaffected_by_multi_ams(self, mqtt_client):
  1944. """tray_now=255 (unloaded) passes through regardless of AMS count."""
  1945. mqtt_client.state.raw_data["mapping"] = [257]
  1946. mqtt_client._process_message(_ams_payload(255, ams_exist_bits="3"))
  1947. assert mqtt_client.state.tray_now == 255
  1948. def test_tray_now_above_3_unaffected(self, mqtt_client):
  1949. """tray_now > 3 is already a global ID and passes through directly."""
  1950. mqtt_client._process_message(_ams_payload(6, ams_exist_bits="3"))
  1951. assert mqtt_client.state.tray_now == 6
  1952. def test_last_loaded_tray_uses_resolved_global_id(self, mqtt_client):
  1953. """last_loaded_tray should reflect the resolved global ID, not local slot."""
  1954. mqtt_client.state.raw_data["mapping"] = [257]
  1955. mqtt_client.state.state = "RUNNING"
  1956. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  1957. assert mqtt_client.state.tray_now == 5
  1958. assert mqtt_client.state.last_loaded_tray == 5
  1959. class TestResolveLocalSlotFromMapping:
  1960. """Unit tests for _resolve_local_slot_from_mapping static method."""
  1961. def test_single_match_ams0(self):
  1962. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1963. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [1]) == 1
  1964. def test_single_match_ams1(self):
  1965. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1966. # 257 = 1*256 + 1 → AMS1 slot1 → global 5
  1967. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [257]) == 5
  1968. def test_single_match_ams2(self):
  1969. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1970. # 514 = 2*256 + 2 → AMS2 slot2 → global 10
  1971. assert BambuMQTTClient._resolve_local_slot_from_mapping(2, [514]) == 10
  1972. def test_unmapped_entries_skipped(self):
  1973. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1974. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [65535, 65535, 65535, 257]) == 5
  1975. def test_no_match_returns_none(self):
  1976. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1977. # mapping has slot 0 only, looking for slot 2
  1978. assert BambuMQTTClient._resolve_local_slot_from_mapping(2, [0]) is None
  1979. def test_ambiguous_returns_none(self):
  1980. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1981. # Both AMS0 slot1 (1) and AMS1 slot1 (257) → ambiguous
  1982. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [1, 257]) is None
  1983. def test_none_mapping_returns_none(self):
  1984. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1985. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, None) is None
  1986. def test_empty_mapping_returns_none(self):
  1987. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1988. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, []) is None
  1989. def test_ams_ht_slot0_match(self):
  1990. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1991. # AMS-HT id=128: snow = 128*256 + 0 = 32768
  1992. assert BambuMQTTClient._resolve_local_slot_from_mapping(0, [32768]) == 128
  1993. # ---------------------------------------------------------------------------
  1994. # 3. H2D Pro — initial state detection
  1995. # ---------------------------------------------------------------------------
  1996. class TestTrayNowDualNozzleH2DSetup:
  1997. """H2D Pro initial state detection."""
  1998. @pytest.fixture
  1999. def mqtt_client(self):
  2000. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2001. return BambuMQTTClient(
  2002. ip_address="192.168.1.100",
  2003. serial_number="TEST_H2D",
  2004. access_code="12345678",
  2005. )
  2006. def test_dual_nozzle_detected_from_extruder_info(self, mqtt_client):
  2007. """2 entries in device.extruder.info → _is_dual_nozzle=True."""
  2008. mqtt_client._process_message(
  2009. _extruder_info_payload(
  2010. [
  2011. {"id": 0, "snow": 0xFF00FF},
  2012. {"id": 1, "snow": 0xFF00FF},
  2013. ]
  2014. )
  2015. )
  2016. assert mqtt_client._is_dual_nozzle is True
  2017. def test_ams_extruder_map_parsed_from_info_field(self, mqtt_client):
  2018. """AMS info field is hex: 0x2003 → ext 0 (right), 0x2104 → ext 1 (left)."""
  2019. # MQTT sends info as string; BambuStudio parses as hex via stoull(str, 16)
  2020. ams_units = [
  2021. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2022. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  2023. ]
  2024. payload = {
  2025. "print": {
  2026. "ams": {
  2027. "ams": ams_units,
  2028. "tray_now": "255",
  2029. "tray_exist_bits": "1000f",
  2030. },
  2031. }
  2032. }
  2033. mqtt_client._process_message(payload)
  2034. # 0x2003: bits 8-11 = (0x2003 >> 8) & 0xF = 0x20 & 0xF = 0 → extruder 0 (right)
  2035. # 0x2104: bits 8-11 = (0x2104 >> 8) & 0xF = 0x21 & 0xF = 1 → extruder 1 (left)
  2036. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2037. def test_ams_extruder_map_real_h2d_values(self, mqtt_client):
  2038. """Real H2D MQTT values: AMS2 Pro on right, AMS-HT on left."""
  2039. ams_units = [
  2040. {"id": 0, "info": "10001003", "tray": [{"id": i} for i in range(4)]},
  2041. {"id": 128, "info": "10002104", "tray": [{"id": 0}]},
  2042. ]
  2043. payload = {
  2044. "print": {
  2045. "ams": {
  2046. "ams": ams_units,
  2047. "tray_now": "255",
  2048. "tray_exist_bits": "1000a",
  2049. },
  2050. }
  2051. }
  2052. mqtt_client._process_message(payload)
  2053. # 0x10001003: bits 8-11 = (0x10001003 >> 8) & 0xF = 0x10 & 0xF = 0 → right
  2054. # 0x10002104: bits 8-11 = (0x10002104 >> 8) & 0xF = 0x21 & 0xF = 1 → left
  2055. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2056. def test_ams_extruder_map_skips_uninitialized(self, mqtt_client):
  2057. """extruder_id 0xE means uninitialized AMS — should be skipped."""
  2058. ams_units = [
  2059. {"id": 0, "info": "e03", "tray": [{"id": i} for i in range(4)]},
  2060. ]
  2061. payload = {
  2062. "print": {
  2063. "ams": {
  2064. "ams": ams_units,
  2065. "tray_now": "255",
  2066. "tray_exist_bits": "f",
  2067. },
  2068. }
  2069. }
  2070. mqtt_client._process_message(payload)
  2071. assert mqtt_client.state.ams_extruder_map == {}
  2072. def test_ams_extruder_map_partial_update_preserves_entries(self, mqtt_client):
  2073. """Partial MQTT update with one AMS should not overwrite other entries."""
  2074. # First: full update with both AMS units
  2075. full_payload = {
  2076. "print": {
  2077. "ams": {
  2078. "ams": [
  2079. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2080. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  2081. ],
  2082. "tray_now": "255",
  2083. "tray_exist_bits": "1000f",
  2084. },
  2085. }
  2086. }
  2087. mqtt_client._process_message(full_payload)
  2088. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2089. # Then: partial update with only AMS 0 (no info field this time)
  2090. partial_payload = {
  2091. "print": {
  2092. "ams": {
  2093. "ams": [
  2094. {"id": 0, "tray": [{"id": 0, "remain": 50}]},
  2095. ],
  2096. "tray_now": "0",
  2097. "tray_exist_bits": "1000f",
  2098. },
  2099. }
  2100. }
  2101. mqtt_client._process_message(partial_payload)
  2102. # Both entries should still be present
  2103. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2104. def test_dual_nozzle_detection_before_ams_in_same_message(self, mqtt_client):
  2105. """Dual-nozzle detection at line 538 happens before _handle_ams_data() at line 549.
  2106. If both arrive in the same message, tray_now disambiguation already uses dual-nozzle logic.
  2107. """
  2108. payload = {
  2109. "print": {
  2110. "device": {
  2111. "extruder": {
  2112. "info": [
  2113. {"id": 0, "snow": 0xFF00FF},
  2114. {"id": 1, "snow": 0xFF00FF},
  2115. ],
  2116. "state": 0x0001,
  2117. }
  2118. },
  2119. "ams": {
  2120. "ams": [
  2121. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2122. ],
  2123. "tray_now": "2",
  2124. "tray_exist_bits": "f",
  2125. },
  2126. }
  2127. }
  2128. mqtt_client._process_message(payload)
  2129. # Dual-nozzle was detected; AMS 0 on right extruder (active by default);
  2130. # snow is 0xFF00FF (unloaded), so falls through to ams_extruder_map fallback.
  2131. # Single AMS on extruder 0 → global_id = 0*4+2 = 2
  2132. assert mqtt_client._is_dual_nozzle is True
  2133. assert mqtt_client.state.tray_now == 2
  2134. # ---------------------------------------------------------------------------
  2135. # Shared H2D fixture for classes 4-8
  2136. # ---------------------------------------------------------------------------
  2137. class _H2DFixtureMixin:
  2138. """Mixin providing a pre-configured H2D Pro client."""
  2139. @pytest.fixture
  2140. def mqtt_client(self):
  2141. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2142. return BambuMQTTClient(
  2143. ip_address="192.168.1.100",
  2144. serial_number="TEST_H2D",
  2145. access_code="12345678",
  2146. )
  2147. @pytest.fixture
  2148. def h2d_client(self, mqtt_client):
  2149. """Pre-configure as H2D Pro: dual-nozzle + ams_extruder_map."""
  2150. mqtt_client._process_message(
  2151. {
  2152. "print": {
  2153. "device": {
  2154. "extruder": {
  2155. "info": [
  2156. {"id": 0, "snow": 0xFF00FF},
  2157. {"id": 1, "snow": 0xFF00FF},
  2158. ],
  2159. "state": 0x0001, # right extruder active
  2160. }
  2161. },
  2162. "ams": {
  2163. "ams": [
  2164. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2165. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  2166. ],
  2167. "tray_now": "255",
  2168. "tray_exist_bits": "1000f",
  2169. },
  2170. }
  2171. }
  2172. )
  2173. assert mqtt_client._is_dual_nozzle is True
  2174. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2175. return mqtt_client
  2176. # ---------------------------------------------------------------------------
  2177. # 4. H2D Snow field disambiguation
  2178. # ---------------------------------------------------------------------------
  2179. class TestTrayNowDualNozzleH2DSnow(_H2DFixtureMixin):
  2180. """Snow field disambiguation (primary path)."""
  2181. def test_snow_disambiguates_ams0_slot(self, h2d_client):
  2182. """snow ext[0]=AMS 0 slot 2, tray_now='2' → global 2."""
  2183. # Send snow update FIRST (snow is parsed AFTER tray_now in the same message,
  2184. # so we need it in a prior message).
  2185. snow_val = 0 << 8 | 2 # AMS 0 slot 2 = raw 2
  2186. h2d_client._process_message(
  2187. _extruder_info_payload(
  2188. [
  2189. {"id": 0, "snow": snow_val},
  2190. {"id": 1, "snow": 0xFF00FF},
  2191. ]
  2192. )
  2193. )
  2194. assert h2d_client.state.h2d_extruder_snow.get(0) == 2
  2195. # Now send tray_now=2
  2196. h2d_client._process_message(_ams_payload(2))
  2197. assert h2d_client.state.tray_now == 2
  2198. def test_snow_disambiguates_ams_ht_to_128(self, h2d_client):
  2199. """snow ext[1]=AMS HT (128), left active, tray_now='0' → global 128."""
  2200. # Snow: extruder 1 → AMS 128 slot 0
  2201. snow_val = 128 << 8 | 0 # = 32768
  2202. h2d_client._process_message(
  2203. _extruder_info_payload(
  2204. [
  2205. {"id": 0, "snow": 0xFF00FF},
  2206. {"id": 1, "snow": snow_val},
  2207. ]
  2208. )
  2209. )
  2210. assert h2d_client.state.h2d_extruder_snow.get(1) == 128
  2211. # Switch to left extruder
  2212. h2d_client._process_message(_extruder_state_payload(0x0100))
  2213. assert h2d_client.state.active_extruder == 1
  2214. # tray_now="0" with left extruder active, snow says AMS HT (128)
  2215. # AMS HT snow_slot = 0 (single slot), parsed_tray_now = 0 → match
  2216. h2d_client._process_message(_ams_payload(0))
  2217. assert h2d_client.state.tray_now == 128
  2218. def test_snow_updates_h2d_extruder_snow_state(self, h2d_client):
  2219. """Verify state.h2d_extruder_snow dict is populated correctly."""
  2220. snow_ext0 = 1 << 8 | 3 # AMS 1 slot 3 → global 7
  2221. snow_ext1 = 0 << 8 | 0 # AMS 0 slot 0 → global 0
  2222. h2d_client._process_message(
  2223. _extruder_info_payload(
  2224. [
  2225. {"id": 0, "snow": snow_ext0},
  2226. {"id": 1, "snow": snow_ext1},
  2227. ]
  2228. )
  2229. )
  2230. assert h2d_client.state.h2d_extruder_snow[0] == 7
  2231. assert h2d_client.state.h2d_extruder_snow[1] == 0
  2232. def test_snow_unloaded_value(self, h2d_client):
  2233. """snow=0xFFFF (ams_id=255, slot=255) → 255 (unloaded)."""
  2234. h2d_client._process_message(
  2235. _extruder_info_payload(
  2236. [
  2237. {"id": 0, "snow": 0xFFFF},
  2238. {"id": 1, "snow": 0xFFFF},
  2239. ]
  2240. )
  2241. )
  2242. assert h2d_client.state.h2d_extruder_snow[0] == 255
  2243. assert h2d_client.state.h2d_extruder_snow[1] == 255
  2244. def test_snow_initial_sentinel_not_stored(self, h2d_client):
  2245. """snow=0xFF00FF (firmware initial sentinel) is not parsed into h2d_extruder_snow."""
  2246. # 0xFF00FF has ams_id=0xFF00=65280 which doesn't match any branch
  2247. h2d_client._process_message(
  2248. _extruder_info_payload(
  2249. [
  2250. {"id": 0, "snow": 0xFF00FF},
  2251. {"id": 1, "snow": 0xFF00FF},
  2252. ]
  2253. )
  2254. )
  2255. # Snow dict should remain empty (no matching branch)
  2256. assert h2d_client.state.h2d_extruder_snow == {}
  2257. # ---------------------------------------------------------------------------
  2258. # 5. H2D Pending target disambiguation
  2259. # ---------------------------------------------------------------------------
  2260. class TestTrayNowDualNozzleH2DPendingTarget(_H2DFixtureMixin):
  2261. """Pending target disambiguation (when Bambuddy initiates load)."""
  2262. def test_pending_target_matches_slot(self, h2d_client):
  2263. """pending=5, tray_now='1' (5%4=1 matches) → tray_now=5."""
  2264. h2d_client.state.pending_tray_target = 5
  2265. h2d_client._process_message(_ams_payload(1))
  2266. assert h2d_client.state.tray_now == 5
  2267. assert h2d_client.state.pending_tray_target is None # cleared
  2268. def test_pending_target_slot_mismatch(self, h2d_client):
  2269. """pending=5, tray_now='2' → uses raw slot, clears pending."""
  2270. h2d_client.state.pending_tray_target = 5
  2271. h2d_client._process_message(_ams_payload(2))
  2272. # Slot 2 != 5%4=1 → mismatch, uses raw slot 2
  2273. assert h2d_client.state.tray_now == 2
  2274. assert h2d_client.state.pending_tray_target is None
  2275. def test_pending_target_takes_priority_over_snow(self, h2d_client):
  2276. """When both pending and snow are set, pending wins."""
  2277. # Set up snow for extruder 0 → AMS 0 slot 1 → global 1
  2278. snow_val = 0 << 8 | 1
  2279. h2d_client._process_message(
  2280. _extruder_info_payload(
  2281. [
  2282. {"id": 0, "snow": snow_val},
  2283. {"id": 1, "snow": 0xFF00FF},
  2284. ]
  2285. )
  2286. )
  2287. assert h2d_client.state.h2d_extruder_snow.get(0) == 1
  2288. # Set pending target to AMS 1 slot 1 (global 5)
  2289. h2d_client.state.pending_tray_target = 5
  2290. # tray_now="1" — matches pending (5%4=1), pending should win over snow
  2291. h2d_client._process_message(_ams_payload(1))
  2292. assert h2d_client.state.tray_now == 5
  2293. # ---------------------------------------------------------------------------
  2294. # 6. H2D ams_extruder_map fallback
  2295. # ---------------------------------------------------------------------------
  2296. class TestTrayNowDualNozzleH2DFallback(_H2DFixtureMixin):
  2297. """ams_extruder_map fallback (no pending, no snow)."""
  2298. def test_single_ams_on_extruder_computes_global_id(self, h2d_client):
  2299. """AMS 0 on right extruder, tray_now='2' → 0*4+2=2."""
  2300. # h2d_client has snow=0xFF00FF (unloaded) by default, so snow path skips
  2301. h2d_client._process_message(_ams_payload(2))
  2302. # AMS 0 is the only AMS on extruder 0 (right, active by default)
  2303. # Fallback: single AMS → global = 0*4+2 = 2
  2304. assert h2d_client.state.tray_now == 2
  2305. def test_multiple_ams_keeps_current_if_valid(self, h2d_client):
  2306. """Current tray matches slot → keeps it (multi-AMS on same extruder)."""
  2307. # Set up: two AMS units on the same extruder (right, ext 0)
  2308. h2d_client.state.ams_extruder_map = {"0": 0, "1": 0}
  2309. # Pre-set tray_now=5 (AMS 1 slot 1) — current_ams=1 which is in ams_on_extruder
  2310. h2d_client.state.tray_now = 5
  2311. # tray_now="1" → 5%4=1 matches → keep current=5
  2312. h2d_client._process_message(_ams_payload(1))
  2313. assert h2d_client.state.tray_now == 5
  2314. def test_no_ams_on_extruder_uses_raw_slot(self, h2d_client):
  2315. """No AMS mapped to the active extruder → raw slot as global ID."""
  2316. # All AMS on left extruder, but right is active
  2317. h2d_client.state.ams_extruder_map = {"0": 1, "128": 1}
  2318. h2d_client._process_message(_ams_payload(2))
  2319. assert h2d_client.state.tray_now == 2
  2320. def test_single_ams_ht_on_extruder_returns_unit_id(self, h2d_client):
  2321. """AMS-HT 128 alone on left extruder, slot 0 → global ID 128 (not 512)."""
  2322. # Switch to left extruder (where AMS-HT 128 is mapped)
  2323. h2d_client._process_message(_extruder_state_payload(0x0100))
  2324. # Only AMS-HT 128 on left extruder; no snow available
  2325. h2d_client._process_message(_ams_payload(0))
  2326. assert h2d_client.state.tray_now == 128
  2327. def test_single_ams_ht_ignores_nonzero_slot(self, h2d_client):
  2328. """AMS-HT has single slot; even if printer reports slot 1, global ID = unit ID."""
  2329. h2d_client.state.ams_extruder_map = {"129": 0}
  2330. h2d_client._process_message(_ams_payload(1))
  2331. # AMS-HT 129: global ID = 129, not 129*4+1=517
  2332. assert h2d_client.state.tray_now == 129
  2333. def test_multiple_ams_keeps_current_ams_ht(self, h2d_client):
  2334. """Current tray is AMS-HT 128, slot 0 reported → keeps 128."""
  2335. h2d_client.state.ams_extruder_map = {"0": 0, "128": 0}
  2336. h2d_client.state.tray_now = 128
  2337. h2d_client._process_message(_ams_payload(0))
  2338. assert h2d_client.state.tray_now == 128
  2339. def test_multiple_ams_slot_nonzero_excludes_ams_ht(self, h2d_client):
  2340. """Slot > 0 eliminates AMS-HT candidates; single regular AMS left → resolves."""
  2341. # AMS 0 + AMS-HT 128 both on right extruder
  2342. h2d_client.state.ams_extruder_map = {"0": 0, "128": 0}
  2343. h2d_client.state.tray_now = 255 # no current match
  2344. # Slot 2 → can't be AMS-HT → only AMS 0 → global = 0*4+2 = 2
  2345. h2d_client._process_message(_ams_payload(2))
  2346. assert h2d_client.state.tray_now == 2
  2347. def test_multiple_ams_slot_nonzero_narrows_to_single_ht_excluded(self, h2d_client):
  2348. """Two regular AMS + one AMS-HT, slot > 0 → AMS-HT excluded but still ambiguous."""
  2349. h2d_client.state.ams_extruder_map = {"0": 0, "1": 0, "128": 0}
  2350. h2d_client.state.tray_now = 255
  2351. # Slot 3 → excludes AMS-HT, but AMS 0 and AMS 1 both remain → ambiguous
  2352. h2d_client._process_message(_ams_payload(3))
  2353. assert h2d_client.state.tray_now == 3 # raw slot fallback
  2354. # ---------------------------------------------------------------------------
  2355. # 6b. H2D last_loaded_tray validation
  2356. # ---------------------------------------------------------------------------
  2357. class TestLastLoadedTrayValidation(_H2DFixtureMixin):
  2358. """last_loaded_tray only stores physically valid tray IDs."""
  2359. def test_regular_ams_tray_stored(self, h2d_client):
  2360. """Valid regular AMS tray (0-15) → stored in last_loaded_tray."""
  2361. h2d_client.state.tray_now = 7
  2362. # Trigger tray_now processing via AMS message
  2363. h2d_client._process_message(
  2364. _extruder_info_payload(
  2365. [
  2366. {"id": 0, "snow": 1 << 8 | 3}, # AMS 1 slot 3 → global 7
  2367. {"id": 1, "snow": 0xFF00FF},
  2368. ]
  2369. )
  2370. )
  2371. h2d_client._process_message(_ams_payload(3))
  2372. assert h2d_client.state.tray_now == 7
  2373. assert h2d_client.state.last_loaded_tray == 7
  2374. def test_ams_ht_tray_stored(self, h2d_client):
  2375. """Valid AMS-HT tray (128-135) → stored in last_loaded_tray."""
  2376. h2d_client._process_message(_extruder_state_payload(0x0100))
  2377. h2d_client._process_message(
  2378. _extruder_info_payload(
  2379. [
  2380. {"id": 0, "snow": 0xFF00FF},
  2381. {"id": 1, "snow": 128 << 8 | 0},
  2382. ]
  2383. )
  2384. )
  2385. h2d_client._process_message(_ams_payload(0))
  2386. assert h2d_client.state.tray_now == 128
  2387. assert h2d_client.state.last_loaded_tray == 128
  2388. def test_unloaded_not_stored(self, h2d_client):
  2389. """tray_now=255 (unloaded) → last_loaded_tray unchanged."""
  2390. h2d_client.state.last_loaded_tray = 5
  2391. h2d_client._process_message(_ams_payload(255))
  2392. assert h2d_client.state.tray_now == 255
  2393. assert h2d_client.state.last_loaded_tray == 5
  2394. # ---------------------------------------------------------------------------
  2395. # 7. H2D Active extruder switching
  2396. # ---------------------------------------------------------------------------
  2397. class TestTrayNowDualNozzleH2DActiveExtruder(_H2DFixtureMixin):
  2398. """Active extruder switching via device.extruder.state bit 8."""
  2399. def test_active_extruder_right_by_default(self, h2d_client):
  2400. """Initial state.active_extruder == 0 (right)."""
  2401. assert h2d_client.state.active_extruder == 0
  2402. def test_extruder_state_bit8_switches_to_left(self, h2d_client):
  2403. """state=0x100 → active_extruder=1 (left)."""
  2404. h2d_client._process_message(_extruder_state_payload(0x0100))
  2405. assert h2d_client.state.active_extruder == 1
  2406. def test_extruder_state_bit8_switches_back_to_right(self, h2d_client):
  2407. """Cycle 0 → 1 → 0."""
  2408. h2d_client._process_message(_extruder_state_payload(0x0100))
  2409. assert h2d_client.state.active_extruder == 1
  2410. h2d_client._process_message(_extruder_state_payload(0x0001))
  2411. assert h2d_client.state.active_extruder == 0
  2412. def test_extruder_switch_changes_tray_disambiguation(self, h2d_client):
  2413. """Snow on both extruders; switching active changes which snow is used."""
  2414. # Snow: ext 0 → AMS 0 slot 1 (global 1), ext 1 → AMS 128 slot 0 (global 128)
  2415. h2d_client._process_message(
  2416. _extruder_info_payload(
  2417. [
  2418. {"id": 0, "snow": 0 << 8 | 1}, # AMS 0 slot 1 → global 1
  2419. {"id": 1, "snow": 128 << 8 | 0}, # AMS HT → global 128
  2420. ]
  2421. )
  2422. )
  2423. # Right active (default) — tray_now="1" → snow ext[0] says global 1
  2424. h2d_client._process_message(_ams_payload(1))
  2425. assert h2d_client.state.tray_now == 1
  2426. # Switch to left
  2427. h2d_client._process_message(_extruder_state_payload(0x0100))
  2428. # Left active — tray_now="0" → snow ext[1] says AMS HT (128), slot 0 matches
  2429. h2d_client._process_message(_ams_payload(0))
  2430. assert h2d_client.state.tray_now == 128
  2431. # ---------------------------------------------------------------------------
  2432. # 8. Device identification probe (#1684 enabler)
  2433. # ---------------------------------------------------------------------------
  2434. class TestDeviceIdentificationProbe:
  2435. """One-shot INFO log of any device.* identification fields the firmware
  2436. sends. Lets a new-model support bundle self-disclose the internal model
  2437. code (e.g. dev_model_name='N2L') without a separate debug build.
  2438. """
  2439. @pytest.fixture
  2440. def mqtt_client(self):
  2441. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2442. return BambuMQTTClient(
  2443. ip_address="192.168.1.100",
  2444. serial_number="TEST_PROBE",
  2445. access_code="12345678",
  2446. )
  2447. def _device_payload(self, device):
  2448. return {"print": {"device": device}}
  2449. def test_logs_known_id_fields_once(self, mqtt_client, caplog):
  2450. import logging
  2451. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  2452. mqtt_client._process_message(
  2453. self._device_payload({"dev_model_name": "N2S", "dev_product_name": "Bambu Lab A1"})
  2454. )
  2455. matches = [r for r in caplog.records if "Device identification" in r.getMessage()]
  2456. assert len(matches) == 1
  2457. msg = matches[0].getMessage()
  2458. assert "dev_model_name" in msg and "N2S" in msg
  2459. assert "dev_product_name" in msg
  2460. def test_one_shot_does_not_repeat(self, mqtt_client, caplog):
  2461. import logging
  2462. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  2463. payload = self._device_payload({"dev_model_name": "N2S"})
  2464. mqtt_client._process_message(payload)
  2465. mqtt_client._process_message(payload)
  2466. mqtt_client._process_message(payload)
  2467. matches = [r for r in caplog.records if "Device identification" in r.getMessage()]
  2468. assert len(matches) == 1
  2469. def test_fallback_dumps_keys_when_no_known_fields(self, mqtt_client, caplog):
  2470. """Future Bambu rename (e.g. model_name without dev_ prefix) still surfaces."""
  2471. import logging
  2472. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  2473. mqtt_client._process_message(self._device_payload({"model_name": "MysteryModel", "extruder": {"state": 0}}))
  2474. matches = [r for r in caplog.records if "Device identification" in r.getMessage()]
  2475. assert len(matches) == 1
  2476. msg = matches[0].getMessage()
  2477. assert "no known id fields" in msg
  2478. assert "model_name" in msg and "extruder" in msg
  2479. # ---------------------------------------------------------------------------
  2480. # 8. H2D Full multi-message sequences
  2481. # ---------------------------------------------------------------------------
  2482. class TestTrayNowDualNozzleH2DFullSequence(_H2DFixtureMixin):
  2483. """Multi-message sequences simulating real H2D Pro prints."""
  2484. def test_h2d_right_nozzle_ams0_lifecycle(self, h2d_client):
  2485. """Setup → load AMS 0 slot 1 → verify tray_now=1."""
  2486. # Snow update: extruder 0 loading AMS 0 slot 1
  2487. h2d_client._process_message(
  2488. _extruder_info_payload(
  2489. [
  2490. {"id": 0, "snow": 0 << 8 | 1},
  2491. {"id": 1, "snow": 0xFF00FF},
  2492. ]
  2493. )
  2494. )
  2495. # Printer reports tray_now="1"
  2496. h2d_client._process_message(_ams_payload(1))
  2497. assert h2d_client.state.tray_now == 1
  2498. assert h2d_client.state.last_loaded_tray == 1
  2499. def test_h2d_left_nozzle_ams_ht_lifecycle(self, h2d_client):
  2500. """Setup → switch left → load AMS HT → verify tray_now=128."""
  2501. # Switch to left extruder
  2502. h2d_client._process_message(_extruder_state_payload(0x0100))
  2503. # Snow: ext 1 → AMS HT slot 0
  2504. h2d_client._process_message(
  2505. _extruder_info_payload(
  2506. [
  2507. {"id": 0, "snow": 0xFF00FF},
  2508. {"id": 1, "snow": 128 << 8 | 0},
  2509. ]
  2510. )
  2511. )
  2512. # Printer reports tray_now="0" (AMS HT single slot)
  2513. h2d_client._process_message(_ams_payload(0))
  2514. assert h2d_client.state.tray_now == 128
  2515. assert h2d_client.state.last_loaded_tray == 128
  2516. def test_h2d_multi_color_alternating_nozzles(self, h2d_client):
  2517. """Multi-color print alternating between right and left nozzles.
  2518. Sequence:
  2519. 1. Right loads AMS 0 slot 0 (tray=0)
  2520. 2. Switch left, load AMS HT (tray=128)
  2521. 3. Switch right, snow updates, load AMS 0 slot 2 (tray=2)
  2522. 4. Unload (255)
  2523. """
  2524. # Step 1: Right extruder loads AMS 0 slot 0
  2525. h2d_client._process_message(
  2526. _extruder_info_payload(
  2527. [
  2528. {"id": 0, "snow": 0 << 8 | 0},
  2529. {"id": 1, "snow": 0xFF00FF},
  2530. ]
  2531. )
  2532. )
  2533. h2d_client._process_message(_ams_payload(0))
  2534. assert h2d_client.state.tray_now == 0
  2535. # Step 2: Switch to left, load AMS HT
  2536. h2d_client._process_message(_extruder_state_payload(0x0100))
  2537. h2d_client._process_message(
  2538. _extruder_info_payload(
  2539. [
  2540. {"id": 0, "snow": 0 << 8 | 0},
  2541. {"id": 1, "snow": 128 << 8 | 0},
  2542. ]
  2543. )
  2544. )
  2545. h2d_client._process_message(_ams_payload(0))
  2546. assert h2d_client.state.tray_now == 128
  2547. # Step 3: Switch back to right, load AMS 0 slot 2
  2548. h2d_client._process_message(_extruder_state_payload(0x0001))
  2549. h2d_client._process_message(
  2550. _extruder_info_payload(
  2551. [
  2552. {"id": 0, "snow": 0 << 8 | 2},
  2553. {"id": 1, "snow": 128 << 8 | 0},
  2554. ]
  2555. )
  2556. )
  2557. h2d_client._process_message(_ams_payload(2))
  2558. assert h2d_client.state.tray_now == 2
  2559. # Step 4: Unload
  2560. h2d_client._process_message(_ams_payload(255))
  2561. assert h2d_client.state.tray_now == 255
  2562. assert h2d_client.state.last_loaded_tray == 2
  2563. class TestTrayChangeLog:
  2564. """Tests for tray_change_log tracking during prints (mid-print tray switch)."""
  2565. @pytest.fixture
  2566. def mqtt_client(self):
  2567. """Create a BambuMQTTClient instance for testing."""
  2568. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2569. client = BambuMQTTClient(
  2570. ip_address="192.168.1.100",
  2571. serial_number="TRAYLOG1",
  2572. access_code="12345678",
  2573. )
  2574. return client
  2575. def test_tray_change_log_defaults_empty(self, mqtt_client):
  2576. """tray_change_log starts as an empty list."""
  2577. assert mqtt_client.state.tray_change_log == []
  2578. def test_tray_change_log_seeded_on_print_start(self, mqtt_client):
  2579. """Print start clears log and seeds with initial tray at layer 0."""
  2580. mqtt_client.state.tray_now = 2
  2581. mqtt_client.state.last_loaded_tray = 2
  2582. mqtt_client._previous_gcode_state = "IDLE"
  2583. # Transition to RUNNING via _process_message
  2584. mqtt_client._process_message(
  2585. {
  2586. "print": {
  2587. "gcode_state": "RUNNING",
  2588. "gcode_file": "test.3mf",
  2589. }
  2590. }
  2591. )
  2592. assert mqtt_client.state.tray_change_log == [(2, 0)]
  2593. def test_tray_change_log_cleared_on_new_print(self, mqtt_client):
  2594. """Old log entries are cleared when a new print starts."""
  2595. mqtt_client.state.tray_change_log = [(5, 0), (3, 100)]
  2596. mqtt_client.state.tray_now = 1
  2597. mqtt_client.state.last_loaded_tray = 1
  2598. mqtt_client._previous_gcode_state = "IDLE"
  2599. mqtt_client._process_message(
  2600. {
  2601. "print": {
  2602. "gcode_state": "RUNNING",
  2603. "gcode_file": "new.3mf",
  2604. }
  2605. }
  2606. )
  2607. assert mqtt_client.state.tray_change_log == [(1, 0)]
  2608. # Helper that mirrors the production gate at bambu_mqtt.py:1571 — tests
  2609. # below replicate the gate so they validate the *contract* without needing
  2610. # to feed a synthetic AMS push through the full _process_message path.
  2611. @staticmethod
  2612. def _record_if_change(client, tn: int) -> None:
  2613. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  2614. if tn != client.state.last_loaded_tray and client._was_running and not client._completion_triggered:
  2615. client.state.tray_change_log.append((tn, client.state.layer_num))
  2616. client.state.last_loaded_tray = tn
  2617. def test_tray_change_recorded_during_running(self, mqtt_client):
  2618. """Tray change while RUNNING is appended to the log."""
  2619. mqtt_client.state.state = "RUNNING"
  2620. mqtt_client._was_running = True
  2621. mqtt_client._completion_triggered = False
  2622. mqtt_client.state.layer_num = 50
  2623. mqtt_client.state.last_loaded_tray = 0
  2624. mqtt_client.state.tray_change_log = [(0, 0)]
  2625. mqtt_client.state.tray_now = 1
  2626. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2627. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50)]
  2628. def test_tray_change_not_recorded_when_idle(self, mqtt_client):
  2629. """Tray changes outside an active print are NOT logged."""
  2630. # IDLE between prints — both lifecycle flags in the cleared state.
  2631. mqtt_client.state.state = "IDLE"
  2632. mqtt_client._was_running = False
  2633. mqtt_client._completion_triggered = False
  2634. mqtt_client.state.layer_num = 0
  2635. mqtt_client.state.last_loaded_tray = 0
  2636. mqtt_client.state.tray_change_log = []
  2637. mqtt_client.state.tray_now = 3
  2638. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2639. assert mqtt_client.state.tray_change_log == []
  2640. def test_tray_change_recorded_during_pause(self, mqtt_client):
  2641. """Tray change while PAUSE is also logged (AMS can swap during pause)."""
  2642. mqtt_client.state.state = "PAUSE"
  2643. mqtt_client._was_running = True
  2644. mqtt_client._completion_triggered = False
  2645. mqtt_client.state.layer_num = 75
  2646. mqtt_client.state.last_loaded_tray = 2
  2647. mqtt_client.state.tray_change_log = [(2, 0)]
  2648. mqtt_client.state.tray_now = 5
  2649. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2650. assert mqtt_client.state.tray_change_log == [(2, 0), (5, 75)]
  2651. def test_tray_change_recorded_during_intermediate_state(self, mqtt_client):
  2652. """Tray change during a transient non-RUNNING state mid-print is logged.
  2653. Regression for #957: P2S firmware briefly transitions out of RUNNING
  2654. (e.g. into LOADING) when the AMS auto-falls-back from an empty spool to
  2655. a same-material sibling. The previous gate ``state in ("RUNNING",
  2656. "PAUSE")`` missed this transition entirely, so the usage tracker had no
  2657. evidence of the switch and double-credited the original tray with the
  2658. full 3MF estimate while the remain%-delta path added the fallback
  2659. weight on top. The new gate keys on the print-lifecycle flags
  2660. (``_was_running and not _completion_triggered``) so any tray change
  2661. between print start and completion is captured regardless of the
  2662. momentary gcode_state string.
  2663. """
  2664. mqtt_client.state.state = "LOADING" # not RUNNING/PAUSE — old gate would skip
  2665. mqtt_client._was_running = True
  2666. mqtt_client._completion_triggered = False
  2667. mqtt_client.state.layer_num = 42
  2668. mqtt_client.state.last_loaded_tray = 0
  2669. mqtt_client.state.tray_change_log = [(0, 0)]
  2670. # AMS auto-fallback: T0 ran out, swapped to T1 of same material
  2671. mqtt_client.state.tray_now = 1
  2672. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2673. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 42)]
  2674. def test_tray_change_not_recorded_after_completion(self, mqtt_client):
  2675. """Once on_print_complete has fired, further tray changes don't pollute the log."""
  2676. mqtt_client.state.state = "FINISH"
  2677. mqtt_client._was_running = True
  2678. mqtt_client._completion_triggered = True # completion already triggered
  2679. mqtt_client.state.layer_num = 0
  2680. mqtt_client.state.last_loaded_tray = 1
  2681. mqtt_client.state.tray_change_log = [(0, 0), (1, 50)]
  2682. mqtt_client.state.tray_now = 2
  2683. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2684. # Log unchanged — completion already triggered so post-print tray
  2685. # movement (e.g. printer self-cleaning) doesn't bleed into the next
  2686. # print's attribution.
  2687. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50)]
  2688. def test_same_tray_not_logged_twice(self, mqtt_client):
  2689. """Same tray value doesn't create duplicate log entries."""
  2690. mqtt_client.state.state = "RUNNING"
  2691. mqtt_client._was_running = True
  2692. mqtt_client._completion_triggered = False
  2693. mqtt_client.state.layer_num = 30
  2694. mqtt_client.state.last_loaded_tray = 2
  2695. mqtt_client.state.tray_change_log = [(2, 0)]
  2696. mqtt_client.state.tray_now = 2
  2697. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2698. assert mqtt_client.state.tray_change_log == [(2, 0)]
  2699. def test_multiple_tray_changes(self, mqtt_client):
  2700. """Multiple tray changes create a full history."""
  2701. mqtt_client.state.state = "RUNNING"
  2702. mqtt_client._was_running = True
  2703. mqtt_client._completion_triggered = False
  2704. mqtt_client.state.last_loaded_tray = 0
  2705. mqtt_client.state.tray_change_log = [(0, 0)]
  2706. for tray, layer in [(1, 50), (3, 120), (0, 200)]:
  2707. mqtt_client.state.tray_now = tray
  2708. mqtt_client.state.layer_num = layer
  2709. self._record_if_change(mqtt_client, tray)
  2710. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50), (3, 120), (0, 200)]
  2711. class TestDeveloperModeDetection:
  2712. """Tests for developer LAN mode detection from MQTT 'fun' field."""
  2713. @pytest.fixture
  2714. def mqtt_client(self):
  2715. """Create a BambuMQTTClient instance for testing."""
  2716. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2717. client = BambuMQTTClient(
  2718. ip_address="192.168.1.100",
  2719. serial_number="TEST123",
  2720. access_code="12345678",
  2721. )
  2722. return client
  2723. def test_developer_mode_initially_none(self, mqtt_client):
  2724. """Verify developer_mode starts as None (unknown)."""
  2725. assert mqtt_client.state.developer_mode is None
  2726. def test_developer_mode_on_when_bit_clear(self, mqtt_client):
  2727. """Verify developer_mode is True when bit 0x20000000 is clear."""
  2728. # Bit 29 clear in lower 32 bits = developer mode ON
  2729. payload = {
  2730. "print": {
  2731. "gcode_state": "IDLE",
  2732. "fun": "1C8187FF9CFF",
  2733. }
  2734. }
  2735. mqtt_client._process_message(payload)
  2736. assert mqtt_client.state.developer_mode is True
  2737. def test_developer_mode_off_when_bit_set(self, mqtt_client):
  2738. """Verify developer_mode is False when bit 0x20000000 is set."""
  2739. # Bit 29 set in lower 32 bits = developer mode OFF (encryption required)
  2740. payload = {
  2741. "print": {
  2742. "gcode_state": "IDLE",
  2743. "fun": "1C81A7FF9CFF",
  2744. }
  2745. }
  2746. mqtt_client._process_message(payload)
  2747. assert mqtt_client.state.developer_mode is False
  2748. def test_developer_mode_exact_bit_check(self, mqtt_client):
  2749. """Verify only bit 0x20000000 matters, not other bits."""
  2750. # 0x20000000 in hex = bit 29. Set ONLY that bit.
  2751. payload = {
  2752. "print": {
  2753. "gcode_state": "IDLE",
  2754. "fun": "000020000000",
  2755. }
  2756. }
  2757. mqtt_client._process_message(payload)
  2758. assert mqtt_client.state.developer_mode is False
  2759. # All zeros = all bits clear = developer mode ON
  2760. payload["print"]["fun"] = "000000000000"
  2761. mqtt_client._process_message(payload)
  2762. assert mqtt_client.state.developer_mode is True
  2763. def test_developer_mode_invalid_fun_ignored(self, mqtt_client):
  2764. """Verify invalid fun values don't crash or change state."""
  2765. mqtt_client.state.developer_mode = True
  2766. payload = {
  2767. "print": {
  2768. "gcode_state": "IDLE",
  2769. "fun": "not_a_hex_value",
  2770. }
  2771. }
  2772. mqtt_client._process_message(payload)
  2773. # Should remain unchanged
  2774. assert mqtt_client.state.developer_mode is True
  2775. def test_developer_mode_missing_fun_preserves_state(self, mqtt_client):
  2776. """Verify messages without fun field don't reset developer_mode."""
  2777. mqtt_client.state.developer_mode = False
  2778. payload = {
  2779. "print": {
  2780. "gcode_state": "RUNNING",
  2781. "mc_percent": 50,
  2782. }
  2783. }
  2784. mqtt_client._process_message(payload)
  2785. assert mqtt_client.state.developer_mode is False
  2786. def test_developer_mode_persists_across_messages(self, mqtt_client):
  2787. """Verify developer_mode set by fun persists across messages without fun."""
  2788. # First message sets developer_mode
  2789. mqtt_client._process_message(
  2790. {
  2791. "print": {
  2792. "gcode_state": "IDLE",
  2793. "fun": "3EC1AFFF9CFF",
  2794. }
  2795. }
  2796. )
  2797. assert mqtt_client.state.developer_mode is False
  2798. # Subsequent messages without fun don't change it
  2799. for _ in range(3):
  2800. mqtt_client._process_message(
  2801. {
  2802. "print": {
  2803. "gcode_state": "RUNNING",
  2804. "mc_percent": 50,
  2805. }
  2806. }
  2807. )
  2808. assert mqtt_client.state.developer_mode is False
  2809. class TestDeveloperModeProbeTimeout:
  2810. """Tests for developer mode probe timeout, retry, and forced reconnect (#887).
  2811. When a printer's MQTT session is half-broken (sends status but ignores
  2812. commands), the developer mode probe gets no response. The timeout logic
  2813. retries once, then force-closes the socket on the second failure.
  2814. """
  2815. @pytest.fixture
  2816. def mqtt_client(self):
  2817. import time
  2818. from unittest.mock import MagicMock
  2819. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2820. client = BambuMQTTClient(
  2821. ip_address="192.168.1.100",
  2822. serial_number="TEST123",
  2823. access_code="12345678",
  2824. )
  2825. # Simulate connected state with a mock MQTT client
  2826. client.state.connected = True
  2827. mock_paho = MagicMock()
  2828. mock_paho.socket.return_value = MagicMock()
  2829. client._client = mock_paho
  2830. # Set connect time in the past so the 5s probe delay is satisfied
  2831. client._connect_time = time.monotonic() - 10.0
  2832. return client
  2833. def _make_pushall_data(self):
  2834. """Create a print data dict with >30 keys (triggers probe) and no 'fun' field."""
  2835. return {f"key_{i}": i for i in range(35)}
  2836. def test_first_timeout_allows_retry(self, mqtt_client):
  2837. """After first probe timeout, _dev_mode_probed resets to allow retry."""
  2838. import time
  2839. data = self._make_pushall_data()
  2840. # First pushall triggers the probe
  2841. mqtt_client._update_state(data)
  2842. assert mqtt_client._dev_mode_probed is True
  2843. assert mqtt_client._dev_mode_probe_seq is not None
  2844. assert mqtt_client.state.developer_mode is None
  2845. # Simulate 11 seconds passing
  2846. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  2847. # Next status message detects the timeout
  2848. mqtt_client._update_state(data)
  2849. assert mqtt_client._dev_mode_probe_failures == 1
  2850. assert mqtt_client._dev_mode_probe_seq is None
  2851. # Should allow retry on next full message
  2852. assert mqtt_client._dev_mode_probed is False
  2853. # Connection should NOT be force-closed after 1 failure
  2854. assert mqtt_client.state.connected is True
  2855. def test_second_timeout_forces_reconnect(self, mqtt_client):
  2856. """After two consecutive probe timeouts, force-close the socket.
  2857. Probe timeout detection runs from paho's network thread (no asyncio
  2858. loop), so force_reconnect_stale_session routes through socket-close
  2859. rather than hard-reset (loop_stop from inside the loop deadlocks)."""
  2860. import time
  2861. data = self._make_pushall_data()
  2862. state_change_called = []
  2863. mqtt_client.on_state_change = lambda s: state_change_called.append(True)
  2864. # First probe + timeout
  2865. mqtt_client._update_state(data)
  2866. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  2867. mqtt_client._update_state(data)
  2868. assert mqtt_client._dev_mode_probe_failures == 1
  2869. # Second probe (retry) + timeout
  2870. mqtt_client._update_state(data) # triggers new probe
  2871. assert mqtt_client._dev_mode_probed is True
  2872. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  2873. mqtt_client._update_state(data) # detects second timeout
  2874. assert mqtt_client._dev_mode_probe_failures == 2
  2875. assert mqtt_client.state.connected is False
  2876. assert mqtt_client._stale_reconnecting is True
  2877. # Sync test → no running loop → socket-close fallback path
  2878. mqtt_client._client.socket().close.assert_called()
  2879. assert len(state_change_called) > 0
  2880. def test_successful_probe_resets_failure_counter(self, mqtt_client):
  2881. """A probe response after a previous failure resets the counter."""
  2882. import time
  2883. data = self._make_pushall_data()
  2884. # First probe + timeout → failure=1
  2885. mqtt_client._update_state(data)
  2886. seq = mqtt_client._dev_mode_probe_seq
  2887. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  2888. mqtt_client._update_state(data)
  2889. assert mqtt_client._dev_mode_probe_failures == 1
  2890. # Retry probe
  2891. mqtt_client._update_state(data)
  2892. new_seq = mqtt_client._dev_mode_probe_seq
  2893. assert new_seq is not None
  2894. assert new_seq != seq
  2895. # Simulate successful response
  2896. mqtt_client._handle_dev_mode_probe_response(
  2897. {
  2898. "command": "ams_filament_setting",
  2899. "sequence_id": new_seq,
  2900. "result": "success",
  2901. }
  2902. )
  2903. assert mqtt_client._dev_mode_probe_failures == 0
  2904. assert mqtt_client.state.developer_mode is True
  2905. assert mqtt_client._dev_mode_probe_seq is None
  2906. def test_no_timeout_when_probe_not_sent(self, mqtt_client):
  2907. """The timeout branch is only entered when a probe is pending."""
  2908. # No probe sent — _dev_mode_probed is False, _dev_mode_probe_seq is None
  2909. data = {"gcode_state": "IDLE", "mc_percent": 0} # < 30 keys
  2910. mqtt_client._update_state(data)
  2911. assert mqtt_client._dev_mode_probe_failures == 0
  2912. def test_on_connect_resets_probe_state_but_preserves_developer_mode(self, mqtt_client):
  2913. """_on_connect resets probe tracking but preserves cached developer_mode."""
  2914. import time
  2915. mqtt_client._dev_mode_probed = True
  2916. mqtt_client._dev_mode_probe_seq = "42"
  2917. mqtt_client._dev_mode_probe_time = time.monotonic()
  2918. mqtt_client._dev_mode_probe_failures = 2
  2919. mqtt_client.state.developer_mode = True
  2920. # subscribe() must return (result, mid) tuple
  2921. mqtt_client._client.subscribe.return_value = (0, 1)
  2922. mqtt_client._on_connect(mqtt_client._client, None, None, 0)
  2923. # developer_mode is preserved across reconnects (#887)
  2924. assert mqtt_client.state.developer_mode is True
  2925. assert mqtt_client._dev_mode_probed is False
  2926. assert mqtt_client._dev_mode_probe_seq is None
  2927. assert mqtt_client._dev_mode_probe_time == 0.0
  2928. assert mqtt_client._dev_mode_probe_failures == 0
  2929. assert mqtt_client._connect_time > 0
  2930. def test_probe_deferred_when_connect_too_recent(self, mqtt_client):
  2931. """Probe is deferred if less than 5s have passed since _on_connect."""
  2932. import time
  2933. data = self._make_pushall_data()
  2934. # Set connect time to 1 second ago — too recent for probe
  2935. mqtt_client._connect_time = time.monotonic() - 1.0
  2936. mqtt_client._update_state(data)
  2937. # Pushall seen, so needs_probe is set, but probe NOT fired yet
  2938. assert mqtt_client._dev_mode_needs_probe is True
  2939. assert mqtt_client._dev_mode_probed is False
  2940. assert mqtt_client._dev_mode_probe_seq is None
  2941. def test_probe_fires_after_delay(self, mqtt_client):
  2942. """Probe fires once 5s have passed since _on_connect."""
  2943. import time
  2944. data = self._make_pushall_data()
  2945. # Set connect time to 6 seconds ago — delay satisfied
  2946. mqtt_client._connect_time = time.monotonic() - 6.0
  2947. mqtt_client._update_state(data)
  2948. # Probe should have fired
  2949. assert mqtt_client._dev_mode_needs_probe is True
  2950. assert mqtt_client._dev_mode_probed is True
  2951. assert mqtt_client._dev_mode_probe_seq is not None
  2952. def test_probe_fires_on_incremental_after_delay(self, mqtt_client):
  2953. """After seeing a pushall within 5s, probe fires on later incremental message."""
  2954. import time
  2955. pushall_data = self._make_pushall_data()
  2956. incremental_data = {"gcode_state": "IDLE", "mc_percent": 0} # < 30 keys
  2957. # Pushall arrives 1s after connect — too early for probe
  2958. mqtt_client._connect_time = time.monotonic() - 1.0
  2959. mqtt_client._update_state(pushall_data)
  2960. assert mqtt_client._dev_mode_needs_probe is True
  2961. assert mqtt_client._dev_mode_probed is False
  2962. # 5s later, an incremental update arrives — probe fires now
  2963. mqtt_client._connect_time = time.monotonic() - 6.0
  2964. mqtt_client._update_state(incremental_data)
  2965. assert mqtt_client._dev_mode_probed is True
  2966. assert mqtt_client._dev_mode_probe_seq is not None
  2967. def test_no_reprobe_when_developer_mode_cached(self, mqtt_client):
  2968. """Auto-reconnect preserves developer_mode, skipping reprobe."""
  2969. import time
  2970. data = self._make_pushall_data()
  2971. # Simulate known developer_mode from previous connection
  2972. mqtt_client.state.developer_mode = True
  2973. mqtt_client._connect_time = time.monotonic() - 10.0
  2974. mqtt_client._update_state(data)
  2975. # Should NOT probe — developer_mode is already known
  2976. assert mqtt_client._dev_mode_needs_probe is False
  2977. assert mqtt_client._dev_mode_probed is False
  2978. assert mqtt_client._dev_mode_probe_seq is None
  2979. assert mqtt_client.state.developer_mode is True
  2980. def test_on_connect_resets_needs_probe(self, mqtt_client):
  2981. """_on_connect resets _dev_mode_needs_probe for a clean start."""
  2982. mqtt_client._dev_mode_needs_probe = True
  2983. mqtt_client._client.subscribe.return_value = (0, 1)
  2984. mqtt_client._on_connect(mqtt_client._client, None, None, 0)
  2985. assert mqtt_client._dev_mode_needs_probe is False
  2986. class TestVtTrayNormalization:
  2987. """Tests for vt_tray dict→list normalization in _update_state.
  2988. MQTT sends vt_tray as a dict for single-slot printers, but all consumers
  2989. expect a list. _update_state must normalize it before any callback can
  2990. read raw_data, because the dev-mode probe may release the GIL and let
  2991. the event loop read the partially-updated state.
  2992. """
  2993. @pytest.fixture
  2994. def mqtt_client(self):
  2995. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2996. client = BambuMQTTClient(
  2997. ip_address="192.168.1.100",
  2998. serial_number="TEST123",
  2999. access_code="12345678",
  3000. )
  3001. return client
  3002. def test_vt_tray_dict_normalized_in_update_state(self, mqtt_client):
  3003. """Verify _update_state wraps a raw vt_tray dict into a list."""
  3004. vt_dict = {
  3005. "id": "254",
  3006. "tray_color": "FF0000",
  3007. "tray_type": "PLA",
  3008. "tag_uid": "0000000000000000",
  3009. "tray_uuid": "00000000000000000000000000000000",
  3010. }
  3011. data = {"gcode_state": "IDLE", "vt_tray": vt_dict}
  3012. mqtt_client._update_state(data)
  3013. stored = mqtt_client.state.raw_data.get("vt_tray")
  3014. assert isinstance(stored, list)
  3015. assert len(stored) == 1
  3016. assert stored[0]["tray_color"] == "FF0000"
  3017. def test_vt_tray_list_unchanged_in_update_state(self, mqtt_client):
  3018. """Verify _update_state keeps an already-list vt_tray unchanged."""
  3019. vt_list = [
  3020. {"id": "254", "tray_type": "PLA"},
  3021. {"id": "255", "tray_type": "PETG"},
  3022. ]
  3023. data = {"gcode_state": "IDLE", "vt_tray": vt_list}
  3024. mqtt_client._update_state(data)
  3025. stored = mqtt_client.state.raw_data.get("vt_tray")
  3026. assert isinstance(stored, list)
  3027. assert len(stored) == 2
  3028. def test_preserved_vt_tray_restored_before_probe(self, mqtt_client):
  3029. """Verify preserved vt_tray is restored before dev-mode probe runs.
  3030. On the first message, the incremental handler wraps vt_tray into a list
  3031. and stores it. _update_state then replaces raw_data with the full data
  3032. dict, but must restore preserved fields BEFORE the probe publishes
  3033. (which can release the GIL).
  3034. """
  3035. # Simulate: incremental handler already stored a wrapped list
  3036. mqtt_client.state.raw_data = {
  3037. "vt_tray": [{"id": "254", "tray_type": "PLA", "tray_color": "00FF00"}],
  3038. }
  3039. # Now _update_state runs with new data that has vt_tray as dict
  3040. new_data = {
  3041. "gcode_state": "IDLE",
  3042. "vt_tray": {"id": "254", "tray_type": "PETG", "tray_color": "FF0000"},
  3043. }
  3044. mqtt_client._update_state(new_data)
  3045. # The preserved list (PLA/green) should take priority over new data
  3046. stored = mqtt_client.state.raw_data["vt_tray"]
  3047. assert isinstance(stored, list)
  3048. assert stored[0]["tray_type"] == "PLA"
  3049. assert stored[0]["tray_color"] == "00FF00"
  3050. def test_first_message_vt_tray_dict_becomes_list(self, mqtt_client):
  3051. """Verify on the very first message, vt_tray dict is still a list.
  3052. When there's no previously preserved data, the normalized dict should
  3053. remain as a list in raw_data.
  3054. """
  3055. # raw_data starts empty — no preserved vt_tray
  3056. mqtt_client.state.raw_data = {}
  3057. data = {
  3058. "gcode_state": "IDLE",
  3059. "vt_tray": {"id": "254", "tray_type": "ABS"},
  3060. }
  3061. mqtt_client._update_state(data)
  3062. stored = mqtt_client.state.raw_data["vt_tray"]
  3063. assert isinstance(stored, list)
  3064. assert stored[0]["tray_type"] == "ABS"
  3065. class TestSendDryingCommand:
  3066. """Tests for send_drying_command MQTT payload construction."""
  3067. @pytest.fixture
  3068. def mqtt_client(self):
  3069. """Create a BambuMQTTClient with a mock MQTT client."""
  3070. from unittest.mock import MagicMock
  3071. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3072. client = BambuMQTTClient(
  3073. ip_address="192.168.1.100",
  3074. serial_number="TEST123",
  3075. access_code="12345678",
  3076. )
  3077. client._client = MagicMock()
  3078. return client
  3079. def test_rotate_tray_false_by_default(self, mqtt_client):
  3080. """Verify rotate_tray defaults to False in the MQTT payload."""
  3081. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  3082. call_args = mqtt_client._client.publish.call_args
  3083. payload = json.loads(call_args[0][1])
  3084. assert payload["print"]["rotate_tray"] is False
  3085. def test_rotate_tray_true_when_enabled(self, mqtt_client):
  3086. """Verify rotate_tray is True when explicitly enabled."""
  3087. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA", rotate_tray=True)
  3088. call_args = mqtt_client._client.publish.call_args
  3089. payload = json.loads(call_args[0][1])
  3090. assert payload["print"]["rotate_tray"] is True
  3091. def test_rotate_tray_false_on_stop(self, mqtt_client):
  3092. """Verify rotate_tray is False when stopping drying (mode=0)."""
  3093. mqtt_client.send_drying_command(ams_id=0, temp=0, duration=0, mode=0)
  3094. call_args = mqtt_client._client.publish.call_args
  3095. payload = json.loads(call_args[0][1])
  3096. assert payload["print"]["rotate_tray"] is False
  3097. def test_all_required_fields_present(self, mqtt_client):
  3098. """Verify all required MQTT fields are present in the drying command."""
  3099. mqtt_client.send_drying_command(ams_id=128, temp=75, duration=8, mode=1, filament="ABS", rotate_tray=True)
  3100. call_args = mqtt_client._client.publish.call_args
  3101. payload = json.loads(call_args[0][1])
  3102. cmd = payload["print"]
  3103. assert cmd["command"] == "ams_filament_drying"
  3104. assert cmd["ams_id"] == 128
  3105. assert cmd["temp"] == 75
  3106. assert cmd["duration"] == 8
  3107. assert cmd["mode"] == 1
  3108. assert cmd["rotate_tray"] is True
  3109. assert cmd["filament"] == "ABS"
  3110. assert cmd["cooling_temp"] == 20
  3111. assert cmd["humidity"] == 0
  3112. assert cmd["close_power_conflict"] is False
  3113. assert "sequence_id" in cmd
  3114. def test_publishes_with_qos_1(self, mqtt_client):
  3115. """Verify drying commands are published with QoS 1."""
  3116. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4)
  3117. call_args = mqtt_client._client.publish.call_args
  3118. # qos may be positional arg [2] or keyword
  3119. qos = call_args.kwargs.get("qos", call_args[0][2] if len(call_args[0]) > 2 else None)
  3120. assert qos == 1
  3121. def test_start_caches_target_for_badge(self, mqtt_client):
  3122. """mode=1 send populates _drying_targets so the badge can render it."""
  3123. mqtt_client.send_drying_command(ams_id=2, temp=65, duration=12, mode=1, filament="PETG")
  3124. assert mqtt_client._drying_targets[2] == {"filament": "PETG", "temp": 65}
  3125. def test_start_overwrites_prior_target_for_same_ams(self, mqtt_client):
  3126. """A second start on the same AMS replaces the cached target."""
  3127. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  3128. mqtt_client.send_drying_command(ams_id=0, temp=70, duration=6, mode=1, filament="ABS")
  3129. assert mqtt_client._drying_targets[0] == {"filament": "ABS", "temp": 70}
  3130. def test_stop_clears_target(self, mqtt_client):
  3131. """mode=0 send drops the cache so the badge stops showing the target."""
  3132. mqtt_client.send_drying_command(ams_id=1, temp=55, duration=4, mode=1, filament="PLA")
  3133. assert 1 in mqtt_client._drying_targets
  3134. mqtt_client.send_drying_command(ams_id=1, temp=0, duration=0, mode=0)
  3135. assert 1 not in mqtt_client._drying_targets
  3136. def test_targets_isolated_per_ams_id(self, mqtt_client):
  3137. """Stopping one AMS doesn't affect another AMS's cached target."""
  3138. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  3139. mqtt_client.send_drying_command(ams_id=128, temp=80, duration=6, mode=1, filament="PA-CF")
  3140. mqtt_client.send_drying_command(ams_id=0, temp=0, duration=0, mode=0)
  3141. assert 0 not in mqtt_client._drying_targets
  3142. assert mqtt_client._drying_targets[128] == {"filament": "PA-CF", "temp": 80}
  3143. class TestStartPrintAmsMapping:
  3144. """Tests for ams_mapping/ams_mapping2 construction in start_print().
  3145. BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  3146. ams_mapping and puts the real external spool info only in ams_mapping2.
  3147. Passing raw 254/255 in the flat array causes H2D firmware to fail
  3148. with 0700_8012 "Failed to get AMS mapping table".
  3149. """
  3150. @pytest.fixture
  3151. def mqtt_client(self):
  3152. from unittest.mock import MagicMock
  3153. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3154. client = BambuMQTTClient(
  3155. ip_address="192.168.1.100",
  3156. serial_number="TEST123",
  3157. access_code="12345678",
  3158. )
  3159. client._client = MagicMock()
  3160. client.state.connected = True
  3161. return client
  3162. def _get_published_command(self, mqtt_client):
  3163. """Extract the parsed print command from the last publish call."""
  3164. call_args = mqtt_client._client.publish.call_args
  3165. return json.loads(call_args[0][1])["print"]
  3166. def test_regular_ams_trays_preserved_in_flat_mapping(self, mqtt_client):
  3167. """Regular AMS tray IDs pass through unchanged in flat ams_mapping."""
  3168. mqtt_client.start_print("test.3mf", ams_mapping=[0, 5, 11])
  3169. cmd = self._get_published_command(mqtt_client)
  3170. assert cmd["ams_mapping"] == [0, 5, 11]
  3171. assert cmd["ams_mapping2"] == [
  3172. {"ams_id": 0, "slot_id": 0},
  3173. {"ams_id": 1, "slot_id": 1},
  3174. {"ams_id": 2, "slot_id": 3},
  3175. ]
  3176. def test_unmapped_slots(self, mqtt_client):
  3177. """Unmapped slots (-1) produce -1 in flat and 0xFF/0xFF in mapping2."""
  3178. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1])
  3179. cmd = self._get_published_command(mqtt_client)
  3180. assert cmd["ams_mapping"] == [-1, -1]
  3181. assert cmd["ams_mapping2"] == [
  3182. {"ams_id": 255, "slot_id": 255},
  3183. {"ams_id": 255, "slot_id": 255},
  3184. ]
  3185. def test_external_main_nozzle_becomes_minus_one_in_flat(self, mqtt_client):
  3186. """Virtual tray 255 (main nozzle) must be -1 in flat mapping."""
  3187. mqtt_client.start_print("test.3mf", ams_mapping=[255])
  3188. cmd = self._get_published_command(mqtt_client)
  3189. assert cmd["ams_mapping"] == [-1]
  3190. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  3191. def test_single_nozzle_external_spool_uses_main_id(self, mqtt_client):
  3192. """Single-nozzle external spool (254) maps to ams_id=255 (VIRTUAL_TRAY_MAIN_ID).
  3193. Firmware reports tray_now=254 for external spool, but the print command
  3194. must use ams_id=255 in ams_mapping2. Sending 254 causes the firmware to
  3195. target AMS tray 0 instead of external spool (07FF_8012 error).
  3196. """
  3197. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  3198. cmd = self._get_published_command(mqtt_client)
  3199. assert cmd["ams_mapping"] == [-1]
  3200. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  3201. def test_h2d_external_spool_mixed_with_ams(self, mqtt_client):
  3202. """H2D scenario: AMS trays + unmapped + external deputy nozzle."""
  3203. # Reproduces the exact scenario from issue #797:
  3204. # 5-slot 3MF, only slot 5 assigned to external deputy nozzle (254)
  3205. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1, -1, -1, 255])
  3206. cmd = self._get_published_command(mqtt_client)
  3207. # Flat mapping: all -1 (external converted, unmapped stay -1)
  3208. assert cmd["ams_mapping"] == [-1, -1, -1, -1, -1]
  3209. # Detailed mapping: unmapped slots use 0xFF, external uses real ams_id
  3210. assert cmd["ams_mapping2"] == [
  3211. {"ams_id": 255, "slot_id": 255},
  3212. {"ams_id": 255, "slot_id": 255},
  3213. {"ams_id": 255, "slot_id": 255},
  3214. {"ams_id": 255, "slot_id": 255},
  3215. {"ams_id": 255, "slot_id": 0},
  3216. ]
  3217. def test_ams_ht_trays_preserved_in_flat_mapping(self, mqtt_client):
  3218. """AMS-HT tray IDs (>=128) pass through in flat mapping."""
  3219. mqtt_client.start_print("test.3mf", ams_mapping=[128, 131])
  3220. cmd = self._get_published_command(mqtt_client)
  3221. assert cmd["ams_mapping"] == [128, 131]
  3222. assert cmd["ams_mapping2"] == [
  3223. {"ams_id": 128, "slot_id": 0},
  3224. {"ams_id": 131, "slot_id": 0},
  3225. ]
  3226. def test_non_h2d_both_external_maps_to_main_id(self, mqtt_client):
  3227. """Non-H2D: both 254 and 255 map to ams_id=255 (single nozzle)."""
  3228. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  3229. cmd = self._get_published_command(mqtt_client)
  3230. assert cmd["ams_mapping"] == [-1, -1]
  3231. assert cmd["ams_mapping2"] == [
  3232. {"ams_id": 255, "slot_id": 0},
  3233. {"ams_id": 255, "slot_id": 0},
  3234. ]
  3235. def test_h2d_external_preserves_deputy_id(self, mqtt_client):
  3236. """H2D dual-nozzle: 254 (deputy) stays 254, 255 (main) stays 255."""
  3237. mqtt_client.model = "H2D"
  3238. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  3239. cmd = self._get_published_command(mqtt_client)
  3240. assert cmd["ams_mapping"] == [-1, -1]
  3241. assert cmd["ams_mapping2"] == [
  3242. {"ams_id": 254, "slot_id": 0},
  3243. {"ams_id": 255, "slot_id": 0},
  3244. ]
  3245. def test_h2d_single_external_deputy(self, mqtt_client):
  3246. """H2D: single external spool on deputy nozzle (254) keeps ams_id=254."""
  3247. mqtt_client.model = "H2D Pro"
  3248. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  3249. cmd = self._get_published_command(mqtt_client)
  3250. assert cmd["ams_mapping"] == [-1]
  3251. assert cmd["ams_mapping2"] == [{"ams_id": 254, "slot_id": 0}]
  3252. def test_external_spool_only_sets_use_ams_false(self, mqtt_client):
  3253. """Single external spool on non-H2D printer sets use_ams=False."""
  3254. mqtt_client.start_print("test.3mf", ams_mapping=[254], use_ams=True)
  3255. cmd = self._get_published_command(mqtt_client)
  3256. assert cmd["use_ams"] is False
  3257. def test_all_unmapped_sets_use_ams_false(self, mqtt_client):
  3258. """All unmapped slots on non-H2D printer sets use_ams=False."""
  3259. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1], use_ams=True)
  3260. cmd = self._get_published_command(mqtt_client)
  3261. assert cmd["use_ams"] is False
  3262. def test_mixed_ams_and_external_keeps_use_ams_true(self, mqtt_client):
  3263. """AMS tray + external spool keeps use_ams=True."""
  3264. mqtt_client.start_print("test.3mf", ams_mapping=[0, 254], use_ams=True)
  3265. cmd = self._get_published_command(mqtt_client)
  3266. assert cmd["use_ams"] is True
  3267. def test_h2d_both_external_keeps_use_ams_true(self, mqtt_client):
  3268. """H2D with both external spools keeps use_ams=True (nozzle routing)."""
  3269. mqtt_client.model = "H2D"
  3270. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255], use_ams=True)
  3271. cmd = self._get_published_command(mqtt_client)
  3272. assert cmd["use_ams"] is True
  3273. def test_empty_ams_mapping_keeps_use_ams_true(self, mqtt_client):
  3274. """Empty ams_mapping list does not override use_ams."""
  3275. mqtt_client.start_print("test.3mf", ams_mapping=[], use_ams=True)
  3276. cmd = self._get_published_command(mqtt_client)
  3277. assert cmd["use_ams"] is True
  3278. def test_no_ams_mapping_omits_fields(self, mqtt_client):
  3279. """When ams_mapping is None, neither field is in the command."""
  3280. mqtt_client.start_print("test.3mf", ams_mapping=None)
  3281. cmd = self._get_published_command(mqtt_client)
  3282. assert "ams_mapping" not in cmd
  3283. assert "ams_mapping2" not in cmd
  3284. def test_x2d_external_preserves_deputy_id(self, mqtt_client):
  3285. """X2D dual-nozzle (#988): 254 (deputy) stays 254, like H2D family.
  3286. X2D launched April 2026 and shares the H2D-style dual-extruder
  3287. firmware convention — external spool on the deputy (left) nozzle
  3288. is addressed as ams_id=254, not coerced to 255.
  3289. """
  3290. mqtt_client.model = "X2D"
  3291. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  3292. cmd = self._get_published_command(mqtt_client)
  3293. assert cmd["ams_mapping"] == [-1, -1]
  3294. assert cmd["ams_mapping2"] == [
  3295. {"ams_id": 254, "slot_id": 0},
  3296. {"ams_id": 255, "slot_id": 0},
  3297. ]
  3298. def test_x2d_uses_boolean_format_for_calibration_fields(self, mqtt_client):
  3299. """X2D sends calibration fields as JSON booleans, like every model (#1478).
  3300. An earlier revision integer-encoded these for the H2 family on the
  3301. belief that H2 firmware required 0/1. A BambuStudio request-topic
  3302. capture from a real H2D disproved it — BambuStudio sends plain
  3303. booleans — so X2D follows the same boolean format.
  3304. """
  3305. mqtt_client.model = "X2D"
  3306. mqtt_client.start_print(
  3307. "test.3mf",
  3308. timelapse=True,
  3309. bed_levelling=False,
  3310. flow_cali=True,
  3311. vibration_cali=False,
  3312. layer_inspect=True,
  3313. )
  3314. cmd = self._get_published_command(mqtt_client)
  3315. assert cmd["timelapse"] is True
  3316. assert cmd["bed_leveling"] is False
  3317. assert cmd["flow_cali"] is True
  3318. assert cmd["vibration_cali"] is False
  3319. assert cmd["layer_inspect"] is True
  3320. # flow_cali on → extrude_cali_flag must request the calibration pass.
  3321. assert cmd["extrude_cali_flag"] == 1
  3322. def test_p2s_uses_boolean_format(self, mqtt_client):
  3323. """P2S sends calibration fields as JSON booleans (single-nozzle, like X1C/A1/P1)."""
  3324. mqtt_client.model = "P2S"
  3325. mqtt_client.start_print("test.3mf", timelapse=True, flow_cali=False)
  3326. cmd = self._get_published_command(mqtt_client)
  3327. assert cmd["timelapse"] is True
  3328. assert cmd["flow_cali"] is False
  3329. # flow_cali off → extrude_cali_flag=0 (firmware actually skips the
  3330. # pre-print calibration stage). #1721 test on H2D 01.x showed `2`
  3331. # didn't suppress stage 8 ("Calibrating dynamic flow") despite the
  3332. # earlier "skip and reuse stored PA" reading; `0` does — verified
  3333. # live against the stg queue.
  3334. assert cmd["extrude_cali_flag"] == 0
  3335. def test_h2s_single_external_spool_uses_main_id(self, mqtt_client):
  3336. """H2S is single-nozzle (#1386): external spool (254) → ams_id=255.
  3337. H2S shares serial prefix "094" and the H-family firmware-format
  3338. quirks with H2D, but it has a single extruder (nozzle_count=1
  3339. confirmed across 9+ support bundles). Routing the deputy-nozzle
  3340. sentinel (254) through to firmware on a single-nozzle printer
  3341. causes 07FF_8012 "Failed to get AMS mapping table" — exactly the
  3342. symptom reporter krootstijn hit when printing without an AMS.
  3343. """
  3344. mqtt_client.model = "H2S"
  3345. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  3346. cmd = self._get_published_command(mqtt_client)
  3347. assert cmd["ams_mapping"] == [-1]
  3348. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  3349. def test_h2s_no_ams_forces_use_ams_false(self, mqtt_client):
  3350. """H2S with only external spool must drop into the use_ams=False
  3351. fallback, like P1S/P1P. The dual-nozzle bypass kept this path
  3352. unreachable before #1386 — the firmware then rejected the print
  3353. with 07FF_8012 because there was no AMS mapping table.
  3354. """
  3355. mqtt_client.model = "H2S"
  3356. mqtt_client.start_print("test.3mf", ams_mapping=[254], use_ams=True)
  3357. cmd = self._get_published_command(mqtt_client)
  3358. assert cmd["use_ams"] is False
  3359. def test_h2s_uses_boolean_format_for_calibration_fields(self, mqtt_client):
  3360. """H2S sends calibration fields as JSON booleans (#1478).
  3361. The H2S was previously integer-encoded as part of the H2 family. That
  3362. made it accept the print command but silently skip flow-dynamics
  3363. calibration — the reporter saw poor corner quality from a stale K
  3364. value. BambuStudio sends booleans for these fields and pairs flow_cali
  3365. with extrude_cali_flag=1 to actually run the calibration pass.
  3366. """
  3367. mqtt_client.model = "H2S"
  3368. mqtt_client.start_print(
  3369. "test.3mf",
  3370. timelapse=True,
  3371. bed_levelling=False,
  3372. flow_cali=True,
  3373. vibration_cali=False,
  3374. layer_inspect=True,
  3375. )
  3376. cmd = self._get_published_command(mqtt_client)
  3377. assert cmd["timelapse"] is True
  3378. assert cmd["bed_leveling"] is False
  3379. assert cmd["flow_cali"] is True
  3380. assert cmd["vibration_cali"] is False
  3381. assert cmd["layer_inspect"] is True
  3382. # flow_cali on → extrude_cali_flag=1 so the printer runs the
  3383. # flow-dynamics calibration instead of reusing the stored PA value.
  3384. assert cmd["extrude_cali_flag"] == 1
  3385. def test_nozzle_offset_cali_default_is_skip(self, mqtt_client):
  3386. """Default `nozzle_offset_cali=False` → wire value `0` (skip).
  3387. #1721 H2D 01.x test: `2` ("skip") didn't actually suppress stage 39
  3388. ("Nozzle offset calibration") — the stage stayed in the `stg` queue
  3389. and ran at print start. `0` does suppress it (verified live). Matches
  3390. what a BambuStudio Send-dialog echo on the same firmware shows.
  3391. """
  3392. mqtt_client.model = "P1S"
  3393. mqtt_client.start_print("test.3mf")
  3394. cmd = self._get_published_command(mqtt_client)
  3395. assert cmd["nozzle_offset_cali"] == 0
  3396. def test_nozzle_offset_cali_ignored_on_single_nozzle(self, mqtt_client):
  3397. """Single-nozzle printer: `nozzle_offset_cali=True` is silently dropped.
  3398. H2S is in the H2 firmware family but single-nozzle. The toggle has
  3399. no physical meaning on single-nozzle machines and the UI gates it
  3400. behind `nozzle_count==2`. Even if a stale queue item from when the
  3401. printer was misidentified as dual carries the flag, the MQTT layer
  3402. must downgrade it so firmware never tries to calibrate a head it
  3403. doesn't have (#1682). `0` is the actually-honoured skip value
  3404. post-#1721; old `2` left the stage in the queue.
  3405. """
  3406. mqtt_client.model = "P1S"
  3407. mqtt_client.start_print("test.3mf", nozzle_offset_cali=True)
  3408. cmd = self._get_published_command(mqtt_client)
  3409. assert cmd["nozzle_offset_cali"] == 0
  3410. def test_nozzle_offset_cali_honored_on_dual_nozzle(self, mqtt_client):
  3411. """Dual-nozzle printer (H2D): `nozzle_offset_cali=True` → wire value `1`.
  3412. H2D is in `DUAL_NOZZLE_MODELS`. The toggle controls whether the
  3413. printer runs the nozzle-offset calibration pass before the print
  3414. starts. `1`=run (#1682).
  3415. """
  3416. mqtt_client.model = "H2D"
  3417. mqtt_client.start_print("test.3mf", nozzle_offset_cali=True)
  3418. cmd = self._get_published_command(mqtt_client)
  3419. assert cmd["nozzle_offset_cali"] == 1
  3420. def test_nozzle_offset_cali_false_on_dual_nozzle(self, mqtt_client):
  3421. """Dual-nozzle printer (H2D Pro): `nozzle_offset_cali=False` → `0` (skip).
  3422. Critical for users like #1682 who run diamond nozzles and need to
  3423. keep the calibration off. The wire value flipped from `2` to `0` in
  3424. #1721 after the H2D test showed `2` didn't actually suppress.
  3425. """
  3426. mqtt_client.model = "H2D Pro"
  3427. mqtt_client.start_print("test.3mf", nozzle_offset_cali=False)
  3428. cmd = self._get_published_command(mqtt_client)
  3429. assert cmd["nozzle_offset_cali"] == 0
  3430. class TestStartPrintUniqueIdentityFields:
  3431. """Regression guard: project_id/subtask_id/task_id must be unique per submission (#1011).
  3432. Hardcoded "0" values caused third-party MQTT observers (e.g. OctoEverywhere)
  3433. to treat archive reprints as continuations of the same job and report
  3434. compounding durations on repeat replays. Each start_print call must produce
  3435. a distinct, non-zero identity triplet so the printer emits a fresh state
  3436. transition. md5 is deliberately left empty — historically firmware treats
  3437. "" as "skip validation" and we don't have the file's real digest here.
  3438. """
  3439. @pytest.fixture
  3440. def mqtt_client(self):
  3441. from unittest.mock import MagicMock
  3442. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3443. client = BambuMQTTClient(
  3444. ip_address="192.168.1.100",
  3445. serial_number="TEST123",
  3446. access_code="12345678",
  3447. )
  3448. client._client = MagicMock()
  3449. client.state.connected = True
  3450. return client
  3451. def _get_published_command(self, mqtt_client):
  3452. call_args = mqtt_client._client.publish.call_args
  3453. return json.loads(call_args[0][1])["print"]
  3454. def test_identity_fields_are_non_zero(self, mqtt_client):
  3455. mqtt_client.start_print("test.3mf")
  3456. cmd = self._get_published_command(mqtt_client)
  3457. assert cmd["project_id"] != "0"
  3458. assert cmd["subtask_id"] != "0"
  3459. assert cmd["task_id"] != "0"
  3460. def test_identity_fields_are_all_equal_per_submission(self, mqtt_client):
  3461. """All three IDs come from the same submission timestamp — Studio also
  3462. uses a single identity per submission across the three fields."""
  3463. mqtt_client.start_print("test.3mf")
  3464. cmd = self._get_published_command(mqtt_client)
  3465. assert cmd["project_id"] == cmd["subtask_id"] == cmd["task_id"]
  3466. def test_md5_stays_empty(self, mqtt_client):
  3467. """Deliberate: synthetic md5 risks activating firmware validation."""
  3468. mqtt_client.start_print("test.3mf")
  3469. cmd = self._get_published_command(mqtt_client)
  3470. assert cmd["md5"] == ""
  3471. def test_identity_fields_change_between_submissions(self, mqtt_client):
  3472. """Two successive start_print calls must produce different IDs.
  3473. Without this, the printer can't tell replays apart and reuses
  3474. gcode_start_time from the prior job.
  3475. """
  3476. mqtt_client.start_print("test.3mf")
  3477. first = self._get_published_command(mqtt_client)
  3478. time.sleep(0.002)
  3479. mqtt_client.start_print("test.3mf")
  3480. second = self._get_published_command(mqtt_client)
  3481. assert first["task_id"] != second["task_id"]
  3482. assert first["subtask_id"] != second["subtask_id"]
  3483. assert first["project_id"] != second["project_id"]
  3484. def test_submission_id_is_numeric_string(self, mqtt_client):
  3485. """ID format: digits-only string. Studio uses cloud task IDs that are
  3486. also numeric-looking strings; the DB column is VARCHAR(64) and
  3487. Bambuddy's own subtask_id parser treats '0'/'' as absent — any valid
  3488. digit string that isn't '0' is fine."""
  3489. mqtt_client.start_print("test.3mf")
  3490. cmd = self._get_published_command(mqtt_client)
  3491. assert cmd["task_id"].isdigit()
  3492. assert int(cmd["task_id"]) > 0
  3493. assert len(cmd["task_id"]) <= 64
  3494. def test_last_dispatch_subtask_id_records_the_minted_id(self, mqtt_client):
  3495. """#1485: start_print records the minted id on the client so
  3496. on_print_start can persist it on the archive before the printer
  3497. echoes subtask_id back — letting a later restart resume by id."""
  3498. assert mqtt_client.last_dispatch_subtask_id is None
  3499. mqtt_client.start_print("test.3mf")
  3500. cmd = self._get_published_command(mqtt_client)
  3501. assert mqtt_client.last_dispatch_subtask_id == cmd["subtask_id"]
  3502. def test_last_dispatch_subtask_id_updates_per_submission(self, mqtt_client):
  3503. """Each dispatch overwrites the recorded id with the new submission's."""
  3504. mqtt_client.start_print("test.3mf")
  3505. first = mqtt_client.last_dispatch_subtask_id
  3506. time.sleep(0.002)
  3507. mqtt_client.start_print("test.3mf")
  3508. assert mqtt_client.last_dispatch_subtask_id != first
  3509. assert mqtt_client.last_dispatch_subtask_id == self._get_published_command(mqtt_client)["subtask_id"]
  3510. def test_submission_id_fits_signed_int32(self, mqtt_client):
  3511. """Regression for #1042: P1S firmware clamps oversized task identity
  3512. fields to signed int32 max (2**31-1 = 2147483647). If we send raw
  3513. epoch-ms (~1.7e12), the printer sees a saturated constant on every
  3514. submission and treats fresh dispatches as continuations of the last
  3515. FAILED job — never leaves IDLE. Keep below 2**31.
  3516. """
  3517. mqtt_client.start_print("test.3mf")
  3518. cmd = self._get_published_command(mqtt_client)
  3519. assert int(cmd["task_id"]) < 2**31
  3520. assert int(cmd["project_id"]) < 2**31
  3521. assert int(cmd["subtask_id"]) < 2**31
  3522. def test_unrelated_payload_fields_untouched(self, mqtt_client):
  3523. """Regression guard: fix only touches identity fields; everything else
  3524. (sequence_id, command verb, calibration defaults, profile_id) must be
  3525. unchanged to avoid silently breaking printer behavior."""
  3526. mqtt_client.start_print("test.3mf")
  3527. cmd = self._get_published_command(mqtt_client)
  3528. assert cmd["sequence_id"] == "20000"
  3529. assert cmd["command"] == "project_file"
  3530. assert cmd["param"] == "Metadata/plate_1.gcode"
  3531. assert cmd["url"] == "ftp://test.3mf"
  3532. assert cmd["file"] == "test.3mf"
  3533. assert cmd["profile_id"] == "0"
  3534. assert cmd["cfg"] == "0"
  3535. assert cmd["subtask_name"] == "test"
  3536. class TestDeleteKProfileDualNozzleDetection:
  3537. """Regression guard: dual-nozzle detection for K-profile delete.
  3538. delete_kprofile branches on dual-nozzle status to pick the wire format.
  3539. Source of truth is the runtime `_is_dual_nozzle` flag (set from
  3540. device.extruder.info); model name is the fallback used before push
  3541. data arrives. Serial-prefix detection alone is wrong — H2S shares
  3542. prefix "094" with H2D but is single-nozzle (#1386).
  3543. """
  3544. def _make_client(self, *, serial: str = "TEST", model: str | None = None, dual_runtime: bool = False):
  3545. from unittest.mock import MagicMock
  3546. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3547. client = BambuMQTTClient(
  3548. ip_address="192.168.1.100",
  3549. serial_number=serial,
  3550. access_code="12345678",
  3551. )
  3552. client._client = MagicMock()
  3553. client.state.connected = True
  3554. client.model = model
  3555. client._is_dual_nozzle = dual_runtime
  3556. return client
  3557. def _published(self, client):
  3558. return json.loads(client._client.publish.call_args[0][1])["print"]
  3559. def test_h2d_model_uses_dual_nozzle_format(self):
  3560. client = self._make_client(serial="09400A000000001", model="H2D")
  3561. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3562. cmd = self._published(client)
  3563. # Dual-nozzle command omits setting_id.
  3564. assert "setting_id" not in cmd
  3565. assert cmd["extruder_id"] == 0
  3566. def test_x2d_model_uses_dual_nozzle_format(self):
  3567. client = self._make_client(serial="20P90A000000001", model="X2D")
  3568. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3569. cmd = self._published(client)
  3570. assert "setting_id" not in cmd
  3571. assert cmd["extruder_id"] == 0
  3572. def test_h2c_model_uses_dual_nozzle_format(self):
  3573. """Post-2026 H2C batches ship with '31B8B' prefix instead of '094' (#1105).
  3574. Model-name detection works regardless of serial prefix."""
  3575. client = self._make_client(serial="31B8BP000000001", model="H2C")
  3576. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3577. cmd = self._published(client)
  3578. assert "setting_id" not in cmd
  3579. assert cmd["extruder_id"] == 0
  3580. def test_runtime_dual_nozzle_flag_uses_dual_format(self):
  3581. """When _is_dual_nozzle is set from device.extruder.info, the model
  3582. fallback isn't needed (covers future dual-nozzle models we haven't
  3583. seen yet)."""
  3584. client = self._make_client(serial="UNKNOWN", model=None, dual_runtime=True)
  3585. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3586. cmd = self._published(client)
  3587. assert "setting_id" not in cmd
  3588. def test_h2s_uses_single_nozzle_format(self):
  3589. """H2S shares serial prefix "094" with H2D but is single-nozzle (#1386).
  3590. Must take the single-nozzle branch with setting_id included.
  3591. """
  3592. client = self._make_client(serial="09400S000000001", model="H2S")
  3593. client.delete_kprofile(
  3594. cali_idx=1,
  3595. filament_id="GFA00",
  3596. nozzle_id="HH00-0.4",
  3597. setting_id="PFB123",
  3598. )
  3599. cmd = self._published(client)
  3600. assert cmd["setting_id"] == "PFB123"
  3601. def test_p2s_uses_single_nozzle_format(self):
  3602. """P2S is single-nozzle — must NOT take the dual-nozzle branch."""
  3603. client = self._make_client(serial="22E00A000000001", model="P2S")
  3604. client.delete_kprofile(
  3605. cali_idx=1,
  3606. filament_id="GFA00",
  3607. nozzle_id="HH00-0.4",
  3608. setting_id="PFB123",
  3609. )
  3610. cmd = self._published(client)
  3611. # Single-nozzle command includes setting_id.
  3612. assert cmd["setting_id"] == "PFB123"
  3613. def test_x1c_uses_single_nozzle_format(self):
  3614. client = self._make_client(serial="00M00A000000001", model="X1C")
  3615. client.delete_kprofile(
  3616. cali_idx=1,
  3617. filament_id="GFA00",
  3618. nozzle_id="HH00-0.4",
  3619. setting_id="PFB123",
  3620. )
  3621. cmd = self._published(client)
  3622. assert cmd["setting_id"] == "PFB123"
  3623. class TestStaleReconnect:
  3624. """Tests for stale connection detection and reconnect without UI bouncing."""
  3625. @pytest.fixture
  3626. def mqtt_client(self):
  3627. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3628. client = BambuMQTTClient(
  3629. ip_address="192.168.1.100",
  3630. serial_number="TEST_STALE",
  3631. access_code="12345678",
  3632. )
  3633. return client
  3634. def test_check_staleness_sets_flag_and_broadcasts_once(self, mqtt_client):
  3635. """check_staleness() should set connected=False, broadcast, and set _stale_reconnecting."""
  3636. import time
  3637. state_changes = []
  3638. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  3639. mqtt_client.state.connected = True
  3640. mqtt_client._last_message_time = time.time() - 120 # well past 60s threshold
  3641. result = mqtt_client.check_staleness()
  3642. assert result is False
  3643. assert mqtt_client.state.connected is False
  3644. assert mqtt_client._stale_reconnecting is True
  3645. assert state_changes == [False] # Exactly one broadcast
  3646. def test_check_staleness_noop_when_not_connected(self, mqtt_client):
  3647. """check_staleness() should not set flag when already disconnected."""
  3648. import time
  3649. mqtt_client.state.connected = False
  3650. mqtt_client._last_message_time = time.time() - 120
  3651. mqtt_client.check_staleness()
  3652. assert mqtt_client._stale_reconnecting is False
  3653. def test_check_staleness_noop_when_not_stale(self, mqtt_client):
  3654. """check_staleness() should not set flag when messages are recent."""
  3655. import time
  3656. mqtt_client.state.connected = True
  3657. mqtt_client._last_message_time = time.time() - 5 # 5s ago, well within 60s
  3658. result = mqtt_client.check_staleness()
  3659. assert result is True
  3660. assert mqtt_client.state.connected is True
  3661. assert mqtt_client._stale_reconnecting is False
  3662. def test_check_staleness_logs_serial_hint_when_no_reports(self, mqtt_client, caplog):
  3663. """#1465 — a stale connection that never received a status report logs
  3664. an actionable serial-number hint, exactly once."""
  3665. import logging
  3666. import time
  3667. mqtt_client.state.connected = True
  3668. mqtt_client._last_message_time = time.time() - 120
  3669. mqtt_client._report_messages_since_connect = 0
  3670. with caplog.at_level(logging.WARNING):
  3671. mqtt_client.check_staleness()
  3672. assert mqtt_client._zero_report_hint_logged is True
  3673. assert any("zero status reports" in r.getMessage() for r in caplog.records)
  3674. # Re-arm staleness — the hint must not log a second time.
  3675. caplog.clear()
  3676. mqtt_client.state.connected = True
  3677. mqtt_client._last_message_time = time.time() - 120
  3678. mqtt_client._last_stale_reconnect = 0.0 # bypass the reconnect cooldown
  3679. with caplog.at_level(logging.WARNING):
  3680. mqtt_client.check_staleness()
  3681. assert not any("zero status reports" in r.getMessage() for r in caplog.records)
  3682. def test_check_staleness_no_serial_hint_when_reports_received(self, mqtt_client, caplog):
  3683. """A stale connection that DID receive reports (a normal mid-session
  3684. quiet gap) must not log the serial-number hint."""
  3685. import logging
  3686. import time
  3687. mqtt_client.state.connected = True
  3688. mqtt_client._last_message_time = time.time() - 120
  3689. mqtt_client._report_messages_since_connect = 5
  3690. with caplog.at_level(logging.WARNING):
  3691. mqtt_client.check_staleness()
  3692. assert mqtt_client._zero_report_hint_logged is False
  3693. assert not any("zero status reports" in r.getMessage() for r in caplog.records)
  3694. def test_on_disconnect_skipped_during_stale_reconnect(self, mqtt_client):
  3695. """_on_disconnect should not broadcast state when _stale_reconnecting is set."""
  3696. state_changes = []
  3697. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  3698. mqtt_client._stale_reconnecting = True
  3699. mqtt_client.state.connected = False
  3700. mqtt_client._on_disconnect(None, None)
  3701. # No state change broadcast — check_staleness() already did it
  3702. assert state_changes == []
  3703. assert mqtt_client.state.connected is False
  3704. def test_on_disconnect_fires_event_during_stale_reconnect(self, mqtt_client):
  3705. """_on_disconnect must still fire _disconnection_event even during stale reconnect.
  3706. If disconnect() is called while _stale_reconnecting is True (e.g. user removes
  3707. the printer before paho reconnects), the event must fire so disconnect() doesn't hang.
  3708. """
  3709. import threading
  3710. mqtt_client._stale_reconnecting = True
  3711. mqtt_client._disconnection_event = threading.Event()
  3712. mqtt_client._on_disconnect(None, None)
  3713. assert mqtt_client._disconnection_event.is_set()
  3714. def test_on_connect_clears_stale_reconnecting_flag(self, mqtt_client):
  3715. """_on_connect should clear _stale_reconnecting and restore connected=True."""
  3716. mqtt_client._stale_reconnecting = True
  3717. mqtt_client.state.connected = False
  3718. subscribe_calls = []
  3719. mock_client = type(
  3720. "MockClient",
  3721. (),
  3722. {
  3723. "subscribe": lambda self, topic: subscribe_calls.append(topic) or (0, 1),
  3724. },
  3725. )()
  3726. mqtt_client._on_connect(mock_client, None, None, 0)
  3727. assert mqtt_client._stale_reconnecting is False
  3728. assert mqtt_client.state.connected is True
  3729. def test_full_stale_reconnect_cycle_no_bounce(self, mqtt_client):
  3730. """Full cycle: stale → disconnect callback → reconnect. UI should see exactly one disconnect."""
  3731. import time
  3732. state_changes = []
  3733. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  3734. mqtt_client.state.connected = True
  3735. mqtt_client._last_message_time = time.time() - 120
  3736. # Step 1: Stale detection triggers
  3737. mqtt_client.check_staleness()
  3738. assert state_changes == [False]
  3739. # Step 2: Paho fires disconnect callback (from socket close)
  3740. mqtt_client._on_disconnect(None, None)
  3741. # Should NOT add another state change
  3742. assert state_changes == [False]
  3743. # Step 3: Paho reconnects
  3744. subscribe_calls = []
  3745. mock_client = type(
  3746. "MockClient",
  3747. (),
  3748. {
  3749. "subscribe": lambda self, topic: subscribe_calls.append(topic) or (0, 1),
  3750. },
  3751. )()
  3752. mqtt_client._on_connect(mock_client, None, None, 0)
  3753. assert state_changes == [False, True] # Now connected again
  3754. assert mqtt_client._stale_reconnecting is False
  3755. def test_spurious_disconnect_suppressed_when_recent_messages(self, mqtt_client):
  3756. """Non-error disconnect with recent messages should be suppressed."""
  3757. import time
  3758. state_changes = []
  3759. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  3760. mqtt_client.state.connected = True
  3761. mqtt_client._last_message_time = time.time() - 3 # 3s ago
  3762. # Non-error disconnect (rc=None)
  3763. mqtt_client._on_disconnect(None, None)
  3764. assert state_changes == []
  3765. assert mqtt_client.state.connected is True
  3766. def test_error_disconnect_not_suppressed_despite_recent_messages(self, mqtt_client):
  3767. """Error disconnect should always be processed, even with recent messages."""
  3768. import time
  3769. import paho.mqtt.client as mqtt
  3770. from paho.mqtt.reasoncodes import ReasonCode
  3771. state_changes = []
  3772. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  3773. mqtt_client.state.connected = True
  3774. mqtt_client._last_message_time = time.time() - 3 # 3s ago
  3775. # Error disconnect (rc.is_failure = True)
  3776. rc = ReasonCode(mqtt.CONNACK >> 4, identifier=0x80) # Failure code
  3777. mqtt_client._on_disconnect(None, None, rc=rc)
  3778. assert state_changes == [False]
  3779. assert mqtt_client.state.connected is False
  3780. class TestDoorOpenParsing:
  3781. """Tests for enclosure door state parsing (X1 home_flag bit 23 vs others stat bit 23)."""
  3782. def _make_client(self, model: str):
  3783. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3784. return BambuMQTTClient(
  3785. ip_address="192.168.1.100",
  3786. serial_number="TEST",
  3787. access_code="12345678",
  3788. model=model,
  3789. )
  3790. def test_x1c_door_open_from_home_flag(self):
  3791. client = self._make_client("X1C")
  3792. # bit 23 set
  3793. client._update_state({"home_flag": 0xC0E5CD98})
  3794. assert client.state.door_open is True
  3795. def test_x1c_door_closed_from_home_flag(self):
  3796. client = self._make_client("X1C")
  3797. client.state.door_open = True # start "open"
  3798. client._update_state({"home_flag": 0xC065CD98})
  3799. assert client.state.door_open is False
  3800. def test_x1c_ignores_stat_field(self):
  3801. # X1C must NOT use stat (bit 23 in stat is unrelated for X1)
  3802. client = self._make_client("X1C")
  3803. client._update_state({"home_flag": 0xC065CD98, "stat": "47A58000"})
  3804. assert client.state.door_open is False # home_flag wins
  3805. def test_h2d_door_open_from_stat(self):
  3806. client = self._make_client("H2D")
  3807. client._update_state({"stat": "640A58000"}) # bit 23 set
  3808. assert client.state.door_open is True
  3809. def test_h2d_door_closed_from_stat(self):
  3810. client = self._make_client("H2D")
  3811. client.state.door_open = True
  3812. client._update_state({"stat": "640258000"}) # bit 23 cleared
  3813. assert client.state.door_open is False
  3814. def test_h2d_ignores_home_flag(self):
  3815. # Non-X1 must NOT consume home_flag for door state
  3816. client = self._make_client("H2D")
  3817. client._update_state({"home_flag": 0xC0E5CD98, "stat": "640258000"})
  3818. assert client.state.door_open is False # stat wins
  3819. def test_invalid_stat_does_not_raise(self):
  3820. client = self._make_client("H2D")
  3821. client._update_state({"stat": "not-hex"})
  3822. assert client.state.door_open is False
  3823. class TestSdCardParsing:
  3824. """SD-card state is only set from the top-level `sdcard` field (bool/int/
  3825. string variants). home_flag is NOT consulted — heartbeat pushes clear those
  3826. bits even when a card is inserted, and the prior badge feature was removed
  3827. entirely because no reliable heartbeat-vs-full-push heuristic existed."""
  3828. def _make_client(self, model: str = "H2D"):
  3829. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3830. return BambuMQTTClient(
  3831. ip_address="192.168.1.100",
  3832. serial_number="TEST",
  3833. access_code="12345678",
  3834. model=model,
  3835. )
  3836. def test_home_flag_alone_does_not_touch_sdcard(self):
  3837. client = self._make_client()
  3838. client.state.sdcard = True
  3839. for home_flag in (0x00000000, 0x00000100, 0x00000200):
  3840. client._update_state({"home_flag": home_flag})
  3841. assert client.state.sdcard is True
  3842. def test_sdcard_string_fallback_when_no_home_flag(self):
  3843. client = self._make_client()
  3844. client._update_state({"sdcard": "HAS_SDCARD_NORMAL"})
  3845. assert client.state.sdcard is True
  3846. def test_sdcard_int_fallback_when_no_home_flag(self):
  3847. # `1 is True` is False — the old strict check flapped here.
  3848. client = self._make_client()
  3849. client._update_state({"sdcard": 1})
  3850. assert client.state.sdcard is True
  3851. def test_sdcard_bool_fallback_when_no_home_flag(self):
  3852. client = self._make_client()
  3853. client._update_state({"sdcard": True})
  3854. assert client.state.sdcard is True
  3855. client._update_state({"sdcard": False})
  3856. assert client.state.sdcard is False
  3857. class TestZombieSessionDetection:
  3858. """Tests for ams_filament_setting response tracking (#887).
  3859. When a printer's MQTT session degrades so that telemetry flows but
  3860. published commands never reach the printer, the zombie detector
  3861. counts consecutive unanswered ams_filament_setting commands and
  3862. force-reconnects after two.
  3863. """
  3864. @pytest.fixture
  3865. def mqtt_client(self):
  3866. import time
  3867. from unittest.mock import MagicMock
  3868. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3869. client = BambuMQTTClient(
  3870. ip_address="192.168.1.100",
  3871. serial_number="TEST123",
  3872. access_code="12345678",
  3873. )
  3874. client.state.connected = True
  3875. mock_paho = MagicMock()
  3876. mock_paho.socket.return_value = MagicMock()
  3877. client._client = mock_paho
  3878. client._connect_time = time.monotonic() - 10.0
  3879. # Set developer_mode so the dev-mode probe branch doesn't interfere
  3880. client.state.developer_mode = True
  3881. return client
  3882. def test_initial_state_is_clean(self, mqtt_client):
  3883. """Tracking fields start at zero / no pending command."""
  3884. assert mqtt_client._last_ams_cmd_time == 0.0
  3885. assert mqtt_client._ams_cmd_unanswered == 0
  3886. def test_publish_sets_pending_time(self, mqtt_client):
  3887. """set_ams_filament_setting records the publish timestamp."""
  3888. import time
  3889. before = time.monotonic()
  3890. mqtt_client.ams_set_filament_setting(
  3891. ams_id=0,
  3892. tray_id=0,
  3893. tray_info_idx="GFL99",
  3894. tray_type="PLA",
  3895. tray_sub_brands="",
  3896. tray_color="FF0000FF",
  3897. nozzle_temp_min=190,
  3898. nozzle_temp_max=230,
  3899. )
  3900. assert mqtt_client._last_ams_cmd_time >= before
  3901. def test_reset_slot_sets_pending_time(self, mqtt_client):
  3902. """reset_ams_slot also records the publish timestamp."""
  3903. import time
  3904. before = time.monotonic()
  3905. mqtt_client.reset_ams_slot(ams_id=0, tray_id=0)
  3906. assert mqtt_client._last_ams_cmd_time >= before
  3907. def test_response_clears_pending(self, mqtt_client):
  3908. """An ams_filament_setting response clears the pending state."""
  3909. import time
  3910. mqtt_client._last_ams_cmd_time = time.monotonic()
  3911. mqtt_client._ams_cmd_unanswered = 1
  3912. # Simulate receiving a user-command response (sequence_id "0")
  3913. print_data = {
  3914. "command": "ams_filament_setting",
  3915. "sequence_id": "0",
  3916. "result": "success",
  3917. }
  3918. # Walk the same path as _on_message: command response check then _update_state
  3919. cmd = print_data.get("command")
  3920. if cmd == "ams_filament_setting" and mqtt_client._last_ams_cmd_time > 0:
  3921. mqtt_client._last_ams_cmd_time = 0.0
  3922. mqtt_client._ams_cmd_unanswered = 0
  3923. assert mqtt_client._last_ams_cmd_time == 0.0
  3924. assert mqtt_client._ams_cmd_unanswered == 0
  3925. def test_single_timeout_increments_counter(self, mqtt_client):
  3926. """One unanswered command increments the counter but does not reconnect."""
  3927. import time
  3928. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  3929. mqtt_client._update_state({"gcode_state": "IDLE"})
  3930. assert mqtt_client._ams_cmd_unanswered == 1
  3931. assert mqtt_client._last_ams_cmd_time == 0.0
  3932. # Should NOT force-reconnect after just one
  3933. assert mqtt_client.state.connected is True
  3934. def test_two_timeouts_force_reconnect(self, mqtt_client):
  3935. """Two consecutive unanswered commands trigger force_reconnect.
  3936. Zombie detection runs from paho's network thread (no asyncio loop), so
  3937. the routing in force_reconnect_stale_session falls back to socket-close
  3938. — which is the safe option since loop_stop() from inside the loop
  3939. thread would deadlock. Hard-reset is reserved for async-context callers
  3940. on the queue dispatch path."""
  3941. import time
  3942. state_change_called = []
  3943. mqtt_client.on_state_change = lambda s: state_change_called.append(True)
  3944. # First unanswered command
  3945. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  3946. mqtt_client._update_state({"gcode_state": "IDLE"})
  3947. assert mqtt_client._ams_cmd_unanswered == 1
  3948. assert mqtt_client.state.connected is True
  3949. # Second unanswered command
  3950. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  3951. mqtt_client._update_state({"gcode_state": "IDLE"})
  3952. assert mqtt_client._ams_cmd_unanswered == 0 # reset after reconnect
  3953. assert mqtt_client.state.connected is False
  3954. assert mqtt_client._stale_reconnecting is True
  3955. # Sync test → no running loop → socket-close fallback path
  3956. mqtt_client._client.socket().close.assert_called()
  3957. assert len(state_change_called) > 0
  3958. def test_response_between_timeouts_resets_counter(self, mqtt_client):
  3959. """A successful response after one timeout resets the counter."""
  3960. import time
  3961. # First unanswered command
  3962. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  3963. mqtt_client._update_state({"gcode_state": "IDLE"})
  3964. assert mqtt_client._ams_cmd_unanswered == 1
  3965. # Now a response arrives — clear pending
  3966. mqtt_client._last_ams_cmd_time = time.monotonic()
  3967. mqtt_client._last_ams_cmd_time = 0.0
  3968. mqtt_client._ams_cmd_unanswered = 0
  3969. # Next unanswered command should be count=1, not count=2
  3970. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  3971. mqtt_client._update_state({"gcode_state": "IDLE"})
  3972. assert mqtt_client._ams_cmd_unanswered == 1
  3973. assert mqtt_client.state.connected is True # no reconnect
  3974. def test_late_response_after_watchdog_clears_counter_issue_1164(self, mqtt_client):
  3975. """Regression for #1164: a late ams_filament_setting response — one
  3976. that arrives AFTER the watchdog has already zeroed
  3977. `_last_ams_cmd_time` and incremented the unanswered counter — must
  3978. still reset the counter. Without this, a single sluggish response
  3979. leaves the counter armed at 1 indefinitely; the next slow response
  3980. on a totally unrelated command (possibly minutes or hours later)
  3981. takes it to 2 and force-reconnects, surfacing as 'AMS slot config
  3982. doesn't reach the printer ~6 changes in'."""
  3983. import time
  3984. # First command publishes, then doesn't get a response for >10s.
  3985. # Watchdog fires: counter=1, _last_ams_cmd_time zeroed.
  3986. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  3987. mqtt_client._update_state({"gcode_state": "IDLE"})
  3988. assert mqtt_client._ams_cmd_unanswered == 1
  3989. assert mqtt_client._last_ams_cmd_time == 0.0 # watchdog cleared it
  3990. # Late response arrives — the `_process_message` path used to require
  3991. # `_last_ams_cmd_time > 0` before resetting the counter, so this would
  3992. # have silently been ignored.
  3993. mqtt_client._process_message(
  3994. {
  3995. "print": {
  3996. "command": "ams_filament_setting",
  3997. "sequence_id": "0",
  3998. "result": "success",
  3999. "reason": "success",
  4000. }
  4001. }
  4002. )
  4003. # Counter MUST be reset — the response proves the channel is alive.
  4004. assert mqtt_client._ams_cmd_unanswered == 0, (
  4005. "Late ams_filament_setting response must reset the unanswered "
  4006. "counter even when the watchdog already zeroed _last_ams_cmd_time. "
  4007. "If this assertion fails the #1164 regression is back: a single "
  4008. "sluggish response will leave the counter armed and cause a "
  4009. "spurious force_reconnect on the next slow response."
  4010. )
  4011. # Now even if a future command times out, the counter starts fresh
  4012. # and a single timeout doesn't trip the 2x reconnect threshold.
  4013. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4014. mqtt_client._update_state({"gcode_state": "IDLE"})
  4015. assert mqtt_client._ams_cmd_unanswered == 1
  4016. assert mqtt_client.state.connected is True # no force reconnect
  4017. def test_on_connect_resets_tracking(self, mqtt_client):
  4018. """_on_connect resets zombie tracking fields."""
  4019. import time
  4020. mqtt_client._last_ams_cmd_time = time.monotonic()
  4021. mqtt_client._ams_cmd_unanswered = 5
  4022. # subscribe() must return (result, mid) tuple
  4023. mqtt_client._client.subscribe.return_value = (0, 1)
  4024. mqtt_client._on_connect(mqtt_client._client, None, None, 0)
  4025. assert mqtt_client._last_ams_cmd_time == 0.0
  4026. assert mqtt_client._ams_cmd_unanswered == 0
  4027. def test_no_check_when_no_command_pending(self, mqtt_client):
  4028. """If no command was published, push_status does not trigger detection."""
  4029. assert mqtt_client._last_ams_cmd_time == 0.0
  4030. mqtt_client._update_state({"gcode_state": "IDLE"})
  4031. assert mqtt_client._ams_cmd_unanswered == 0
  4032. def test_no_timeout_within_window(self, mqtt_client):
  4033. """A command published <10s ago should not trigger a timeout."""
  4034. import time
  4035. mqtt_client._last_ams_cmd_time = time.monotonic() - 5.0
  4036. mqtt_client._update_state({"gcode_state": "IDLE"})
  4037. assert mqtt_client._ams_cmd_unanswered == 0
  4038. assert mqtt_client._last_ams_cmd_time > 0 # still pending
  4039. class TestHMSUserActionFiltering:
  4040. """HMS short codes the printer firmware emits during user-cancel sequences
  4041. must not appear in state.hms_errors — they're status echoes, not faults,
  4042. and shouldn't drive the printer card's "X problem" badge or red pip."""
  4043. @pytest.fixture
  4044. def mqtt_client(self):
  4045. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4046. return BambuMQTTClient(
  4047. ip_address="192.168.1.100",
  4048. serial_number="TEST_HMS",
  4049. access_code="12345678",
  4050. )
  4051. def test_task_cancelled_echo_0300_400c_filtered(self, mqtt_client):
  4052. """0300_400C ("The task was canceled.") is the user-cancel echo that was
  4053. leaving the printer card stuck on "1 problem" after every stop."""
  4054. mqtt_client._update_state({"hms": [{"attr": 0x03000300, "code": 0x400C}]})
  4055. assert mqtt_client.state.hms_errors == []
  4056. def test_printing_cancelled_echo_0500_400e_filtered(self, mqtt_client):
  4057. """0500_400E ("Printing was cancelled.") — the corresponding nozzle-module
  4058. echo that the backend notification path was already suppressing for the
  4059. same reason."""
  4060. mqtt_client._update_state({"hms": [{"attr": 0x05000300, "code": 0x400E}]})
  4061. assert mqtt_client.state.hms_errors == []
  4062. def test_real_layer_shift_still_passes_through(self, mqtt_client):
  4063. """0300_4057 (Z-axis step loss) is a real fault and must NOT be filtered."""
  4064. mqtt_client._update_state({"hms": [{"attr": 0x03000100, "code": 0x4057}]})
  4065. assert len(mqtt_client.state.hms_errors) == 1
  4066. assert mqtt_client.state.hms_errors[0].code == "0x4057"
  4067. def test_filter_only_drops_user_action_codes_keeps_concurrent_real_faults(self, mqtt_client):
  4068. """When the user cancels mid-fault, the firmware sends the real fault HMS
  4069. alongside the cancel echo. Drop only the echo, keep the real fault."""
  4070. mqtt_client._update_state(
  4071. {
  4072. "hms": [
  4073. {"attr": 0x03000300, "code": 0x400C}, # cancel echo — drop
  4074. {"attr": 0x07FF0200, "code": 0x8011}, # filament runout — keep
  4075. ]
  4076. }
  4077. )
  4078. codes = [e.code for e in mqtt_client.state.hms_errors]
  4079. assert "0x8011" in codes
  4080. assert "0x400c" not in codes
  4081. assert len(mqtt_client.state.hms_errors) == 1
  4082. def test_print_error_path_also_filters_cancel_echo(self, mqtt_client):
  4083. """`print_error` is a second route that appends into state.hms_errors. The
  4084. same user-action codes (e.g. 0500_400E "Printing was cancelled") must be
  4085. filtered there too — otherwise the printer card stays on "1 problem"
  4086. when the firmware reports the cancel via print_error rather than hms[]."""
  4087. mqtt_client._update_state({"print_error": 0x0500_400E})
  4088. assert mqtt_client.state.hms_errors == []
  4089. def test_print_error_path_passes_real_errors_through(self, mqtt_client):
  4090. """Real print_error codes still reach state.hms_errors."""
  4091. mqtt_client._update_state({"print_error": 0x0500_8061})
  4092. assert len(mqtt_client.state.hms_errors) == 1
  4093. assert mqtt_client.state.hms_errors[0].code == "0x8061"
  4094. class TestHMSFullCode:
  4095. """full_code is the firmware-matching key for HMS-related commands.
  4096. Truncating it to the 8-char short code is what caused #1830's silent
  4097. rejection on H2C, and the H2D wrong-plate path needs the print_error
  4098. 32-bit form. Both branches must populate full_code consistently."""
  4099. @pytest.fixture
  4100. def mqtt_client(self):
  4101. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4102. return BambuMQTTClient(
  4103. ip_address="192.168.1.100",
  4104. serial_number="TEST_FULLCODE",
  4105. access_code="12345678",
  4106. )
  4107. def test_hms_array_path_populates_16_char_full_code(self, mqtt_client):
  4108. """hms[] entries carry a 64-bit identifier (attr + code, 32 bits each).
  4109. The full 16-char hex is what BambuStudio uses to match err on
  4110. idle_ignore — the truncated short_code drops 32 bits and the firmware
  4111. silently rejects (#1830). Verifies the parser preserves the full
  4112. identifier on HMSError.full_code."""
  4113. # 0x07FF0200 / 0x8011 → displayed as 07FF_0200_0000_8011 in the wiki
  4114. mqtt_client._update_state({"hms": [{"attr": 0x07FF0200, "code": 0x8011}]})
  4115. assert len(mqtt_client.state.hms_errors) == 1
  4116. assert mqtt_client.state.hms_errors[0].full_code == "07FF02000000" + "8011"
  4117. def test_print_error_path_populates_8_char_full_code(self, mqtt_client):
  4118. """print_error is already 32 bits — no truncation. full_code is the
  4119. 8-char hex form, which is exactly what the firmware matches against."""
  4120. mqtt_client._update_state({"print_error": 0x05008051})
  4121. assert len(mqtt_client.state.hms_errors) == 1
  4122. assert mqtt_client.state.hms_errors[0].full_code == "05008051"
  4123. def test_hms_array_catalog_lookup_tries_16_char_first(self, mqtt_client, monkeypatch):
  4124. """When the catalog has both an 8-char and a 16-char entry for the
  4125. same fault family, the 16-char (specific variant) wins. The 8-char
  4126. is the fallback for codes that aren't in the long-form catalog."""
  4127. from backend.app.services import bambu_mqtt as mod
  4128. calls = []
  4129. def fake_lookup(device, code):
  4130. calls.append((device, code))
  4131. if len(code) == 16:
  4132. return ["RESUME_PRINTING"]
  4133. return []
  4134. monkeypatch.setattr(mod, "get_actions_for_error_code", fake_lookup)
  4135. # SN prefix "TES" — irrelevant for the test, we mocked the lookup.
  4136. mqtt_client._update_state({"hms": [{"attr": 0x07FF0200, "code": 0x8011}]})
  4137. # 16-char lookup attempted first, then 8-char only if 16-char missed.
  4138. assert calls[0][1] == "07FF020000008011"
  4139. assert mqtt_client.state.hms_errors[0].actions == ["RESUME_PRINTING"]
  4140. def test_hms_array_catalog_falls_back_to_8_char(self, mqtt_client, monkeypatch):
  4141. """If the catalog has no 16-char entry, fall back to the 8-char short
  4142. code — that's where base-class HMS codes live."""
  4143. from backend.app.services import bambu_mqtt as mod
  4144. calls = []
  4145. def fake_lookup(device, code):
  4146. calls.append((device, code))
  4147. if len(code) == 16:
  4148. return [] # no specific variant
  4149. return ["CHECK_ASSISTANT"] # base class hit
  4150. monkeypatch.setattr(mod, "get_actions_for_error_code", fake_lookup)
  4151. mqtt_client._update_state({"hms": [{"attr": 0x07FF0200, "code": 0x8011}]})
  4152. # Two lookups: 16-char miss, then 8-char hit.
  4153. assert len(calls) == 2
  4154. assert calls[0][1] == "07FF020000008011"
  4155. assert calls[1][1] == "07FF8011"
  4156. assert mqtt_client.state.hms_errors[0].actions == ["CHECK_ASSISTANT"]
  4157. class TestForceReconnectRouting:
  4158. """#1136 — force_reconnect_stale_session routes between hard-reset (full
  4159. paho-client teardown, wipes the QoS 1 queue) and socket-close (the legacy
  4160. behaviour, safe to call from paho's own network thread). The routing
  4161. decision is based on whether an asyncio loop is running: hard-reset
  4162. requires loop_stop() which would deadlock if called from inside the
  4163. network thread itself."""
  4164. @pytest.fixture
  4165. def mqtt_client(self):
  4166. from unittest.mock import MagicMock
  4167. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4168. client = BambuMQTTClient(
  4169. ip_address="192.168.1.100",
  4170. serial_number="TEST_HARD_RESET",
  4171. access_code="12345678",
  4172. )
  4173. client.state.connected = True
  4174. client._client = MagicMock()
  4175. return client
  4176. def test_routing_falls_back_to_socket_close_without_running_loop(self, mqtt_client):
  4177. """Sync caller → no asyncio loop → socket-close path (legacy behaviour
  4178. preserved for paho-thread callers like zombie detection)."""
  4179. mqtt_client.force_reconnect_stale_session("test")
  4180. mqtt_client._client.socket().close.assert_called()
  4181. # Old client is NOT torn down on this path; same-instance reconnect
  4182. # via paho's auto-reconnect handles it.
  4183. assert mqtt_client._client is not None
  4184. def test_routing_uses_hard_reset_when_loop_is_running(self, mqtt_client):
  4185. """Async caller → loop available → hard-reset path wipes the queue."""
  4186. import asyncio
  4187. original = mqtt_client._client
  4188. # Stub connect() so the rebuild doesn't open a real socket.
  4189. mqtt_client.connect = lambda loop=None: None
  4190. async def _trigger():
  4191. mqtt_client.force_reconnect_stale_session("test")
  4192. asyncio.run(_trigger())
  4193. original.disconnect.assert_called()
  4194. original.loop_stop.assert_called()
  4195. # connect() stub didn't repopulate _client, so it's None — the contract
  4196. # in production is that connect() builds a fresh mqtt.Client here.
  4197. assert mqtt_client._client is None
  4198. def test_marks_state_disconnected_and_broadcasts(self, mqtt_client):
  4199. """Both routing paths must broadcast the disconnected state once."""
  4200. broadcasts: list[bool] = []
  4201. mqtt_client.on_state_change = lambda s: broadcasts.append(s.connected)
  4202. mqtt_client.force_reconnect_stale_session("test")
  4203. assert mqtt_client.state.connected is False
  4204. assert mqtt_client._stale_reconnecting is True
  4205. assert broadcasts == [False]
  4206. class TestHardResetClientDirect:
  4207. """Lower-level coverage of `_hard_reset_client` itself — the helper called
  4208. by the routing layer when a full paho-client teardown is safe. These tests
  4209. drive the helper directly so they don't depend on the routing decision."""
  4210. @pytest.fixture
  4211. def mqtt_client(self):
  4212. from unittest.mock import MagicMock
  4213. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4214. client = BambuMQTTClient(
  4215. ip_address="192.168.1.100",
  4216. serial_number="TEST_HARD_DIRECT",
  4217. access_code="12345678",
  4218. )
  4219. client.state.connected = True
  4220. client._client = MagicMock()
  4221. # Stub connect() so the rebuild doesn't open a real socket.
  4222. client.connect = lambda loop=None: None
  4223. return client
  4224. def test_disconnects_and_stops_old_client(self, mqtt_client):
  4225. """Old paho client must receive DISCONNECT (broker drops session) +
  4226. loop_stop (network thread exits, taking its QoS 1 queue with it)."""
  4227. original = mqtt_client._client
  4228. mqtt_client._hard_reset_client()
  4229. original.disconnect.assert_called()
  4230. original.loop_stop.assert_called()
  4231. def test_clears_client_reference(self, mqtt_client):
  4232. """Old reference must go to None so subsequent code can't accidentally
  4233. publish through the dying client."""
  4234. mqtt_client._hard_reset_client()
  4235. assert mqtt_client._client is None
  4236. def test_swallows_disconnect_exception(self, mqtt_client):
  4237. """A failing disconnect() (e.g. paho already in error state) must not
  4238. propagate through async dispatch callers, and a single broken client
  4239. could brick every future dispatch."""
  4240. original = mqtt_client._client
  4241. original.disconnect.side_effect = RuntimeError("boom")
  4242. # No exception escapes the call (test would fail if it did).
  4243. mqtt_client._hard_reset_client()
  4244. # loop_stop is still attempted after the disconnect failure.
  4245. original.loop_stop.assert_called()
  4246. assert mqtt_client._client is None
  4247. class TestStartPrintRecordsDispatchedPlate:
  4248. """Tests for the dispatched-plate record set by start_print() — used by the
  4249. /cover route to pick the right thumbnail when the printer's gcode_file
  4250. echo doesn't include the plate path (#1166).
  4251. Some firmware versions (P1S 01.10.00.00) only put the .3mf filename in
  4252. print.gcode_file, so the regex falls back to plate 1 and the printer card
  4253. shows the wrong plate's thumbnail. Recording what we dispatched at the
  4254. publish site lets resolve_plate_id() return the right plate without
  4255. needing to introspect the 3MF.
  4256. """
  4257. @pytest.fixture
  4258. def mqtt_client(self):
  4259. from unittest.mock import MagicMock
  4260. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4261. client = BambuMQTTClient(
  4262. ip_address="192.168.1.100",
  4263. serial_number="TEST123",
  4264. access_code="12345678",
  4265. )
  4266. client._client = MagicMock()
  4267. client.state.connected = True
  4268. return client
  4269. def test_dispatched_plate_recorded_after_start_print(self, mqtt_client):
  4270. # Default state has no dispatched plate.
  4271. assert mqtt_client.state.dispatched_plate_id is None
  4272. assert mqtt_client.state.dispatched_subtask is None
  4273. mqtt_client.start_print("Luigi.3mf", plate_id=2)
  4274. # The subtask_name we record matches the one we send (and the printer
  4275. # reflects back via MQTT), so resolve_plate_id() can validate the
  4276. # match downstream.
  4277. assert mqtt_client.state.dispatched_plate_id == 2
  4278. assert mqtt_client.state.dispatched_subtask == "Luigi"
  4279. def test_dispatched_plate_default_is_one(self, mqtt_client):
  4280. # When start_print is called without plate_id (legacy/single-plate
  4281. # flow), we still record plate=1 — the contract is that dispatched_*
  4282. # describes the active dispatch.
  4283. mqtt_client.start_print("Single.3mf")
  4284. assert mqtt_client.state.dispatched_plate_id == 1
  4285. assert mqtt_client.state.dispatched_subtask == "Single"
  4286. def test_dispatched_plate_overwritten_by_subsequent_dispatch(self, mqtt_client):
  4287. # Each dispatch replaces the prior record so we can never serve a
  4288. # stale plate from an older print.
  4289. mqtt_client.start_print("First.3mf", plate_id=4)
  4290. mqtt_client.start_print("Second.3mf", plate_id=2)
  4291. assert mqtt_client.state.dispatched_plate_id == 2
  4292. assert mqtt_client.state.dispatched_subtask == "Second"
  4293. def test_dispatched_plate_not_recorded_when_publish_skipped(self, mqtt_client):
  4294. # If start_print early-returns because we're not connected, no record
  4295. # should land — otherwise the next print's /cover call would believe
  4296. # a phantom dispatch happened.
  4297. mqtt_client.state.connected = False
  4298. result = mqtt_client.start_print("Phantom.3mf", plate_id=3)
  4299. assert result is False
  4300. assert mqtt_client.state.dispatched_plate_id is None
  4301. assert mqtt_client.state.dispatched_subtask is None
  4302. class TestStartPrintNozzleMappingDispatch:
  4303. """H2C dual-nozzle-rack (#1780) — nozzle_mapping on dispatch.
  4304. BambuStudio's project_file MQTT command for O1C2 carries a per-filament
  4305. physical nozzle position ID array (`nozzle_mapping`). Without forwarding
  4306. it, the H2C firmware falls back to "last matching nozzle type" auto-pick
  4307. and ignores the user's slicer choice. Tests pin the gate, the parse, the
  4308. no-op cases, and the malformed-JSON safety net.
  4309. The original #1780 attempt also captured `nozzles_info` but a wire capture
  4310. on H2C confirmed BambuStudio never sends that field — the capture/dispatch
  4311. paths for it were dropped in the same release.
  4312. """
  4313. @pytest.fixture
  4314. def mqtt_client(self):
  4315. from unittest.mock import MagicMock
  4316. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4317. client = BambuMQTTClient(
  4318. ip_address="192.168.1.100",
  4319. serial_number="TEST_O1C2",
  4320. access_code="12345678",
  4321. )
  4322. client._client = MagicMock()
  4323. client.state.connected = True
  4324. return client
  4325. def _published_print_cmd(self, mqtt_client):
  4326. call_args = mqtt_client._client.publish.call_args
  4327. return json.loads(call_args[0][1])["print"]
  4328. def test_dual_nozzle_includes_nozzle_mapping(self, mqtt_client):
  4329. """Dual-nozzle + nozzle_mapping present → parsed JSON array injected
  4330. verbatim onto the dispatched project_file command."""
  4331. mqtt_client._is_dual_nozzle = True
  4332. mqtt_client.start_print(
  4333. "test.3mf",
  4334. nozzle_mapping=json.dumps([16, -1, -1, 1, -1, -1, -1, -1]),
  4335. )
  4336. cmd = self._published_print_cmd(mqtt_client)
  4337. # List, not string — the wire shape must match BambuStudio's.
  4338. assert cmd["nozzle_mapping"] == [16, -1, -1, 1, -1, -1, -1, -1]
  4339. def test_single_nozzle_omits_nozzle_mapping_even_if_set(self, mqtt_client):
  4340. """A single-nozzle printer must NOT emit the rack field even if the
  4341. caller passes it (defense-in-depth — the queue item could legitimately
  4342. carry a stale capture from before a model change)."""
  4343. mqtt_client._is_dual_nozzle = False
  4344. mqtt_client.model = "P1S" # single-nozzle
  4345. mqtt_client.start_print(
  4346. "test.3mf",
  4347. nozzle_mapping=json.dumps([16, 0, 19]),
  4348. )
  4349. cmd = self._published_print_cmd(mqtt_client)
  4350. assert "nozzle_mapping" not in cmd
  4351. def test_dual_nozzle_no_field_no_injection(self, mqtt_client):
  4352. """Dual-nozzle printer + no slicer pick (NULL on queue item) → command
  4353. carries no nozzle_mapping. The firmware then runs its normal
  4354. auto-pick, which is the pre-fix behaviour for any non-O1C2 dual-
  4355. nozzle model that has no rack to disambiguate against anyway."""
  4356. mqtt_client._is_dual_nozzle = True
  4357. mqtt_client.start_print("test.3mf", nozzle_mapping=None)
  4358. cmd = self._published_print_cmd(mqtt_client)
  4359. assert "nozzle_mapping" not in cmd
  4360. def test_malformed_nozzle_mapping_is_logged_and_omitted(self, mqtt_client, caplog):
  4361. """Invalid JSON on the queue item must NOT block the dispatch. Log a
  4362. warning and let the firmware auto-pick — the failure mode is just
  4363. the pre-fix behaviour, not a worse one. Fail-open is correct here
  4364. because the alternative would silently brick every dispatch on a
  4365. single bad row."""
  4366. mqtt_client._is_dual_nozzle = True
  4367. with caplog.at_level("WARNING"):
  4368. result = mqtt_client.start_print(
  4369. "test.3mf",
  4370. nozzle_mapping="not valid json {",
  4371. )
  4372. assert result is True # dispatch still proceeded
  4373. cmd = self._published_print_cmd(mqtt_client)
  4374. assert "nozzle_mapping" not in cmd
  4375. assert any("Invalid nozzle_mapping" in rec.message for rec in caplog.records)
  4376. def test_empty_string_field_is_treated_as_absent(self, mqtt_client):
  4377. """An empty-string column value (legacy data, or a NOT NULL DB
  4378. recovery shim) must behave the same as NULL — no injection, no
  4379. parse error log."""
  4380. mqtt_client._is_dual_nozzle = True
  4381. mqtt_client.start_print("test.3mf", nozzle_mapping="")
  4382. cmd = self._published_print_cmd(mqtt_client)
  4383. assert "nozzle_mapping" not in cmd
  4384. class TestFilamentTrackSwitchDetection:
  4385. """Tests for Filament Track Switch (FTS) accessory detection (#1162).
  4386. The FTS is an accessory that sits between an AMS and the printer's
  4387. extruders, dynamically routing any slot to either nozzle. When installed,
  4388. each AMS unit reports info bits 8-11 = 0xE (uninitialized) since slots are
  4389. no longer tied to a specific extruder. Detection comes from the presence of
  4390. the print.device.fila_switch object in MQTT push_status.
  4391. """
  4392. @pytest.fixture
  4393. def mqtt_client(self):
  4394. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4395. return BambuMQTTClient(
  4396. ip_address="192.168.1.100",
  4397. serial_number="TEST123",
  4398. access_code="12345678",
  4399. )
  4400. def test_fts_default_not_installed(self, mqtt_client):
  4401. """Without any MQTT data, fila_switch.installed must be False so the
  4402. frontend keeps applying the per-extruder filter on regular dual-nozzle
  4403. printers."""
  4404. assert mqtt_client.state.fila_switch.installed is False
  4405. assert mqtt_client.state.fila_switch.in_slots == []
  4406. assert mqtt_client.state.fila_switch.out_extruders == []
  4407. def test_fts_detected_from_device_fila_switch(self, mqtt_client):
  4408. """A push_status with print.device.fila_switch present must mark FTS
  4409. installed and capture its routing arrays. Mirrors the user's MQTT
  4410. bundle in #1162."""
  4411. data = {
  4412. "gcode_state": "RUNNING",
  4413. "device": {
  4414. "fila_switch": {
  4415. "in": [-1, 2],
  4416. "info": 2,
  4417. "out": [0, 1],
  4418. "stat": 0,
  4419. }
  4420. },
  4421. }
  4422. mqtt_client._update_state(data)
  4423. fs = mqtt_client.state.fila_switch
  4424. assert fs.installed is True
  4425. assert fs.in_slots == [-1, 2]
  4426. assert fs.out_extruders == [0, 1]
  4427. assert fs.stat == 0
  4428. assert fs.info == 2
  4429. def test_fts_absent_when_no_fila_switch_field(self, mqtt_client):
  4430. """A push_status that has device.* but no fila_switch must leave
  4431. fila_switch.installed = False — only that specific field flips it on."""
  4432. data = {
  4433. "gcode_state": "IDLE",
  4434. "device": {"extruder": {"state": 0}},
  4435. }
  4436. mqtt_client._update_state(data)
  4437. assert mqtt_client.state.fila_switch.installed is False
  4438. def test_fts_handles_missing_in_out_arrays(self, mqtt_client):
  4439. """If the firmware sends fila_switch with missing or non-list in/out,
  4440. we must still mark it installed (presence is the signal) and default
  4441. the arrays to empty lists rather than crashing."""
  4442. data = {
  4443. "gcode_state": "IDLE",
  4444. "device": {"fila_switch": {"stat": 0, "info": 0}},
  4445. }
  4446. mqtt_client._update_state(data)
  4447. fs = mqtt_client.state.fila_switch
  4448. assert fs.installed is True
  4449. assert fs.in_slots == []
  4450. assert fs.out_extruders == []
  4451. class TestAmsLoadFilamentEncoding:
  4452. """Per-target ams_change_filament command encoding (#891)."""
  4453. @pytest.fixture
  4454. def mqtt_client(self):
  4455. from unittest.mock import MagicMock
  4456. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4457. client = BambuMQTTClient(
  4458. ip_address="192.168.1.100",
  4459. serial_number="TEST123",
  4460. access_code="12345678",
  4461. )
  4462. # Pretend the MQTT layer is connected so the publish path is reached.
  4463. client._client = MagicMock()
  4464. client.state.connected = True
  4465. return client
  4466. @staticmethod
  4467. def _published(client) -> dict:
  4468. """Return the JSON of the most recent publish() call."""
  4469. last_call = client._client.publish.call_args_list[-1]
  4470. topic, payload, *_ = last_call.args
  4471. return json.loads(payload)
  4472. def test_ams_slot_uses_local_index_and_minus_one_temps(self, mqtt_client):
  4473. """tray_id=5 → ams_id=1, slot_id=1, target=5, curr/tar=-1."""
  4474. assert mqtt_client.ams_load_filament(5) is True
  4475. cmd = self._published(mqtt_client)["print"]
  4476. assert cmd["command"] == "ams_change_filament"
  4477. assert cmd["ams_id"] == 1
  4478. assert cmd["slot_id"] == 1
  4479. assert cmd["target"] == 5
  4480. assert cmd["curr_temp"] == -1
  4481. assert cmd["tar_temp"] == -1
  4482. def test_external_left_keeps_legacy_encoding(self, mqtt_client):
  4483. """tray_id=254 → ams_id=255, slot_id=254, target=254, curr/tar=-1.
  4484. This is the original capture from a single-extruder printer; preserved
  4485. verbatim so existing single-external setups don't regress.
  4486. """
  4487. assert mqtt_client.ams_load_filament(254) is True
  4488. cmd = self._published(mqtt_client)["print"]
  4489. assert cmd["ams_id"] == 255
  4490. assert cmd["slot_id"] == 254
  4491. assert cmd["target"] == 254
  4492. assert cmd["curr_temp"] == -1
  4493. assert cmd["tar_temp"] == -1
  4494. def test_external_right_uses_extruder_index_and_actual_temp(self, mqtt_client):
  4495. """tray_id=255 → captured BambuStudio shape on dual-nozzle H2D:
  4496. ams_id=255, slot_id=0 (right extruder), target=255, curr/tar = right
  4497. nozzle temp.
  4498. """
  4499. # Simulate a heated right nozzle.
  4500. mqtt_client.state.temperatures["nozzle_2"] = 215.0
  4501. assert mqtt_client.ams_load_filament(255) is True
  4502. cmd = self._published(mqtt_client)["print"]
  4503. assert cmd["ams_id"] == 255
  4504. assert cmd["slot_id"] == 0
  4505. assert cmd["target"] == 255
  4506. assert cmd["curr_temp"] == 215
  4507. assert cmd["tar_temp"] == 215
  4508. def test_external_right_falls_back_when_nozzle_cold(self, mqtt_client):
  4509. """If the right nozzle reports < 180 °C, fall back to a sane default
  4510. so the printer accepts the command rather than rejecting it on a
  4511. nonsensical temperature.
  4512. """
  4513. mqtt_client.state.temperatures["nozzle_2"] = 25.0
  4514. assert mqtt_client.ams_load_filament(255) is True
  4515. cmd = self._published(mqtt_client)["print"]
  4516. assert cmd["curr_temp"] == 215
  4517. assert cmd["tar_temp"] == 215
  4518. def test_returns_false_when_disconnected(self, mqtt_client):
  4519. """Disconnected client must not publish anything."""
  4520. mqtt_client.state.connected = False
  4521. assert mqtt_client.ams_load_filament(0) is False
  4522. mqtt_client._client.publish.assert_not_called()
  4523. class TestAmsFilamentSettingExternalSpoolEncoding:
  4524. """Encoding of `ams_filament_setting` / `reset_ams_slot` for the external spool.
  4525. Regression coverage for #1279. The encoding is verified against a captured
  4526. BambuStudio → X1C exchange (May 2026):
  4527. REQ {"command":"ams_filament_setting","ams_id":255,"tray_id":254,"slot_id":0,...}
  4528. REP {"result":"success",...}
  4529. The previous code sent `tray_id: 0` for the single-external case, which the
  4530. P1S in #1279 rejected with `result: "fail"`.
  4531. """
  4532. @pytest.fixture
  4533. def mqtt_client(self):
  4534. from unittest.mock import MagicMock
  4535. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4536. client = BambuMQTTClient(
  4537. ip_address="192.168.1.100",
  4538. serial_number="TEST123",
  4539. access_code="12345678",
  4540. )
  4541. client._client = MagicMock()
  4542. client.state.connected = True
  4543. return client
  4544. def _published(self, mqtt_client):
  4545. call_args = mqtt_client._client.publish.call_args
  4546. return json.loads(call_args[0][1])["print"]
  4547. def test_single_external_uses_tray_id_254(self, mqtt_client):
  4548. """X1C/P1S/A1 (single external slot): ams_id=255, tray_id=254, slot_id=0."""
  4549. # Simulate a single-external printer: vt_tray is a single-element list.
  4550. mqtt_client.state.raw_data = {"vt_tray": [{"id": "255"}]}
  4551. assert mqtt_client.ams_set_filament_setting(
  4552. ams_id=255,
  4553. tray_id=0,
  4554. tray_info_idx="GFL99",
  4555. tray_type="PLA",
  4556. tray_sub_brands="Generic PLA",
  4557. tray_color="000000FF",
  4558. nozzle_temp_min=190,
  4559. nozzle_temp_max=230,
  4560. )
  4561. cmd = self._published(mqtt_client)
  4562. assert cmd["command"] == "ams_filament_setting"
  4563. assert cmd["ams_id"] == 255
  4564. assert cmd["tray_id"] == 254, (
  4565. "Single-external `ams_filament_setting` must send tray_id=254 "
  4566. "(verified via BambuStudio→X1C capture). Sending tray_id=0 "
  4567. "is what the P1S in #1279 rejects."
  4568. )
  4569. assert cmd["slot_id"] == 0
  4570. def test_single_external_reset_uses_tray_id_254(self, mqtt_client):
  4571. """reset_ams_slot shares the convention — same encoding."""
  4572. mqtt_client.state.raw_data = {"vt_tray": [{"id": "255"}]}
  4573. assert mqtt_client.reset_ams_slot(ams_id=255, tray_id=0)
  4574. cmd = self._published(mqtt_client)
  4575. assert cmd["command"] == "ams_filament_setting"
  4576. assert cmd["ams_id"] == 255
  4577. assert cmd["tray_id"] == 254
  4578. assert cmd["slot_id"] == 0
  4579. # Reset clears the filament identity
  4580. assert cmd["tray_info_idx"] == ""
  4581. assert cmd["tray_type"] == ""
  4582. def test_regular_ams_tray_unchanged(self, mqtt_client):
  4583. """Regular AMS slots (ams_id <= 3) keep their existing encoding."""
  4584. mqtt_client.state.raw_data = {"vt_tray": []}
  4585. assert mqtt_client.ams_set_filament_setting(
  4586. ams_id=0,
  4587. tray_id=2,
  4588. tray_info_idx="GFA01",
  4589. tray_type="PLA",
  4590. tray_sub_brands="PLA Matte",
  4591. tray_color="FFFFFFFF",
  4592. nozzle_temp_min=190,
  4593. nozzle_temp_max=230,
  4594. )
  4595. cmd = self._published(mqtt_client)
  4596. assert cmd["ams_id"] == 0
  4597. assert cmd["tray_id"] == 2
  4598. assert cmd["slot_id"] == 2
  4599. def test_ams_ht_unchanged(self, mqtt_client):
  4600. """AMS-HT (ams_id >= 128) keeps its single-tray-per-unit encoding."""
  4601. mqtt_client.state.raw_data = {"vt_tray": []}
  4602. assert mqtt_client.ams_set_filament_setting(
  4603. ams_id=128,
  4604. tray_id=0,
  4605. tray_info_idx="GFA01",
  4606. tray_type="PLA",
  4607. tray_sub_brands="PLA Matte",
  4608. tray_color="FFFFFFFF",
  4609. nozzle_temp_min=190,
  4610. nozzle_temp_max=230,
  4611. )
  4612. cmd = self._published(mqtt_client)
  4613. assert cmd["ams_id"] == 128
  4614. assert cmd["tray_id"] == 0
  4615. assert cmd["slot_id"] == 0
  4616. def test_dual_external_left_keeps_legacy_encoding(self, mqtt_client):
  4617. """H2D dual-external (`vt_tray` length > 1): not in the X1C capture, so
  4618. left at the legacy `mqtt_tray_id = 0` until verified separately."""
  4619. mqtt_client.state.raw_data = {"vt_tray": [{"id": "254"}, {"id": "255"}]}
  4620. assert mqtt_client.ams_set_filament_setting(
  4621. ams_id=255,
  4622. tray_id=0, # Ext-L
  4623. tray_info_idx="GFA01",
  4624. tray_type="PLA",
  4625. tray_sub_brands="PLA Matte",
  4626. tray_color="FFFFFFFF",
  4627. nozzle_temp_min=190,
  4628. nozzle_temp_max=230,
  4629. )
  4630. cmd = self._published(mqtt_client)
  4631. # Ext-L → mqtt_ams_id = 254
  4632. assert cmd["ams_id"] == 254
  4633. # tray_id stays at 0 for dual external; this pins current behavior so
  4634. # a future capture-driven change shows up in the diff.
  4635. assert cmd["tray_id"] == 0
  4636. assert cmd["slot_id"] == 0
  4637. class TestDryingCompleteCallback:
  4638. """#1349 — fires ``on_drying_complete(ams_id)`` on a dry_time falling edge."""
  4639. @pytest.fixture
  4640. def mqtt_client(self):
  4641. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4642. events: list[int] = []
  4643. client = BambuMQTTClient(
  4644. ip_address="192.168.1.100",
  4645. serial_number="TEST-DRYING",
  4646. access_code="12345678",
  4647. on_drying_complete=events.append,
  4648. )
  4649. client._drying_events = events # Expose for assertions
  4650. return client
  4651. def test_falling_edge_fires_callback(self, mqtt_client):
  4652. """First push reports drying active, second reports drying done."""
  4653. # Push 1: AMS 0 drying with 60 minutes remaining.
  4654. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 60, "tray": []}]})
  4655. assert mqtt_client._drying_events == []
  4656. # Push 2: dry_time hits 0 → callback fires with the AMS id.
  4657. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4658. assert mqtt_client._drying_events == [0]
  4659. def test_no_fire_when_dry_time_never_started(self, mqtt_client):
  4660. """dry_time = 0 across consecutive pushes does NOT fire — there was
  4661. no drying cycle to finish. Guards against the seed-from-zero false
  4662. positive on startup."""
  4663. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4664. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4665. assert mqtt_client._drying_events == []
  4666. def test_falling_edge_fires_once(self, mqtt_client):
  4667. """Subsequent zero-pushes after the edge don't refire the callback."""
  4668. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 30, "tray": []}]})
  4669. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4670. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4671. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4672. assert mqtt_client._drying_events == [0]
  4673. def test_per_ams_tracking(self, mqtt_client):
  4674. """Two AMS units finishing drying at different times each fire once
  4675. — the falling-edge state is keyed per AMS id."""
  4676. # Both start drying.
  4677. mqtt_client._handle_ams_data(
  4678. {"ams": [{"id": "0", "dry_time": 30, "tray": []}, {"id": "1", "dry_time": 30, "tray": []}]}
  4679. )
  4680. # AMS 0 finishes, AMS 1 still drying.
  4681. mqtt_client._handle_ams_data(
  4682. {"ams": [{"id": "0", "dry_time": 0, "tray": []}, {"id": "1", "dry_time": 15, "tray": []}]}
  4683. )
  4684. assert mqtt_client._drying_events == [0]
  4685. # AMS 1 finishes.
  4686. mqtt_client._handle_ams_data(
  4687. {"ams": [{"id": "0", "dry_time": 0, "tray": []}, {"id": "1", "dry_time": 0, "tray": []}]}
  4688. )
  4689. assert mqtt_client._drying_events == [0, 1]
  4690. def test_restart_drying_after_completion_refires_callback(self, mqtt_client):
  4691. """A new drying cycle after the previous one finished fires the
  4692. callback again on its own falling edge — covers the user manually
  4693. starting a second dry from the UI."""
  4694. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 30, "tray": []}]})
  4695. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4696. # New cycle starts.
  4697. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 45, "tray": []}]})
  4698. # And finishes.
  4699. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4700. assert mqtt_client._drying_events == [0, 0]
  4701. def test_tray_only_partial_does_not_fake_completion(self, mqtt_client):
  4702. """#1462 — a tray-bearing partial update that omits dry_time must not
  4703. be read as dry_time=0. The pre-fix merge dropped dry_time on such
  4704. partials, so the falling-edge detector saw a 60→0 edge and fired a
  4705. false 'drying complete' seconds after drying started — which armed
  4706. smart-plug auto-off and killed the printer mid-cycle."""
  4707. # Drying active, 60 minutes remaining.
  4708. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 60, "tray": []}]})
  4709. assert mqtt_client._drying_events == []
  4710. # Printer sends a tray-bearing partial carrying NO dry_time field.
  4711. mqtt_client._handle_ams_data({"ams": [{"id": "0", "tray": []}]})
  4712. assert mqtt_client._drying_events == []
  4713. # dry_time survived the partial in the merged AMS state.
  4714. assert mqtt_client.state.raw_data["ams"][0]["dry_time"] == 60
  4715. # Drying genuinely finishes → the real edge still fires exactly once.
  4716. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  4717. assert mqtt_client._drying_events == [0]
  4718. class TestPrintRunningObservedCallback:
  4719. """#1485 follow-up: on_print_running_observed fires the FIRST time we
  4720. see ``state == RUNNING`` for a printer whose print started before
  4721. Bambuddy came up. It lets main.py capture a timelapse baseline at
  4722. restart-recovery time — when on_print_start was suppressed by the
  4723. #1304 first-push guard. Must NOT fire when on_print_start handles the
  4724. transition (avoids double-capture), and must NOT fire again after
  4725. the first observation in the same session.
  4726. """
  4727. @pytest.fixture
  4728. def mqtt_client(self):
  4729. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4730. return BambuMQTTClient(
  4731. ip_address="192.168.1.100",
  4732. serial_number="TEST123",
  4733. access_code="12345678",
  4734. )
  4735. def test_fires_on_first_running_push_after_startup(self, mqtt_client):
  4736. """First push the client sees has _previous_gcode_state=None, so the
  4737. #1304 guard suppresses on_print_start. on_print_running_observed
  4738. must fire instead so the consumer can recover."""
  4739. start_calls: list[dict] = []
  4740. running_observed_calls: list[dict] = []
  4741. mqtt_client.on_print_start = lambda data: start_calls.append(data)
  4742. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  4743. # Pristine state — exactly what we have right after BambuMQTTClient
  4744. # construction following a Bambuddy restart.
  4745. mqtt_client._was_running = False
  4746. mqtt_client._previous_gcode_state = None
  4747. mqtt_client._process_message(
  4748. {
  4749. "print": {
  4750. "gcode_state": "RUNNING",
  4751. "gcode_file": "/data/Metadata/test_print.gcode",
  4752. "subtask_name": "Test_Print",
  4753. }
  4754. }
  4755. )
  4756. assert start_calls == [], "on_print_start must be suppressed by the #1304 guard"
  4757. assert len(running_observed_calls) == 1
  4758. assert running_observed_calls[0]["filename"] == "/data/Metadata/test_print.gcode"
  4759. assert running_observed_calls[0]["subtask_name"] == "Test_Print"
  4760. def test_does_not_fire_when_print_start_fires(self, mqtt_client):
  4761. """Normal print start (a real state transition from non-RUNNING to
  4762. RUNNING) goes through on_print_start; on_print_running_observed
  4763. must stay quiet so the consumer doesn't capture the baseline twice."""
  4764. start_calls: list[dict] = []
  4765. running_observed_calls: list[dict] = []
  4766. mqtt_client.on_print_start = lambda data: start_calls.append(data)
  4767. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  4768. mqtt_client._was_running = False
  4769. mqtt_client._previous_gcode_state = "IDLE" # Not None — past the #1304 guard
  4770. mqtt_client._process_message(
  4771. {
  4772. "print": {
  4773. "gcode_state": "RUNNING",
  4774. "gcode_file": "/data/Metadata/test_print.gcode",
  4775. "subtask_name": "Test_Print",
  4776. }
  4777. }
  4778. )
  4779. assert len(start_calls) == 1, "on_print_start should fire on a real start transition"
  4780. assert running_observed_calls == [], "on_print_running_observed must not double up with on_print_start"
  4781. def test_fires_only_once_per_session(self, mqtt_client):
  4782. """Subsequent RUNNING pushes in the same session must not re-fire the
  4783. callback — the baseline only needs to be captured once, the consumer
  4784. treats repeat calls as a hint to skip via the in-memory dict guard."""
  4785. running_observed_calls: list[dict] = []
  4786. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  4787. mqtt_client._was_running = False
  4788. mqtt_client._previous_gcode_state = None
  4789. msg = {
  4790. "print": {
  4791. "gcode_state": "RUNNING",
  4792. "gcode_file": "/data/Metadata/test_print.gcode",
  4793. "subtask_name": "Test_Print",
  4794. }
  4795. }
  4796. mqtt_client._process_message(msg)
  4797. mqtt_client._process_message(msg)
  4798. mqtt_client._process_message(msg)
  4799. assert len(running_observed_calls) == 1
  4800. def test_does_not_fire_when_not_running(self, mqtt_client):
  4801. """An IDLE / PREPARE / FINISH first-push must not trigger the
  4802. restart-recovery path — there's no print to baseline."""
  4803. running_observed_calls: list[dict] = []
  4804. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  4805. mqtt_client._was_running = False
  4806. mqtt_client._previous_gcode_state = None
  4807. mqtt_client._process_message(
  4808. {
  4809. "print": {
  4810. "gcode_state": "IDLE",
  4811. "gcode_file": "",
  4812. "subtask_name": "",
  4813. }
  4814. }
  4815. )
  4816. assert running_observed_calls == []
  4817. def test_does_not_fire_without_current_file(self, mqtt_client):
  4818. """RUNNING with no file is ill-formed (firmware glitch / transient).
  4819. We need ``current_file`` to find the right archive, so skip the
  4820. callback rather than fire it with a meaningless payload."""
  4821. running_observed_calls: list[dict] = []
  4822. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  4823. mqtt_client._was_running = False
  4824. mqtt_client._previous_gcode_state = None
  4825. mqtt_client._process_message(
  4826. {
  4827. "print": {
  4828. "gcode_state": "RUNNING",
  4829. "gcode_file": "",
  4830. "subtask_name": "",
  4831. }
  4832. }
  4833. )
  4834. assert running_observed_calls == []
  4835. def test_safe_when_callback_not_set(self, mqtt_client):
  4836. """No callback configured → silently skip; no AttributeError on the
  4837. firing branch."""
  4838. mqtt_client.on_print_running_observed = None
  4839. mqtt_client._was_running = False
  4840. mqtt_client._previous_gcode_state = None
  4841. # Should not raise.
  4842. mqtt_client._process_message(
  4843. {
  4844. "print": {
  4845. "gcode_state": "RUNNING",
  4846. "gcode_file": "/data/Metadata/test_print.gcode",
  4847. "subtask_name": "Test_Print",
  4848. }
  4849. }
  4850. )
  4851. assert mqtt_client._was_running is True
  4852. def test_payload_shape_matches_print_start(self, mqtt_client):
  4853. """The payload shape must mirror on_print_start so main.py's
  4854. consumer can reuse the same dict fields (filename / subtask_name /
  4855. remaining_time / raw_data / ams_mapping). Test pins the keys."""
  4856. running_observed_calls: list[dict] = []
  4857. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  4858. mqtt_client._was_running = False
  4859. mqtt_client._previous_gcode_state = None
  4860. mqtt_client._process_message(
  4861. {
  4862. "print": {
  4863. "gcode_state": "RUNNING",
  4864. "gcode_file": "/data/Metadata/test_print.gcode",
  4865. "subtask_name": "Test_Print",
  4866. "mc_remaining_time": 42,
  4867. }
  4868. }
  4869. )
  4870. assert len(running_observed_calls) == 1
  4871. payload = running_observed_calls[0]
  4872. assert set(payload.keys()) == {
  4873. "filename",
  4874. "subtask_name",
  4875. "remaining_time",
  4876. "raw_data",
  4877. "ams_mapping",
  4878. }
  4879. class TestTotalLayersPreservation:
  4880. """#1771: P1S firmware resets `total_layer_num` to 0 at print end. Without
  4881. this guard, the usage tracker's split path saw `state.total_layers = 0` at
  4882. completion and dumped the whole print onto the last spool.
  4883. These tests pin the preservation pattern (mirror of `_last_valid_layer_num`)
  4884. and the explicit reset on new print start so the previous print's total
  4885. can't bleed into the next.
  4886. """
  4887. @pytest.fixture
  4888. def mqtt_client(self):
  4889. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4890. client = BambuMQTTClient(
  4891. ip_address="192.168.1.100",
  4892. serial_number="TEST123",
  4893. access_code="12345678",
  4894. )
  4895. return client
  4896. def test_nonzero_total_layer_num_sets_state(self, mqtt_client):
  4897. # Baseline: a fresh push with the slicer's total updates state.total_layers.
  4898. mqtt_client._process_message({"print": {"total_layer_num": 260}})
  4899. assert mqtt_client.state.total_layers == 260
  4900. def test_zero_total_layer_num_does_not_clobber_cached_value(self, mqtt_client):
  4901. # Firmware-reset frame: total_layer_num=0 arrives mid- or end-of-print.
  4902. # The guard must NOT overwrite the previously-captured 260.
  4903. mqtt_client._process_message({"print": {"total_layer_num": 260}})
  4904. mqtt_client._process_message({"print": {"total_layer_num": 0}})
  4905. assert mqtt_client.state.total_layers == 260
  4906. def test_print_start_explicitly_resets_total_layers(self, mqtt_client):
  4907. # Without the explicit reset on print start, the previous print's total
  4908. # would persist into the new print until its first total_layer_num push
  4909. # arrived — which is exactly the kind of cross-print bleed the
  4910. # preservation guard above otherwise opens up.
  4911. mqtt_client._process_message({"print": {"total_layer_num": 260}})
  4912. assert mqtt_client.state.total_layers == 260
  4913. # Simulate the new-print-start trigger shape (is_new_print path):
  4914. # state was previously RUNNING on an old file; now we observe a
  4915. # different file going RUNNING.
  4916. mqtt_client._previous_gcode_state = "RUNNING"
  4917. mqtt_client._previous_gcode_file = "/data/Metadata/old_print.gcode"
  4918. mqtt_client._was_running = True
  4919. mqtt_client._process_message(
  4920. {
  4921. "print": {
  4922. "gcode_state": "RUNNING",
  4923. "gcode_file": "/data/Metadata/new_print.gcode",
  4924. "subtask_name": "new_print",
  4925. }
  4926. }
  4927. )
  4928. assert mqtt_client.state.total_layers == 0
  4929. class TestAmsFilamentBackupHoldTimer:
  4930. """Regression: stale push_status arriving within the hold window after a
  4931. toggle command MUST NOT flip ams_filament_backup back to the printer's
  4932. old cfg. Same race-guard pattern xcam uses for spaghetti / first-layer
  4933. detector settings.
  4934. """
  4935. @pytest.fixture
  4936. def mqtt_client(self):
  4937. from unittest.mock import MagicMock
  4938. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4939. client = BambuMQTTClient(
  4940. ip_address="192.168.1.100",
  4941. serial_number="TEST123",
  4942. access_code="12345678",
  4943. )
  4944. # Pretend we're connected so _set_print_option actually publishes.
  4945. client.state.connected = True
  4946. client._client = MagicMock()
  4947. return client
  4948. def test_cfg_push_with_old_value_is_ignored_during_hold(self, mqtt_client):
  4949. # User toggled ON via badge → command sent → state optimistically set.
  4950. mqtt_client.set_ams_filament_backup(True)
  4951. assert mqtt_client.state.ams_filament_backup is True
  4952. # Within the 3 s hold window, a stale push_status arrives still showing
  4953. # the printer's old cfg (bit 18 cleared). The parser must NOT flip our
  4954. # optimistic state back to OFF — otherwise the badge flickers ON→OFF→ON.
  4955. mqtt_client._process_message({"print": {"cfg": "C0340BC219"}}) # bit18=0
  4956. assert mqtt_client.state.ams_filament_backup is True
  4957. def test_cfg_push_after_hold_expires_overrides_state(self, mqtt_client):
  4958. # After the hold window, the printer's real cfg becomes authoritative
  4959. # so a genuine slicer-side or display toggle that we did NOT initiate
  4960. # propagates correctly.
  4961. mqtt_client.set_ams_filament_backup(True)
  4962. mqtt_client._xcam_hold_start["print_option_auto_switch_filament"] = time.time() - 10.0
  4963. mqtt_client._process_message({"print": {"cfg": "C0340BC219"}}) # bit18=0
  4964. assert mqtt_client.state.ams_filament_backup is False
  4965. def test_cfg_push_with_matching_value_during_hold_is_a_noop(self, mqtt_client):
  4966. # Same-value push during hold doesn't trigger the change branch at all
  4967. # (no state mutation, no log spam, hold timer stays armed).
  4968. mqtt_client.set_ams_filament_backup(True)
  4969. before_hold = mqtt_client._xcam_hold_start["print_option_auto_switch_filament"]
  4970. mqtt_client._process_message({"print": {"cfg": "C0340FC219"}}) # bit18=1
  4971. assert mqtt_client.state.ams_filament_backup is True
  4972. # Hold timer still armed — sub-second push didn't reset it.
  4973. assert mqtt_client._xcam_hold_start["print_option_auto_switch_filament"] == before_hold
  4974. # ---------------------------------------------------------------------------
  4975. # 2c. Single-nozzle H2S — external-spool tray_now override (#1822)
  4976. # ---------------------------------------------------------------------------
  4977. class TestTrayNowH2SExternalSpoolOverride:
  4978. """H2S firmware reports tray_now as the AMS's idle slot (typically 0)
  4979. instead of 254 when the active feed is the external spool.
  4980. Bambuddy detects the all-external case via the slicer-captured
  4981. ams_mapping (every entry == -1) and promotes tray_now to 254 so the
  4982. UI active-tray highlight matches the real feed.
  4983. The override is intentionally narrow:
  4984. * only fires when ams_mapping is captured AND every entry is -1
  4985. * does not touch mixed prints ([5, -1]) or AMS-only prints ([5])
  4986. * does not fire when no ams_mapping is captured (printer-screen start)
  4987. """
  4988. @pytest.fixture
  4989. def mqtt_client(self):
  4990. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4991. return BambuMQTTClient(
  4992. ip_address="192.168.1.100",
  4993. serial_number="TEST_H2S",
  4994. access_code="12345678",
  4995. )
  4996. def test_all_external_mapping_promotes_tray_now_to_254(self, mqtt_client):
  4997. """Reporter's scenario: H2S, single nozzle, captured ams_mapping=[-1],
  4998. firmware sends tray_now=0 -> Bambuddy promotes to 254."""
  4999. mqtt_client._captured_ams_mapping = [-1]
  5000. mqtt_client._process_message(_ams_payload(0))
  5001. assert mqtt_client.state.tray_now == 254
  5002. def test_multi_external_mapping_also_promotes(self, mqtt_client):
  5003. """Multi-filament print, every filament mapped to external. Still
  5004. all-external -> still promotes."""
  5005. mqtt_client._captured_ams_mapping = [-1, -1, -1]
  5006. mqtt_client._process_message(_ams_payload(0))
  5007. assert mqtt_client.state.tray_now == 254
  5008. def test_ams_only_mapping_does_not_override(self, mqtt_client):
  5009. """ams_mapping=[5] (AMS slot 5 only) -> firmware value trusted as-is.
  5010. Without the all-external guard, this would falsely override real
  5011. AMS-slot prints."""
  5012. mqtt_client._captured_ams_mapping = [5]
  5013. mqtt_client._process_message(_ams_payload(0))
  5014. assert mqtt_client.state.tray_now == 0
  5015. def test_mixed_mapping_does_not_override(self, mqtt_client):
  5016. """Mixed mapping (AMS slot 5 + external): we have no evidence the
  5017. firmware misreports mid-print swaps, so leave tray_now alone."""
  5018. mqtt_client._captured_ams_mapping = [5, -1]
  5019. mqtt_client._process_message(_ams_payload(0))
  5020. assert mqtt_client.state.tray_now == 0
  5021. def test_no_captured_mapping_does_not_override(self, mqtt_client):
  5022. """Prints started from the printer screen (or before Bambuddy
  5023. connected) have no captured ams_mapping. Behaviour unchanged from
  5024. pre-#1822 — we accept the wrong value rather than guess."""
  5025. mqtt_client._captured_ams_mapping = None
  5026. mqtt_client._process_message(_ams_payload(0))
  5027. assert mqtt_client.state.tray_now == 0
  5028. def test_empty_captured_mapping_does_not_override(self, mqtt_client):
  5029. """Empty list (defensive — should not happen in practice but
  5030. all([]) returns True). Treat as no signal, not as all-external."""
  5031. mqtt_client._captured_ams_mapping = []
  5032. mqtt_client._process_message(_ams_payload(0))
  5033. assert mqtt_client.state.tray_now == 0
  5034. def test_unloaded_after_print_still_resolves_correctly(self, mqtt_client):
  5035. """When the firmware unloads (tray_now=255), the override is skipped
  5036. because the branch only fires for tray_now in 0-3."""
  5037. mqtt_client._captured_ams_mapping = [-1]
  5038. mqtt_client._process_message(_ams_payload(0))
  5039. assert mqtt_client.state.tray_now == 254
  5040. mqtt_client._process_message(_ams_payload(255))
  5041. assert mqtt_client.state.tray_now == 255