test_bambu_mqtt.py 323 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832
  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 TestRequestTopicIsCaptured:
  1701. """The MQTT debug log has to show commands going *to* the printer.
  1702. Bambuddy subscribes to the request topic as well as the report topic, so
  1703. every command the printer is given crosses this client -- ours echoed back
  1704. by the broker, and whatever Bambu Studio sends. Those messages used to
  1705. return from _on_message before the logging block, which left a capture able
  1706. to prove only what the printer said and never what it was told. Answering
  1707. "what does Studio put in this field?" from a user's log depends on it
  1708. (#2774).
  1709. """
  1710. @pytest.fixture
  1711. def mqtt_client(self):
  1712. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1713. client = BambuMQTTClient(
  1714. ip_address="192.168.1.100",
  1715. serial_number="TEST123",
  1716. access_code="12345678",
  1717. )
  1718. client.enable_logging(True)
  1719. return client
  1720. @staticmethod
  1721. def _deliver(client, topic, payload):
  1722. class _Msg:
  1723. pass
  1724. msg = _Msg()
  1725. msg.topic = topic
  1726. msg.payload = json.dumps(payload).encode()
  1727. client._on_message(None, None, msg)
  1728. def test_a_command_on_the_request_topic_is_logged(self, mqtt_client):
  1729. payload = {
  1730. "print": {
  1731. "command": "ams_filament_drying",
  1732. "ams_id": 128,
  1733. "temp": 45,
  1734. "duration": 12,
  1735. "filament": "PLA",
  1736. }
  1737. }
  1738. self._deliver(mqtt_client, mqtt_client.topic_publish, payload)
  1739. logs = mqtt_client.get_logs()
  1740. assert len(logs) == 1
  1741. assert logs[0].topic == mqtt_client.topic_publish
  1742. # Filed with the commands rather than with telemetry: the direction
  1743. # filter is how someone finds what was sent to the printer.
  1744. assert logs[0].direction == "out"
  1745. assert logs[0].payload == payload
  1746. def test_the_payload_is_kept_whole(self, mqtt_client):
  1747. """The point of the capture is the fields we don't parse."""
  1748. payload = {"print": {"command": "ams_filament_drying", "unparsed_field": "keep me"}}
  1749. self._deliver(mqtt_client, mqtt_client.topic_publish, payload)
  1750. assert mqtt_client.get_logs()[0].payload["print"]["unparsed_field"] == "keep me"
  1751. def test_request_topic_messages_are_still_parsed(self, mqtt_client):
  1752. """Logging is additive -- the ams_mapping capture must survive it."""
  1753. self._deliver(
  1754. mqtt_client,
  1755. mqtt_client.topic_publish,
  1756. {"print": {"command": "project_file", "ams_mapping": [0, 4, -1, -1]}},
  1757. )
  1758. assert mqtt_client._captured_ams_mapping == [0, 4, -1, -1]
  1759. assert len(mqtt_client.get_logs()) == 1
  1760. def test_nothing_is_logged_while_logging_is_off(self, mqtt_client):
  1761. mqtt_client.enable_logging(False)
  1762. self._deliver(
  1763. mqtt_client,
  1764. mqtt_client.topic_publish,
  1765. {"print": {"command": "project_file", "ams_mapping": [0, -1, -1, -1]}},
  1766. )
  1767. assert mqtt_client.get_logs() == []
  1768. assert mqtt_client._captured_ams_mapping == [0, -1, -1, -1]
  1769. def test_the_report_topic_is_still_logged_as_incoming(self, mqtt_client):
  1770. """Telemetry keeps its direction -- the two must stay distinguishable."""
  1771. self._deliver(mqtt_client, mqtt_client.topic_subscribe, {"print": {"gcode_state": "IDLE"}})
  1772. logs = mqtt_client.get_logs()
  1773. assert len(logs) == 1
  1774. assert logs[0].direction == "in"
  1775. class TestRequestTopicAmsMapping:
  1776. """Tests for capturing ams_mapping from the MQTT request topic."""
  1777. @pytest.fixture
  1778. def mqtt_client(self):
  1779. """Create a BambuMQTTClient instance for testing."""
  1780. from backend.app.services.bambu_mqtt import BambuMQTTClient
  1781. client = BambuMQTTClient(
  1782. ip_address="192.168.1.100",
  1783. serial_number="TEST123",
  1784. access_code="12345678",
  1785. )
  1786. return client
  1787. def test_captured_ams_mapping_initializes_to_none(self, mqtt_client):
  1788. """Verify _captured_ams_mapping starts as None."""
  1789. assert mqtt_client._captured_ams_mapping is None
  1790. def test_handle_request_message_captures_ams_mapping(self, mqtt_client):
  1791. """project_file command with ams_mapping stores the mapping."""
  1792. data = {
  1793. "print": {
  1794. "command": "project_file",
  1795. "ams_mapping": [0, 4, -1, -1],
  1796. "url": "ftp://192.168.1.100/test.3mf",
  1797. }
  1798. }
  1799. mqtt_client._handle_request_message(data)
  1800. assert mqtt_client._captured_ams_mapping == [0, 4, -1, -1]
  1801. def test_handle_request_message_ignores_non_print_commands(self, mqtt_client):
  1802. """Non-project_file commands don't store ams_mapping."""
  1803. data = {
  1804. "print": {
  1805. "command": "pause",
  1806. }
  1807. }
  1808. mqtt_client._handle_request_message(data)
  1809. assert mqtt_client._captured_ams_mapping is None
  1810. def test_handle_request_message_ignores_missing_ams_mapping(self, mqtt_client):
  1811. """project_file command without ams_mapping doesn't store anything."""
  1812. data = {
  1813. "print": {
  1814. "command": "project_file",
  1815. "url": "ftp://192.168.1.100/test.3mf",
  1816. }
  1817. }
  1818. mqtt_client._handle_request_message(data)
  1819. assert mqtt_client._captured_ams_mapping is None
  1820. def test_handle_request_message_ignores_non_dict_print(self, mqtt_client):
  1821. """Non-dict print value is safely ignored."""
  1822. data = {"print": "not_a_dict"}
  1823. mqtt_client._handle_request_message(data)
  1824. assert mqtt_client._captured_ams_mapping is None
  1825. def test_handle_request_message_ignores_missing_print(self, mqtt_client):
  1826. """Message without print key is safely ignored."""
  1827. data = {"pushing": {"command": "pushall"}}
  1828. mqtt_client._handle_request_message(data)
  1829. assert mqtt_client._captured_ams_mapping is None
  1830. def test_captured_mapping_overwrites_previous(self, mqtt_client):
  1831. """A new print command overwrites a previously captured mapping."""
  1832. mqtt_client._captured_ams_mapping = [0, -1, -1, -1]
  1833. data = {
  1834. "print": {
  1835. "command": "project_file",
  1836. "ams_mapping": [4, 8, -1, -1],
  1837. }
  1838. }
  1839. mqtt_client._handle_request_message(data)
  1840. assert mqtt_client._captured_ams_mapping == [4, 8, -1, -1]
  1841. def test_print_start_callback_includes_ams_mapping(self, mqtt_client):
  1842. """on_print_start callback data includes captured ams_mapping."""
  1843. start_data = {}
  1844. def on_start(data):
  1845. start_data.update(data)
  1846. mqtt_client.on_print_start = on_start
  1847. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  1848. # Seed a prior state so the first RUNNING push is treated as a real
  1849. # state transition rather than a Bambuddy-restart catch-up (#1304).
  1850. mqtt_client._previous_gcode_state = "IDLE"
  1851. # Trigger print start
  1852. mqtt_client._process_message(
  1853. {
  1854. "print": {
  1855. "gcode_state": "RUNNING",
  1856. "gcode_file": "/data/Metadata/test.gcode",
  1857. "subtask_name": "Test",
  1858. }
  1859. }
  1860. )
  1861. assert start_data.get("ams_mapping") == [0, 4, -1, -1]
  1862. def test_print_start_callback_ams_mapping_none_when_not_captured(self, mqtt_client):
  1863. """on_print_start callback has ams_mapping=None when no mapping captured."""
  1864. start_data = {}
  1865. def on_start(data):
  1866. start_data.update(data)
  1867. mqtt_client.on_print_start = on_start
  1868. # Seed a prior state so the first RUNNING push is treated as a real
  1869. # state transition rather than a Bambuddy-restart catch-up (#1304).
  1870. mqtt_client._previous_gcode_state = "IDLE"
  1871. mqtt_client._process_message(
  1872. {
  1873. "print": {
  1874. "gcode_state": "RUNNING",
  1875. "gcode_file": "/data/Metadata/test.gcode",
  1876. "subtask_name": "Test",
  1877. }
  1878. }
  1879. )
  1880. assert "ams_mapping" in start_data
  1881. assert start_data["ams_mapping"] is None
  1882. def test_first_running_push_after_bambuddy_restart_does_not_fire_print_start(self, mqtt_client):
  1883. """Regression for #1304: Bambuddy restart mid-print misfired plate check + archive.
  1884. When Bambuddy restarts while a print is already in progress, the freshly
  1885. constructed BambuMQTTClient has `_previous_gcode_state = None`. The first
  1886. push_status the printer sends reports `gcode_state: RUNNING`. Before the
  1887. fix, the (None → RUNNING) transition satisfied is_new_print's guard and
  1888. fired on_print_start, which then ran plate detection (objects on plate →
  1889. paused the live print) AND re-archived the file (duplicate archive).
  1890. With the fix in place the on_print_start callback must NOT be called for
  1891. this catch-up push, but `_was_running` still tracks the print so
  1892. completion detection works the same way as before.
  1893. """
  1894. start_data = {}
  1895. def on_start(data):
  1896. start_data.update(data)
  1897. mqtt_client.on_print_start = on_start
  1898. # Explicit: this simulates a fresh Bambuddy process attaching to a
  1899. # printer that's already in the middle of a print.
  1900. mqtt_client._previous_gcode_state = None
  1901. mqtt_client._was_running = False
  1902. mqtt_client._process_message(
  1903. {
  1904. "print": {
  1905. "gcode_state": "RUNNING",
  1906. "gcode_file": "/data/Metadata/big_print.gcode",
  1907. "subtask_name": "big_print",
  1908. }
  1909. }
  1910. )
  1911. assert start_data == {}, "on_print_start must not fire on Bambuddy-restart catch-up"
  1912. # Completion detection still needs to know we're tracking a running job.
  1913. assert mqtt_client._was_running is True
  1914. # And the state-update bookkeeping ran so the NEXT push won't keep
  1915. # treating the first RUNNING as fresh.
  1916. assert mqtt_client._previous_gcode_state == "RUNNING"
  1917. def test_print_complete_callback_includes_ams_mapping(self, mqtt_client):
  1918. """on_print_complete callback data includes captured ams_mapping."""
  1919. complete_data = {}
  1920. def on_complete(data):
  1921. complete_data.update(data)
  1922. mqtt_client.on_print_start = lambda d: None
  1923. mqtt_client.on_print_complete = on_complete
  1924. mqtt_client._captured_ams_mapping = [0, 9, -1, -1]
  1925. # Start print
  1926. mqtt_client._process_message(
  1927. {
  1928. "print": {
  1929. "gcode_state": "RUNNING",
  1930. "gcode_file": "/data/Metadata/test.gcode",
  1931. "subtask_name": "Test",
  1932. }
  1933. }
  1934. )
  1935. # Complete print
  1936. mqtt_client._process_message(
  1937. {
  1938. "print": {
  1939. "gcode_state": "FINISH",
  1940. "gcode_file": "/data/Metadata/test.gcode",
  1941. "subtask_name": "Test",
  1942. }
  1943. }
  1944. )
  1945. assert complete_data.get("ams_mapping") == [0, 9, -1, -1]
  1946. def test_captured_mapping_cleared_after_print_complete(self, mqtt_client):
  1947. """_captured_ams_mapping is reset to None after print completion."""
  1948. mqtt_client.on_print_start = lambda d: None
  1949. mqtt_client.on_print_complete = lambda d: None
  1950. mqtt_client._captured_ams_mapping = [0, 4, -1, -1]
  1951. # Start print
  1952. mqtt_client._process_message(
  1953. {
  1954. "print": {
  1955. "gcode_state": "RUNNING",
  1956. "gcode_file": "/data/Metadata/test.gcode",
  1957. "subtask_name": "Test",
  1958. }
  1959. }
  1960. )
  1961. # Complete print
  1962. mqtt_client._process_message(
  1963. {
  1964. "print": {
  1965. "gcode_state": "FINISH",
  1966. "gcode_file": "/data/Metadata/test.gcode",
  1967. "subtask_name": "Test",
  1968. }
  1969. }
  1970. )
  1971. assert mqtt_client._captured_ams_mapping is None
  1972. def test_full_flow_capture_and_deliver(self, mqtt_client):
  1973. """Full flow: slicer sends print command → MQTT captures mapping → completion delivers it."""
  1974. complete_data = {}
  1975. def on_complete(data):
  1976. complete_data.update(data)
  1977. mqtt_client.on_print_start = lambda d: None
  1978. mqtt_client.on_print_complete = on_complete
  1979. # 1. Slicer sends print command (captured from request topic)
  1980. mqtt_client._handle_request_message(
  1981. {
  1982. "print": {
  1983. "command": "project_file",
  1984. "ams_mapping": [4, 9, -1, -1],
  1985. "url": "ftp://192.168.1.100/model.3mf",
  1986. }
  1987. }
  1988. )
  1989. assert mqtt_client._captured_ams_mapping == [4, 9, -1, -1]
  1990. # 2. Printer reports RUNNING
  1991. mqtt_client._process_message(
  1992. {
  1993. "print": {
  1994. "gcode_state": "RUNNING",
  1995. "gcode_file": "/data/Metadata/model.gcode",
  1996. "subtask_name": "Model",
  1997. }
  1998. }
  1999. )
  2000. # 3. Printer reports FINISH
  2001. mqtt_client._process_message(
  2002. {
  2003. "print": {
  2004. "gcode_state": "FINISH",
  2005. "gcode_file": "/data/Metadata/model.gcode",
  2006. "subtask_name": "Model",
  2007. }
  2008. }
  2009. )
  2010. assert complete_data["ams_mapping"] == [4, 9, -1, -1]
  2011. assert complete_data["status"] == "completed"
  2012. # Mapping cleared after completion
  2013. assert mqtt_client._captured_ams_mapping is None
  2014. # ---------------------------------------------------------------------------
  2015. # tray_now disambiguation helpers
  2016. # ---------------------------------------------------------------------------
  2017. def _ams_payload(tray_now, ams_units=None, tray_exist_bits=None, ams_exist_bits=None):
  2018. """Build minimal print.ams payload for tray_now disambiguation tests."""
  2019. ams = {"tray_now": str(tray_now)}
  2020. if ams_units is not None:
  2021. ams["ams"] = ams_units
  2022. if tray_exist_bits is not None:
  2023. ams["tray_exist_bits"] = tray_exist_bits
  2024. if ams_exist_bits is not None:
  2025. ams["ams_exist_bits"] = ams_exist_bits
  2026. return {"print": {"ams": ams}}
  2027. def _extruder_info_payload(extruders):
  2028. """Build device.extruder.info payload (dual-nozzle detection + snow).
  2029. Each entry in *extruders* is a dict with at least ``id`` and ``snow``.
  2030. """
  2031. return {
  2032. "print": {
  2033. "device": {
  2034. "extruder": {
  2035. "info": extruders,
  2036. }
  2037. }
  2038. }
  2039. }
  2040. def _extruder_state_payload(state_val):
  2041. """Build device.extruder.state payload (active extruder via bit 8)."""
  2042. return {
  2043. "print": {
  2044. "device": {
  2045. "extruder": {
  2046. "state": state_val,
  2047. }
  2048. }
  2049. }
  2050. }
  2051. # ---------------------------------------------------------------------------
  2052. # 1. Single-nozzle X1E — direct passthrough
  2053. # ---------------------------------------------------------------------------
  2054. class TestTrayNowSingleNozzleX1E:
  2055. """Single-nozzle, 1 AMS — tray_now is a direct passthrough."""
  2056. @pytest.fixture
  2057. def mqtt_client(self):
  2058. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2059. return BambuMQTTClient(
  2060. ip_address="192.168.1.100",
  2061. serial_number="TEST_X1E",
  2062. access_code="12345678",
  2063. )
  2064. def test_tray_now_direct_passthrough_slot_0_to_3(self, mqtt_client):
  2065. """Each tray_now 0-3 maps 1:1 on single-nozzle printers."""
  2066. for slot in range(4):
  2067. mqtt_client._process_message(_ams_payload(slot))
  2068. assert mqtt_client.state.tray_now == slot
  2069. def test_tray_now_255_means_unloaded(self, mqtt_client):
  2070. """tray_now=255 means no filament loaded."""
  2071. mqtt_client._process_message(_ams_payload(255))
  2072. assert mqtt_client.state.tray_now == 255
  2073. def test_single_extruder_does_not_trigger_dual_nozzle(self, mqtt_client):
  2074. """device.extruder.info with 1 entry must NOT set _is_dual_nozzle."""
  2075. mqtt_client._process_message(_extruder_info_payload([{"id": 0, "snow": 0xFF00FF}]))
  2076. assert mqtt_client._is_dual_nozzle is False
  2077. def test_last_loaded_tray_survives_unload(self, mqtt_client):
  2078. """Load tray 2, unload → last_loaded_tray stays 2."""
  2079. mqtt_client._process_message(_ams_payload(2))
  2080. assert mqtt_client.state.last_loaded_tray == 2
  2081. mqtt_client._process_message(_ams_payload(255))
  2082. assert mqtt_client.state.tray_now == 255
  2083. assert mqtt_client.state.last_loaded_tray == 2
  2084. # ---------------------------------------------------------------------------
  2085. # 2. Single-nozzle P2S — multiple AMS, global IDs pass through
  2086. # ---------------------------------------------------------------------------
  2087. class TestTrayNowSingleNozzleP2S:
  2088. """Single-nozzle, 2 AMS — tray_now > 3 passes through as global ID."""
  2089. @pytest.fixture
  2090. def mqtt_client(self):
  2091. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2092. return BambuMQTTClient(
  2093. ip_address="192.168.1.100",
  2094. serial_number="TEST_P2S",
  2095. access_code="12345678",
  2096. )
  2097. def test_tray_now_ams1_global_ids_4_to_7(self, mqtt_client):
  2098. """tray_now 4-7 are global IDs for AMS 1 on single-nozzle printers."""
  2099. for global_id in range(4, 8):
  2100. mqtt_client._process_message(_ams_payload(global_id))
  2101. assert mqtt_client.state.tray_now == global_id
  2102. def test_tray_change_across_ams_units(self, mqtt_client):
  2103. """Switch from AMS 0 slot 1 → AMS 1 slot 2 (global 6)."""
  2104. mqtt_client._process_message(_ams_payload(1))
  2105. assert mqtt_client.state.tray_now == 1
  2106. mqtt_client._process_message(_ams_payload(6))
  2107. assert mqtt_client.state.tray_now == 6
  2108. # ---------------------------------------------------------------------------
  2109. # 2b. Single-nozzle P2S — multi-AMS local slot disambiguation (#420)
  2110. # ---------------------------------------------------------------------------
  2111. class TestTrayNowP2SMultiAmsDisambiguation:
  2112. """P2S firmware sends local slot IDs (0-3) in tray_now even with dual AMS.
  2113. When ams_exist_bits indicates >1 AMS unit and tray_now is 0-3, the backend
  2114. should use the MQTT mapping field (snow-encoded) to resolve the correct
  2115. global tray ID.
  2116. """
  2117. @pytest.fixture
  2118. def mqtt_client(self):
  2119. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2120. client = BambuMQTTClient(
  2121. ip_address="192.168.1.100",
  2122. serial_number="TEST_P2S_DUAL",
  2123. access_code="12345678",
  2124. )
  2125. return client
  2126. def test_resolves_ams1_slot1_from_mapping(self, mqtt_client):
  2127. """tray_now=1 with mapping=[257] → global ID 5 (AMS1-T1).
  2128. 257 snow-decoded: ams_hw_id=1, slot=1 → global 1*4+1=5.
  2129. """
  2130. # Set mapping field in raw_data (as the MQTT handler would)
  2131. mqtt_client.state.raw_data["mapping"] = [257]
  2132. mqtt_client._process_message(
  2133. _ams_payload(1, ams_exist_bits="3") # '3' = 0b11 → AMS 0 and 1
  2134. )
  2135. assert mqtt_client.state.tray_now == 5
  2136. def test_resolves_ams1_slot0_from_mapping(self, mqtt_client):
  2137. """tray_now=0 with mapping=[256] → global ID 4 (AMS1-T0).
  2138. 256 snow-decoded: ams_hw_id=1, slot=0 → global 1*4+0=4.
  2139. """
  2140. mqtt_client.state.raw_data["mapping"] = [256]
  2141. mqtt_client._process_message(_ams_payload(0, ams_exist_bits="3"))
  2142. assert mqtt_client.state.tray_now == 4
  2143. def test_resolves_ams1_slot3_from_mapping(self, mqtt_client):
  2144. """tray_now=3 with mapping=[259] → global ID 7 (AMS1-T3).
  2145. 259 snow-decoded: ams_hw_id=1, slot=3 → global 1*4+3=7.
  2146. """
  2147. mqtt_client.state.raw_data["mapping"] = [259]
  2148. mqtt_client._process_message(_ams_payload(3, ams_exist_bits="3"))
  2149. assert mqtt_client.state.tray_now == 7
  2150. def test_ams0_slot_unchanged_when_mapping_confirms_ams0(self, mqtt_client):
  2151. """tray_now=1 with mapping=[1] → stays 1 (AMS0-T1).
  2152. 1 snow-decoded: ams_hw_id=0, slot=1 → global 0*4+1=1.
  2153. """
  2154. mqtt_client.state.raw_data["mapping"] = [1]
  2155. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2156. assert mqtt_client.state.tray_now == 1
  2157. def test_multicolor_resolves_ams1_from_multi_entry_mapping(self, mqtt_client):
  2158. """Multi-color print: mapping=[0, 257] → tray_now=1 resolves to AMS1-T1 (5).
  2159. Entry 0: ams_hw_id=0, slot=0 (local 0) — doesn't match tray_now=1.
  2160. Entry 257: ams_hw_id=1, slot=1 (local 1) — matches tray_now=1 → global 5.
  2161. """
  2162. mqtt_client.state.raw_data["mapping"] = [0, 257]
  2163. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2164. assert mqtt_client.state.tray_now == 5
  2165. def test_multicolor_four_slot_mapping(self, mqtt_client):
  2166. """mapping=[65535, 65535, 65535, 257] → tray_now=1 resolves to global 5.
  2167. Only entry 257 has local slot=1, other entries are unmapped (65535).
  2168. Reproduces exact data from issue #420 support package.
  2169. """
  2170. mqtt_client.state.raw_data["mapping"] = [65535, 65535, 65535, 257]
  2171. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2172. assert mqtt_client.state.tray_now == 5
  2173. def test_ambiguous_mapping_falls_back_to_local_slot(self, mqtt_client):
  2174. """Two AMS units with same local slot in mapping → ambiguous, keep local slot.
  2175. mapping=[1, 257]: both have local slot 1 (AMS0-T1 and AMS1-T1).
  2176. Cannot disambiguate → fall back to tray_now=1.
  2177. """
  2178. mqtt_client.state.raw_data["mapping"] = [1, 257]
  2179. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2180. assert mqtt_client.state.tray_now == 1
  2181. def test_no_mapping_falls_back_to_local_slot(self, mqtt_client):
  2182. """No mapping field available → fall back to raw tray_now."""
  2183. # No mapping in raw_data (e.g. manual filament load, not during print)
  2184. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2185. assert mqtt_client.state.tray_now == 1
  2186. def test_empty_mapping_falls_back_to_local_slot(self, mqtt_client):
  2187. """Empty mapping list → fall back to raw tray_now."""
  2188. mqtt_client.state.raw_data["mapping"] = []
  2189. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2190. assert mqtt_client.state.tray_now == 1
  2191. def test_single_ams_passthrough(self, mqtt_client):
  2192. """Single AMS (ams_exist_bits='1') → tray_now 0-3 is direct global ID."""
  2193. mqtt_client._process_message(_ams_payload(2, ams_exist_bits="1"))
  2194. assert mqtt_client.state.tray_now == 2
  2195. def test_no_ams_exist_bits_passthrough(self, mqtt_client):
  2196. """No ams_exist_bits in payload → fall back to raw tray_now."""
  2197. mqtt_client._process_message(_ams_payload(1))
  2198. assert mqtt_client.state.tray_now == 1
  2199. def test_tray_now_255_unaffected_by_multi_ams(self, mqtt_client):
  2200. """tray_now=255 (unloaded) passes through regardless of AMS count."""
  2201. mqtt_client.state.raw_data["mapping"] = [257]
  2202. mqtt_client._process_message(_ams_payload(255, ams_exist_bits="3"))
  2203. assert mqtt_client.state.tray_now == 255
  2204. def test_tray_now_above_3_unaffected(self, mqtt_client):
  2205. """tray_now > 3 is already a global ID and passes through directly."""
  2206. mqtt_client._process_message(_ams_payload(6, ams_exist_bits="3"))
  2207. assert mqtt_client.state.tray_now == 6
  2208. def test_last_loaded_tray_uses_resolved_global_id(self, mqtt_client):
  2209. """last_loaded_tray should reflect the resolved global ID, not local slot."""
  2210. mqtt_client.state.raw_data["mapping"] = [257]
  2211. mqtt_client.state.state = "RUNNING"
  2212. mqtt_client._process_message(_ams_payload(1, ams_exist_bits="3"))
  2213. assert mqtt_client.state.tray_now == 5
  2214. assert mqtt_client.state.last_loaded_tray == 5
  2215. class TestResolveLocalSlotFromMapping:
  2216. """Unit tests for _resolve_local_slot_from_mapping static method."""
  2217. def test_single_match_ams0(self):
  2218. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2219. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [1]) == 1
  2220. def test_single_match_ams1(self):
  2221. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2222. # 257 = 1*256 + 1 → AMS1 slot1 → global 5
  2223. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [257]) == 5
  2224. def test_single_match_ams2(self):
  2225. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2226. # 514 = 2*256 + 2 → AMS2 slot2 → global 10
  2227. assert BambuMQTTClient._resolve_local_slot_from_mapping(2, [514]) == 10
  2228. def test_unmapped_entries_skipped(self):
  2229. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2230. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [65535, 65535, 65535, 257]) == 5
  2231. def test_no_match_returns_none(self):
  2232. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2233. # mapping has slot 0 only, looking for slot 2
  2234. assert BambuMQTTClient._resolve_local_slot_from_mapping(2, [0]) is None
  2235. def test_ambiguous_returns_none(self):
  2236. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2237. # Both AMS0 slot1 (1) and AMS1 slot1 (257) → ambiguous
  2238. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, [1, 257]) is None
  2239. def test_none_mapping_returns_none(self):
  2240. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2241. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, None) is None
  2242. def test_empty_mapping_returns_none(self):
  2243. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2244. assert BambuMQTTClient._resolve_local_slot_from_mapping(1, []) is None
  2245. def test_ams_ht_slot0_match(self):
  2246. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2247. # AMS-HT id=128: snow = 128*256 + 0 = 32768
  2248. assert BambuMQTTClient._resolve_local_slot_from_mapping(0, [32768]) == 128
  2249. # ---------------------------------------------------------------------------
  2250. # 3. H2D Pro — initial state detection
  2251. # ---------------------------------------------------------------------------
  2252. class TestTrayNowDualNozzleH2DSetup:
  2253. """H2D Pro initial state detection."""
  2254. @pytest.fixture
  2255. def mqtt_client(self):
  2256. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2257. return BambuMQTTClient(
  2258. ip_address="192.168.1.100",
  2259. serial_number="TEST_H2D",
  2260. access_code="12345678",
  2261. )
  2262. def test_dual_nozzle_detected_from_extruder_info(self, mqtt_client):
  2263. """2 entries in device.extruder.info → _is_dual_nozzle=True."""
  2264. mqtt_client._process_message(
  2265. _extruder_info_payload(
  2266. [
  2267. {"id": 0, "snow": 0xFF00FF},
  2268. {"id": 1, "snow": 0xFF00FF},
  2269. ]
  2270. )
  2271. )
  2272. assert mqtt_client._is_dual_nozzle is True
  2273. def test_ams_extruder_map_parsed_from_info_field(self, mqtt_client):
  2274. """AMS info field is hex: 0x2003 → ext 0 (right), 0x2104 → ext 1 (left)."""
  2275. # MQTT sends info as string; BambuStudio parses as hex via stoull(str, 16)
  2276. ams_units = [
  2277. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2278. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  2279. ]
  2280. payload = {
  2281. "print": {
  2282. "ams": {
  2283. "ams": ams_units,
  2284. "tray_now": "255",
  2285. "tray_exist_bits": "1000f",
  2286. },
  2287. }
  2288. }
  2289. mqtt_client._process_message(payload)
  2290. # 0x2003: bits 8-11 = (0x2003 >> 8) & 0xF = 0x20 & 0xF = 0 → extruder 0 (right)
  2291. # 0x2104: bits 8-11 = (0x2104 >> 8) & 0xF = 0x21 & 0xF = 1 → extruder 1 (left)
  2292. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2293. def test_ams_extruder_map_real_h2d_values(self, mqtt_client):
  2294. """Real H2D MQTT values: AMS2 Pro on right, AMS-HT on left."""
  2295. ams_units = [
  2296. {"id": 0, "info": "10001003", "tray": [{"id": i} for i in range(4)]},
  2297. {"id": 128, "info": "10002104", "tray": [{"id": 0}]},
  2298. ]
  2299. payload = {
  2300. "print": {
  2301. "ams": {
  2302. "ams": ams_units,
  2303. "tray_now": "255",
  2304. "tray_exist_bits": "1000a",
  2305. },
  2306. }
  2307. }
  2308. mqtt_client._process_message(payload)
  2309. # 0x10001003: bits 8-11 = (0x10001003 >> 8) & 0xF = 0x10 & 0xF = 0 → right
  2310. # 0x10002104: bits 8-11 = (0x10002104 >> 8) & 0xF = 0x21 & 0xF = 1 → left
  2311. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2312. def test_ams_extruder_map_skips_uninitialized(self, mqtt_client):
  2313. """extruder_id 0xE means uninitialized AMS — should be skipped."""
  2314. ams_units = [
  2315. {"id": 0, "info": "e03", "tray": [{"id": i} for i in range(4)]},
  2316. ]
  2317. payload = {
  2318. "print": {
  2319. "ams": {
  2320. "ams": ams_units,
  2321. "tray_now": "255",
  2322. "tray_exist_bits": "f",
  2323. },
  2324. }
  2325. }
  2326. mqtt_client._process_message(payload)
  2327. assert mqtt_client.state.ams_extruder_map == {}
  2328. def test_ams_extruder_map_partial_update_preserves_entries(self, mqtt_client):
  2329. """Partial MQTT update with one AMS should not overwrite other entries."""
  2330. # First: full update with both AMS units
  2331. full_payload = {
  2332. "print": {
  2333. "ams": {
  2334. "ams": [
  2335. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2336. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  2337. ],
  2338. "tray_now": "255",
  2339. "tray_exist_bits": "1000f",
  2340. },
  2341. }
  2342. }
  2343. mqtt_client._process_message(full_payload)
  2344. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2345. # Then: partial update with only AMS 0 (no info field this time)
  2346. partial_payload = {
  2347. "print": {
  2348. "ams": {
  2349. "ams": [
  2350. {"id": 0, "tray": [{"id": 0, "remain": 50}]},
  2351. ],
  2352. "tray_now": "0",
  2353. "tray_exist_bits": "1000f",
  2354. },
  2355. }
  2356. }
  2357. mqtt_client._process_message(partial_payload)
  2358. # Both entries should still be present
  2359. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2360. def test_dual_nozzle_detection_before_ams_in_same_message(self, mqtt_client):
  2361. """Dual-nozzle detection at line 538 happens before _handle_ams_data() at line 549.
  2362. If both arrive in the same message, tray_now disambiguation already uses dual-nozzle logic.
  2363. """
  2364. payload = {
  2365. "print": {
  2366. "device": {
  2367. "extruder": {
  2368. "info": [
  2369. {"id": 0, "snow": 0xFF00FF},
  2370. {"id": 1, "snow": 0xFF00FF},
  2371. ],
  2372. "state": 0x0001,
  2373. }
  2374. },
  2375. "ams": {
  2376. "ams": [
  2377. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2378. ],
  2379. "tray_now": "2",
  2380. "tray_exist_bits": "f",
  2381. },
  2382. }
  2383. }
  2384. mqtt_client._process_message(payload)
  2385. # Dual-nozzle was detected; AMS 0 on right extruder (active by default);
  2386. # snow is 0xFF00FF (unloaded), so falls through to ams_extruder_map fallback.
  2387. # Single AMS on extruder 0 → global_id = 0*4+2 = 2
  2388. assert mqtt_client._is_dual_nozzle is True
  2389. assert mqtt_client.state.tray_now == 2
  2390. # ---------------------------------------------------------------------------
  2391. # Shared H2D fixture for classes 4-8
  2392. # ---------------------------------------------------------------------------
  2393. class _H2DFixtureMixin:
  2394. """Mixin providing a pre-configured H2D Pro client."""
  2395. @pytest.fixture
  2396. def mqtt_client(self):
  2397. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2398. return BambuMQTTClient(
  2399. ip_address="192.168.1.100",
  2400. serial_number="TEST_H2D",
  2401. access_code="12345678",
  2402. )
  2403. @pytest.fixture
  2404. def h2d_client(self, mqtt_client):
  2405. """Pre-configure as H2D Pro: dual-nozzle + ams_extruder_map."""
  2406. mqtt_client._process_message(
  2407. {
  2408. "print": {
  2409. "device": {
  2410. "extruder": {
  2411. "info": [
  2412. {"id": 0, "snow": 0xFF00FF},
  2413. {"id": 1, "snow": 0xFF00FF},
  2414. ],
  2415. "state": 0x0001, # right extruder active
  2416. }
  2417. },
  2418. "ams": {
  2419. "ams": [
  2420. {"id": 0, "info": "2003", "tray": [{"id": i} for i in range(4)]},
  2421. {"id": 128, "info": "2104", "tray": [{"id": 0}]},
  2422. ],
  2423. "tray_now": "255",
  2424. "tray_exist_bits": "1000f",
  2425. },
  2426. }
  2427. }
  2428. )
  2429. assert mqtt_client._is_dual_nozzle is True
  2430. assert mqtt_client.state.ams_extruder_map == {"0": 0, "128": 1}
  2431. return mqtt_client
  2432. # ---------------------------------------------------------------------------
  2433. # 4. H2D Snow field disambiguation
  2434. # ---------------------------------------------------------------------------
  2435. class TestTrayNowDualNozzleH2DSnow(_H2DFixtureMixin):
  2436. """Snow field disambiguation (primary path)."""
  2437. def test_snow_disambiguates_ams0_slot(self, h2d_client):
  2438. """snow ext[0]=AMS 0 slot 2, tray_now='2' → global 2."""
  2439. # Send snow update FIRST (snow is parsed AFTER tray_now in the same message,
  2440. # so we need it in a prior message).
  2441. snow_val = 0 << 8 | 2 # AMS 0 slot 2 = raw 2
  2442. h2d_client._process_message(
  2443. _extruder_info_payload(
  2444. [
  2445. {"id": 0, "snow": snow_val},
  2446. {"id": 1, "snow": 0xFF00FF},
  2447. ]
  2448. )
  2449. )
  2450. assert h2d_client.state.h2d_extruder_snow.get(0) == 2
  2451. # Now send tray_now=2
  2452. h2d_client._process_message(_ams_payload(2))
  2453. assert h2d_client.state.tray_now == 2
  2454. def test_snow_disambiguates_ams_ht_to_128(self, h2d_client):
  2455. """snow ext[1]=AMS HT (128), left active, tray_now='0' → global 128."""
  2456. # Snow: extruder 1 → AMS 128 slot 0
  2457. snow_val = 128 << 8 | 0 # = 32768
  2458. h2d_client._process_message(
  2459. _extruder_info_payload(
  2460. [
  2461. {"id": 0, "snow": 0xFF00FF},
  2462. {"id": 1, "snow": snow_val},
  2463. ]
  2464. )
  2465. )
  2466. assert h2d_client.state.h2d_extruder_snow.get(1) == 128
  2467. # Switch to left extruder
  2468. h2d_client._process_message(_extruder_state_payload(0x0100))
  2469. assert h2d_client.state.active_extruder == 1
  2470. # tray_now="0" with left extruder active, snow says AMS HT (128)
  2471. # AMS HT snow_slot = 0 (single slot), parsed_tray_now = 0 → match
  2472. h2d_client._process_message(_ams_payload(0))
  2473. assert h2d_client.state.tray_now == 128
  2474. def test_snow_updates_h2d_extruder_snow_state(self, h2d_client):
  2475. """Verify state.h2d_extruder_snow dict is populated correctly."""
  2476. snow_ext0 = 1 << 8 | 3 # AMS 1 slot 3 → global 7
  2477. snow_ext1 = 0 << 8 | 0 # AMS 0 slot 0 → global 0
  2478. h2d_client._process_message(
  2479. _extruder_info_payload(
  2480. [
  2481. {"id": 0, "snow": snow_ext0},
  2482. {"id": 1, "snow": snow_ext1},
  2483. ]
  2484. )
  2485. )
  2486. assert h2d_client.state.h2d_extruder_snow[0] == 7
  2487. assert h2d_client.state.h2d_extruder_snow[1] == 0
  2488. def test_snow_unloaded_value(self, h2d_client):
  2489. """snow=0xFFFF (ams_id=255, slot=255) → 255 (unloaded)."""
  2490. h2d_client._process_message(
  2491. _extruder_info_payload(
  2492. [
  2493. {"id": 0, "snow": 0xFFFF},
  2494. {"id": 1, "snow": 0xFFFF},
  2495. ]
  2496. )
  2497. )
  2498. assert h2d_client.state.h2d_extruder_snow[0] == 255
  2499. assert h2d_client.state.h2d_extruder_snow[1] == 255
  2500. def test_snow_initial_sentinel_not_stored(self, h2d_client):
  2501. """snow=0xFF00FF (firmware initial sentinel) is not parsed into h2d_extruder_snow."""
  2502. # 0xFF00FF has ams_id=0xFF00=65280 which doesn't match any branch
  2503. h2d_client._process_message(
  2504. _extruder_info_payload(
  2505. [
  2506. {"id": 0, "snow": 0xFF00FF},
  2507. {"id": 1, "snow": 0xFF00FF},
  2508. ]
  2509. )
  2510. )
  2511. # Snow dict should remain empty (no matching branch)
  2512. assert h2d_client.state.h2d_extruder_snow == {}
  2513. # ---------------------------------------------------------------------------
  2514. # 5. H2D Pending target disambiguation
  2515. # ---------------------------------------------------------------------------
  2516. class TestTrayNowDualNozzleH2DPendingTarget(_H2DFixtureMixin):
  2517. """Pending target disambiguation (when Bambuddy initiates load)."""
  2518. def test_pending_target_matches_slot(self, h2d_client):
  2519. """pending=5, tray_now='1' (5%4=1 matches) → tray_now=5."""
  2520. h2d_client.state.pending_tray_target = 5
  2521. h2d_client._process_message(_ams_payload(1))
  2522. assert h2d_client.state.tray_now == 5
  2523. assert h2d_client.state.pending_tray_target is None # cleared
  2524. def test_pending_target_slot_mismatch(self, h2d_client):
  2525. """pending=5, tray_now='2' → uses raw slot, clears pending."""
  2526. h2d_client.state.pending_tray_target = 5
  2527. h2d_client._process_message(_ams_payload(2))
  2528. # Slot 2 != 5%4=1 → mismatch, uses raw slot 2
  2529. assert h2d_client.state.tray_now == 2
  2530. assert h2d_client.state.pending_tray_target is None
  2531. def test_pending_target_takes_priority_over_snow(self, h2d_client):
  2532. """When both pending and snow are set, pending wins."""
  2533. # Set up snow for extruder 0 → AMS 0 slot 1 → global 1
  2534. snow_val = 0 << 8 | 1
  2535. h2d_client._process_message(
  2536. _extruder_info_payload(
  2537. [
  2538. {"id": 0, "snow": snow_val},
  2539. {"id": 1, "snow": 0xFF00FF},
  2540. ]
  2541. )
  2542. )
  2543. assert h2d_client.state.h2d_extruder_snow.get(0) == 1
  2544. # Set pending target to AMS 1 slot 1 (global 5)
  2545. h2d_client.state.pending_tray_target = 5
  2546. # tray_now="1" — matches pending (5%4=1), pending should win over snow
  2547. h2d_client._process_message(_ams_payload(1))
  2548. assert h2d_client.state.tray_now == 5
  2549. # ---------------------------------------------------------------------------
  2550. # 6. H2D ams_extruder_map fallback
  2551. # ---------------------------------------------------------------------------
  2552. class TestTrayNowDualNozzleH2DFallback(_H2DFixtureMixin):
  2553. """ams_extruder_map fallback (no pending, no snow)."""
  2554. def test_single_ams_on_extruder_computes_global_id(self, h2d_client):
  2555. """AMS 0 on right extruder, tray_now='2' → 0*4+2=2."""
  2556. # h2d_client has snow=0xFF00FF (unloaded) by default, so snow path skips
  2557. h2d_client._process_message(_ams_payload(2))
  2558. # AMS 0 is the only AMS on extruder 0 (right, active by default)
  2559. # Fallback: single AMS → global = 0*4+2 = 2
  2560. assert h2d_client.state.tray_now == 2
  2561. def test_multiple_ams_keeps_current_if_valid(self, h2d_client):
  2562. """Current tray matches slot → keeps it (multi-AMS on same extruder)."""
  2563. # Set up: two AMS units on the same extruder (right, ext 0)
  2564. h2d_client.state.ams_extruder_map = {"0": 0, "1": 0}
  2565. # Pre-set tray_now=5 (AMS 1 slot 1) — current_ams=1 which is in ams_on_extruder
  2566. h2d_client.state.tray_now = 5
  2567. # tray_now="1" → 5%4=1 matches → keep current=5
  2568. h2d_client._process_message(_ams_payload(1))
  2569. assert h2d_client.state.tray_now == 5
  2570. def test_no_ams_on_extruder_uses_raw_slot(self, h2d_client):
  2571. """No AMS mapped to the active extruder → raw slot as global ID."""
  2572. # All AMS on left extruder, but right is active
  2573. h2d_client.state.ams_extruder_map = {"0": 1, "128": 1}
  2574. h2d_client._process_message(_ams_payload(2))
  2575. assert h2d_client.state.tray_now == 2
  2576. def test_single_ams_ht_on_extruder_returns_unit_id(self, h2d_client):
  2577. """AMS-HT 128 alone on left extruder, slot 0 → global ID 128 (not 512)."""
  2578. # Switch to left extruder (where AMS-HT 128 is mapped)
  2579. h2d_client._process_message(_extruder_state_payload(0x0100))
  2580. # Only AMS-HT 128 on left extruder; no snow available
  2581. h2d_client._process_message(_ams_payload(0))
  2582. assert h2d_client.state.tray_now == 128
  2583. def test_single_ams_ht_ignores_nonzero_slot(self, h2d_client):
  2584. """AMS-HT has single slot; even if printer reports slot 1, global ID = unit ID."""
  2585. h2d_client.state.ams_extruder_map = {"129": 0}
  2586. h2d_client._process_message(_ams_payload(1))
  2587. # AMS-HT 129: global ID = 129, not 129*4+1=517
  2588. assert h2d_client.state.tray_now == 129
  2589. def test_multiple_ams_keeps_current_ams_ht(self, h2d_client):
  2590. """Current tray is AMS-HT 128, slot 0 reported → keeps 128."""
  2591. h2d_client.state.ams_extruder_map = {"0": 0, "128": 0}
  2592. h2d_client.state.tray_now = 128
  2593. h2d_client._process_message(_ams_payload(0))
  2594. assert h2d_client.state.tray_now == 128
  2595. def test_multiple_ams_slot_nonzero_excludes_ams_ht(self, h2d_client):
  2596. """Slot > 0 eliminates AMS-HT candidates; single regular AMS left → resolves."""
  2597. # AMS 0 + AMS-HT 128 both on right extruder
  2598. h2d_client.state.ams_extruder_map = {"0": 0, "128": 0}
  2599. h2d_client.state.tray_now = 255 # no current match
  2600. # Slot 2 → can't be AMS-HT → only AMS 0 → global = 0*4+2 = 2
  2601. h2d_client._process_message(_ams_payload(2))
  2602. assert h2d_client.state.tray_now == 2
  2603. def test_multiple_ams_slot_nonzero_narrows_to_single_ht_excluded(self, h2d_client):
  2604. """Two regular AMS + one AMS-HT, slot > 0 → AMS-HT excluded but still ambiguous."""
  2605. h2d_client.state.ams_extruder_map = {"0": 0, "1": 0, "128": 0}
  2606. h2d_client.state.tray_now = 255
  2607. # Slot 3 → excludes AMS-HT, but AMS 0 and AMS 1 both remain → ambiguous
  2608. h2d_client._process_message(_ams_payload(3))
  2609. assert h2d_client.state.tray_now == 3 # raw slot fallback
  2610. # ---------------------------------------------------------------------------
  2611. # 6b. H2D last_loaded_tray validation
  2612. # ---------------------------------------------------------------------------
  2613. class TestLastLoadedTrayValidation(_H2DFixtureMixin):
  2614. """last_loaded_tray only stores physically valid tray IDs."""
  2615. def test_regular_ams_tray_stored(self, h2d_client):
  2616. """Valid regular AMS tray (0-15) → stored in last_loaded_tray."""
  2617. h2d_client.state.tray_now = 7
  2618. # Trigger tray_now processing via AMS message
  2619. h2d_client._process_message(
  2620. _extruder_info_payload(
  2621. [
  2622. {"id": 0, "snow": 1 << 8 | 3}, # AMS 1 slot 3 → global 7
  2623. {"id": 1, "snow": 0xFF00FF},
  2624. ]
  2625. )
  2626. )
  2627. h2d_client._process_message(_ams_payload(3))
  2628. assert h2d_client.state.tray_now == 7
  2629. assert h2d_client.state.last_loaded_tray == 7
  2630. def test_ams_ht_tray_stored(self, h2d_client):
  2631. """Valid AMS-HT tray (128-135) → stored in last_loaded_tray."""
  2632. h2d_client._process_message(_extruder_state_payload(0x0100))
  2633. h2d_client._process_message(
  2634. _extruder_info_payload(
  2635. [
  2636. {"id": 0, "snow": 0xFF00FF},
  2637. {"id": 1, "snow": 128 << 8 | 0},
  2638. ]
  2639. )
  2640. )
  2641. h2d_client._process_message(_ams_payload(0))
  2642. assert h2d_client.state.tray_now == 128
  2643. assert h2d_client.state.last_loaded_tray == 128
  2644. def test_unloaded_not_stored(self, h2d_client):
  2645. """tray_now=255 (unloaded) → last_loaded_tray unchanged."""
  2646. h2d_client.state.last_loaded_tray = 5
  2647. h2d_client._process_message(_ams_payload(255))
  2648. assert h2d_client.state.tray_now == 255
  2649. assert h2d_client.state.last_loaded_tray == 5
  2650. # ---------------------------------------------------------------------------
  2651. # 7. H2D Active extruder switching
  2652. # ---------------------------------------------------------------------------
  2653. class TestTrayNowDualNozzleH2DActiveExtruder(_H2DFixtureMixin):
  2654. """Active extruder switching via device.extruder.state bit 8."""
  2655. def test_active_extruder_right_by_default(self, h2d_client):
  2656. """Initial state.active_extruder == 0 (right)."""
  2657. assert h2d_client.state.active_extruder == 0
  2658. def test_extruder_state_bit8_switches_to_left(self, h2d_client):
  2659. """state=0x100 → active_extruder=1 (left)."""
  2660. h2d_client._process_message(_extruder_state_payload(0x0100))
  2661. assert h2d_client.state.active_extruder == 1
  2662. def test_extruder_state_bit8_switches_back_to_right(self, h2d_client):
  2663. """Cycle 0 → 1 → 0."""
  2664. h2d_client._process_message(_extruder_state_payload(0x0100))
  2665. assert h2d_client.state.active_extruder == 1
  2666. h2d_client._process_message(_extruder_state_payload(0x0001))
  2667. assert h2d_client.state.active_extruder == 0
  2668. def test_extruder_switch_changes_tray_disambiguation(self, h2d_client):
  2669. """Snow on both extruders; switching active changes which snow is used."""
  2670. # Snow: ext 0 → AMS 0 slot 1 (global 1), ext 1 → AMS 128 slot 0 (global 128)
  2671. h2d_client._process_message(
  2672. _extruder_info_payload(
  2673. [
  2674. {"id": 0, "snow": 0 << 8 | 1}, # AMS 0 slot 1 → global 1
  2675. {"id": 1, "snow": 128 << 8 | 0}, # AMS HT → global 128
  2676. ]
  2677. )
  2678. )
  2679. # Right active (default) — tray_now="1" → snow ext[0] says global 1
  2680. h2d_client._process_message(_ams_payload(1))
  2681. assert h2d_client.state.tray_now == 1
  2682. # Switch to left
  2683. h2d_client._process_message(_extruder_state_payload(0x0100))
  2684. # Left active — tray_now="0" → snow ext[1] says AMS HT (128), slot 0 matches
  2685. h2d_client._process_message(_ams_payload(0))
  2686. assert h2d_client.state.tray_now == 128
  2687. # ---------------------------------------------------------------------------
  2688. # 8. Device identification probe (#1684 enabler)
  2689. # ---------------------------------------------------------------------------
  2690. class TestDeviceIdentificationProbe:
  2691. """One-shot INFO log of any device.* identification fields the firmware
  2692. sends. Lets a new-model support bundle self-disclose the internal model
  2693. code (e.g. dev_model_name='N2L') without a separate debug build.
  2694. """
  2695. @pytest.fixture
  2696. def mqtt_client(self):
  2697. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2698. return BambuMQTTClient(
  2699. ip_address="192.168.1.100",
  2700. serial_number="TEST_PROBE",
  2701. access_code="12345678",
  2702. )
  2703. def _device_payload(self, device):
  2704. return {"print": {"device": device}}
  2705. def test_logs_known_id_fields_once(self, mqtt_client, caplog):
  2706. import logging
  2707. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  2708. mqtt_client._process_message(
  2709. self._device_payload({"dev_model_name": "N2S", "dev_product_name": "Bambu Lab A1"})
  2710. )
  2711. matches = [r for r in caplog.records if "Device identification" in r.getMessage()]
  2712. assert len(matches) == 1
  2713. msg = matches[0].getMessage()
  2714. assert "dev_model_name" in msg and "N2S" in msg
  2715. assert "dev_product_name" in msg
  2716. def test_one_shot_does_not_repeat(self, mqtt_client, caplog):
  2717. import logging
  2718. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  2719. payload = self._device_payload({"dev_model_name": "N2S"})
  2720. mqtt_client._process_message(payload)
  2721. mqtt_client._process_message(payload)
  2722. mqtt_client._process_message(payload)
  2723. matches = [r for r in caplog.records if "Device identification" in r.getMessage()]
  2724. assert len(matches) == 1
  2725. def test_fallback_dumps_keys_when_no_known_fields(self, mqtt_client, caplog):
  2726. """Future Bambu rename (e.g. model_name without dev_ prefix) still surfaces."""
  2727. import logging
  2728. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  2729. mqtt_client._process_message(self._device_payload({"model_name": "MysteryModel", "extruder": {"state": 0}}))
  2730. matches = [r for r in caplog.records if "Device identification" in r.getMessage()]
  2731. assert len(matches) == 1
  2732. msg = matches[0].getMessage()
  2733. assert "no known id fields" in msg
  2734. assert "model_name" in msg and "extruder" in msg
  2735. # ---------------------------------------------------------------------------
  2736. # 8. H2D Full multi-message sequences
  2737. # ---------------------------------------------------------------------------
  2738. class TestTrayNowDualNozzleH2DFullSequence(_H2DFixtureMixin):
  2739. """Multi-message sequences simulating real H2D Pro prints."""
  2740. def test_h2d_right_nozzle_ams0_lifecycle(self, h2d_client):
  2741. """Setup → load AMS 0 slot 1 → verify tray_now=1."""
  2742. # Snow update: extruder 0 loading AMS 0 slot 1
  2743. h2d_client._process_message(
  2744. _extruder_info_payload(
  2745. [
  2746. {"id": 0, "snow": 0 << 8 | 1},
  2747. {"id": 1, "snow": 0xFF00FF},
  2748. ]
  2749. )
  2750. )
  2751. # Printer reports tray_now="1"
  2752. h2d_client._process_message(_ams_payload(1))
  2753. assert h2d_client.state.tray_now == 1
  2754. assert h2d_client.state.last_loaded_tray == 1
  2755. def test_h2d_left_nozzle_ams_ht_lifecycle(self, h2d_client):
  2756. """Setup → switch left → load AMS HT → verify tray_now=128."""
  2757. # Switch to left extruder
  2758. h2d_client._process_message(_extruder_state_payload(0x0100))
  2759. # Snow: ext 1 → AMS HT slot 0
  2760. h2d_client._process_message(
  2761. _extruder_info_payload(
  2762. [
  2763. {"id": 0, "snow": 0xFF00FF},
  2764. {"id": 1, "snow": 128 << 8 | 0},
  2765. ]
  2766. )
  2767. )
  2768. # Printer reports tray_now="0" (AMS HT single slot)
  2769. h2d_client._process_message(_ams_payload(0))
  2770. assert h2d_client.state.tray_now == 128
  2771. assert h2d_client.state.last_loaded_tray == 128
  2772. def test_h2d_multi_color_alternating_nozzles(self, h2d_client):
  2773. """Multi-color print alternating between right and left nozzles.
  2774. Sequence:
  2775. 1. Right loads AMS 0 slot 0 (tray=0)
  2776. 2. Switch left, load AMS HT (tray=128)
  2777. 3. Switch right, snow updates, load AMS 0 slot 2 (tray=2)
  2778. 4. Unload (255)
  2779. """
  2780. # Step 1: Right extruder loads AMS 0 slot 0
  2781. h2d_client._process_message(
  2782. _extruder_info_payload(
  2783. [
  2784. {"id": 0, "snow": 0 << 8 | 0},
  2785. {"id": 1, "snow": 0xFF00FF},
  2786. ]
  2787. )
  2788. )
  2789. h2d_client._process_message(_ams_payload(0))
  2790. assert h2d_client.state.tray_now == 0
  2791. # Step 2: Switch to left, load AMS HT
  2792. h2d_client._process_message(_extruder_state_payload(0x0100))
  2793. h2d_client._process_message(
  2794. _extruder_info_payload(
  2795. [
  2796. {"id": 0, "snow": 0 << 8 | 0},
  2797. {"id": 1, "snow": 128 << 8 | 0},
  2798. ]
  2799. )
  2800. )
  2801. h2d_client._process_message(_ams_payload(0))
  2802. assert h2d_client.state.tray_now == 128
  2803. # Step 3: Switch back to right, load AMS 0 slot 2
  2804. h2d_client._process_message(_extruder_state_payload(0x0001))
  2805. h2d_client._process_message(
  2806. _extruder_info_payload(
  2807. [
  2808. {"id": 0, "snow": 0 << 8 | 2},
  2809. {"id": 1, "snow": 128 << 8 | 0},
  2810. ]
  2811. )
  2812. )
  2813. h2d_client._process_message(_ams_payload(2))
  2814. assert h2d_client.state.tray_now == 2
  2815. # Step 4: Unload
  2816. h2d_client._process_message(_ams_payload(255))
  2817. assert h2d_client.state.tray_now == 255
  2818. assert h2d_client.state.last_loaded_tray == 2
  2819. class TestTrayChangeLog:
  2820. """Tests for tray_change_log tracking during prints (mid-print tray switch)."""
  2821. @pytest.fixture
  2822. def mqtt_client(self):
  2823. """Create a BambuMQTTClient instance for testing."""
  2824. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2825. client = BambuMQTTClient(
  2826. ip_address="192.168.1.100",
  2827. serial_number="TRAYLOG1",
  2828. access_code="12345678",
  2829. )
  2830. return client
  2831. def test_tray_change_log_defaults_empty(self, mqtt_client):
  2832. """tray_change_log starts as an empty list."""
  2833. assert mqtt_client.state.tray_change_log == []
  2834. def test_tray_change_log_seeded_on_print_start(self, mqtt_client):
  2835. """Print start clears log and seeds with initial tray at layer 0."""
  2836. mqtt_client.state.tray_now = 2
  2837. mqtt_client.state.last_loaded_tray = 2
  2838. mqtt_client._previous_gcode_state = "IDLE"
  2839. # Transition to RUNNING via _process_message
  2840. mqtt_client._process_message(
  2841. {
  2842. "print": {
  2843. "gcode_state": "RUNNING",
  2844. "gcode_file": "test.3mf",
  2845. }
  2846. }
  2847. )
  2848. assert mqtt_client.state.tray_change_log == [(2, 0)]
  2849. def test_tray_change_log_cleared_on_new_print(self, mqtt_client):
  2850. """Old log entries are cleared when a new print starts."""
  2851. mqtt_client.state.tray_change_log = [(5, 0), (3, 100)]
  2852. mqtt_client.state.tray_now = 1
  2853. mqtt_client.state.last_loaded_tray = 1
  2854. mqtt_client._previous_gcode_state = "IDLE"
  2855. mqtt_client._process_message(
  2856. {
  2857. "print": {
  2858. "gcode_state": "RUNNING",
  2859. "gcode_file": "new.3mf",
  2860. }
  2861. }
  2862. )
  2863. assert mqtt_client.state.tray_change_log == [(1, 0)]
  2864. # Helper that mirrors the production gate at bambu_mqtt.py:1571 — tests
  2865. # below replicate the gate so they validate the *contract* without needing
  2866. # to feed a synthetic AMS push through the full _process_message path.
  2867. @staticmethod
  2868. def _record_if_change(client, tn: int) -> None:
  2869. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  2870. if tn != client.state.last_loaded_tray and client._was_running and not client._completion_triggered:
  2871. client.state.tray_change_log.append((tn, client.state.layer_num))
  2872. client.state.last_loaded_tray = tn
  2873. def test_tray_change_recorded_during_running(self, mqtt_client):
  2874. """Tray change while RUNNING is appended to the log."""
  2875. mqtt_client.state.state = "RUNNING"
  2876. mqtt_client._was_running = True
  2877. mqtt_client._completion_triggered = False
  2878. mqtt_client.state.layer_num = 50
  2879. mqtt_client.state.last_loaded_tray = 0
  2880. mqtt_client.state.tray_change_log = [(0, 0)]
  2881. mqtt_client.state.tray_now = 1
  2882. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2883. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50)]
  2884. def test_tray_change_not_recorded_when_idle(self, mqtt_client):
  2885. """Tray changes outside an active print are NOT logged."""
  2886. # IDLE between prints — both lifecycle flags in the cleared state.
  2887. mqtt_client.state.state = "IDLE"
  2888. mqtt_client._was_running = False
  2889. mqtt_client._completion_triggered = False
  2890. mqtt_client.state.layer_num = 0
  2891. mqtt_client.state.last_loaded_tray = 0
  2892. mqtt_client.state.tray_change_log = []
  2893. mqtt_client.state.tray_now = 3
  2894. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2895. assert mqtt_client.state.tray_change_log == []
  2896. def test_tray_change_recorded_during_pause(self, mqtt_client):
  2897. """Tray change while PAUSE is also logged (AMS can swap during pause)."""
  2898. mqtt_client.state.state = "PAUSE"
  2899. mqtt_client._was_running = True
  2900. mqtt_client._completion_triggered = False
  2901. mqtt_client.state.layer_num = 75
  2902. mqtt_client.state.last_loaded_tray = 2
  2903. mqtt_client.state.tray_change_log = [(2, 0)]
  2904. mqtt_client.state.tray_now = 5
  2905. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2906. assert mqtt_client.state.tray_change_log == [(2, 0), (5, 75)]
  2907. def test_tray_change_recorded_during_intermediate_state(self, mqtt_client):
  2908. """Tray change during a transient non-RUNNING state mid-print is logged.
  2909. Regression for #957: P2S firmware briefly transitions out of RUNNING
  2910. (e.g. into LOADING) when the AMS auto-falls-back from an empty spool to
  2911. a same-material sibling. The previous gate ``state in ("RUNNING",
  2912. "PAUSE")`` missed this transition entirely, so the usage tracker had no
  2913. evidence of the switch and double-credited the original tray with the
  2914. full 3MF estimate while the remain%-delta path added the fallback
  2915. weight on top. The new gate keys on the print-lifecycle flags
  2916. (``_was_running and not _completion_triggered``) so any tray change
  2917. between print start and completion is captured regardless of the
  2918. momentary gcode_state string.
  2919. """
  2920. mqtt_client.state.state = "LOADING" # not RUNNING/PAUSE — old gate would skip
  2921. mqtt_client._was_running = True
  2922. mqtt_client._completion_triggered = False
  2923. mqtt_client.state.layer_num = 42
  2924. mqtt_client.state.last_loaded_tray = 0
  2925. mqtt_client.state.tray_change_log = [(0, 0)]
  2926. # AMS auto-fallback: T0 ran out, swapped to T1 of same material
  2927. mqtt_client.state.tray_now = 1
  2928. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2929. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 42)]
  2930. def test_tray_change_not_recorded_after_completion(self, mqtt_client):
  2931. """Once on_print_complete has fired, further tray changes don't pollute the log."""
  2932. mqtt_client.state.state = "FINISH"
  2933. mqtt_client._was_running = True
  2934. mqtt_client._completion_triggered = True # completion already triggered
  2935. mqtt_client.state.layer_num = 0
  2936. mqtt_client.state.last_loaded_tray = 1
  2937. mqtt_client.state.tray_change_log = [(0, 0), (1, 50)]
  2938. mqtt_client.state.tray_now = 2
  2939. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2940. # Log unchanged — completion already triggered so post-print tray
  2941. # movement (e.g. printer self-cleaning) doesn't bleed into the next
  2942. # print's attribution.
  2943. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50)]
  2944. def test_same_tray_not_logged_twice(self, mqtt_client):
  2945. """Same tray value doesn't create duplicate log entries."""
  2946. mqtt_client.state.state = "RUNNING"
  2947. mqtt_client._was_running = True
  2948. mqtt_client._completion_triggered = False
  2949. mqtt_client.state.layer_num = 30
  2950. mqtt_client.state.last_loaded_tray = 2
  2951. mqtt_client.state.tray_change_log = [(2, 0)]
  2952. mqtt_client.state.tray_now = 2
  2953. self._record_if_change(mqtt_client, mqtt_client.state.tray_now)
  2954. assert mqtt_client.state.tray_change_log == [(2, 0)]
  2955. def test_multiple_tray_changes(self, mqtt_client):
  2956. """Multiple tray changes create a full history."""
  2957. mqtt_client.state.state = "RUNNING"
  2958. mqtt_client._was_running = True
  2959. mqtt_client._completion_triggered = False
  2960. mqtt_client.state.last_loaded_tray = 0
  2961. mqtt_client.state.tray_change_log = [(0, 0)]
  2962. for tray, layer in [(1, 50), (3, 120), (0, 200)]:
  2963. mqtt_client.state.tray_now = tray
  2964. mqtt_client.state.layer_num = layer
  2965. self._record_if_change(mqtt_client, tray)
  2966. assert mqtt_client.state.tray_change_log == [(0, 0), (1, 50), (3, 120), (0, 200)]
  2967. class TestDeveloperModeDetection:
  2968. """Tests for developer LAN mode detection from MQTT 'fun' field."""
  2969. @pytest.fixture
  2970. def mqtt_client(self):
  2971. """Create a BambuMQTTClient instance for testing."""
  2972. from backend.app.services.bambu_mqtt import BambuMQTTClient
  2973. client = BambuMQTTClient(
  2974. ip_address="192.168.1.100",
  2975. serial_number="TEST123",
  2976. access_code="12345678",
  2977. )
  2978. return client
  2979. def test_developer_mode_initially_none(self, mqtt_client):
  2980. """Verify developer_mode starts as None (unknown)."""
  2981. assert mqtt_client.state.developer_mode is None
  2982. def test_developer_mode_on_when_bit_clear(self, mqtt_client):
  2983. """Verify developer_mode is True when bit 0x20000000 is clear."""
  2984. # Bit 29 clear in lower 32 bits = developer mode ON
  2985. payload = {
  2986. "print": {
  2987. "gcode_state": "IDLE",
  2988. "fun": "1C8187FF9CFF",
  2989. }
  2990. }
  2991. mqtt_client._process_message(payload)
  2992. assert mqtt_client.state.developer_mode is True
  2993. def test_developer_mode_off_when_bit_set(self, mqtt_client):
  2994. """Verify developer_mode is False when bit 0x20000000 is set."""
  2995. # Bit 29 set in lower 32 bits = developer mode OFF (encryption required)
  2996. payload = {
  2997. "print": {
  2998. "gcode_state": "IDLE",
  2999. "fun": "1C81A7FF9CFF",
  3000. }
  3001. }
  3002. mqtt_client._process_message(payload)
  3003. assert mqtt_client.state.developer_mode is False
  3004. def test_developer_mode_exact_bit_check(self, mqtt_client):
  3005. """Verify only bit 0x20000000 matters, not other bits."""
  3006. # 0x20000000 in hex = bit 29. Set ONLY that bit.
  3007. payload = {
  3008. "print": {
  3009. "gcode_state": "IDLE",
  3010. "fun": "000020000000",
  3011. }
  3012. }
  3013. mqtt_client._process_message(payload)
  3014. assert mqtt_client.state.developer_mode is False
  3015. # All zeros = all bits clear = developer mode ON
  3016. payload["print"]["fun"] = "000000000000"
  3017. mqtt_client._process_message(payload)
  3018. assert mqtt_client.state.developer_mode is True
  3019. def test_developer_mode_invalid_fun_ignored(self, mqtt_client):
  3020. """Verify invalid fun values don't crash or change state."""
  3021. mqtt_client.state.developer_mode = True
  3022. payload = {
  3023. "print": {
  3024. "gcode_state": "IDLE",
  3025. "fun": "not_a_hex_value",
  3026. }
  3027. }
  3028. mqtt_client._process_message(payload)
  3029. # Should remain unchanged
  3030. assert mqtt_client.state.developer_mode is True
  3031. def test_developer_mode_missing_fun_preserves_state(self, mqtt_client):
  3032. """Verify messages without fun field don't reset developer_mode."""
  3033. mqtt_client.state.developer_mode = False
  3034. payload = {
  3035. "print": {
  3036. "gcode_state": "RUNNING",
  3037. "mc_percent": 50,
  3038. }
  3039. }
  3040. mqtt_client._process_message(payload)
  3041. assert mqtt_client.state.developer_mode is False
  3042. def test_developer_mode_persists_across_messages(self, mqtt_client):
  3043. """Verify developer_mode set by fun persists across messages without fun."""
  3044. # First message sets developer_mode
  3045. mqtt_client._process_message(
  3046. {
  3047. "print": {
  3048. "gcode_state": "IDLE",
  3049. "fun": "3EC1AFFF9CFF",
  3050. }
  3051. }
  3052. )
  3053. assert mqtt_client.state.developer_mode is False
  3054. # Subsequent messages without fun don't change it
  3055. for _ in range(3):
  3056. mqtt_client._process_message(
  3057. {
  3058. "print": {
  3059. "gcode_state": "RUNNING",
  3060. "mc_percent": 50,
  3061. }
  3062. }
  3063. )
  3064. assert mqtt_client.state.developer_mode is False
  3065. class TestMqttCommandVerificationFailed:
  3066. """HMS 0500_0500_0001_0007 is the printer refusing to verify our commands (#2732).
  3067. A P1S on firmware 01.10.00.00 answers queries normally while dropping every
  3068. control command, so nothing else in the connection looks wrong. This HMS is
  3069. the only direct evidence, which makes it authoritative over the probe.
  3070. """
  3071. @pytest.fixture
  3072. def mqtt_client(self):
  3073. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3074. return BambuMQTTClient(
  3075. ip_address="192.168.1.100",
  3076. serial_number="01S00A000000000",
  3077. access_code="12345678",
  3078. )
  3079. @staticmethod
  3080. def _hms_payload(*entries):
  3081. return {"print": {"gcode_state": "IDLE", "hms": list(entries)}}
  3082. # attr 0x05000500, code 0x00010007 — the values a real P1S sends.
  3083. VERIFY_FAILED = {"attr": 83887360, "code": 65543}
  3084. OTHER_FAULT = {"attr": 0x03000200, "code": 0x00018012}
  3085. def test_hms_forces_developer_mode_false(self, mqtt_client):
  3086. mqtt_client.state.developer_mode = True # what the probe wrongly concluded
  3087. mqtt_client._process_message(self._hms_payload(self.VERIFY_FAILED))
  3088. assert mqtt_client.state.developer_mode is False
  3089. def test_hms_is_surfaced_with_its_full_code(self, mqtt_client):
  3090. """The short code collapses to a useless 0500_0007 — full_code must survive."""
  3091. from backend.app.services.bambu_mqtt import HMS_MQTT_VERIFY_FAILED
  3092. mqtt_client._process_message(self._hms_payload(self.VERIFY_FAILED))
  3093. assert [e.full_code for e in mqtt_client.state.hms_errors] == [HMS_MQTT_VERIFY_FAILED]
  3094. def test_unrelated_hms_does_not_touch_developer_mode(self, mqtt_client):
  3095. mqtt_client.state.developer_mode = True
  3096. mqtt_client._process_message(self._hms_payload(self.OTHER_FAULT))
  3097. assert mqtt_client.state.developer_mode is True
  3098. def test_clearing_the_hms_re_arms_the_probe(self, mqtt_client):
  3099. """Enabling Developer Mode and restarting must not leave a stuck False."""
  3100. mqtt_client._process_message(self._hms_payload(self.VERIFY_FAILED))
  3101. assert mqtt_client.state.developer_mode is False
  3102. mqtt_client._dev_mode_probed = True
  3103. mqtt_client._process_message(self._hms_payload())
  3104. assert mqtt_client.state.developer_mode is None
  3105. assert mqtt_client._dev_mode_probed is False
  3106. def test_empty_hms_leaves_a_probe_verdict_alone(self, mqtt_client):
  3107. """Only the HMS-derived latch self-clears; a probe's False is not ours to undo."""
  3108. mqtt_client.state.developer_mode = False # from an explicit probe refusal
  3109. mqtt_client._process_message(self._hms_payload())
  3110. assert mqtt_client.state.developer_mode is False
  3111. def test_inconclusive_probe_does_not_overwrite_the_hms_verdict(self, mqtt_client):
  3112. mqtt_client._process_message(self._hms_payload(self.VERIFY_FAILED))
  3113. mqtt_client._handle_dev_mode_probe_response({"command": "ams_filament_setting", "sequence_id": "3"})
  3114. assert mqtt_client.state.developer_mode is False
  3115. class TestDeveloperModeProbeInconclusive:
  3116. """An empty probe response proves nothing and must not read as ENABLED (#2732)."""
  3117. @pytest.fixture
  3118. def mqtt_client(self):
  3119. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3120. return BambuMQTTClient(
  3121. ip_address="192.168.1.100",
  3122. serial_number="TEST123",
  3123. access_code="12345678",
  3124. )
  3125. def test_empty_result_stays_unknown(self, mqtt_client):
  3126. """P1S 01.10.00.00 echoes the command back with no `result` field at all."""
  3127. mqtt_client._handle_dev_mode_probe_response({"command": "ams_filament_setting", "sequence_id": "3"})
  3128. assert mqtt_client.state.developer_mode is None
  3129. def test_explicit_success_still_enables(self, mqtt_client):
  3130. mqtt_client._handle_dev_mode_probe_response({"sequence_id": "3", "result": "success"})
  3131. assert mqtt_client.state.developer_mode is True
  3132. def test_verify_failure_still_disables(self, mqtt_client):
  3133. mqtt_client._handle_dev_mode_probe_response(
  3134. {"sequence_id": "3", "result": "failed", "reason": "mqtt message verify failed"}
  3135. )
  3136. assert mqtt_client.state.developer_mode is False
  3137. def test_inconclusive_response_still_clears_probe_bookkeeping(self, mqtt_client):
  3138. """Whatever the verdict, the response ends the probe (no retry storm)."""
  3139. mqtt_client._dev_mode_probe_seq = "3"
  3140. mqtt_client._dev_mode_probe_failures = 1
  3141. mqtt_client._handle_dev_mode_probe_response({"sequence_id": "3", "result": ""})
  3142. assert mqtt_client._dev_mode_probe_seq is None
  3143. assert mqtt_client._dev_mode_probe_failures == 0
  3144. class TestDeveloperModeProbeTimeout:
  3145. """Tests for developer mode probe timeout, retry, and forced reconnect (#887).
  3146. When a printer's MQTT session is half-broken (sends status but ignores
  3147. commands), the developer mode probe gets no response. The timeout logic
  3148. retries once, then force-closes the socket on the second failure.
  3149. """
  3150. @pytest.fixture
  3151. def mqtt_client(self):
  3152. import time
  3153. from unittest.mock import MagicMock
  3154. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3155. client = BambuMQTTClient(
  3156. ip_address="192.168.1.100",
  3157. serial_number="TEST123",
  3158. access_code="12345678",
  3159. )
  3160. # Simulate connected state with a mock MQTT client
  3161. client.state.connected = True
  3162. mock_paho = MagicMock()
  3163. mock_paho.socket.return_value = MagicMock()
  3164. client._client = mock_paho
  3165. # Set connect time in the past so the 5s probe delay is satisfied
  3166. client._connect_time = time.monotonic() - 10.0
  3167. return client
  3168. def _make_pushall_data(self):
  3169. """Create a print data dict with >30 keys (triggers probe) and no 'fun' field."""
  3170. return {f"key_{i}": i for i in range(35)}
  3171. def test_first_timeout_allows_retry(self, mqtt_client):
  3172. """After first probe timeout, _dev_mode_probed resets to allow retry."""
  3173. import time
  3174. data = self._make_pushall_data()
  3175. # First pushall triggers the probe
  3176. mqtt_client._update_state(data)
  3177. assert mqtt_client._dev_mode_probed is True
  3178. assert mqtt_client._dev_mode_probe_seq is not None
  3179. assert mqtt_client.state.developer_mode is None
  3180. # Simulate 11 seconds passing
  3181. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  3182. # Next status message detects the timeout
  3183. mqtt_client._update_state(data)
  3184. assert mqtt_client._dev_mode_probe_failures == 1
  3185. assert mqtt_client._dev_mode_probe_seq is None
  3186. # Should allow retry on next full message
  3187. assert mqtt_client._dev_mode_probed is False
  3188. # Connection should NOT be force-closed after 1 failure
  3189. assert mqtt_client.state.connected is True
  3190. def test_second_timeout_forces_reconnect(self, mqtt_client):
  3191. """After two consecutive probe timeouts, force-close the socket.
  3192. Probe timeout detection runs from paho's network thread (no asyncio
  3193. loop), so force_reconnect_stale_session routes through socket-close
  3194. rather than hard-reset (loop_stop from inside the loop deadlocks)."""
  3195. import time
  3196. data = self._make_pushall_data()
  3197. state_change_called = []
  3198. mqtt_client.on_state_change = lambda s: state_change_called.append(True)
  3199. # First probe + timeout
  3200. mqtt_client._update_state(data)
  3201. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  3202. mqtt_client._update_state(data)
  3203. assert mqtt_client._dev_mode_probe_failures == 1
  3204. # Second probe (retry) + timeout
  3205. mqtt_client._update_state(data) # triggers new probe
  3206. assert mqtt_client._dev_mode_probed is True
  3207. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  3208. mqtt_client._update_state(data) # detects second timeout
  3209. assert mqtt_client._dev_mode_probe_failures == 2
  3210. assert mqtt_client.state.connected is False
  3211. assert mqtt_client._stale_reconnecting is True
  3212. # Sync test → no running loop → socket-close fallback path
  3213. mqtt_client._client.socket().close.assert_called()
  3214. assert len(state_change_called) > 0
  3215. def test_successful_probe_resets_failure_counter(self, mqtt_client):
  3216. """A probe response after a previous failure resets the counter."""
  3217. import time
  3218. data = self._make_pushall_data()
  3219. # First probe + timeout → failure=1
  3220. mqtt_client._update_state(data)
  3221. seq = mqtt_client._dev_mode_probe_seq
  3222. mqtt_client._dev_mode_probe_time = time.monotonic() - 11.0
  3223. mqtt_client._update_state(data)
  3224. assert mqtt_client._dev_mode_probe_failures == 1
  3225. # Retry probe
  3226. mqtt_client._update_state(data)
  3227. new_seq = mqtt_client._dev_mode_probe_seq
  3228. assert new_seq is not None
  3229. assert new_seq != seq
  3230. # Simulate successful response
  3231. mqtt_client._handle_dev_mode_probe_response(
  3232. {
  3233. "command": "ams_filament_setting",
  3234. "sequence_id": new_seq,
  3235. "result": "success",
  3236. }
  3237. )
  3238. assert mqtt_client._dev_mode_probe_failures == 0
  3239. assert mqtt_client.state.developer_mode is True
  3240. assert mqtt_client._dev_mode_probe_seq is None
  3241. def test_no_timeout_when_probe_not_sent(self, mqtt_client):
  3242. """The timeout branch is only entered when a probe is pending."""
  3243. # No probe sent — _dev_mode_probed is False, _dev_mode_probe_seq is None
  3244. data = {"gcode_state": "IDLE", "mc_percent": 0} # < 30 keys
  3245. mqtt_client._update_state(data)
  3246. assert mqtt_client._dev_mode_probe_failures == 0
  3247. def test_on_connect_resets_probe_state_but_preserves_developer_mode(self, mqtt_client):
  3248. """_on_connect resets probe tracking but preserves cached developer_mode."""
  3249. import time
  3250. mqtt_client._dev_mode_probed = True
  3251. mqtt_client._dev_mode_probe_seq = "42"
  3252. mqtt_client._dev_mode_probe_time = time.monotonic()
  3253. mqtt_client._dev_mode_probe_failures = 2
  3254. mqtt_client.state.developer_mode = True
  3255. # subscribe() must return (result, mid) tuple
  3256. mqtt_client._client.subscribe.return_value = (0, 1)
  3257. mqtt_client._on_connect(mqtt_client._client, None, None, 0)
  3258. # developer_mode is preserved across reconnects (#887)
  3259. assert mqtt_client.state.developer_mode is True
  3260. assert mqtt_client._dev_mode_probed is False
  3261. assert mqtt_client._dev_mode_probe_seq is None
  3262. assert mqtt_client._dev_mode_probe_time == 0.0
  3263. assert mqtt_client._dev_mode_probe_failures == 0
  3264. assert mqtt_client._connect_time > 0
  3265. def test_probe_deferred_when_connect_too_recent(self, mqtt_client):
  3266. """Probe is deferred if less than 5s have passed since _on_connect."""
  3267. import time
  3268. data = self._make_pushall_data()
  3269. # Set connect time to 1 second ago — too recent for probe
  3270. mqtt_client._connect_time = time.monotonic() - 1.0
  3271. mqtt_client._update_state(data)
  3272. # Pushall seen, so needs_probe is set, but probe NOT fired yet
  3273. assert mqtt_client._dev_mode_needs_probe is True
  3274. assert mqtt_client._dev_mode_probed is False
  3275. assert mqtt_client._dev_mode_probe_seq is None
  3276. def test_probe_fires_after_delay(self, mqtt_client):
  3277. """Probe fires once 5s have passed since _on_connect."""
  3278. import time
  3279. data = self._make_pushall_data()
  3280. # Set connect time to 6 seconds ago — delay satisfied
  3281. mqtt_client._connect_time = time.monotonic() - 6.0
  3282. mqtt_client._update_state(data)
  3283. # Probe should have fired
  3284. assert mqtt_client._dev_mode_needs_probe is True
  3285. assert mqtt_client._dev_mode_probed is True
  3286. assert mqtt_client._dev_mode_probe_seq is not None
  3287. def test_probe_fires_on_incremental_after_delay(self, mqtt_client):
  3288. """After seeing a pushall within 5s, probe fires on later incremental message."""
  3289. import time
  3290. pushall_data = self._make_pushall_data()
  3291. incremental_data = {"gcode_state": "IDLE", "mc_percent": 0} # < 30 keys
  3292. # Pushall arrives 1s after connect — too early for probe
  3293. mqtt_client._connect_time = time.monotonic() - 1.0
  3294. mqtt_client._update_state(pushall_data)
  3295. assert mqtt_client._dev_mode_needs_probe is True
  3296. assert mqtt_client._dev_mode_probed is False
  3297. # 5s later, an incremental update arrives — probe fires now
  3298. mqtt_client._connect_time = time.monotonic() - 6.0
  3299. mqtt_client._update_state(incremental_data)
  3300. assert mqtt_client._dev_mode_probed is True
  3301. assert mqtt_client._dev_mode_probe_seq is not None
  3302. def test_no_reprobe_when_developer_mode_cached(self, mqtt_client):
  3303. """Auto-reconnect preserves developer_mode, skipping reprobe."""
  3304. import time
  3305. data = self._make_pushall_data()
  3306. # Simulate known developer_mode from previous connection
  3307. mqtt_client.state.developer_mode = True
  3308. mqtt_client._connect_time = time.monotonic() - 10.0
  3309. mqtt_client._update_state(data)
  3310. # Should NOT probe — developer_mode is already known
  3311. assert mqtt_client._dev_mode_needs_probe is False
  3312. assert mqtt_client._dev_mode_probed is False
  3313. assert mqtt_client._dev_mode_probe_seq is None
  3314. assert mqtt_client.state.developer_mode is True
  3315. def test_on_connect_resets_needs_probe(self, mqtt_client):
  3316. """_on_connect resets _dev_mode_needs_probe for a clean start."""
  3317. mqtt_client._dev_mode_needs_probe = True
  3318. mqtt_client._client.subscribe.return_value = (0, 1)
  3319. mqtt_client._on_connect(mqtt_client._client, None, None, 0)
  3320. assert mqtt_client._dev_mode_needs_probe is False
  3321. class TestVtTrayNormalization:
  3322. """Tests for vt_tray dict→list normalization in _update_state.
  3323. MQTT sends vt_tray as a dict for single-slot printers, but all consumers
  3324. expect a list. _update_state must normalize it before any callback can
  3325. read raw_data, because the dev-mode probe may release the GIL and let
  3326. the event loop read the partially-updated state.
  3327. """
  3328. @pytest.fixture
  3329. def mqtt_client(self):
  3330. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3331. client = BambuMQTTClient(
  3332. ip_address="192.168.1.100",
  3333. serial_number="TEST123",
  3334. access_code="12345678",
  3335. )
  3336. return client
  3337. def test_vt_tray_dict_normalized_in_update_state(self, mqtt_client):
  3338. """Verify _update_state wraps a raw vt_tray dict into a list."""
  3339. vt_dict = {
  3340. "id": "254",
  3341. "tray_color": "FF0000",
  3342. "tray_type": "PLA",
  3343. "tag_uid": "0000000000000000",
  3344. "tray_uuid": "00000000000000000000000000000000",
  3345. }
  3346. data = {"gcode_state": "IDLE", "vt_tray": vt_dict}
  3347. mqtt_client._update_state(data)
  3348. stored = mqtt_client.state.raw_data.get("vt_tray")
  3349. assert isinstance(stored, list)
  3350. assert len(stored) == 1
  3351. assert stored[0]["tray_color"] == "FF0000"
  3352. def test_vt_tray_list_unchanged_in_update_state(self, mqtt_client):
  3353. """Verify _update_state keeps an already-list vt_tray unchanged."""
  3354. vt_list = [
  3355. {"id": "254", "tray_type": "PLA"},
  3356. {"id": "255", "tray_type": "PETG"},
  3357. ]
  3358. data = {"gcode_state": "IDLE", "vt_tray": vt_list}
  3359. mqtt_client._update_state(data)
  3360. stored = mqtt_client.state.raw_data.get("vt_tray")
  3361. assert isinstance(stored, list)
  3362. assert len(stored) == 2
  3363. def test_preserved_vt_tray_restored_before_probe(self, mqtt_client):
  3364. """Verify preserved vt_tray is restored before dev-mode probe runs.
  3365. On the first message, the incremental handler wraps vt_tray into a list
  3366. and stores it. _update_state then replaces raw_data with the full data
  3367. dict, but must restore preserved fields BEFORE the probe publishes
  3368. (which can release the GIL).
  3369. """
  3370. # Simulate: incremental handler already stored a wrapped list
  3371. mqtt_client.state.raw_data = {
  3372. "vt_tray": [{"id": "254", "tray_type": "PLA", "tray_color": "00FF00"}],
  3373. }
  3374. # Now _update_state runs with new data that has vt_tray as dict
  3375. new_data = {
  3376. "gcode_state": "IDLE",
  3377. "vt_tray": {"id": "254", "tray_type": "PETG", "tray_color": "FF0000"},
  3378. }
  3379. mqtt_client._update_state(new_data)
  3380. # The preserved list (PLA/green) should take priority over new data
  3381. stored = mqtt_client.state.raw_data["vt_tray"]
  3382. assert isinstance(stored, list)
  3383. assert stored[0]["tray_type"] == "PLA"
  3384. assert stored[0]["tray_color"] == "00FF00"
  3385. def test_first_message_vt_tray_dict_becomes_list(self, mqtt_client):
  3386. """Verify on the very first message, vt_tray dict is still a list.
  3387. When there's no previously preserved data, the normalized dict should
  3388. remain as a list in raw_data.
  3389. """
  3390. # raw_data starts empty — no preserved vt_tray
  3391. mqtt_client.state.raw_data = {}
  3392. data = {
  3393. "gcode_state": "IDLE",
  3394. "vt_tray": {"id": "254", "tray_type": "ABS"},
  3395. }
  3396. mqtt_client._update_state(data)
  3397. stored = mqtt_client.state.raw_data["vt_tray"]
  3398. assert isinstance(stored, list)
  3399. assert stored[0]["tray_type"] == "ABS"
  3400. class TestSendDryingCommand:
  3401. """Tests for send_drying_command MQTT payload construction."""
  3402. @pytest.fixture
  3403. def mqtt_client(self):
  3404. """Create a BambuMQTTClient with a mock MQTT client."""
  3405. from unittest.mock import MagicMock
  3406. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3407. client = BambuMQTTClient(
  3408. ip_address="192.168.1.100",
  3409. serial_number="TEST123",
  3410. access_code="12345678",
  3411. )
  3412. client._client = MagicMock()
  3413. return client
  3414. def test_rotate_tray_false_by_default(self, mqtt_client):
  3415. """Verify rotate_tray defaults to False in the MQTT payload."""
  3416. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  3417. call_args = mqtt_client._client.publish.call_args
  3418. payload = json.loads(call_args[0][1])
  3419. assert payload["print"]["rotate_tray"] is False
  3420. def test_rotate_tray_true_when_enabled(self, mqtt_client):
  3421. """Verify rotate_tray is True when explicitly enabled."""
  3422. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA", rotate_tray=True)
  3423. call_args = mqtt_client._client.publish.call_args
  3424. payload = json.loads(call_args[0][1])
  3425. assert payload["print"]["rotate_tray"] is True
  3426. def test_rotate_tray_false_on_stop(self, mqtt_client):
  3427. """Verify rotate_tray is False when stopping drying (mode=0)."""
  3428. mqtt_client.send_drying_command(ams_id=0, temp=0, duration=0, mode=0)
  3429. call_args = mqtt_client._client.publish.call_args
  3430. payload = json.loads(call_args[0][1])
  3431. assert payload["print"]["rotate_tray"] is False
  3432. def test_all_required_fields_present(self, mqtt_client):
  3433. """Verify all required MQTT fields are present in the drying command."""
  3434. mqtt_client.send_drying_command(ams_id=128, temp=75, duration=8, mode=1, filament="ABS", rotate_tray=True)
  3435. call_args = mqtt_client._client.publish.call_args
  3436. payload = json.loads(call_args[0][1])
  3437. cmd = payload["print"]
  3438. assert cmd["command"] == "ams_filament_drying"
  3439. assert cmd["ams_id"] == 128
  3440. assert cmd["temp"] == 75
  3441. assert cmd["duration"] == 8
  3442. assert cmd["mode"] == 1
  3443. assert cmd["rotate_tray"] is True
  3444. assert cmd["filament"] == "ABS"
  3445. assert cmd["cooling_temp"] == 20
  3446. assert cmd["humidity"] == 0
  3447. assert cmd["close_power_conflict"] is False
  3448. assert "sequence_id" in cmd
  3449. def test_publishes_with_qos_1(self, mqtt_client):
  3450. """Verify drying commands are published with QoS 1."""
  3451. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4)
  3452. call_args = mqtt_client._client.publish.call_args
  3453. # qos may be positional arg [2] or keyword
  3454. qos = call_args.kwargs.get("qos", call_args[0][2] if len(call_args[0]) > 2 else None)
  3455. assert qos == 1
  3456. def test_start_caches_target_for_badge(self, mqtt_client):
  3457. """mode=1 send populates _drying_targets so the badge can render it."""
  3458. mqtt_client.send_drying_command(ams_id=2, temp=65, duration=12, mode=1, filament="PETG")
  3459. assert mqtt_client._drying_targets[2] == {"filament": "PETG", "temp": 65, "duration_hours": 12}
  3460. def test_start_overwrites_prior_target_for_same_ams(self, mqtt_client):
  3461. """A second start on the same AMS replaces the cached target."""
  3462. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  3463. mqtt_client.send_drying_command(ams_id=0, temp=70, duration=6, mode=1, filament="ABS")
  3464. assert mqtt_client._drying_targets[0] == {"filament": "ABS", "temp": 70, "duration_hours": 6}
  3465. def test_stop_clears_target(self, mqtt_client):
  3466. """mode=0 send drops the cache so the badge stops showing the target."""
  3467. mqtt_client.send_drying_command(ams_id=1, temp=55, duration=4, mode=1, filament="PLA")
  3468. assert 1 in mqtt_client._drying_targets
  3469. mqtt_client.send_drying_command(ams_id=1, temp=0, duration=0, mode=0)
  3470. assert 1 not in mqtt_client._drying_targets
  3471. def test_targets_isolated_per_ams_id(self, mqtt_client):
  3472. """Stopping one AMS doesn't affect another AMS's cached target."""
  3473. mqtt_client.send_drying_command(ams_id=0, temp=55, duration=4, mode=1, filament="PLA")
  3474. mqtt_client.send_drying_command(ams_id=128, temp=80, duration=6, mode=1, filament="PA-CF")
  3475. mqtt_client.send_drying_command(ams_id=0, temp=0, duration=0, mode=0)
  3476. assert 0 not in mqtt_client._drying_targets
  3477. assert mqtt_client._drying_targets[128] == {"filament": "PA-CF", "temp": 80, "duration_hours": 6}
  3478. class TestStartPrintAmsMapping:
  3479. """Tests for ams_mapping/ams_mapping2 construction in start_print().
  3480. BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  3481. ams_mapping and puts the real external spool info only in ams_mapping2.
  3482. Passing raw 254/255 in the flat array causes H2D firmware to fail
  3483. with 0700_8012 "Failed to get AMS mapping table".
  3484. """
  3485. @pytest.fixture
  3486. def mqtt_client(self):
  3487. from unittest.mock import MagicMock
  3488. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3489. client = BambuMQTTClient(
  3490. ip_address="192.168.1.100",
  3491. serial_number="TEST123",
  3492. access_code="12345678",
  3493. )
  3494. client._client = MagicMock()
  3495. client.state.connected = True
  3496. return client
  3497. def _get_published_command(self, mqtt_client):
  3498. """Extract the parsed print command from the last publish call."""
  3499. call_args = mqtt_client._client.publish.call_args
  3500. return json.loads(call_args[0][1])["print"]
  3501. def test_regular_ams_trays_preserved_in_flat_mapping(self, mqtt_client):
  3502. """Regular AMS tray IDs pass through unchanged in flat ams_mapping."""
  3503. mqtt_client.start_print("test.3mf", ams_mapping=[0, 5, 11])
  3504. cmd = self._get_published_command(mqtt_client)
  3505. assert cmd["ams_mapping"] == [0, 5, 11]
  3506. assert cmd["ams_mapping2"] == [
  3507. {"ams_id": 0, "slot_id": 0},
  3508. {"ams_id": 1, "slot_id": 1},
  3509. {"ams_id": 2, "slot_id": 3},
  3510. ]
  3511. def test_unmapped_slots(self, mqtt_client):
  3512. """Unmapped slots (-1) produce -1 in flat and 0xFF/0xFF in mapping2."""
  3513. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1])
  3514. cmd = self._get_published_command(mqtt_client)
  3515. assert cmd["ams_mapping"] == [-1, -1]
  3516. assert cmd["ams_mapping2"] == [
  3517. {"ams_id": 255, "slot_id": 255},
  3518. {"ams_id": 255, "slot_id": 255},
  3519. ]
  3520. def test_external_main_nozzle_becomes_minus_one_in_flat(self, mqtt_client):
  3521. """Virtual tray 255 (main nozzle) must be -1 in flat mapping."""
  3522. mqtt_client.start_print("test.3mf", ams_mapping=[255])
  3523. cmd = self._get_published_command(mqtt_client)
  3524. assert cmd["ams_mapping"] == [-1]
  3525. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  3526. def test_single_nozzle_external_spool_uses_main_id(self, mqtt_client):
  3527. """Single-nozzle external spool (254) maps to ams_id=255 (VIRTUAL_TRAY_MAIN_ID).
  3528. Firmware reports tray_now=254 for external spool, but the print command
  3529. must use ams_id=255 in ams_mapping2. Sending 254 causes the firmware to
  3530. target AMS tray 0 instead of external spool (07FF_8012 error).
  3531. """
  3532. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  3533. cmd = self._get_published_command(mqtt_client)
  3534. assert cmd["ams_mapping"] == [-1]
  3535. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  3536. def test_h2d_external_spool_mixed_with_ams(self, mqtt_client):
  3537. """H2D scenario: AMS trays + unmapped + external deputy nozzle."""
  3538. # Reproduces the exact scenario from issue #797:
  3539. # 5-slot 3MF, only slot 5 assigned to external deputy nozzle (254)
  3540. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1, -1, -1, 255])
  3541. cmd = self._get_published_command(mqtt_client)
  3542. # Flat mapping: all -1 (external converted, unmapped stay -1)
  3543. assert cmd["ams_mapping"] == [-1, -1, -1, -1, -1]
  3544. # Detailed mapping: unmapped slots use 0xFF, external uses real ams_id
  3545. assert cmd["ams_mapping2"] == [
  3546. {"ams_id": 255, "slot_id": 255},
  3547. {"ams_id": 255, "slot_id": 255},
  3548. {"ams_id": 255, "slot_id": 255},
  3549. {"ams_id": 255, "slot_id": 255},
  3550. {"ams_id": 255, "slot_id": 0},
  3551. ]
  3552. def test_ams_ht_trays_preserved_in_flat_mapping(self, mqtt_client):
  3553. """AMS-HT tray IDs (>=128) pass through in flat mapping."""
  3554. mqtt_client.start_print("test.3mf", ams_mapping=[128, 131])
  3555. cmd = self._get_published_command(mqtt_client)
  3556. assert cmd["ams_mapping"] == [128, 131]
  3557. assert cmd["ams_mapping2"] == [
  3558. {"ams_id": 128, "slot_id": 0},
  3559. {"ams_id": 131, "slot_id": 0},
  3560. ]
  3561. def test_non_h2d_both_external_maps_to_main_id(self, mqtt_client):
  3562. """Non-H2D: both 254 and 255 map to ams_id=255 (single nozzle)."""
  3563. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  3564. cmd = self._get_published_command(mqtt_client)
  3565. assert cmd["ams_mapping"] == [-1, -1]
  3566. assert cmd["ams_mapping2"] == [
  3567. {"ams_id": 255, "slot_id": 0},
  3568. {"ams_id": 255, "slot_id": 0},
  3569. ]
  3570. def test_h2d_external_preserves_deputy_id(self, mqtt_client):
  3571. """H2D dual-nozzle: 254 (deputy) stays 254, 255 (main) stays 255."""
  3572. mqtt_client.model = "H2D"
  3573. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  3574. cmd = self._get_published_command(mqtt_client)
  3575. assert cmd["ams_mapping"] == [-1, -1]
  3576. assert cmd["ams_mapping2"] == [
  3577. {"ams_id": 254, "slot_id": 0},
  3578. {"ams_id": 255, "slot_id": 0},
  3579. ]
  3580. def test_h2d_single_external_deputy(self, mqtt_client):
  3581. """H2D: single external spool on deputy nozzle (254) keeps ams_id=254."""
  3582. mqtt_client.model = "H2D Pro"
  3583. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  3584. cmd = self._get_published_command(mqtt_client)
  3585. assert cmd["ams_mapping"] == [-1]
  3586. assert cmd["ams_mapping2"] == [{"ams_id": 254, "slot_id": 0}]
  3587. def test_external_spool_only_sets_use_ams_false(self, mqtt_client):
  3588. """Single external spool on non-H2D printer sets use_ams=False."""
  3589. mqtt_client.start_print("test.3mf", ams_mapping=[254], use_ams=True)
  3590. cmd = self._get_published_command(mqtt_client)
  3591. assert cmd["use_ams"] is False
  3592. def test_all_unresolved_keeps_use_ams_true(self, mqtt_client):
  3593. """All-unresolved (-1) is NOT external — must keep use_ams=True (#2589).
  3594. A stored [-1] comes from an unresolved mapping (e.g. a frontend
  3595. status-load race), not an explicit external-spool selection. Treating it
  3596. as external silently started the print against the empty external feed.
  3597. Only >=254 may downgrade to use_ams=False.
  3598. """
  3599. mqtt_client.start_print("test.3mf", ams_mapping=[-1, -1], use_ams=True)
  3600. cmd = self._get_published_command(mqtt_client)
  3601. assert cmd["use_ams"] is True
  3602. def test_mixed_ams_and_external_keeps_use_ams_true(self, mqtt_client):
  3603. """AMS tray + external spool keeps use_ams=True."""
  3604. mqtt_client.start_print("test.3mf", ams_mapping=[0, 254], use_ams=True)
  3605. cmd = self._get_published_command(mqtt_client)
  3606. assert cmd["use_ams"] is True
  3607. def test_h2d_both_external_keeps_use_ams_true(self, mqtt_client):
  3608. """H2D with both external spools keeps use_ams=True (nozzle routing)."""
  3609. mqtt_client.model = "H2D"
  3610. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255], use_ams=True)
  3611. cmd = self._get_published_command(mqtt_client)
  3612. assert cmd["use_ams"] is True
  3613. def test_empty_ams_mapping_keeps_use_ams_true(self, mqtt_client):
  3614. """Empty ams_mapping list does not override use_ams."""
  3615. mqtt_client.start_print("test.3mf", ams_mapping=[], use_ams=True)
  3616. cmd = self._get_published_command(mqtt_client)
  3617. assert cmd["use_ams"] is True
  3618. def test_no_ams_mapping_omits_fields(self, mqtt_client):
  3619. """When ams_mapping is None, neither field is in the command."""
  3620. mqtt_client.start_print("test.3mf", ams_mapping=None)
  3621. cmd = self._get_published_command(mqtt_client)
  3622. assert "ams_mapping" not in cmd
  3623. assert "ams_mapping2" not in cmd
  3624. def test_x2d_external_preserves_deputy_id(self, mqtt_client):
  3625. """X2D dual-nozzle (#988): 254 (deputy) stays 254, like H2D family.
  3626. X2D launched April 2026 and shares the H2D-style dual-extruder
  3627. firmware convention — external spool on the deputy (left) nozzle
  3628. is addressed as ams_id=254, not coerced to 255.
  3629. """
  3630. mqtt_client.model = "X2D"
  3631. mqtt_client.start_print("test.3mf", ams_mapping=[254, 255])
  3632. cmd = self._get_published_command(mqtt_client)
  3633. assert cmd["ams_mapping"] == [-1, -1]
  3634. assert cmd["ams_mapping2"] == [
  3635. {"ams_id": 254, "slot_id": 0},
  3636. {"ams_id": 255, "slot_id": 0},
  3637. ]
  3638. def test_x2d_uses_boolean_format_for_calibration_fields(self, mqtt_client):
  3639. """X2D sends calibration fields as JSON booleans, like every model (#1478).
  3640. An earlier revision integer-encoded these for the H2 family on the
  3641. belief that H2 firmware required 0/1. A BambuStudio request-topic
  3642. capture from a real H2D disproved it — BambuStudio sends plain
  3643. booleans — so X2D follows the same boolean format.
  3644. """
  3645. mqtt_client.model = "X2D"
  3646. mqtt_client.start_print(
  3647. "test.3mf",
  3648. timelapse=True,
  3649. bed_levelling="off",
  3650. flow_cali="on",
  3651. vibration_cali=False,
  3652. layer_inspect=True,
  3653. )
  3654. cmd = self._get_published_command(mqtt_client)
  3655. assert cmd["timelapse"] is True
  3656. # bed_leveling stays a bool (true only for "on"); the tri-state rides on
  3657. # the auto_bed_leveling int.
  3658. assert cmd["bed_leveling"] is False
  3659. assert cmd["auto_bed_leveling"] == 0
  3660. assert cmd["flow_cali"] is True
  3661. assert cmd["vibration_cali"] is False
  3662. assert cmd["layer_inspect"] is True
  3663. # flow_cali on → extrude_cali_flag must request the calibration pass.
  3664. assert cmd["extrude_cali_flag"] == 1
  3665. def test_p2s_uses_boolean_format(self, mqtt_client):
  3666. """P2S sends calibration fields as JSON booleans (single-nozzle, like X1C/A1/P1)."""
  3667. mqtt_client.model = "P2S"
  3668. mqtt_client.start_print("test.3mf", timelapse=True, flow_cali="off")
  3669. cmd = self._get_published_command(mqtt_client)
  3670. assert cmd["timelapse"] is True
  3671. assert cmd["flow_cali"] is False
  3672. # flow_cali "off" → extrude_cali_flag=0 (firmware skips the pre-print
  3673. # calibration stage entirely). "auto" would send 2 instead.
  3674. assert cmd["extrude_cali_flag"] == 0
  3675. def test_h2s_single_external_spool_uses_main_id(self, mqtt_client):
  3676. """H2S is single-nozzle (#1386): external spool (254) → ams_id=255.
  3677. H2S shares serial prefix "094" and the H-family firmware-format
  3678. quirks with H2D, but it has a single extruder (nozzle_count=1
  3679. confirmed across 9+ support bundles). Routing the deputy-nozzle
  3680. sentinel (254) through to firmware on a single-nozzle printer
  3681. causes 07FF_8012 "Failed to get AMS mapping table" — exactly the
  3682. symptom reporter krootstijn hit when printing without an AMS.
  3683. """
  3684. mqtt_client.model = "H2S"
  3685. mqtt_client.start_print("test.3mf", ams_mapping=[254])
  3686. cmd = self._get_published_command(mqtt_client)
  3687. assert cmd["ams_mapping"] == [-1]
  3688. assert cmd["ams_mapping2"] == [{"ams_id": 255, "slot_id": 0}]
  3689. def test_h2s_no_ams_forces_use_ams_false(self, mqtt_client):
  3690. """H2S with only external spool must drop into the use_ams=False
  3691. fallback, like P1S/P1P. The dual-nozzle bypass kept this path
  3692. unreachable before #1386 — the firmware then rejected the print
  3693. with 07FF_8012 because there was no AMS mapping table.
  3694. """
  3695. mqtt_client.model = "H2S"
  3696. mqtt_client.start_print("test.3mf", ams_mapping=[254], use_ams=True)
  3697. cmd = self._get_published_command(mqtt_client)
  3698. assert cmd["use_ams"] is False
  3699. def test_h2s_uses_boolean_format_for_calibration_fields(self, mqtt_client):
  3700. """H2S sends calibration fields as JSON booleans (#1478).
  3701. The H2S was previously integer-encoded as part of the H2 family. That
  3702. made it accept the print command but silently skip flow-dynamics
  3703. calibration — the reporter saw poor corner quality from a stale K
  3704. value. BambuStudio sends booleans for these fields and pairs flow_cali
  3705. with extrude_cali_flag=1 to actually run the calibration pass.
  3706. """
  3707. mqtt_client.model = "H2S"
  3708. mqtt_client.start_print(
  3709. "test.3mf",
  3710. timelapse=True,
  3711. bed_levelling="off",
  3712. flow_cali="on",
  3713. vibration_cali=False,
  3714. layer_inspect=True,
  3715. )
  3716. cmd = self._get_published_command(mqtt_client)
  3717. assert cmd["timelapse"] is True
  3718. assert cmd["bed_leveling"] is False
  3719. assert cmd["flow_cali"] is True
  3720. assert cmd["vibration_cali"] is False
  3721. assert cmd["layer_inspect"] is True
  3722. # flow_cali on → extrude_cali_flag=1 so the printer runs the
  3723. # flow-dynamics calibration instead of reusing the stored PA value.
  3724. assert cmd["extrude_cali_flag"] == 1
  3725. def test_bed_leveling_auto_sends_int_two(self, mqtt_client):
  3726. """`bed_levelling="auto"` → bool false + auto_bed_leveling=2.
  3727. Matches BambuStudio's ops_auto wire shape: the bool is true only for the
  3728. explicit "on" state; "auto" carries its intent in the int (2 = run only
  3729. if the bed wasn't levelled recently).
  3730. """
  3731. mqtt_client.model = "X1C"
  3732. mqtt_client.start_print("test.3mf", bed_levelling="auto")
  3733. cmd = self._get_published_command(mqtt_client)
  3734. assert cmd["bed_leveling"] is False
  3735. assert cmd["auto_bed_leveling"] == 2
  3736. def test_bed_leveling_on_sends_int_one(self, mqtt_client):
  3737. """`bed_levelling="on"` → bool true + auto_bed_leveling=1 (force)."""
  3738. mqtt_client.model = "X1C"
  3739. mqtt_client.start_print("test.3mf", bed_levelling="on")
  3740. cmd = self._get_published_command(mqtt_client)
  3741. assert cmd["bed_leveling"] is True
  3742. assert cmd["auto_bed_leveling"] == 1
  3743. def test_flow_cali_auto_sends_int_two(self, mqtt_client):
  3744. """`flow_cali="auto"` → bool false + extrude_cali_flag=2.
  3745. #1721 saw stage 8 stay queued on 2 — that is the auto contract (queued,
  3746. skipped at runtime if the filament was calibrated recently), which is
  3747. exactly what "auto" should do.
  3748. """
  3749. mqtt_client.model = "X1C"
  3750. mqtt_client.start_print("test.3mf", flow_cali="auto")
  3751. cmd = self._get_published_command(mqtt_client)
  3752. assert cmd["flow_cali"] is False
  3753. assert cmd["extrude_cali_flag"] == 2
  3754. def test_nozzle_offset_cali_default_auto_gated_on_single_nozzle(self, mqtt_client):
  3755. """Default (auto) on a single-nozzle printer → wire value `0`.
  3756. The default is now "auto", but single-nozzle machines have no second
  3757. head to calibrate, so the MQTT layer gates any state to `0` there.
  3758. """
  3759. mqtt_client.model = "P1S"
  3760. mqtt_client.start_print("test.3mf")
  3761. cmd = self._get_published_command(mqtt_client)
  3762. assert cmd["nozzle_offset_cali"] == 0
  3763. def test_nozzle_offset_cali_ignored_on_single_nozzle(self, mqtt_client):
  3764. """Single-nozzle printer: `nozzle_offset_cali="on"` is silently dropped.
  3765. H2S is in the H2 firmware family but single-nozzle. The toggle has
  3766. no physical meaning on single-nozzle machines and the UI gates it
  3767. behind `nozzle_count==2`. Even if a stale queue item from when the
  3768. printer was misidentified as dual carries the flag, the MQTT layer
  3769. must downgrade it so firmware never tries to calibrate a head it
  3770. doesn't have (#1682).
  3771. """
  3772. mqtt_client.model = "P1S"
  3773. mqtt_client.start_print("test.3mf", nozzle_offset_cali="on")
  3774. cmd = self._get_published_command(mqtt_client)
  3775. assert cmd["nozzle_offset_cali"] == 0
  3776. def test_nozzle_offset_cali_honored_on_dual_nozzle(self, mqtt_client):
  3777. """Dual-nozzle printer (H2D): `nozzle_offset_cali="on"` → wire value `1`.
  3778. H2D is in `DUAL_NOZZLE_MODELS`. The toggle controls whether the
  3779. printer runs the nozzle-offset calibration pass before the print
  3780. starts. "on"=1 (force), "auto"=2, "off"=0 (#1682).
  3781. """
  3782. mqtt_client.model = "H2D"
  3783. mqtt_client.start_print("test.3mf", nozzle_offset_cali="on")
  3784. cmd = self._get_published_command(mqtt_client)
  3785. assert cmd["nozzle_offset_cali"] == 1
  3786. def test_nozzle_offset_cali_auto_on_dual_nozzle(self, mqtt_client):
  3787. """Dual-nozzle printer (H2D): `nozzle_offset_cali="auto"` → wire value `2`."""
  3788. mqtt_client.model = "H2D"
  3789. mqtt_client.start_print("test.3mf", nozzle_offset_cali="auto")
  3790. cmd = self._get_published_command(mqtt_client)
  3791. assert cmd["nozzle_offset_cali"] == 2
  3792. def test_nozzle_offset_cali_off_on_dual_nozzle(self, mqtt_client):
  3793. """Dual-nozzle printer (H2D Pro): `nozzle_offset_cali="off"` → `0` (skip).
  3794. Critical for users like #1682 who run diamond nozzles and need to
  3795. keep the calibration off.
  3796. """
  3797. mqtt_client.model = "H2D Pro"
  3798. mqtt_client.start_print("test.3mf", nozzle_offset_cali="off")
  3799. cmd = self._get_published_command(mqtt_client)
  3800. assert cmd["nozzle_offset_cali"] == 0
  3801. class TestStartPrintUniqueIdentityFields:
  3802. """Regression guard: project_id/subtask_id/task_id must be unique per submission (#1011).
  3803. Hardcoded "0" values caused third-party MQTT observers (e.g. OctoEverywhere)
  3804. to treat archive reprints as continuations of the same job and report
  3805. compounding durations on repeat replays. Each start_print call must produce
  3806. a distinct, non-zero identity triplet so the printer emits a fresh state
  3807. transition. md5 is deliberately left empty — historically firmware treats
  3808. "" as "skip validation" and we don't have the file's real digest here.
  3809. """
  3810. @pytest.fixture
  3811. def mqtt_client(self):
  3812. from unittest.mock import MagicMock
  3813. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3814. client = BambuMQTTClient(
  3815. ip_address="192.168.1.100",
  3816. serial_number="TEST123",
  3817. access_code="12345678",
  3818. )
  3819. client._client = MagicMock()
  3820. client.state.connected = True
  3821. return client
  3822. def _get_published_command(self, mqtt_client):
  3823. call_args = mqtt_client._client.publish.call_args
  3824. return json.loads(call_args[0][1])["print"]
  3825. def test_identity_fields_are_non_zero(self, mqtt_client):
  3826. mqtt_client.start_print("test.3mf")
  3827. cmd = self._get_published_command(mqtt_client)
  3828. assert cmd["project_id"] != "0"
  3829. assert cmd["subtask_id"] != "0"
  3830. assert cmd["task_id"] != "0"
  3831. def test_identity_fields_are_all_equal_per_submission(self, mqtt_client):
  3832. """All three IDs come from the same submission timestamp — Studio also
  3833. uses a single identity per submission across the three fields."""
  3834. mqtt_client.start_print("test.3mf")
  3835. cmd = self._get_published_command(mqtt_client)
  3836. assert cmd["project_id"] == cmd["subtask_id"] == cmd["task_id"]
  3837. def test_md5_stays_empty(self, mqtt_client):
  3838. """Deliberate: synthetic md5 risks activating firmware validation."""
  3839. mqtt_client.start_print("test.3mf")
  3840. cmd = self._get_published_command(mqtt_client)
  3841. assert cmd["md5"] == ""
  3842. def test_identity_fields_change_between_submissions(self, mqtt_client):
  3843. """Two successive start_print calls must produce different IDs.
  3844. Without this, the printer can't tell replays apart and reuses
  3845. gcode_start_time from the prior job.
  3846. """
  3847. mqtt_client.start_print("test.3mf")
  3848. first = self._get_published_command(mqtt_client)
  3849. time.sleep(0.002)
  3850. mqtt_client.start_print("test.3mf")
  3851. second = self._get_published_command(mqtt_client)
  3852. assert first["task_id"] != second["task_id"]
  3853. assert first["subtask_id"] != second["subtask_id"]
  3854. assert first["project_id"] != second["project_id"]
  3855. def test_submission_id_is_numeric_string(self, mqtt_client):
  3856. """ID format: digits-only string. Studio uses cloud task IDs that are
  3857. also numeric-looking strings; the DB column is VARCHAR(64) and
  3858. Bambuddy's own subtask_id parser treats '0'/'' as absent — any valid
  3859. digit string that isn't '0' is fine."""
  3860. mqtt_client.start_print("test.3mf")
  3861. cmd = self._get_published_command(mqtt_client)
  3862. assert cmd["task_id"].isdigit()
  3863. assert int(cmd["task_id"]) > 0
  3864. assert len(cmd["task_id"]) <= 64
  3865. def test_last_dispatch_subtask_id_records_the_minted_id(self, mqtt_client):
  3866. """#1485: start_print records the minted id on the client so
  3867. on_print_start can persist it on the archive before the printer
  3868. echoes subtask_id back — letting a later restart resume by id."""
  3869. assert mqtt_client.last_dispatch_subtask_id is None
  3870. mqtt_client.start_print("test.3mf")
  3871. cmd = self._get_published_command(mqtt_client)
  3872. assert mqtt_client.last_dispatch_subtask_id == cmd["subtask_id"]
  3873. def test_last_dispatch_subtask_id_updates_per_submission(self, mqtt_client):
  3874. """Each dispatch overwrites the recorded id with the new submission's."""
  3875. mqtt_client.start_print("test.3mf")
  3876. first = mqtt_client.last_dispatch_subtask_id
  3877. time.sleep(0.002)
  3878. mqtt_client.start_print("test.3mf")
  3879. assert mqtt_client.last_dispatch_subtask_id != first
  3880. assert mqtt_client.last_dispatch_subtask_id == self._get_published_command(mqtt_client)["subtask_id"]
  3881. def test_submission_id_fits_signed_int32(self, mqtt_client):
  3882. """Regression for #1042: P1S firmware clamps oversized task identity
  3883. fields to signed int32 max (2**31-1 = 2147483647). If we send raw
  3884. epoch-ms (~1.7e12), the printer sees a saturated constant on every
  3885. submission and treats fresh dispatches as continuations of the last
  3886. FAILED job — never leaves IDLE. Keep below 2**31.
  3887. """
  3888. mqtt_client.start_print("test.3mf")
  3889. cmd = self._get_published_command(mqtt_client)
  3890. assert int(cmd["task_id"]) < 2**31
  3891. assert int(cmd["project_id"]) < 2**31
  3892. assert int(cmd["subtask_id"]) < 2**31
  3893. def test_unrelated_payload_fields_untouched(self, mqtt_client):
  3894. """Regression guard: fix only touches identity fields; everything else
  3895. (sequence_id, command verb, calibration defaults, profile_id) must be
  3896. unchanged to avoid silently breaking printer behavior."""
  3897. mqtt_client.start_print("test.3mf")
  3898. cmd = self._get_published_command(mqtt_client)
  3899. assert cmd["sequence_id"] == "20000"
  3900. assert cmd["command"] == "project_file"
  3901. assert cmd["param"] == "Metadata/plate_1.gcode"
  3902. assert cmd["url"] == "ftp://test.3mf"
  3903. assert cmd["file"] == "test.3mf"
  3904. assert cmd["profile_id"] == "0"
  3905. assert cmd["cfg"] == "0"
  3906. assert cmd["subtask_name"] == "test"
  3907. class TestDeleteKProfileDualNozzleDetection:
  3908. """Regression guard: dual-nozzle detection for K-profile delete.
  3909. delete_kprofile branches on dual-nozzle status to pick the wire format.
  3910. Source of truth is the runtime `_is_dual_nozzle` flag (set from
  3911. device.extruder.info); model name is the fallback used before push
  3912. data arrives. Serial-prefix detection alone is wrong — H2S shares
  3913. prefix "094" with H2D but is single-nozzle (#1386).
  3914. """
  3915. def _make_client(self, *, serial: str = "TEST", model: str | None = None, dual_runtime: bool = False):
  3916. from unittest.mock import MagicMock
  3917. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3918. client = BambuMQTTClient(
  3919. ip_address="192.168.1.100",
  3920. serial_number=serial,
  3921. access_code="12345678",
  3922. )
  3923. client._client = MagicMock()
  3924. client.state.connected = True
  3925. client.model = model
  3926. client._is_dual_nozzle = dual_runtime
  3927. return client
  3928. def _published(self, client):
  3929. return json.loads(client._client.publish.call_args[0][1])["print"]
  3930. def test_h2d_model_uses_dual_nozzle_format(self):
  3931. client = self._make_client(serial="09400A000000001", model="H2D")
  3932. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3933. cmd = self._published(client)
  3934. # Dual-nozzle command omits setting_id.
  3935. assert "setting_id" not in cmd
  3936. assert cmd["extruder_id"] == 0
  3937. def test_x2d_model_uses_dual_nozzle_format(self):
  3938. client = self._make_client(serial="20P90A000000001", model="X2D")
  3939. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3940. cmd = self._published(client)
  3941. assert "setting_id" not in cmd
  3942. assert cmd["extruder_id"] == 0
  3943. def test_h2c_model_uses_dual_nozzle_format(self):
  3944. """Post-2026 H2C batches ship with '31B8B' prefix instead of '094' (#1105).
  3945. Model-name detection works regardless of serial prefix."""
  3946. client = self._make_client(serial="31B8BP000000001", model="H2C")
  3947. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3948. cmd = self._published(client)
  3949. assert "setting_id" not in cmd
  3950. assert cmd["extruder_id"] == 0
  3951. def test_runtime_dual_nozzle_flag_uses_dual_format(self):
  3952. """When _is_dual_nozzle is set from device.extruder.info, the model
  3953. fallback isn't needed (covers future dual-nozzle models we haven't
  3954. seen yet)."""
  3955. client = self._make_client(serial="UNKNOWN", model=None, dual_runtime=True)
  3956. client.delete_kprofile(cali_idx=1, filament_id="GFA00", nozzle_id="HH00-0.4")
  3957. cmd = self._published(client)
  3958. assert "setting_id" not in cmd
  3959. def test_h2s_uses_single_nozzle_format(self):
  3960. """H2S shares serial prefix "094" with H2D but is single-nozzle (#1386).
  3961. Must take the single-nozzle branch with setting_id included.
  3962. """
  3963. client = self._make_client(serial="09400S000000001", model="H2S")
  3964. client.delete_kprofile(
  3965. cali_idx=1,
  3966. filament_id="GFA00",
  3967. nozzle_id="HH00-0.4",
  3968. setting_id="PFB123",
  3969. )
  3970. cmd = self._published(client)
  3971. assert cmd["setting_id"] == "PFB123"
  3972. def test_p2s_uses_single_nozzle_format(self):
  3973. """P2S is single-nozzle — must NOT take the dual-nozzle branch."""
  3974. client = self._make_client(serial="22E00A000000001", model="P2S")
  3975. client.delete_kprofile(
  3976. cali_idx=1,
  3977. filament_id="GFA00",
  3978. nozzle_id="HH00-0.4",
  3979. setting_id="PFB123",
  3980. )
  3981. cmd = self._published(client)
  3982. # Single-nozzle command includes setting_id.
  3983. assert cmd["setting_id"] == "PFB123"
  3984. def test_x1c_uses_single_nozzle_format(self):
  3985. client = self._make_client(serial="00M00A000000001", model="X1C")
  3986. client.delete_kprofile(
  3987. cali_idx=1,
  3988. filament_id="GFA00",
  3989. nozzle_id="HH00-0.4",
  3990. setting_id="PFB123",
  3991. )
  3992. cmd = self._published(client)
  3993. assert cmd["setting_id"] == "PFB123"
  3994. class TestStaleReconnect:
  3995. """Tests for stale connection detection and reconnect without UI bouncing."""
  3996. @pytest.fixture
  3997. def mqtt_client(self):
  3998. from backend.app.services.bambu_mqtt import BambuMQTTClient
  3999. client = BambuMQTTClient(
  4000. ip_address="192.168.1.100",
  4001. serial_number="TEST_STALE",
  4002. access_code="12345678",
  4003. )
  4004. return client
  4005. def test_check_staleness_sets_flag_and_broadcasts_once(self, mqtt_client):
  4006. """check_staleness() should set connected=False, broadcast, and set _stale_reconnecting."""
  4007. import time
  4008. state_changes = []
  4009. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  4010. mqtt_client.state.connected = True
  4011. mqtt_client._last_message_time = time.time() - 120 # well past 60s threshold
  4012. result = mqtt_client.check_staleness()
  4013. assert result is False
  4014. assert mqtt_client.state.connected is False
  4015. assert mqtt_client._stale_reconnecting is True
  4016. assert state_changes == [False] # Exactly one broadcast
  4017. def test_check_staleness_noop_when_not_connected(self, mqtt_client):
  4018. """check_staleness() should not set flag when already disconnected."""
  4019. import time
  4020. mqtt_client.state.connected = False
  4021. mqtt_client._last_message_time = time.time() - 120
  4022. mqtt_client.check_staleness()
  4023. assert mqtt_client._stale_reconnecting is False
  4024. def test_check_staleness_noop_when_not_stale(self, mqtt_client):
  4025. """check_staleness() should not set flag when messages are recent."""
  4026. import time
  4027. mqtt_client.state.connected = True
  4028. mqtt_client._last_message_time = time.time() - 5 # 5s ago, well within 60s
  4029. result = mqtt_client.check_staleness()
  4030. assert result is True
  4031. assert mqtt_client.state.connected is True
  4032. assert mqtt_client._stale_reconnecting is False
  4033. def test_check_staleness_logs_serial_hint_when_no_reports(self, mqtt_client, caplog):
  4034. """#1465 — a stale connection that never received a status report logs
  4035. an actionable serial-number hint, exactly once."""
  4036. import logging
  4037. import time
  4038. mqtt_client.state.connected = True
  4039. mqtt_client._last_message_time = time.time() - 120
  4040. mqtt_client._report_messages_since_connect = 0
  4041. with caplog.at_level(logging.WARNING):
  4042. mqtt_client.check_staleness()
  4043. assert mqtt_client._zero_report_hint_logged is True
  4044. assert any("zero status reports" in r.getMessage() for r in caplog.records)
  4045. # Re-arm staleness — the hint must not log a second time.
  4046. caplog.clear()
  4047. mqtt_client.state.connected = True
  4048. mqtt_client._last_message_time = time.time() - 120
  4049. mqtt_client._last_stale_reconnect = 0.0 # bypass the reconnect cooldown
  4050. with caplog.at_level(logging.WARNING):
  4051. mqtt_client.check_staleness()
  4052. assert not any("zero status reports" in r.getMessage() for r in caplog.records)
  4053. def test_check_staleness_no_serial_hint_right_after_reconnect(self, mqtt_client, caplog):
  4054. """#2732 — _report_messages_since_connect is reset by _on_connect, so a
  4055. reconnect landing just before the staleness check leaves it at 0 for
  4056. reasons that have nothing to do with the serial. A healthy P1S was being
  4057. told to check its serial number 1 ms after reconnecting."""
  4058. import logging
  4059. import time
  4060. mqtt_client.state.connected = True
  4061. mqtt_client._last_message_time = time.time() - 120
  4062. mqtt_client._report_messages_since_connect = 0
  4063. mqtt_client._connect_time = time.monotonic() # fresh session
  4064. with caplog.at_level(logging.WARNING):
  4065. mqtt_client.check_staleness()
  4066. assert mqtt_client._zero_report_hint_logged is False
  4067. assert not any("zero status reports" in r.getMessage() for r in caplog.records)
  4068. # The stale reconnect itself still happens — only the hint is suppressed.
  4069. assert mqtt_client._stale_reconnecting is True
  4070. def test_check_staleness_serial_hint_when_session_old_enough(self, mqtt_client, caplog):
  4071. """A session that has been up past the stale window and still received
  4072. nothing is the case the hint was written for."""
  4073. import logging
  4074. import time
  4075. mqtt_client.state.connected = True
  4076. mqtt_client._last_message_time = time.time() - 120
  4077. mqtt_client._report_messages_since_connect = 0
  4078. mqtt_client._connect_time = time.monotonic() - 120
  4079. with caplog.at_level(logging.WARNING):
  4080. mqtt_client.check_staleness()
  4081. assert mqtt_client._zero_report_hint_logged is True
  4082. assert any("zero status reports" in r.getMessage() for r in caplog.records)
  4083. def test_check_staleness_no_serial_hint_when_reports_received(self, mqtt_client, caplog):
  4084. """A stale connection that DID receive reports (a normal mid-session
  4085. quiet gap) must not log the serial-number hint."""
  4086. import logging
  4087. import time
  4088. mqtt_client.state.connected = True
  4089. mqtt_client._last_message_time = time.time() - 120
  4090. mqtt_client._report_messages_since_connect = 5
  4091. with caplog.at_level(logging.WARNING):
  4092. mqtt_client.check_staleness()
  4093. assert mqtt_client._zero_report_hint_logged is False
  4094. assert not any("zero status reports" in r.getMessage() for r in caplog.records)
  4095. def test_on_disconnect_skipped_during_stale_reconnect(self, mqtt_client):
  4096. """_on_disconnect should not broadcast state when _stale_reconnecting is set."""
  4097. state_changes = []
  4098. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  4099. mqtt_client._stale_reconnecting = True
  4100. mqtt_client.state.connected = False
  4101. mqtt_client._on_disconnect(None, None)
  4102. # No state change broadcast — check_staleness() already did it
  4103. assert state_changes == []
  4104. assert mqtt_client.state.connected is False
  4105. def test_on_disconnect_fires_event_during_stale_reconnect(self, mqtt_client):
  4106. """_on_disconnect must still fire _disconnection_event even during stale reconnect.
  4107. If disconnect() is called while _stale_reconnecting is True (e.g. user removes
  4108. the printer before paho reconnects), the event must fire so disconnect() doesn't hang.
  4109. """
  4110. import threading
  4111. mqtt_client._stale_reconnecting = True
  4112. mqtt_client._disconnection_event = threading.Event()
  4113. mqtt_client._on_disconnect(None, None)
  4114. assert mqtt_client._disconnection_event.is_set()
  4115. def test_on_connect_clears_stale_reconnecting_flag(self, mqtt_client):
  4116. """_on_connect should clear _stale_reconnecting and restore connected=True."""
  4117. mqtt_client._stale_reconnecting = True
  4118. mqtt_client.state.connected = False
  4119. subscribe_calls = []
  4120. mock_client = type(
  4121. "MockClient",
  4122. (),
  4123. {
  4124. "subscribe": lambda self, topic: subscribe_calls.append(topic) or (0, 1),
  4125. },
  4126. )()
  4127. mqtt_client._on_connect(mock_client, None, None, 0)
  4128. assert mqtt_client._stale_reconnecting is False
  4129. assert mqtt_client.state.connected is True
  4130. def test_full_stale_reconnect_cycle_no_bounce(self, mqtt_client):
  4131. """Full cycle: stale → disconnect callback → reconnect. UI should see exactly one disconnect."""
  4132. import time
  4133. state_changes = []
  4134. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  4135. mqtt_client.state.connected = True
  4136. mqtt_client._last_message_time = time.time() - 120
  4137. # Step 1: Stale detection triggers
  4138. mqtt_client.check_staleness()
  4139. assert state_changes == [False]
  4140. # Step 2: Paho fires disconnect callback (from socket close)
  4141. mqtt_client._on_disconnect(None, None)
  4142. # Should NOT add another state change
  4143. assert state_changes == [False]
  4144. # Step 3: Paho reconnects
  4145. subscribe_calls = []
  4146. mock_client = type(
  4147. "MockClient",
  4148. (),
  4149. {
  4150. "subscribe": lambda self, topic: subscribe_calls.append(topic) or (0, 1),
  4151. },
  4152. )()
  4153. mqtt_client._on_connect(mock_client, None, None, 0)
  4154. assert state_changes == [False, True] # Now connected again
  4155. assert mqtt_client._stale_reconnecting is False
  4156. def test_spurious_disconnect_suppressed_when_recent_messages(self, mqtt_client):
  4157. """Non-error disconnect with recent messages should be suppressed."""
  4158. import time
  4159. state_changes = []
  4160. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  4161. mqtt_client.state.connected = True
  4162. mqtt_client._last_message_time = time.time() - 3 # 3s ago
  4163. # Non-error disconnect (rc=None)
  4164. mqtt_client._on_disconnect(None, None)
  4165. assert state_changes == []
  4166. assert mqtt_client.state.connected is True
  4167. def test_error_disconnect_not_suppressed_despite_recent_messages(self, mqtt_client):
  4168. """Error disconnect should always be processed, even with recent messages."""
  4169. import time
  4170. import paho.mqtt.client as mqtt
  4171. from paho.mqtt.reasoncodes import ReasonCode
  4172. state_changes = []
  4173. mqtt_client.on_state_change = lambda s: state_changes.append(s.connected)
  4174. mqtt_client.state.connected = True
  4175. mqtt_client._last_message_time = time.time() - 3 # 3s ago
  4176. # Error disconnect (rc.is_failure = True)
  4177. rc = ReasonCode(mqtt.CONNACK >> 4, identifier=0x80) # Failure code
  4178. mqtt_client._on_disconnect(None, None, rc=rc)
  4179. assert state_changes == [False]
  4180. assert mqtt_client.state.connected is False
  4181. class TestDoorOpenParsing:
  4182. """Tests for enclosure door state parsing (X1 home_flag bit 23 vs others stat bit 23)."""
  4183. def _make_client(self, model: str):
  4184. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4185. return BambuMQTTClient(
  4186. ip_address="192.168.1.100",
  4187. serial_number="TEST",
  4188. access_code="12345678",
  4189. model=model,
  4190. )
  4191. def test_x1c_door_open_from_home_flag(self):
  4192. client = self._make_client("X1C")
  4193. # bit 23 set
  4194. client._update_state({"home_flag": 0xC0E5CD98})
  4195. assert client.state.door_open is True
  4196. def test_x1c_door_closed_from_home_flag(self):
  4197. client = self._make_client("X1C")
  4198. client.state.door_open = True # start "open"
  4199. client._update_state({"home_flag": 0xC065CD98})
  4200. assert client.state.door_open is False
  4201. def test_x1c_ignores_stat_field(self):
  4202. # X1C must NOT use stat (bit 23 in stat is unrelated for X1)
  4203. client = self._make_client("X1C")
  4204. client._update_state({"home_flag": 0xC065CD98, "stat": "47A58000"})
  4205. assert client.state.door_open is False # home_flag wins
  4206. def test_h2d_door_open_from_stat(self):
  4207. client = self._make_client("H2D")
  4208. client._update_state({"stat": "640A58000"}) # bit 23 set
  4209. assert client.state.door_open is True
  4210. def test_h2d_door_closed_from_stat(self):
  4211. client = self._make_client("H2D")
  4212. client.state.door_open = True
  4213. client._update_state({"stat": "640258000"}) # bit 23 cleared
  4214. assert client.state.door_open is False
  4215. def test_h2d_ignores_home_flag(self):
  4216. # Non-X1 must NOT consume home_flag for door state
  4217. client = self._make_client("H2D")
  4218. client._update_state({"home_flag": 0xC0E5CD98, "stat": "640258000"})
  4219. assert client.state.door_open is False # stat wins
  4220. def test_invalid_stat_does_not_raise(self):
  4221. client = self._make_client("H2D")
  4222. client._update_state({"stat": "not-hex"})
  4223. assert client.state.door_open is False
  4224. class TestSdCardParsing:
  4225. """SD-card state is only set from the top-level `sdcard` field (bool/int/
  4226. string variants). home_flag is NOT consulted — heartbeat pushes clear those
  4227. bits even when a card is inserted, and the prior badge feature was removed
  4228. entirely because no reliable heartbeat-vs-full-push heuristic existed."""
  4229. def _make_client(self, model: str = "H2D"):
  4230. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4231. return BambuMQTTClient(
  4232. ip_address="192.168.1.100",
  4233. serial_number="TEST",
  4234. access_code="12345678",
  4235. model=model,
  4236. )
  4237. def test_home_flag_alone_does_not_touch_sdcard(self):
  4238. client = self._make_client()
  4239. client.state.sdcard = True
  4240. for home_flag in (0x00000000, 0x00000100, 0x00000200):
  4241. client._update_state({"home_flag": home_flag})
  4242. assert client.state.sdcard is True
  4243. def test_sdcard_string_fallback_when_no_home_flag(self):
  4244. client = self._make_client()
  4245. client._update_state({"sdcard": "HAS_SDCARD_NORMAL"})
  4246. assert client.state.sdcard is True
  4247. def test_sdcard_int_fallback_when_no_home_flag(self):
  4248. # `1 is True` is False — the old strict check flapped here.
  4249. client = self._make_client()
  4250. client._update_state({"sdcard": 1})
  4251. assert client.state.sdcard is True
  4252. def test_sdcard_bool_fallback_when_no_home_flag(self):
  4253. client = self._make_client()
  4254. client._update_state({"sdcard": True})
  4255. assert client.state.sdcard is True
  4256. client._update_state({"sdcard": False})
  4257. assert client.state.sdcard is False
  4258. class TestZombieSessionDetection:
  4259. """Tests for ams_filament_setting response tracking (#887).
  4260. When a printer's MQTT session degrades so that telemetry flows but
  4261. published commands never reach the printer, the zombie detector
  4262. counts consecutive unanswered ams_filament_setting commands and
  4263. force-reconnects after two.
  4264. """
  4265. @pytest.fixture
  4266. def mqtt_client(self):
  4267. import time
  4268. from unittest.mock import MagicMock
  4269. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4270. client = BambuMQTTClient(
  4271. ip_address="192.168.1.100",
  4272. serial_number="TEST123",
  4273. access_code="12345678",
  4274. )
  4275. client.state.connected = True
  4276. mock_paho = MagicMock()
  4277. mock_paho.socket.return_value = MagicMock()
  4278. client._client = mock_paho
  4279. client._connect_time = time.monotonic() - 10.0
  4280. # Set developer_mode so the dev-mode probe branch doesn't interfere
  4281. client.state.developer_mode = True
  4282. return client
  4283. def test_initial_state_is_clean(self, mqtt_client):
  4284. """Tracking fields start at zero / no pending command."""
  4285. assert mqtt_client._last_ams_cmd_time == 0.0
  4286. assert mqtt_client._ams_cmd_unanswered == 0
  4287. def test_publish_sets_pending_time(self, mqtt_client):
  4288. """set_ams_filament_setting records the publish timestamp."""
  4289. import time
  4290. before = time.monotonic()
  4291. mqtt_client.ams_set_filament_setting(
  4292. ams_id=0,
  4293. tray_id=0,
  4294. tray_info_idx="GFL99",
  4295. tray_type="PLA",
  4296. tray_sub_brands="",
  4297. tray_color="FF0000FF",
  4298. nozzle_temp_min=190,
  4299. nozzle_temp_max=230,
  4300. )
  4301. assert mqtt_client._last_ams_cmd_time >= before
  4302. def test_reset_slot_sets_pending_time(self, mqtt_client):
  4303. """reset_ams_slot also records the publish timestamp."""
  4304. import time
  4305. before = time.monotonic()
  4306. mqtt_client.reset_ams_slot(ams_id=0, tray_id=0)
  4307. assert mqtt_client._last_ams_cmd_time >= before
  4308. def test_response_clears_pending(self, mqtt_client):
  4309. """An ams_filament_setting response clears the pending state."""
  4310. import time
  4311. mqtt_client._last_ams_cmd_time = time.monotonic()
  4312. mqtt_client._ams_cmd_unanswered = 1
  4313. # Simulate receiving a user-command response (sequence_id "0")
  4314. print_data = {
  4315. "command": "ams_filament_setting",
  4316. "sequence_id": "0",
  4317. "result": "success",
  4318. }
  4319. # Walk the same path as _on_message: command response check then _update_state
  4320. cmd = print_data.get("command")
  4321. if cmd == "ams_filament_setting" and mqtt_client._last_ams_cmd_time > 0:
  4322. mqtt_client._last_ams_cmd_time = 0.0
  4323. mqtt_client._ams_cmd_unanswered = 0
  4324. assert mqtt_client._last_ams_cmd_time == 0.0
  4325. assert mqtt_client._ams_cmd_unanswered == 0
  4326. def test_single_timeout_increments_counter(self, mqtt_client):
  4327. """One unanswered command increments the counter but does not reconnect."""
  4328. import time
  4329. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4330. mqtt_client._update_state({"gcode_state": "IDLE"})
  4331. assert mqtt_client._ams_cmd_unanswered == 1
  4332. assert mqtt_client._last_ams_cmd_time == 0.0
  4333. # Should NOT force-reconnect after just one
  4334. assert mqtt_client.state.connected is True
  4335. def test_two_timeouts_force_reconnect(self, mqtt_client):
  4336. """Two consecutive unanswered commands trigger force_reconnect.
  4337. Zombie detection runs from paho's network thread (no asyncio loop), so
  4338. the routing in force_reconnect_stale_session falls back to socket-close
  4339. — which is the safe option since loop_stop() from inside the loop
  4340. thread would deadlock. Hard-reset is reserved for async-context callers
  4341. on the queue dispatch path."""
  4342. import time
  4343. state_change_called = []
  4344. mqtt_client.on_state_change = lambda s: state_change_called.append(True)
  4345. # First unanswered command
  4346. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4347. mqtt_client._update_state({"gcode_state": "IDLE"})
  4348. assert mqtt_client._ams_cmd_unanswered == 1
  4349. assert mqtt_client.state.connected is True
  4350. # Second unanswered command
  4351. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4352. mqtt_client._update_state({"gcode_state": "IDLE"})
  4353. assert mqtt_client._ams_cmd_unanswered == 0 # reset after reconnect
  4354. assert mqtt_client.state.connected is False
  4355. assert mqtt_client._stale_reconnecting is True
  4356. # Sync test → no running loop → socket-close fallback path
  4357. mqtt_client._client.socket().close.assert_called()
  4358. assert len(state_change_called) > 0
  4359. def test_response_between_timeouts_resets_counter(self, mqtt_client):
  4360. """A successful response after one timeout resets the counter."""
  4361. import time
  4362. # First unanswered command
  4363. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4364. mqtt_client._update_state({"gcode_state": "IDLE"})
  4365. assert mqtt_client._ams_cmd_unanswered == 1
  4366. # Now a response arrives — clear pending
  4367. mqtt_client._last_ams_cmd_time = time.monotonic()
  4368. mqtt_client._last_ams_cmd_time = 0.0
  4369. mqtt_client._ams_cmd_unanswered = 0
  4370. # Next unanswered command should be count=1, not count=2
  4371. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4372. mqtt_client._update_state({"gcode_state": "IDLE"})
  4373. assert mqtt_client._ams_cmd_unanswered == 1
  4374. assert mqtt_client.state.connected is True # no reconnect
  4375. def test_late_response_after_watchdog_clears_counter_issue_1164(self, mqtt_client):
  4376. """Regression for #1164: a late ams_filament_setting response — one
  4377. that arrives AFTER the watchdog has already zeroed
  4378. `_last_ams_cmd_time` and incremented the unanswered counter — must
  4379. still reset the counter. Without this, a single sluggish response
  4380. leaves the counter armed at 1 indefinitely; the next slow response
  4381. on a totally unrelated command (possibly minutes or hours later)
  4382. takes it to 2 and force-reconnects, surfacing as 'AMS slot config
  4383. doesn't reach the printer ~6 changes in'."""
  4384. import time
  4385. # First command publishes, then doesn't get a response for >10s.
  4386. # Watchdog fires: counter=1, _last_ams_cmd_time zeroed.
  4387. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4388. mqtt_client._update_state({"gcode_state": "IDLE"})
  4389. assert mqtt_client._ams_cmd_unanswered == 1
  4390. assert mqtt_client._last_ams_cmd_time == 0.0 # watchdog cleared it
  4391. # Late response arrives — the `_process_message` path used to require
  4392. # `_last_ams_cmd_time > 0` before resetting the counter, so this would
  4393. # have silently been ignored.
  4394. mqtt_client._process_message(
  4395. {
  4396. "print": {
  4397. "command": "ams_filament_setting",
  4398. "sequence_id": "0",
  4399. "result": "success",
  4400. "reason": "success",
  4401. }
  4402. }
  4403. )
  4404. # Counter MUST be reset — the response proves the channel is alive.
  4405. assert mqtt_client._ams_cmd_unanswered == 0, (
  4406. "Late ams_filament_setting response must reset the unanswered "
  4407. "counter even when the watchdog already zeroed _last_ams_cmd_time. "
  4408. "If this assertion fails the #1164 regression is back: a single "
  4409. "sluggish response will leave the counter armed and cause a "
  4410. "spurious force_reconnect on the next slow response."
  4411. )
  4412. # Now even if a future command times out, the counter starts fresh
  4413. # and a single timeout doesn't trip the 2x reconnect threshold.
  4414. mqtt_client._last_ams_cmd_time = time.monotonic() - 11.0
  4415. mqtt_client._update_state({"gcode_state": "IDLE"})
  4416. assert mqtt_client._ams_cmd_unanswered == 1
  4417. assert mqtt_client.state.connected is True # no force reconnect
  4418. def test_on_connect_resets_tracking(self, mqtt_client):
  4419. """_on_connect resets zombie tracking fields."""
  4420. import time
  4421. mqtt_client._last_ams_cmd_time = time.monotonic()
  4422. mqtt_client._ams_cmd_unanswered = 5
  4423. # subscribe() must return (result, mid) tuple
  4424. mqtt_client._client.subscribe.return_value = (0, 1)
  4425. mqtt_client._on_connect(mqtt_client._client, None, None, 0)
  4426. assert mqtt_client._last_ams_cmd_time == 0.0
  4427. assert mqtt_client._ams_cmd_unanswered == 0
  4428. def test_no_check_when_no_command_pending(self, mqtt_client):
  4429. """If no command was published, push_status does not trigger detection."""
  4430. assert mqtt_client._last_ams_cmd_time == 0.0
  4431. mqtt_client._update_state({"gcode_state": "IDLE"})
  4432. assert mqtt_client._ams_cmd_unanswered == 0
  4433. def test_no_timeout_within_window(self, mqtt_client):
  4434. """A command published <10s ago should not trigger a timeout."""
  4435. import time
  4436. mqtt_client._last_ams_cmd_time = time.monotonic() - 5.0
  4437. mqtt_client._update_state({"gcode_state": "IDLE"})
  4438. assert mqtt_client._ams_cmd_unanswered == 0
  4439. assert mqtt_client._last_ams_cmd_time > 0 # still pending
  4440. class TestHMSUserActionFiltering:
  4441. """HMS short codes the printer firmware emits during user-cancel sequences
  4442. must not appear in state.hms_errors — they're status echoes, not faults,
  4443. and shouldn't drive the printer card's "X problem" badge or red pip."""
  4444. @pytest.fixture
  4445. def mqtt_client(self):
  4446. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4447. return BambuMQTTClient(
  4448. ip_address="192.168.1.100",
  4449. serial_number="TEST_HMS",
  4450. access_code="12345678",
  4451. )
  4452. def test_task_cancelled_echo_0300_400c_filtered(self, mqtt_client):
  4453. """0300_400C ("The task was canceled.") is the user-cancel echo that was
  4454. leaving the printer card stuck on "1 problem" after every stop."""
  4455. mqtt_client._update_state({"hms": [{"attr": 0x03000300, "code": 0x400C}]})
  4456. assert mqtt_client.state.hms_errors == []
  4457. def test_printing_cancelled_echo_0500_400e_filtered(self, mqtt_client):
  4458. """0500_400E ("Printing was cancelled.") — the corresponding nozzle-module
  4459. echo that the backend notification path was already suppressing for the
  4460. same reason."""
  4461. mqtt_client._update_state({"hms": [{"attr": 0x05000300, "code": 0x400E}]})
  4462. assert mqtt_client.state.hms_errors == []
  4463. def test_real_layer_shift_still_passes_through(self, mqtt_client):
  4464. """0300_4057 (Z-axis step loss) is a real fault and must NOT be filtered."""
  4465. mqtt_client._update_state({"hms": [{"attr": 0x03000100, "code": 0x4057}]})
  4466. assert len(mqtt_client.state.hms_errors) == 1
  4467. assert mqtt_client.state.hms_errors[0].code == "0x4057"
  4468. def test_filter_only_drops_user_action_codes_keeps_concurrent_real_faults(self, mqtt_client):
  4469. """When the user cancels mid-fault, the firmware sends the real fault HMS
  4470. alongside the cancel echo. Drop only the echo, keep the real fault."""
  4471. mqtt_client._update_state(
  4472. {
  4473. "hms": [
  4474. {"attr": 0x03000300, "code": 0x400C}, # cancel echo — drop
  4475. {"attr": 0x07FF0200, "code": 0x8011}, # filament runout — keep
  4476. ]
  4477. }
  4478. )
  4479. codes = [e.code for e in mqtt_client.state.hms_errors]
  4480. assert "0x8011" in codes
  4481. assert "0x400c" not in codes
  4482. assert len(mqtt_client.state.hms_errors) == 1
  4483. def test_print_error_path_also_filters_cancel_echo(self, mqtt_client):
  4484. """`print_error` is a second route that appends into state.hms_errors. The
  4485. same user-action codes (e.g. 0500_400E "Printing was cancelled") must be
  4486. filtered there too — otherwise the printer card stays on "1 problem"
  4487. when the firmware reports the cancel via print_error rather than hms[]."""
  4488. mqtt_client._update_state({"print_error": 0x0500_400E})
  4489. assert mqtt_client.state.hms_errors == []
  4490. def test_print_error_path_passes_real_errors_through(self, mqtt_client):
  4491. """Real print_error codes still reach state.hms_errors."""
  4492. mqtt_client._update_state({"print_error": 0x0500_8061})
  4493. assert len(mqtt_client.state.hms_errors) == 1
  4494. assert mqtt_client.state.hms_errors[0].code == "0x8061"
  4495. class TestHMSFullCode:
  4496. """full_code is the firmware-matching key for HMS-related commands.
  4497. Truncating it to the 8-char short code is what caused #1830's silent
  4498. rejection on H2C, and the H2D wrong-plate path needs the print_error
  4499. 32-bit form. Both branches must populate full_code consistently."""
  4500. @pytest.fixture
  4501. def mqtt_client(self):
  4502. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4503. return BambuMQTTClient(
  4504. ip_address="192.168.1.100",
  4505. serial_number="TEST_FULLCODE",
  4506. access_code="12345678",
  4507. )
  4508. def test_hms_array_path_populates_16_char_full_code(self, mqtt_client):
  4509. """hms[] entries carry a 64-bit identifier (attr + code, 32 bits each).
  4510. The full 16-char hex is what BambuStudio uses to match err on
  4511. idle_ignore — the truncated short_code drops 32 bits and the firmware
  4512. silently rejects (#1830). Verifies the parser preserves the full
  4513. identifier on HMSError.full_code."""
  4514. # 0x07FF0200 / 0x8011 → displayed as 07FF_0200_0000_8011 in the wiki
  4515. mqtt_client._update_state({"hms": [{"attr": 0x07FF0200, "code": 0x8011}]})
  4516. assert len(mqtt_client.state.hms_errors) == 1
  4517. assert mqtt_client.state.hms_errors[0].full_code == "07FF02000000" + "8011"
  4518. def test_print_error_path_populates_8_char_full_code(self, mqtt_client):
  4519. """print_error is already 32 bits — no truncation. full_code is the
  4520. 8-char hex form, which is exactly what the firmware matches against."""
  4521. mqtt_client._update_state({"print_error": 0x05008051})
  4522. assert len(mqtt_client.state.hms_errors) == 1
  4523. assert mqtt_client.state.hms_errors[0].full_code == "05008051"
  4524. def test_hms_array_catalog_lookup_tries_16_char_first(self, mqtt_client, monkeypatch):
  4525. """When the catalog has both an 8-char and a 16-char entry for the
  4526. same fault family, the 16-char (specific variant) wins. The 8-char
  4527. is the fallback for codes that aren't in the long-form catalog."""
  4528. from backend.app.services import bambu_mqtt as mod
  4529. calls = []
  4530. def fake_lookup(device, code):
  4531. calls.append((device, code))
  4532. if len(code) == 16:
  4533. return ["RESUME_PRINTING"]
  4534. return []
  4535. monkeypatch.setattr(mod, "get_actions_for_error_code", fake_lookup)
  4536. # SN prefix "TES" — irrelevant for the test, we mocked the lookup.
  4537. mqtt_client._update_state({"hms": [{"attr": 0x07FF0200, "code": 0x8011}]})
  4538. # 16-char lookup attempted first, then 8-char only if 16-char missed.
  4539. assert calls[0][1] == "07FF020000008011"
  4540. assert mqtt_client.state.hms_errors[0].actions == ["RESUME_PRINTING"]
  4541. def test_hms_array_catalog_falls_back_to_8_char(self, mqtt_client, monkeypatch):
  4542. """If the catalog has no 16-char entry, fall back to the 8-char short
  4543. code — that's where base-class HMS codes live."""
  4544. from backend.app.services import bambu_mqtt as mod
  4545. calls = []
  4546. def fake_lookup(device, code):
  4547. calls.append((device, code))
  4548. if len(code) == 16:
  4549. return [] # no specific variant
  4550. return ["CHECK_ASSISTANT"] # base class hit
  4551. monkeypatch.setattr(mod, "get_actions_for_error_code", fake_lookup)
  4552. mqtt_client._update_state({"hms": [{"attr": 0x07FF0200, "code": 0x8011}]})
  4553. # Two lookups: 16-char miss, then 8-char hit.
  4554. assert len(calls) == 2
  4555. assert calls[0][1] == "07FF020000008011"
  4556. assert calls[1][1] == "07FF8011"
  4557. assert mqtt_client.state.hms_errors[0].actions == ["CHECK_ASSISTANT"]
  4558. class TestForceReconnectRouting:
  4559. """#1136 — force_reconnect_stale_session routes between hard-reset (full
  4560. paho-client teardown, wipes the QoS 1 queue) and socket-close (the legacy
  4561. behaviour, safe to call from paho's own network thread). The routing
  4562. decision is based on whether an asyncio loop is running: hard-reset
  4563. requires loop_stop() which would deadlock if called from inside the
  4564. network thread itself."""
  4565. @pytest.fixture
  4566. def mqtt_client(self):
  4567. from unittest.mock import MagicMock
  4568. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4569. client = BambuMQTTClient(
  4570. ip_address="192.168.1.100",
  4571. serial_number="TEST_HARD_RESET",
  4572. access_code="12345678",
  4573. )
  4574. client.state.connected = True
  4575. client._client = MagicMock()
  4576. return client
  4577. def test_routing_falls_back_to_socket_close_without_running_loop(self, mqtt_client):
  4578. """Sync caller → no asyncio loop → socket-close path (legacy behaviour
  4579. preserved for paho-thread callers like zombie detection)."""
  4580. mqtt_client.force_reconnect_stale_session("test")
  4581. mqtt_client._client.socket().close.assert_called()
  4582. # Old client is NOT torn down on this path; same-instance reconnect
  4583. # via paho's auto-reconnect handles it.
  4584. assert mqtt_client._client is not None
  4585. def test_routing_uses_hard_reset_when_loop_is_running(self, mqtt_client):
  4586. """Async caller → loop available → hard-reset path wipes the queue."""
  4587. import asyncio
  4588. original = mqtt_client._client
  4589. # Stub connect() so the rebuild doesn't open a real socket.
  4590. mqtt_client.connect = lambda loop=None: None
  4591. async def _trigger():
  4592. mqtt_client.force_reconnect_stale_session("test")
  4593. asyncio.run(_trigger())
  4594. original.disconnect.assert_called()
  4595. original.loop_stop.assert_called()
  4596. # connect() stub didn't repopulate _client, so it's None — the contract
  4597. # in production is that connect() builds a fresh mqtt.Client here.
  4598. assert mqtt_client._client is None
  4599. def test_marks_state_disconnected_and_broadcasts(self, mqtt_client):
  4600. """Both routing paths must broadcast the disconnected state once."""
  4601. broadcasts: list[bool] = []
  4602. mqtt_client.on_state_change = lambda s: broadcasts.append(s.connected)
  4603. mqtt_client.force_reconnect_stale_session("test")
  4604. assert mqtt_client.state.connected is False
  4605. assert mqtt_client._stale_reconnecting is True
  4606. assert broadcasts == [False]
  4607. class TestHardResetClientDirect:
  4608. """Lower-level coverage of `_hard_reset_client` itself — the helper called
  4609. by the routing layer when a full paho-client teardown is safe. These tests
  4610. drive the helper directly so they don't depend on the routing decision."""
  4611. @pytest.fixture
  4612. def mqtt_client(self):
  4613. from unittest.mock import MagicMock
  4614. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4615. client = BambuMQTTClient(
  4616. ip_address="192.168.1.100",
  4617. serial_number="TEST_HARD_DIRECT",
  4618. access_code="12345678",
  4619. )
  4620. client.state.connected = True
  4621. client._client = MagicMock()
  4622. # Stub connect() so the rebuild doesn't open a real socket.
  4623. client.connect = lambda loop=None: None
  4624. return client
  4625. def test_disconnects_and_stops_old_client(self, mqtt_client):
  4626. """Old paho client must receive DISCONNECT (broker drops session) +
  4627. loop_stop (network thread exits, taking its QoS 1 queue with it)."""
  4628. original = mqtt_client._client
  4629. mqtt_client._hard_reset_client()
  4630. original.disconnect.assert_called()
  4631. original.loop_stop.assert_called()
  4632. def test_clears_client_reference(self, mqtt_client):
  4633. """Old reference must go to None so subsequent code can't accidentally
  4634. publish through the dying client."""
  4635. mqtt_client._hard_reset_client()
  4636. assert mqtt_client._client is None
  4637. def test_swallows_disconnect_exception(self, mqtt_client):
  4638. """A failing disconnect() (e.g. paho already in error state) must not
  4639. propagate through async dispatch callers, and a single broken client
  4640. could brick every future dispatch."""
  4641. original = mqtt_client._client
  4642. original.disconnect.side_effect = RuntimeError("boom")
  4643. # No exception escapes the call (test would fail if it did).
  4644. mqtt_client._hard_reset_client()
  4645. # loop_stop is still attempted after the disconnect failure.
  4646. original.loop_stop.assert_called()
  4647. assert mqtt_client._client is None
  4648. class TestStartPrintRecordsDispatchedPlate:
  4649. """Tests for the dispatched-plate record set by start_print() — used by the
  4650. /cover route to pick the right thumbnail when the printer's gcode_file
  4651. echo doesn't include the plate path (#1166).
  4652. Some firmware versions (P1S 01.10.00.00) only put the .3mf filename in
  4653. print.gcode_file, so the regex falls back to plate 1 and the printer card
  4654. shows the wrong plate's thumbnail. Recording what we dispatched at the
  4655. publish site lets resolve_plate_id() return the right plate without
  4656. needing to introspect the 3MF.
  4657. """
  4658. @pytest.fixture
  4659. def mqtt_client(self):
  4660. from unittest.mock import MagicMock
  4661. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4662. client = BambuMQTTClient(
  4663. ip_address="192.168.1.100",
  4664. serial_number="TEST123",
  4665. access_code="12345678",
  4666. )
  4667. client._client = MagicMock()
  4668. client.state.connected = True
  4669. return client
  4670. def test_dispatched_plate_recorded_after_start_print(self, mqtt_client):
  4671. # Default state has no dispatched plate.
  4672. assert mqtt_client.state.dispatched_plate_id is None
  4673. assert mqtt_client.state.dispatched_subtask is None
  4674. mqtt_client.start_print("Luigi.3mf", plate_id=2)
  4675. # The subtask_name we record matches the one we send (and the printer
  4676. # reflects back via MQTT), so resolve_plate_id() can validate the
  4677. # match downstream.
  4678. assert mqtt_client.state.dispatched_plate_id == 2
  4679. assert mqtt_client.state.dispatched_subtask == "Luigi"
  4680. def test_dispatched_plate_default_is_one(self, mqtt_client):
  4681. # When start_print is called without plate_id (legacy/single-plate
  4682. # flow), we still record plate=1 — the contract is that dispatched_*
  4683. # describes the active dispatch.
  4684. mqtt_client.start_print("Single.3mf")
  4685. assert mqtt_client.state.dispatched_plate_id == 1
  4686. assert mqtt_client.state.dispatched_subtask == "Single"
  4687. def test_dispatched_plate_overwritten_by_subsequent_dispatch(self, mqtt_client):
  4688. # Each dispatch replaces the prior record so we can never serve a
  4689. # stale plate from an older print.
  4690. mqtt_client.start_print("First.3mf", plate_id=4)
  4691. mqtt_client.start_print("Second.3mf", plate_id=2)
  4692. assert mqtt_client.state.dispatched_plate_id == 2
  4693. assert mqtt_client.state.dispatched_subtask == "Second"
  4694. def test_dispatched_plate_not_recorded_when_publish_skipped(self, mqtt_client):
  4695. # If start_print early-returns because we're not connected, no record
  4696. # should land — otherwise the next print's /cover call would believe
  4697. # a phantom dispatch happened.
  4698. mqtt_client.state.connected = False
  4699. result = mqtt_client.start_print("Phantom.3mf", plate_id=3)
  4700. assert result is False
  4701. assert mqtt_client.state.dispatched_plate_id is None
  4702. assert mqtt_client.state.dispatched_subtask is None
  4703. class TestStartPrintNozzleMappingDispatch:
  4704. """H2C dual-nozzle-rack (#1780) — nozzle_mapping on dispatch.
  4705. BambuStudio's project_file MQTT command for O1C2 carries a per-filament
  4706. physical nozzle position ID array (`nozzle_mapping`). Without forwarding
  4707. it, the H2C firmware falls back to "last matching nozzle type" auto-pick
  4708. and ignores the user's slicer choice. Tests pin the gate, the parse, the
  4709. no-op cases, and the malformed-JSON safety net.
  4710. The original #1780 attempt also captured `nozzles_info` but a wire capture
  4711. on H2C confirmed BambuStudio never sends that field — the capture/dispatch
  4712. paths for it were dropped in the same release.
  4713. """
  4714. @pytest.fixture
  4715. def mqtt_client(self):
  4716. from unittest.mock import MagicMock
  4717. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4718. client = BambuMQTTClient(
  4719. ip_address="192.168.1.100",
  4720. serial_number="TEST_O1C2",
  4721. access_code="12345678",
  4722. )
  4723. client._client = MagicMock()
  4724. client.state.connected = True
  4725. return client
  4726. def _published_print_cmd(self, mqtt_client):
  4727. call_args = mqtt_client._client.publish.call_args
  4728. return json.loads(call_args[0][1])["print"]
  4729. def test_dual_nozzle_includes_nozzle_mapping(self, mqtt_client):
  4730. """Dual-nozzle + nozzle_mapping present → parsed JSON array injected
  4731. verbatim onto the dispatched project_file command."""
  4732. mqtt_client._is_dual_nozzle = True
  4733. mqtt_client.start_print(
  4734. "test.3mf",
  4735. nozzle_mapping=json.dumps([16, -1, -1, 1, -1, -1, -1, -1]),
  4736. )
  4737. cmd = self._published_print_cmd(mqtt_client)
  4738. # List, not string — the wire shape must match BambuStudio's.
  4739. assert cmd["nozzle_mapping"] == [16, -1, -1, 1, -1, -1, -1, -1]
  4740. def test_single_nozzle_omits_nozzle_mapping_even_if_set(self, mqtt_client):
  4741. """A single-nozzle printer must NOT emit the rack field even if the
  4742. caller passes it (defense-in-depth — the queue item could legitimately
  4743. carry a stale capture from before a model change)."""
  4744. mqtt_client._is_dual_nozzle = False
  4745. mqtt_client.model = "P1S" # single-nozzle
  4746. mqtt_client.start_print(
  4747. "test.3mf",
  4748. nozzle_mapping=json.dumps([16, 0, 19]),
  4749. )
  4750. cmd = self._published_print_cmd(mqtt_client)
  4751. assert "nozzle_mapping" not in cmd
  4752. def test_dual_nozzle_no_field_no_injection(self, mqtt_client):
  4753. """Dual-nozzle printer + no slicer pick (NULL on queue item) → command
  4754. carries no nozzle_mapping. The firmware then runs its normal
  4755. auto-pick, which is the pre-fix behaviour for any non-O1C2 dual-
  4756. nozzle model that has no rack to disambiguate against anyway."""
  4757. mqtt_client._is_dual_nozzle = True
  4758. mqtt_client.start_print("test.3mf", nozzle_mapping=None)
  4759. cmd = self._published_print_cmd(mqtt_client)
  4760. assert "nozzle_mapping" not in cmd
  4761. def test_malformed_nozzle_mapping_is_logged_and_omitted(self, mqtt_client, caplog):
  4762. """Invalid JSON on the queue item must NOT block the dispatch. Log a
  4763. warning and let the firmware auto-pick — the failure mode is just
  4764. the pre-fix behaviour, not a worse one. Fail-open is correct here
  4765. because the alternative would silently brick every dispatch on a
  4766. single bad row."""
  4767. mqtt_client._is_dual_nozzle = True
  4768. with caplog.at_level("WARNING"):
  4769. result = mqtt_client.start_print(
  4770. "test.3mf",
  4771. nozzle_mapping="not valid json {",
  4772. )
  4773. assert result is True # dispatch still proceeded
  4774. cmd = self._published_print_cmd(mqtt_client)
  4775. assert "nozzle_mapping" not in cmd
  4776. assert any("Invalid nozzle_mapping" in rec.message for rec in caplog.records)
  4777. def test_empty_string_field_is_treated_as_absent(self, mqtt_client):
  4778. """An empty-string column value (legacy data, or a NOT NULL DB
  4779. recovery shim) must behave the same as NULL — no injection, no
  4780. parse error log."""
  4781. mqtt_client._is_dual_nozzle = True
  4782. mqtt_client.start_print("test.3mf", nozzle_mapping="")
  4783. cmd = self._published_print_cmd(mqtt_client)
  4784. assert "nozzle_mapping" not in cmd
  4785. class TestFilamentTrackSwitchDetection:
  4786. """Tests for Filament Track Switch (FTS) accessory detection (#1162).
  4787. The FTS is an accessory that sits between an AMS and the printer's
  4788. extruders, dynamically routing any slot to either nozzle. When installed,
  4789. each AMS unit reports info bits 8-11 = 0xE (uninitialized) since slots are
  4790. no longer tied to a specific extruder. Detection comes from the presence of
  4791. the print.device.fila_switch object in MQTT push_status.
  4792. """
  4793. @pytest.fixture
  4794. def mqtt_client(self):
  4795. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4796. return BambuMQTTClient(
  4797. ip_address="192.168.1.100",
  4798. serial_number="TEST123",
  4799. access_code="12345678",
  4800. )
  4801. def test_fts_default_not_installed(self, mqtt_client):
  4802. """Without any MQTT data, fila_switch.installed must be False so the
  4803. frontend keeps applying the per-extruder filter on regular dual-nozzle
  4804. printers."""
  4805. assert mqtt_client.state.fila_switch.installed is False
  4806. assert mqtt_client.state.fila_switch.in_slots == []
  4807. assert mqtt_client.state.fila_switch.out_extruders == []
  4808. def test_fts_detected_from_device_fila_switch(self, mqtt_client):
  4809. """A push_status with print.device.fila_switch present must mark FTS
  4810. installed and capture its routing arrays. Mirrors the user's MQTT
  4811. bundle in #1162."""
  4812. data = {
  4813. "gcode_state": "RUNNING",
  4814. "device": {
  4815. "fila_switch": {
  4816. "in": [-1, 2],
  4817. "info": 2,
  4818. "out": [0, 1],
  4819. "stat": 0,
  4820. }
  4821. },
  4822. }
  4823. mqtt_client._update_state(data)
  4824. fs = mqtt_client.state.fila_switch
  4825. assert fs.installed is True
  4826. assert fs.in_slots == [-1, 2]
  4827. assert fs.out_extruders == [0, 1]
  4828. assert fs.stat == 0
  4829. assert fs.info == 2
  4830. def test_fts_absent_when_no_fila_switch_field(self, mqtt_client):
  4831. """A push_status that has device.* but no fila_switch must leave
  4832. fila_switch.installed = False — only that specific field flips it on."""
  4833. data = {
  4834. "gcode_state": "IDLE",
  4835. "device": {"extruder": {"state": 0}},
  4836. }
  4837. mqtt_client._update_state(data)
  4838. assert mqtt_client.state.fila_switch.installed is False
  4839. def test_fts_handles_missing_in_out_arrays(self, mqtt_client):
  4840. """If the firmware sends fila_switch with missing or non-list in/out,
  4841. we must still mark it installed (presence is the signal) and default
  4842. the arrays to empty lists rather than crashing."""
  4843. data = {
  4844. "gcode_state": "IDLE",
  4845. "device": {"fila_switch": {"stat": 0, "info": 0}},
  4846. }
  4847. mqtt_client._update_state(data)
  4848. fs = mqtt_client.state.fila_switch
  4849. assert fs.installed is True
  4850. assert fs.in_slots == []
  4851. assert fs.out_extruders == []
  4852. class TestAmsLoadFilamentEncoding:
  4853. """Per-target ams_change_filament command encoding (#891)."""
  4854. @pytest.fixture
  4855. def mqtt_client(self):
  4856. from unittest.mock import MagicMock
  4857. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4858. client = BambuMQTTClient(
  4859. ip_address="192.168.1.100",
  4860. serial_number="TEST123",
  4861. access_code="12345678",
  4862. )
  4863. # Pretend the MQTT layer is connected so the publish path is reached.
  4864. client._client = MagicMock()
  4865. client.state.connected = True
  4866. return client
  4867. @staticmethod
  4868. def _published(client) -> dict:
  4869. """Return the JSON of the most recent publish() call."""
  4870. last_call = client._client.publish.call_args_list[-1]
  4871. topic, payload, *_ = last_call.args
  4872. return json.loads(payload)
  4873. def test_ams_slot_uses_local_index_and_minus_one_temps(self, mqtt_client):
  4874. """tray_id=5 → ams_id=1, slot_id=1, target=5, curr/tar=-1."""
  4875. assert mqtt_client.ams_load_filament(5) is True
  4876. cmd = self._published(mqtt_client)["print"]
  4877. assert cmd["command"] == "ams_change_filament"
  4878. assert cmd["ams_id"] == 1
  4879. assert cmd["slot_id"] == 1
  4880. assert cmd["target"] == 5
  4881. assert cmd["curr_temp"] == -1
  4882. assert cmd["tar_temp"] == -1
  4883. def test_external_left_keeps_legacy_encoding(self, mqtt_client):
  4884. """tray_id=254 → ams_id=255, slot_id=254, target=254, curr/tar=-1.
  4885. This is the original capture from a single-extruder printer; preserved
  4886. verbatim so existing single-external setups don't regress.
  4887. """
  4888. assert mqtt_client.ams_load_filament(254) is True
  4889. cmd = self._published(mqtt_client)["print"]
  4890. assert cmd["ams_id"] == 255
  4891. assert cmd["slot_id"] == 254
  4892. assert cmd["target"] == 254
  4893. assert cmd["curr_temp"] == -1
  4894. assert cmd["tar_temp"] == -1
  4895. def test_external_right_uses_extruder_index_and_actual_temp(self, mqtt_client):
  4896. """tray_id=255 → captured BambuStudio shape on dual-nozzle H2D:
  4897. ams_id=255, slot_id=0 (right extruder), target=255, curr/tar = right
  4898. nozzle temp.
  4899. """
  4900. # Simulate a heated right nozzle.
  4901. mqtt_client.state.temperatures["nozzle_2"] = 215.0
  4902. assert mqtt_client.ams_load_filament(255) is True
  4903. cmd = self._published(mqtt_client)["print"]
  4904. assert cmd["ams_id"] == 255
  4905. assert cmd["slot_id"] == 0
  4906. assert cmd["target"] == 255
  4907. assert cmd["curr_temp"] == 215
  4908. assert cmd["tar_temp"] == 215
  4909. def test_external_right_falls_back_when_nozzle_cold(self, mqtt_client):
  4910. """If the right nozzle reports < 180 °C, fall back to a sane default
  4911. so the printer accepts the command rather than rejecting it on a
  4912. nonsensical temperature.
  4913. """
  4914. mqtt_client.state.temperatures["nozzle_2"] = 25.0
  4915. assert mqtt_client.ams_load_filament(255) is True
  4916. cmd = self._published(mqtt_client)["print"]
  4917. assert cmd["curr_temp"] == 215
  4918. assert cmd["tar_temp"] == 215
  4919. def test_returns_false_when_disconnected(self, mqtt_client):
  4920. """Disconnected client must not publish anything."""
  4921. mqtt_client.state.connected = False
  4922. assert mqtt_client.ams_load_filament(0) is False
  4923. mqtt_client._client.publish.assert_not_called()
  4924. class TestAmsFilamentSettingExternalSpoolEncoding:
  4925. """Encoding of `ams_filament_setting` / `reset_ams_slot` for the external spool.
  4926. Regression coverage for #1279. The encoding is verified against a captured
  4927. BambuStudio → X1C exchange (May 2026):
  4928. REQ {"command":"ams_filament_setting","ams_id":255,"tray_id":254,"slot_id":0,...}
  4929. REP {"result":"success",...}
  4930. The previous code sent `tray_id: 0` for the single-external case, which the
  4931. P1S in #1279 rejected with `result: "fail"`.
  4932. """
  4933. @pytest.fixture
  4934. def mqtt_client(self):
  4935. from unittest.mock import MagicMock
  4936. from backend.app.services.bambu_mqtt import BambuMQTTClient
  4937. client = BambuMQTTClient(
  4938. ip_address="192.168.1.100",
  4939. serial_number="TEST123",
  4940. access_code="12345678",
  4941. )
  4942. client._client = MagicMock()
  4943. client.state.connected = True
  4944. return client
  4945. def _published(self, mqtt_client):
  4946. call_args = mqtt_client._client.publish.call_args
  4947. return json.loads(call_args[0][1])["print"]
  4948. def test_single_external_uses_tray_id_254(self, mqtt_client):
  4949. """X1C/P1S/A1 (single external slot): ams_id=255, tray_id=254, slot_id=0."""
  4950. # Simulate a single-external printer: vt_tray is a single-element list.
  4951. mqtt_client.state.raw_data = {"vt_tray": [{"id": "255"}]}
  4952. assert mqtt_client.ams_set_filament_setting(
  4953. ams_id=255,
  4954. tray_id=0,
  4955. tray_info_idx="GFL99",
  4956. tray_type="PLA",
  4957. tray_sub_brands="Generic PLA",
  4958. tray_color="000000FF",
  4959. nozzle_temp_min=190,
  4960. nozzle_temp_max=230,
  4961. )
  4962. cmd = self._published(mqtt_client)
  4963. assert cmd["command"] == "ams_filament_setting"
  4964. assert cmd["ams_id"] == 255
  4965. assert cmd["tray_id"] == 254, (
  4966. "Single-external `ams_filament_setting` must send tray_id=254 "
  4967. "(verified via BambuStudio→X1C capture). Sending tray_id=0 "
  4968. "is what the P1S in #1279 rejects."
  4969. )
  4970. assert cmd["slot_id"] == 0
  4971. def test_single_external_reset_uses_tray_id_254(self, mqtt_client):
  4972. """reset_ams_slot shares the convention — same encoding."""
  4973. mqtt_client.state.raw_data = {"vt_tray": [{"id": "255"}]}
  4974. assert mqtt_client.reset_ams_slot(ams_id=255, tray_id=0)
  4975. cmd = self._published(mqtt_client)
  4976. assert cmd["command"] == "ams_filament_setting"
  4977. assert cmd["ams_id"] == 255
  4978. assert cmd["tray_id"] == 254
  4979. assert cmd["slot_id"] == 0
  4980. # Reset clears the filament identity
  4981. assert cmd["tray_info_idx"] == ""
  4982. assert cmd["tray_type"] == ""
  4983. def test_regular_ams_tray_unchanged(self, mqtt_client):
  4984. """Regular AMS slots (ams_id <= 3) keep their existing encoding."""
  4985. mqtt_client.state.raw_data = {"vt_tray": []}
  4986. assert mqtt_client.ams_set_filament_setting(
  4987. ams_id=0,
  4988. tray_id=2,
  4989. tray_info_idx="GFA01",
  4990. tray_type="PLA",
  4991. tray_sub_brands="PLA Matte",
  4992. tray_color="FFFFFFFF",
  4993. nozzle_temp_min=190,
  4994. nozzle_temp_max=230,
  4995. )
  4996. cmd = self._published(mqtt_client)
  4997. assert cmd["ams_id"] == 0
  4998. assert cmd["tray_id"] == 2
  4999. assert cmd["slot_id"] == 2
  5000. def test_ams_ht_unchanged(self, mqtt_client):
  5001. """AMS-HT (ams_id >= 128) keeps its single-tray-per-unit encoding."""
  5002. mqtt_client.state.raw_data = {"vt_tray": []}
  5003. assert mqtt_client.ams_set_filament_setting(
  5004. ams_id=128,
  5005. tray_id=0,
  5006. tray_info_idx="GFA01",
  5007. tray_type="PLA",
  5008. tray_sub_brands="PLA Matte",
  5009. tray_color="FFFFFFFF",
  5010. nozzle_temp_min=190,
  5011. nozzle_temp_max=230,
  5012. )
  5013. cmd = self._published(mqtt_client)
  5014. assert cmd["ams_id"] == 128
  5015. assert cmd["tray_id"] == 0
  5016. assert cmd["slot_id"] == 0
  5017. def test_dual_external_left_keeps_legacy_encoding(self, mqtt_client):
  5018. """H2D dual-external (`vt_tray` length > 1): not in the X1C capture, so
  5019. left at the legacy `mqtt_tray_id = 0` until verified separately."""
  5020. mqtt_client.state.raw_data = {"vt_tray": [{"id": "254"}, {"id": "255"}]}
  5021. assert mqtt_client.ams_set_filament_setting(
  5022. ams_id=255,
  5023. tray_id=0, # Ext-L
  5024. tray_info_idx="GFA01",
  5025. tray_type="PLA",
  5026. tray_sub_brands="PLA Matte",
  5027. tray_color="FFFFFFFF",
  5028. nozzle_temp_min=190,
  5029. nozzle_temp_max=230,
  5030. )
  5031. cmd = self._published(mqtt_client)
  5032. # Ext-L → mqtt_ams_id = 254
  5033. assert cmd["ams_id"] == 254
  5034. # tray_id stays at 0 for dual external; this pins current behavior so
  5035. # a future capture-driven change shows up in the diff.
  5036. assert cmd["tray_id"] == 0
  5037. assert cmd["slot_id"] == 0
  5038. class TestDryingCompleteCallback:
  5039. """#1349 — fires ``on_drying_complete(ams_id)`` on a dry_time falling edge."""
  5040. @pytest.fixture
  5041. def mqtt_client(self):
  5042. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5043. events: list[int] = []
  5044. client = BambuMQTTClient(
  5045. ip_address="192.168.1.100",
  5046. serial_number="TEST-DRYING",
  5047. access_code="12345678",
  5048. on_drying_complete=events.append,
  5049. )
  5050. client._drying_events = events # Expose for assertions
  5051. return client
  5052. def test_falling_edge_fires_callback(self, mqtt_client):
  5053. """First push reports drying active, second reports drying done."""
  5054. # Push 1: AMS 0 drying with 60 minutes remaining.
  5055. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 60, "tray": []}]})
  5056. assert mqtt_client._drying_events == []
  5057. # Push 2: dry_time hits 0 → callback fires with the AMS id.
  5058. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5059. assert mqtt_client._drying_events == [0]
  5060. def test_no_fire_when_dry_time_never_started(self, mqtt_client):
  5061. """dry_time = 0 across consecutive pushes does NOT fire — there was
  5062. no drying cycle to finish. Guards against the seed-from-zero false
  5063. positive on startup."""
  5064. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5065. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5066. assert mqtt_client._drying_events == []
  5067. def test_falling_edge_fires_once(self, mqtt_client):
  5068. """Subsequent zero-pushes after the edge don't refire the callback."""
  5069. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 30, "tray": []}]})
  5070. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5071. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5072. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5073. assert mqtt_client._drying_events == [0]
  5074. def test_per_ams_tracking(self, mqtt_client):
  5075. """Two AMS units finishing drying at different times each fire once
  5076. — the falling-edge state is keyed per AMS id."""
  5077. # Both start drying.
  5078. mqtt_client._handle_ams_data(
  5079. {"ams": [{"id": "0", "dry_time": 30, "tray": []}, {"id": "1", "dry_time": 30, "tray": []}]}
  5080. )
  5081. # AMS 0 finishes, AMS 1 still drying.
  5082. mqtt_client._handle_ams_data(
  5083. {"ams": [{"id": "0", "dry_time": 0, "tray": []}, {"id": "1", "dry_time": 15, "tray": []}]}
  5084. )
  5085. assert mqtt_client._drying_events == [0]
  5086. # AMS 1 finishes.
  5087. mqtt_client._handle_ams_data(
  5088. {"ams": [{"id": "0", "dry_time": 0, "tray": []}, {"id": "1", "dry_time": 0, "tray": []}]}
  5089. )
  5090. assert mqtt_client._drying_events == [0, 1]
  5091. def test_restart_drying_after_completion_refires_callback(self, mqtt_client):
  5092. """A new drying cycle after the previous one finished fires the
  5093. callback again on its own falling edge — covers the user manually
  5094. starting a second dry from the UI."""
  5095. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 30, "tray": []}]})
  5096. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5097. # New cycle starts.
  5098. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 45, "tray": []}]})
  5099. # And finishes.
  5100. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5101. assert mqtt_client._drying_events == [0, 0]
  5102. def test_tray_only_partial_does_not_fake_completion(self, mqtt_client):
  5103. """#1462 — a tray-bearing partial update that omits dry_time must not
  5104. be read as dry_time=0. The pre-fix merge dropped dry_time on such
  5105. partials, so the falling-edge detector saw a 60→0 edge and fired a
  5106. false 'drying complete' seconds after drying started — which armed
  5107. smart-plug auto-off and killed the printer mid-cycle."""
  5108. # Drying active, 60 minutes remaining.
  5109. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 60, "tray": []}]})
  5110. assert mqtt_client._drying_events == []
  5111. # Printer sends a tray-bearing partial carrying NO dry_time field.
  5112. mqtt_client._handle_ams_data({"ams": [{"id": "0", "tray": []}]})
  5113. assert mqtt_client._drying_events == []
  5114. # dry_time survived the partial in the merged AMS state.
  5115. assert mqtt_client.state.raw_data["ams"][0]["dry_time"] == 60
  5116. # Drying genuinely finishes → the real edge still fires exactly once.
  5117. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5118. assert mqtt_client._drying_events == [0]
  5119. def test_transient_zero_while_checking_is_not_completion(self, mqtt_client):
  5120. """#2759 — between the command ack and the countdown settling, firmware
  5121. publishes a dry_time of 0 while the AMS is still in its Checking phase.
  5122. The reporter's log caught 720 → 0 → 719 one minute into a 12-hour
  5123. cycle: it dropped the cached target (so the badge guessed the filament
  5124. from tray 1 and read "PETG @ 65°C" for a PLA dry) and armed smart-plug
  5125. auto-off."""
  5126. mqtt_client._drying_targets[0] = {"filament": "PLA", "temp": 45}
  5127. # Cycle starts: 12 hours, unit reports dry_status 1 (Checking).
  5128. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 720, "info": "11402113", "tray": []}]})
  5129. assert mqtt_client._drying_events == []
  5130. # The blip: dry_time 0, still Checking.
  5131. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "info": "11402113", "tray": []}]})
  5132. assert mqtt_client._drying_events == []
  5133. # And the user's chosen target survived it.
  5134. assert mqtt_client._drying_targets[0] == {"filament": "PLA", "temp": 45}
  5135. # Countdown settles and the unit moves to dry_status 2 (Drying).
  5136. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 719, "info": "11402123", "tray": []}]})
  5137. assert mqtt_client._drying_events == []
  5138. # Twelve hours later it really finishes, back to dry_status 0 (Off).
  5139. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "info": "11402103", "tray": []}]})
  5140. assert mqtt_client._drying_events == [0]
  5141. assert 0 not in mqtt_client._drying_targets
  5142. def test_zero_while_stopping_completes(self, mqtt_client):
  5143. """dry_status 4 (Stopping) means the cycle is ending, not running — the
  5144. edge must still fire so smart-plug auto-off runs when a user stops a
  5145. dry early."""
  5146. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 720, "info": "11402123", "tray": []}]})
  5147. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "info": "11402143", "tray": []}]})
  5148. assert mqtt_client._drying_events == [0]
  5149. def test_absent_dry_status_still_completes(self, mqtt_client):
  5150. """The phase gate is a suppression, not a requirement: firmware that
  5151. never reports an info hex must still be able to end a cycle."""
  5152. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 720, "tray": []}]})
  5153. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5154. assert mqtt_client._drying_events == [0]
  5155. def test_early_end_logs_firmware_reason_codes(self, mqtt_client, caplog):
  5156. """#2770 — a 12-hour cycle the firmware abandoned 20 minutes in logged
  5157. only 'drying complete', so the report carried no evidence of why. An
  5158. early end now names the shortfall and the reason fields we already
  5159. parse: phase, sub-phase, cannot-dry codes and live HMS."""
  5160. from backend.app.services.bambu_mqtt import HMSError
  5161. mqtt_client.state.hms_errors = [
  5162. HMSError(code="0x2000003", attr=0x07008000, module=7, severity=2, full_code="0700800002000003")
  5163. ]
  5164. mqtt_client._client = MagicMock()
  5165. mqtt_client.send_drying_command(ams_id=0, temp=65, duration=12, mode=1, filament="PETG")
  5166. mqtt_client._handle_ams_data(
  5167. {"ams": [{"id": "0", "dry_time": 700, "info": "10002123", "dry_sf_reason": [1], "tray": []}]}
  5168. )
  5169. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_mqtt"):
  5170. mqtt_client._handle_ams_data(
  5171. {"ams": [{"id": "0", "dry_time": 0, "info": "10002103", "dry_sf_reason": [1], "tray": []}]}
  5172. )
  5173. assert mqtt_client._drying_events == [0]
  5174. message = "\n".join(r.getMessage() for r in caplog.records)
  5175. assert "drying ended early" in message
  5176. # The shortfall, against the duration we asked the firmware for.
  5177. assert "700 of 720 minutes" in message
  5178. # dry_status 0 (Off) and dry_sub_status 0 from info hex 10002103.
  5179. assert "dry_status=0" in message
  5180. assert "dry_sub_status=0" in message
  5181. # InsufficientPower, and the AMS heater-fan HMS that goes with it.
  5182. assert "dry_sf_reason=[1]" in message
  5183. assert "0700800002000003" in message
  5184. def test_early_end_without_a_cached_target_still_logs(self, mqtt_client, caplog):
  5185. """A cycle Bambuddy did not start — from the printer's screen, from
  5186. Studio, or from before a restart — has no cached duration to compare
  5187. against. The remaining time alone still proves it was cut short, so the
  5188. reason codes must be logged rather than withheld for lack of a target."""
  5189. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 480, "tray": []}]})
  5190. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_mqtt"):
  5191. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5192. message = "\n".join(r.getMessage() for r in caplog.records)
  5193. assert "drying ended early" in message
  5194. assert "480 of ? minutes" in message
  5195. assert "hms=none" in message
  5196. def test_stop_we_sent_is_not_blamed_on_the_firmware(self, mqtt_client, caplog):
  5197. """A stop Bambuddy sends — print takes priority, or the user's Stop
  5198. button — also ends the cycle far short of its duration, which on the
  5199. telemetry alone looks exactly like the firmware abandoning it. It must
  5200. be named as ours rather than reported as an unexplained early end."""
  5201. mqtt_client._client = MagicMock()
  5202. mqtt_client.send_drying_command(ams_id=0, temp=65, duration=12, mode=1, filament="PETG")
  5203. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 700, "tray": []}]})
  5204. mqtt_client.send_drying_command(ams_id=0, temp=0, duration=0, mode=0)
  5205. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_mqtt"):
  5206. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5207. message = "\n".join(r.getMessage() for r in caplog.records)
  5208. assert "drying stopped by Bambuddy" in message
  5209. assert "ended early" not in message
  5210. # And the attribution is consumed, so a later firmware-ended cycle on
  5211. # the same unit is not credited to a stop we sent hours earlier.
  5212. mqtt_client.send_drying_command(ams_id=0, temp=65, duration=12, mode=1, filament="PETG")
  5213. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 700, "tray": []}]})
  5214. caplog.clear()
  5215. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_mqtt"):
  5216. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5217. assert "drying ended early" in "\n".join(r.getMessage() for r in caplog.records)
  5218. def test_cycle_that_runs_to_term_keeps_the_plain_completion_log(self, mqtt_client, caplog):
  5219. """The countdown of a cycle that finishes normally is all but exhausted
  5220. when it drops to 0. Nothing needs explaining, so it keeps the one-line
  5221. message it has always had — the early-end diagnostics must not become
  5222. noise on every completed dry."""
  5223. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 1, "tray": []}]})
  5224. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_mqtt"):
  5225. mqtt_client._handle_ams_data({"ams": [{"id": "0", "dry_time": 0, "tray": []}]})
  5226. message = "\n".join(r.getMessage() for r in caplog.records)
  5227. assert "drying complete (dry_time 1 → 0" in message
  5228. assert "ended early" not in message
  5229. def test_every_cycle_end_records_the_box_conditions(self, mqtt_client, caplog):
  5230. """Whether auto-drying re-arms is decided by the unit's temperature and
  5231. humidity at the moment the cycle ends, so both belong on the line that
  5232. reports the end — normal or early. Reconstructing them for #2770 meant
  5233. cross-referencing hourly alarm lines against scheduler debug that was
  5234. switched off at the time."""
  5235. mqtt_client._handle_ams_data(
  5236. {"ams": [{"id": "0", "dry_time": 1, "temp": "63.0", "humidity_raw": "16", "tray": []}]}
  5237. )
  5238. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_mqtt"):
  5239. mqtt_client._handle_ams_data(
  5240. {"ams": [{"id": "0", "dry_time": 0, "temp": "63.0", "humidity_raw": "16", "tray": []}]}
  5241. )
  5242. message = "\n".join(r.getMessage() for r in caplog.records)
  5243. assert "temp=63.0" in message
  5244. assert "humidity=16" in message
  5245. class TestPrintRunningObservedCallback:
  5246. """#1485 follow-up: on_print_running_observed fires the FIRST time we
  5247. see ``state == RUNNING`` for a printer whose print started before
  5248. Bambuddy came up. It lets main.py capture a timelapse baseline at
  5249. restart-recovery time — when on_print_start was suppressed by the
  5250. #1304 first-push guard. Must NOT fire when on_print_start handles the
  5251. transition (avoids double-capture), and must NOT fire again after
  5252. the first observation in the same session.
  5253. """
  5254. @pytest.fixture
  5255. def mqtt_client(self):
  5256. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5257. return BambuMQTTClient(
  5258. ip_address="192.168.1.100",
  5259. serial_number="TEST123",
  5260. access_code="12345678",
  5261. )
  5262. def test_fires_on_first_running_push_after_startup(self, mqtt_client):
  5263. """First push the client sees has _previous_gcode_state=None, so the
  5264. #1304 guard suppresses on_print_start. on_print_running_observed
  5265. must fire instead so the consumer can recover."""
  5266. start_calls: list[dict] = []
  5267. running_observed_calls: list[dict] = []
  5268. mqtt_client.on_print_start = lambda data: start_calls.append(data)
  5269. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  5270. # Pristine state — exactly what we have right after BambuMQTTClient
  5271. # construction following a Bambuddy restart.
  5272. mqtt_client._was_running = False
  5273. mqtt_client._previous_gcode_state = None
  5274. mqtt_client._process_message(
  5275. {
  5276. "print": {
  5277. "gcode_state": "RUNNING",
  5278. "gcode_file": "/data/Metadata/test_print.gcode",
  5279. "subtask_name": "Test_Print",
  5280. }
  5281. }
  5282. )
  5283. assert start_calls == [], "on_print_start must be suppressed by the #1304 guard"
  5284. assert len(running_observed_calls) == 1
  5285. assert running_observed_calls[0]["filename"] == "/data/Metadata/test_print.gcode"
  5286. assert running_observed_calls[0]["subtask_name"] == "Test_Print"
  5287. def test_does_not_fire_when_print_start_fires(self, mqtt_client):
  5288. """Normal print start (a real state transition from non-RUNNING to
  5289. RUNNING) goes through on_print_start; on_print_running_observed
  5290. must stay quiet so the consumer doesn't capture the baseline twice."""
  5291. start_calls: list[dict] = []
  5292. running_observed_calls: list[dict] = []
  5293. mqtt_client.on_print_start = lambda data: start_calls.append(data)
  5294. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  5295. mqtt_client._was_running = False
  5296. mqtt_client._previous_gcode_state = "IDLE" # Not None — past the #1304 guard
  5297. mqtt_client._process_message(
  5298. {
  5299. "print": {
  5300. "gcode_state": "RUNNING",
  5301. "gcode_file": "/data/Metadata/test_print.gcode",
  5302. "subtask_name": "Test_Print",
  5303. }
  5304. }
  5305. )
  5306. assert len(start_calls) == 1, "on_print_start should fire on a real start transition"
  5307. assert running_observed_calls == [], "on_print_running_observed must not double up with on_print_start"
  5308. def test_fires_only_once_per_session(self, mqtt_client):
  5309. """Subsequent RUNNING pushes in the same session must not re-fire the
  5310. callback — the baseline only needs to be captured once, the consumer
  5311. treats repeat calls as a hint to skip via the in-memory dict guard."""
  5312. running_observed_calls: list[dict] = []
  5313. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  5314. mqtt_client._was_running = False
  5315. mqtt_client._previous_gcode_state = None
  5316. msg = {
  5317. "print": {
  5318. "gcode_state": "RUNNING",
  5319. "gcode_file": "/data/Metadata/test_print.gcode",
  5320. "subtask_name": "Test_Print",
  5321. }
  5322. }
  5323. mqtt_client._process_message(msg)
  5324. mqtt_client._process_message(msg)
  5325. mqtt_client._process_message(msg)
  5326. assert len(running_observed_calls) == 1
  5327. def test_does_not_fire_when_not_running(self, mqtt_client):
  5328. """An IDLE / PREPARE / FINISH first-push must not trigger the
  5329. restart-recovery path — there's no print to baseline."""
  5330. running_observed_calls: list[dict] = []
  5331. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  5332. mqtt_client._was_running = False
  5333. mqtt_client._previous_gcode_state = None
  5334. mqtt_client._process_message(
  5335. {
  5336. "print": {
  5337. "gcode_state": "IDLE",
  5338. "gcode_file": "",
  5339. "subtask_name": "",
  5340. }
  5341. }
  5342. )
  5343. assert running_observed_calls == []
  5344. def test_does_not_fire_without_current_file(self, mqtt_client):
  5345. """RUNNING with no file is ill-formed (firmware glitch / transient).
  5346. We need ``current_file`` to find the right archive, so skip the
  5347. callback rather than fire it with a meaningless payload."""
  5348. running_observed_calls: list[dict] = []
  5349. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  5350. mqtt_client._was_running = False
  5351. mqtt_client._previous_gcode_state = None
  5352. mqtt_client._process_message(
  5353. {
  5354. "print": {
  5355. "gcode_state": "RUNNING",
  5356. "gcode_file": "",
  5357. "subtask_name": "",
  5358. }
  5359. }
  5360. )
  5361. assert running_observed_calls == []
  5362. def test_safe_when_callback_not_set(self, mqtt_client):
  5363. """No callback configured → silently skip; no AttributeError on the
  5364. firing branch."""
  5365. mqtt_client.on_print_running_observed = None
  5366. mqtt_client._was_running = False
  5367. mqtt_client._previous_gcode_state = None
  5368. # Should not raise.
  5369. mqtt_client._process_message(
  5370. {
  5371. "print": {
  5372. "gcode_state": "RUNNING",
  5373. "gcode_file": "/data/Metadata/test_print.gcode",
  5374. "subtask_name": "Test_Print",
  5375. }
  5376. }
  5377. )
  5378. assert mqtt_client._was_running is True
  5379. def test_payload_shape_matches_print_start(self, mqtt_client):
  5380. """The payload shape must mirror on_print_start so main.py's
  5381. consumer can reuse the same dict fields (filename / subtask_name /
  5382. remaining_time / raw_data / ams_mapping). Test pins the keys."""
  5383. running_observed_calls: list[dict] = []
  5384. mqtt_client.on_print_running_observed = lambda data: running_observed_calls.append(data)
  5385. mqtt_client._was_running = False
  5386. mqtt_client._previous_gcode_state = None
  5387. mqtt_client._process_message(
  5388. {
  5389. "print": {
  5390. "gcode_state": "RUNNING",
  5391. "gcode_file": "/data/Metadata/test_print.gcode",
  5392. "subtask_name": "Test_Print",
  5393. "mc_remaining_time": 42,
  5394. }
  5395. }
  5396. )
  5397. assert len(running_observed_calls) == 1
  5398. payload = running_observed_calls[0]
  5399. assert set(payload.keys()) == {
  5400. "filename",
  5401. "subtask_name",
  5402. "remaining_time",
  5403. "raw_data",
  5404. "ams_mapping",
  5405. }
  5406. class TestTotalLayersPreservation:
  5407. """#1771: P1S firmware resets `total_layer_num` to 0 at print end. Without
  5408. this guard, the usage tracker's split path saw `state.total_layers = 0` at
  5409. completion and dumped the whole print onto the last spool.
  5410. These tests pin the preservation pattern (mirror of `_last_valid_layer_num`)
  5411. and the explicit reset on new print start so the previous print's total
  5412. can't bleed into the next.
  5413. """
  5414. @pytest.fixture
  5415. def mqtt_client(self):
  5416. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5417. client = BambuMQTTClient(
  5418. ip_address="192.168.1.100",
  5419. serial_number="TEST123",
  5420. access_code="12345678",
  5421. )
  5422. return client
  5423. def test_nonzero_total_layer_num_sets_state(self, mqtt_client):
  5424. # Baseline: a fresh push with the slicer's total updates state.total_layers.
  5425. mqtt_client._process_message({"print": {"total_layer_num": 260}})
  5426. assert mqtt_client.state.total_layers == 260
  5427. def test_zero_total_layer_num_does_not_clobber_cached_value(self, mqtt_client):
  5428. # Firmware-reset frame: total_layer_num=0 arrives mid- or end-of-print.
  5429. # The guard must NOT overwrite the previously-captured 260.
  5430. mqtt_client._process_message({"print": {"total_layer_num": 260}})
  5431. mqtt_client._process_message({"print": {"total_layer_num": 0}})
  5432. assert mqtt_client.state.total_layers == 260
  5433. def test_print_start_explicitly_resets_total_layers(self, mqtt_client):
  5434. # Without the explicit reset on print start, the previous print's total
  5435. # would persist into the new print until its first total_layer_num push
  5436. # arrived — which is exactly the kind of cross-print bleed the
  5437. # preservation guard above otherwise opens up.
  5438. mqtt_client._process_message({"print": {"total_layer_num": 260}})
  5439. assert mqtt_client.state.total_layers == 260
  5440. # Simulate the new-print-start trigger shape (is_new_print path):
  5441. # state was previously RUNNING on an old file; now we observe a
  5442. # different file going RUNNING.
  5443. mqtt_client._previous_gcode_state = "RUNNING"
  5444. mqtt_client._previous_gcode_file = "/data/Metadata/old_print.gcode"
  5445. mqtt_client._was_running = True
  5446. mqtt_client._process_message(
  5447. {
  5448. "print": {
  5449. "gcode_state": "RUNNING",
  5450. "gcode_file": "/data/Metadata/new_print.gcode",
  5451. "subtask_name": "new_print",
  5452. }
  5453. }
  5454. )
  5455. assert mqtt_client.state.total_layers == 0
  5456. class TestAmsFilamentBackupHoldTimer:
  5457. """Regression: stale push_status arriving within the hold window after a
  5458. toggle command MUST NOT flip ams_filament_backup back to the printer's
  5459. old cfg. Same race-guard pattern xcam uses for spaghetti / first-layer
  5460. detector settings.
  5461. """
  5462. @pytest.fixture
  5463. def mqtt_client(self):
  5464. from unittest.mock import MagicMock
  5465. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5466. client = BambuMQTTClient(
  5467. ip_address="192.168.1.100",
  5468. serial_number="TEST123",
  5469. access_code="12345678",
  5470. )
  5471. # Pretend we're connected so _set_print_option actually publishes.
  5472. client.state.connected = True
  5473. client._client = MagicMock()
  5474. return client
  5475. def test_cfg_push_with_old_value_is_ignored_during_hold(self, mqtt_client):
  5476. # User toggled ON via badge → command sent → state optimistically set.
  5477. mqtt_client.set_ams_filament_backup(True)
  5478. assert mqtt_client.state.ams_filament_backup is True
  5479. # Within the 3 s hold window, a stale push_status arrives still showing
  5480. # the printer's old cfg (bit 18 cleared). The parser must NOT flip our
  5481. # optimistic state back to OFF — otherwise the badge flickers ON→OFF→ON.
  5482. mqtt_client._process_message({"print": {"cfg": "C0340BC219"}}) # bit18=0
  5483. assert mqtt_client.state.ams_filament_backup is True
  5484. def test_cfg_push_after_hold_expires_overrides_state(self, mqtt_client):
  5485. # After the hold window, the printer's real cfg becomes authoritative
  5486. # so a genuine slicer-side or display toggle that we did NOT initiate
  5487. # propagates correctly.
  5488. mqtt_client.set_ams_filament_backup(True)
  5489. mqtt_client._xcam_hold_start["print_option_auto_switch_filament"] = time.time() - 10.0
  5490. mqtt_client._process_message({"print": {"cfg": "C0340BC219"}}) # bit18=0
  5491. assert mqtt_client.state.ams_filament_backup is False
  5492. def test_cfg_push_with_matching_value_during_hold_is_a_noop(self, mqtt_client):
  5493. # Same-value push during hold doesn't trigger the change branch at all
  5494. # (no state mutation, no log spam, hold timer stays armed).
  5495. mqtt_client.set_ams_filament_backup(True)
  5496. before_hold = mqtt_client._xcam_hold_start["print_option_auto_switch_filament"]
  5497. mqtt_client._process_message({"print": {"cfg": "C0340FC219"}}) # bit18=1
  5498. assert mqtt_client.state.ams_filament_backup is True
  5499. # Hold timer still armed — sub-second push didn't reset it.
  5500. assert mqtt_client._xcam_hold_start["print_option_auto_switch_filament"] == before_hold
  5501. # ---------------------------------------------------------------------------
  5502. # 2c. Single-nozzle H2S — external-spool tray_now override (#1822)
  5503. # ---------------------------------------------------------------------------
  5504. class TestTrayNowH2SExternalSpoolOverride:
  5505. """H2S firmware reports tray_now as the AMS's idle slot (typically 0)
  5506. instead of 254 when the active feed is the external spool.
  5507. Bambuddy detects the all-external case via the slicer-captured
  5508. ams_mapping (every entry == -1) and promotes tray_now to 254 so the
  5509. UI active-tray highlight matches the real feed.
  5510. The override is intentionally narrow:
  5511. * only fires when ams_mapping is captured AND every entry is -1
  5512. * does not touch mixed prints ([5, -1]) or AMS-only prints ([5])
  5513. * does not fire when no ams_mapping is captured (printer-screen start)
  5514. """
  5515. @pytest.fixture
  5516. def mqtt_client(self):
  5517. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5518. return BambuMQTTClient(
  5519. ip_address="192.168.1.100",
  5520. serial_number="TEST_H2S",
  5521. access_code="12345678",
  5522. )
  5523. def test_all_external_mapping_promotes_tray_now_to_254(self, mqtt_client):
  5524. """Reporter's scenario: H2S, single nozzle, captured ams_mapping=[-1],
  5525. firmware sends tray_now=0 -> Bambuddy promotes to 254."""
  5526. mqtt_client._captured_ams_mapping = [-1]
  5527. mqtt_client._process_message(_ams_payload(0))
  5528. assert mqtt_client.state.tray_now == 254
  5529. def test_multi_external_mapping_also_promotes(self, mqtt_client):
  5530. """Multi-filament print, every filament mapped to external. Still
  5531. all-external -> still promotes."""
  5532. mqtt_client._captured_ams_mapping = [-1, -1, -1]
  5533. mqtt_client._process_message(_ams_payload(0))
  5534. assert mqtt_client.state.tray_now == 254
  5535. def test_ams_only_mapping_does_not_override(self, mqtt_client):
  5536. """ams_mapping=[5] (AMS slot 5 only) -> firmware value trusted as-is.
  5537. Without the all-external guard, this would falsely override real
  5538. AMS-slot prints."""
  5539. mqtt_client._captured_ams_mapping = [5]
  5540. mqtt_client._process_message(_ams_payload(0))
  5541. assert mqtt_client.state.tray_now == 0
  5542. def test_mixed_mapping_does_not_override(self, mqtt_client):
  5543. """Mixed mapping (AMS slot 5 + external): we have no evidence the
  5544. firmware misreports mid-print swaps, so leave tray_now alone."""
  5545. mqtt_client._captured_ams_mapping = [5, -1]
  5546. mqtt_client._process_message(_ams_payload(0))
  5547. assert mqtt_client.state.tray_now == 0
  5548. def test_no_captured_mapping_does_not_override(self, mqtt_client):
  5549. """Prints started from the printer screen (or before Bambuddy
  5550. connected) have no captured ams_mapping. Behaviour unchanged from
  5551. pre-#1822 — we accept the wrong value rather than guess."""
  5552. mqtt_client._captured_ams_mapping = None
  5553. mqtt_client._process_message(_ams_payload(0))
  5554. assert mqtt_client.state.tray_now == 0
  5555. def test_empty_captured_mapping_does_not_override(self, mqtt_client):
  5556. """Empty list (defensive — should not happen in practice but
  5557. all([]) returns True). Treat as no signal, not as all-external."""
  5558. mqtt_client._captured_ams_mapping = []
  5559. mqtt_client._process_message(_ams_payload(0))
  5560. assert mqtt_client.state.tray_now == 0
  5561. def test_unloaded_after_print_still_resolves_correctly(self, mqtt_client):
  5562. """When the firmware unloads (tray_now=255), the override is skipped
  5563. because the branch only fires for tray_now in 0-3."""
  5564. mqtt_client._captured_ams_mapping = [-1]
  5565. mqtt_client._process_message(_ams_payload(0))
  5566. assert mqtt_client.state.tray_now == 254
  5567. mqtt_client._process_message(_ams_payload(255))
  5568. assert mqtt_client.state.tray_now == 255
  5569. class TestNoLastLayerFinishPhotoTrigger:
  5570. """#2547: the layer_num→total_layer_num edge must NOT trigger a photo.
  5571. That edge is the moment the printer *starts* the final layer. On the H2C
  5572. capture that closed #2547 it arrived at 92% with `mc_remaining_time=2`,
  5573. three minutes and one filament change before the print actually ended, so
  5574. the photo showed the toolhead mid-print over the part. It also latched
  5575. `_finish_photo_captured`, which locked out the two triggers that fire at a
  5576. real end-of-print — so these tests pin both halves: the edge is silent, and
  5577. the later triggers still work after it has passed.
  5578. #1867 (End G-code ejecting the plate before FINISH) is handled in
  5579. `on_finish_photo_moment` via `print_dispatch_context`, not here.
  5580. """
  5581. @pytest.fixture
  5582. def mqtt_client(self):
  5583. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5584. client = BambuMQTTClient(
  5585. ip_address="192.168.1.100",
  5586. serial_number="TEST123",
  5587. access_code="12345678",
  5588. )
  5589. client._was_running = True
  5590. client.state.total_layers = 100
  5591. client.state.layer_num = 99
  5592. return client
  5593. def test_reaching_the_last_layer_fires_nothing(self, mqtt_client):
  5594. events = []
  5595. mqtt_client.on_finish_photo_moment = lambda data: events.append(data)
  5596. mqtt_client._process_message({"print": {"layer_num": 100}})
  5597. assert events == []
  5598. assert mqtt_client._finish_photo_captured is False
  5599. def test_stage_22_still_fires_after_the_last_layer_started(self, mqtt_client):
  5600. """The regression the removed trigger caused: stage 22 is the good
  5601. moment on firmware that emits it, and it arrives *after* the last-layer
  5602. edge. The old latch swallowed it."""
  5603. events = []
  5604. mqtt_client.on_finish_photo_moment = lambda data: events.append(data)
  5605. mqtt_client._process_message({"print": {"layer_num": 100}})
  5606. mqtt_client.state.progress = 100
  5607. mqtt_client._process_message({"print": {"stg_cur": 22}})
  5608. assert [e["trigger"] for e in events] == ["stage_22"]
  5609. def test_finish_state_still_fires_after_the_last_layer_started(self, mqtt_client):
  5610. """H2C/A1 Mini never emit stage 22, so FINISH is their only moment —
  5611. and it is now reachable, where the latch used to block it."""
  5612. events = []
  5613. completion_events = []
  5614. mqtt_client.on_finish_photo_moment = lambda data: events.append(data)
  5615. mqtt_client.on_print_complete = lambda data: completion_events.append(data)
  5616. mqtt_client._previous_gcode_state = "RUNNING"
  5617. mqtt_client._process_message({"print": {"layer_num": 100}})
  5618. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  5619. assert [e["trigger"] for e in events] == ["finish_state"]
  5620. assert len(completion_events) == 1
  5621. def test_no_photo_trigger_fires_repeatedly_across_the_last_layer(self, mqtt_client):
  5622. """A three-minute last layer publishes many frames at layer_num ==
  5623. total. None of them may produce a moment."""
  5624. events = []
  5625. mqtt_client.on_finish_photo_moment = lambda data: events.append(data)
  5626. for percent in (92, 93, 94, 95, 97, 98, 99):
  5627. mqtt_client._process_message({"print": {"layer_num": 100, "mc_percent": percent}})
  5628. assert events == []
  5629. class TestBillingProgressTracking:
  5630. """The latest positive MQTT progress is the fallback for partial billing."""
  5631. @pytest.fixture
  5632. def mqtt_client(self):
  5633. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5634. return BambuMQTTClient(
  5635. ip_address="192.168.1.100",
  5636. serial_number="TEST123",
  5637. access_code="12345678",
  5638. )
  5639. def test_current_frame_is_retained_and_zero_reset_does_not_overwrite_it(self, mqtt_client):
  5640. """Even the first positive frame must survive an immediate printer abort."""
  5641. mqtt_client._process_message({"print": {"mc_percent": 25}})
  5642. assert mqtt_client._last_valid_progress == 25
  5643. mqtt_client._process_message({"print": {"mc_percent": 0}})
  5644. assert mqtt_client._last_valid_progress == 25
  5645. class TestPrintProgressCallback:
  5646. """#2547: `on_print_progress` keeps the finish-photo frame bank fresh.
  5647. Layer changes stop firing the instant the final layer begins, so the bank
  5648. would otherwise stay stale for the whole length of that layer. Progress is
  5649. the field that keeps advancing there — and it freezes before the End G-code
  5650. runs, which is what keeps a swapped plate out of the bank (#1867).
  5651. """
  5652. @pytest.fixture
  5653. def mqtt_client(self):
  5654. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5655. client = BambuMQTTClient(
  5656. ip_address="192.168.1.100",
  5657. serial_number="TEST123",
  5658. access_code="12345678",
  5659. )
  5660. client._was_running = True
  5661. return client
  5662. def test_fires_on_each_advance(self, mqtt_client):
  5663. seen = []
  5664. mqtt_client.on_print_progress = seen.append
  5665. for percent in (92, 93, 94):
  5666. mqtt_client._process_message({"print": {"mc_percent": percent}})
  5667. assert seen == [92, 93, 94]
  5668. def test_does_not_fire_when_progress_is_unchanged(self, mqtt_client):
  5669. """Most frames repeat the same percent; each one would otherwise cost a
  5670. camera grab that contends with the live view."""
  5671. seen = []
  5672. mqtt_client.on_print_progress = seen.append
  5673. mqtt_client._process_message({"print": {"mc_percent": 92}})
  5674. mqtt_client._process_message({"print": {"mc_percent": 92}})
  5675. mqtt_client._process_message({"print": {"mc_percent": 92}})
  5676. assert seen == [92]
  5677. def test_does_not_fire_when_progress_goes_backwards(self, mqtt_client):
  5678. """Firmware resets progress to 0 on cancel — that is not the print
  5679. advancing, and banking a frame there would be banking a cancelled bed."""
  5680. seen = []
  5681. mqtt_client.on_print_progress = seen.append
  5682. mqtt_client._process_message({"print": {"mc_percent": 92}})
  5683. mqtt_client._process_message({"print": {"mc_percent": 0}})
  5684. assert seen == [92]
  5685. def test_does_not_fire_when_no_print_is_running(self, mqtt_client):
  5686. mqtt_client._was_running = False
  5687. seen = []
  5688. mqtt_client.on_print_progress = seen.append
  5689. mqtt_client._process_message({"print": {"mc_percent": 92}})
  5690. assert seen == []
  5691. def test_absent_callback_is_not_an_error(self, mqtt_client):
  5692. mqtt_client.on_print_progress = None
  5693. mqtt_client._process_message({"print": {"mc_percent": 92}})
  5694. assert mqtt_client.state.progress == 92
  5695. class TestPresumedPowerOffRecovery:
  5696. """#2629: a smart-plug turn-off marks the printer offline optimistically.
  5697. When the plug does not actually feed the printer, the printer keeps
  5698. publishing — and the forced 'unknown' state must be undone, or it sticks
  5699. until the next full pushall and the queue scheduler stalls forever.
  5700. """
  5701. @pytest.fixture
  5702. def mqtt_client(self):
  5703. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5704. client = BambuMQTTClient(
  5705. ip_address="192.168.1.100",
  5706. serial_number="TEST123",
  5707. access_code="12345678",
  5708. )
  5709. client.state.connected = True
  5710. client.state.state = "FINISH"
  5711. return client
  5712. @staticmethod
  5713. def _report(client, payload):
  5714. """Feed a report-topic message through the real _on_message path."""
  5715. class _Msg:
  5716. def __init__(self, topic, data):
  5717. self.topic = topic
  5718. self.payload = json.dumps(data).encode()
  5719. client._on_message(None, None, _Msg(client.topic_subscribe, payload))
  5720. def test_mark_power_off_blanks_state_and_remembers_it(self, mqtt_client):
  5721. assert mqtt_client.mark_power_off() is True
  5722. assert mqtt_client.state.connected is False
  5723. assert mqtt_client.state.state == "unknown"
  5724. assert mqtt_client._state_before_power_off == "FINISH"
  5725. def test_mark_power_off_noop_when_already_disconnected(self, mqtt_client):
  5726. mqtt_client.state.connected = False
  5727. assert mqtt_client.mark_power_off() is False
  5728. assert mqtt_client._state_before_power_off is None
  5729. def test_second_mark_does_not_overwrite_saved_state(self, mqtt_client):
  5730. mqtt_client.mark_power_off()
  5731. # Something flips connected back (a partial message) before the second mark
  5732. mqtt_client.state.connected = True
  5733. mqtt_client.mark_power_off()
  5734. assert mqtt_client._state_before_power_off == "FINISH"
  5735. def test_partial_report_restores_state(self, mqtt_client):
  5736. """The steady-state push_status carries no gcode_state — the pre-off
  5737. state must come back anyway, otherwise 'unknown' is permanent."""
  5738. mqtt_client.mark_power_off()
  5739. self._report(mqtt_client, {"print": {"wifi_signal": "-30dBm"}})
  5740. assert mqtt_client.state.connected is True
  5741. assert mqtt_client.state.state == "FINISH"
  5742. assert mqtt_client._state_before_power_off is None
  5743. def test_restore_broadcasts_state_change(self, mqtt_client):
  5744. broadcasts = []
  5745. mqtt_client.on_state_change = lambda state: broadcasts.append(state.state)
  5746. mqtt_client.mark_power_off()
  5747. self._report(mqtt_client, {"print": {"wifi_signal": "-30dBm"}})
  5748. assert "FINISH" in broadcasts
  5749. def test_fresh_gcode_state_wins_over_restored_state(self, mqtt_client):
  5750. """A report that does carry gcode_state is authoritative."""
  5751. mqtt_client.mark_power_off()
  5752. self._report(mqtt_client, {"print": {"gcode_state": "IDLE"}})
  5753. assert mqtt_client.state.state == "IDLE"
  5754. def test_restore_happens_only_once(self, mqtt_client):
  5755. """After recovery a later genuine blank must not be undone by a stale
  5756. saved state."""
  5757. mqtt_client.mark_power_off()
  5758. self._report(mqtt_client, {"print": {"wifi_signal": "-30dBm"}})
  5759. # Printer really loses power now: state blanked, nothing to restore from
  5760. mqtt_client.state.state = "unknown"
  5761. assert mqtt_client._restore_state_after_false_power_off() is False
  5762. assert mqtt_client.state.state == "unknown"
  5763. def test_request_topic_traffic_does_not_restore(self, mqtt_client):
  5764. """Only the printer's own report topic proves it is alive; the request
  5765. topic also carries slicer/Bambuddy commands."""
  5766. mqtt_client.mark_power_off()
  5767. class _Msg:
  5768. topic = mqtt_client.topic_publish
  5769. payload = json.dumps({"print": {"command": "project_file"}}).encode()
  5770. mqtt_client._on_message(None, None, _Msg())
  5771. assert mqtt_client.state.state == "unknown"
  5772. assert mqtt_client._state_before_power_off == "FINISH"
  5773. def test_reconnect_discards_saved_state(self, mqtt_client):
  5774. """A real power cut drops the MQTT session; on reconnect the saved state
  5775. is stale and must not be broadcast ahead of the printer's first report."""
  5776. from unittest.mock import MagicMock
  5777. mqtt_client.mark_power_off()
  5778. paho = MagicMock()
  5779. paho.subscribe.return_value = (0, 1) # (MQTT_ERR_SUCCESS, mid)
  5780. mqtt_client._on_connect(paho, None, {}, 0)
  5781. assert mqtt_client._state_before_power_off is None
  5782. self._report(mqtt_client, {"print": {"wifi_signal": "-30dBm"}})
  5783. assert mqtt_client.state.state == "unknown"
  5784. def test_already_unknown_state_is_not_saved(self, mqtt_client):
  5785. """A printer that never reported has nothing to restore — saving
  5786. 'unknown' would make the recovery broadcast a no-op state change."""
  5787. mqtt_client.state.state = "unknown"
  5788. assert mqtt_client.mark_power_off() is True
  5789. assert mqtt_client._state_before_power_off is None
  5790. def test_message_interleaved_with_mark_does_not_strand_unknown(self, mqtt_client):
  5791. """mark_power_off runs on the event loop, _on_message on the paho
  5792. thread. A message landing mid-mark must not consume the saved state and
  5793. leave the printer stuck on 'unknown' — the next message must recover."""
  5794. # Simulate the worst interleaving: a report is processed after the state
  5795. # was blanked but before the previous state was recorded.
  5796. mqtt_client.state.connected = False
  5797. mqtt_client.state.state = "unknown"
  5798. self._report(mqtt_client, {"print": {"wifi_signal": "-30dBm"}})
  5799. # ...now the rest of the mark completes.
  5800. mqtt_client._state_before_power_off = "FINISH"
  5801. self._report(mqtt_client, {"print": {"wifi_signal": "-30dBm"}})
  5802. assert mqtt_client.state.state == "FINISH"
  5803. class TestKProfileResponseDoesNotClobberNozzle:
  5804. """#2663: the K-profile fetch (get_kprofiles) probes every nozzle size
  5805. 0.2/0.4/0.6/0.8 with an ``extrusion_cali_get`` request. Each response
  5806. echoes the *requested* nozzle_diameter at the top level, which is NOT the
  5807. installed hardware. _process_message must not feed those responses to
  5808. _update_state, or the real nozzle size gets overwritten (typically to 0.8,
  5809. the last size probed) and the #1899 dispatch guard then blocks prints.
  5810. """
  5811. @pytest.fixture
  5812. def mqtt_client(self):
  5813. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5814. return BambuMQTTClient(
  5815. ip_address="192.168.1.100",
  5816. serial_number="A1TEST",
  5817. access_code="12345678",
  5818. )
  5819. def test_kprofile_response_does_not_overwrite_nozzle_diameter(self, mqtt_client):
  5820. # A genuine pushall reports the real 0.4mm nozzle.
  5821. mqtt_client._process_message({"print": {"nozzle_diameter": "0.4"}})
  5822. assert mqtt_client.state.nozzles[0].nozzle_diameter == "0.4"
  5823. # The K-profile probe's 0.8mm response arrives (as it did on the
  5824. # reporter's A1s). It must NOT clobber the hardware nozzle.
  5825. mqtt_client._process_message(
  5826. {
  5827. "print": {
  5828. "command": "extrusion_cali_get",
  5829. "nozzle_diameter": "0.8",
  5830. "filaments": [],
  5831. "sequence_id": "1501",
  5832. }
  5833. }
  5834. )
  5835. assert mqtt_client.state.nozzles[0].nozzle_diameter == "0.4"
  5836. def test_kprofile_response_is_still_parsed(self, mqtt_client):
  5837. # Skipping _update_state must not skip the K-profile handler: the
  5838. # response's profiles still populate state.kprofiles.
  5839. mqtt_client._process_message(
  5840. {
  5841. "print": {
  5842. "command": "extrusion_cali_get",
  5843. "nozzle_diameter": "0.4",
  5844. "filaments": [
  5845. {
  5846. "cali_idx": 0,
  5847. "nozzle_diameter": "0.4",
  5848. "filament_id": "GFA00",
  5849. "name": "PLA",
  5850. "k_value": "0.020000",
  5851. }
  5852. ],
  5853. }
  5854. }
  5855. )
  5856. assert len(mqtt_client.state.kprofiles) == 1
  5857. assert mqtt_client.state.kprofiles[0].filament_id == "GFA00"
  5858. def test_genuine_pushall_still_updates_nozzle(self, mqtt_client):
  5859. # The one legitimate source of the hardware nozzle still works, and a
  5860. # later pushall corrects a value an old build left wrong.
  5861. mqtt_client.state.nozzles[0].nozzle_diameter = "0.8"
  5862. mqtt_client._process_message({"print": {"nozzle_diameter": "0.4"}})
  5863. assert mqtt_client.state.nozzles[0].nozzle_diameter == "0.4"
  5864. class TestKProfileNozzleDiameterFromEnvelope:
  5865. """#1748: every K-profile came back as 0.4mm on single-nozzle printers.
  5866. ``extrusion_cali_get`` carries ``nozzle_diameter`` only on the response
  5867. envelope — the per-filament entries hold just setting_id, filament_id,
  5868. name, k_value, n_coef and cali_idx. The parser read the field per entry
  5869. with a "0.4" default, so a 0.6/0.8 nozzle's profiles were all stamped 0.4.
  5870. Beyond the K-Profiles display that broke the cali_idx cascade in the
  5871. inventory and Spoolman assign paths, which match on nozzle_diameter.
  5872. """
  5873. @pytest.fixture
  5874. def mqtt_client(self):
  5875. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5876. return BambuMQTTClient(
  5877. ip_address="192.168.1.100",
  5878. serial_number="X1ETEST",
  5879. access_code="12345678",
  5880. )
  5881. @staticmethod
  5882. def _response(nozzle="0.8", entries=None, seq="48"):
  5883. """A verbatim-shaped extrusion_cali_get payload from the #1748 report."""
  5884. if entries is None:
  5885. entries = [
  5886. {
  5887. "setting_id": "GFSNLS02_07",
  5888. "filament_id": "GFSNL02",
  5889. "name": "SUNLU PLA Matte WHITE 0.8",
  5890. "k_value": "0.01750",
  5891. "n_coef": "1.000",
  5892. "cali_idx": 265,
  5893. "is_history_setting": True,
  5894. }
  5895. ]
  5896. print_data = {"command": "extrusion_cali_get", "filament_id": "", "filaments": entries}
  5897. if nozzle is not None:
  5898. print_data["nozzle_diameter"] = nozzle
  5899. if seq is not None:
  5900. print_data["sequence_id"] = seq
  5901. return {"print": print_data}
  5902. def test_broadcast_uses_envelope_diameter(self, mqtt_client):
  5903. # No request in flight: the unsolicited broadcast still has to record
  5904. # the right diameter, because state.kprofiles is what the assign paths
  5905. # read when nobody has just fetched.
  5906. mqtt_client._process_message(self._response(nozzle="0.8"))
  5907. assert [p.nozzle_diameter for p in mqtt_client.state.kprofiles] == ["0.8"]
  5908. @pytest.mark.asyncio
  5909. async def test_awaited_response_uses_envelope_diameter(self, mqtt_client):
  5910. profiles = await self._fetch(mqtt_client, "0.6", self._response(nozzle="0.6", seq="7"))
  5911. assert [p.nozzle_diameter for p in profiles] == ["0.6"]
  5912. def test_entry_value_still_wins(self, mqtt_client):
  5913. # Dual-nozzle firmware does put the field on each entry; that stays
  5914. # authoritative, since a batch can legitimately span nozzles.
  5915. entries = [{"cali_idx": 1, "filament_id": "GFA00", "name": "PLA", "nozzle_diameter": "0.4"}]
  5916. mqtt_client._process_message(self._response(nozzle="0.8", entries=entries))
  5917. assert mqtt_client.state.kprofiles[0].nozzle_diameter == "0.4"
  5918. def test_empty_entry_value_falls_back_to_envelope(self, mqtt_client):
  5919. entries = [{"cali_idx": 1, "filament_id": "GFA00", "name": "PLA", "nozzle_diameter": ""}]
  5920. mqtt_client._process_message(self._response(nozzle="0.8", entries=entries))
  5921. assert mqtt_client.state.kprofiles[0].nozzle_diameter == "0.8"
  5922. def test_no_envelope_value_falls_back_to_default(self, mqtt_client):
  5923. # Neither source available: keep the old default rather than let
  5924. # str(None) write the literal string "None" into the profile.
  5925. mqtt_client._process_message(self._response(nozzle=None))
  5926. assert mqtt_client.state.kprofiles[0].nozzle_diameter == "0.4"
  5927. @staticmethod
  5928. async def _fetch(client, nozzle, response):
  5929. """Run get_kprofiles, feeding `response` in as the printer's answer."""
  5930. client.state.connected = True
  5931. client._client = MagicMock()
  5932. client._client.publish.side_effect = lambda *a, **kw: client._process_message(response)
  5933. return await client.get_kprofiles(nozzle_diameter=nozzle, timeout=2.0)
  5934. class TestKProfileWriteAcks:
  5935. """#2718: K-profile writes were fire-and-forget.
  5936. ``set_kprofiles_batch`` published and returned True immediately, and the
  5937. printer's ``extrusion_cali_set`` answer was logged at DEBUG and dropped, so
  5938. a rejected write was reported to the user as saved. Two facts measured on
  5939. real hardware shape the fix: the printer echoes our ``sequence_id`` back
  5940. (so the ack can be correlated), and it answers ``result: "fail",
  5941. reason: "invalid tray_id"`` to ``tray_id: -1`` on single-nozzle firmware
  5942. while applying the write anyway — flipping that field to 0 is what makes
  5943. ``result`` trustworthy.
  5944. """
  5945. @pytest.fixture
  5946. def mqtt_client(self):
  5947. from backend.app.services.bambu_mqtt import BambuMQTTClient
  5948. client = BambuMQTTClient(
  5949. ip_address="192.168.1.100",
  5950. serial_number="X1CTEST",
  5951. access_code="12345678",
  5952. )
  5953. client.state.connected = True
  5954. client._client = MagicMock()
  5955. return client
  5956. @staticmethod
  5957. def _sent(client):
  5958. return json.loads(client._client.publish.call_args[0][1])["print"]
  5959. def test_set_sends_tray_id_zero(self, mqtt_client):
  5960. mqtt_client.set_kprofile(filament_id="GFL99", name="test", k_value="0.022000")
  5961. assert self._sent(mqtt_client)["filaments"][0]["tray_id"] == 0
  5962. def test_batch_sends_tray_id_zero(self, mqtt_client):
  5963. mqtt_client.set_kprofiles_batch([{"filament_id": "GFL99", "name": "t", "k_value": "0.020000"}])
  5964. assert self._sent(mqtt_client)["filaments"][0]["tray_id"] == 0
  5965. def test_writers_return_their_sequence_id(self, mqtt_client):
  5966. seq = mqtt_client.set_kprofile(filament_id="GFL99", name="test", k_value="0.022000")
  5967. assert seq == self._sent(mqtt_client)["sequence_id"]
  5968. assert seq in mqtt_client._pending_cali_acks
  5969. def test_writers_return_none_when_disconnected(self, mqtt_client):
  5970. mqtt_client.state.connected = False
  5971. assert mqtt_client.set_kprofile(filament_id="GFL99", name="t", k_value="0.02") is None
  5972. assert mqtt_client.set_kprofiles_batch([{"filament_id": "GFL99"}]) is None
  5973. assert mqtt_client.delete_kprofile(cali_idx=1, filament_id="GFL99", nozzle_id="HH00-0.4") is None
  5974. def test_per_tray_extrusion_cali_set_advances_the_sequence_id(self, mqtt_client):
  5975. # It used to reuse the previous command's id, which would silently
  5976. # defeat the correlation the write path now depends on.
  5977. before = mqtt_client._sequence_id
  5978. mqtt_client.extrusion_cali_set(tray_id=0, k_value=0.02)
  5979. assert mqtt_client._sequence_id > before
  5980. assert self._sent(mqtt_client)["sequence_id"] == str(mqtt_client._sequence_id)
  5981. @pytest.mark.asyncio
  5982. async def test_failure_ack_is_reported_as_failure(self, mqtt_client):
  5983. seq = mqtt_client.set_kprofile(filament_id="GFL99", name="test", k_value="0.022000")
  5984. mqtt_client._process_message(
  5985. {
  5986. "print": {
  5987. "command": "extrusion_cali_set",
  5988. "result": "fail",
  5989. "reason": "invalid tray_id",
  5990. "sequence_id": seq,
  5991. }
  5992. }
  5993. )
  5994. ok, detail = await mqtt_client.await_cali_ack(seq, timeout=2.0)
  5995. assert ok is False
  5996. assert detail == "invalid tray_id"
  5997. @pytest.mark.asyncio
  5998. async def test_success_ack_passes(self, mqtt_client):
  5999. seq = mqtt_client.set_kprofile(filament_id="GFL99", name="test", k_value="0.022000")
  6000. mqtt_client._process_message(
  6001. {"print": {"command": "extrusion_cali_set", "result": "success", "reason": "", "sequence_id": seq}}
  6002. )
  6003. ok, _ = await mqtt_client.await_cali_ack(seq, timeout=2.0)
  6004. assert ok is True
  6005. @pytest.mark.asyncio
  6006. async def test_ack_for_another_write_does_not_resolve_this_one(self, mqtt_client):
  6007. seq = mqtt_client.set_kprofile(filament_id="GFL99", name="test", k_value="0.022000")
  6008. mqtt_client._process_message(
  6009. {
  6010. "print": {
  6011. "command": "extrusion_cali_set",
  6012. "result": "fail",
  6013. "reason": "invalid tray_id",
  6014. "sequence_id": "999999",
  6015. }
  6016. }
  6017. )
  6018. # Unrelated sequence_id: this write is still unanswered, so it times
  6019. # out rather than inheriting someone else's failure.
  6020. ok, detail = await mqtt_client.await_cali_ack(seq, timeout=0.3)
  6021. assert ok is True
  6022. assert "no acknowledgement" in detail
  6023. @pytest.mark.asyncio
  6024. async def test_silence_is_not_treated_as_rejection(self, mqtt_client):
  6025. # Firmware that never answers must not turn every save into an error.
  6026. seq = mqtt_client.delete_kprofile(cali_idx=1, filament_id="GFL99", nozzle_id="HH00-0.4")
  6027. ok, detail = await mqtt_client.await_cali_ack(seq, timeout=0.3)
  6028. assert ok is True
  6029. assert "no acknowledgement" in detail
  6030. @pytest.mark.asyncio
  6031. async def test_pending_slot_is_released(self, mqtt_client):
  6032. seq = mqtt_client.set_kprofile(filament_id="GFL99", name="test", k_value="0.022000")
  6033. await mqtt_client.await_cali_ack(seq, timeout=0.3)
  6034. assert mqtt_client._pending_cali_acks == {}
  6035. def test_delete_ack_is_matched_too(self, mqtt_client):
  6036. seq = mqtt_client.delete_kprofile(cali_idx=1, filament_id="GFL99", nozzle_id="HH00-0.4")
  6037. mqtt_client._process_message(
  6038. {"print": {"command": "extrusion_cali_del", "result": "success", "sequence_id": seq}}
  6039. )
  6040. assert mqtt_client._pending_cali_acks[seq]["result"] == "success"
  6041. class TestKProfileRequestCorrelation:
  6042. """#1748: K-profile requests timed out whenever two were in flight.
  6043. Responses were matched to requests by nozzle diameter alone, held in one
  6044. shared ``_expected_kprofile_nozzle`` slot. A second request overwrote the
  6045. first's expectation, so the first's valid answer was discarded as a
  6046. mismatch and that request timed out even though the printer had replied.
  6047. Correlation now runs off the sequence_id we send, with the nozzle match
  6048. kept as a fallback for firmware that doesn't echo it.
  6049. """
  6050. @pytest.fixture
  6051. def mqtt_client(self):
  6052. from backend.app.services.bambu_mqtt import BambuMQTTClient
  6053. client = BambuMQTTClient(
  6054. ip_address="192.168.1.100",
  6055. serial_number="X1ETEST",
  6056. access_code="12345678",
  6057. )
  6058. client.state.connected = True
  6059. client._client = MagicMock()
  6060. return client
  6061. @staticmethod
  6062. def _response(nozzle, seq, name):
  6063. return {
  6064. "print": {
  6065. "command": "extrusion_cali_get",
  6066. "nozzle_diameter": nozzle,
  6067. "sequence_id": seq,
  6068. "filaments": [{"cali_idx": 1, "filament_id": "GFA00", "name": name, "k_value": "0.020000"}],
  6069. }
  6070. }
  6071. @pytest.mark.asyncio
  6072. async def test_concurrent_requests_each_get_their_own_response(self, mqtt_client):
  6073. # The failing sequence from the report: 0.8 is requested, then 0.4,
  6074. # then the 0.8 answer lands. Under nozzle-only matching the expected
  6075. # slot already said 0.4, so the 0.8 answer was dropped on the floor.
  6076. seen: list[str] = []
  6077. def publish(_topic, payload, **_kw):
  6078. seen.append(json.loads(payload)["print"]["sequence_id"])
  6079. mqtt_client._client.publish.side_effect = publish
  6080. big = asyncio.create_task(mqtt_client.get_kprofiles(nozzle_diameter="0.8", timeout=5.0))
  6081. small = asyncio.create_task(mqtt_client.get_kprofiles(nozzle_diameter="0.4", timeout=5.0))
  6082. await asyncio.sleep(0) # let both publish before either answer arrives
  6083. assert len(seen) == 2
  6084. mqtt_client._process_message(self._response("0.8", seen[0], "wide"))
  6085. mqtt_client._process_message(self._response("0.4", seen[1], "narrow"))
  6086. assert [p.name for p in await big] == ["wide"]
  6087. assert [p.name for p in await small] == ["narrow"]
  6088. @pytest.mark.asyncio
  6089. async def test_falls_back_to_nozzle_match_when_sequence_id_is_not_echoed(self, mqtt_client):
  6090. # Firmware that answers with its own sequence_id must keep working.
  6091. mqtt_client._client.publish.side_effect = lambda *a, **kw: mqtt_client._process_message(
  6092. self._response("0.6", "9999", "echoed-nothing")
  6093. )
  6094. profiles = await mqtt_client.get_kprofiles(nozzle_diameter="0.6", timeout=2.0)
  6095. assert [p.name for p in profiles] == ["echoed-nothing"]
  6096. @pytest.mark.asyncio
  6097. async def test_unrelated_broadcast_does_not_clobber_a_pending_fetch(self, mqtt_client):
  6098. # The printer broadcasts 0.4 profiles unsolicited. One arriving while a
  6099. # 0.8 fetch is open must neither satisfy nor overwrite it.
  6100. def publish(_topic, payload, **_kw):
  6101. seq = json.loads(payload)["print"]["sequence_id"]
  6102. mqtt_client._process_message(self._response("0.4", "9999", "broadcast"))
  6103. mqtt_client._process_message(self._response("0.8", seq, "wanted"))
  6104. mqtt_client._client.publish.side_effect = publish
  6105. profiles = await mqtt_client.get_kprofiles(nozzle_diameter="0.8", timeout=2.0)
  6106. assert [p.name for p in profiles] == ["wanted"]
  6107. assert [p.name for p in mqtt_client.state.kprofiles] == ["wanted"]
  6108. @pytest.mark.asyncio
  6109. async def test_pending_entry_is_released_on_timeout(self, mqtt_client):
  6110. # A timed-out attempt must not leave its entry behind, or a later
  6111. # broadcast would be matched to a request nobody is waiting on.
  6112. profiles = await mqtt_client.get_kprofiles(nozzle_diameter="0.8", timeout=0.01, max_retries=1)
  6113. assert profiles == []
  6114. assert mqtt_client._pending_kprofile_requests == {}
  6115. class TestConnectRefusalReporting:
  6116. """#2698: a refused CONNACK must leave a trace.
  6117. ``_on_connect``'s failure branch used to be a bare ``connected = False``.
  6118. A printer refusing our access code then looked exactly like one that was
  6119. powered off: paho reports the follow-up drop as the generic "Unspecified
  6120. error", so the support bundle from a 30-second reconnect loop carried no
  6121. hint of the real cause. Bambu speaks MQTT 3.1.1, whose CONNACK return codes
  6122. 4 and 5 paho maps to reason codes 134 / 135.
  6123. """
  6124. @pytest.fixture
  6125. def mqtt_client(self):
  6126. from backend.app.services.bambu_mqtt import BambuMQTTClient
  6127. return BambuMQTTClient(
  6128. ip_address="192.168.1.100",
  6129. serial_number="TEST123",
  6130. access_code="12345678",
  6131. )
  6132. @staticmethod
  6133. def _connack(v3_return_code):
  6134. from paho.mqtt.client import convert_connack_rc_to_reason_code
  6135. return convert_connack_rc_to_reason_code(v3_return_code)
  6136. def test_no_error_recorded_before_any_attempt(self, mqtt_client):
  6137. assert mqtt_client.last_connect_error is None
  6138. assert mqtt_client.last_connect_error_name is None
  6139. @pytest.mark.parametrize("v3_rc", [4, 5])
  6140. def test_credential_refusal_recorded(self, mqtt_client, v3_rc, caplog):
  6141. with caplog.at_level(logging.WARNING):
  6142. mqtt_client._on_connect(None, None, None, self._connack(v3_rc))
  6143. assert mqtt_client.state.connected is False
  6144. assert mqtt_client.last_connect_error == "auth_rejected"
  6145. assert "refused" in caplog.text.lower()
  6146. # The remedy has to be in the log — that line is what a maintainer
  6147. # reads out of a support bundle.
  6148. assert "access code" in caplog.text.lower()
  6149. # Never leak the credential itself into a bundle.
  6150. assert "12345678" not in caplog.text
  6151. def test_non_credential_refusal_recorded_separately(self, mqtt_client, caplog):
  6152. # CONNACK 3 = server unavailable: a real refusal, but not about creds.
  6153. with caplog.at_level(logging.WARNING):
  6154. mqtt_client._on_connect(None, None, None, self._connack(3))
  6155. assert mqtt_client.last_connect_error == "refused"
  6156. assert "access code" not in caplog.text.lower()
  6157. def test_successful_connect_clears_previous_error(self, mqtt_client):
  6158. mqtt_client._on_connect(None, None, None, self._connack(5))
  6159. assert mqtt_client.last_connect_error == "auth_rejected"
  6160. mock_client = type("MockClient", (), {"subscribe": lambda self, topic: (0, 1)})()
  6161. mqtt_client._on_connect(mock_client, None, None, 0)
  6162. assert mqtt_client.state.connected is True
  6163. assert mqtt_client.last_connect_error is None
  6164. assert mqtt_client.last_connect_error_name is None
  6165. def test_disconnect_line_carries_the_refusal(self, mqtt_client, caplog):
  6166. """The reconnect loop is what fills the log, so it must say why."""
  6167. mqtt_client._on_connect(None, None, None, self._connack(5))
  6168. caplog.clear()
  6169. with caplog.at_level(logging.WARNING):
  6170. mqtt_client._on_disconnect(None, None)
  6171. assert "MQTT disconnected" in caplog.text
  6172. assert "refused" in caplog.text
  6173. assert "Not authorized" in caplog.text
  6174. def test_disconnect_line_unchanged_without_a_refusal(self, mqtt_client, caplog):
  6175. with caplog.at_level(logging.WARNING):
  6176. mqtt_client._on_disconnect(None, None)
  6177. assert "MQTT disconnected" in caplog.text
  6178. assert "refused" not in caplog.text
  6179. class TestEndOfPrintProbe:
  6180. """Tests for #2547: the end-of-print telemetry probe.
  6181. The probe exists to answer a question no existing support bundle can:
  6182. what do the stage/action fields do between the last object layer and
  6183. gcode_state=FINISH? stg_cur=22 was supposed to mark "toolhead parked,
  6184. before filament unload" (#1721) and fires on no model in the field, and
  6185. Bambuddy drops every other stage field unread. These tests pin the
  6186. window's boundaries and the guarantee that instrumentation stays
  6187. instrumentation — it must never raise into the ingest path.
  6188. """
  6189. LOGGER = "backend.app.services.bambu_mqtt"
  6190. @pytest.fixture
  6191. def mqtt_client(self):
  6192. from backend.app.services.bambu_mqtt import BambuMQTTClient
  6193. client = BambuMQTTClient(
  6194. ip_address="192.168.1.100",
  6195. serial_number="TEST123",
  6196. access_code="12345678",
  6197. )
  6198. client._was_running = True
  6199. client.state.state = "RUNNING"
  6200. client.state.total_layers = 100
  6201. client.state.layer_num = 98
  6202. client.state.progress = 90.0
  6203. client.state.remaining_time = 12
  6204. return client
  6205. def test_silent_when_debug_logging_is_off(self, mqtt_client, caplog):
  6206. """The probe is a debug tool; at INFO it must cost nothing and say
  6207. nothing, including for a frame that would otherwise open the window."""
  6208. with caplog.at_level(logging.INFO, logger=self.LOGGER):
  6209. mqtt_client._process_message({"print": {"layer_num": 100}})
  6210. assert "EOP-PROBE" not in caplog.text
  6211. assert mqtt_client._eop_probe_open is False
  6212. def test_does_not_open_mid_print(self, mqtt_client, caplog):
  6213. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6214. mqtt_client._process_message({"print": {"layer_num": 99, "mc_percent": 91}})
  6215. assert "EOP-PROBE" not in caplog.text
  6216. assert mqtt_client._eop_probe_open is False
  6217. def test_opens_on_the_last_layer_frame_itself(self, mqtt_client, caplog):
  6218. """The frame carrying the signal must be captured, not just the ones
  6219. after it — so the probe has to read the raw frame rather than state,
  6220. which _update_state only updates further down the same call."""
  6221. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6222. mqtt_client._process_message({"print": {"layer_num": 100, "stg_cur": 0}})
  6223. assert "EOP-PROBE open" in caplog.text
  6224. assert "'layer_num': 100" in caplog.text
  6225. assert mqtt_client._eop_probe_open is True
  6226. def test_opens_on_progress_when_the_last_layer_packet_is_missed(self, mqtt_client, caplog):
  6227. """The layer_num edge is a single transient packet and is dropped
  6228. intermittently (the reason #1867 needed a second mechanism). Progress
  6229. has to be able to open the window on its own."""
  6230. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6231. mqtt_client._process_message({"print": {"mc_percent": 99}})
  6232. assert "EOP-PROBE open" in caplog.text
  6233. assert mqtt_client._eop_probe_open is True
  6234. def test_zero_remaining_does_not_open_before_the_print_progresses(self, mqtt_client, caplog):
  6235. """mc_remaining_time reads 0 during pre-print calibration too, so it
  6236. only counts once progress is non-zero."""
  6237. mqtt_client.state.progress = 0.0
  6238. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6239. mqtt_client._process_message({"print": {"mc_remaining_time": 0, "mc_percent": 0}})
  6240. assert "EOP-PROBE" not in caplog.text
  6241. def test_does_not_open_when_the_print_never_ran(self, mqtt_client, caplog):
  6242. """Bambuddy restarted mid-print, or firmware replayed a stale frame."""
  6243. mqtt_client._was_running = False
  6244. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6245. mqtt_client._process_message({"print": {"layer_num": 100}})
  6246. assert "EOP-PROBE" not in caplog.text
  6247. def test_logs_only_changed_fields_after_opening(self, mqtt_client, caplog):
  6248. """Most probed fields are static across the window; logging all of
  6249. them every frame would bury the transitions we're looking for."""
  6250. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6251. mqtt_client._process_message({"print": {"layer_num": 100, "stg_cur": 0}})
  6252. caplog.clear()
  6253. # Identical frame — nothing moved, so nothing to say.
  6254. mqtt_client._process_message({"print": {"layer_num": 100, "stg_cur": 0}})
  6255. assert "EOP-PROBE" not in caplog.text
  6256. mqtt_client._process_message({"print": {"layer_num": 100, "stg_cur": 22}})
  6257. assert "'stg_cur': 22" in caplog.text
  6258. assert "layer_num" not in caplog.text.split("EOP-PROBE")[-1]
  6259. def test_captures_the_fields_bambuddy_does_not_parse(self, mqtt_client, caplog):
  6260. """The whole point: mc_stage / mc_action / print_real_action are read
  6261. by nothing else in the codebase, so only the probe can show them."""
  6262. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6263. mqtt_client._process_message({"print": {"layer_num": 100}})
  6264. mqtt_client._process_message(
  6265. {
  6266. "print": {
  6267. "mc_stage": 3,
  6268. "mc_action": 8,
  6269. "print_real_action": 2,
  6270. "print_gcode_action": 5,
  6271. "stg_cd": 1,
  6272. "home_flag": 2231371,
  6273. "spd_lvl": 0,
  6274. }
  6275. }
  6276. )
  6277. for field in ("mc_stage", "mc_action", "print_real_action", "print_gcode_action", "stg_cd", "spd_lvl"):
  6278. assert field in caplog.text
  6279. def test_closes_on_finish_and_does_not_reopen(self, mqtt_client, caplog):
  6280. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6281. mqtt_client._process_message({"print": {"layer_num": 100}})
  6282. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  6283. assert "EOP-PROBE 2 CLOSE" in caplog.text
  6284. assert mqtt_client._eop_probe_open is False
  6285. assert mqtt_client._eop_probe_armed is False
  6286. caplog.clear()
  6287. # Firmware re-sending FINISH, or a stale replay, must not restart it.
  6288. mqtt_client._process_message({"print": {"layer_num": 100, "mc_percent": 100}})
  6289. assert "EOP-PROBE" not in caplog.text
  6290. def test_closing_frame_is_self_contained_when_nothing_changed(self, mqtt_client, caplog):
  6291. """A FINISH frame that repeats values already seen still has to log
  6292. something — otherwise the window has no visible end."""
  6293. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6294. mqtt_client._process_message({"print": {"gcode_state": "RUNNING", "mc_percent": 100}})
  6295. caplog.clear()
  6296. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  6297. # Same value the probe already recorded on the opening frame.
  6298. mqtt_client._eop_probe_open = True
  6299. mqtt_client._eop_probe_armed = True
  6300. mqtt_client._eop_probe_last = {"gcode_state": "FINISH"}
  6301. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  6302. assert "CLOSE" in caplog.text
  6303. assert "'gcode_state': 'FINISH'" in caplog.text
  6304. def test_rearms_for_the_next_print(self, mqtt_client, caplog):
  6305. # A completion callback is what lets _update_state finish the print
  6306. # (and clear _was_running), which the new-print detection depends on.
  6307. mqtt_client.on_print_complete = lambda data: None
  6308. mqtt_client.state.gcode_file = "current.3mf"
  6309. mqtt_client._previous_gcode_state = "RUNNING"
  6310. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6311. mqtt_client._process_message({"print": {"layer_num": 100}})
  6312. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  6313. assert mqtt_client._eop_probe_armed is False
  6314. # New print: RUNNING again with a file, after the previous print
  6315. # completed. _update_state rearms the probe alongside the
  6316. # finish-photo one-shot.
  6317. mqtt_client._process_message(
  6318. {"print": {"gcode_state": "RUNNING", "gcode_file": "next.3mf", "subtask_name": "next"}}
  6319. )
  6320. assert mqtt_client._eop_probe_armed is True
  6321. caplog.clear()
  6322. mqtt_client.state.total_layers = 50
  6323. mqtt_client._process_message({"print": {"layer_num": 50}})
  6324. assert "EOP-PROBE open" in caplog.text
  6325. def test_frame_budget_caps_output_but_still_logs_the_close(self, mqtt_client, caplog):
  6326. """A long final layer holds the window open at ~1 frame/second; the
  6327. user still has to be able to upload the resulting log."""
  6328. from backend.app.services.bambu_mqtt import _END_OF_PRINT_PROBE_MAX_FRAMES
  6329. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6330. mqtt_client._process_message({"print": {"layer_num": 100}})
  6331. for i in range(_END_OF_PRINT_PROBE_MAX_FRAMES + 50):
  6332. mqtt_client._process_message({"print": {"mc_remaining_time": i}})
  6333. assert "frame budget" in caplog.text
  6334. caplog.clear()
  6335. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  6336. assert "CLOSE" in caplog.text
  6337. def test_opens_on_numeric_strings(self, mqtt_client, caplog):
  6338. """Firmware sends these as ints or as numeric strings depending on
  6339. model and field, so the window checks must coerce rather than compare
  6340. a str against an int and silently never open."""
  6341. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6342. mqtt_client._process_message({"print": {"layer_num": "100", "mc_percent": "99"}})
  6343. assert "EOP-PROBE open" in caplog.text
  6344. assert mqtt_client._eop_probe_open is True
  6345. def test_coercion_helper_falls_back_on_junk(self, mqtt_client):
  6346. """Unit-level, because feeding junk through _process_message would trip
  6347. the pre-existing parsers before ever reaching the probe. The guarantee
  6348. under test is only that the probe's own reads can't raise."""
  6349. assert mqtt_client._probe_number("100") == 100.0
  6350. assert mqtt_client._probe_number("not-a-number", 7) == 7
  6351. assert mqtt_client._probe_number(None) is None
  6352. assert mqtt_client._probe_number({"unexpected": "shape"}, 0) == 0
  6353. def test_probe_failure_cannot_break_ingest(self, mqtt_client, caplog, monkeypatch):
  6354. """Instrumentation must stay instrumentation: if the probe ever throws,
  6355. state parsing still has to complete."""
  6356. def boom(_data):
  6357. raise RuntimeError("probe exploded")
  6358. monkeypatch.setattr(mqtt_client, "_probe_end_of_print", boom)
  6359. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6360. mqtt_client._process_message({"print": {"gcode_state": "RUNNING", "layer_num": 100}})
  6361. assert mqtt_client.state.layer_num == 100
  6362. assert "EOP-PROBE failed" in caplog.text
  6363. def test_never_logs_the_access_code(self, mqtt_client, caplog):
  6364. with caplog.at_level(logging.DEBUG, logger=self.LOGGER):
  6365. mqtt_client._process_message({"print": {"layer_num": 100}})
  6366. mqtt_client._process_message({"print": {"gcode_state": "FINISH"}})
  6367. probe_lines = [line for line in caplog.text.splitlines() if "EOP-PROBE" in line]
  6368. assert probe_lines
  6369. assert not any("12345678" in line for line in probe_lines)
  6370. class TestAmsFilamentSettingRefusalLogging:
  6371. """A refused `ams_filament_setting` reaches the log at INFO (#2756).
  6372. The reporter configured a slot on an X1C six times. Every request returned
  6373. HTTP 200, every publish carried the complete `GFG99`/`GFSG99` pair, and
  6374. every #2582 read-back showed the previous profile still in place — with no
  6375. record anywhere of what the printer answered, because the response sat at
  6376. DEBUG and support bundles are collected at INFO.
  6377. Only a non-success is promoted. This command is not rare — every spool
  6378. assignment and every K-profile re-apply sends one — so logging each ack
  6379. would bury the one line worth reading.
  6380. """
  6381. @pytest.fixture
  6382. def mqtt_client(self):
  6383. from backend.app.services.bambu_mqtt import BambuMQTTClient
  6384. return BambuMQTTClient(
  6385. ip_address="192.168.1.100",
  6386. serial_number="TEST123",
  6387. access_code="12345678",
  6388. )
  6389. def _refusals(self, caplog):
  6390. return [line for line in caplog.text.splitlines() if "ams_filament_setting refused" in line]
  6391. def test_refusal_is_logged_at_info_with_result_and_reason(self, mqtt_client, caplog):
  6392. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  6393. mqtt_client._process_message(
  6394. {
  6395. "print": {
  6396. "command": "ams_filament_setting",
  6397. "result": "fail",
  6398. "reason": "invalid tray_id",
  6399. "ams_id": 0,
  6400. "tray_id": 1,
  6401. "sequence_id": "0",
  6402. }
  6403. }
  6404. )
  6405. refusals = self._refusals(caplog)
  6406. assert len(refusals) == 1
  6407. # The reason is the whole point of the promotion — a bare "fail" would
  6408. # not have told the reporter anything the read-back hadn't already.
  6409. assert "result=fail" in refusals[0]
  6410. assert "invalid tray_id" in refusals[0]
  6411. assert "ams_id=0" in refusals[0]
  6412. assert "tray_id=1" in refusals[0]
  6413. def test_success_stays_quiet(self, mqtt_client, caplog):
  6414. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  6415. mqtt_client._process_message(
  6416. {"print": {"command": "ams_filament_setting", "result": "success", "sequence_id": "0"}}
  6417. )
  6418. assert self._refusals(caplog) == []
  6419. def test_response_without_a_result_field_stays_quiet(self, mqtt_client, caplog):
  6420. """Firmware that omits `result` tells us nothing — don't invent a refusal."""
  6421. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  6422. mqtt_client._process_message({"print": {"command": "ams_filament_setting", "sequence_id": "0"}})
  6423. assert self._refusals(caplog) == []
  6424. def test_developer_mode_probe_failure_is_not_reported_as_a_refusal(self, mqtt_client, caplog):
  6425. """The probe sends this command to the external slot *expecting* a
  6426. refusal on P1 firmware — that is a reading, not a fault, and promoting
  6427. it would put an alarming line in every P1 bundle on every reconnect."""
  6428. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  6429. mqtt_client._dev_mode_probe_seq = "7"
  6430. mqtt_client._process_message(
  6431. {
  6432. "print": {
  6433. "command": "ams_filament_setting",
  6434. "result": "failed",
  6435. "reason": "mqtt message verify failed",
  6436. "sequence_id": "7",
  6437. }
  6438. }
  6439. )
  6440. assert self._refusals(caplog) == []
  6441. def test_user_command_is_not_mistaken_for_the_probe(self, mqtt_client, caplog):
  6442. """User-initiated publishes hardcode sequence_id "0", so a refusal is
  6443. still reported while a probe is outstanding under a different seq."""
  6444. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  6445. mqtt_client._dev_mode_probe_seq = "7"
  6446. mqtt_client._process_message(
  6447. {
  6448. "print": {
  6449. "command": "ams_filament_setting",
  6450. "result": "fail",
  6451. "reason": "",
  6452. "sequence_id": "0",
  6453. }
  6454. }
  6455. )
  6456. assert len(self._refusals(caplog)) == 1
  6457. def test_extrusion_cali_sel_is_untouched(self, mqtt_client, caplog):
  6458. """The sibling in the same branch keeps its DEBUG-only handling; this
  6459. change is scoped to the write #2756 is about."""
  6460. caplog.set_level(logging.INFO, logger="backend.app.services.bambu_mqtt")
  6461. mqtt_client._process_message({"print": {"command": "extrusion_cali_sel", "result": "fail", "sequence_id": "0"}})
  6462. assert self._refusals(caplog) == []
  6463. assert "extrusion_cali_sel" not in caplog.text