test_bambu_mqtt.py 260 KB

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