test_bambu_mqtt.py 310 KB

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