test_bambu_mqtt.py 250 KB

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