test_bambu_mqtt.py 284 KB

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