bambu_mqtt.py 465 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195
  1. """Bambu Lab MQTT communication service.
  2. IMPORTANT: Always use qos=1 for all MQTT publish calls!
  3. The printer ignores qos=0 messages when busy broadcasting status updates.
  4. Using qos=1 ensures the printer acknowledges and processes our commands immediately.
  5. This was discovered when K-profile requests with qos=0 took 20-30 seconds,
  6. but with qos=1 they respond instantly.
  7. """
  8. import asyncio
  9. import json
  10. import logging
  11. import os
  12. import ssl
  13. import threading
  14. import time
  15. from collections import deque
  16. from collections.abc import Callable
  17. from dataclasses import dataclass, field
  18. from datetime import datetime, timezone
  19. import paho.mqtt.client as mqtt
  20. from backend.app.services.hms_actions import HMSAction, get_actions_for_error_code
  21. from backend.app.services.hms_errors import alert_level_from_print_error, describe_fault
  22. from backend.app.utils.ams_drying import ACTIVE_DRY_STATUSES, DRY_COUNTDOWN_STALL_SECONDS
  23. from backend.app.utils.ams_humidity import ams_humidity_percent
  24. from backend.app.utils.paho_teardown import discard_queued_publishes, retire_paho_client
  25. from backend.app.utils.tray_ids import (
  26. AMS3H_UNIT_ID,
  27. RACK_SLOT_COUNT,
  28. AmsType,
  29. TrayLayout,
  30. ams_type_from_info,
  31. decode_wire_slot,
  32. external_tray_id,
  33. global_tray_id,
  34. is_ams_ht_id,
  35. is_external_tray,
  36. is_rack_ams,
  37. legacy_tray_index,
  38. mapped_trays_with_slot,
  39. tray_flag_bit,
  40. unit_ams_type,
  41. unit_label,
  42. )
  43. logger = logging.getLogger(__name__)
  44. # How long a manual load's tray target stays a hint for an H2D's tray_now: long
  45. # enough for a real load to report, short enough that a refused one cannot
  46. # relabel a later print's load of the same slot number (FW-C7).
  47. PENDING_TRAY_TARGET_TTL = 120.0
  48. # AMS module name prefixes used in get_version responses.
  49. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  50. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  51. # "ams_f1/<id>" – AMS Lite (A1, A1 Mini; the A2L reports id 16, stored as 6)
  52. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  53. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  54. # "n10a" – AMS 3H (H3C), no suffix: read as "n10a/<its unit id>"
  55. _AMS_MODULE_PREFIXES = ("ams/", "ams_f1/", "n3f/", "n3s/", "n10a/")
  56. # gcode_state values that mean the printer is not idle and must not be handed a
  57. # new start-print (#2598). The firmware rejects a project_file while busy with
  58. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  59. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  60. # are valid start targets and are deliberately excluded. Mirrors
  61. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  62. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  63. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  64. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  65. # ended the cycle on schedule or aborted it. More than this many minutes still on
  66. # the clock means it was cut short, and the firmware's own reason codes are worth
  67. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  68. # left), and the log said only "drying complete", so the report carried no
  69. # evidence of why. The margin absorbs a stale last observation between AMS
  70. # pushes; it is not a judgement about how short "short" is.
  71. _EARLY_DRY_END_MINUTES = 5
  72. # CONNACK reason codes that mean the printer actively refused our credentials,
  73. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  74. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  75. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  76. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  77. # code (or, on some firmware, the serial used as the username) is wrong.
  78. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  79. # Short, stable slugs recorded on the client and surfaced to the connection
  80. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  81. # frontend picks a localized message key off these.
  82. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  83. CONNECT_ERROR_REFUSED = "refused"
  84. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  85. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  86. OrcaSlicer reads bit 18 of the hex string via
  87. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  88. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  89. that doesn't yield a clean integer so downstream consumers preserve today's
  90. behaviour rather than treating "absent" as "OFF".
  91. """
  92. if not isinstance(cfg_raw, str) or not cfg_raw:
  93. return None
  94. try:
  95. return bool((int(cfg_raw, 16) >> 18) & 1)
  96. except ValueError:
  97. return None
  98. def parse_ams_filament_backup_from_home_flag(home_flag: object) -> bool | None:
  99. """Extract AMS Filament Backup state from a push_status ``print.home_flag`` value.
  100. Bambu Studio reads bit 10 for every family (DeviceManager.cpp
  101. ``parse_home_flag``: ``SetAutoRefillEnabled((flag >> 10) & 0x1)``). It's
  102. the only source on the P1S, P1P, A1 and A1 Mini, which never send ``cfg``
  103. (#3259). On every printer that sends both, the two bits agree in all
  104. captured snapshots, ON and OFF alike. Returns ``None`` for anything that
  105. isn't an integer.
  106. """
  107. if isinstance(home_flag, bool) or not isinstance(home_flag, int):
  108. return None
  109. # Negative values are the 32-bit flag read as signed; bit 10 is the same.
  110. return bool((home_flag >> 10) & 1)
  111. def is_printer_status_frame(print_data: dict) -> bool:
  112. """True when a ``print`` payload is the printer reporting its own state.
  113. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  114. `project_file` ack carries whatever Bambuddy put on the wire — including
  115. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  116. telemetry means reading our own request back as the printer's state
  117. (#3040). Only `push_status` (and the odd firmware that omits `command`
  118. entirely on a status frame) describes the printer.
  119. """
  120. command = print_data.get("command")
  121. return command is None or command == "push_status"
  122. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  123. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  124. # firmware is internally inconsistent about it:
  125. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  126. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  127. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  128. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  129. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  130. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  131. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  132. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  133. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  134. A2L_LITE_PHYSICAL_AMS_ID = 16
  135. A2L_LITE_NORMALIZED_AMS_ID = 6
  136. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  137. def normalize_am_unit_id(ams_id: int) -> int:
  138. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  139. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  140. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  141. through untouched.
  142. """
  143. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  144. def wire_tray_color(tray_color: str | None) -> str:
  145. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  146. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  147. as a zero, and does it silently: the command response echoes the value you
  148. sent and reports ``result: "success"``, so only the next AMS push shows what
  149. was really stored. Measured on the reporter's machine (#2987), where the
  150. spool's own ``rgba`` is stored lowercase and went out verbatim:
  151. sent 09ff00ff -> AMS reports 09000000
  152. sent ff5100ff -> AMS reports 00510000
  153. sent 090000FF -> AMS reports 090000FF
  154. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  155. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  156. longer matches the spool that asked for it and the assignment is deleted
  157. seconds after being made -- and re-assigning through the slot modal writes
  158. the mangled colour back, because the modal seeds itself from the tray.
  159. Applied here, at the one place the command is built, rather than in each of
  160. the four callers: a caller that forgets is exactly how this arrived.
  161. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  162. blank stays blank, which is how a slot is cleared.
  163. """
  164. return (tray_color or "").strip().lstrip("#").upper()
  165. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  166. """Translate a normalised A2L slot back to the physical wire form.
  167. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  168. (normalised id 6), else ``None`` for every other unit.
  169. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  170. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  171. confirmed by capture: the physical **global** tray value the extrusion_cali
  172. commands put in `tray_id` — we extrapolate it as 16*4+slot = 64-67 to stay
  173. consistent with the physical unit id. BambuStudio's source sends 24+slot
  174. there instead (``GetTrayIndexMap``); a BambuStudio->A2L capture of a cali
  175. command would settle it, and it lives only here. Load's `target` is not this
  176. value: see ``change_filament_wire_ids``.
  177. """
  178. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  179. return None
  180. local_slot = tray_id % 4
  181. return (
  182. A2L_LITE_PHYSICAL_AMS_ID,
  183. local_slot,
  184. legacy_tray_index(A2L_LITE_PHYSICAL_AMS_ID, local_slot),
  185. )
  186. def change_filament_wire_ids(tray_id: int, layout: TrayLayout | None = None) -> tuple[int, int, int]:
  187. """``(ams_id, slot_id, target)`` of ``ams_change_filament`` for an AMS tray.
  188. As BambuStudio's ``command_ams_change_filament`` builds them: a regular AMS
  189. is addressed by unit and local slot with the global tray as target; a unit
  190. id of 16 or more (the A2L AMS-Lite's physical 16, an AMS-HT's 128-135) has
  191. the unit id itself as target. An AMS-HT holds one tray, so its global tray
  192. id is its unit id and its slot is 0.
  193. """
  194. if is_ams_ht_id(tray_id):
  195. return tray_id, 0, tray_id
  196. ams_id, slot_id = (layout or TrayLayout()).slot_key(tray_id)
  197. if (a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  198. return a2l[0], a2l[1], a2l[0]
  199. return ams_id, slot_id, tray_id
  200. # The H3C's AMS 3H is one unit (32, AMS type 6) with nine slots, numbered 28 + k
  201. # (utils.tray_ids). Its tray_now / tray_tar / tray_pre are the raw slot 0-8;
  202. # print.mapping and the snow fields encode a slot as (32 << 8) | k. Commands
  203. # address it as {ams_id: 32, slot_id: k}.
  204. AMS3H_MODULE_NAME = "n10a" # its get_version module (no "/<unit>" suffix)
  205. def _mqtt_int(value: object) -> int | None:
  206. """An MQTT id / number field as an int (they arrive as int or numeric str), else None."""
  207. if isinstance(value, bool) or not isinstance(value, (int, str)):
  208. return None
  209. try:
  210. return int(value)
  211. except ValueError:
  212. return None
  213. # AMS 3H drying (Bambu Studio 02.09, AMSDryControl.cpp): the unit reports
  214. # `zone_info[]` and only a zone with exactly two slots can dry; the others are
  215. # ambient readings. A drying start carries the filament's softening temperature
  216. # as `cooling_temp` (the preset's filament_dev_drying_softening_temperature).
  217. AMS3H_DRY_COOLING_TEMP = {"PLA": 65, "PETG": 75, "ABS": 95, "ASA": 95, "TPU": 70, "PA": 150, "PC": 120}
  218. AMS3H_DRY_COOLING_TEMP_DEFAULT = 50
  219. def ams3h_drying_zone(zone_info: object) -> dict | None:
  220. """The zone of an AMS 3H's `zone_info` that can dry: the first holding exactly two slots."""
  221. if not isinstance(zone_info, list):
  222. return None
  223. for zone in zone_info:
  224. if isinstance(zone, dict) and isinstance(zone.get("zone_slots"), list) and len(zone["zone_slots"]) == 2:
  225. return zone
  226. return None
  227. def ams3h_drying_cooling_temp(filament: str) -> int:
  228. """`cooling_temp` for an AMS 3H drying start: the filament's softening temperature."""
  229. base = (filament or "").upper().split("-")[0].split(" ")[0]
  230. return AMS3H_DRY_COOLING_TEMP.get(base, AMS3H_DRY_COOLING_TEMP_DEFAULT)
  231. def _ams3h_unit_drying_fields(unit: dict) -> dict:
  232. """An AMS 3H's drying state, which lives on its drying zone, lifted onto the unit."""
  233. zone = ams3h_drying_zone(unit.get("zone_info"))
  234. if zone is None:
  235. return {}
  236. fields: dict = {"dry_zone_id": zone.get("zone_id", 0), "dry_zone_slots": list(zone.get("zone_slots") or [])}
  237. for key in ("dry_time", "dry_setting", "dry_sf_reason"):
  238. if key in zone:
  239. fields[key] = zone[key]
  240. if "info" not in unit and "info" in zone:
  241. fields["info"] = zone["info"]
  242. if "humidity_raw" in zone:
  243. fields["dry_zone_humidity_raw"] = zone["humidity_raw"]
  244. if "temp" in zone:
  245. fields["dry_zone_temp"] = zone["temp"]
  246. return fields
  247. def _ams3h_unit_env_fields(unit: dict) -> dict:
  248. """An AMS 3H's humidity and temperature (the unit has none) from its first non-drying zone, as Studio shows it."""
  249. zones = unit.get("zone_info")
  250. if not isinstance(zones, list):
  251. return {}
  252. dry_zone = ams3h_drying_zone(zones)
  253. ambient = next((z for z in zones if isinstance(z, dict) and z is not dry_zone), None)
  254. if ambient is None:
  255. return {}
  256. return {key: ambient[key] for key in ("humidity_raw", "temp") if key in ambient and key not in unit}
  257. def apply_rack_ams_zone_fields(ams_list: object, known_types: dict[int, AmsType] | None = None) -> None:
  258. """Lift a rack AMS's per-zone readings and drying state onto the unit, in place (type from `info`, else ``known_types``)."""
  259. if not isinstance(ams_list, list):
  260. return
  261. for unit in ams_list:
  262. if not isinstance(unit, dict) or not isinstance(unit.get("zone_info"), list):
  263. continue
  264. uid = _mqtt_int(unit.get("id"))
  265. if uid is None:
  266. continue
  267. kind = ams_type_from_info(unit.get("info"))
  268. if kind is None:
  269. kind = (known_types or {}).get(uid, unit_ams_type(uid))
  270. if not is_rack_ams(kind):
  271. continue
  272. unit.update({**_ams3h_unit_env_fields(unit), **_ams3h_unit_drying_fields(unit)})
  273. def resolve_external_spools_in_mapping(
  274. ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool, layout: TrayLayout | None = None
  275. ) -> object:
  276. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  277. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  278. dispatch both write an external spool there as -1 -- the same value as a
  279. slot that isn't fed at all -- and carry the real target only in
  280. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  281. list alone turns "printed from the external spool" into "unmapped", and
  282. usage then lands on whatever tray the fallback guesses.
  283. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  284. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  285. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  286. printers, which have one external spool that the wire always calls 255.
  287. ``{255, 255}`` is the unmapped marker and stays -1.
  288. An A2L AMS-Lite tray is the local slot 0-3 in the flat list and
  289. ``{ams_id: 16, slot_id: n}`` in ``ams_mapping2``; it becomes its normalised
  290. global tray 24+n. Kept local, it read as a regular AMS tray, so usage was
  291. charged to the wrong spool. A rack AMS slot (``{ams_id: 32, slot_id: k}``)
  292. becomes its global tray 28+k, and on a rack printer each external input
  293. 247-255 keeps its own id. Every other entry is left exactly as captured.
  294. Without a usable ``ams_mapping2`` the input is returned unchanged.
  295. """
  296. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  297. return ams_mapping
  298. if len(ams_mapping2) != len(ams_mapping):
  299. return ams_mapping
  300. resolved = list(ams_mapping)
  301. layout = layout or TrayLayout()
  302. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  303. if not isinstance(detail, dict):
  304. continue
  305. ams_id = detail.get("ams_id")
  306. slot_id = detail.get("slot_id")
  307. if ams_id == A2L_LITE_PHYSICAL_AMS_ID and slot_id in (0, 1, 2, 3):
  308. resolved[i] = A2L_LITE_GLOBAL_BASE + slot_id
  309. continue
  310. if (
  311. isinstance(ams_id, int)
  312. and isinstance(slot_id, int)
  313. and not is_external_tray(ams_id, layout.rack)
  314. and is_rack_ams(layout.ams_type(ams_id))
  315. and 0 <= slot_id < RACK_SLOT_COUNT
  316. ):
  317. resolved[i] = layout.global_tray_id(ams_id, slot_id)
  318. continue
  319. if flat != -1 or not is_external_tray(ams_id, layout.rack) or slot_id == 255:
  320. continue
  321. resolved[i] = ams_id if is_dual_nozzle or layout.rack else 254
  322. return resolved
  323. def unit_reported_absent(ams_id, ams_list: list, ams_exist_bits) -> bool:
  324. """Whether a push that doesn't list AMS unit ``ams_id`` says it is unplugged.
  325. ``ams_exist_bits`` (hex) has bit n set for AMS unit n, measured on an X1C
  326. (unit 1 -> "2", none -> "0") and an H2C (units 0, 1, 2 and HT 128 -> "17").
  327. So an AMS unit 0-3 whose bit is clear is gone. An empty unit list with no
  328. bits set means no unit at all, which is what the X1C sends with its AMS
  329. unplugged. Anything else is kept, as the merge always did: a partial push
  330. lists only some units, and the bits of an AMS HT or AMS Lite next to other
  331. units are not measured well enough to read.
  332. """
  333. if ams_exist_bits is None:
  334. return False
  335. try:
  336. bits = int(ams_exist_bits, 16) if isinstance(ams_exist_bits, str) else int(ams_exist_bits)
  337. unit = int(ams_id)
  338. except (TypeError, ValueError):
  339. return False
  340. if bits == 0 and not ams_list:
  341. return True
  342. return 0 <= unit <= 3 and not bits >> unit & 1
  343. def apply_tray_exist_bits(
  344. units: list,
  345. tray_exist_bits_str: str | int | None,
  346. *,
  347. power_on_flag: bool = True,
  348. log_label: str | None = None,
  349. annotate_exists: bool = False,
  350. ) -> int:
  351. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  352. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  353. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  354. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  355. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  356. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  357. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  358. instead of guessing from payload shape (#1322, #147).
  359. Two callers share this helper to keep their views consistent:
  360. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  361. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  362. facing push_status (#1726 — without this the VP would forward stale
  363. per-tray fields for empty slots, and BambuStudio's Sync would render
  364. phantom loaded slots).
  365. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  366. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  367. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  368. so spool removal is detected without requiring a manual reconnect.
  369. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  370. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  371. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  372. authoritative empty signal for the HT — the only working clear path, since
  373. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  374. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  375. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  376. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  377. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  378. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  379. the raw physical id 16 get the same bit base as callers holding the
  380. normalised 6 (#2697).
  381. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  382. way). Ints are tolerated for defensive symmetry but typically not seen
  383. on the wire. ``None`` / empty / unparseable → no-op.
  384. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  385. every processed slot. This is firmware's authoritative "spool physically
  386. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  387. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  388. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  389. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  390. leaves it False so the ``exists`` key never reaches the slicer wire format.
  391. Mutates ``units`` in place. Returns the number of slots cleared.
  392. """
  393. if not tray_exist_bits_str:
  394. return 0
  395. try:
  396. if isinstance(tray_exist_bits_str, int):
  397. tray_exist_bits = tray_exist_bits_str
  398. else:
  399. tray_exist_bits = int(tray_exist_bits_str, 16)
  400. except (ValueError, TypeError):
  401. return 0
  402. if tray_exist_bits == 0 and not power_on_flag:
  403. return 0
  404. if not isinstance(units, list):
  405. return 0
  406. cleared = 0
  407. for ams_unit in units:
  408. if not isinstance(ams_unit, dict):
  409. continue
  410. ams_id_raw = ams_unit.get("id")
  411. if ams_id_raw is None:
  412. continue
  413. try:
  414. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  415. except (ValueError, TypeError):
  416. continue
  417. if not isinstance(ams_id, int):
  418. continue
  419. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  420. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  421. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  422. # the physical 16. Both mean bit base 24, so fold them together here
  423. # rather than relying on every caller to normalise first — reading 16 as
  424. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  425. ams_id = normalize_am_unit_id(ams_id)
  426. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  427. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  428. # A rack AMS (unit 32): its global tray id 28 + slot.
  429. # Anything outside those has no known bit layout — don't guess it.
  430. kind = unit_ams_type(ams_id, ams_unit.get("info"))
  431. if tray_flag_bit(ams_id, 0, kind) is None:
  432. continue
  433. for tray in ams_unit.get("tray", []):
  434. if not isinstance(tray, dict):
  435. continue
  436. tray_id_raw = tray.get("id")
  437. if tray_id_raw is None:
  438. continue
  439. try:
  440. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  441. except (ValueError, TypeError):
  442. continue
  443. if not isinstance(tray_id, int):
  444. continue
  445. global_bit = tray_flag_bit(ams_id, tray_id, kind)
  446. if global_bit is None or global_bit < 0:
  447. continue
  448. slot_exists = (tray_exist_bits >> global_bit) & 1
  449. if annotate_exists:
  450. tray["exists"] = bool(slot_exists)
  451. if slot_exists:
  452. continue
  453. tray["state"] = 9
  454. if tray.get("tray_type"):
  455. if log_label:
  456. logger.debug(
  457. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  458. f"(tray_exist_bits bit {global_bit} = 0)"
  459. )
  460. tray["tray_type"] = ""
  461. tray["tray_sub_brands"] = ""
  462. tray["tray_color"] = ""
  463. tray["tray_id_name"] = ""
  464. tray["tag_uid"] = "0000000000000000"
  465. tray["tray_uuid"] = "00000000000000000000000000000000"
  466. tray["tray_info_idx"] = ""
  467. tray["remain"] = 0
  468. cleared += 1
  469. return cleared
  470. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  471. #
  472. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  473. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  474. # rack position is never mistakable for the nozzle on the other carriage.
  475. #
  476. # Extruder indices are a different namespace that happens to overlap these
  477. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  478. # Nothing below may pass a value from one namespace to the other untranslated;
  479. # doing exactly that is what #2800 was.
  480. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  481. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  482. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  483. #
  484. # Briefly changed to the plate's own slot count on the strength of a single
  485. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  486. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  487. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  488. # a calibration job, so the length varies with whatever Studio is doing rather
  489. # than with the filament count -- which makes it the wrong thing to derive.
  490. _RACK_WIRE_SLOTS = 32
  491. # The two carriages, as extruder indices in the form the queue stores (already
  492. # translated through the file's physical_extruder_map).
  493. #
  494. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  495. #
  496. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  497. # extruder 1, AMS 1 and 2 feed extruder 0;
  498. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  499. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  500. # and that print completed. So extruder 1 is the fixed hotend and extruder
  501. # 0 is the rack;
  502. # - our own constants were internally inconsistent about it: physical nozzle
  503. # id N sits on extruder N (see the L/R split in PrintersPage), and
  504. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  505. # extruder index of 0.
  506. #
  507. # These were the other way round until then, which is what dispatched a plate
  508. # to the carriage that had not been levelled and printed its first layer in
  509. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  510. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  511. # which *wire* worked, and the extruder indices were only inferred from it by
  512. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  513. # wire result stands; the inference from it did not.
  514. _FIXED_EXTRUDER_ID = 1
  515. _RACK_EXTRUDER_ID = 0
  516. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  517. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  518. # outright, which would not start the job at all. Native BambuStudio captures
  519. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  520. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  521. _FIXED_NOZZLE_ID = 1
  522. def resolve_rack_nozzle_mapping(
  523. slot_extruders: list[int],
  524. rack_nozzle_id: int | None,
  525. ) -> list[int] | None:
  526. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  527. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  528. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  529. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  530. reports as live.
  531. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  532. when the mapping cannot be resolved with confidence -- in which case the
  533. caller omits the field entirely and the firmware falls back to its own
  534. nozzle pick, exactly as it did before this translation existed. Omitting
  535. is deliberately the failure mode: a *wrong* physical ID makes the printer
  536. level with one nozzle and print with another several millimetres off the
  537. bed, which is far worse than letting the firmware choose.
  538. Returns None specifically when:
  539. - a slot needs the rack but the printer has not reported a live rack
  540. position (mid-swap, or a stale connection);
  541. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  542. for a plate sliced for the fixed hotend only (#2800 capture), so this
  543. matches it rather than naming a nozzle it does not have to name;
  544. - a slot names a carriage that is neither of the two an H2C has, which
  545. means the file was mapped for a machine this translation does not model;
  546. - the plate needs more slots than the wire format carries;
  547. - the input is not a list of whole numbers.
  548. Total by construction: it raises nothing, because the only caller is
  549. building an MQTT print command with no exception handler above it and the
  550. queue item has already been committed as `printing` by then. An
  551. unparseable input has to degrade to "let the firmware pick", not to a job
  552. wedged in a state no print will ever leave.
  553. """
  554. if not isinstance(slot_extruders, list) or not slot_extruders:
  555. return None
  556. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  557. return None
  558. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  559. return None
  560. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  561. return None
  562. # Normalise first so the checks below, and the values that reach the wire,
  563. # are known ints. bool is an int subclass and would otherwise serialise as
  564. # a JSON `true`; None means "slot not printed" and is folded into -1.
  565. normalised: list[int] = []
  566. for extruder in slot_extruders:
  567. if extruder is None:
  568. normalised.append(-1)
  569. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  570. normalised.append(extruder)
  571. else:
  572. return None
  573. if _RACK_EXTRUDER_ID not in normalised:
  574. return None
  575. wire = [-1] * _RACK_WIRE_SLOTS
  576. for index, extruder in enumerate(normalised):
  577. if extruder < 0:
  578. continue
  579. if extruder == _RACK_EXTRUDER_ID:
  580. wire[index] = rack_nozzle_id
  581. elif extruder == _FIXED_EXTRUDER_ID:
  582. wire[index] = _FIXED_NOZZLE_ID
  583. else:
  584. # An H2C has these two carriages and no others. A third index is a
  585. # file mapped for something else, and forwarding it raw would name
  586. # a physical nozzle by an index that does not identify one.
  587. return None
  588. return wire
  589. # A rack position as the operator counts it (and as the printer card and
  590. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  591. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  592. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  593. _RACK_POSITION_BASE = 15
  594. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  595. def rack_position_to_nozzle_id(position: int) -> int | None:
  596. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  597. if not isinstance(position, int) or isinstance(position, bool):
  598. return None
  599. if position not in RACK_POSITIONS:
  600. return None
  601. return _RACK_POSITION_BASE + position
  602. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  603. """Whether a live rack slot can print a group wanting this nozzle.
  604. Mirrors the filter BambuStudio applies in its own picker: the position has
  605. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  606. and flow type. A mismatch here is not cosmetic -- it is the printer being
  607. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  608. """
  609. if not isinstance(slot, dict):
  610. return False
  611. slot_diameter = str(slot.get("diameter") or "").strip()
  612. slot_type = str(slot.get("type") or "").strip()
  613. if not slot_diameter and not slot_type:
  614. return False # empty position
  615. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  616. # the printer does not.
  617. try:
  618. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  619. return False
  620. except (TypeError, ValueError):
  621. return False
  622. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  623. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  624. # printer that omits the code is not thereby ruled ineligible.
  625. wanted = volume_type.strip().lower()
  626. if wanted and slot_type:
  627. is_high_flow = slot_type.upper().startswith("HH")
  628. if wanted.startswith("high flow") != is_high_flow:
  629. return False
  630. return True
  631. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  632. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  633. _RACK_CARRIAGE_NOZZLE_ID = 0
  634. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  635. """Live rack contents keyed by 1-based position, mounted nozzle included.
  636. The firmware omits a rack id entirely while that nozzle is picked up onto
  637. the carriage (#943) -- it does not send an empty placeholder. Taking the
  638. omission at face value would rule the nozzle ineligible for the very print
  639. that wants it, and it is the single most likely position to be picked,
  640. because it is the one the last print left mounted.
  641. The absent id is recoverable only when exactly one is missing: rack ids are
  642. fixed at 16..21, so a single gap alongside a loaded carriage is that
  643. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  644. with four nozzles in six positions looks the same -- so those stay absent
  645. and the caller treats them as empty.
  646. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  647. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  648. """
  649. by_position: dict[int, dict] = {}
  650. carriage: dict | None = None
  651. for slot in rack_slots or []:
  652. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  653. continue
  654. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  655. carriage = slot
  656. continue
  657. position = slot["id"] - _RACK_POSITION_BASE
  658. if position in RACK_POSITIONS:
  659. by_position[position] = slot
  660. missing = [position for position in RACK_POSITIONS if position not in by_position]
  661. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  662. by_position[missing[0]] = carriage
  663. return by_position
  664. def resolve_rack_plan_mapping(
  665. slot_groups: list[int],
  666. groups: dict[int, dict],
  667. choice: dict[int, int],
  668. rack_slots: list[dict],
  669. ) -> tuple[list[int] | None, str | None]:
  670. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  671. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  672. That one can only name the single live rack position, so a plate wanting a
  673. different hotend per group is unresolvable to it. Here each group carries
  674. its own position, which is the operator's choice (#1784) -- the 3MF states
  675. it nowhere, proven by dispatching one plate twice with different picks and
  676. diffing the two files down to float noise.
  677. ``choice`` may be partial or empty; groups it does not name are assigned
  678. from the live rack, preferring a position already loaded with the group's
  679. own filament colour and otherwise taking the lowest eligible one.
  680. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  681. is a sentence naming what could not be satisfied. The caller decides what
  682. to do with a failure, and the two cases differ: a stale *explicit* pick
  683. should stop the print, while a failed auto-assignment should degrade to
  684. letting the firmware choose, exactly as before this existed.
  685. """
  686. if not isinstance(slot_groups, list) or not slot_groups:
  687. return None, "the plate lists no filament slots"
  688. if len(slot_groups) > _RACK_WIRE_SLOTS:
  689. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  690. by_position = _rack_by_position(rack_slots)
  691. # Assign every rack-bound group a position before building the wire, so a
  692. # group can never be handed one an earlier group already took. Explicit
  693. # picks are placed first: an auto-assignment must yield to them rather than
  694. # claim a position the operator asked for.
  695. assigned: dict[int, int] = {}
  696. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  697. for group_id in rack_group_ids:
  698. position = choice.get(group_id)
  699. if position is None:
  700. continue
  701. group = groups[group_id]
  702. if rack_position_to_nozzle_id(position) is None:
  703. return None, f"rack position {position} does not exist"
  704. if position in assigned.values():
  705. return None, f"rack position {position} is picked for more than one filament group"
  706. slot = by_position.get(position)
  707. if slot is None:
  708. return None, f"the printer reports nothing at rack position {position}"
  709. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  710. return None, (
  711. f"rack position {position} holds a "
  712. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  713. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  714. )
  715. assigned[group_id] = position
  716. for group_id in rack_group_ids:
  717. if group_id in assigned:
  718. continue
  719. group = groups[group_id]
  720. eligible = [
  721. position
  722. for position in RACK_POSITIONS
  723. if position not in assigned.values()
  724. and position in by_position
  725. and _rack_slot_is_eligible(
  726. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  727. )
  728. ]
  729. if not eligible:
  730. return None, (
  731. f"no free rack position holds a {group.get('nozzle_diameter')} "
  732. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  733. )
  734. # Prefer a position already carrying this group's colour: picking it
  735. # means the operator does not have to move filament to make the print
  736. # match what they asked for.
  737. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  738. assigned[group_id] = next(
  739. (
  740. position
  741. for position in eligible
  742. if wanted_colour
  743. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  744. == wanted_colour
  745. ),
  746. eligible[0],
  747. )
  748. wire = [-1] * _RACK_WIRE_SLOTS
  749. for index, group_id in enumerate(slot_groups):
  750. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  751. continue # slot this plate does not print
  752. group = groups.get(group_id)
  753. if group is None:
  754. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  755. if not group.get("on_rack"):
  756. wire[index] = _FIXED_NOZZLE_ID
  757. continue
  758. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  759. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  760. return None, f"filament group {group_id} resolved to no rack position"
  761. wire[index] = nozzle_id
  762. if all(value == -1 for value in wire):
  763. return None, "the plate assigns no filament to a nozzle"
  764. return wire, None
  765. @dataclass(frozen=True)
  766. class DryingCycleEnd:
  767. """What Bambuddy saw of one AMS drying cycle, reported when it ends (#2863).
  768. ``peak_minutes`` is the highest ``dry_time`` observed during the cycle and
  769. ``remaining_minutes`` the last one before the drop to 0. ``start_seen`` says
  770. whether the countdown was watched from its first minute; when it was not
  771. (Bambuddy started mid-cycle) the peak is only a lower bound on the length.
  772. ``target_temp`` / ``target_hours`` are known only for cycles Bambuddy itself
  773. started, because the printer never echoes them.
  774. """
  775. ams_id: int
  776. remaining_minutes: int
  777. peak_minutes: int
  778. start_seen: bool
  779. target_temp: int | None = None
  780. target_hours: int | None = None
  781. @dataclass
  782. class MQTTLogEntry:
  783. """Log entry for MQTT message debugging."""
  784. timestamp: str
  785. topic: str
  786. direction: str # "in" or "out"
  787. payload: dict
  788. @dataclass
  789. class HMSError:
  790. """Health Management System error from printer."""
  791. code: str
  792. attr: int # Attribute value for constructing wiki URL
  793. module: int
  794. # Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  795. # 3 notification, 0 invalid. From `code >> 16` for `hms[]` faults, and from
  796. # the error's first hex digit for `print_error` (#2728).
  797. severity: int
  798. # The bundled catalogue's sentence for this fault, resolved once here so
  799. # every surface that reports it — the status response, the WebSocket
  800. # broadcast, the completion payload, notifications — says the same thing.
  801. # None when Bambu publishes no text for the code; see `describe_fault`.
  802. # Replaces a `message` field that was never set or read anywhere.
  803. description: str | None = None
  804. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  805. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  806. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  807. # HMSError without explicitly passing actions can't silently land None on the schema
  808. # boundary and raise ValidationError at routes/printers.py response time.
  809. actions: list[str] = field(default_factory=list)
  810. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  811. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  812. job_id: str | None = None
  813. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  814. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  815. # 32-bit `print_error` path. The frontend echoes this back to
  816. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  817. # used to send caused the firmware to silently reject HMS commands on H2C
  818. # (#1830) and on `hms[]`-sourced faults generally.
  819. full_code: str = ""
  820. def completion_payload(self) -> dict:
  821. """This error as a print-complete payload carries it, for the failure reason."""
  822. return {
  823. "code": self.code,
  824. "attr": self.attr,
  825. "module": self.module,
  826. "severity": self.severity,
  827. # Lets the queue's failure reason label an `hms[]` fault
  828. # with its full code rather than a lossy short one (#2728).
  829. "full_code": self.full_code,
  830. # Carried so the queue's failure reason quotes the same
  831. # sentence the status response and the broadcast do,
  832. # rather than resolving the code a fourth time (#2926).
  833. "description": self.description,
  834. }
  835. def _is_print_error_entry(error: HMSError) -> bool:
  836. """Whether this entry came from the 32-bit `print_error` field, whose
  837. full code has 8 hex digits; an `hms[]` entry's has 16."""
  838. return len(error.full_code) == 8
  839. def _hms_short_code(error: HMSError) -> str:
  840. """The MMMM_EEEE short code of an entry from either source."""
  841. module = (error.attr >> 16) & 0xFFFF
  842. # The low half only: an hms[] code carries its alert level above it
  843. # (0x18061 for 0500_8061), and read whole it never matched, listing the
  844. # fault twice (M-U9).
  845. number = (int(error.code.replace("0x", ""), 16) & 0xFFFF) if error.code else 0
  846. return f"{module:04X}_{number:04X}"
  847. def _hms_short_codes(errors: list) -> set[str]:
  848. return {_hms_short_code(e) for e in errors}
  849. # HMS short codes the firmware emits during normal user-cancel sequences.
  850. # These aren't faults — they're status echoes that confirm the cancel happened.
  851. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  852. # so they don't drive the printer card's "X problem" badge, the red pip, or
  853. # any other consumer that treats hms_errors as the active-fault list.
  854. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  855. {
  856. "0300_400C", # "The task was canceled."
  857. "0500_400E", # "Printing was cancelled."
  858. }
  859. )
  860. # "MQTT command verification failed" — the printer's authorization/authentication
  861. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  862. # command it could not verify. Queries (get_version, extrusion_cali_get,
  863. # pushall) still answer, so the connection looks perfectly healthy while
  864. # project_file, gcode_line and ams_change_filament are all silently dropped —
  865. # which is exactly how it presents: uploads succeed, the printer echoes our
  866. # subtask_id, then sits at IDLE forever (#2732).
  867. #
  868. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  869. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  870. # "0500_0007", which matches nothing in any catalog.
  871. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  872. @dataclass
  873. class KProfile:
  874. """Pressure advance (K) calibration profile from printer."""
  875. slot_id: int
  876. extruder_id: int
  877. nozzle_id: str
  878. nozzle_diameter: str
  879. filament_id: str
  880. name: str
  881. k_value: str
  882. n_coef: str = "0.000000"
  883. ams_id: int = 0
  884. tray_id: int = -1
  885. setting_id: str | None = None
  886. @dataclass
  887. class NozzleInfo:
  888. """Nozzle hardware configuration."""
  889. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  890. nozzle_diameter: str = "" # e.g., "0.4"
  891. # What await_cali_ack reports when the printer did not answer a K-profile write
  892. # in time. Not a refusal: firmware that predates the ack never answers.
  893. CALI_ACK_UNCONFIRMED = "no acknowledgement from printer"
  894. class KProfileReadError(Exception):
  895. """The printer's K-profile table could not be read: not connected, or no
  896. answer to any attempt. Not an empty table, which is a printer without
  897. profiles for that nozzle (#3404)."""
  898. # Time the printer has to list a skipped object in s_obj before the skip is
  899. # logged as not confirmed.
  900. SKIP_CONFIRM_TIMEOUT_S = 60.0
  901. # Answers to K-profile commands: they echo the command's own fields (the nozzle
  902. # diameter among them), never the printer's status.
  903. _KPROFILE_COMMAND_ANSWERS = frozenset(
  904. {"extrusion_cali_get", "extrusion_cali_set", "extrusion_cali_del", "extrusion_cali_sel"}
  905. )
  906. @dataclass
  907. class FilaSwitchState:
  908. """Filament Track Switch (FTS) accessory state.
  909. The FTS is an external accessory that mediates filament routing between an
  910. AMS and the printer's extruders. When installed, the AMS no longer has a
  911. fixed extruder assignment — any slot can be routed to any extruder via the
  912. track switch. Detected from print.device.fila_switch in MQTT.
  913. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  914. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  915. stable, operator-visible relationship — it is set on the printer's "Manual
  916. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  917. Field semantics below are taken from BambuStudio's own parser
  918. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  919. """
  920. installed: bool = False
  921. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  922. # the arrays are ordered B-then-A, which is the opposite of how they read.
  923. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  924. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  925. in_slots: list[int] = field(default_factory=list)
  926. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  927. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  928. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  929. # inlet is currently paired with which outlet is not reported at all.
  930. out_extruders: list[int] = field(default_factory=list)
  931. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  932. info: int = 0 # bit 0 = inlet has filament
  933. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  934. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  935. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  936. one of A/B.
  937. """
  938. index = {"A": 1, "B": 0}.get(inlet.upper())
  939. if index is None or index >= len(self.in_slots):
  940. return None
  941. raw = self.in_slots[index]
  942. if raw < 0:
  943. return None
  944. return (raw >> 8) & 0xFF, raw & 0xFF
  945. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  946. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  947. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  948. # as empty everywhere is strictly safer than reading it as the external spool.
  949. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  950. @dataclass
  951. class ExtruderSlot:
  952. """Which AMS slot an extruder is currently fed from.
  953. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  954. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  955. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  956. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  957. ``state.tray_now`` cannot answer this: it is a single value for the whole
  958. printer, so on a dual-nozzle machine with both hotends loaded it names only
  959. one of them. Unloading a specific slot needs to know which extruder is
  960. holding it, which is what this is for.
  961. """
  962. ams_id: int | None = None
  963. slot_id: int | None = None
  964. has_filament: bool = False
  965. def holds(self, ams_id: int, slot_id: int) -> bool:
  966. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  967. return self.ams_id == ams_id and self.slot_id == slot_id
  968. @dataclass
  969. class PrintOptions:
  970. """AI detection and print options from xcam data."""
  971. # Core AI detectors
  972. spaghetti_detector: bool = False
  973. print_halt: bool = False
  974. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  975. first_layer_inspector: bool = False
  976. printing_monitor: bool = False # AI print quality monitoring
  977. buildplate_marker_detector: bool = False
  978. allow_skip_parts: bool = False
  979. # Additional AI detectors - decoded from cfg bitmask
  980. nozzle_clumping_detector: bool = True
  981. nozzle_clumping_sensitivity: str = "medium"
  982. pileup_detector: bool = True
  983. pileup_sensitivity: str = "medium"
  984. airprint_detector: bool = True
  985. airprint_sensitivity: str = "medium"
  986. auto_recovery_step_loss: bool = True # Uses print.print_option command
  987. filament_tangle_detect: bool = False
  988. @dataclass
  989. class PrinterState:
  990. connected: bool = False
  991. state: str = "unknown"
  992. current_print: str | None = None
  993. subtask_name: str | None = None
  994. progress: float = 0.0
  995. remaining_time: int = 0
  996. layer_num: int = 0
  997. total_layers: int = 0
  998. temperatures: dict = field(default_factory=dict)
  999. raw_data: dict = field(default_factory=dict)
  1000. gcode_file: str | None = None
  1001. subtask_id: str | None = None
  1002. hms_errors: list = field(default_factory=list) # List of HMSError
  1003. kprofiles: list = field(default_factory=list) # List of KProfile
  1004. sdcard: bool = False # SD card inserted
  1005. # Whether the printer has ever actually told us about `sdcard`. Without this
  1006. # the default False is indistinguishable from a real "no card", and any
  1007. # consumer that treats False as evidence would act on silence — which is how
  1008. # a storage gate turns into a regression for every printer whose firmware
  1009. # simply doesn't publish the field (#2780).
  1010. sdcard_reported: bool = False
  1011. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  1012. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  1013. # whoever sent it (the slicer or us). Bambu states where the sliced file
  1014. # went: `ftp://<name>` is external storage, which FTPS serves, while
  1015. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  1016. #
  1017. # Two fields, because the two readers need different guarantees.
  1018. # ``current_project_url`` belongs to the print now running and is cleared
  1019. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  1020. # "unknown" rather than inheriting the previous job's answer. That matters:
  1021. # 18% of the print starts in #2780's bundle had no dispatch on the request
  1022. # topic at all (touchscreen reprints, restart recovery), and a stale
  1023. # internal-storage URL would make those skip an FTPS sweep that could have
  1024. # found the file — losing an archive that works today.
  1025. #
  1026. # ``last_project_url`` is sticky and exists for reporting only: the
  1027. # connection diagnostic is usually run *after* the print that prompted it,
  1028. # by which point the per-print value is rightly gone.
  1029. #
  1030. # None means we never saw a dispatch — say nothing, don't guess.
  1031. current_project_url: str | None = None
  1032. last_project_url: str | None = None
  1033. timelapse: bool = False # Timelapse recording active
  1034. ipcam: bool = False # Live view / camera streaming enabled
  1035. wifi_signal: int | None = None # WiFi signal strength in dBm
  1036. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  1037. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  1038. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  1039. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  1040. # right. (The legacy parser below writes left -> [0], but it only ever runs
  1041. # for single-nozzle printers -- every dual-nozzle model reports
  1042. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  1043. # than indexing it directly.
  1044. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  1045. # AI detection and print options
  1046. print_options: PrintOptions = field(default_factory=PrintOptions)
  1047. # Calibration stage tracking (from stg_cur and stg fields)
  1048. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  1049. stg: list = field(default_factory=list) # List of stages to execute
  1050. # Air conditioning mode (0=cooling, 1=heating)
  1051. airduct_mode: int = 0
  1052. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1053. speed_level: int = 2
  1054. # Chamber light on/off
  1055. chamber_light: bool = False
  1056. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  1057. active_extruder: int = 0
  1058. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  1059. tray_now: int = 255
  1060. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  1061. # tray_tar = the slot the paused/loading print now expects
  1062. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  1063. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  1064. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  1065. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  1066. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  1067. tray_tar: int = 255
  1068. tray_pre: int = 255
  1069. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  1070. last_loaded_tray: int = -1
  1071. # Pending load target - used to track what tray we're loading for H2D disambiguation
  1072. pending_tray_target: int | None = None
  1073. # When it was set (time.monotonic): see PENDING_TRAY_TARGET_TTL.
  1074. pending_tray_target_at: float | None = None
  1075. # AMS status for filament change tracking (from print.ams.ams_status field)
  1076. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1077. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  1078. ams_status: int = 0
  1079. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  1080. ams_status_sub: int = 0 # ams_status & 0xFF
  1081. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  1082. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  1083. mc_print_sub_stage: int = 0
  1084. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  1085. ams_mapping: list = field(default_factory=list)
  1086. # The running print's AMS mapping (global tray per filament, -1 = none),
  1087. # as captured from its print command. None when no print has one.
  1088. print_ams_mapping: list | None = None
  1089. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  1090. ams_extruder_map: dict = field(default_factory=dict)
  1091. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  1092. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  1093. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  1094. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  1095. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  1096. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  1097. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  1098. ams_switch_inlet: dict = field(default_factory=dict)
  1099. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  1100. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  1101. # series). Empty elsewhere, which every reader has to tolerate — see
  1102. # ExtruderSlot for why tray_now cannot stand in for it.
  1103. extruder_slots: dict = field(default_factory=dict)
  1104. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  1105. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  1106. # regex used to derive the plate number from the path always falls back to
  1107. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  1108. # Bambuddy dispatches the print itself we know the plate authoritatively;
  1109. # we record it here and prefer it over the gcode_file regex. The subtask
  1110. # field guards against staleness: if the printer is currently running a
  1111. # different subtask (e.g. a Studio-direct dispatch), these values are
  1112. # ignored. Cleared on disconnect.
  1113. dispatched_plate_id: int | None = None
  1114. dispatched_subtask: str | None = None
  1115. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  1116. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  1117. h2d_extruder_snow: dict = field(default_factory=dict)
  1118. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  1119. nozzle_rack: list = field(default_factory=list)
  1120. # H2C rack position currently mounted / being moved to, from
  1121. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  1122. # the six rack slots), not extruder indices, and they are what the
  1123. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  1124. # can tell us which hotend is in the carriage right now, so this is read
  1125. # live rather than derived from the queued job.
  1126. nozzle_rack_src_id: int | None = None
  1127. nozzle_rack_tar_id: int | None = None
  1128. # Timestamp of last AMS data update (for RFID refresh detection)
  1129. last_ams_update: float = 0.0
  1130. # Printable objects for skip object functionality: {identify_id: object_name}
  1131. printable_objects: dict = field(default_factory=dict)
  1132. # Objects that have been skipped during the current print
  1133. skipped_objects: list = field(default_factory=list)
  1134. # Pauses the slicer put into the running print, from its archived 3MF
  1135. # (#2984): threemf_tools.PausePoint, in print order. Empty when unknown.
  1136. pause_points: list = field(default_factory=list)
  1137. # Layers of those pauses a heads-up notification already went out for.
  1138. pause_warned_layers: set = field(default_factory=set)
  1139. # Fan speeds (0-100 percentage, None if not available for this model)
  1140. cooling_fan_speed: int | None = None # Part cooling fan
  1141. big_fan1_speed: int | None = None # Auxiliary fan
  1142. big_fan2_speed: int | None = None # Chamber/exhaust fan
  1143. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  1144. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  1145. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  1146. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  1147. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  1148. left_aux_fan_speed: int | None = None
  1149. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  1150. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  1151. # omits it, which is the case this flag exists to detect.
  1152. #
  1153. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  1154. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  1155. # harmless because only the P2S/X2D badge consults it — those models keep
  1156. # their unconditional "Chamber Fan" badge — but do not read this as
  1157. # "an exhaust kit is fitted" without also checking the model.
  1158. exhaust_fan_present: bool = False
  1159. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  1160. # Used by usage tracker to split filament weight on mid-print tray switch
  1161. tray_change_log: list = field(default_factory=list)
  1162. # Spools assigned to a tray during the current print, and the spool each
  1163. # assigned tray held at its start (services.spool_swaps, #3325).
  1164. spool_change_log: list = field(default_factory=list)
  1165. # Firmware version info (from info.module[name="ota"].sw_ver)
  1166. firmware_version: str | None = None
  1167. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  1168. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  1169. developer_mode: bool | None = None
  1170. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  1171. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  1172. # which uses the old protocol path; field not yet found). Consumers must treat
  1173. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  1174. ams_filament_backup: bool | None = None
  1175. # Stage name mapping from BambuStudio DeviceManager.cpp
  1176. STAGE_NAMES = {
  1177. 0: "Printing",
  1178. 1: "Auto bed leveling",
  1179. 2: "Heatbed preheating",
  1180. 3: "Vibration compensation",
  1181. 4: "Changing filament",
  1182. 5: "M400 pause",
  1183. 6: "Paused (filament ran out)",
  1184. 7: "Heating nozzle",
  1185. 8: "Calibrating dynamic flow",
  1186. 9: "Scanning bed surface",
  1187. 10: "Inspecting first layer",
  1188. 11: "Identifying build plate type",
  1189. 12: "Calibrating Micro Lidar",
  1190. 13: "Homing toolhead",
  1191. 14: "Cleaning nozzle tip",
  1192. 15: "Checking extruder temperature",
  1193. 16: "Paused by the user",
  1194. 17: "Pause (front cover fall off)",
  1195. 18: "Calibrating the micro lidar",
  1196. 19: "Calibrating flow ratio",
  1197. 20: "Pause (nozzle temperature malfunction)",
  1198. 21: "Pause (heatbed temperature malfunction)",
  1199. 22: "Filament unloading",
  1200. 23: "Pause (step loss)",
  1201. 24: "Filament loading",
  1202. 25: "Motor noise cancellation",
  1203. 26: "Pause (AMS offline)",
  1204. 27: "Pause (low speed of the heatbreak fan)",
  1205. 28: "Pause (chamber temperature control problem)",
  1206. 29: "Cooling chamber",
  1207. 30: "Pause (Gcode inserted by user)",
  1208. 31: "Motor noise showoff",
  1209. 32: "Pause (nozzle clumping)",
  1210. 33: "Pause (cutter error)",
  1211. 34: "Pause (first layer error)",
  1212. 35: "Pause (nozzle clog)",
  1213. 36: "Measuring motion precision",
  1214. 37: "Enhancing motion precision",
  1215. 38: "Measure motion accuracy",
  1216. 39: "Nozzle offset calibration",
  1217. 40: "High temperature auto bed leveling",
  1218. 41: "Auto Check: Quick Release Lever",
  1219. 42: "Auto Check: Door and Upper Cover",
  1220. 43: "Laser Calibration",
  1221. 44: "Auto Check: Platform",
  1222. 45: "Confirming BirdsEye Camera location",
  1223. 46: "Calibrating BirdsEye Camera",
  1224. 47: "Auto bed leveling - phase 1",
  1225. 48: "Auto bed leveling - phase 2",
  1226. 49: "Heating chamber",
  1227. 50: "Cooling heatbed",
  1228. 51: "Printing calibration lines",
  1229. 52: "Auto Check: Material",
  1230. 53: "Live View Camera Calibration",
  1231. 54: "Waiting for heatbed temperature",
  1232. 55: "Auto Check: Material Position",
  1233. 56: "Cutting Module Offset Calibration",
  1234. 57: "Measuring Surface",
  1235. 58: "Thermal Preconditioning",
  1236. 59: "Homing Blade Holder",
  1237. 60: "Calibrating Camera Offset",
  1238. 61: "Calibrating Blade Holder Position",
  1239. 62: "Hotend Pick and Place Test",
  1240. 63: "Waiting for Chamber temperature",
  1241. 64: "Preparing Hotend",
  1242. 65: "Calibrating nozzle clumping detection",
  1243. 66: "Purifying the chamber air",
  1244. 74: "Preparing", # Seen on H2D during print preparation
  1245. 77: "Preparing AMS",
  1246. }
  1247. def get_stage_name(stage: int) -> str:
  1248. """Get human-readable stage name from stage number."""
  1249. try:
  1250. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1251. except TypeError:
  1252. # `stage` is an int by convention only -- it comes straight out of the
  1253. # printer's JSON, and an unhashable value there would otherwise raise
  1254. # from inside the f-string that builds the stage-change log line, which
  1255. # is evaluated on every transition whatever the log level is set to.
  1256. # Labelling a value must not be able to abort the state update.
  1257. return f"Unknown stage ({stage})"
  1258. # #2547 end-of-print telemetry probe.
  1259. #
  1260. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1261. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1262. # but fires on no model in the field: across 247 support bundles there is not a
  1263. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1264. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1265. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1266. #
  1267. # We can't design a replacement from bundles we already have, because out of
  1268. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1269. # every other stage/action field is dropped unread. The obvious candidates
  1270. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1271. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1272. # own. Dumping the raw values for the window between the last object layer and
  1273. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1274. # anything — marks that moment.
  1275. #
  1276. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1277. # Nothing identifying, and nothing that could carry an access code.
  1278. _END_OF_PRINT_PROBE_FIELDS = (
  1279. "gcode_state",
  1280. "state",
  1281. "print_error",
  1282. "stg_cur",
  1283. "stg",
  1284. "stg_cd",
  1285. "mc_print_stage",
  1286. "mc_print_sub_stage",
  1287. "mc_action",
  1288. "mc_stage",
  1289. "print_real_action",
  1290. "print_gcode_action",
  1291. "spd_lvl",
  1292. "mc_percent",
  1293. "mc_remaining_time",
  1294. "layer_num",
  1295. "total_layer_num",
  1296. "home_flag",
  1297. "prepare_per",
  1298. )
  1299. # Frame budget for one print's probe. A long final layer can hold the window
  1300. # open for minutes at ~1 frame/second; this stops a single print from filling
  1301. # the log the user then has to upload.
  1302. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1303. # States that close the window. FINISH is the interesting one — the probe's
  1304. # whole job is to show what happened in the run-up to it.
  1305. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1306. class BambuMQTTClient:
  1307. """MQTT client for Bambu Lab printer communication."""
  1308. MQTT_PORT = 8883
  1309. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1310. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1311. _request_topic_cache: dict[str, bool] = {}
  1312. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1313. # the request topic. A SUBACK failure is the broker answering the question;
  1314. # a disconnect is only circumstantial, and any drop inside the window looks
  1315. # identical -- a network blip, the printer rebooting, the container being
  1316. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1317. # the rest of the process on a printer that supports it perfectly well
  1318. # (#2953). Require the drop to repeat before believing it; a printer that
  1319. # really does refuse the topic answers the same way every time and pays one
  1320. # extra reconnect for it.
  1321. _request_topic_probe_failures: dict[str, int] = {}
  1322. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1323. # Counter for generating unique MQTT client IDs across instances.
  1324. _client_instance_counter: int = 0
  1325. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1326. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1327. # every few seconds (and register_assignment_verification nudges a fresh
  1328. # pushall), so this only has to survive a couple of idle push intervals.
  1329. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1330. def __init__(
  1331. self,
  1332. ip_address: str,
  1333. serial_number: str,
  1334. access_code: str,
  1335. model: str | None = None,
  1336. on_state_change: Callable[[PrinterState], None] | None = None,
  1337. on_print_start: Callable[[dict], None] | None = None,
  1338. on_print_complete: Callable[[dict], None] | None = None,
  1339. on_ams_change: Callable[[list], None] | None = None,
  1340. on_layer_change: Callable[[int], None] | None = None,
  1341. on_print_progress: Callable[[int], None] | None = None,
  1342. on_bed_temp_update: Callable[[float], None] | None = None,
  1343. on_drying_complete: Callable[[int], None] | None = None,
  1344. on_drying_cycle_end: Callable[[DryingCycleEnd], None] | None = None,
  1345. on_print_running_observed: Callable[[dict], None] | None = None,
  1346. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1347. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1348. on_tray_change: Callable[[int, int], None] | None = None,
  1349. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1350. ):
  1351. self.ip_address = ip_address
  1352. self.serial_number = serial_number
  1353. self.access_code = access_code
  1354. self.model = model
  1355. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1356. self._debug_last: dict[str, object] = {}
  1357. self.on_state_change = on_state_change
  1358. self.on_print_start = on_print_start
  1359. self.on_print_complete = on_print_complete
  1360. self.on_ams_change = on_ams_change
  1361. # Fired when an AMS is moved to the switch's other inlet, which changes
  1362. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1363. self.on_fts_inlet_change = on_fts_inlet_change
  1364. self.on_layer_change = on_layer_change
  1365. # #2547: fired when `mc_percent` advances during a running print.
  1366. # `on_layer_change` stops firing the instant the final layer starts, so
  1367. # it is blind to the last few percent of a print — which is exactly the
  1368. # window the finish-photo frame bank needs to keep refreshing through.
  1369. # Progress is the one field that keeps ticking there and then freezes
  1370. # before the end G-code runs, so banking on it stays inside the print.
  1371. self.on_print_progress = on_print_progress
  1372. self.on_bed_temp_update = on_bed_temp_update
  1373. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1374. # the drying cycle just finished (auto- or manually-triggered).
  1375. # Receives the AMS id of the unit that finished drying.
  1376. self.on_drying_complete = on_drying_complete
  1377. # #2863: fired on the same edge with what was seen of the cycle, so the
  1378. # spools in that AMS can be stamped as dried.
  1379. self.on_drying_cycle_end = on_drying_cycle_end
  1380. # #1485 follow-up: fired the first time we see RUNNING state in a
  1381. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1382. # print, the #1304 first-push guard skipped the start event). Lets
  1383. # main.py capture a fresh timelapse baseline at restart-recovery
  1384. # time so the completion-time snapshot-diff still works. Receives
  1385. # the same shape as on_print_start (filename / subtask_name /
  1386. # remaining_time / raw_data / ams_mapping).
  1387. self.on_print_running_observed = on_print_running_observed
  1388. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1389. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1390. # with the process, and a long print outliving a restart would
  1391. # otherwise lose the segment boundaries the usage tracker splits on.
  1392. # Receives (global_tray_id, layer_num).
  1393. self.on_tray_change = on_tray_change
  1394. # #1721: fired the moment the printer enters the end-of-print
  1395. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1396. # we've hit the last layer / remaining_time<=0). This is the
  1397. # framing #1397 was after — toolhead parked, bed not yet
  1398. # dropped — but reached via a clean state signal instead of
  1399. # the per-layer M622 J1 macros which caused per-layer nozzle
  1400. # parks on slicer profiles with Timelapse Type = Smooth.
  1401. # A FINISH-state fallback below fires this same callback if
  1402. # stage 22 never arrives (cancel mid-print, external-spool-
  1403. # only prints, HMS halt before unload, firmware variants).
  1404. self.on_finish_photo_moment = on_finish_photo_moment
  1405. # #2582: fired after a spool assignment (ams_filament_setting +
  1406. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1407. # push landed or a timeout elapses without it. Receives
  1408. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1409. # tell the user "loaded" vs "assignment didn't take" instead of the
  1410. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1411. # feel random. See _check_assignment_verifications.
  1412. self.on_assignment_verified = on_assignment_verified
  1413. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1414. # value is the desired end-state we just pushed plus a monotonic
  1415. # deadline. Populated by register_assignment_verification, drained by
  1416. # _check_assignment_verifications on every AMS push.
  1417. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1418. # Per-AMS previous dry_time, used to detect the falling edge above.
  1419. # Seeded lazily as we observe each AMS unit.
  1420. self._previous_dry_times: dict[int, int] = {}
  1421. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1422. # A live cycle's countdown ticks once a minute; a command the firmware
  1423. # accepted but never actually started (observed on an H2D mid-print
  1424. # with two AMS-HT cycles already running: the third unit's timer sat
  1425. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1426. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1427. # reported as dry_countdown_stalled so the UI can stop claiming an
  1428. # active cycle that is not running.
  1429. self._dry_time_changed_at: dict[int, float] = {}
  1430. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1431. # last start. Bambu does not echo these back in the per-tick AMS push
  1432. # — only the dry_time countdown — so we cache what we sent to drive
  1433. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1434. self._drying_targets: dict[int, dict[str, object]] = {}
  1435. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1436. # ends a cycle far short of its duration, which on the telemetry alone
  1437. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1438. # log would otherwise blame the printer for our own decision (#2770).
  1439. self._drying_stops_sent: set[int] = set()
  1440. # Per-AMS record of the cycle in progress: the highest dry_time seen,
  1441. # whether its first minute was observed, and the target we sent for it.
  1442. # The target is copied here when the countdown starts because a stop
  1443. # drops _drying_targets before the cycle ends (#2863).
  1444. self._dry_cycles: dict[int, dict[str, object]] = {}
  1445. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1446. # for, so each is reported once rather than on every transition into it.
  1447. self._unnamed_stages_seen: set[int] = set()
  1448. self.state = PrinterState()
  1449. self._client: mqtt.Client | None = None
  1450. self._loop: asyncio.AbstractEventLoop | None = None
  1451. self._previous_gcode_state: str | None = None
  1452. self._previous_gcode_file: str | None = None
  1453. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1454. # #3485: the first state after startup was PAUSE with a print loaded,
  1455. # e.g. a printer in power-loss recovery when Bambuddy came back. Its
  1456. # PAUSE -> RUNNING is that print resuming, not a new one.
  1457. self._paused_at_startup: bool = False
  1458. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1459. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1460. # #1721: one-shot guard so the end-of-print stage-22 detector
  1461. # and the FINISH-state fallback don't both fire on the same
  1462. # print. Reset to False on every print start.
  1463. self._finish_photo_captured: bool = False
  1464. # #2702: one-shot re-request of the layer total. Armed at print start
  1465. # when the starting frame carried no `total_layer_num`, spent on the
  1466. # first layer advance that still has no denominator. Bambu firmware
  1467. # only re-sends *changed* fields, so a total we never received (or
  1468. # dropped) is only recoverable via a full pushall.
  1469. self._total_layers_refresh_armed: bool = False
  1470. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1471. # window has run for a print so a late FINISH re-send can't reopen it.
  1472. self._eop_probe_armed: bool = True
  1473. self._eop_probe_open: bool = False
  1474. self._eop_probe_frames: int = 0
  1475. self._eop_probe_last: dict = {}
  1476. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1477. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1478. # #3317: the layer the previous print ended on. Right after a print
  1479. # starts, the printer can send one frame that still carries it (H2S:
  1480. # `layer_num` 357 with `mc_percent` 0, then 0 a second later). Taken at
  1481. # face value, the 0 that follows saved 357 as this print's last layer,
  1482. # and a print failing at layer 0 was charged as finished. Frames with
  1483. # this value are ignored until the new print reports another layer.
  1484. self._stale_layer_num: int = 0
  1485. # The subtask_id minted for the most recent start_print() command. The
  1486. # printer echoes it back in status, but often not within the first few
  1487. # seconds — so on_print_start uses this as the id source when the
  1488. # printer hasn't reported it yet, letting queue/scheduled archives
  1489. # persist a restart-stable id from the moment they dispatch (#1485).
  1490. self.last_dispatch_subtask_id: str | None = None
  1491. # The printer's answer to the last print start it refused, as (result,
  1492. # reason); cleared when the next start is sent. The start watchdog
  1493. # reads it to stop waiting for a print that will not come.
  1494. self.last_start_refusal: tuple[str, str | None] | None = None
  1495. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1496. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1497. self._logging_enabled: bool = False
  1498. self._last_message_time: float = 0.0 # Track when we last received a message
  1499. # Count of report-topic messages received since the last (re)connect.
  1500. # Lets check_staleness() distinguish "printer never sent a status
  1501. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1502. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1503. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1504. self._report_messages_since_connect: int = 0
  1505. self._zero_report_hint_logged: bool = False
  1506. # Set by mark_power_off() to the gcode_state held just before we
  1507. # optimistically forced the printer to "unknown" (#2629). Restored on
  1508. # the next inbound message, because message traffic proves the power
  1509. # was never actually cut. None whenever no power-off is presumed.
  1510. self._state_before_power_off: str | None = None
  1511. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1512. # printer's pushes verbatim to slicers connected to a virtual printer).
  1513. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1514. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1515. self._disconnection_event: threading.Event | None = None
  1516. self._previous_ams_hash: str | None = None # Track AMS changes
  1517. # Track external-spool (vt_tray) identity changes separately: the AMS
  1518. # hash above covers only AMS units, so an external-spool-only filament
  1519. # swap would never re-trigger inventory reconciliation (#2575).
  1520. self._previous_vt_tray_hash: str | None = None
  1521. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1522. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1523. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1524. # Track which (ams_id, field) warnings have already been emitted this connection
  1525. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1526. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1527. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1528. # keyed by the sequence_id we sent, so two concurrent requests for
  1529. # different nozzle sizes can't steal each other's response (#1748).
  1530. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1531. self._sequence_id: int = 0
  1532. self._pending_kprofile_requests: dict[str, dict] = {}
  1533. # The printer's calibration table, one bucket per nozzle diameter.
  1534. #
  1535. # An extrusion_cali_get response is the complete table for *one* nozzle
  1536. # size, and the printer answers whoever asks — including BambuStudio,
  1537. # whose queries land on the same report topic we subscribe to. Assigning
  1538. # each response straight to state.kprofiles therefore let any single
  1539. # answer stand for the whole printer: a GitHub backup probing
  1540. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1541. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1542. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1543. # card because H2-series trays carry no `k` of their own — the slot's
  1544. # K value is resolved from cali_idx against exactly this list.
  1545. #
  1546. # Keyed by diameter so a response only ever replaces the bucket it
  1547. # actually describes; state.kprofiles is then the union across buckets.
  1548. # An empty answer for a nozzle the printer doesn't have empties that
  1549. # bucket alone.
  1550. self._kprofiles_by_nozzle: dict[str, list] = {}
  1551. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1552. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1553. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1554. # by await_cali_ack.
  1555. self._pending_cali_acks: dict[str, dict | None] = {}
  1556. # Objects sent in skip_objects that the printer's s_obj list has not
  1557. # shown yet: object id -> when it was sent. And the ids of each
  1558. # command by its sequence_id, for its answer.
  1559. self._unconfirmed_skips: dict[int, float] = {}
  1560. self._skip_commands: dict[str, list[int]] = {}
  1561. # Acks for RFID re-reads (ams_get_rfid, and the M620 R gcode_line
  1562. # fallback), keyed the same way. Drained by ams_refresh_tray (#3206).
  1563. self._pending_rfid_acks: dict[str, dict | None] = {}
  1564. # Identifies the one project_file *we* dispatched, so its echo on the
  1565. # topic can be told apart from a slicer's. One-shot: consumed by the
  1566. # first frame that matches. See _project_file_key.
  1567. self._own_project_file_key: str | None = None
  1568. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1569. # Key: module_name, Value: timestamp when command was sent
  1570. self._xcam_hold_start: dict[str, float] = {}
  1571. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1572. # True once the printer has sent `cfg`; from then on AMS Filament Backup
  1573. # is read from cfg only, never from home_flag (#3259).
  1574. self._backup_cfg_seen: bool = False
  1575. # True once a full status report arrived without `cfg`; from then on
  1576. # home_flag bit 10 is read from every status frame (#3259).
  1577. self._backup_home_flag_trusted: bool = False
  1578. # Whether the frame being handled carried the nozzles' snow: only then
  1579. # may snow overrule the slot the same frame reports as tray_now.
  1580. self._snow_in_frame = False
  1581. # The captured ams_mapping lives on the state (print_ams_mapping), so
  1582. # the status the card reads carries it; see _captured_ams_mapping.
  1583. # The destination of the dispatch it was captured from.
  1584. self._captured_mapping_url: str | None = None
  1585. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1586. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1587. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1588. self._has_a2l_am_unit: bool = False
  1589. # Rack AMS units already logged as detected (once per unit).
  1590. self._rack_ams_logged: set[int] = set()
  1591. self._tray_layout_key: tuple | None = None
  1592. self._tray_layout = TrayLayout()
  1593. # Why the last connection attempt was refused by the printer, or None
  1594. # when we have never seen a CONNACK failure since the last success.
  1595. # Without this a rejected access code was completely invisible: paho
  1596. # reports the follow-up disconnect as the generic "Unspecified error"
  1597. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1598. # printer stuck in a reconnect loop looked identical whether it was
  1599. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1600. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1601. # string, kept for the log line only.
  1602. self.last_connect_error: str | None = None
  1603. self.last_connect_error_name: str | None = None
  1604. # Request topic subscription tracking
  1605. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1606. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1607. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1608. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1609. self._request_topic_sub_mid: int | None = None
  1610. self._request_topic_sub_time: float = 0.0
  1611. self._request_topic_confirmed: bool = False
  1612. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1613. # we probe by sending an ams_filament_setting and checking the response.
  1614. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1615. self._dev_mode_probed: bool = False
  1616. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1617. self._dev_mode_probe_seq: str | None = None
  1618. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1619. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1620. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1621. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1622. # the printer reports it until the fault clears, so when a later hms[]
  1623. # arrives without it (user enabled Developer Mode and restarted the
  1624. # printer) we drop back to "unknown" and let the probe re-run instead of
  1625. # leaving a permanently-wrong False behind (#2732).
  1626. self._dev_mode_from_hms: bool = False
  1627. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1628. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1629. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1630. self._stale_reconnecting: bool = False
  1631. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1632. # when the frontend polls status faster than paho can reconnect.
  1633. self._last_stale_reconnect: float = 0.0
  1634. # Zombie session detection via ams_filament_setting response tracking (#887).
  1635. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1636. # that develop later (telemetry flows but publishes silently fail).
  1637. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1638. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1639. @property
  1640. def topic_subscribe(self) -> str:
  1641. return f"device/{self.serial_number}/report"
  1642. @property
  1643. def topic_publish(self) -> str:
  1644. return f"device/{self.serial_number}/request"
  1645. @property
  1646. def report_messages_since_connect(self) -> int:
  1647. """Count of report-topic messages received since the latest (re)connect.
  1648. Exposed for the connection diagnostic so it can distinguish "MQTT
  1649. broker accepted us but the printer never published" (typically a
  1650. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1651. bridge that happens to be idle right now. Zero immediately after a
  1652. fresh connect is normal; zero after a full status push cycle is the
  1653. wrong-serial failure mode.
  1654. """
  1655. return self._report_messages_since_connect
  1656. # Maximum time (seconds) without a message before considering connection stale
  1657. STALE_TIMEOUT = 60.0
  1658. def is_stale(self) -> bool:
  1659. """Check if the connection is stale (no messages for too long)."""
  1660. if self._last_message_time == 0:
  1661. return False # Never received a message yet
  1662. time_since_last = time.time() - self._last_message_time
  1663. return time_since_last > self.STALE_TIMEOUT
  1664. def mark_power_off(self) -> bool:
  1665. """Presume the printer lost power (smart plug switched off).
  1666. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1667. The presumption is undone by ``_on_message`` if the printer keeps
  1668. talking — inbound traffic proves the power was never cut (#2629).
  1669. Returns True when the state was actually changed.
  1670. """
  1671. if not self.state.connected:
  1672. return False
  1673. previous = self.state.state
  1674. # Blank the state BEFORE recording what to restore. This runs on the
  1675. # event loop while _on_message runs on the paho thread, and the restore
  1676. # is a two-step (read saved state, compare against "unknown"). Writing
  1677. # "unknown" first means an interleaved message either sees no saved
  1678. # state yet (and skips, leaving the next message to restore) or sees a
  1679. # consistent pair — never a saved state paired with a live state it
  1680. # then discards, which would strand the printer on "unknown".
  1681. self.state.connected = False
  1682. self.state.state = "unknown"
  1683. # Only the first mark wins: a second call before any message arrives
  1684. # must not overwrite the real state with the "unknown" it just wrote.
  1685. # Nothing to restore if the state was already blank.
  1686. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1687. self._state_before_power_off = previous
  1688. return True
  1689. def _restore_state_after_false_power_off(self) -> bool:
  1690. """Undo a presumed power-off once the printer proves it is alive.
  1691. ``connected`` self-heals on the next message, but ``state`` does not:
  1692. it is only rewritten when a payload carries ``gcode_state``, and the
  1693. steady-state ``push_status`` frames are partial. Without this the
  1694. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1695. and the queue scheduler treats the printer as not idle the whole time
  1696. (#2629). Returns True when a state was restored.
  1697. """
  1698. previous = self._state_before_power_off
  1699. self._state_before_power_off = None
  1700. if previous is None or self.state.state != "unknown":
  1701. return False
  1702. logger.info(
  1703. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1704. self.serial_number,
  1705. previous,
  1706. )
  1707. self.state.state = previous
  1708. return True
  1709. # Minimum seconds between stale reconnect attempts. Frontend polls
  1710. # status every few seconds — without a cooldown, each poll would
  1711. # force-close the socket before paho has time to reconnect.
  1712. STALE_RECONNECT_COOLDOWN = 30.0
  1713. def check_staleness(self) -> bool:
  1714. """Check staleness and update connected state if stale. Returns True if connected."""
  1715. if self.state.connected and self.is_stale():
  1716. # Don't force-close again if we already did recently — give paho
  1717. # time to reconnect and the printer time to send its first message.
  1718. now = time.time()
  1719. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1720. return self.state.connected
  1721. logger.warning(
  1722. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1723. )
  1724. # A connection that keeps going stale without ever receiving a
  1725. # status report is almost always a wrong or mis-cased serial
  1726. # number — the broker accepts the connection and the subscription
  1727. # regardless, but the printer publishes to device/<real-serial>/
  1728. # report, which is case-sensitive. Surface that once so the user
  1729. # has something actionable instead of an endless reconnect loop.
  1730. # Only meaningful once the *current* session has had time to receive
  1731. # something. _report_messages_since_connect is reset by _on_connect,
  1732. # so a reconnect that lands microseconds before this check leaves it
  1733. # at 0 for reasons that have nothing to do with the serial — which is
  1734. # how a healthy P1S ended up being told to go check its serial number
  1735. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1736. # on this session means the hint only fires when the printer really
  1737. # has published nothing to the topic we subscribed to.
  1738. # _connect_time of 0 means we have no timestamp to judge by (never went
  1739. # through _on_connect); fall back to the old unconditional behaviour
  1740. # rather than silently swallowing the hint.
  1741. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1742. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1743. self._zero_report_hint_logged = True
  1744. logger.warning(
  1745. "[%s] Connected and subscribed, but the printer has sent zero "
  1746. "status reports. The most common cause is a wrong or mis-cased "
  1747. "serial number — the device/<serial>/report MQTT topic is "
  1748. "case-sensitive. Verify the serial number configured in Bambuddy "
  1749. "exactly matches the printer.",
  1750. self.serial_number,
  1751. )
  1752. self._last_stale_reconnect = now
  1753. self.state.connected = False
  1754. if self.on_state_change:
  1755. self.on_state_change(self.state)
  1756. # Route based on caller thread — see force_reconnect_stale_session.
  1757. # check_staleness is normally called from FastAPI handlers (async,
  1758. # gets the hard-reset path) but the dispatcher exists for safety.
  1759. self._stale_reconnecting = True
  1760. self._reset_client_for_reconnect()
  1761. return self.state.connected
  1762. def force_reconnect_stale_session(self, reason: str) -> None:
  1763. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1764. # arriving but our publishes don't reach the printer.
  1765. #
  1766. # Two routing paths:
  1767. #
  1768. # Async-context callers (queue dispatch deadline)
  1769. # → full client teardown + fresh client_id. Wipes paho's client-side
  1770. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1771. # `project_file` from the broken session would otherwise replay on
  1772. # reconnect, mixing stale commands into the next dispatch and
  1773. # triggering 0500_4003 SD R/W on the printer.
  1774. #
  1775. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1776. # zombie detection, both inside `_update_state`)
  1777. # → socket-close fallback. There is no running loop on that thread to
  1778. # hand the rebuilt client, so close the socket and let paho's own
  1779. # loop detect the broken connection and auto-reconnect (same
  1780. # instance, same client_id). paho would re-send its old outbox on
  1781. # that reconnect; _on_connect empties it first (#3454).
  1782. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1783. self._stale_reconnecting = True
  1784. self.state.connected = False
  1785. if self.on_state_change:
  1786. self.on_state_change(self.state)
  1787. self._reset_client_for_reconnect()
  1788. def _reset_client_for_reconnect(self) -> None:
  1789. """Route between hard-reset and socket-close based on caller thread.
  1790. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1791. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1792. answers that and identifies the caller in one go — paho's callback
  1793. thread has no loop; every legitimate hard-reset caller (FastAPI
  1794. handlers, background async tasks) does."""
  1795. try:
  1796. loop = asyncio.get_running_loop()
  1797. except RuntimeError:
  1798. loop = None
  1799. if loop is not None:
  1800. self._loop = loop
  1801. self._hard_reset_client()
  1802. else:
  1803. self._socket_close_for_reconnect()
  1804. def _hard_reset_client(self) -> None:
  1805. """Tear down the paho client entirely and rebuild it with a fresh
  1806. client_id, so the broker drops the old session and paho's local
  1807. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1808. Caller is responsible for setting ``_stale_reconnecting`` and
  1809. broadcasting the disconnected state.
  1810. Returns as fast as it can build a client: the old one's teardown is
  1811. handed off rather than waited on, because waiting on it is what
  1812. stopped the event loop in #3068. See ``retire_paho_client``."""
  1813. old_client = self._client
  1814. self._client = None
  1815. if old_client is not None:
  1816. retire_paho_client(old_client, self.serial_number)
  1817. # Skip reconnect if no asyncio loop is available (test environment or
  1818. # pre-init). The next initial connect() call from PrinterManager will
  1819. # set up the client fresh.
  1820. if self._loop is None:
  1821. return
  1822. try:
  1823. self.connect(loop=self._loop)
  1824. except Exception as e:
  1825. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1826. def _socket_close_for_reconnect(self) -> None:
  1827. """Close the underlying socket so paho's loop thread detects the
  1828. broken connection and triggers auto-reconnect on the SAME client
  1829. instance. Safe to call from paho's own network thread (the loop
  1830. polls the socket on every iteration and handles a closed socket
  1831. gracefully). Used as a fallback when hard-reset isn't safe. The old
  1832. outbox is not re-sent: _on_connect empties it first (#3454)."""
  1833. if self._client:
  1834. try:
  1835. sock = self._client.socket()
  1836. if sock:
  1837. sock.close()
  1838. except Exception:
  1839. pass
  1840. def _drop_previous_connection_commands(self, client) -> None:
  1841. """Forget every command queued on an earlier connection (#3454).
  1842. Called first in on_connect, which paho runs before it re-sends its
  1843. old outbox. Makes every printer command at most once per connection;
  1844. a command lost in the seconds before a drop is clicked again."""
  1845. dropped = discard_queued_publishes(client)
  1846. if dropped is None:
  1847. logger.warning(
  1848. "[%s] Cannot clear paho's outbox on reconnect (paho internals changed); "
  1849. "commands from the previous connection may be sent again",
  1850. self.serial_number,
  1851. )
  1852. elif dropped:
  1853. logger.info(
  1854. "[%s] Dropped %d command(s) queued on the previous MQTT connection",
  1855. self.serial_number,
  1856. dropped,
  1857. )
  1858. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1859. if rc == 0:
  1860. # First, before anything here publishes on the new connection.
  1861. self._drop_previous_connection_commands(client)
  1862. self.state.connected = True
  1863. self.last_connect_error = None
  1864. self.last_connect_error_name = None
  1865. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1866. # A dropped-and-restored MQTT session means the presumed power-off was
  1867. # real (or at least that the printer restarted): there is nothing
  1868. # legitimate left to restore, and the printer will send a full status
  1869. # push shortly. Dropping the saved state keeps a stale one from being
  1870. # broadcast ahead of the first real report (#2629, #1679).
  1871. self._state_before_power_off = None
  1872. # Reset per-connection warning state so warnings fire once per (re)connection
  1873. self._ams_version_warned = set()
  1874. # Preserve cached developer_mode across auto-reconnects to avoid
  1875. # re-probing on every reconnect. The probe (ams_filament_setting to
  1876. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1877. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1878. # once when developer_mode is truly unknown (first connect).
  1879. # Reset probe tracking so stale timeout state doesn't carry over.
  1880. self._dev_mode_probed = False
  1881. self._dev_mode_needs_probe = False
  1882. self._dev_mode_probe_seq = None
  1883. self._dev_mode_probe_time = 0.0
  1884. self._dev_mode_probe_failures = 0
  1885. self._connect_time = time.monotonic()
  1886. self._report_messages_since_connect = 0
  1887. self._last_ams_cmd_time = 0.0
  1888. self._ams_cmd_unanswered = 0
  1889. # Drop any assignment verifications that were mid-flight before the
  1890. # reconnect — their deadlines are stale and the tray state we would
  1891. # compare against is about to be re-pushed from scratch (#2582).
  1892. # Dropping is silent (no failure event) on purpose.
  1893. self._pending_assignments.clear()
  1894. client.subscribe(self.topic_subscribe)
  1895. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1896. if self._request_topic_supported:
  1897. result, mid = client.subscribe(self.topic_publish)
  1898. if result == mqtt.MQTT_ERR_SUCCESS:
  1899. self._request_topic_sub_mid = mid
  1900. self._request_topic_sub_time = time.time()
  1901. self._request_topic_confirmed = False
  1902. else:
  1903. logger.warning(
  1904. "[%s] Failed to send request topic subscription",
  1905. self.serial_number,
  1906. )
  1907. self._request_topic_supported = False
  1908. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1909. # Request full status update (includes nozzle info in push_status response)
  1910. self._request_push_all()
  1911. # Request firmware version info
  1912. self._request_version()
  1913. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1914. # The correct nozzle data comes from push_status.
  1915. # Prime K-profile request (Bambu printers often ignore first request)
  1916. self._prime_kprofile_request()
  1917. # Immediately broadcast connection state change
  1918. if self.on_state_change:
  1919. self.on_state_change(self.state)
  1920. else:
  1921. self.state.connected = False
  1922. self._record_connect_refusal(rc)
  1923. def _record_connect_refusal(self, rc) -> None:
  1924. """Log and remember why the printer refused the MQTT connection.
  1925. The failure branch of ``_on_connect`` used to be a bare
  1926. ``connected = False``, which threw away the only signal that says
  1927. *why* a printer never comes online. The user-visible result was a
  1928. 30-second reconnect loop logging nothing but paho's generic
  1929. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1930. powered-off printer, so "my printer won't print" reports could not be
  1931. triaged without a round trip (#2698).
  1932. Never logs the access code itself; the code is the likely culprit but
  1933. printing it would put a credential in every support bundle.
  1934. """
  1935. code = getattr(rc, "value", rc)
  1936. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1937. self.last_connect_error_name = name
  1938. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1939. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1940. logger.warning(
  1941. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1942. "or serial number is wrong — the access code changes every time LAN Only or "
  1943. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1944. self.serial_number,
  1945. name,
  1946. code,
  1947. )
  1948. else:
  1949. self.last_connect_error = CONNECT_ERROR_REFUSED
  1950. logger.warning(
  1951. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1952. self.serial_number,
  1953. name,
  1954. code,
  1955. )
  1956. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1957. """Handle SUBACK responses to detect request topic subscription rejection."""
  1958. if mid == self._request_topic_sub_mid:
  1959. for rc in reason_code_list:
  1960. if rc.is_failure:
  1961. logger.warning(
  1962. "[%s] Request topic subscription rejected (code=%d: %s). "
  1963. "ams_mapping capture from slicer-initiated prints unavailable.",
  1964. self.serial_number,
  1965. rc.value,
  1966. rc.getName(),
  1967. )
  1968. self._request_topic_supported = False
  1969. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1970. else:
  1971. logger.info(
  1972. "[%s] Request topic subscription accepted. "
  1973. "ams_mapping capture enabled for slicer-initiated prints.",
  1974. self.serial_number,
  1975. )
  1976. self._request_topic_confirmed = True
  1977. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  1978. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  1979. self._request_topic_sub_mid = None
  1980. self._request_topic_sub_time = 0.0
  1981. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  1982. # Always unblock disconnect() callers, regardless of whether we suppress
  1983. # the state broadcast below. disconnect() sets _disconnection_event and
  1984. # waits on it — every callback path must fire it.
  1985. if self._disconnection_event:
  1986. self._disconnection_event.set()
  1987. # If we intentionally closed the socket for stale reconnect, don't broadcast
  1988. # another state change — check_staleness() already set connected=False and
  1989. # notified the UI. Just log and let paho auto-reconnect.
  1990. if self._stale_reconnecting:
  1991. logger.info(
  1992. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  1993. self.serial_number,
  1994. rc,
  1995. )
  1996. return
  1997. # Ignore spurious disconnect callbacks if we've received a message recently
  1998. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  1999. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  2000. # — only suppress when rc indicates a clean/normal disconnect.
  2001. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  2002. time_since_last_message = time.time() - self._last_message_time
  2003. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  2004. logger.debug(
  2005. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  2006. )
  2007. return
  2008. # Carry the last CONNACK refusal into the disconnect line. paho reports
  2009. # the drop that follows a refused CONNACK as "Unspecified error", so on
  2010. # its own this line says nothing useful about a printer that is looping
  2011. # on bad credentials — and this is the line that fills a support bundle
  2012. # (#2698).
  2013. if self.last_connect_error:
  2014. logger.warning(
  2015. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  2016. self.serial_number,
  2017. rc,
  2018. disconnect_flags,
  2019. self.last_connect_error_name,
  2020. )
  2021. else:
  2022. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  2023. # Detect if request topic subscription caused the disconnect.
  2024. # If we just subscribed and got disconnected before any SUBACK confirmation,
  2025. # the broker likely killed the connection due to the unauthorized subscription.
  2026. if (
  2027. self._request_topic_sub_time > 0
  2028. and not self._request_topic_confirmed
  2029. and time.time() - self._request_topic_sub_time < 10.0
  2030. # A disconnect we asked for says nothing about the subscription.
  2031. and self._disconnection_event is None
  2032. ):
  2033. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  2034. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  2035. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  2036. logger.warning(
  2037. "[%s] Disconnected shortly after request topic subscription %d times. "
  2038. "Disabling request topic for this printer — ams_mapping capture from "
  2039. "slicer-initiated prints is unavailable, and their filament will be "
  2040. "attributed from the printer's own tray reporting instead.",
  2041. self.serial_number,
  2042. failures,
  2043. )
  2044. self._request_topic_supported = False
  2045. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  2046. else:
  2047. logger.info(
  2048. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  2049. "Retrying it on the next connection before giving up.",
  2050. self.serial_number,
  2051. failures,
  2052. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  2053. )
  2054. self._request_topic_sub_mid = None
  2055. self._request_topic_sub_time = 0.0
  2056. self.state.connected = False
  2057. if self.on_state_change:
  2058. self.on_state_change(self.state)
  2059. def _log_message(self, topic: str, direction: str, raw: str) -> None:
  2060. """Record a message for the MQTT Debug log, as it arrived.
  2061. Parsed again from the raw text rather than shared with the handlers:
  2062. processing keeps the payload's "print" dict as the new raw_data and
  2063. writes Bambuddy's merged AMS list and other state into it, so a shared
  2064. dict showed Bambuddy's state instead of what the printer sent (#3356).
  2065. """
  2066. self._message_log.append(
  2067. MQTTLogEntry(
  2068. timestamp=datetime.now(timezone.utc).isoformat(),
  2069. topic=topic,
  2070. direction=direction,
  2071. payload=json.loads(raw),
  2072. )
  2073. )
  2074. def _on_message(self, client, userdata, msg):
  2075. for handler in self._raw_message_handlers:
  2076. try:
  2077. handler(msg.topic, msg.payload)
  2078. except Exception:
  2079. logger.exception(
  2080. "[%s] raw-message handler crashed for topic=%s",
  2081. self.serial_number,
  2082. msg.topic,
  2083. )
  2084. try:
  2085. try:
  2086. raw = msg.payload.decode()
  2087. except UnicodeDecodeError:
  2088. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  2089. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  2090. raw = msg.payload.decode(errors="replace")
  2091. logger.warning(
  2092. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  2093. self.serial_number,
  2094. msg.topic,
  2095. len(msg.payload),
  2096. )
  2097. payload = json.loads(raw)
  2098. # Track last message time - receiving a message proves we're connected
  2099. self._last_message_time = time.time()
  2100. self.state.connected = True
  2101. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  2102. if msg.topic == self.topic_publish:
  2103. # Record it before returning. This topic carries every command
  2104. # travelling *to* the printer, including the ones Bambu Studio
  2105. # sends, and it used to be the one thing an MQTT capture could
  2106. # never show -- which is why "what does Studio put in the drying
  2107. # command?" had no answer from a user's log (#2774). Filed as
  2108. # "out" so the direction filter groups it with our own commands
  2109. # rather than with printer telemetry; anything we send
  2110. # lands twice, once on publish and once on the
  2111. # broker's echo, and the pair is itself evidence the command
  2112. # reached the broker.
  2113. if self._logging_enabled:
  2114. self._log_message(msg.topic, "out", raw)
  2115. self._handle_request_message(payload)
  2116. return
  2117. # Count status reports per connection so check_staleness() can tell
  2118. # "printer never sent a report" apart from a mid-session quiet gap.
  2119. if msg.topic == self.topic_subscribe:
  2120. self._report_messages_since_connect += 1
  2121. # Only report-topic traffic proves the *printer* is alive — the
  2122. # request topic also carries slicer/Bambuddy commands.
  2123. if self._state_before_power_off is not None:
  2124. if self._restore_state_after_false_power_off() and self.on_state_change:
  2125. self.on_state_change(self.state)
  2126. # Log message if logging is enabled
  2127. if self._logging_enabled:
  2128. self._log_message(msg.topic, "in", raw)
  2129. self._process_message(payload)
  2130. except json.JSONDecodeError:
  2131. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  2132. @property
  2133. def _captured_ams_mapping(self):
  2134. """The ams_mapping captured from the current print's command.
  2135. Kept on the state so the status shows it (the slot pills, #1762): the
  2136. printer's own push almost never carries one.
  2137. """
  2138. return self.state.print_ams_mapping
  2139. @_captured_ams_mapping.setter
  2140. def _captured_ams_mapping(self, mapping) -> None:
  2141. self.state.print_ams_mapping = mapping
  2142. def _handle_request_message(self, data: dict) -> None:
  2143. """Intercept print commands on the request topic to capture ams_mapping."""
  2144. print_data = data.get("print", {})
  2145. if not isinstance(print_data, dict):
  2146. return
  2147. command = print_data.get("command", "")
  2148. if command == "project_file":
  2149. # Where the dispatcher put the sliced file. Captured for every
  2150. # project_file, ours included: we publish to this same topic and
  2151. # subscribe to it, so whoever dispatched last wins, which is exactly
  2152. # the print the archive lookup is about to go looking for (#2780).
  2153. url = print_data.get("url")
  2154. if isinstance(url, str) and url:
  2155. self.state.current_project_url = url
  2156. self.state.last_project_url = url
  2157. if "ams_mapping" in print_data:
  2158. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2159. self._captured_mapping_url = url if isinstance(url, str) else None
  2160. logger.info(
  2161. "[%s] Captured ams_mapping from print command: %s",
  2162. self.serial_number,
  2163. self._captured_ams_mapping,
  2164. )
  2165. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  2166. # slicer-launched project_file passes through the request topic,
  2167. # log the full payload so we can diff Studio's field set against
  2168. # ours.
  2169. #
  2170. # This used to read `sequence_id != "20000"`, on the belief that
  2171. # 20000 was ours alone. It is not: 20000 is the slicer convention
  2172. # Bambuddy adopted -- bind_server documents the slicer sending it
  2173. # during detect, and measured on the wire OrcaSlicer dispatched
  2174. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  2175. # counting up from the same base. So the test swallowed whichever
  2176. # slicer dispatch happened to land on 20000, which on a fresh
  2177. # slicer start is the first one. Match our own dispatch instead.
  2178. if self._project_file_key(print_data) == self._own_project_file_key:
  2179. self._own_project_file_key = None
  2180. else:
  2181. logger.info(
  2182. "[%s] External project_file payload: %s",
  2183. self.serial_number,
  2184. json.dumps(print_data),
  2185. )
  2186. def _capture_report_project_file(self, print_data: dict) -> None:
  2187. """Read a print's destination off a ``project_file`` *response* (#1820).
  2188. ``_handle_request_message`` only ever sees the request topic, so a print
  2189. started from the printer's own touchscreen -- which publishes nothing --
  2190. left ``current_project_url`` at None, and the storage verdict fell
  2191. through to the ``sdcard`` fallback for the one case it was written for.
  2192. On an H2S that flag is True (its "card" is the internal eMMC), so the
  2193. verdict came back reachable and the ~110-connection sweep ran in full.
  2194. The printer does announce it: an unsolicited ``project_file`` response
  2195. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  2196. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  2197. This also covers an install nobody had in view: some brokers refuse the
  2198. request-topic subscription, and on those no print of any kind has ever
  2199. populated the field.
  2200. Both kinds of ``project_file`` on this topic are read -- the printer's
  2201. echo of a dispatch and a screen start -- because both name the
  2202. destination in ``url``, which is the only thing the verdict wants. What
  2203. this must NOT do is reuse ``_handle_request_message``'s "External
  2204. project_file payload" diagnostic: our own dispatch is echoed on *both*
  2205. topics, the request-topic echo arrives first and clears
  2206. ``_own_project_file_key``, so by the time this frame lands the key is
  2207. already None and every Bambuddy-started print would log itself as
  2208. someone else's.
  2209. """
  2210. # Same shape as _handle_request_message: the frame is whatever the
  2211. # printer put on the wire, and this is the first thing to touch it.
  2212. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  2213. return
  2214. # A refused dispatch names a file that was never written. Acting on it
  2215. # would pin an archive on a destination nothing ever went to. Logged:
  2216. # nothing else says the printer refused a print it was sent.
  2217. result = str(print_data.get("result") or "")
  2218. if result.upper() != "SUCCESS":
  2219. logger.info(
  2220. "[%s] Printer refused a print start (project_file): result=%s reason=%s url=%s",
  2221. self.serial_number,
  2222. result,
  2223. print_data.get("reason"),
  2224. print_data.get("url"),
  2225. )
  2226. self.last_start_refusal = (result, print_data.get("reason"))
  2227. return
  2228. url = print_data.get("url")
  2229. if not isinstance(url, str) or not url:
  2230. return
  2231. if self.state.current_project_url != url:
  2232. logger.info(
  2233. "[%s] Print destination from the report topic: %s",
  2234. self.serial_number,
  2235. url,
  2236. )
  2237. self.state.current_project_url = url
  2238. self.state.last_project_url = url
  2239. # On a screen start this frame is the only place the mapping appears --
  2240. # no slicer ever sent one. Fill a gap only: when the request topic
  2241. # already captured this print's mapping that copy is the slicer's own,
  2242. # and the echo can arrive without the field at all. A mapping captured
  2243. # for another destination is from a dispatch that never ran (refused,
  2244. # or cancelled before it started, so no completion cleared it).
  2245. stale = self._captured_ams_mapping is not None and self._captured_mapping_url != url
  2246. if (self._captured_ams_mapping is None or stale) and isinstance(print_data.get("ams_mapping"), list):
  2247. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2248. self._captured_mapping_url = url
  2249. logger.info(
  2250. "[%s] Captured ams_mapping from print response: %s",
  2251. self.serial_number,
  2252. self._captured_ams_mapping,
  2253. )
  2254. def _resolve_captured_mapping(self, print_data: dict) -> object:
  2255. """The ``ams_mapping`` of a project_file, with external spools resolved
  2256. from its ``ams_mapping2`` (#3166)."""
  2257. from backend.app.utils.printer_models import is_dual_nozzle_model
  2258. return resolve_external_spools_in_mapping(
  2259. print_data.get("ams_mapping"),
  2260. print_data.get("ams_mapping2"),
  2261. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  2262. self.tray_layout,
  2263. )
  2264. @staticmethod
  2265. def _project_file_key(print_data: dict) -> str:
  2266. """Identity of a project_file dispatch, for telling ours from a slicer's.
  2267. Sequence id alone cannot do it -- every slicer counts up from the same
  2268. 20000 -- so this also carries the file and its destination, which differ
  2269. between any two real dispatches.
  2270. """
  2271. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  2272. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  2273. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  2274. The state dumps in the push_status handler fire whenever their field is
  2275. *present* in the frame — and a full push_status carries every field, so
  2276. they fire on every frame regardless of whether anything changed. Several
  2277. even say "updated" or "changes" in their own comment while doing nothing
  2278. of the sort.
  2279. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  2280. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  2281. minutes: the reporter enabled debug logging as asked and the support
  2282. bundle came back holding under five minutes of history, almost none of it
  2283. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  2284. these dumps.
  2285. Deduplicating on the value keeps every transition — which is the only part
  2286. anyone reads these lines for — and drops the steady-state repetition.
  2287. ``value`` must capture everything interpolated into ``msg``, or a change
  2288. will be swallowed; pass a tuple when the message renders several fields.
  2289. """
  2290. if not logger.isEnabledFor(logging.DEBUG):
  2291. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  2292. # and these clients outlive the toggle. Letting INFO-level frames warm
  2293. # the cache would be self-defeating: the operator turns debug on
  2294. # precisely to see the printer's current state, and a cache already
  2295. # holding every steady-state value would suppress that baseline until
  2296. # something happened to change. On an idle printer the bundle would
  2297. # come back with none of these lines at all.
  2298. #
  2299. # So while debug is off we record nothing and drop whatever we had.
  2300. # Every enable then starts cold and dumps a full baseline on the next
  2301. # frame, exactly as it did before this method existed.
  2302. self._debug_last.clear()
  2303. return
  2304. if self._debug_last.get(key) == value:
  2305. return
  2306. self._debug_last[key] = value
  2307. logger.debug(msg, *args)
  2308. def _process_message(self, payload: dict):
  2309. """Process incoming MQTT message from printer."""
  2310. # Handle top-level AMS data (comes outside of "print" key)
  2311. # Wrap in try/except to prevent breaking the MQTT connection
  2312. if "ams" in payload:
  2313. try:
  2314. self._snow_in_frame = False # a bare AMS frame carries no extruder data
  2315. self._handle_ams_data(payload["ams"])
  2316. except Exception as e:
  2317. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  2318. # Handle xcam data (camera settings and AI detection) at top level
  2319. if "xcam" in payload:
  2320. xcam_data = payload["xcam"]
  2321. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  2322. self._parse_xcam_data(xcam_data)
  2323. # Fire state change callback for top-level xcam (not nested in "print")
  2324. if "print" not in payload and self.on_state_change:
  2325. self.on_state_change(self.state)
  2326. # Handle system responses (accessories info, etc.)
  2327. if "system" in payload:
  2328. system_data = payload["system"]
  2329. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  2330. self._handle_system_response(system_data)
  2331. # Handle info responses (firmware version info from get_version command)
  2332. if "info" in payload:
  2333. info_data = payload["info"]
  2334. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2335. self._handle_version_info(info_data)
  2336. # Parse WiFi signal at top level (some printers send it here)
  2337. if "wifi_signal" in payload:
  2338. wifi_signal = payload["wifi_signal"]
  2339. if isinstance(wifi_signal, (int, float)):
  2340. self.state.wifi_signal = int(wifi_signal)
  2341. elif isinstance(wifi_signal, str):
  2342. try:
  2343. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2344. except ValueError:
  2345. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2346. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2347. from backend.app.utils.printer_models import has_ethernet
  2348. if has_ethernet(self.model):
  2349. self.state.wired_network = self.state.wifi_signal == -90
  2350. # Parse developer LAN mode from top-level "fun" field
  2351. # Some firmware versions send "fun" at the top level, others inside "print"
  2352. if "fun" in payload:
  2353. try:
  2354. fun_val = payload["fun"]
  2355. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2356. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2357. except (ValueError, TypeError):
  2358. pass
  2359. if "print" in payload:
  2360. print_data = payload["print"]
  2361. # Before anything reads the state: this is where a touchscreen-
  2362. # started print announces where its file lives, and the print-start
  2363. # handler asks ~2 s later (#1820).
  2364. self._capture_report_project_file(print_data)
  2365. # Check if xcam is nested inside print data
  2366. if "xcam" in print_data:
  2367. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2368. self._parse_xcam_data(print_data["xcam"])
  2369. # Log when we see gcode_state changes
  2370. if "gcode_state" in print_data:
  2371. logger.debug(
  2372. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2373. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2374. )
  2375. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2376. # new-protocol printers. Verified against OrcaSlicer's
  2377. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2378. # and live H2D ON/OFF capture 2026-06-20.
  2379. #
  2380. # Families without cfg (P1S, P1P, A1, A1 Mini) carry it in home_flag
  2381. # bit 10 (#3259). Trusted once a full status report (the same
  2382. # >30-key test as the developer-mode probe) arrived without cfg;
  2383. # from then on every status frame that carries home_flag is read,
  2384. # so a toggle in the slicer shows up without a Force Refresh (P1S
  2385. # capture: each toggle came in a 4-6 key update frame). Before
  2386. # that nothing is read from small frames, so a cfg printer can't
  2387. # be misread from a frame that arrives ahead of its first cfg.
  2388. # Printers that send cfg keep reading it alone.
  2389. #
  2390. # Hold-timer guard: when the user just toggled via the badge, the
  2391. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2392. # for ~3 s before the firmware reflects the change. Without this
  2393. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2394. # Only from a status frame: a project_file ack echoes our own
  2395. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2396. # stuck on every family that doesn't repeat `cfg` in its periodic
  2397. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2398. new_backup = None
  2399. if is_printer_status_frame(print_data):
  2400. if "cfg" in print_data:
  2401. self._backup_cfg_seen = True
  2402. new_backup = parse_ams_filament_backup_from_cfg(print_data["cfg"])
  2403. elif not self._backup_cfg_seen:
  2404. if len(print_data) > 30:
  2405. self._backup_home_flag_trusted = True
  2406. if self._backup_home_flag_trusted:
  2407. new_backup = parse_ams_filament_backup_from_home_flag(print_data.get("home_flag"))
  2408. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2409. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2410. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2411. logger.debug(
  2412. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2413. self.serial_number,
  2414. time.time() - hold_start,
  2415. )
  2416. else:
  2417. logger.info(
  2418. "[%s] AMS Filament Backup: %s",
  2419. self.serial_number,
  2420. "ON" if new_backup else "OFF",
  2421. )
  2422. self.state.ams_filament_backup = new_backup
  2423. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2424. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2425. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2426. if not self._is_dual_nozzle and "device" in print_data:
  2427. dev = print_data.get("device")
  2428. if isinstance(dev, dict):
  2429. ext_info = dev.get("extruder", {}).get("info", [])
  2430. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2431. self._is_dual_nozzle = True
  2432. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2433. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2434. # out of the AMS info bits, but only means anything once we know a
  2435. # switch is installed. Parsing them the other way round would lose
  2436. # the binding on every frame where the two arrive together.
  2437. self._parse_fila_switch(print_data)
  2438. # Before _handle_ams_data too: an H2D's tray_now is a bare slot that
  2439. # this frame's extruder data places (which nozzle, which AMS).
  2440. self._snow_in_frame = self._parse_extruder_position(print_data)
  2441. self._parse_extruder_slots(print_data)
  2442. # Handle AMS data that comes inside print key
  2443. if "ams" in print_data:
  2444. try:
  2445. self._handle_ams_data(print_data["ams"])
  2446. except Exception as e:
  2447. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2448. # Handle vir_slot (H2-series external spool data) — list of external trays
  2449. # Process vir_slot FIRST so it takes priority over vt_tray
  2450. if "vir_slot" in print_data:
  2451. vir_slot = print_data["vir_slot"]
  2452. if isinstance(vir_slot, list) and vir_slot:
  2453. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2454. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2455. # Remap id=255→254 for single-slot printers so active detection works.
  2456. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2457. # A nozzle-rack printer (H3C) reports one input per hotend,
  2458. # 247-255, kept as reported.
  2459. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2460. vir_slot[0]["id"] = "254"
  2461. self.state.raw_data["vt_tray"] = vir_slot
  2462. # Handle vt_tray (virtual tray / external spool) data
  2463. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2464. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2465. # which would overwrite the correct multi-slot vir_slot data)
  2466. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2467. vt_tray = print_data["vt_tray"]
  2468. existing = self.state.raw_data.get("vt_tray")
  2469. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2470. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2471. pass # Keep the vir_slot data
  2472. else:
  2473. if isinstance(vt_tray, dict):
  2474. vt_tray = [vt_tray]
  2475. self.state.raw_data["vt_tray"] = vt_tray
  2476. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2477. # units, and _handle_ams_data runs before this block — so a change
  2478. # to the external spool alone (e.g. swapping generic TPU for generic
  2479. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2480. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2481. # external-spool identity changes here and fire the same callback.
  2482. self._maybe_trigger_external_spool_change()
  2483. # Parse ams_status directly from print data (NOT from print.ams)
  2484. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2485. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2486. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2487. if "ams_status" in print_data:
  2488. raw_ams_status = print_data["ams_status"]
  2489. if isinstance(raw_ams_status, str):
  2490. try:
  2491. self.state.ams_status = int(raw_ams_status)
  2492. except ValueError:
  2493. self.state.ams_status = 0
  2494. else:
  2495. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2496. # Compute main and sub status
  2497. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2498. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2499. # Log when ams_status changes (for filament change tracking debug)
  2500. self._debug_on_change(
  2501. "ams_status:print",
  2502. self.state.ams_status,
  2503. "[%s] ams_status: %s (main=%s, sub=%s)",
  2504. self.serial_number,
  2505. self.state.ams_status,
  2506. self.state.ams_status_main,
  2507. self.state.ams_status_sub,
  2508. )
  2509. # Check for command responses
  2510. if "command" in print_data:
  2511. cmd = print_data.get("command")
  2512. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2513. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2514. # INFO, not debug: this is the printer's verdict on a write
  2515. # the user just made, and it was invisible in support
  2516. # bundles for as long as it sat at DEBUG (#2718). Same
  2517. # reasoning as ams_filament_drying below.
  2518. logger.info(
  2519. "[%s] %s response: result=%s reason=%s seq=%s",
  2520. self.serial_number,
  2521. cmd,
  2522. print_data.get("result"),
  2523. print_data.get("reason", ""),
  2524. print_data.get("sequence_id"),
  2525. )
  2526. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2527. ack_seq = str(print_data.get("sequence_id", ""))
  2528. if ack_seq in self._pending_cali_acks:
  2529. self._pending_cali_acks[ack_seq] = print_data
  2530. elif cmd == "skip_objects":
  2531. self._handle_skip_objects_answer(print_data)
  2532. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2533. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2534. # A refused ams_filament_setting is the printer's verdict on
  2535. # a write the user just made, and at DEBUG it never reached
  2536. # a support bundle: #2756 reported six manual Configure Slot
  2537. # attempts on an X1C, each returning HTTP 200 with the
  2538. # read-back still showing the previous profile, and no
  2539. # record of what the printer said about any of them. Same
  2540. # promotion as extrusion_cali_set (#2718) and
  2541. # ams_filament_drying (#1447) — but only on a non-success,
  2542. # because unlike those two this command is not rare: every
  2543. # spool assignment and every K-profile re-apply sends one,
  2544. # so promoting each ack would bury the interesting line.
  2545. #
  2546. # The developer-mode probe is excluded. It sends this exact
  2547. # command to the external slot precisely to see it refused
  2548. # on P1 firmware, so its failure is a normal reading rather
  2549. # than a fault. Its response is still matched below (this
  2550. # runs before _handle_dev_mode_probe_response clears the
  2551. # seq), and user-initiated commands can't be mistaken for
  2552. # it — they publish a hardcoded sequence_id of "0".
  2553. result = print_data.get("result")
  2554. is_dev_mode_probe = (
  2555. self._dev_mode_probe_seq is not None
  2556. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2557. )
  2558. # extrusion_cali_sel too (FW-C3): every RFID re-read
  2559. # re-applies the spool's K-profile and logs "Applied PA
  2560. # profile", so its refusal must reach the bundle beside it.
  2561. # The printer's word, not a verdict: the extrusion_cali_*
  2562. # acks are known to say "fail" for writes that applied.
  2563. if not is_dev_mode_probe and isinstance(result, str) and result.lower() != "success":
  2564. logger.info(
  2565. "[%s] %s refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2566. self.serial_number,
  2567. cmd,
  2568. result,
  2569. print_data.get("reason", ""),
  2570. print_data.get("ams_id"),
  2571. print_data.get("tray_id"),
  2572. )
  2573. # AMS drying responses are rare (user-initiated only) and the
  2574. # full payload — including `result` and any `reason` code —
  2575. # is the only way to diagnose silent rejections like #1447.
  2576. # INFO level so the body lands in support bundles by default.
  2577. elif cmd == "ams_filament_drying":
  2578. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2579. # RFID re-reads are user-initiated and rare, and a refusal was
  2580. # invisible until #3206 (X1Plus answering FAIL / ERROR STATE).
  2581. # gcode_line acks are only of interest when they answer our
  2582. # M620 R fallback, so those are matched by sequence_id alone.
  2583. ack_seq = str(print_data.get("sequence_id", ""))
  2584. if (
  2585. cmd in ("ams_get_rfid", "gcode_line")
  2586. and ack_seq in self._pending_rfid_acks
  2587. and "result" in print_data
  2588. ):
  2589. logger.info(
  2590. "[%s] %s response: result=%s reason=%s seq=%s",
  2591. self.serial_number,
  2592. cmd,
  2593. print_data.get("result"),
  2594. print_data.get("reason", ""),
  2595. ack_seq,
  2596. )
  2597. self._pending_rfid_acks[ack_seq] = print_data
  2598. # Check for developer mode probe response
  2599. if (
  2600. cmd == "ams_filament_setting"
  2601. and self._dev_mode_probe_seq is not None
  2602. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2603. ):
  2604. self._handle_dev_mode_probe_response(print_data)
  2605. # Track user-initiated ams_filament_setting responses (#887
  2606. # zombie detection). Reset both the timer AND the unanswered
  2607. # counter on ANY response — the response proves the channel is
  2608. # alive, so the counter must not stay armed even when the
  2609. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2610. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2611. # caused #1164: one sluggish response (>10s) would set the
  2612. # counter to 1 and zero the timer; the late response arrived
  2613. # but was ignored by this branch (timer is 0); the counter
  2614. # stayed at 1 indefinitely; the very next slow response —
  2615. # possibly hours later, on a totally unrelated command — would
  2616. # take it to 2 and force-reconnect, surfacing as "filament
  2617. # config doesn't reach the printer ~6 changes in".
  2618. elif cmd == "ams_filament_setting":
  2619. self._last_ams_cmd_time = 0.0
  2620. self._ams_cmd_unanswered = 0
  2621. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2622. if is_kprofile_response:
  2623. self._handle_kprofile_response(print_data)
  2624. # An extrusion_cali_get response echoes the *requested* nozzle
  2625. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2626. # installed hardware. Feeding it to _update_state clobbered the real
  2627. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2628. # which then failed the #1899 dispatch guard. The response carries no
  2629. # status telemetry, so skip it; the true nozzle comes from pushall.
  2630. # (Same reasoning as get_accessories in _handle_system_response.)
  2631. # The answers to K-profile writes and selections echo the diameter
  2632. # the command named in the same way, so none of them is status.
  2633. if print_data.get("command") not in _KPROFILE_COMMAND_ANSWERS:
  2634. self._update_state(print_data)
  2635. def _handle_system_response(self, data: dict):
  2636. """Handle system responses including accessories info.
  2637. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2638. The correct nozzle data comes from push_status, so we don't update
  2639. nozzle type/diameter from get_accessories. We just log the response
  2640. for debugging purposes.
  2641. """
  2642. command = data.get("command")
  2643. if command == "get_accessories":
  2644. # Log response for debugging - but DON'T use it to update nozzle data
  2645. # because it returns stale values (e.g., 'stainless_steel' when the
  2646. # actual nozzle is 'HH01' hardened steel high-flow)
  2647. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2648. def _handle_version_info(self, data: dict):
  2649. """Handle version info response from get_version command.
  2650. Parses firmware version from the 'ota' module in the module list.
  2651. Also extracts AMS unit firmware versions from AMS modules and stores
  2652. them on the corresponding AMS unit in raw_data so the status route can
  2653. expose them to the frontend.
  2654. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2655. - ``ams/<id>`` – original AMS
  2656. - ``ams_f1/<id>`` – AMS Lite (#3348)
  2657. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2658. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2659. Message format:
  2660. {
  2661. "command": "get_version",
  2662. "module": [
  2663. {"name": "ota", "sw_ver": "01.08.05.00"},
  2664. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2665. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2666. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2667. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2668. ...
  2669. ]
  2670. }
  2671. """
  2672. modules = data.get("module", [])
  2673. if not isinstance(modules, list):
  2674. return
  2675. state_changed = False
  2676. for module in modules:
  2677. if not isinstance(module, dict):
  2678. continue
  2679. if module.get("name") == "ota":
  2680. version = module.get("sw_ver")
  2681. if version:
  2682. old_version = self.state.firmware_version
  2683. self.state.firmware_version = version
  2684. if old_version != version:
  2685. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2686. state_changed = True
  2687. break
  2688. # Extract AMS unit firmware versions from AMS modules.
  2689. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2690. # Always cache regardless of whether AMS data has arrived yet — get_version
  2691. # often arrives before the first push_status, so caching must be unconditional.
  2692. ams_raw = self.state.raw_data.get("ams")
  2693. for module in modules:
  2694. if not isinstance(module, dict):
  2695. continue
  2696. name = module.get("name", "")
  2697. if name == AMS3H_MODULE_NAME:
  2698. name = f"{name}/{self._ams3h_unit_id()}"
  2699. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2700. continue
  2701. try:
  2702. # The A2L's AMS Lite is unit 16 here but stored as 6, like
  2703. # everywhere else it is ingested.
  2704. ams_id = normalize_am_unit_id(int(name.split("/", 1)[1]))
  2705. except (ValueError, IndexError):
  2706. continue
  2707. sw_ver = module.get("sw_ver", "")
  2708. sn = module.get("sn", "")
  2709. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2710. module_type = name.split("/", 1)[0]
  2711. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2712. if sw_ver or sn or module_type:
  2713. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2714. state_changed = True
  2715. # Also directly update any AMS unit already present in raw_data
  2716. if ams_raw and isinstance(ams_raw, list):
  2717. for ams_unit in ams_raw:
  2718. if not isinstance(ams_unit, dict):
  2719. continue
  2720. try:
  2721. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2722. except (ValueError, TypeError):
  2723. unit_id = None
  2724. if unit_id == ams_id:
  2725. if sw_ver:
  2726. ams_unit["sw_ver"] = sw_ver
  2727. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2728. # Only set sn from version info if not already present in AMS data
  2729. if sn and not ams_unit.get("sn"):
  2730. ams_unit["sn"] = sn
  2731. if module_type:
  2732. ams_unit["module_type"] = module_type
  2733. break
  2734. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2735. # included in the broadcast (not just the printer firmware version).
  2736. if state_changed and self.on_state_change:
  2737. self.on_state_change(self.state)
  2738. # Warn if any AMS unit is still missing serial number or firmware version
  2739. # after processing the version info response. Warn only once per connection
  2740. # to avoid repeated noise on older firmware that doesn't report these fields.
  2741. if ams_raw and isinstance(ams_raw, list):
  2742. for ams_unit in ams_raw:
  2743. if not isinstance(ams_unit, dict):
  2744. continue
  2745. ams_id = ams_unit.get("id", "?")
  2746. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2747. key = (ams_id, "sn")
  2748. if key not in self._ams_version_warned:
  2749. self._ams_version_warned.add(key)
  2750. logger.warning(
  2751. "[%s] AMS unit %s: serial number not available in version info",
  2752. self.serial_number,
  2753. ams_id,
  2754. )
  2755. if not ams_unit.get("sw_ver"):
  2756. key = (ams_id, "sw_ver")
  2757. if key not in self._ams_version_warned:
  2758. self._ams_version_warned.add(key)
  2759. logger.warning(
  2760. "[%s] AMS unit %s: firmware version not available in version info",
  2761. self.serial_number,
  2762. ams_id,
  2763. )
  2764. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2765. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2766. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2767. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2768. sw_ver/sn fields without overwriting values already present.
  2769. """
  2770. if not ams_list or not isinstance(ams_list, list):
  2771. return
  2772. cache = self._ams_version_cache
  2773. if not cache:
  2774. return
  2775. for unit in ams_list:
  2776. if not isinstance(unit, dict):
  2777. continue
  2778. raw_id = unit.get("id")
  2779. try:
  2780. unit_id = int(raw_id) if raw_id is not None else None
  2781. except (ValueError, TypeError):
  2782. unit_id = None
  2783. if unit_id is None:
  2784. continue
  2785. cached = cache.get(unit_id)
  2786. if not cached:
  2787. continue
  2788. sw_ver = cached.get("sw_ver") or ""
  2789. sn = cached.get("sn") or ""
  2790. if sw_ver and not unit.get("sw_ver"):
  2791. unit["sw_ver"] = sw_ver
  2792. # Only set sn if not already present in AMS data
  2793. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2794. unit["sn"] = sn
  2795. module_type = cached.get("module_type") or ""
  2796. if module_type and not unit.get("module_type"):
  2797. unit["module_type"] = module_type
  2798. def _parse_xcam_data(self, xcam_data):
  2799. """Parse xcam data for camera settings and AI detection options."""
  2800. if not isinstance(xcam_data, dict):
  2801. return
  2802. current_time = time.time()
  2803. # Helper to check if we should accept incoming value for a module
  2804. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2805. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2806. """Check if we should accept an incoming xcam value.
  2807. OrcaSlicer pattern: After sending a command, ignore incoming data
  2808. for 3 seconds. After that, accept whatever the printer sends.
  2809. """
  2810. if module_name not in self._xcam_hold_start:
  2811. return True # No hold timer, accept incoming
  2812. hold_start = self._xcam_hold_start[module_name]
  2813. elapsed = current_time - hold_start
  2814. if elapsed > self._xcam_hold_time:
  2815. # Hold timer expired - accept incoming and clear hold
  2816. del self._xcam_hold_start[module_name]
  2817. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2818. return True
  2819. # Within hold period - ignore incoming data
  2820. logger.debug(
  2821. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2822. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2823. )
  2824. return False
  2825. # Log all xcam fields for debugging
  2826. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2827. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2828. # fields (spaghetti_detector, etc.) are often stale/cached.
  2829. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2830. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2831. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2832. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2833. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2834. # Sensitivity values: 0=low, 1=medium, 2=high
  2835. if "cfg" in xcam_data:
  2836. cfg = xcam_data["cfg"]
  2837. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2838. def decode_detector(start_bit):
  2839. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2840. sens_bits = (cfg >> start_bit) & 0x3
  2841. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2842. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2843. return enabled, sensitivity
  2844. # Spaghetti detector (bits 5-7)
  2845. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2846. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2847. old_value = self.state.print_options.spaghetti_detector
  2848. if cfg_spaghetti != old_value:
  2849. logger.debug(
  2850. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2851. )
  2852. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2853. # Check hold timer for sensitivity before accepting
  2854. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2855. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2856. logger.debug(
  2857. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2858. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2859. )
  2860. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2861. else:
  2862. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2863. elapsed = current_time - hold_start
  2864. if elapsed <= self._xcam_hold_time:
  2865. logger.debug(
  2866. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2867. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2868. )
  2869. else:
  2870. # Hold expired - accept from cfg
  2871. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2872. logger.debug(
  2873. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2874. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2875. )
  2876. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2877. del self._xcam_hold_start["halt_print_sensitivity"]
  2878. # Pileup detector (bits 8-10)
  2879. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2880. if should_accept_value("pileup_detector", cfg_pileup):
  2881. if cfg_pileup != self.state.print_options.pileup_detector:
  2882. logger.debug(
  2883. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2884. )
  2885. self.state.print_options.pileup_detector = cfg_pileup
  2886. # Pileup sensitivity with hold timer
  2887. if "pileup_sensitivity" not in self._xcam_hold_start:
  2888. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2889. logger.debug(
  2890. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2891. )
  2892. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2893. else:
  2894. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2895. elapsed = current_time - hold_start
  2896. if elapsed > self._xcam_hold_time:
  2897. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2898. logger.debug(
  2899. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2900. )
  2901. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2902. del self._xcam_hold_start["pileup_sensitivity"]
  2903. # Clump/nozzle clumping detector (bits 11-13)
  2904. cfg_clump, cfg_clump_sens = decode_detector(11)
  2905. if should_accept_value("clump_detector", cfg_clump):
  2906. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2907. logger.debug(
  2908. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2909. )
  2910. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2911. # Clump sensitivity with hold timer
  2912. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2913. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2914. logger.debug(
  2915. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2916. )
  2917. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2918. else:
  2919. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2920. elapsed = current_time - hold_start
  2921. if elapsed > self._xcam_hold_time:
  2922. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2923. logger.debug(
  2924. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2925. )
  2926. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2927. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2928. # Airprint detector (bits 14-16)
  2929. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2930. if should_accept_value("airprint_detector", cfg_airprint):
  2931. if cfg_airprint != self.state.print_options.airprint_detector:
  2932. logger.debug(
  2933. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2934. )
  2935. self.state.print_options.airprint_detector = cfg_airprint
  2936. # Airprint sensitivity with hold timer
  2937. if "airprint_sensitivity" not in self._xcam_hold_start:
  2938. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2939. logger.debug(
  2940. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2941. )
  2942. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2943. else:
  2944. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2945. elapsed = current_time - hold_start
  2946. if elapsed > self._xcam_hold_time:
  2947. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2948. logger.debug(
  2949. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2950. )
  2951. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2952. del self._xcam_hold_start["airprint_sensitivity"]
  2953. # Camera settings
  2954. if "ipcam_record" in xcam_data:
  2955. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2956. if "timelapse" in xcam_data:
  2957. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2958. # Track if timelapse was ever active during this print
  2959. if self.state.timelapse and self._was_running:
  2960. self._timelapse_during_print = True
  2961. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2962. if "print_halt" in xcam_data:
  2963. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  2964. # Skip halt_print_sensitivity field - it's always stale ("medium")
  2965. # We read the actual sensitivity from cfg bits 5-6 above
  2966. if "first_layer_inspector" in xcam_data:
  2967. new_value = bool(xcam_data.get("first_layer_inspector"))
  2968. if should_accept_value("first_layer_inspector", new_value):
  2969. self.state.print_options.first_layer_inspector = new_value
  2970. if "printing_monitor" in xcam_data:
  2971. new_value = bool(xcam_data.get("printing_monitor"))
  2972. if should_accept_value("printing_monitor", new_value):
  2973. self.state.print_options.printing_monitor = new_value
  2974. if "buildplate_marker_detector" in xcam_data:
  2975. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  2976. if should_accept_value("buildplate_marker_detector", new_value):
  2977. self.state.print_options.buildplate_marker_detector = new_value
  2978. if "allow_skip_parts" in xcam_data:
  2979. new_value = bool(xcam_data.get("allow_skip_parts"))
  2980. if should_accept_value("allow_skip_parts", new_value):
  2981. self.state.print_options.allow_skip_parts = new_value
  2982. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  2983. # individual boolean fields (which are not sent by the printer)
  2984. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  2985. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  2986. if "auto_recovery_step_loss" in xcam_data:
  2987. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  2988. if "filament_tangle_detect" in xcam_data:
  2989. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  2990. @staticmethod
  2991. def _resolve_local_slot_from_mapping(
  2992. local_slot: int, mapping_raw: list | None, units: list[int] | None = None
  2993. ) -> int | None:
  2994. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  2995. The MQTT mapping field is an array of snow-encoded values:
  2996. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  2997. Finds entries where the local slot matches, then computes the global tray ID.
  2998. When several match and ``units`` is given (the AMS units on the active
  2999. extruder of a dual-nozzle printer), only those units' trays count.
  3000. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  3001. """
  3002. if not isinstance(mapping_raw, list) or not mapping_raw:
  3003. return None
  3004. candidates = mapped_trays_with_slot(mapping_raw, local_slot) # global tray ID -> AMS unit
  3005. if len(candidates) > 1 and units:
  3006. candidates = {tray: unit for tray, unit in candidates.items() if unit in units}
  3007. if len(candidates) == 1:
  3008. return next(iter(candidates))
  3009. return None
  3010. def _maybe_trigger_external_spool_change(self):
  3011. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  3012. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  3013. an external-spool-only filament swap would otherwise never re-run the
  3014. inventory reconciliation that unlinks a stale ams_id=255 assignment
  3015. (#2575). The reconciliation reads vt_tray from live status itself, so we
  3016. just need to re-fire the callback with the current merged AMS data.
  3017. """
  3018. import hashlib
  3019. vt_tray = self.state.raw_data.get("vt_tray")
  3020. if not isinstance(vt_tray, list):
  3021. return
  3022. # Identity fields only — deliberately exclude `remain` so a print's
  3023. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  3024. fp_parts = [
  3025. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  3026. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  3027. for vt in vt_tray
  3028. if isinstance(vt, dict)
  3029. ]
  3030. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  3031. if vt_hash == self._previous_vt_tray_hash:
  3032. return
  3033. self._previous_vt_tray_hash = vt_hash
  3034. if self.on_ams_change:
  3035. logger.debug(
  3036. "[%s] External spool (vt_tray) changed, triggering sync callback",
  3037. self.serial_number,
  3038. )
  3039. self.on_ams_change(self.state.raw_data.get("ams") or [])
  3040. def _normalize_a2l_am_units(self, ams_list) -> None:
  3041. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  3042. id 16 -> 6 in place, as early as possible, so every downstream reader —
  3043. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  3044. the DB constraint — sees the normalised id and needs no special-casing.
  3045. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  3046. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  3047. both the dict-wrapped and bare-list AMS shapes.
  3048. """
  3049. if not isinstance(ams_list, list):
  3050. return
  3051. for unit in ams_list:
  3052. if not isinstance(unit, dict):
  3053. continue
  3054. try:
  3055. uid = int(unit.get("id"))
  3056. except (TypeError, ValueError):
  3057. continue
  3058. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  3059. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  3060. if not self._has_a2l_am_unit:
  3061. logger.info(
  3062. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  3063. self.serial_number,
  3064. A2L_LITE_NORMALIZED_AMS_ID,
  3065. )
  3066. self._has_a2l_am_unit = True
  3067. @property
  3068. def tray_layout(self) -> TrayLayout:
  3069. """How this printer numbers its trays (utils.tray_ids); rebuilt only when its units change."""
  3070. raw = self.state.raw_data
  3071. units, vt_trays = raw.get("ams"), raw.get("vt_tray")
  3072. key = (
  3073. tuple((u.get("id"), u.get("info")) for u in units if isinstance(u, dict))
  3074. if isinstance(units, list)
  3075. else (),
  3076. tuple(vt.get("id") for vt in vt_trays if isinstance(vt, dict)) if isinstance(vt_trays, list) else (),
  3077. self.model,
  3078. )
  3079. if key != self._tray_layout_key:
  3080. from backend.app.utils.printer_models import has_ams3h
  3081. self._tray_layout = TrayLayout.from_state(self.state, has_ams3h(self.model))
  3082. self._tray_layout_key = key
  3083. return self._tray_layout
  3084. def _layout_with(self, ams_list: object) -> TrayLayout:
  3085. """``tray_layout`` including the units of a push not merged into the state yet."""
  3086. if not isinstance(ams_list, list) or not any(isinstance(u, dict) for u in ams_list):
  3087. return self.tray_layout
  3088. units = [u for u in ams_list if isinstance(u, dict)]
  3089. known = self.state.raw_data.get("ams")
  3090. if isinstance(known, list):
  3091. units.extend(u for u in known if isinstance(u, dict))
  3092. vt_trays = self.state.raw_data.get("vt_tray")
  3093. return TrayLayout.from_units(units, vt_trays if isinstance(vt_trays, list) else None)
  3094. def _note_rack_ams(self, layout: TrayLayout) -> None:
  3095. """Log a rack AMS the first time this connection sees it."""
  3096. for ams_id, kind in layout.rack_units:
  3097. if ams_id in self._rack_ams_logged:
  3098. continue
  3099. self._rack_ams_logged.add(ams_id)
  3100. logger.info(
  3101. "[%s] Rack AMS detected: unit %s (AMS type %s), global tray ids %s-%s",
  3102. self.serial_number,
  3103. ams_id,
  3104. int(kind),
  3105. global_tray_id(ams_id, 0, kind),
  3106. global_tray_id(ams_id, RACK_SLOT_COUNT - 1, kind),
  3107. )
  3108. def _ams3h_unit_id(self) -> int:
  3109. """The unit id of this printer's AMS 3H (32 on the H3C)."""
  3110. return next((uid for uid, kind in self.tray_layout.rack_units if kind == AmsType.ZMULTI_A), AMS3H_UNIT_ID)
  3111. def _rack_ams_type(self, ams_id: int) -> AmsType | None:
  3112. """The type of unit ``ams_id`` when it is one of this printer's rack AMS units, else None."""
  3113. for uid, kind in self.tray_layout.rack_units:
  3114. if uid == ams_id:
  3115. return kind
  3116. return None
  3117. def _parse_fila_switch(self, data: dict) -> None:
  3118. """Read the Filament Track Switch block out of a print payload — #1162.
  3119. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  3120. separate from the rest of the state update because ``_handle_ams_data``
  3121. needs the answer before it parses the AMS info bits, and that runs first.
  3122. """
  3123. if not isinstance(data.get("device"), dict):
  3124. return
  3125. fs_data = data["device"].get("fila_switch")
  3126. if not isinstance(fs_data, dict):
  3127. return
  3128. in_raw = fs_data.get("in")
  3129. out_raw = fs_data.get("out")
  3130. self.state.fila_switch = FilaSwitchState(
  3131. installed=True,
  3132. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  3133. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  3134. stat=int(fs_data.get("stat", 0) or 0),
  3135. info=int(fs_data.get("info", 0) or 0),
  3136. )
  3137. def _parse_extruder_position(self, data: dict) -> bool:
  3138. """Read which nozzle is active and which tray each nozzle holds.
  3139. From ``device.extruder``: ``state`` bit 8 is the active nozzle, each
  3140. ``info`` entry's ``snow`` names its AMS and slot. Run on a frame before
  3141. its AMS block, because an H2D's tray_now is a bare slot that only the
  3142. extruder data of the same frame places. Returns True when the frame
  3143. carried the active nozzle's snow. A malformed value is skipped, never
  3144. raised: this runs ahead of everything else the frame carries.
  3145. """
  3146. device = data.get("device")
  3147. extruder = device.get("extruder") if isinstance(device, dict) else None
  3148. if not isinstance(extruder, dict):
  3149. return False
  3150. try:
  3151. state_val = int(extruder["state"]) if "state" in extruder else None
  3152. except (TypeError, ValueError):
  3153. state_val = None
  3154. if state_val is not None:
  3155. # Extract bit 8 for extruder position
  3156. new_extruder = (state_val >> 8) & 0x1
  3157. if new_extruder != self.state.active_extruder:
  3158. logger.debug(
  3159. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  3160. )
  3161. self.state.active_extruder = new_extruder
  3162. extruder_info = extruder.get("info")
  3163. if not isinstance(extruder_info, list) or len(extruder_info) < 2:
  3164. return False
  3165. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  3166. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  3167. snow_read: set[int] = set()
  3168. for ext_info in extruder_info:
  3169. if not isinstance(ext_info, dict) or "id" not in ext_info or "snow" not in ext_info:
  3170. continue
  3171. try:
  3172. ext_id = int(ext_info["id"])
  3173. snow = int(ext_info["snow"])
  3174. except (TypeError, ValueError):
  3175. continue
  3176. if ext_id <= 1:
  3177. snow_read.add(ext_id)
  3178. # Normalize H2D snow value to global tray ID (255 = unloaded)
  3179. global_tray = 255 if snow == 0xFFFF else decode_wire_slot(snow)
  3180. if global_tray is None:
  3181. continue
  3182. if self.state.h2d_extruder_snow.get(ext_id) != global_tray:
  3183. logger.debug(
  3184. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: raw={snow} -> global tray {global_tray}"
  3185. )
  3186. self.state.h2d_extruder_snow[ext_id] = global_tray
  3187. return self.state.active_extruder in snow_read
  3188. def _parse_extruder_slots(self, data: dict) -> None:
  3189. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  3190. Absent on printers that do not report the block, in which case the
  3191. previous answer is kept rather than cleared: a partial payload carrying
  3192. only temperatures must not look like "both hotends are now empty".
  3193. """
  3194. device = data.get("device")
  3195. if not isinstance(device, dict):
  3196. return
  3197. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  3198. if not isinstance(info, list) or not info:
  3199. return
  3200. slots: dict[int, ExtruderSlot] = {}
  3201. for entry in info:
  3202. if not isinstance(entry, dict) or "id" not in entry:
  3203. continue
  3204. try:
  3205. ext_id = int(entry["id"])
  3206. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  3207. flags = int(entry.get("info", 0) or 0)
  3208. except (TypeError, ValueError):
  3209. continue
  3210. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  3211. ams_id = slot_id = None
  3212. else:
  3213. ams_id = (snow >> 8) & 0xFF
  3214. slot_id = snow & 0xFF
  3215. slots[ext_id] = ExtruderSlot(
  3216. ams_id=ams_id,
  3217. slot_id=slot_id,
  3218. has_filament=bool(flags & 0b10),
  3219. )
  3220. if slots:
  3221. self.state.extruder_slots = slots
  3222. def _handle_ams_data(self, ams_data):
  3223. """Handle AMS data changes for Spoolman integration.
  3224. This is called when we receive top-level AMS data in MQTT messages.
  3225. It detects changes and triggers the callback for Spoolman sync.
  3226. """
  3227. import hashlib
  3228. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  3229. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  3230. ams_list = None
  3231. if isinstance(ams_data, dict):
  3232. if "ams" in ams_data:
  3233. ams_list = ams_data["ams"]
  3234. self._normalize_a2l_am_units(ams_list)
  3235. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3236. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  3237. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  3238. if non_list_fields:
  3239. self._debug_on_change(
  3240. "ams_dict_fields",
  3241. non_list_fields,
  3242. "[%s] AMS dict fields: %s",
  3243. self.serial_number,
  3244. non_list_fields,
  3245. )
  3246. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  3247. # when checking if we're in filament change mode for tray_now disambiguation
  3248. if "ams_status" in ams_data:
  3249. raw_ams_status = ams_data["ams_status"]
  3250. if isinstance(raw_ams_status, str):
  3251. try:
  3252. self.state.ams_status = int(raw_ams_status)
  3253. except ValueError:
  3254. self.state.ams_status = 0
  3255. else:
  3256. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  3257. # Compute main and sub status
  3258. self.state.ams_status_sub = self.state.ams_status & 0xFF
  3259. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  3260. self._debug_on_change(
  3261. "ams_status:ams",
  3262. self.state.ams_status,
  3263. "[%s] ams_status: %s (main=%s, sub=%s)",
  3264. self.serial_number,
  3265. self.state.ams_status,
  3266. self.state.ams_status_main,
  3267. self.state.ams_status_sub,
  3268. )
  3269. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  3270. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  3271. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  3272. # next compatible slot (#2587). Stored raw here; globalised at the API
  3273. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  3274. # these are local slot numbers (0-3), not global IDs.
  3275. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  3276. if _tk in ams_data:
  3277. _raw = ams_data[_tk]
  3278. if isinstance(_raw, str):
  3279. try:
  3280. _val = int(_raw)
  3281. except ValueError:
  3282. _val = 255
  3283. else:
  3284. _val = _raw if _raw is not None else 255
  3285. prev = getattr(self.state, _attr)
  3286. setattr(self.state, _attr, _val)
  3287. # Log changes only while paused — the moment the operator cares —
  3288. # so a healthy print's normal tar churn doesn't spam the log.
  3289. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  3290. logger.info(
  3291. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  3292. self.serial_number,
  3293. _tk,
  3294. _val,
  3295. )
  3296. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  3297. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  3298. if "tray_now" in ams_data:
  3299. raw_tray_now = ams_data["tray_now"]
  3300. # Convert string to int if needed
  3301. if isinstance(raw_tray_now, str):
  3302. try:
  3303. parsed_tray_now = int(raw_tray_now)
  3304. except ValueError:
  3305. parsed_tray_now = 255
  3306. else:
  3307. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  3308. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  3309. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  3310. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  3311. # — disambiguated below using MQTT mapping field
  3312. ams_map = self.state.ams_extruder_map
  3313. # A rack AMS reports tray_now as its raw slot 0-8 (global 28 +
  3314. # slot). Its units may arrive in this same push, before the merge.
  3315. rack_layout = self._layout_with(ams_list)
  3316. self._note_rack_ams(rack_layout)
  3317. if rack_layout.rack_units and not self._is_dual_nozzle:
  3318. rack_tray = rack_layout.raw_slot_to_global(parsed_tray_now)
  3319. # 255 (nothing on the toolhead, also mid-swap) and any
  3320. # external input id are kept as reported.
  3321. self.state.tray_now = rack_tray if rack_tray is not None else parsed_tray_now
  3322. elif self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3323. # First, check if we have a pending target that matches this slot
  3324. pending_target = self.state.pending_tray_target
  3325. pending_at = self.state.pending_tray_target_at
  3326. if (
  3327. pending_target is not None
  3328. and pending_at is not None
  3329. and time.monotonic() - pending_at > PENDING_TRAY_TARGET_TTL
  3330. ):
  3331. # A load the printer refused or dropped: nothing clears
  3332. # it (tray_now stays 255), and a print loading the same
  3333. # slot number on another AMS long after was shown as
  3334. # this target (FW-C7). Fall through to the snow field.
  3335. self.state.pending_tray_target = None
  3336. self.state.pending_tray_target_at = None
  3337. pending_target = None
  3338. if pending_target is not None:
  3339. # Same slot rule as the snow branch below: an AMS-HT
  3340. # (128-135) has its one tray in slot 0.
  3341. pending_slot = 0 if is_ams_ht_id(pending_target) else pending_target % 4
  3342. if pending_slot == parsed_tray_now:
  3343. # Slot matches our pending target - use the full global ID
  3344. logger.debug(
  3345. f"[{self.serial_number}] H2D tray_now disambiguation: "
  3346. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  3347. )
  3348. self.state.tray_now = pending_target
  3349. # Clear pending target now that load is confirmed
  3350. self.state.pending_tray_target = None
  3351. else:
  3352. # Slot doesn't match our pending target - something changed, use slot as-is
  3353. logger.warning(
  3354. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  3355. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  3356. )
  3357. self.state.tray_now = parsed_tray_now
  3358. # Clear pending target since it's stale
  3359. self.state.pending_tray_target = None
  3360. else:
  3361. # No pending target - use h2d_extruder_snow for accurate disambiguation
  3362. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  3363. active_ext = self.state.active_extruder # 0=right, 1=left
  3364. # Best source: use snow value from device.extruder.info if available
  3365. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  3366. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  3367. snow_slot = (
  3368. None
  3369. if snow_tray is None
  3370. else snow_tray % 4
  3371. if snow_tray < 128
  3372. else (0 if is_ams_ht_id(snow_tray) else -1)
  3373. )
  3374. # A snow from an earlier frame may predate a swap: it
  3375. # names the tray only while it agrees with the slot.
  3376. snow_usable = (
  3377. snow_tray is not None
  3378. and snow_tray != 255
  3379. and (snow_slot == parsed_tray_now or self._snow_in_frame)
  3380. )
  3381. if snow_usable and snow_tray is not None:
  3382. # snow_tray is already normalized to global ID
  3383. if snow_slot == parsed_tray_now:
  3384. if self.state.tray_now != snow_tray:
  3385. logger.debug(
  3386. f"[{self.serial_number}] H2D tray_now from snow: "
  3387. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  3388. )
  3389. self.state.tray_now = snow_tray
  3390. else:
  3391. # Slot mismatch in one frame: the extruder's own
  3392. # report is the complete answer, trust snow
  3393. logger.debug(
  3394. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  3395. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  3396. )
  3397. self.state.tray_now = snow_tray
  3398. else:
  3399. # Fallback: snow not available, use ams_extruder_map (less reliable)
  3400. # Find ALL AMS units on the active extruder
  3401. ams_on_extruder = []
  3402. for ams_id_str, ext_id in ams_map.items():
  3403. if ext_id == active_ext:
  3404. try:
  3405. ams_on_extruder.append(int(ams_id_str))
  3406. except ValueError:
  3407. pass # Skip AMS IDs that aren't valid integers
  3408. # Several AMS (or none the map knows of) leave the
  3409. # slot ambiguous. The printer's own mapping names the
  3410. # trays the running print uses: one of them at this
  3411. # slot is the one feeding (#3242). Only while a print
  3412. # runs: an idle H2 keeps reporting the previous
  3413. # print's mapping.
  3414. mapped_tray = None
  3415. if len(ams_on_extruder) != 1 and self._was_running and not self._completion_triggered:
  3416. mapped_tray = self._resolve_local_slot_from_mapping(
  3417. parsed_tray_now, self.state.raw_data.get("mapping"), ams_on_extruder
  3418. )
  3419. if mapped_tray is not None:
  3420. if self.state.tray_now != mapped_tray:
  3421. logger.debug(
  3422. f"[{self.serial_number}] H2D tray_now: AMS {ams_on_extruder} on extruder "
  3423. f"{active_ext}, slot {parsed_tray_now} -> global ID {mapped_tray} (from mapping)"
  3424. )
  3425. self.state.tray_now = mapped_tray
  3426. elif len(ams_on_extruder) == 1:
  3427. # Single AMS on this extruder - unambiguous
  3428. active_ams_id = ams_on_extruder[0]
  3429. # AMS-HT: single slot per unit, global ID = unit ID
  3430. fallback_tray = global_tray_id(active_ams_id, parsed_tray_now)
  3431. logger.debug(
  3432. f"[{self.serial_number}] H2D tray_now fallback: "
  3433. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {fallback_tray}"
  3434. )
  3435. self.state.tray_now = fallback_tray
  3436. elif len(ams_on_extruder) > 1:
  3437. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  3438. current_tray = self.state.tray_now
  3439. # Determine which AMS unit and slot the current tray belongs to
  3440. if 0 <= current_tray <= 15 or is_ams_ht_id(current_tray):
  3441. # AMS-HT: ID = tray ID, one slot
  3442. current_ams, current_slot = rack_layout.slot_key(current_tray)
  3443. else:
  3444. current_ams = -1
  3445. current_slot = -1
  3446. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  3447. # Current is valid and matches slot - keep it
  3448. logger.debug(
  3449. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3450. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  3451. )
  3452. else:
  3453. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  3454. if parsed_tray_now > 0:
  3455. candidates = [a for a in ams_on_extruder if a <= 3]
  3456. else:
  3457. candidates = ams_on_extruder
  3458. if len(candidates) == 1:
  3459. cand = candidates[0]
  3460. resolved = global_tray_id(cand, parsed_tray_now)
  3461. logger.debug(
  3462. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3463. f"narrowed to AMS {cand} -> global ID {resolved}"
  3464. )
  3465. self.state.tray_now = resolved
  3466. else:
  3467. # Genuinely ambiguous. This is the second between a
  3468. # filament change reaching the AMS report and the
  3469. # extruder's snow, which then names the tray. Using
  3470. # the bare slot would point at AMS 0 and put that
  3471. # tray in the usage change log (#3242), so keep the
  3472. # current tray until snow arrives.
  3473. logger.debug(
  3474. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on "
  3475. f"extruder {active_ext}, slot {parsed_tray_now} is ambiguous without snow, "
  3476. f"keeping {current_tray}"
  3477. )
  3478. else:
  3479. # No AMS on this extruder that the map knows of: the
  3480. # slot can't be placed, keep the current tray (#3242)
  3481. logger.debug(
  3482. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  3483. f"slot {parsed_tray_now} can't be placed without snow, keeping {self.state.tray_now}"
  3484. )
  3485. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3486. # Single-nozzle printer with tray_now in 0-3 range.
  3487. # #1822: H2S firmware reports tray_now as the AMS's idle
  3488. # slot (typically 0) when the active feed is actually the
  3489. # external spool. X1C / P1S / A1 correctly report 254 in
  3490. # that case; H2S does not. When the slicer-captured
  3491. # ams_mapping is all-external (every entry is 254, or -1
  3492. # when the command carried no ams_mapping2 to resolve it
  3493. # from, #3166), the print can only be feeding from the
  3494. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  3495. # AMS-only mappings are NOT overridden — there's no
  3496. # evidence the firmware misreports in those cases. Prints
  3497. # started without a captured mapping (printer-screen start,
  3498. # or before Bambuddy connected) fall through unchanged.
  3499. captured = self._captured_ams_mapping
  3500. if captured and all(s in (-1, 254, 255) for s in captured):
  3501. if self.state.tray_now != 254:
  3502. logger.debug(
  3503. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  3504. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  3505. )
  3506. self.state.tray_now = 254
  3507. else:
  3508. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  3509. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  3510. # (snow-encoded) to resolve the correct AMS unit.
  3511. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  3512. try:
  3513. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  3514. except (ValueError, TypeError):
  3515. ams_exist = 0
  3516. num_ams = bin(ams_exist).count("1")
  3517. if self._has_a2l_am_unit and num_ams <= 1:
  3518. # A2L AMS-Lite (normalised unit 6): the firmware reports
  3519. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  3520. # otherwise usage tracking keys the wrong spool (it would
  3521. # deduct from AMS 0's slot). Confirmed by capture:
  3522. # tray_now="2" while printing physical slot 3.
  3523. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  3524. elif num_ams > 1:
  3525. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  3526. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  3527. if self._has_a2l_am_unit:
  3528. # A2L Lite + a regular AMS attached together is out of
  3529. # scope: the flat mapping ids are unknown for that combo
  3530. # and could collide with AMS 0. Fall through to the
  3531. # mapping-based resolve, but warn — a capture is needed.
  3532. logger.warning(
  3533. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3534. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3535. self.serial_number,
  3536. )
  3537. mapping_raw = self.state.raw_data.get("mapping")
  3538. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3539. if resolved is not None:
  3540. if resolved != parsed_tray_now:
  3541. logger.debug(
  3542. f"[{self.serial_number}] Multi-AMS tray_now: "
  3543. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3544. )
  3545. self.state.tray_now = resolved
  3546. else:
  3547. # No mapping available (not printing, or ambiguous) — use as-is.
  3548. # This matches the old behavior and is correct for AMS 0.
  3549. self.state.tray_now = parsed_tray_now
  3550. else:
  3551. # Single AMS — local slot 0-3 equals global ID
  3552. self.state.tray_now = parsed_tray_now
  3553. else:
  3554. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3555. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3556. # During filament change, the printer sends 255 first (unload), then the slot.
  3557. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3558. # Trust the printer's reported value.
  3559. self.state.tray_now = parsed_tray_now
  3560. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3561. tn = self.state.tray_now
  3562. if rack_layout.is_loaded_tray(tn):
  3563. # Log tray change for mid-print usage splitting. Gate on the
  3564. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3565. # new print, `_completion_triggered` set when on_print_complete
  3566. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3567. # firmware briefly transitions out of RUNNING during AMS
  3568. # auto-fallback (#957), so a literal-string gate misses the
  3569. # switch and the usage tracker double-credits at completion.
  3570. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3571. self.state.tray_change_log.append((tn, self.state.layer_num))
  3572. logger.info(
  3573. "[%s] Tray change during print: tray=%d at layer=%d",
  3574. self.serial_number,
  3575. tn,
  3576. self.state.layer_num,
  3577. )
  3578. if self.on_tray_change:
  3579. self.on_tray_change(tn, self.state.layer_num)
  3580. self.state.last_loaded_tray = self.state.tray_now
  3581. self._debug_on_change(
  3582. "tray_now",
  3583. self.state.tray_now,
  3584. "[%s] tray_now updated: %s",
  3585. self.serial_number,
  3586. self.state.tray_now,
  3587. )
  3588. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3589. # state when checking filament change mode for H2D disambiguation
  3590. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3591. # We've already processed the status fields above, so just return if no ams list
  3592. if ams_list is None:
  3593. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3594. return
  3595. elif isinstance(ams_data, list):
  3596. ams_list = ams_data
  3597. self._normalize_a2l_am_units(ams_list)
  3598. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3599. else:
  3600. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3601. return
  3602. # Merge AMS data instead of replacing, to handle partial updates
  3603. # During prints, the printer may only send updates for active AMS units
  3604. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3605. existing_ams = self.state.raw_data.get("ams", [])
  3606. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  3607. # Update existing units with new data, add new units
  3608. for ams_unit in ams_list:
  3609. ams_id = ams_unit.get("id")
  3610. if ams_id is not None:
  3611. existing_unit = existing_by_id.get(ams_id)
  3612. if existing_unit and "tray" in ams_unit:
  3613. # Deep merge trays to preserve fields from previous updates
  3614. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3615. merged_trays = []
  3616. for new_tray in ams_unit.get("tray", []):
  3617. tray_id = new_tray.get("id")
  3618. if tray_id is not None and tray_id in existing_trays:
  3619. # Merge: start with existing, update with new non-empty values
  3620. merged_tray = existing_trays[tray_id].copy()
  3621. # Detect slot-clearing updates (spool removal):
  3622. # When tray_type is explicitly empty, clear everything
  3623. # including RFID data (tag_uid/tray_uuid).
  3624. slot_clearing = new_tray.get("tray_type") == ""
  3625. # Some printers (e.g. H2D) only send {id, state} in
  3626. # incremental updates when a tray is not fully loaded.
  3627. # state=11 means loaded; other values (9=empty,
  3628. # 10=spool present but filament not in feeder) indicate
  3629. # the slot should be cleared. Without this, old
  3630. # tray_type/tray_color persist indefinitely (#784).
  3631. #
  3632. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3633. # tray high-temp dry box, id >= 128) reports its loaded
  3634. # tray as state=9, not 11 — it doesn't feed filament into
  3635. # a shared buffer the way a 4-slot AMS does. Applying the
  3636. # `state != 11 → empty` rule to an HT unit wiped a present
  3637. # spool on every power-on, when the printer sends a partial
  3638. # {id, state=9} for the HT tray (#2594). Skip the state
  3639. # heuristic for HT units — a genuine HT spool removal still
  3640. # clears via the explicit tray_type=="" case above and the
  3641. # tray_exist_bits cleanup below.
  3642. #
  3643. # A rack AMS (the H3C's AMS 3H) reports a loaded slot
  3644. # as state=27, so it is skipped the same way.
  3645. try:
  3646. _is_ht_unit = int(ams_id) >= 128 or is_rack_ams(
  3647. unit_ams_type(int(ams_id), ams_unit.get("info") or existing_unit.get("info"))
  3648. )
  3649. except (TypeError, ValueError):
  3650. _is_ht_unit = False
  3651. tray_state = new_tray.get("state")
  3652. if (
  3653. tray_state is not None
  3654. and tray_state != 11
  3655. and not _is_ht_unit
  3656. and "tray_type" not in new_tray
  3657. and merged_tray.get("tray_type")
  3658. ):
  3659. logger.info(
  3660. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3661. self.serial_number,
  3662. ams_id,
  3663. tray_id,
  3664. tray_state,
  3665. )
  3666. slot_clearing = True
  3667. # The incremental update only has {id, state} — inject
  3668. # empty values for all content fields so the merge loop
  3669. # below clears the stale data from merged_tray.
  3670. new_tray.update(
  3671. {
  3672. "tray_type": "",
  3673. "tray_sub_brands": "",
  3674. "tray_color": "",
  3675. "tray_id_name": "",
  3676. "tray_info_idx": "",
  3677. "tag_uid": "0000000000000000",
  3678. "tray_uuid": "00000000000000000000000000000000",
  3679. "remain": 0,
  3680. "k": None,
  3681. "cali_idx": None,
  3682. }
  3683. )
  3684. for key, value in new_tray.items():
  3685. # Fields that should always be updated (even with empty/zero values):
  3686. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3687. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3688. # tray_id_name: slot content indicators that must be cleared
  3689. # when a spool is removed (fixes #147 - old AMS empty slot)
  3690. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3691. # They are only cleared during spool removal (slot_clearing=True).
  3692. # Periodic AMS updates often include empty RFID fields which
  3693. # would overwrite valid data from the initial pushall.
  3694. always_update_fields = (
  3695. "remain",
  3696. "k",
  3697. "id",
  3698. "cali_idx",
  3699. "tray_type",
  3700. "tray_sub_brands",
  3701. "tray_info_idx",
  3702. "tray_color",
  3703. "tray_id_name",
  3704. )
  3705. if (
  3706. key in always_update_fields
  3707. or slot_clearing
  3708. or value
  3709. not in (
  3710. None,
  3711. "",
  3712. "0000000000000000",
  3713. "00000000000000000000000000000000",
  3714. )
  3715. ):
  3716. merged_tray[key] = value
  3717. merged_trays.append(merged_tray)
  3718. else:
  3719. merged_trays.append(new_tray)
  3720. # Update ams_unit with merged trays. Spread existing_unit
  3721. # FIRST so top-level fields the partial update omits —
  3722. # dry_time, info (which drives dry_status / dry_sub_status),
  3723. # humidity, temp — are preserved instead of dropped. The
  3724. # printer sends tray-bearing partials that carry no drying
  3725. # fields; without this, dry_time reads as absent → 0 and the
  3726. # falling-edge detector below fires a false "drying complete"
  3727. # (#1462). Mirrors the no-tray branch's merge semantics.
  3728. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3729. elif existing_unit:
  3730. # Partial update without tray data: merge new fields into existing
  3731. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3732. ams_unit = {**existing_unit, **ams_unit}
  3733. existing_by_id[ams_id] = ams_unit
  3734. # The merge keeps a unit the push doesn't list, so an unplugged AMS used
  3735. # to stay until Bambuddy restarted (#3356). Drop one only on the
  3736. # printer's own word that it is gone.
  3737. if isinstance(ams_data, dict):
  3738. listed = {ams_unit.get("id") for ams_unit in ams_list}
  3739. for ams_id in [i for i in existing_by_id if i not in listed]:
  3740. if unit_reported_absent(ams_id, ams_list, ams_data.get("ams_exist_bits")):
  3741. logger.info("[%s] AMS %s no longer attached, removing it", self.serial_number, ams_id)
  3742. del existing_by_id[ams_id]
  3743. # Convert back to list, sorted by ID for consistent ordering
  3744. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  3745. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3746. # Shared with the VP bridge cache so the slicer-facing view stays in
  3747. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3748. # for the full rationale and the printer-shutdown guard.
  3749. if isinstance(ams_data, dict):
  3750. apply_tray_exist_bits(
  3751. merged_ams,
  3752. ams_data.get("tray_exist_bits"),
  3753. power_on_flag=ams_data.get("power_on_flag", True),
  3754. log_label=self.serial_number,
  3755. annotate_exists=True,
  3756. )
  3757. self.state.raw_data["ams"] = merged_ams
  3758. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3759. self._apply_ams_version_cache(merged_ams)
  3760. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3761. self.state.last_ams_update = time.time()
  3762. self._debug_on_change(
  3763. "merged_ams",
  3764. (len(ams_list), len(merged_ams)),
  3765. "[%s] Merged AMS data: %s new units, %s total",
  3766. self.serial_number,
  3767. len(ams_list),
  3768. len(merged_ams),
  3769. )
  3770. # Extract ams_extruder_map from each AMS unit's info field
  3771. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3772. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3773. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3774. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3775. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3776. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3777. #
  3778. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3779. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3780. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3781. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3782. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3783. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3784. # the switch being installed.
  3785. #
  3786. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3787. # the full map. Merge into existing map to preserve entries from prior updates.
  3788. fts_installed = self.state.fila_switch.installed
  3789. inlet_moves: list[tuple[int, str]] = []
  3790. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3791. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3792. # A rack AMS feeds the one extruder of a rack printer; listed here it
  3793. # would make the slot/dispatch code assume two nozzles.
  3794. rack_ams_ids = {uid for uid, _ in TrayLayout.from_units(merged_ams).rack_units}
  3795. for ams_unit in merged_ams:
  3796. ams_id = ams_unit.get("id")
  3797. info = ams_unit.get("info")
  3798. if _mqtt_int(ams_id) in rack_ams_ids:
  3799. continue
  3800. if ams_id is not None and info is not None:
  3801. try:
  3802. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3803. info_val = int(str(info), 16)
  3804. # Extract 4 bits starting at bit 8 for extruder assignment
  3805. extruder_id = (info_val >> 8) & 0xF
  3806. if extruder_id == 0xE:
  3807. if fts_installed:
  3808. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3809. if inlet is not None:
  3810. previous = ams_switch_inlet.get(str(ams_id))
  3811. ams_switch_inlet[str(ams_id)] = inlet
  3812. self._debug_on_change(
  3813. f"ams_inlet:{ams_id}",
  3814. inlet,
  3815. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3816. self.serial_number,
  3817. ams_id,
  3818. info,
  3819. inlet,
  3820. )
  3821. if previous is not None and previous != inlet:
  3822. # Only a genuine move, never the first sighting:
  3823. # re-applying K-profiles on every reconnect would
  3824. # fight a binding the operator set deliberately.
  3825. logger.info(
  3826. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3827. self.serial_number,
  3828. ams_id,
  3829. inlet,
  3830. previous,
  3831. )
  3832. inlet_moves.append((int(ams_id), inlet))
  3833. continue
  3834. ams_extruder_map[str(ams_id)] = extruder_id
  3835. self._debug_on_change(
  3836. f"ams_info:{ams_id}",
  3837. (info, extruder_id),
  3838. "[%s] AMS %s info=0x%s -> extruder %s",
  3839. self.serial_number,
  3840. ams_id,
  3841. info,
  3842. extruder_id,
  3843. )
  3844. except (ValueError, TypeError):
  3845. pass # Skip AMS units with unparseable info bitmask values
  3846. if ams_extruder_map:
  3847. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3848. self.state.ams_extruder_map = ams_extruder_map
  3849. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3850. if ams_switch_inlet:
  3851. self.state.ams_switch_inlet = ams_switch_inlet
  3852. for moved_ams_id, moved_inlet in inlet_moves:
  3853. if self.on_fts_inlet_change:
  3854. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3855. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3856. # BambuStudio DevFilaSystem.cpp parses info bits:
  3857. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3858. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3859. for ams_unit in merged_ams:
  3860. info = ams_unit.get("info")
  3861. if info is not None:
  3862. try:
  3863. info_val = int(str(info), 16)
  3864. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3865. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3866. except (ValueError, TypeError):
  3867. pass # Skip unparseable info values
  3868. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3869. if "dry_sf_reason" in ams_unit:
  3870. sf_reason = ams_unit["dry_sf_reason"]
  3871. if isinstance(sf_reason, list):
  3872. ams_unit["dry_sf_reason"] = [
  3873. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3874. ]
  3875. else:
  3876. ams_unit["dry_sf_reason"] = []
  3877. # Persist updated drying fields back to raw_data
  3878. self.state.raw_data["ams"] = merged_ams
  3879. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3880. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3881. # — fire the callback so smart-plug auto-off-after-drying can run,
  3882. # and drop our cached target-cycle params so the badge stops claiming
  3883. # an active cycle. Works identically for queue-triggered, ambient,
  3884. # and manual drying because we observe the firmware-reported state.
  3885. for ams_unit in merged_ams:
  3886. try:
  3887. ams_id = int(ams_unit.get("id", -1))
  3888. except (TypeError, ValueError):
  3889. continue
  3890. if ams_id < 0:
  3891. continue
  3892. # The firmware phase outranks the stalled-countdown heuristic even
  3893. # on a transient-zero frame, which the completion guard below skips.
  3894. # Clear a previously raised flag before that early continue.
  3895. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3896. ams_unit["dry_countdown_stalled"] = False
  3897. # Only evaluate the edge when this update carries an explicit
  3898. # dry_time. An absent / unparseable value is NOT zero — treating
  3899. # it as 0 lets a tray-only partial fake a drying-complete edge
  3900. # (#1462). Skip without touching the remembered value so the
  3901. # next update that DOES carry dry_time sees the true previous.
  3902. raw_dry_time = ams_unit.get("dry_time")
  3903. if raw_dry_time is None:
  3904. continue
  3905. try:
  3906. current = int(raw_dry_time)
  3907. except (TypeError, ValueError):
  3908. continue
  3909. # A dry_time of 0 only means "finished" when the unit also reports
  3910. # an idle phase. Between the command ack and the countdown settling
  3911. # the firmware publishes a transient 0 while the AMS is still
  3912. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3913. # 12-hour cycle. Taking that at face value dropped the cached target
  3914. # (leaving the badge to guess the filament from tray 1, so a PLA
  3915. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3916. # schedules smart-plug auto-off. dry_status comes from the same info
  3917. # hex parsed above; when it is absent we let the edge through, so a
  3918. # firmware that never reports one still ends its cycles.
  3919. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3920. # Leave the remembered value alone, exactly as the absent-
  3921. # dry_time skip above does: whichever push ends the cycle for
  3922. # real must still see a non-zero previous.
  3923. logger.debug(
  3924. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3925. self.serial_number,
  3926. ams_id,
  3927. ams_unit.get("dry_status"),
  3928. )
  3929. continue
  3930. seen_before = ams_id in self._previous_dry_times
  3931. previous = self._previous_dry_times.get(ams_id, 0)
  3932. self._previous_dry_times[ams_id] = current
  3933. if current > 0:
  3934. cycle = self._dry_cycles.get(ams_id)
  3935. if cycle is None or previous == 0:
  3936. cycle = {
  3937. "peak": current,
  3938. # A rise from an observed 0 is the cycle's first minute.
  3939. # A first sighting already counting down is not.
  3940. "start_seen": seen_before,
  3941. "target": self._drying_targets.get(ams_id),
  3942. }
  3943. self._dry_cycles[ams_id] = cycle
  3944. elif current > int(cycle["peak"]):
  3945. cycle["peak"] = current
  3946. # Stall detection: stamp value CHANGES only — a live countdown
  3947. # decrements once a minute, so repeats of the same value within
  3948. # the minute must not refresh the stamp, and a frame without a
  3949. # dry_time never reaches here (the absent-value skip above).
  3950. now_mono = time.monotonic()
  3951. if current != previous or ams_id not in self._dry_time_changed_at:
  3952. self._dry_time_changed_at[ams_id] = now_mono
  3953. ams_unit["dry_countdown_stalled"] = bool(
  3954. current > 0
  3955. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  3956. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  3957. )
  3958. if previous > 0 and current == 0:
  3959. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  3960. if self.on_drying_complete:
  3961. self.on_drying_complete(ams_id)
  3962. cycle = self._dry_cycles.pop(ams_id, None) or {"peak": previous, "start_seen": False, "target": None}
  3963. if self.on_drying_cycle_end:
  3964. self.on_drying_cycle_end(self._drying_cycle_end(ams_id, previous, cycle))
  3965. # Create a hash of relevant AMS data to detect changes.
  3966. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  3967. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  3968. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  3969. # above but leaves the raw payload's tracked fields untouched — so a
  3970. # raw-based hash never flips and on_ams_change never fires, leaving the
  3971. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  3972. # always spans every unit, so a partial single-unit update can't produce a
  3973. # spuriously different hash from a full pushall.
  3974. ams_hash_data = []
  3975. for ams_unit in merged_ams:
  3976. for tray in ams_unit.get("tray", []):
  3977. # Include fields that matter for filament tracking
  3978. ams_hash_data.append(
  3979. f"{ams_unit.get('id')}:{tray.get('id')}:"
  3980. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  3981. )
  3982. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  3983. # Only trigger callback if AMS data actually changed
  3984. if ams_hash != self._previous_ams_hash:
  3985. self._previous_ams_hash = ams_hash
  3986. if self.on_ams_change:
  3987. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  3988. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  3989. # may lack fields like 'remain' that the merged state preserves
  3990. self.on_ams_change(merged_ams)
  3991. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  3992. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  3993. # or cali_idx — so an assignment that only swaps the filament id on an
  3994. # already-loaded slot would not flip the hash, and gating the check on
  3995. # it would miss exactly the confirmation we are after.
  3996. if self._pending_assignments:
  3997. self._check_assignment_verifications()
  3998. @staticmethod
  3999. def _drying_cycle_end(ams_id: int, remaining: int, cycle: dict[str, object]) -> DryingCycleEnd:
  4000. """Build the cycle-end report from the record kept while it ran."""
  4001. target = cycle.get("target")
  4002. target_temp: int | None = None
  4003. target_hours: int | None = None
  4004. if isinstance(target, dict):
  4005. try:
  4006. target_temp = int(target.get("temp") or 0) or None
  4007. target_hours = int(target.get("duration_hours") or 0) or None
  4008. except (TypeError, ValueError):
  4009. target_temp = target_hours = None
  4010. return DryingCycleEnd(
  4011. ams_id=ams_id,
  4012. remaining_minutes=remaining,
  4013. peak_minutes=max(int(cycle.get("peak") or 0), remaining),
  4014. start_seen=bool(cycle.get("start_seen")),
  4015. target_temp=target_temp,
  4016. target_hours=target_hours,
  4017. )
  4018. def _log_drying_cycle_end(
  4019. self,
  4020. ams_id: int,
  4021. remaining: int,
  4022. ams_unit: dict,
  4023. target: dict[str, object] | None,
  4024. ) -> None:
  4025. """Report a finished drying cycle, with the firmware's reason when it was
  4026. cut short (#2770).
  4027. A cycle that reaches its configured duration needs no explanation and
  4028. keeps the one-line "drying complete" it has always had. One that ends
  4029. with most of its countdown left was ended by somebody, and there are
  4030. only two candidates: a stop Bambuddy sent — the print-takes-priority
  4031. stop, or the user's Stop button — which is named as such, or the
  4032. firmware.
  4033. For the firmware case the only account of why lives in fields we already
  4034. parse but have never written down: the ``dry_status`` /
  4035. ``dry_sub_status`` phase from the info hex, the per-unit
  4036. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  4037. that moment. Logging them at INFO puts them in every support bundle by
  4038. default, which is what a report like #2770 needs before its cause can be
  4039. argued about at all.
  4040. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  4041. logged for every cycle, early or not, because they are what decides
  4042. whether auto-drying re-arms. Reconstructing them for #2770 meant
  4043. cross-referencing hourly alarm lines against 30-second scheduler debug
  4044. that was switched off at the time; one line here says it outright — a
  4045. cycle ending at 63 degC with the reading still above the threshold is
  4046. the whole shape of the re-arm loop.
  4047. """
  4048. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  4049. if ams_id in self._drying_stops_sent:
  4050. self._drying_stops_sent.discard(ams_id)
  4051. logger.info(
  4052. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  4053. self.serial_number,
  4054. ams_id,
  4055. remaining,
  4056. box,
  4057. )
  4058. return
  4059. if remaining <= _EARLY_DRY_END_MINUTES:
  4060. logger.info(
  4061. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  4062. self.serial_number,
  4063. ams_id,
  4064. remaining,
  4065. box,
  4066. )
  4067. return
  4068. requested_minutes: int | None = None
  4069. if target is not None:
  4070. try:
  4071. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  4072. except (TypeError, ValueError):
  4073. requested_minutes = None
  4074. logger.info(
  4075. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  4076. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  4077. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  4078. self.serial_number,
  4079. ams_id,
  4080. remaining,
  4081. requested_minutes if requested_minutes is not None else "?",
  4082. ams_unit.get("dry_status"),
  4083. ams_unit.get("dry_sub_status"),
  4084. ams_unit.get("dry_sf_reason") or [],
  4085. [e.full_code for e in self.state.hms_errors] or "none",
  4086. box,
  4087. )
  4088. def register_assignment_verification(
  4089. self,
  4090. ams_id: int,
  4091. tray_id: int,
  4092. tray_info_idx: str,
  4093. tray_color: str,
  4094. cali_idx: int | None,
  4095. ) -> None:
  4096. """Record an assignment we just pushed so subsequent AMS telemetry can
  4097. confirm the tray actually accepted it (#2582).
  4098. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  4099. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  4100. accepted filament id back in the per-tray push, so a match means the
  4101. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  4102. signal so we can specifically flag "filament loaded but K-profile not
  4103. applied", which is the exact symptom the reporter chased via flow-cal.
  4104. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  4105. there is nothing to verify and no record is stored.
  4106. """
  4107. want_idx = (tray_info_idx or "").strip().upper()
  4108. if not want_idx:
  4109. return
  4110. self._pending_assignments[(ams_id, tray_id)] = {
  4111. "tray_info_idx": want_idx,
  4112. "tray_color": (tray_color or "").strip().upper(),
  4113. "cali_idx": cali_idx,
  4114. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  4115. "last_seen_idx": None,
  4116. }
  4117. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  4118. """Locate the live tray dict for a pending verification.
  4119. External spools (ams_id 255) live in ``vt_tray`` under global ids
  4120. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  4121. report a single tray whose id may not equal the logical tray_id, so fall
  4122. back to the sole tray when an id match fails.
  4123. """
  4124. raw = self.state.raw_data or {}
  4125. if ams_id == 255:
  4126. want_ext = external_tray_id(tray_id)
  4127. for vt in raw.get("vt_tray", []) or []:
  4128. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  4129. return vt
  4130. return None
  4131. for unit in raw.get("ams", []) or []:
  4132. if str(unit.get("id")) != str(ams_id):
  4133. continue
  4134. trays = unit.get("tray", []) or []
  4135. for tray in trays:
  4136. if str(tray.get("id")) == str(tray_id):
  4137. return tray
  4138. if ams_id >= 128 and len(trays) == 1:
  4139. return trays[0]
  4140. return None
  4141. return None
  4142. def _check_assignment_verifications(self) -> None:
  4143. """Compare each pending assignment against live tray telemetry and fire
  4144. ``on_assignment_verified`` on a match or once the deadline passes.
  4145. Runs on every AMS push. Non-matching-but-still-within-window entries are
  4146. left in place for the next push. The timeout branch only fires when a
  4147. later push arrives after the deadline; if the printer goes silent we
  4148. simply never confirm, which is preferable to inventing a failure.
  4149. """
  4150. now = time.monotonic()
  4151. for key, want in list(self._pending_assignments.items()):
  4152. ams_id, tray_id = key
  4153. tray = self._find_verify_tray(ams_id, tray_id)
  4154. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  4155. if tray is not None and actual_idx:
  4156. want["last_seen_idx"] = actual_idx
  4157. if actual_idx and actual_idx == want["tray_info_idx"]:
  4158. self._pending_assignments.pop(key, None)
  4159. kprofile_applied = True
  4160. want_cali = want.get("cali_idx")
  4161. if want_cali is not None and want_cali >= 0:
  4162. actual_cali = tray.get("cali_idx")
  4163. kprofile_applied = actual_cali == want_cali
  4164. self._fire_assignment_verified(
  4165. ams_id,
  4166. tray_id,
  4167. True,
  4168. {
  4169. "tray_info_idx": actual_idx,
  4170. "kprofile_applied": kprofile_applied,
  4171. },
  4172. )
  4173. elif now >= want["deadline"]:
  4174. self._pending_assignments.pop(key, None)
  4175. self._fire_assignment_verified(
  4176. ams_id,
  4177. tray_id,
  4178. False,
  4179. {
  4180. "expected_tray_info_idx": want["tray_info_idx"],
  4181. "actual_tray_info_idx": want.get("last_seen_idx"),
  4182. # True when we saw the tray at least once (so the push
  4183. # channel is alive and the printer really stored a
  4184. # different/blank id) vs never observing it at all.
  4185. "saw_tray": want.get("last_seen_idx") is not None,
  4186. },
  4187. )
  4188. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  4189. if verified:
  4190. logger.info(
  4191. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  4192. self.serial_number,
  4193. ams_id,
  4194. tray_id,
  4195. detail.get("tray_info_idx"),
  4196. detail.get("kprofile_applied"),
  4197. )
  4198. else:
  4199. logger.warning(
  4200. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  4201. self.serial_number,
  4202. ams_id,
  4203. tray_id,
  4204. detail.get("expected_tray_info_idx"),
  4205. detail.get("actual_tray_info_idx"),
  4206. detail.get("saw_tray"),
  4207. )
  4208. if self.on_assignment_verified:
  4209. try:
  4210. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  4211. except Exception:
  4212. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  4213. @staticmethod
  4214. def _probe_number(value, fallback: float | None = None) -> float | None:
  4215. """Coerce a telemetry field to a number, or return `fallback`.
  4216. Firmware is inconsistent about whether these arrive as ints or as
  4217. numeric strings, and the probe must never raise on a surprise type.
  4218. """
  4219. try:
  4220. return float(value)
  4221. except (TypeError, ValueError):
  4222. return fallback
  4223. def _probe_end_of_print(self, data: dict) -> None:
  4224. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  4225. Opens on the first frame that looks like end-of-print (last object
  4226. layer reached, progress at 99+, or no remaining time), then logs each
  4227. frame in which any probed field changed, and closes on the transition
  4228. out of RUNNING. Armed once per print — see the module-level comment on
  4229. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  4230. currently see into.
  4231. Read-only with respect to printer state: this is instrumentation, and
  4232. nothing downstream may come to depend on it.
  4233. """
  4234. if not logger.isEnabledFor(logging.DEBUG):
  4235. return
  4236. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  4237. return
  4238. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  4239. if not present:
  4240. return
  4241. if not self._eop_probe_open:
  4242. # Open on any end-of-print signal. Read from the raw frame first so
  4243. # the frame that *carries* the signal is itself captured — state
  4244. # fields are only updated further down this same call.
  4245. frame_layer = data.get("layer_num")
  4246. if self._is_stale_layer(frame_layer):
  4247. frame_layer = None
  4248. layer = self._probe_number(frame_layer, self.state.layer_num) or 0
  4249. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  4250. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  4251. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  4252. at_last_layer = total > 0 and layer >= total
  4253. # `remaining <= 0` is only meaningful once the print has actually
  4254. # progressed — it reads 0 during the pre-print calibration too.
  4255. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  4256. if not (at_last_layer or percent >= 99 or out_of_time):
  4257. return
  4258. self._eop_probe_open = True
  4259. self._eop_probe_frames = 0
  4260. self._eop_probe_last = {}
  4261. logger.debug(
  4262. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  4263. self.serial_number,
  4264. layer,
  4265. total,
  4266. percent,
  4267. remaining,
  4268. )
  4269. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  4270. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  4271. self._eop_probe_last.update(present)
  4272. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  4273. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  4274. self._eop_probe_frames += 1
  4275. logger.debug(
  4276. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  4277. self.serial_number,
  4278. _END_OF_PRINT_PROBE_MAX_FRAMES,
  4279. )
  4280. return
  4281. if changed or closing:
  4282. self._eop_probe_frames += 1
  4283. logger.debug(
  4284. "[%s] EOP-PROBE %s%s: %s",
  4285. self.serial_number,
  4286. self._eop_probe_frames,
  4287. " CLOSE" if closing else "",
  4288. # `changed` on a closing frame can be empty; fall back to the
  4289. # full picture so the last line is always self-contained.
  4290. changed if changed else present,
  4291. )
  4292. if closing:
  4293. self._eop_probe_open = False
  4294. self._eop_probe_armed = False
  4295. self._eop_probe_last = {}
  4296. @property
  4297. def layer_before_new_print(self) -> int:
  4298. """The layer the printer was on when a print start was detected, until
  4299. it reports another (#3317); 0 when none.
  4300. For a print that is resumed rather than new, which a restart while it
  4301. was paused makes look new, that is the layer it is still on (#2984).
  4302. """
  4303. return self._stale_layer_num
  4304. def _is_stale_layer(self, value) -> bool:
  4305. """Whether a frame's `layer_num` is the previous print's last layer (#3317)."""
  4306. if not self._stale_layer_num:
  4307. return False
  4308. try:
  4309. return int(value) == self._stale_layer_num
  4310. except (TypeError, ValueError):
  4311. return False
  4312. def _update_state(self, data: dict):
  4313. """Update printer state from message data."""
  4314. _previous_state = self.state.state
  4315. # #2547: instrumentation only — runs before any state mutation so the
  4316. # frame carrying an end-of-print signal is logged as it arrived.
  4317. try:
  4318. self._probe_end_of_print(data)
  4319. except Exception: # pragma: no cover - a probe must never break ingest
  4320. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  4321. # Update state fields
  4322. if "gcode_state" in data:
  4323. self.state.state = data["gcode_state"]
  4324. if "gcode_file" in data:
  4325. self.state.gcode_file = data["gcode_file"]
  4326. self.state.current_print = data["gcode_file"]
  4327. # The answer to a print start the printer refused names the job it
  4328. # refused, not one it runs: read as status, its job id told the start
  4329. # watchdog the file had landed.
  4330. refused_start = (
  4331. data.get("command") == "project_file"
  4332. and data.get("result") is not None
  4333. and str(data["result"]).upper() != "SUCCESS"
  4334. )
  4335. if "subtask_name" in data and not refused_start:
  4336. self.state.subtask_name = data["subtask_name"]
  4337. # Prefer subtask_name as current_print if available
  4338. if data["subtask_name"]:
  4339. self.state.current_print = data["subtask_name"]
  4340. if "subtask_id" in data and not refused_start:
  4341. self.state.subtask_id = data["subtask_id"]
  4342. if "mc_percent" in data:
  4343. # Billing: retain this frame's latest positive value immediately.
  4344. # A display-side abort may be the very next frame (and may omit
  4345. # mc_percent entirely), so retaining only the previous frame can
  4346. # lose the only usable estimate for proportional charging.
  4347. previous_progress = self.state.progress
  4348. new_progress = float(data["mc_percent"])
  4349. if new_progress > 0:
  4350. self._last_valid_progress = new_progress
  4351. self.state.progress = new_progress
  4352. # #2547: strictly-increasing only. The firmware resets progress to 0
  4353. # on cancel and re-reports the same percent on most frames; neither
  4354. # is the print advancing, and both would make the frame bank grab a
  4355. # camera frame for nothing.
  4356. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  4357. self.on_print_progress(int(self.state.progress))
  4358. if "mc_remaining_time" in data:
  4359. self.state.remaining_time = int(data["mc_remaining_time"])
  4360. if "mc_print_sub_stage" in data:
  4361. new_sub_stage = int(data["mc_print_sub_stage"])
  4362. if new_sub_stage != self.state.mc_print_sub_stage:
  4363. logger.debug(
  4364. f"[{self.serial_number}] mc_print_sub_stage changed: "
  4365. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  4366. )
  4367. self.state.mc_print_sub_stage = new_sub_stage
  4368. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  4369. # front because three places below consult it and they run in an order
  4370. # that is not the order they read most naturally in: the layer-advance
  4371. # refresh (#2702) must not fire on a frame that already answers it, the
  4372. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  4373. # reset must not discard a total that belongs to the starting print.
  4374. total_from_this_frame = 0
  4375. if "total_layer_num" in data:
  4376. try:
  4377. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  4378. except (TypeError, ValueError):
  4379. # Must not escape. `_on_message` catches only JSONDecodeError
  4380. # and paho is left at `suppress_exceptions = False`, so an
  4381. # exception raised here is re-raised on the network thread and
  4382. # takes the printer connection down over one unusable field.
  4383. # Treat it as "not reported": the refresh below then recovers
  4384. # the real total from a pushall.
  4385. logger.debug(
  4386. "[%s] ignoring unusable total_layer_num: %r",
  4387. self.serial_number,
  4388. data["total_layer_num"],
  4389. )
  4390. if "layer_num" in data:
  4391. try:
  4392. new_layer = int(data["layer_num"])
  4393. except (TypeError, ValueError):
  4394. # Contained for the same reason as `total_layer_num` above: an
  4395. # exception raised here escapes `_update_state` and paho
  4396. # re-raises it on the network thread. Losing this frame would
  4397. # also lose the print-start and completion detection further
  4398. # down, which is worse than losing a layer number.
  4399. #
  4400. # Held at the last known layer rather than substituted with 0:
  4401. # a fabricated 0 reads as the firmware's cancel reset, which
  4402. # would move `_last_valid_layer_num` and show layer 0 in the UI
  4403. # until the next good frame.
  4404. logger.debug(
  4405. "[%s] ignoring unusable layer_num: %r",
  4406. self.serial_number,
  4407. data["layer_num"],
  4408. )
  4409. new_layer = self.state.layer_num
  4410. if self._is_stale_layer(new_layer):
  4411. logger.debug(
  4412. "[%s] ignoring layer_num %s: last layer of the previous print",
  4413. self.serial_number,
  4414. new_layer,
  4415. )
  4416. new_layer = self.state.layer_num
  4417. elif new_layer > 0:
  4418. # The new print reports a layer of its own; from here on the
  4419. # previous print's value is a layer this print can reach.
  4420. self._stale_layer_num = 0
  4421. old_layer = self.state.layer_num
  4422. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  4423. if old_layer > 0:
  4424. self._last_valid_layer_num = old_layer
  4425. self.state.layer_num = new_layer
  4426. # Trigger layer change callback if layer increased
  4427. if new_layer > old_layer and self.on_layer_change:
  4428. self.on_layer_change(new_layer)
  4429. # #2702: the print is demonstrably laying down layers but we still
  4430. # have no denominator, so the pushall requested at print start
  4431. # either went unanswered or raced the printer learning the total.
  4432. # Ask once more — by layer 1 the printer definitely knows it.
  4433. # One-shot: an unanswered pushall must not turn into a per-layer
  4434. # retry loop for the rest of the print.
  4435. if (
  4436. new_layer > old_layer
  4437. and self._total_layers_refresh_armed
  4438. and not self.state.total_layers
  4439. and not total_from_this_frame
  4440. ):
  4441. self._total_layers_refresh_armed = False
  4442. logger.debug(
  4443. "[%s] layer %s with no total_layer_num — re-requesting full status",
  4444. self.serial_number,
  4445. new_layer,
  4446. )
  4447. self._request_push_all()
  4448. # #2547: there is deliberately NO finish-photo trigger on the
  4449. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  4450. # moment the printer *starts* the final layer, not the moment it
  4451. # finishes it — on the H2C capture that closed #2547 the edge
  4452. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  4453. # filament change before the print actually ended, so the photo
  4454. # showed the toolhead mid-print over the part. Worse, the trigger
  4455. # latched `_finish_photo_captured`, locking out both the stage-22
  4456. # and FINISH triggers below for the rest of the print.
  4457. #
  4458. # #1867 (End G-code ejects the plate before FINISH) is handled
  4459. # where it belongs instead: `on_finish_photo_moment` prefers the
  4460. # in-print frame bank when the dispatcher recorded that it injected
  4461. # End G-code into this print. See services/print_dispatch_context.
  4462. if total_from_this_frame:
  4463. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  4464. # end — same shape as the `layer_num` reset guarded above. Applying
  4465. # only positive values preserves the last known good denominator so
  4466. # the usage-tracker split path (#1771) survives the reset frame.
  4467. self.state.total_layers = total_from_this_frame
  4468. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  4469. # Convert to 0-100 percentage for display
  4470. def parse_fan_speed(value: str | int | None) -> int | None:
  4471. if value is None:
  4472. return None
  4473. try:
  4474. speed = int(value)
  4475. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  4476. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  4477. if speed <= 15:
  4478. return round(speed * 100 / 15)
  4479. # If already a percentage (0-255 scale from some printers), convert
  4480. elif speed <= 255:
  4481. return round(speed * 100 / 255)
  4482. return speed
  4483. except (ValueError, TypeError):
  4484. return None
  4485. # Log fan fields once for debugging
  4486. if not hasattr(self, "_fan_fields_logged"):
  4487. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  4488. if fan_fields:
  4489. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  4490. self._fan_fields_logged = True
  4491. if "cooling_fan_speed" in data:
  4492. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  4493. if "big_fan1_speed" in data:
  4494. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  4495. if "big_fan2_speed" in data:
  4496. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  4497. if "heatbreak_fan_speed" in data:
  4498. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  4499. # Calibration stage tracking
  4500. if "stg_cur" in data:
  4501. new_stg = data["stg_cur"]
  4502. prev_stg = self.state.stg_cur
  4503. # Always log ANY stg_cur change for debugging filament operations
  4504. if new_stg != prev_stg:
  4505. logger.debug(
  4506. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  4507. )
  4508. # A stage we cannot name is the one worth seeing at the default
  4509. # log level: the DEBUG line above is off in normal running, so
  4510. # an unnamed stage otherwise reaches the user as "Unknown stage
  4511. # (72)" on a card with nothing behind it to say when it
  4512. # happened or what the printer was doing. Recorded once per
  4513. # stage number per session, with the stage it came from and the
  4514. # print state, which is what naming it later needs. Guarded on
  4515. # the int type because the field is whatever the firmware sent.
  4516. if (
  4517. isinstance(new_stg, int)
  4518. and not isinstance(new_stg, bool)
  4519. # -1 is Bambuddy's own "not in a stage" sentinel and the
  4520. # initial value of the field, not something the firmware
  4521. # reports; every print would otherwise report it on the way
  4522. # out of its last real stage.
  4523. and new_stg != -1
  4524. and new_stg not in STAGE_NAMES
  4525. and new_stg not in self._unnamed_stages_seen
  4526. ):
  4527. self._unnamed_stages_seen.add(new_stg)
  4528. logger.info(
  4529. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  4530. "state=%s progress=%s%% layer=%s/%s",
  4531. self.serial_number,
  4532. new_stg,
  4533. self.model,
  4534. prev_stg,
  4535. get_stage_name(prev_stg),
  4536. self.state.state,
  4537. self.state.progress,
  4538. self.state.layer_num,
  4539. self.state.total_layers,
  4540. )
  4541. self.state.stg_cur = new_stg
  4542. # #1721 end-of-print finish photo trigger.
  4543. # Stage 22 = "Filament unloading" fires at end-of-print AND
  4544. # during mid-print color swaps. The end-of-print gate
  4545. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  4546. # — those signals only line up at the real end. Edge-only
  4547. # (prev != 22) so the trigger fires once per stage entry.
  4548. if (
  4549. new_stg == 22
  4550. and prev_stg != 22
  4551. and self._was_running
  4552. and not self._finish_photo_captured
  4553. and self.on_finish_photo_moment
  4554. ):
  4555. progress = self.state.progress or 0.0
  4556. layer_num = self.state.layer_num or 0
  4557. total_layers = self.state.total_layers or 0
  4558. remaining = self.state.remaining_time or 0
  4559. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  4560. if is_end_of_print:
  4561. self._finish_photo_captured = True
  4562. logger.info(
  4563. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  4564. f"progress={progress}, layer={layer_num}/{total_layers}, "
  4565. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  4566. )
  4567. self.on_finish_photo_moment(
  4568. {
  4569. "trigger": "stage_22",
  4570. "filename": self._previous_gcode_file or self.state.gcode_file,
  4571. "subtask_name": self.state.subtask_name,
  4572. "timelapse_was_active": self._timelapse_during_print,
  4573. }
  4574. )
  4575. if "stg" in data:
  4576. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  4577. # Temperature data
  4578. temps = {}
  4579. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  4580. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  4581. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  4582. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  4583. # Log ALL keys in print data for H2D temperature discovery
  4584. all_keys = sorted(data.keys())
  4585. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  4586. self._temp_fields_logged = True
  4587. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  4588. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  4589. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  4590. self._vir_slot_logged = True
  4591. # Log nozzle hardware info fields (once)
  4592. nozzle_fields = {
  4593. k: v
  4594. for k, v in data.items()
  4595. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  4596. }
  4597. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  4598. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  4599. self._nozzle_fields_logged = True
  4600. # Parse active extruder from device.extruder.state bit 8
  4601. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  4602. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  4603. if "device" in data and isinstance(data.get("device"), dict):
  4604. device = data["device"]
  4605. # One-shot identification probe: surface whatever the firmware uses to
  4606. # name itself so an unknown model in a support bundle becomes self-
  4607. # diagnosing. INFO level so it shows up without debug logging. Falls
  4608. # back to dumping device.keys() if none of the known fields are present
  4609. # (so a future Bambu rename like `model_name` is still observable).
  4610. if not getattr(self, "_device_id_logged", False):
  4611. id_fields = {
  4612. k: device.get(k)
  4613. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  4614. if k in device
  4615. }
  4616. if id_fields:
  4617. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  4618. else:
  4619. logger.info(
  4620. "[%s] Device identification: no known id fields; device.keys=%s",
  4621. self.serial_number,
  4622. sorted(device.keys()),
  4623. )
  4624. self._device_id_logged = True
  4625. self._parse_extruder_position(data)
  4626. # Log device.extruder structure for active extruder
  4627. if "device" in data and isinstance(data.get("device"), dict):
  4628. device = data["device"]
  4629. if "extruder" in device:
  4630. ext_data = device["extruder"]
  4631. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4632. if "state" in ext_data:
  4633. state_val = ext_data["state"]
  4634. # Extract bits 12-14 (3 bits) for switch state
  4635. switch_state = (state_val >> 12) & 0x7
  4636. self._debug_on_change(
  4637. "extruder_state",
  4638. state_val,
  4639. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4640. self.serial_number,
  4641. state_val,
  4642. switch_state,
  4643. )
  4644. # Log 'cur' field if present (might indicate current/active extruder)
  4645. if "cur" in ext_data:
  4646. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4647. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4648. # it first. Repeated here so _update_state stays a complete "absorb this
  4649. # payload" step for any other caller; re-parsing the same block is free.
  4650. self._parse_fila_switch(data)
  4651. self._parse_extruder_slots(data)
  4652. if "bed_temper" in data:
  4653. temps["bed"] = float(data["bed_temper"])
  4654. if "bed_target_temper" in data:
  4655. temps["bed_target"] = float(data["bed_target_temper"])
  4656. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4657. has_h2d_extruder_info = (
  4658. "device" in data
  4659. and isinstance(data.get("device"), dict)
  4660. and "extruder" in data["device"]
  4661. and isinstance(data["device"]["extruder"].get("info"), list)
  4662. and len(data["device"]["extruder"]["info"]) >= 2
  4663. )
  4664. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4665. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4666. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4667. if "nozzle_temper" in data:
  4668. if has_h2d_extruder_info:
  4669. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4670. else:
  4671. temps["nozzle"] = float(data["nozzle_temper"])
  4672. if "nozzle_target_temper" in data:
  4673. if has_h2d_extruder_info:
  4674. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4675. else:
  4676. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4677. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4678. if not has_h2d_extruder_info:
  4679. # Try multiple possible field names used by different firmware versions
  4680. if "nozzle_temper_2" in data:
  4681. val = float(data["nozzle_temper_2"])
  4682. if -50 < val < 500: # Valid temp range
  4683. temps["nozzle_2"] = val
  4684. else:
  4685. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4686. elif "right_nozzle_temper" in data:
  4687. val = float(data["right_nozzle_temper"])
  4688. if -50 < val < 500: # Valid temp range
  4689. temps["nozzle_2"] = val
  4690. else:
  4691. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4692. if "nozzle_target_temper_2" in data:
  4693. val = float(data["nozzle_target_temper_2"])
  4694. if 0 <= val < 500: # Valid temp range
  4695. temps["nozzle_2_target"] = val
  4696. else:
  4697. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4698. elif "right_nozzle_target_temper" in data:
  4699. val = float(data["right_nozzle_target_temper"])
  4700. if 0 <= val < 500: # Valid temp range
  4701. temps["nozzle_2_target"] = val
  4702. else:
  4703. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4704. # Also check for left nozzle as primary (some H2 models)
  4705. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4706. temps["nozzle"] = float(data["left_nozzle_temper"])
  4707. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4708. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4709. if "chamber_temper" in data:
  4710. chamber_val = float(data["chamber_temper"])
  4711. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4712. # Check if we recently set the target locally (within 5 seconds)
  4713. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4714. respect_local = (time.time() - local_set_time) < 5.0
  4715. # H2D protocol: chamber_temper encoding indicates heater state
  4716. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4717. # - When < 500: direct Celsius current temp only - heater is OFF
  4718. if -50 < chamber_val < 100:
  4719. # Direct value = heater is OFF
  4720. temps["chamber"] = chamber_val
  4721. if not respect_local:
  4722. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4723. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4724. else:
  4725. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4726. # Try to decode if it looks like an encoded value
  4727. if chamber_val > 500:
  4728. mqtt_target = int(chamber_val) // 65536
  4729. current = int(chamber_val) % 65536
  4730. logger.debug(
  4731. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4732. )
  4733. if -50 < current < 100:
  4734. temps["chamber"] = float(current)
  4735. # Store decoded target for later use, but DON'T set chamber_heating here!
  4736. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4737. # which is the authoritative source the slicer uses.
  4738. if not respect_local:
  4739. if 0 <= mqtt_target <= 60:
  4740. # Store as "decoded" target - may be overridden by explicit target fields
  4741. temps["_chamber_decoded_target"] = float(mqtt_target)
  4742. # Chamber target temperature (set by print file or display)
  4743. if "mc_target_cham" in data:
  4744. mc_target = float(data["mc_target_cham"])
  4745. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4746. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4747. if 0 <= mc_target <= 60:
  4748. temps["chamber_target"] = mc_target
  4749. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4750. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4751. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4752. try:
  4753. if "info" in data and isinstance(data["info"], dict):
  4754. info_temp = data["info"].get("temp")
  4755. if info_temp is not None and "chamber" not in temps:
  4756. # Check for encoded value (target * 65536 + current)
  4757. if info_temp > 500:
  4758. # Decode: extract current temperature and target
  4759. target = info_temp // 65536
  4760. current = info_temp % 65536
  4761. temps["chamber"] = float(current)
  4762. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4763. if "_chamber_decoded_target" not in temps:
  4764. temps["_chamber_decoded_target"] = float(target)
  4765. logger.debug(
  4766. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4767. )
  4768. elif -50 < info_temp < 100:
  4769. # Valid direct temperature - heater is OFF
  4770. temps["chamber"] = float(info_temp)
  4771. temps["chamber_target"] = 0.0 # Direct value means heater off
  4772. self._debug_on_change(
  4773. "info_temp_direct",
  4774. info_temp,
  4775. "[%s] info.temp direct: %s°C (heater OFF)",
  4776. self.serial_number,
  4777. info_temp,
  4778. )
  4779. # H2D series: Dual extruder temps are in device.extruder.info array
  4780. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4781. if "device" in data and isinstance(data["device"], dict):
  4782. device = data["device"]
  4783. # Parse dual extruder temperatures
  4784. extruder_data = device.get("extruder", {})
  4785. extruder_info = extruder_data.get("info", [])
  4786. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4787. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4788. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4789. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4790. if has_h2d_extruder_info:
  4791. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4792. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4793. if "temp" in extruder_info[0]:
  4794. temp_val = extruder_info[0]["temp"]
  4795. if temp_val > 500:
  4796. # Encoded format: temp = target * 65536 + current
  4797. target = temp_val // 65536
  4798. current = temp_val % 65536
  4799. if -50 < current < 500:
  4800. temps["nozzle_2"] = float(current)
  4801. if 0 < target < 500:
  4802. temps["nozzle_2_target"] = float(target)
  4803. temps["nozzle_2_heating"] = target > 0 and current < target
  4804. elif -50 < temp_val < 500:
  4805. # Direct Celsius value = heater is OFF
  4806. temps["nozzle_2"] = float(temp_val)
  4807. temps["nozzle_2_target"] = 0.0
  4808. temps["nozzle_2_heating"] = False
  4809. # Left nozzle (extruder 1) - only for dual nozzle printers
  4810. # H2D protocol: temp field encoding depends on value
  4811. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4812. # - When < 500: direct Celsius current temp only - heater is OFF
  4813. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4814. ext1 = extruder_info[1]
  4815. temp_val = ext1["temp"]
  4816. # Check if we recently set the target locally (within 5 seconds)
  4817. # If so, don't let MQTT data overwrite it
  4818. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4819. respect_local_target = (time.time() - local_set_time) < 5.0
  4820. if temp_val > 500:
  4821. # Encoded format: temp = target * 65536 + current
  4822. target = temp_val // 65536
  4823. current = temp_val % 65536
  4824. if 0 < target < 500 and not respect_local_target:
  4825. temps["nozzle_target"] = float(target)
  4826. if -50 < current < 500:
  4827. temps["nozzle"] = float(current)
  4828. # Heating = encoded AND we're using the MQTT target (not local override)
  4829. # If local target is being respected, use local target to determine heating
  4830. if respect_local_target:
  4831. local_target = self.state.temperatures.get("nozzle_target", 0)
  4832. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4833. else:
  4834. temps["nozzle_heating"] = target > 0 and current < target
  4835. elif -50 < temp_val < 500:
  4836. # Direct Celsius = heater is OFF (or at target with heater off)
  4837. temps["nozzle"] = float(temp_val)
  4838. if not respect_local_target:
  4839. temps["nozzle_target"] = 0.0
  4840. temps["nozzle_heating"] = False # Direct = not heating
  4841. # The extruder snow is read by _parse_extruder_position, before the
  4842. # AMS block of the same frame (tray_now resolution needs it first).
  4843. # Parse bed heating state from device.bed.info.temp encoding
  4844. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4845. bed_data = device.get("bed", {})
  4846. bed_info = bed_data.get("info", {})
  4847. if "temp" in bed_info:
  4848. temp_val = bed_info["temp"]
  4849. if temp_val > 500:
  4850. target = temp_val // 65536
  4851. current = temp_val % 65536
  4852. temps["bed_heating"] = target > 0 and current < target
  4853. else:
  4854. temps["bed_heating"] = False
  4855. # Parse chamber temp from device.ctc.info.temp if not already set
  4856. ctc_data = device.get("ctc", {})
  4857. ctc_info = ctc_data.get("info", {})
  4858. # Parse airduct mode (0=cooling, 1=heating)
  4859. airduct_data = device.get("airduct", {})
  4860. if "modeCur" in airduct_data:
  4861. new_mode = airduct_data["modeCur"]
  4862. if new_mode != self.state.airduct_mode:
  4863. logger.debug(
  4864. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4865. )
  4866. self.state.airduct_mode = new_mode
  4867. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4868. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4869. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4870. # AIR_FUN enum: 1=part cooling, 2=aux, 3=chamber/exhaust,
  4871. # 10=second aux (FAN_REMOTE_COOLING_1). Aux 2 is the right fan and
  4872. # 10 the left on the P2S, the other way round on the X2D (#3373;
  4873. # Bambu Studio's N7.json / N6.json). The airduct `parts` list only
  4874. # contains the fans that physically exist, so it doubles as a
  4875. # presence signal for the two P2S/X2D add-on kits:
  4876. # - id 10 (second auxiliary part cooling fan) — reported ONLY here,
  4877. # never mirrored into a flat big_fanX_speed field.
  4878. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4879. # big_fan2_speed, but the part is only listed when the External
  4880. # Exhaust Fan kit (get_version module "eef") is installed.
  4881. # `state` is already a 0-100 percentage.
  4882. parts = airduct_data.get("parts")
  4883. if isinstance(parts, list):
  4884. speeds: dict[int, int] = {}
  4885. for part in parts:
  4886. if not isinstance(part, dict):
  4887. continue
  4888. try:
  4889. # Studio reads the id with get_flag_bits(id, 4, 8),
  4890. # so mask after shifting for the same reason `state`
  4891. # is masked below. Every id seen in the wild
  4892. # (16/32/48/160) decodes identically either way —
  4893. # this is consistency, not a live bug.
  4894. part_id = (int(part["id"]) >> 4) & 0xFF
  4895. # `state` is bit-packed like its sibling `range`
  4896. # (end << 16 | start), so take only the low 8 bits —
  4897. # the same decode Bambu Studio does with
  4898. # get_flag_bits(state, 0, 8). Without the mask a
  4899. # packed value would clamp to 100 instead of
  4900. # decoding to the real percentage.
  4901. part_state = int(part["state"]) & 0xFF
  4902. except (KeyError, ValueError, TypeError):
  4903. continue
  4904. # Ids seen across the support-package archive:
  4905. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4906. # 6 (H2 series, unmapped), 10 second aux.
  4907. speeds[part_id] = max(0, min(100, part_state))
  4908. # Absence in this list is what tells us a kit is NOT fitted,
  4909. # so it may only be trusted when the list is a full
  4910. # inventory rather than a diff frame. `device.airduct` is
  4911. # pushed field by field — the `modeCur` handler above exists
  4912. # for exactly that reason — and a truncated `parts` read as
  4913. # gospel would retract both accessory badges mid-print and
  4914. # start rejecting `aux2` on a printer that has the fan.
  4915. #
  4916. # Every airduct layout in the support-package archive
  4917. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4918. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4919. # part cooling fan and the aux fan, neither of which is
  4920. # optional on any machine that reports an airduct at all.
  4921. # A list carrying both is therefore a complete inventory; a
  4922. # list missing either is a partial frame, and we take its
  4923. # speeds without touching presence.
  4924. is_full_inventory = 1 in speeds and 2 in speeds
  4925. left_aux_speed = speeds.get(10)
  4926. if left_aux_speed is None and not is_full_inventory:
  4927. # Partial frame that didn't mention the second aux fan —
  4928. # keep whatever we already knew about it.
  4929. left_aux_speed = self.state.left_aux_fan_speed
  4930. if left_aux_speed != self.state.left_aux_fan_speed:
  4931. logger.debug(
  4932. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4933. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4934. )
  4935. # A FULL parts list without id 10 means the second aux fan is
  4936. # not installed — report None so the UI can hide the widget.
  4937. self.state.left_aux_fan_speed = left_aux_speed
  4938. # id 3 present == chamber exhaust fan installed (base P2S
  4939. # omits it). Only ever retracted on a full inventory.
  4940. if 3 in speeds:
  4941. self.state.exhaust_fan_present = True
  4942. elif is_full_inventory:
  4943. self.state.exhaust_fan_present = False
  4944. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  4945. # Check if we recently set the target locally (within 5 seconds)
  4946. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4947. respect_local_target = (time.time() - local_set_time) < 5.0
  4948. # Log ctc_info contents for debugging
  4949. if ctc_info:
  4950. self._debug_on_change(
  4951. "ctc_info_keys",
  4952. tuple(ctc_info.keys()),
  4953. "[%s] ctc_info keys: %s",
  4954. self.serial_number,
  4955. list(ctc_info.keys()),
  4956. )
  4957. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  4958. # (what the slicer shows). This OVERRIDES any previously decoded target.
  4959. explicit_target = None
  4960. if "target" in ctc_info:
  4961. target_val = ctc_info["target"]
  4962. logger.debug(
  4963. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  4964. )
  4965. # Filter out invalid values (valid chamber target is 0-60°C)
  4966. if 0 <= target_val <= 60 and not respect_local_target:
  4967. explicit_target = float(target_val)
  4968. temps["chamber_target"] = explicit_target # Override any previous value
  4969. logger.debug(
  4970. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  4971. )
  4972. # Parse chamber temp from ctc.info.temp - may be encoded
  4973. if "temp" in ctc_info and "chamber" not in temps:
  4974. temp_val = ctc_info["temp"]
  4975. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  4976. if temp_val > 500:
  4977. # Encoded value: decode target and current
  4978. decoded_target = temp_val // 65536
  4979. current = temp_val % 65536
  4980. temps["chamber"] = float(current)
  4981. logger.debug(
  4982. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  4983. )
  4984. # Determine which target to use for heating state:
  4985. # Priority: local target > explicit target > decoded target
  4986. if respect_local_target:
  4987. local_target = self.state.temperatures.get("chamber_target", 0)
  4988. temps["chamber_heating"] = local_target > 0 and current < local_target
  4989. elif explicit_target is not None:
  4990. # Use explicit ctc.info.target - this is what slicer sees
  4991. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  4992. else:
  4993. # Fallback to decoded target only if no explicit target available
  4994. if not respect_local_target and "chamber_target" not in temps:
  4995. temps["chamber_target"] = float(decoded_target)
  4996. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  4997. else:
  4998. # Direct value (not encoded) - heater is OFF
  4999. temps["chamber"] = float(temp_val)
  5000. temps["chamber_heating"] = False
  5001. except Exception as e:
  5002. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  5003. if temps:
  5004. # Handle chamber_target: prefer explicit over decoded
  5005. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  5006. # No explicit target available, use decoded target from chamber_temper
  5007. temps["chamber_target"] = temps["_chamber_decoded_target"]
  5008. # Remove internal temp key before merging
  5009. temps.pop("_chamber_decoded_target", None)
  5010. # Merge new temps into existing, preserving valid values when new ones are filtered out
  5011. for key, value in temps.items():
  5012. self.state.temperatures[key] = value
  5013. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  5014. if "bed" in temps and self.on_bed_temp_update:
  5015. self.on_bed_temp_update(temps["bed"])
  5016. # Calculate chamber_heating after all targets are known
  5017. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  5018. if "chamber" in temps and "chamber_heating" not in temps:
  5019. current = self.state.temperatures.get("chamber", 0)
  5020. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  5021. respect_local = (time.time() - local_set_time) < 5.0
  5022. if respect_local:
  5023. # Use locally-set target
  5024. target = self.state.temperatures.get("chamber_target", 0)
  5025. else:
  5026. # Use explicit/decoded target from MQTT
  5027. target = self.state.temperatures.get("chamber_target", 0)
  5028. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  5029. self._debug_on_change(
  5030. "chamber_heating",
  5031. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  5032. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  5033. self.serial_number,
  5034. target,
  5035. current,
  5036. self.state.temperatures["chamber_heating"],
  5037. respect_local,
  5038. )
  5039. # Debug: log chamber value if it was updated
  5040. if "chamber" in temps:
  5041. self._debug_on_change(
  5042. "chamber_temp",
  5043. (
  5044. self.state.temperatures.get("chamber"),
  5045. self.state.temperatures.get("chamber_target"),
  5046. self.state.temperatures.get("chamber_heating"),
  5047. ),
  5048. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  5049. self.serial_number,
  5050. self.state.temperatures.get("chamber"),
  5051. self.state.temperatures.get("chamber_target"),
  5052. self.state.temperatures.get("chamber_heating"),
  5053. )
  5054. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  5055. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  5056. if "nozzle" in temps and "nozzle_heating" not in temps:
  5057. current = self.state.temperatures.get("nozzle", 0)
  5058. target = self.state.temperatures.get("nozzle_target", 0)
  5059. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  5060. # Parse HMS (Health Management System) errors
  5061. if "hms" in data:
  5062. hms_list = data["hms"]
  5063. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  5064. # A `print_error` fault is not in `hms[]` and its field only comes
  5065. # when it changes, so a list rebuilt from `hms[]` keeps it (#3487).
  5066. print_error_entries = [e for e in self.state.hms_errors if _is_print_error_entry(e)]
  5067. self.state.hms_errors = []
  5068. verify_failed = False
  5069. if isinstance(hms_list, list):
  5070. for hms in hms_list:
  5071. if isinstance(hms, dict):
  5072. # HMS format: {"attr": attribute_code, "code": error_code}
  5073. # attr contains module/severity info, code contains error number
  5074. # Both are needed to construct the wiki URL
  5075. attr = hms.get("attr", 0)
  5076. code = hms.get("code", 0)
  5077. if isinstance(attr, str):
  5078. attr = int(attr.replace("0x", ""), 16) if attr else 0
  5079. if isinstance(code, str):
  5080. code = int(code.replace("0x", ""), 16) if code else 0
  5081. # attr is module, module no., part, part no. (a byte each);
  5082. # code is the alert level (high 16 bits) then the error
  5083. # (low 16). The level is 1 error (task stopped), 2 warning
  5084. # (task paused), 3 notification; 0 is invalid. This is how
  5085. # Bambu Studio decodes it (DevHMSItem::parse_hms_info). It
  5086. # used to be read from attr bits 8-15, which is the part
  5087. # byte (#2728).
  5088. severity = (code >> 16) & 0xFFFF
  5089. # Module is in attr byte 3 (bits 24-31)
  5090. module = (attr >> 24) & 0xFF
  5091. # Skip non-error status codes. A real fault has a level of
  5092. # at least 1 in the high half, so its code is >= 0x10000
  5093. # and clears this; lower values are status/phase
  5094. # indicators some firmware sends during normal printing.
  5095. if code < 0x4000:
  5096. continue
  5097. # Skip user-action echoes — the printer firmware emits these
  5098. # as part of normal user-cancel sequences. They're not faults
  5099. # and shouldn't count toward "X problem" badges or surface as
  5100. # red pips on the printer card. Backend's notification path
  5101. # already suppresses 0500_400E for the same reason.
  5102. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  5103. if short_code in _HMS_USER_ACTION_CODES:
  5104. continue
  5105. # The full 16-char identifier is the firmware's matching key
  5106. # and the HMS catalogue's key for this kind of fault; the
  5107. # short code discards the part and alert-level groups. The
  5108. # action table still has some short-form entries, so that
  5109. # lookup falls back to it.
  5110. full_code = f"{attr:08X}{code:08X}"
  5111. if full_code == HMS_MQTT_VERIFY_FAILED:
  5112. verify_failed = True
  5113. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  5114. if not actions:
  5115. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5116. self.state.hms_errors.append(
  5117. HMSError(
  5118. code=f"0x{code:x}" if code else "0x0",
  5119. attr=attr,
  5120. module=module,
  5121. # No fallback: 0 is Bambu's "invalid" level, and
  5122. # promoting it would render it as a fault.
  5123. severity=severity,
  5124. actions=actions,
  5125. job_id=self.state.subtask_id,
  5126. full_code=full_code,
  5127. description=describe_fault(full_code, self.serial_number[:3]),
  5128. )
  5129. )
  5130. hms_short_codes = _hms_short_codes(self.state.hms_errors)
  5131. self.state.hms_errors.extend(e for e in print_error_entries if _hms_short_code(e) not in hms_short_codes)
  5132. self._apply_mqtt_verify_state(verify_failed)
  5133. # Parse print_error - this is a different error format than HMS
  5134. # print_error is a 32-bit integer where:
  5135. # - High 16 bits contain module info (e.g., 0x0500)
  5136. # - Low 16 bits contain error code (e.g., 0x8061)
  5137. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  5138. if "print_error" in data:
  5139. print_error = data["print_error"]
  5140. # The field holds the one current fault, and 0 once it is resolved,
  5141. # for example when the filament-load prompt is answered on the
  5142. # printer. The entry of a code that is no longer reported goes
  5143. # (#3487); the entry of the same code is kept as it is.
  5144. self.state.hms_errors = [
  5145. e for e in self.state.hms_errors if not _is_print_error_entry(e) or e.attr == print_error
  5146. ]
  5147. if print_error and print_error != 0:
  5148. # Extract components: MMMMEEEE -> MMMM_EEEE
  5149. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  5150. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  5151. # Values below 0x4000 are status/phase indicators, not real errors.
  5152. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  5153. # Some firmware sends low values like 0x0002 during normal printing.
  5154. if error < 0x4000:
  5155. pass # Skip — not a real error
  5156. else:
  5157. # Store in a format that matches the community error database
  5158. # attr stores the full 32-bit value for reconstruction
  5159. # code stores the short format string for lookup
  5160. short_code = f"{module:04X}_{error:04X}"
  5161. logger.debug(
  5162. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  5163. )
  5164. # Same user-action filter as the hms[] branch above — print_error
  5165. # carries the same cancel echoes (e.g. 0500_400E) and they must
  5166. # not surface as faults on the printer card.
  5167. if short_code in _HMS_USER_ACTION_CODES:
  5168. pass # cancel echo — silently drop
  5169. else:
  5170. # Only add if not already in HMS errors (avoid duplicates)
  5171. if short_code not in _hms_short_codes(self.state.hms_errors):
  5172. # Bambu's HMS catalog keys by 3-letter device code (the SN
  5173. # prefix) and a 16-char short error code without the
  5174. # underscore separator we store internally.
  5175. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5176. # Bambu pushes the current job as `subtask_id` on the
  5177. # state stream; the HMS-action commands echo it back as
  5178. # `job_id`. The error payload itself doesn't carry the
  5179. # id, so snapshot it from the live state at parse time
  5180. # and freeze it on the HMSError so subsequent
  5181. # job changes don't invalidate the action.
  5182. job_id = self.state.subtask_id
  5183. logger.debug(
  5184. "[%s, %s] HMS available actions: %s (job_id=%s)",
  5185. self.serial_number[:3],
  5186. short_code.replace("_", ""),
  5187. actions,
  5188. job_id,
  5189. )
  5190. self.state.hms_errors.append(
  5191. HMSError(
  5192. code=f"0x{error:x}",
  5193. attr=print_error, # Store full value for display
  5194. module=module >> 8, # High byte of module (e.g., 0x05)
  5195. # print_error has no level field; its error
  5196. # number's first digit carries it instead.
  5197. severity=alert_level_from_print_error(error),
  5198. actions=actions,
  5199. job_id=job_id,
  5200. # print_error is already 32-bit — `f"{print_error:08X}"`
  5201. # is the firmware's matching key with no truncation.
  5202. full_code=f"{print_error:08X}",
  5203. description=describe_fault(f"{print_error:08X}", self.serial_number[:3]),
  5204. )
  5205. )
  5206. # Parse home_flag first so SD-card detection below can prefer it.
  5207. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  5208. # bit 23 = door-open (X1 family only).
  5209. home_flag = None
  5210. if "home_flag" in data:
  5211. home_flag = data["home_flag"]
  5212. if home_flag < 0:
  5213. home_flag = home_flag & 0xFFFFFFFF
  5214. # SD card presence: the only remaining consumer is the firmware-update
  5215. # precondition check (firmware_update.py). Use the top-level `sdcard`
  5216. # field when present with a permissive truthy check covering the
  5217. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  5218. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  5219. # when a card is inserted, which caused the badge to flap before the
  5220. # badge was removed entirely.
  5221. if "sdcard" in data:
  5222. raw_sdcard = data["sdcard"]
  5223. if isinstance(raw_sdcard, str):
  5224. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  5225. else:
  5226. self.state.sdcard = bool(raw_sdcard)
  5227. self.state.sdcard_reported = True
  5228. if home_flag is not None:
  5229. store_to_sdcard = bool((home_flag >> 11) & 1)
  5230. if store_to_sdcard != self.state.store_to_sdcard:
  5231. logger.debug(
  5232. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  5233. )
  5234. self.state.store_to_sdcard = store_to_sdcard
  5235. # Door open detection — source depends on printer family:
  5236. # X1 series (X1, X1C, X1E): home_flag bit 23
  5237. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  5238. # Both share the same bitmask (0x00800000) but live in different fields.
  5239. model_upper = (self.model or "").upper().strip()
  5240. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  5241. if is_x1_family and home_flag is not None:
  5242. door_open = (home_flag & 0x00800000) != 0
  5243. if door_open != self.state.door_open:
  5244. logger.debug(
  5245. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  5246. self.serial_number,
  5247. self.state.door_open,
  5248. door_open,
  5249. home_flag,
  5250. )
  5251. self.state.door_open = door_open
  5252. elif not is_x1_family and "stat" in data:
  5253. try:
  5254. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  5255. door_open = (stat_value & 0x00800000) != 0
  5256. if door_open != self.state.door_open:
  5257. logger.debug(
  5258. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  5259. self.serial_number,
  5260. self.state.door_open,
  5261. door_open,
  5262. stat_value,
  5263. )
  5264. self.state.door_open = door_open
  5265. except (ValueError, TypeError):
  5266. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  5267. # Parse timelapse status (recording active during print). Status frames
  5268. # only — the project_file ack echoes back the per-job timelapse flag we
  5269. # asked for, which is a request, not the recorder's state (#3040).
  5270. if "timelapse" in data and is_printer_status_frame(data):
  5271. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  5272. self.state.timelapse = data["timelapse"] is True
  5273. # Track if timelapse was ever active during this print
  5274. if self.state.timelapse and self._was_running:
  5275. self._timelapse_during_print = True
  5276. # Parse ipcam/live view status
  5277. if "ipcam" in data:
  5278. ipcam_data = data["ipcam"]
  5279. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  5280. if isinstance(ipcam_data, dict):
  5281. # Check ipcam_record field for live view status
  5282. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  5283. # Check timelapse field (H2D sends it here, not in xcam)
  5284. if "timelapse" in ipcam_data:
  5285. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  5286. if timelapse_enabled != self.state.timelapse:
  5287. logger.debug(
  5288. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  5289. )
  5290. self.state.timelapse = timelapse_enabled
  5291. # Track if timelapse was ever active during this print
  5292. if self.state.timelapse and self._was_running:
  5293. self._timelapse_during_print = True
  5294. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  5295. else:
  5296. self.state.ipcam = ipcam_data is True
  5297. # Parse WiFi signal strength (dBm)
  5298. if "wifi_signal" in data:
  5299. wifi_signal = data["wifi_signal"]
  5300. self._debug_on_change(
  5301. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  5302. )
  5303. if isinstance(wifi_signal, (int, float)):
  5304. self.state.wifi_signal = int(wifi_signal)
  5305. elif isinstance(wifi_signal, str):
  5306. # Handle string format like "-52dBm"
  5307. try:
  5308. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  5309. except ValueError:
  5310. pass # Ignore unparseable wifi_signal strings; field is non-critical
  5311. # Detect ethernet connection: printers on ethernet with WiFi disabled
  5312. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  5313. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  5314. from backend.app.utils.printer_models import has_ethernet
  5315. if has_ethernet(self.model):
  5316. self.state.wired_network = self.state.wifi_signal == -90
  5317. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5318. if "spd_lvl" in data:
  5319. new_speed = data["spd_lvl"]
  5320. if new_speed != self.state.speed_level:
  5321. logger.debug(
  5322. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  5323. )
  5324. self.state.speed_level = new_speed
  5325. # Parse skipped objects from printer status (s_obj field)
  5326. # This allows us to restore skipped objects state after reconnection
  5327. if "s_obj" in data:
  5328. s_obj = data["s_obj"]
  5329. if isinstance(s_obj, list):
  5330. # Update skipped objects from printer's list
  5331. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  5332. if new_skipped != self.state.skipped_objects:
  5333. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  5334. self.state.skipped_objects = new_skipped
  5335. for oid in new_skipped:
  5336. self._unconfirmed_skips.pop(oid, None)
  5337. self._check_unconfirmed_skips()
  5338. # Parse chamber light status from lights_report
  5339. if "lights_report" in data:
  5340. lights = data["lights_report"]
  5341. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  5342. if isinstance(lights, list):
  5343. for light in lights:
  5344. if isinstance(light, dict) and light.get("node") == "chamber_light":
  5345. new_light_state = light.get("mode") == "on"
  5346. if new_light_state != self.state.chamber_light:
  5347. logger.debug(
  5348. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  5349. )
  5350. self.state.chamber_light = new_light_state
  5351. break
  5352. # Parse nozzle hardware info (single nozzle printers)
  5353. if "nozzle_type" in data:
  5354. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  5355. if "nozzle_diameter" in data:
  5356. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  5357. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  5358. # Left nozzle
  5359. if "left_nozzle_type" in data:
  5360. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  5361. if "left_nozzle_diameter" in data:
  5362. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  5363. # Right nozzle
  5364. if "right_nozzle_type" in data:
  5365. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  5366. if "right_nozzle_diameter" in data:
  5367. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  5368. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  5369. if "nozzle_type_2" in data:
  5370. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  5371. if "nozzle_diameter_2" in data:
  5372. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  5373. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  5374. if "device" in data and isinstance(data["device"], dict):
  5375. device = data["device"]
  5376. nozzle_data = device.get("nozzle", {})
  5377. # H2C rack position (#2800). `tar_id` is where the carriage is
  5378. # headed, `src_id` where it came from; mid-swap they differ, so
  5379. # dispatch prefers tar_id and falls back to src_id. Both are
  5380. # sticky — the field is only pushed when it changes, so an
  5381. # absent key must leave the last known value alone rather than
  5382. # reset it to None.
  5383. if isinstance(nozzle_data, dict):
  5384. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  5385. if key not in nozzle_data:
  5386. continue
  5387. try:
  5388. parsed_id = int(nozzle_data[key])
  5389. except (TypeError, ValueError):
  5390. continue
  5391. if getattr(self.state, attr) != parsed_id:
  5392. setattr(self.state, attr, parsed_id)
  5393. # DEBUG, not INFO: these move on every tool change, so
  5394. # a long multi-material print would otherwise write
  5395. # thousands of lines. The dispatch log records both
  5396. # values once per print, which is where triage needs
  5397. # them. Same reasoning as the one-shot `nozzle_info`
  5398. # log below.
  5399. logger.debug(
  5400. "[%s] Nozzle rack %s -> %s",
  5401. self.serial_number,
  5402. key,
  5403. parsed_id,
  5404. )
  5405. nozzle_info = nozzle_data.get("info", [])
  5406. if isinstance(nozzle_info, list):
  5407. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  5408. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  5409. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  5410. # for hover cards on both the L/R indicator and the nozzle rack card.
  5411. if nozzle_info:
  5412. self.state.nozzle_rack = sorted(
  5413. [
  5414. {
  5415. "id": n.get("id", i),
  5416. "type": str(n.get("type", "")),
  5417. "diameter": str(n.get("diameter", "")),
  5418. "wear": n.get("wear"),
  5419. "stat": n.get("stat"),
  5420. # H2C uses "tm", H2D uses "max_temp"
  5421. "max_temp": n.get("max_temp") or n.get("tm", 0),
  5422. # H2C uses "sn", H2D uses "serial_number"
  5423. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  5424. # H2C uses "color_m", H2D uses "filament_colour"
  5425. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  5426. # H2C uses "fila_id", H2D uses "filament_id"
  5427. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  5428. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  5429. # H3C: home rack position 0-8 (the mounted hotend reports id 0)
  5430. "addr_id": n.get("addr_id") if isinstance(n.get("addr_id"), int) else None,
  5431. }
  5432. for i, n in enumerate(nozzle_info)
  5433. ],
  5434. key=lambda x: x["id"],
  5435. )
  5436. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  5437. self._nozzle_rack_logged = True
  5438. logger.debug(
  5439. "[%s] Nozzle info: %d entries, IDs: %s",
  5440. self.serial_number,
  5441. len(nozzle_info),
  5442. [n.get("id") for n in nozzle_info],
  5443. )
  5444. for nozzle in nozzle_info:
  5445. idx = nozzle.get("id", 0)
  5446. if idx < len(self.state.nozzles):
  5447. if "type" in nozzle and nozzle["type"]:
  5448. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  5449. if "diameter" in nozzle:
  5450. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  5451. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  5452. # (these fields aren't sent in every MQTT push, only when changed)
  5453. ams_data = self.state.raw_data.get("ams")
  5454. vt_tray_data = self.state.raw_data.get("vt_tray")
  5455. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  5456. mapping_data = self.state.raw_data.get("mapping")
  5457. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  5458. # as a dict but consumers expect a list. Without this, the dev mode probe
  5459. # below can release the GIL (via publish), letting the event-loop thread
  5460. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  5461. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  5462. data["vt_tray"] = [data["vt_tray"]]
  5463. self.state.raw_data = data
  5464. # Restore preserved fields BEFORE any work that may release the GIL
  5465. # (e.g. _probe_developer_mode publishes an MQTT message).
  5466. if ams_data is not None:
  5467. self.state.raw_data["ams"] = ams_data
  5468. if vt_tray_data is not None:
  5469. self.state.raw_data["vt_tray"] = vt_tray_data
  5470. if ams_extruder_map_data is not None:
  5471. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  5472. if mapping_data is not None and "mapping" not in data:
  5473. self.state.raw_data["mapping"] = mapping_data
  5474. # Parse developer LAN mode from "fun" field
  5475. if "fun" in data:
  5476. try:
  5477. fun_val = data["fun"]
  5478. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  5479. self.state.developer_mode = (fun_int & 0x20000000) == 0
  5480. except (ValueError, TypeError):
  5481. pass
  5482. elif self.state.developer_mode is None and not self._dev_mode_probed:
  5483. # No "fun" field — A1/P1 series never send it, so we need to probe.
  5484. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  5485. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  5486. # after connect to let the MQTT session stabilize — probing too early
  5487. # can destabilize some firmware MQTT brokers (#887).
  5488. if not self._dev_mode_needs_probe and len(data) > 30:
  5489. # First full status without "fun" — mark that probe is needed
  5490. self._dev_mode_needs_probe = True
  5491. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  5492. self._probe_developer_mode()
  5493. elif self._dev_mode_needs_probe:
  5494. logger.debug(
  5495. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  5496. self.serial_number,
  5497. time.monotonic() - self._connect_time,
  5498. )
  5499. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  5500. # Probe was sent but no response yet — check for timeout.
  5501. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  5502. # may deliver status pushes but silently drop commands (#887).
  5503. elapsed = time.monotonic() - self._dev_mode_probe_time
  5504. if elapsed > 10.0:
  5505. self._dev_mode_probe_failures += 1
  5506. logger.warning(
  5507. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  5508. self.serial_number,
  5509. elapsed,
  5510. self._dev_mode_probe_failures,
  5511. )
  5512. self._dev_mode_probe_seq = None
  5513. if self._dev_mode_probe_failures >= 2:
  5514. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  5515. else:
  5516. # Allow retry on next full status message
  5517. self._dev_mode_probed = False
  5518. # Zombie session detection: if an ams_filament_setting command has been
  5519. # pending for >10s with no response, the publish path is likely dead (#887).
  5520. if self._last_ams_cmd_time > 0:
  5521. elapsed = time.monotonic() - self._last_ams_cmd_time
  5522. if elapsed > 10.0:
  5523. self._ams_cmd_unanswered += 1
  5524. logger.warning(
  5525. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  5526. self.serial_number,
  5527. elapsed,
  5528. self._ams_cmd_unanswered,
  5529. )
  5530. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  5531. if self._ams_cmd_unanswered >= 2:
  5532. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  5533. self._ams_cmd_unanswered = 0
  5534. # Log mapping data when received (for usage tracking debugging)
  5535. if "mapping" in data:
  5536. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  5537. # Log state transitions for debugging
  5538. if "gcode_state" in data:
  5539. logger.debug(
  5540. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  5541. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  5542. )
  5543. # Detect print start (state changes TO RUNNING with a file)
  5544. current_file = self.state.gcode_file or self.state.current_print
  5545. if self._previous_gcode_state is None and self.state.state == "PAUSE" and current_file:
  5546. self._paused_at_startup = True
  5547. is_new_print = (
  5548. self.state.state == "RUNNING"
  5549. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  5550. and self._previous_gcode_state != "RUNNING"
  5551. and current_file
  5552. and not self._was_running # Prevent duplicates when resuming from PAUSE
  5553. # #3485: a print paused when Bambuddy started resumes like one it
  5554. # found running (#1304): restart recovery below, not a new print.
  5555. and not (self._paused_at_startup and self._previous_gcode_state == "PAUSE")
  5556. )
  5557. if self.state.state != "PAUSE":
  5558. self._paused_at_startup = False
  5559. # Also detect if file changed while running (new print started)
  5560. is_file_change = (
  5561. self.state.state == "RUNNING"
  5562. and current_file
  5563. and current_file != self._previous_gcode_file
  5564. and self._previous_gcode_file is not None
  5565. )
  5566. # Track RUNNING state for more robust completion detection
  5567. running_first_observed = False
  5568. if self.state.state == "RUNNING" and current_file:
  5569. if not self._was_running:
  5570. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  5571. # Check if timelapse was enabled in the same message (xcam parsed before this)
  5572. if self.state.timelapse:
  5573. self._timelapse_during_print = True
  5574. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  5575. # Mark this as the first RUNNING observation of the session.
  5576. # If is_new_print also fires below, on_print_start handles
  5577. # baseline capture and we suppress on_print_running_observed
  5578. # to avoid double-capture. If is_new_print does NOT fire
  5579. # (Bambuddy started mid-print — the #1304 guard suppressed
  5580. # it), main.py needs this hook to catch the restart-recovery
  5581. # case (#1485 follow-up).
  5582. running_first_observed = True
  5583. self._was_running = True
  5584. self._completion_triggered = False
  5585. if is_new_print or is_file_change:
  5586. # Clear any old HMS errors when a new print starts
  5587. self.state.hms_errors = []
  5588. # The last print's pauses; this one's come from its 3MF (#2984).
  5589. self.state.pause_points = []
  5590. self.state.pause_warned_layers = set()
  5591. # Reset layer tracking for new print (needed for layer-based timelapse)
  5592. # #3317: only above 1. Every print reports layer 1 first, which
  5593. # clears a higher value; a previous print that ended on layer 1
  5594. # would make this print's own first layer look stale.
  5595. self._stale_layer_num = self.state.layer_num if self.state.layer_num > 1 else 0
  5596. self.state.layer_num = 0
  5597. # Reset total_layers so the previous print's value can't bleed into
  5598. # this print's usage-tracker split (#1771 follow-on to the
  5599. # preservation guard at the `total_layer_num` parse above — that
  5600. # guard ignores firmware-reset 0s, so the explicit reset has to
  5601. # happen here instead).
  5602. #
  5603. # #2702: reset to *this frame's* total, not to 0. The frame that
  5604. # trips the new-print detection can carry the new print's
  5605. # `total_layer_num` as well — the parse above has already applied
  5606. # it, and zeroing unconditionally threw it away. That looked
  5607. # harmless but is not recoverable: Bambu firmware sends only
  5608. # changed fields, so the printer never offers the total again, and
  5609. # the print runs to completion at `n/0` in the UI, in
  5610. # `{total_layers}` notifications, and as the usage-split
  5611. # denominator. The value only reappears on the next full pushall
  5612. # (reconnect / Force Refresh), which is why the symptom looked
  5613. # random and why a *stable* connection made it worse.
  5614. self.state.total_layers = total_from_this_frame
  5615. # If the starting frame brought no total, ask for one. Costs one
  5616. # MQTT message per print and covers the ordering where the printer
  5617. # published the total a frame or two before the state flip.
  5618. self._total_layers_refresh_armed = not total_from_this_frame
  5619. if self._total_layers_refresh_armed:
  5620. self._request_push_all()
  5621. # Reset completion tracking for new print
  5622. self._was_running = True
  5623. self._completion_triggered = False
  5624. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5625. self._finish_photo_captured = False
  5626. # #2547: rearm the end-of-print telemetry probe for the new print
  5627. self._eop_probe_armed = True
  5628. self._eop_probe_open = False
  5629. self._eop_probe_frames = 0
  5630. self._eop_probe_last = {}
  5631. # Reset last valid progress/layer for usage tracking
  5632. self._last_valid_progress = 0.0
  5633. self._last_valid_layer_num = 0
  5634. # Clear and seed tray change log for mid-print usage splitting
  5635. self.state.tray_change_log.clear()
  5636. # Seeded with the assigned spools by usage_tracker.on_print_start.
  5637. self.state.spool_change_log = []
  5638. tn = self.state.tray_now
  5639. if self.tray_layout.is_loaded_tray(tn):
  5640. self.state.tray_change_log.append((tn, 0))
  5641. # Initialize timelapse tracking based on current state
  5642. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5643. # so self.state.timelapse may already be set from this message.
  5644. # We preserve that value instead of blindly resetting to False.
  5645. if self.state.timelapse:
  5646. self._timelapse_during_print = True
  5647. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5648. else:
  5649. self._timelapse_during_print = False
  5650. if (is_new_print or is_file_change) and self.on_print_start:
  5651. logger.info(
  5652. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5653. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5654. )
  5655. self.on_print_start(
  5656. {
  5657. "filename": current_file,
  5658. "subtask_name": self.state.subtask_name,
  5659. "remaining_time": self.state.remaining_time * 60
  5660. if self.state.remaining_time > 0
  5661. else None, # Convert minutes to seconds
  5662. "raw_data": data,
  5663. "ams_mapping": self._captured_ams_mapping,
  5664. }
  5665. )
  5666. elif running_first_observed and self.on_print_running_observed:
  5667. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5668. # print, so the #1304 first-push guard suppressed on_print_start,
  5669. # but we still need main.py to capture a fresh timelapse baseline
  5670. # before the printer uploads the in-flight MP4. Same payload
  5671. # shape as on_print_start so the consumer can reuse fields.
  5672. logger.info(
  5673. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5674. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5675. )
  5676. self.on_print_running_observed(
  5677. {
  5678. "filename": current_file,
  5679. "subtask_name": self.state.subtask_name,
  5680. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5681. "raw_data": data,
  5682. "ams_mapping": self._captured_ams_mapping,
  5683. }
  5684. )
  5685. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5686. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5687. # This handles cases where server restarts during a print
  5688. should_trigger_completion = (
  5689. self.state.state in ("FINISH", "FAILED")
  5690. and not self._completion_triggered
  5691. and self.on_print_complete
  5692. and (
  5693. self._previous_gcode_state == "RUNNING" # Normal transition
  5694. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5695. # Pre-print failure (#1111): printer rejected the job during setup
  5696. # — wrong nozzle size, AMS error, etc. The print never reaches
  5697. # RUNNING, so without this branch neither the RUNNING check nor
  5698. # _was_running match and the queue item stays stuck at "printing".
  5699. # Restricted to FAILED from pre-print states so a stale FAILED on
  5700. # first connection (prev=None) still can't accidentally fire.
  5701. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5702. )
  5703. )
  5704. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5705. if (
  5706. self.state.state == "IDLE"
  5707. and self._previous_gcode_state == "RUNNING"
  5708. and not self._completion_triggered
  5709. and self.on_print_complete
  5710. ):
  5711. should_trigger_completion = True
  5712. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5713. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5714. if (
  5715. not should_trigger_completion
  5716. and self.state.state in ("FINISH", "FAILED")
  5717. and self._previous_gcode_state != self.state.state
  5718. ):
  5719. logger.info(
  5720. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5721. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5722. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5723. )
  5724. # Mark as triggered so state is clean for the next print cycle
  5725. self._completion_triggered = True
  5726. if should_trigger_completion:
  5727. if self.state.state == "FINISH":
  5728. status = "completed"
  5729. elif self.state.state == "FAILED":
  5730. status = "failed"
  5731. else:
  5732. status = "aborted"
  5733. logger.info(
  5734. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5735. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5736. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5737. f"timelapse_during_print: {self._timelapse_during_print}"
  5738. )
  5739. timelapse_was_active = self._timelapse_during_print
  5740. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5741. # external-spool-only, HMS halt, or firmware variant that skips
  5742. # the unload phase) fire the finish-photo moment now. Bed has
  5743. # already dropped, framing is worse, but we still capture.
  5744. # Only on successful completion — aborted/failed prints don't
  5745. # produce a meaningful finish photo.
  5746. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5747. self._finish_photo_captured = True
  5748. logger.info(
  5749. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5750. f"stage-22 never fired; capturing at FINISH-state transition"
  5751. )
  5752. self.on_finish_photo_moment(
  5753. {
  5754. "trigger": "finish_state",
  5755. "filename": self._previous_gcode_file or current_file,
  5756. "subtask_name": self.state.subtask_name,
  5757. "timelapse_was_active": timelapse_was_active,
  5758. }
  5759. )
  5760. self._completion_triggered = True
  5761. self._was_running = False
  5762. self._timelapse_during_print = False # Reset for next print
  5763. # Include HMS errors for failure reason detection
  5764. hms_errors_data = [e.completion_payload() for e in self.state.hms_errors or []]
  5765. from backend.app.utils.printer_models import usage_progress
  5766. last_progress = usage_progress(
  5767. self.model, self._last_valid_progress, self._last_valid_layer_num, self.state.total_layers
  5768. )
  5769. self.on_print_complete(
  5770. {
  5771. "status": status,
  5772. "subtask_id": self.state.subtask_id,
  5773. "filename": self._previous_gcode_file or current_file,
  5774. "subtask_name": self.state.subtask_name,
  5775. "raw_data": data,
  5776. "timelapse_was_active": timelapse_was_active,
  5777. "hms_errors": hms_errors_data,
  5778. "ams_mapping": self._captured_ams_mapping,
  5779. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5780. "last_progress": last_progress,
  5781. "last_layer_num": self._last_valid_layer_num,
  5782. }
  5783. )
  5784. self._captured_ams_mapping = None
  5785. # Same lifecycle as the mapping above: it described *this* print.
  5786. # Leaving it set would hand the next print an answer about where a
  5787. # different file went, and a stale "internal storage" reading costs
  5788. # an archive that the FTPS sweep would have found (#2780).
  5789. self.state.current_project_url = None
  5790. self._previous_gcode_state = self.state.state
  5791. if current_file:
  5792. self._previous_gcode_file = current_file
  5793. if self.on_state_change:
  5794. self.on_state_change(self.state)
  5795. def _request_push_all(self):
  5796. """Request full status update from printer."""
  5797. if self._client:
  5798. message = {"pushing": {"command": "pushall"}}
  5799. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5800. def _probe_developer_mode(self):
  5801. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5802. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5803. For these, we detect developer mode by sending a harmless command and
  5804. checking whether the printer accepts or rejects it:
  5805. - result="success" → developer mode ON (commands accepted)
  5806. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5807. The probe re-sends the current external slot configuration so it's a no-op
  5808. when the command succeeds. If there's no external slot data yet, we send a
  5809. reset (empty filament) which is also safe.
  5810. """
  5811. if not self._client or not self.state.connected:
  5812. return
  5813. self._dev_mode_probed = True
  5814. self._dev_mode_probe_time = time.monotonic()
  5815. self._sequence_id += 1
  5816. seq = str(self._sequence_id)
  5817. self._dev_mode_probe_seq = seq
  5818. # Build probe command: re-send current external slot config (no-op on success)
  5819. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5820. current = vt_tray[0] if vt_tray else {}
  5821. command = {
  5822. "print": {
  5823. "command": "ams_filament_setting",
  5824. "ams_id": 255,
  5825. "tray_id": 0,
  5826. "slot_id": 0,
  5827. "tray_info_idx": current.get("tray_info_idx", ""),
  5828. "tray_type": current.get("tray_type", ""),
  5829. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5830. "tray_color": current.get("tray_color", "00000000"),
  5831. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5832. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5833. "sequence_id": seq,
  5834. }
  5835. }
  5836. setting_id = current.get("setting_id")
  5837. if setting_id:
  5838. command["print"]["setting_id"] = setting_id
  5839. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5840. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5841. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5842. """Reconcile developer_mode with the printer's own command-verification verdict.
  5843. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5844. control commands are being refused, so it outranks the probe in both
  5845. directions:
  5846. * present → developer_mode is definitively False, whatever the probe
  5847. concluded. The probe can only read the response to its own
  5848. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5849. instead, so the probe answers ENABLED while every print silently dies
  5850. (#2732).
  5851. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5852. probe, so a user who enables Developer Mode and restarts the printer
  5853. isn't stuck behind a verdict nothing would ever revisit.
  5854. A False that came from the probe or the ``fun`` bit is left alone — this
  5855. only ever unwinds its own latch.
  5856. """
  5857. if verify_failed:
  5858. if not self._dev_mode_from_hms:
  5859. logger.warning(
  5860. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5861. "rejecting control commands, so prints, temperature changes and filament "
  5862. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5863. self.serial_number,
  5864. HMS_MQTT_VERIFY_FAILED,
  5865. )
  5866. self._dev_mode_from_hms = True
  5867. self.state.developer_mode = False
  5868. return
  5869. if not self._dev_mode_from_hms:
  5870. return
  5871. logger.info(
  5872. "[%s] HMS %s cleared — re-probing developer mode",
  5873. self.serial_number,
  5874. HMS_MQTT_VERIFY_FAILED,
  5875. )
  5876. self._dev_mode_from_hms = False
  5877. self.state.developer_mode = None
  5878. self._dev_mode_probed = False
  5879. self._dev_mode_needs_probe = False
  5880. def _handle_dev_mode_probe_response(self, data: dict):
  5881. """Handle response to the developer mode probe command.
  5882. Sets developer_mode based on whether the printer accepted or rejected the command.
  5883. Three outcomes, not two. An explicit ``success`` proves commands are
  5884. accepted and an explicit verify-failure proves they are not, but anything
  5885. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5886. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5887. ``result`` at all, while refusing every control command and reporting
  5888. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5889. is what put ``developer_mode: pass`` in the support bundle of a printer
  5890. that had not accepted a command all day (#2732). Leaving it unknown makes
  5891. the connection diagnostic report ``skip``, which is the honest answer.
  5892. """
  5893. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5894. self._dev_mode_probe_failures = 0 # Reset on any response
  5895. result = data.get("result", "")
  5896. reason = data.get("reason", "")
  5897. if result == "failed" and "verify failed" in reason:
  5898. self.state.developer_mode = False
  5899. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5900. elif str(result).lower() == "success":
  5901. self.state.developer_mode = True
  5902. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5903. else:
  5904. # An HMS verdict already recorded here is real evidence; don't let an
  5905. # inconclusive probe response wipe it back to unknown.
  5906. if not self._dev_mode_from_hms:
  5907. self.state.developer_mode = None
  5908. logger.info(
  5909. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5910. "the printer neither confirmed nor refused the command",
  5911. self.serial_number,
  5912. result,
  5913. reason,
  5914. )
  5915. if self.on_state_change:
  5916. self.on_state_change(self.state)
  5917. def _request_version(self):
  5918. """Request firmware version info from printer."""
  5919. if self._client:
  5920. self._sequence_id += 1
  5921. message = {
  5922. "info": {
  5923. "sequence_id": str(self._sequence_id),
  5924. "command": "get_version",
  5925. }
  5926. }
  5927. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5928. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5929. def request_status_update(self) -> bool:
  5930. """Request a full status update from the printer (public API).
  5931. Sends both pushall and get_accessories commands to refresh all data
  5932. including nozzle hardware info.
  5933. Returns:
  5934. True if the request was sent, False if not connected.
  5935. """
  5936. if not self._client or not self.state.connected:
  5937. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5938. return False
  5939. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  5940. self._request_push_all()
  5941. # Note: get_accessories returns stale nozzle data on H2D.
  5942. # The correct nozzle data comes from push_status response.
  5943. return True
  5944. def _prime_kprofile_request(self):
  5945. """Send a priming K-profile request on connect.
  5946. Bambu printers often ignore the first K-profile request after connection,
  5947. so we send a dummy request on connect to 'prime' the system.
  5948. """
  5949. if self._client:
  5950. self._sequence_id += 1
  5951. command = {
  5952. "print": {
  5953. "command": "extrusion_cali_get",
  5954. "filament_id": "",
  5955. "nozzle_diameter": "0.4",
  5956. "sequence_id": str(self._sequence_id),
  5957. }
  5958. }
  5959. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  5960. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5961. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  5962. """Connect to the printer MQTT broker.
  5963. Args:
  5964. loop: The asyncio event loop to use for thread-safe callbacks.
  5965. If not provided, will try to get the running loop.
  5966. """
  5967. self._loop = loop
  5968. BambuMQTTClient._client_instance_counter += 1
  5969. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  5970. self._client = mqtt.Client(
  5971. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  5972. client_id=client_id,
  5973. protocol=mqtt.MQTTv311,
  5974. )
  5975. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  5976. # tracking (#1164). The default ceiling of 20 wedges sessions after
  5977. # ~16-20 cumulative commands; lifting it well above any realistic
  5978. # session count keeps QoS=1 working without changing wire-protocol
  5979. # behaviour across printer models.
  5980. self._client.max_inflight_messages_set(1000)
  5981. self._client.username_pw_set("bblp", self.access_code)
  5982. self._client.on_connect = self._on_connect
  5983. self._client.on_disconnect = self._on_disconnect
  5984. self._client.on_subscribe = self._on_subscribe
  5985. self._client.on_message = self._on_message
  5986. # TLS setup - Bambu uses self-signed certs
  5987. ssl_context = ssl.create_default_context()
  5988. ssl_context.check_hostname = False
  5989. ssl_context.verify_mode = ssl.CERT_NONE
  5990. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  5991. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  5992. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  5993. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  5994. # bare-metal installs whose build allows TLS 1.0.
  5995. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  5996. self._client.tls_set_context(ssl_context)
  5997. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  5998. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  5999. # Keepalive: paho sends PINGREQs at this interval, broker considers
  6000. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  6001. # real network loss (45s), not so aggressive that transient hiccups
  6002. # trigger false disconnects. Stale detection (60s no messages) handles
  6003. # the P1S/P1P firmware bug where the broker stops publishing but the
  6004. # TCP connection stays alive.
  6005. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  6006. self._client.loop_start()
  6007. def start_print(
  6008. self,
  6009. filename: str,
  6010. plate_id: int = 1,
  6011. ams_mapping: list[int] | None = None,
  6012. bed_levelling: str = "auto",
  6013. flow_cali: str = "auto",
  6014. vibration_cali: bool = True,
  6015. layer_inspect: bool = False,
  6016. timelapse: bool = False,
  6017. use_ams: bool = True,
  6018. nozzle_offset_cali: str = "auto",
  6019. nozzle_mapping: str | None = None,
  6020. nozzle_slot_extruders: str | None = None,
  6021. plate_uses_only_external: bool = False,
  6022. ):
  6023. """Start a print job on the printer.
  6024. The file should already be uploaded to the printer's root directory via FTP.
  6025. Args:
  6026. filename: Name of the uploaded file
  6027. plate_id: Plate number to print (default 1)
  6028. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  6029. Global tray ID = (ams_id * 4) + slot_id, external = 254
  6030. timelapse: Record timelapse video
  6031. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  6032. if the bed was levelled recently, matching BambuStudio).
  6033. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  6034. vibration_cali: Vibration compensation calibration
  6035. layer_inspect: First layer AI inspection
  6036. use_ams: Use AMS for automatic filament changes
  6037. plate_uses_only_external: The caller determined from the plate's
  6038. own filament list that it prints only from the spool holder;
  6039. use_ams=False then stands even if the mapping names a real
  6040. tray (one another plate of the file uses, #3087)
  6041. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  6042. (dual-nozzle printers only — silently ignored on single-nozzle).
  6043. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  6044. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  6045. AND the printer is dual-nozzle, parsed and injected as the
  6046. `nozzle_mapping` array on the dispatched project_file so the
  6047. firmware honours the user's slicer pick instead of falling
  6048. back to "last matching nozzle" auto-pick. Silently ignored
  6049. on single-nozzle printers.
  6050. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  6051. MQTT extruder indices, derived from the 3MF when no
  6052. BambuStudio capture exists (#2800). Consulted only on
  6053. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  6054. not already supply one; resolved here into physical rack
  6055. positions using the live `device.nozzle` state. When it
  6056. cannot be resolved the field is omitted and the firmware
  6057. picks, as it did before this existed.
  6058. Returns True when the start command was published, False otherwise
  6059. (not connected, or the printer is already busy — see the run-state
  6060. guard below).
  6061. """
  6062. # Never dispatch project_file to a printer that is not idle (#2598).
  6063. # This is the single publish choke point for every dispatch path — the
  6064. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  6065. # forwarded job all funnel through here — so one guard covers them all.
  6066. # The firmware rejects a start while busy with 0500_4004 ("Device is
  6067. # busy and cannot start a new task"), and on an A1 mini that error
  6068. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  6069. # start targets; only the active-print states are refused. (A
  6070. # transport-level QoS-1 replay on reconnect would bypass this guard;
  6071. # _on_connect empties paho's outbox before it can re-send (#3454).)
  6072. if self.state.state in _ACTIVE_PRINT_STATES:
  6073. logger.warning(
  6074. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  6075. self.serial_number,
  6076. self.state.state,
  6077. filename,
  6078. )
  6079. return False
  6080. if self._client and self.state.connected:
  6081. # Bambu print command format — matches Bambu Studio's format.
  6082. # The calibration/leveling fields (timelapse, bed_leveling,
  6083. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  6084. # every model. An earlier revision integer-encoded them for the H2
  6085. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  6086. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  6087. # sends plain booleans, and the integer encoding made the H2S
  6088. # silently skip flow-dynamics calibration (#1478). use_ams is the
  6089. # one field that genuinely must stay boolean: H2D Pro firmware
  6090. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  6091. # what actually caused the wrong-extruder routing behind #1386.
  6092. # Dual-nozzle routing for external spool (254 = deputy/left,
  6093. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  6094. # H2 firmware family but is single-nozzle, despite sharing serial
  6095. # prefix "094" with H2D. Prefer runtime detection from
  6096. # device.extruder.info (set in _handle_push_status); fall back to
  6097. # model name for the brief window after connect before push data
  6098. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  6099. # as the primary signal.
  6100. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  6101. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6102. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  6103. ams_mapping2 = []
  6104. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  6105. # ams_mapping and relies on ams_mapping2 for external spool details.
  6106. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  6107. # with 0700_8012 "Failed to get AMS mapping table".
  6108. flat_ams_mapping = []
  6109. layout = self.tray_layout
  6110. if ams_mapping is not None:
  6111. for tray_id in ams_mapping:
  6112. # Ensure tray_id is an integer (may be string from JSON)
  6113. tray_id = int(tray_id) if tray_id is not None else -1
  6114. rack_slot = layout.rack_slot(tray_id) if tray_id >= 0 else None
  6115. if tray_id == -1:
  6116. # Unmapped filament slot
  6117. flat_ams_mapping.append(-1)
  6118. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  6119. elif layout.rack and layout.is_external(tray_id):
  6120. # A rack printer's per-hotend input 247-255, as Studio
  6121. # sends it: -1 flat, its own id in ams_mapping2.
  6122. flat_ams_mapping.append(-1)
  6123. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6124. elif rack_slot is not None:
  6125. # Rack AMS slot, as Studio sends it: 28 + k flat,
  6126. # {ams_id: 32, slot_id: k} in ams_mapping2.
  6127. flat_ams_mapping.append(tray_id)
  6128. ams_mapping2.append({"ams_id": rack_slot[0], "slot_id": rack_slot[1]})
  6129. elif tray_id >= 254:
  6130. # External/virtual spool. BambuStudio convention:
  6131. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  6132. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  6133. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  6134. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  6135. # for external spool, but BambuStudio always sends ams_id=255
  6136. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  6137. # firmware to target AMS tray 0 instead of external spool, leading
  6138. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  6139. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  6140. flat_ams_mapping.append(-1)
  6141. ext_ams_id = tray_id if is_dual_nozzle else 255
  6142. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  6143. elif tray_id >= 128:
  6144. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  6145. flat_ams_mapping.append(tray_id)
  6146. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6147. elif (_a2l := a2l_lite_wire_ids(layout.slot_key(tray_id)[0], tray_id)) is not None:
  6148. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  6149. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  6150. # — both CONFIRMED against the firmware's own mapping
  6151. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  6152. _wire_ams, _wire_slot, _ = _a2l
  6153. flat_ams_mapping.append(_wire_slot)
  6154. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  6155. else:
  6156. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  6157. ams_id, slot_id = layout.slot_key(tray_id)
  6158. flat_ams_mapping.append(tray_id)
  6159. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  6160. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  6161. # printers — the mapping is authoritative about whether this print
  6162. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  6163. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  6164. # H2S falls through here now (#1386): it is single-nozzle and was
  6165. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  6166. # without an AMS attached.
  6167. #
  6168. # Two symmetric corrections:
  6169. #
  6170. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  6171. # use_ams=True even if it arrived False. A print sent to a Virtual
  6172. # Printer is sliced against the VP, which advertises no AMS, so the
  6173. # slicer sends use_ams=false and that gets stamped on the queue item
  6174. # — but at dispatch the scheduler colour-matches a real printer and
  6175. # resolves a real AMS slot. Without this, the stale False reaches the
  6176. # printer, which ignores the mapped slot and aborts at layer 0 on the
  6177. # empty external spool ("not enough filament"). Diagnosed by
  6178. # @Sawtaytoes (#2595, PR #2596).
  6179. #
  6180. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  6181. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  6182. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  6183. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  6184. # status-load race that persisted [-1] (#2589) — and treating it as
  6185. # external silently started the print against an empty feed. A genuine
  6186. # external selection is >=254; unresolved is -1; a loaded tray is
  6187. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  6188. # (or is recomputed upstream) instead of silently going external, and
  6189. # never gets force-enabled by (a) either.
  6190. if ams_mapping and not is_dual_nozzle:
  6191. has_real_tray = any(
  6192. t is not None and 0 <= int(t) <= 253 and not layout.is_external(int(t)) for t in ams_mapping
  6193. )
  6194. all_external = all(t is None or int(t) >= 254 or layout.is_external(int(t)) for t in ams_mapping)
  6195. # (Not when the scheduler worked out from the plate's own
  6196. # filament list that it prints only from the spool holder: a
  6197. # real tray here is then one another plate of the file uses.)
  6198. if has_real_tray and not use_ams and not plate_uses_only_external:
  6199. use_ams = True
  6200. logger.info(
  6201. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  6202. self.serial_number,
  6203. )
  6204. elif use_ams and all_external:
  6205. use_ams = False
  6206. logger.info(
  6207. "[%s] All filament slots use external spool — setting use_ams=False",
  6208. self.serial_number,
  6209. )
  6210. # (c) A single-nozzle printer that reported no AMS at all can only
  6211. # print from the spool holder, whatever the mapping says. With
  6212. # nothing set on the holder the matcher resolves no mapping, so
  6213. # neither (a) nor (b) ran and the print went out as use_ams=True,
  6214. # which the firmware refuses with 07FF_8012 "Failed to get AMS
  6215. # mapping table" (#3356). An empty raw_data["ams"] is the
  6216. # printer's own report of no AMS; a missing key means no AMS
  6217. # push has been handled yet (a reconnect), which changes nothing.
  6218. if use_ams and not is_dual_nozzle and self.state.raw_data.get("ams") == []:
  6219. use_ams = False
  6220. logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
  6221. # Unique per-submission identity fields. Hardcoded "0" values caused
  6222. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  6223. # continuations of the same job: the printer reuses gcode_start_time
  6224. # from the prior print with task_id=0, so observers latch onto a stale
  6225. # timestamp and report compounding durations on repeat replays (#1011).
  6226. # BambuStudio mints fresh IDs per submission; matching that behavior
  6227. # makes the printer emit a clean state-transition for each job.
  6228. # md5 is left empty — firmware historically accepts "" as "skip
  6229. # validation" (unlike Studio, we don't have the file's real md5 here
  6230. # without re-reading the upload, and sending a synthetic wrong digest
  6231. # risks activation of md5 verification on some firmwares).
  6232. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  6233. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  6234. # overflows and every submission ends up with the same task_id from
  6235. # the printer's perspective — the printer then treats a fresh dispatch
  6236. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  6237. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  6238. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  6239. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  6240. # Remember it so on_print_start can persist a restart-stable id on
  6241. # the archive even before the printer echoes subtask_id back (#1485).
  6242. self.last_dispatch_subtask_id = submission_id
  6243. self.last_start_refusal = None
  6244. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  6245. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  6246. # only if it wasn't done recently). The paired bool field is true
  6247. # only for the explicit "on" state — for "auto" the bool is false and
  6248. # the int carries the intent, exactly as BambuStudio's SelectMachine
  6249. # sends it. Unknown values fall back to auto.
  6250. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  6251. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  6252. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  6253. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  6254. command = {
  6255. "print": {
  6256. "sequence_id": "20000",
  6257. "command": "project_file",
  6258. "param": f"Metadata/plate_{plate_id}.gcode",
  6259. "url": f"ftp://{filename}",
  6260. "file": filename,
  6261. "md5": "",
  6262. "bed_type": "auto",
  6263. "timelapse": timelapse,
  6264. # bed_leveling stays a JSON bool (true only for "on") and
  6265. # auto_bed_leveling carries the tri-state int — the exact
  6266. # two-field shape BambuStudio sends. The int must stay a plain
  6267. # number, never quoted (#1478 boolean-family concern applies to
  6268. # the *_cali bools, not these companion ints).
  6269. "bed_leveling": bed_levelling == "on",
  6270. "auto_bed_leveling": bed_level_int,
  6271. "flow_cali": flow_cali == "on",
  6272. "vibration_cali": vibration_cali,
  6273. "layer_inspect": layer_inspect,
  6274. "use_ams": use_ams,
  6275. # No "cfg": it is the printer's device-config bitmask
  6276. # (auto-refill, detect-on-insert, chamber light, ...), not a
  6277. # per-job field — BambuStudio's PrintParams has no such
  6278. # member. We used to send "0"; firmware ignores it, but it
  6279. # comes straight back in the project_file ack (#3040).
  6280. # extrude_cali_flag gates flow-dynamics calibration:
  6281. # 0 = never, 1 = force every print, 2 = auto (run only if the
  6282. # filament wasn't calibrated recently). #1721 saw stage 8
  6283. # ("Calibrating dynamic flow") still queued when we send 2 —
  6284. # that is exactly the auto contract (the printer queues the
  6285. # stage and skips it at runtime if recent), not a bug, so 2 is
  6286. # the right wire value for "auto". off/on remain 0/1.
  6287. "extrude_cali_flag": flow_cali_int,
  6288. "extrude_cali_manual_mode": 0,
  6289. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  6290. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  6291. # again the auto contract, not a failure to suppress.
  6292. # BambuStudio exposes the toggle only for dual-nozzle
  6293. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  6294. # firmware never runs a calibration the head doesn't support.
  6295. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  6296. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  6297. "profile_id": "0",
  6298. "project_id": submission_id,
  6299. "subtask_id": submission_id,
  6300. "task_id": submission_id,
  6301. }
  6302. }
  6303. # P2S-specific parameter adjustments
  6304. # P2S printer doesn't support vibration calibration like X1/P1 series
  6305. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  6306. command["print"]["vibration_cali"] = False
  6307. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  6308. # Add AMS mapping if provided
  6309. if ams_mapping is not None:
  6310. command["print"]["ams_mapping"] = flat_ams_mapping
  6311. command["print"]["ams_mapping2"] = ams_mapping2
  6312. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  6313. # `nozzle_mapping` carries per-filament physical nozzle position
  6314. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  6315. # item; parse here so the wire ships an array, matching
  6316. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  6317. # defensively — single-nozzle firmwares would ignore the field
  6318. # but we err on the side of not emitting unrecognised fields. A
  6319. # parse failure is logged but never blocks the dispatch — the
  6320. # firmware will fall back to its auto-pick path, which is the
  6321. # pre-fix behaviour.
  6322. if is_dual_nozzle and nozzle_mapping:
  6323. try:
  6324. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  6325. except json.JSONDecodeError:
  6326. logger.warning(
  6327. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  6328. "project_file (firmware will auto-pick): %r",
  6329. self.serial_number,
  6330. nozzle_mapping,
  6331. )
  6332. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  6333. # never saw the job, so it can never override a real capture. The
  6334. # queue stores extruder indices per filament slot; the physical
  6335. # rack position they resolve to is only knowable here, because the
  6336. # mounted hotend can change between queueing and dispatch.
  6337. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  6338. try:
  6339. slot_extruders = json.loads(nozzle_slot_extruders)
  6340. except (json.JSONDecodeError, TypeError):
  6341. # TypeError covers a caller handing us the list itself
  6342. # rather than its JSON — the field is opaque by contract,
  6343. # and a print must not die over the difference.
  6344. slot_extruders = None
  6345. logger.warning(
  6346. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  6347. "omitting nozzle_mapping (firmware will auto-pick): %r",
  6348. self.serial_number,
  6349. nozzle_slot_extruders,
  6350. )
  6351. if isinstance(slot_extruders, list):
  6352. rack_nozzle_id = (
  6353. self.state.nozzle_rack_tar_id
  6354. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  6355. else self.state.nozzle_rack_src_id
  6356. )
  6357. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  6358. if resolved is None:
  6359. logger.info(
  6360. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  6361. "omitting nozzle_mapping so the firmware picks",
  6362. self.serial_number,
  6363. slot_extruders,
  6364. self.state.nozzle_rack_tar_id,
  6365. self.state.nozzle_rack_src_id,
  6366. )
  6367. else:
  6368. logger.info(
  6369. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  6370. self.serial_number,
  6371. slot_extruders,
  6372. rack_nozzle_id,
  6373. resolved,
  6374. )
  6375. command["print"]["nozzle_mapping"] = resolved
  6376. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  6377. # Remember this dispatch so its echo on the topic is recognised as
  6378. # ours rather than logged as a slicer's.
  6379. self._own_project_file_key = self._project_file_key(command["print"])
  6380. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6381. # Record what we dispatched so /cover can pick the right plate
  6382. # thumbnail even when the printer's gcode_file echo is just the
  6383. # 3MF filename without a plate path (#1166). Match the same
  6384. # subtask_name shape we send so the comparison in the cover route
  6385. # works against state.subtask_name reflected back via MQTT.
  6386. self.state.dispatched_plate_id = plate_id
  6387. self.state.dispatched_subtask = command["print"]["subtask_name"]
  6388. return True
  6389. else:
  6390. # Log why we couldn't send the command
  6391. if not self._client:
  6392. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  6393. elif not self.state.connected:
  6394. logger.error(
  6395. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  6396. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  6397. )
  6398. return False
  6399. def stop_print(self) -> bool:
  6400. """Stop the current print job."""
  6401. if self._client and self.state.connected:
  6402. command = {"print": {"command": "stop", "sequence_id": "0"}}
  6403. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6404. logger.info("[%s] Sent stop print command", self.serial_number)
  6405. return True
  6406. return False
  6407. def set_xcam_option(
  6408. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  6409. ) -> bool:
  6410. """Set an xcam (AI detection) option on the printer.
  6411. Args:
  6412. module_name: The xcam module to control (e.g., "spaghetti_detector",
  6413. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  6414. enabled: Whether to enable or disable the feature
  6415. print_halt: Whether to halt print on detection (only applies to some detectors)
  6416. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  6417. Returns:
  6418. True if command was sent, False if not connected
  6419. """
  6420. if not self._client or not self.state.connected:
  6421. return False
  6422. # auto_recovery_step_loss uses a different command format (print.print_option)
  6423. if module_name == "auto_recovery_step_loss":
  6424. return self._set_print_option("auto_recovery", enabled)
  6425. self._sequence_id += 1
  6426. # Build the xcam control command (exact OrcaSlicer format)
  6427. # Key findings from OrcaSlicer source:
  6428. # - Uses "xcam" wrapper (not "print")
  6429. # - print_halt is ALWAYS true (legacy protocol requirement)
  6430. # - Both "control" and "enable" are set to the same value
  6431. # - halt_print_sensitivity controls actual halt behavior
  6432. command = {
  6433. "xcam": {
  6434. "command": "xcam_control_set",
  6435. "sequence_id": str(self._sequence_id),
  6436. "module_name": module_name,
  6437. "control": enabled,
  6438. "enable": enabled, # old protocol compatibility
  6439. "print_halt": True, # ALWAYS true per OrcaSlicer
  6440. }
  6441. }
  6442. # Only add sensitivity if not "never_halt"
  6443. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  6444. # The module_name field determines which detector's sensitivity is being set
  6445. if sensitivity and sensitivity != "never_halt":
  6446. command["xcam"]["halt_print_sensitivity"] = sensitivity
  6447. command_json = json.dumps(command)
  6448. self._client.publish(self.topic_publish, command_json, qos=1)
  6449. logger.debug(
  6450. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  6451. )
  6452. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  6453. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  6454. # This prevents stale MQTT data from immediately overwriting our change
  6455. self._xcam_hold_start[module_name] = time.time()
  6456. # Update local state immediately for responsive UI
  6457. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  6458. # When spaghetti_detector sensitivity is changed, pileup also changes
  6459. if module_name == "spaghetti_detector":
  6460. self.state.print_options.spaghetti_detector = enabled
  6461. self.state.print_options.print_halt = print_halt
  6462. if sensitivity and sensitivity != "never_halt":
  6463. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  6464. self.state.print_options.halt_print_sensitivity = sensitivity
  6465. self.state.print_options.pileup_sensitivity = sensitivity
  6466. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  6467. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  6468. elif module_name == "first_layer_inspector":
  6469. self.state.print_options.first_layer_inspector = enabled
  6470. elif module_name == "printing_monitor":
  6471. self.state.print_options.printing_monitor = enabled
  6472. elif module_name == "buildplate_marker_detector":
  6473. self.state.print_options.buildplate_marker_detector = enabled
  6474. elif module_name == "allow_skip_parts":
  6475. self.state.print_options.allow_skip_parts = enabled
  6476. elif module_name == "pileup_detector":
  6477. self.state.print_options.pileup_detector = enabled
  6478. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  6479. elif module_name == "clump_detector":
  6480. self.state.print_options.nozzle_clumping_detector = enabled
  6481. if sensitivity and sensitivity != "never_halt":
  6482. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  6483. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  6484. elif module_name == "airprint_detector":
  6485. self.state.print_options.airprint_detector = enabled
  6486. if sensitivity and sensitivity != "never_halt":
  6487. self.state.print_options.airprint_sensitivity = sensitivity
  6488. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  6489. elif module_name == "auto_recovery_step_loss":
  6490. self.state.print_options.auto_recovery_step_loss = enabled
  6491. return True
  6492. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  6493. """Set a print option using the print.print_option command.
  6494. This is different from xcam_control_set and is used for options like:
  6495. - auto_recovery
  6496. - air_print_detect
  6497. - filament_tangle_detect
  6498. - nozzle_blob_detect
  6499. - sound_enable
  6500. Args:
  6501. option_name: The option to control (e.g., "auto_recovery")
  6502. enabled: Whether to enable or disable the option
  6503. Returns:
  6504. True if command was sent, False if not connected
  6505. """
  6506. if not self._client or not self.state.connected:
  6507. return False
  6508. self._sequence_id += 1
  6509. command = {
  6510. "print": {
  6511. "command": "print_option",
  6512. "sequence_id": str(self._sequence_id),
  6513. option_name: enabled,
  6514. }
  6515. }
  6516. command_json = json.dumps(command)
  6517. self._client.publish(self.topic_publish, command_json, qos=1)
  6518. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  6519. # Set hold timer
  6520. hold_key = f"print_option_{option_name}"
  6521. self._xcam_hold_start[hold_key] = time.time()
  6522. # Update local state immediately
  6523. if option_name == "auto_recovery":
  6524. self.state.print_options.auto_recovery_step_loss = enabled
  6525. elif option_name == "auto_switch_filament":
  6526. self.state.ams_filament_backup = enabled
  6527. return True
  6528. def set_ams_filament_backup(self, enabled: bool) -> bool:
  6529. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  6530. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  6531. shape from H2D capture 2026-06-20.
  6532. """
  6533. return self._set_print_option("auto_switch_filament", enabled)
  6534. def start_calibration(
  6535. self,
  6536. bed_leveling: bool = False,
  6537. vibration: bool = False,
  6538. motor_noise: bool = False,
  6539. nozzle_offset: bool = False,
  6540. high_temp_heatbed: bool = False,
  6541. ) -> bool:
  6542. """Start printer calibration with selected options.
  6543. Args:
  6544. bed_leveling: Run bed leveling calibration
  6545. vibration: Run vibration compensation calibration
  6546. motor_noise: Run motor noise cancellation calibration
  6547. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  6548. high_temp_heatbed: Run high-temperature heatbed calibration
  6549. Returns:
  6550. True if command was sent, False if not connected
  6551. """
  6552. if not self._client or not self.state.connected:
  6553. return False
  6554. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  6555. # Bit 0: xcam_cali (not exposed in UI)
  6556. # Bit 1: bed_leveling
  6557. # Bit 2: vibration
  6558. # Bit 3: motor_noise
  6559. # Bit 4: nozzle_cali
  6560. # Bit 5: bed_cali (high-temp heatbed)
  6561. # Bit 6: clumppos_cali (not exposed in UI)
  6562. option = 0
  6563. if bed_leveling:
  6564. option |= 1 << 1
  6565. if vibration:
  6566. option |= 1 << 2
  6567. if motor_noise:
  6568. option |= 1 << 3
  6569. if nozzle_offset:
  6570. option |= 1 << 4
  6571. if high_temp_heatbed:
  6572. option |= 1 << 5
  6573. if option == 0:
  6574. logger.warning("[%s] No calibration options selected", self.serial_number)
  6575. return False
  6576. self._sequence_id += 1
  6577. command = {
  6578. "print": {
  6579. "command": "calibration",
  6580. "sequence_id": str(self._sequence_id),
  6581. "option": option,
  6582. }
  6583. }
  6584. command_json = json.dumps(command)
  6585. self._client.publish(self.topic_publish, command_json, qos=1)
  6586. logger.info(
  6587. f"[{self.serial_number}] Starting calibration: "
  6588. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  6589. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  6590. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  6591. )
  6592. return True
  6593. def disconnect(self, timeout: float = 0):
  6594. """Disconnect from the printer.
  6595. Waits up to *timeout* for paho to report the disconnect, then lets the
  6596. client go without joining its network thread — the callers are route
  6597. handlers (printer edited, deleted, disconnected by hand) running on the
  6598. asyncio thread, and that join has no bound (#3068)."""
  6599. if self._client:
  6600. old_client = self._client
  6601. self._disconnection_event = threading.Event()
  6602. old_client.disconnect()
  6603. # The callback that sets this fires on paho's thread, so it has to
  6604. # be given its window before retire_paho_client detaches it.
  6605. self._disconnection_event.wait(timeout=timeout)
  6606. self._client = None
  6607. retire_paho_client(old_client, self.serial_number)
  6608. self.state.connected = False
  6609. # Deliberately no on_state_change here. paho's disconnect callback
  6610. # used to land during the join, but `_on_disconnect` suppresses
  6611. # itself for a clean disconnect of a printer that reported within
  6612. # the last 10s -- which is every healthy printer -- so a
  6613. # hand-disconnected printer never broadcast one. Announcing it now
  6614. # would fire the connected→disconnected edge in
  6615. # `on_printer_status_change` and notify the user their printer went
  6616. # offline a minute after they disconnected it on purpose (#1752).
  6617. # The callers drop the client from the manager anyway, so the next
  6618. # status read already shows it gone.
  6619. def enable_logging(self, enabled: bool = True):
  6620. """Enable or disable MQTT message logging."""
  6621. self._logging_enabled = enabled
  6622. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6623. def get_logs(self) -> list[MQTTLogEntry]:
  6624. """Get all logged MQTT messages."""
  6625. return list(self._message_log)
  6626. def clear_logs(self):
  6627. """Clear the message log."""
  6628. self._message_log.clear()
  6629. @property
  6630. def logging_enabled(self) -> bool:
  6631. """Check if logging is enabled."""
  6632. return self._logging_enabled
  6633. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6634. """Register a handler invoked for every incoming MQTT message.
  6635. Used by the VP MQTT bridge to republish the printer's report pushes to
  6636. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6637. on paho's network thread and must not block; exceptions are caught.
  6638. """
  6639. if handler not in self._raw_message_handlers:
  6640. self._raw_message_handlers.append(handler)
  6641. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6642. """Unregister a previously-registered raw-message handler."""
  6643. try:
  6644. self._raw_message_handlers.remove(handler)
  6645. except ValueError:
  6646. pass
  6647. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6648. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6649. Used by the VP MQTT bridge to forward slicer-originated commands without
  6650. giving it one of our own sequence ids. Returns False if the
  6651. underlying paho client isn't ready.
  6652. """
  6653. if self._client is None:
  6654. return False
  6655. try:
  6656. info = self._client.publish(topic, payload, qos=qos)
  6657. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6658. except Exception:
  6659. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6660. return False
  6661. def _ams3h_drying_zone_id(self, ams_id: int) -> int:
  6662. """The drying zone id of AMS 3H unit ``ams_id`` from the last status, else 0."""
  6663. unit = self._ams_unit(ams_id)
  6664. return _mqtt_int((unit or {}).get("dry_zone_id")) or 0
  6665. def send_drying_command(
  6666. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6667. ):
  6668. """Send AMS drying start/stop command.
  6669. Args:
  6670. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6671. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6672. duration: Drying duration in hours
  6673. mode: 1=start, 0=stop
  6674. filament: Filament type string (e.g. "PLA", "PETG")
  6675. rotate_tray: Whether to rotate the spool during drying for even heat
  6676. """
  6677. if not self._client:
  6678. return False
  6679. self._sequence_id += 1
  6680. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6681. # not actually support drying, but keep the translation consistent). The
  6682. # _drying_targets dict below stays keyed by the normalised id so the
  6683. # on_drying_complete callback matches the telemetry.
  6684. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6685. ams3h = self._rack_ams_type(ams_id) == AmsType.ZMULTI_A
  6686. command = {
  6687. "print": {
  6688. "sequence_id": str(self._sequence_id),
  6689. "command": "ams_filament_drying",
  6690. "ams_id": wire_ams_id,
  6691. "temp": temp,
  6692. "cooling_temp": 20 if mode == 1 else 0,
  6693. "duration": duration,
  6694. "humidity": 0,
  6695. "mode": mode,
  6696. "rotate_tray": rotate_tray,
  6697. "filament": filament,
  6698. "close_power_conflict": False,
  6699. }
  6700. }
  6701. if ams3h:
  6702. # As Studio 02.09 sends it (DevFilaSystemCtrl.cpp): a start names
  6703. # the drying zone and cooling_temp; a stop names no zone. The AMS 3H
  6704. # can't turn spools.
  6705. command["print"]["rotate_tray"] = False
  6706. if mode == 1:
  6707. command["print"]["zone_id"] = self._ams3h_drying_zone_id(ams_id)
  6708. command["print"]["cooling_temp"] = ams3h_drying_cooling_temp(filament)
  6709. # Log the full wire JSON at INFO so support bundles capture exactly
  6710. # what we sent — needed to diagnose silent rejections (#1447) where
  6711. # the printer ACKs the command but never starts/stops drying.
  6712. # Paired with the ams_filament_drying response-payload INFO log so
  6713. # both halves of the conversation land in the bundle by default.
  6714. wire_json = json.dumps(command)
  6715. self._client.publish(self.topic_publish, wire_json, qos=1)
  6716. logger.info(
  6717. "[%s] Sent ams_filament_drying: %s",
  6718. self.serial_number,
  6719. wire_json,
  6720. )
  6721. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6722. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6723. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6724. # say how much of the requested time the firmware actually ran (#2770).
  6725. if mode == 1:
  6726. self._drying_targets[ams_id] = {
  6727. "filament": filament or "",
  6728. "temp": int(temp),
  6729. "duration_hours": int(duration),
  6730. }
  6731. self._drying_stops_sent.discard(ams_id)
  6732. # A start sent while a cycle is still counting down replaces it
  6733. # without dry_time passing through 0; begin a fresh record so the
  6734. # new target and length are the ones reported (#2863).
  6735. self._dry_cycles.pop(ams_id, None)
  6736. else:
  6737. self._drying_targets.pop(ams_id, None)
  6738. # Remember that this cycle's end is ours, so the cycle-end log
  6739. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6740. # stop always ends the cycle far short of its duration, which is
  6741. # otherwise indistinguishable from the firmware abandoning it.
  6742. self._drying_stops_sent.add(ams_id)
  6743. return True
  6744. @staticmethod
  6745. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6746. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6747. The printer reports ``nozzle_diameter`` **only on the response
  6748. envelope** — the per-filament entries carry just setting_id,
  6749. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6750. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6751. single-nozzle printers regardless of the installed nozzle (#1748),
  6752. which broke the K-Profiles display and, worse, the cali_idx cascade
  6753. in the inventory/Spoolman assign paths that matches on
  6754. nozzle_diameter. Fall back to the envelope value instead, and only
  6755. to "0.4" when the envelope has none either.
  6756. ``or`` rather than a dict default on purpose: it also covers an entry
  6757. that carries the key with an empty value, and stops ``str()`` turning
  6758. a missing envelope value into the literal "None".
  6759. """
  6760. profiles: list[KProfile] = []
  6761. for i, f in enumerate(filaments):
  6762. if not isinstance(f, dict):
  6763. continue
  6764. try:
  6765. profiles.append(
  6766. KProfile(
  6767. # cali_idx is the actual slot/calibration index from the printer
  6768. slot_id=f.get("cali_idx", i),
  6769. extruder_id=int(f.get("extruder_id", 0)),
  6770. nozzle_id=str(f.get("nozzle_id", "")),
  6771. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6772. filament_id=str(f.get("filament_id", "")),
  6773. name=str(f.get("name", "")),
  6774. k_value=str(f.get("k_value", "0.000000")),
  6775. n_coef=str(f.get("n_coef", "0.000000")),
  6776. ams_id=int(f.get("ams_id", 0)),
  6777. tray_id=int(f.get("tray_id", -1)),
  6778. setting_id=f.get("setting_id"),
  6779. )
  6780. )
  6781. except (ValueError, TypeError) as e:
  6782. # Skip malformed entries; the remaining profiles stay usable.
  6783. # Unsolicited broadcasts arrive constantly, so only a response
  6784. # someone is actually waiting on is worth a warning.
  6785. if log_errors:
  6786. logger.warning("Failed to parse K-profile: %s", e)
  6787. else:
  6788. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6789. return profiles
  6790. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6791. """File one calibration-table response under its nozzle diameter.
  6792. ``response_nozzle`` names the table the printer just sent, so that
  6793. bucket is replaced wholesale and every other one is left alone. When
  6794. the envelope carries no diameter, fall back to the diameters the parsed
  6795. profiles claim for themselves — and if there are none of those either,
  6796. keep what we have rather than dropping a table we cannot attribute.
  6797. ``state.kprofiles`` stays a flat list because that is what its readers
  6798. expect; the three assign paths already filter it by ``nozzle_diameter``
  6799. and were quietly finding nothing whenever the last response happened to
  6800. be for a different nozzle.
  6801. """
  6802. buckets: dict[str, list] = {}
  6803. if response_nozzle:
  6804. buckets[str(response_nozzle)] = list(profiles)
  6805. else:
  6806. for profile in profiles:
  6807. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6808. if not buckets:
  6809. return
  6810. self._kprofiles_by_nozzle.update(buckets)
  6811. self.state.kprofiles = [
  6812. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6813. ]
  6814. def _handle_kprofile_response(self, data: dict):
  6815. """Handle K-profile response from printer."""
  6816. response_nozzle = data.get("nozzle_diameter")
  6817. response_seq_id = str(data.get("sequence_id", ""))
  6818. filaments = data.get("filaments", [])
  6819. # Snapshot the map: the asyncio thread adds and removes entries while
  6820. # this MQTT callback thread walks it.
  6821. pending = dict(self._pending_kprofile_requests)
  6822. request = pending.get(response_seq_id)
  6823. if request is None and pending:
  6824. # Firmware that doesn't echo our sequence_id still has to be
  6825. # served, so fall back to the pre-#1748 rule of matching on the
  6826. # nozzle size. Only requests still waiting are eligible, and the
  6827. # sequence_id lookup above has already claimed any response that
  6828. # identifies itself, so this can no longer hand request A's
  6829. # answer to request B when both are in flight.
  6830. request = next(
  6831. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6832. None,
  6833. )
  6834. if pending:
  6835. logger.info(
  6836. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6837. self.serial_number,
  6838. response_nozzle,
  6839. response_seq_id or "?",
  6840. len(filaments),
  6841. request is not None,
  6842. )
  6843. if request is None and pending:
  6844. # A request is outstanding and this isn't its answer. The printer
  6845. # broadcasts extrusion_cali_get unsolicited, so letting this
  6846. # through would replace state.kprofiles with another nozzle's
  6847. # profiles while the caller is still waiting.
  6848. logger.debug(
  6849. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6850. self.serial_number,
  6851. response_nozzle,
  6852. response_seq_id or "?",
  6853. )
  6854. return
  6855. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6856. self._store_kprofiles(profiles, response_nozzle)
  6857. if request is None:
  6858. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6859. # nobody to wake. Worth a line — this is the printer answering
  6860. # somebody else (BambuStudio queries the same report topic), and
  6861. # until it was bucketed by nozzle it was also the quietest way for
  6862. # the AMS card's K values to change underneath us.
  6863. logger.debug(
  6864. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6865. self.serial_number,
  6866. response_nozzle or "?",
  6867. len(profiles),
  6868. )
  6869. return
  6870. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6871. request["profiles"] = profiles
  6872. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6873. # in a different thread than the event loop.
  6874. event = request["event"]
  6875. if self._loop and self._loop.is_running():
  6876. self._loop.call_soon_threadsafe(event.set)
  6877. else:
  6878. # Fallback for when loop is not available
  6879. event.set()
  6880. async def get_kprofiles(
  6881. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6882. ) -> list[KProfile]:
  6883. """Request K-profiles from the printer with retry logic.
  6884. Bambu printers sometimes ignore the first K-profile request, so we
  6885. implement retry logic to ensure reliable retrieval.
  6886. Args:
  6887. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6888. timeout: Timeout in seconds to wait for each response attempt
  6889. max_retries: Maximum number of retry attempts
  6890. Returns:
  6891. List of KProfile objects; empty when the printer has none for
  6892. the nozzle.
  6893. Raises:
  6894. KProfileReadError: not connected, or no answer to any attempt.
  6895. Returning an empty list made that a printer without profiles
  6896. (#3404).
  6897. """
  6898. if not self._client or not self.state.connected:
  6899. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6900. raise KProfileReadError("Printer not connected")
  6901. # Capture current event loop for thread-safe callback
  6902. try:
  6903. self._loop = asyncio.get_running_loop()
  6904. except RuntimeError:
  6905. logger.warning("[%s] No running event loop", self.serial_number)
  6906. raise KProfileReadError("No running event loop") from None
  6907. for attempt in range(max_retries):
  6908. # Register this attempt under its own sequence_id so a concurrent
  6909. # request for a different nozzle size can't consume its response
  6910. # (#1748) — the pending map is keyed by exactly the id we send.
  6911. self._sequence_id += 1
  6912. seq_id = str(self._sequence_id)
  6913. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6914. self._pending_kprofile_requests[seq_id] = request
  6915. # Send the command with nozzle_diameter filter
  6916. command = {
  6917. "print": {
  6918. "command": "extrusion_cali_get",
  6919. "filament_id": "",
  6920. "nozzle_diameter": nozzle_diameter,
  6921. "sequence_id": seq_id,
  6922. }
  6923. }
  6924. logger.info(
  6925. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6926. )
  6927. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6928. # Wait for the response (the handler matches it back to this entry)
  6929. try:
  6930. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6931. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6932. profiles = request["profiles"] or []
  6933. logger.info(
  6934. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6935. )
  6936. return profiles
  6937. except TimeoutError:
  6938. logger.warning(
  6939. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  6940. )
  6941. if attempt < max_retries - 1:
  6942. # Brief delay before retry
  6943. await asyncio.sleep(0.5)
  6944. finally:
  6945. self._pending_kprofile_requests.pop(seq_id, None)
  6946. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  6947. raise KProfileReadError("The printer did not answer the K-profile request")
  6948. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  6949. """Publish a K-profile write and arm its ack slot.
  6950. Registration happens before the publish because the printer answers in
  6951. well under a second — measured at 70-150ms — which is comfortably
  6952. before an async caller gets back to awaiting.
  6953. """
  6954. self._pending_cali_acks[seq_id] = None
  6955. try:
  6956. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6957. except Exception:
  6958. self._pending_cali_acks.pop(seq_id, None)
  6959. raise
  6960. return True
  6961. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  6962. """Wait for the printer's verdict on a K-profile write.
  6963. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  6964. explicitly said ``result: "fail"`` — a timeout returns True with a
  6965. detail string, because "no answer" is not evidence of rejection and
  6966. older firmware may not answer at all. Callers that need certainty read
  6967. the calibration table back.
  6968. Polled rather than event-driven on purpose: the ack is filled in by the
  6969. MQTT callback thread, and polling a dict costs one lookup every 50ms
  6970. for at most a few hundred milliseconds, against the cross-thread
  6971. event plumbing it would otherwise take.
  6972. """
  6973. deadline = time.monotonic() + timeout
  6974. try:
  6975. while time.monotonic() < deadline:
  6976. ack = self._pending_cali_acks.get(seq_id)
  6977. if ack is not None:
  6978. result = str(ack.get("result", "")).lower()
  6979. reason = str(ack.get("reason", "") or "")
  6980. if result == "fail":
  6981. return (False, reason or "printer reported failure")
  6982. return (True, reason)
  6983. await asyncio.sleep(0.05)
  6984. finally:
  6985. self._pending_cali_acks.pop(seq_id, None)
  6986. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  6987. return (True, CALI_ACK_UNCONFIRMED)
  6988. def set_kprofile(
  6989. self,
  6990. filament_id: str,
  6991. name: str,
  6992. k_value: str,
  6993. nozzle_diameter: str = "0.4",
  6994. nozzle_id: str = "HS00-0.4",
  6995. extruder_id: int = 0,
  6996. setting_id: str | None = None,
  6997. slot_id: int = 0,
  6998. cali_idx: int | None = None,
  6999. ) -> str | None:
  7000. """Set/update a K-profile on the printer.
  7001. Args:
  7002. filament_id: Bambu filament identifier
  7003. name: Profile name
  7004. k_value: Pressure advance value (e.g., "0.020000")
  7005. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7006. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  7007. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7008. setting_id: Existing setting ID for updates, None for new
  7009. slot_id: Calibration index (cali_idx) for the profile
  7010. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  7011. Returns:
  7012. The sequence_id the command was sent under, so the caller can
  7013. await the printer's verdict via await_cali_ack. None if the
  7014. command could not be sent.
  7015. """
  7016. if not self._client or not self.state.connected:
  7017. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  7018. return None
  7019. self._sequence_id += 1
  7020. seq_id = str(self._sequence_id)
  7021. # Build the filament entry - printer uses cali_idx for profile identification
  7022. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  7023. # For edits, use the provided cali_idx or slot_id
  7024. if cali_idx is not None:
  7025. effective_cali_idx = cali_idx
  7026. else:
  7027. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7028. # Generate a setting_id for new profiles (required by printer)
  7029. # Format: "PF" + 17 random digits
  7030. import random
  7031. if not setting_id and slot_id == 0:
  7032. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7033. filament_entry = {
  7034. "ams_id": 0,
  7035. "cali_idx": effective_cali_idx,
  7036. "extruder_id": extruder_id,
  7037. "filament_id": filament_id,
  7038. "k_value": k_value,
  7039. "n_coef": "0.000000",
  7040. "name": name,
  7041. "nozzle_diameter": nozzle_diameter,
  7042. "nozzle_id": nozzle_id,
  7043. "setting_id": setting_id if setting_id else "",
  7044. # 0, not -1. Single-nozzle firmware validates this field and
  7045. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  7046. # applying the write anyway, so the rejection looked like noise.
  7047. # Measured on an X1C: flipping only this value turns the ack into
  7048. # `success` (#2718). BambuStudio always sends a real tray_id and
  7049. # defaults it to 0 for a manually entered profile.
  7050. "tray_id": 0,
  7051. }
  7052. command = {
  7053. "print": {
  7054. "command": "extrusion_cali_set",
  7055. "filaments": [filament_entry],
  7056. "nozzle_diameter": nozzle_diameter,
  7057. "sequence_id": seq_id,
  7058. }
  7059. }
  7060. command_json = json.dumps(command)
  7061. logger.info(
  7062. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  7063. )
  7064. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  7065. self._publish_cali_write(command, seq_id)
  7066. return seq_id
  7067. def set_kprofiles_batch(
  7068. self,
  7069. profiles: list[dict],
  7070. nozzle_diameter: str = "0.4",
  7071. ) -> str | None:
  7072. """Set multiple K-profiles in a single command (for dual-nozzle).
  7073. Args:
  7074. profiles: List of profile dicts, each with:
  7075. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  7076. nozzle_diameter: Common nozzle diameter for all profiles
  7077. Returns:
  7078. The sequence_id the command was sent under (see set_kprofile),
  7079. or None if it could not be sent.
  7080. """
  7081. if not self._client or not self.state.connected:
  7082. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  7083. return None
  7084. import random
  7085. self._sequence_id += 1
  7086. seq_id = str(self._sequence_id)
  7087. filament_entries = []
  7088. for p in profiles:
  7089. slot_id = p.get("slot_id", 0)
  7090. cali_idx = p.get("cali_idx")
  7091. if cali_idx is not None:
  7092. effective_cali_idx = cali_idx
  7093. else:
  7094. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7095. setting_id = p.get("setting_id")
  7096. if not setting_id and slot_id == 0:
  7097. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7098. filament_entries.append(
  7099. {
  7100. "ams_id": 0,
  7101. "cali_idx": effective_cali_idx,
  7102. "extruder_id": p.get("extruder_id", 0),
  7103. "filament_id": p.get("filament_id", ""),
  7104. "k_value": p.get("k_value", "0.020000"),
  7105. "n_coef": "0.000000",
  7106. "name": p.get("name", ""),
  7107. "nozzle_diameter": nozzle_diameter,
  7108. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  7109. "setting_id": setting_id if setting_id else "",
  7110. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  7111. # single-nozzle firmware even though the write lands (#2718).
  7112. "tray_id": 0,
  7113. }
  7114. )
  7115. command = {
  7116. "print": {
  7117. "command": "extrusion_cali_set",
  7118. "filaments": filament_entries,
  7119. "nozzle_diameter": nozzle_diameter,
  7120. "sequence_id": seq_id,
  7121. }
  7122. }
  7123. command_json = json.dumps(command)
  7124. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  7125. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  7126. self._publish_cali_write(command, seq_id)
  7127. return seq_id
  7128. def delete_kprofile(
  7129. self,
  7130. cali_idx: int,
  7131. filament_id: str,
  7132. nozzle_id: str,
  7133. nozzle_diameter: str = "0.4",
  7134. extruder_id: int = 0,
  7135. setting_id: str | None = None,
  7136. ) -> str | None:
  7137. """Delete a K-profile from the printer.
  7138. Args:
  7139. cali_idx: The calibration index (slot_id) of the profile to delete
  7140. filament_id: Bambu filament identifier
  7141. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  7142. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7143. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7144. setting_id: Unique setting identifier (for X1C series)
  7145. Returns:
  7146. The sequence_id the command was sent under (see set_kprofile),
  7147. or None if it could not be sent.
  7148. """
  7149. if not self._client or not self.state.connected:
  7150. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  7151. return None
  7152. self._sequence_id += 1
  7153. seq_id = str(self._sequence_id)
  7154. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  7155. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  7156. # Prefer runtime detection from device.extruder.info; fall back to
  7157. # model name. H2S is single-nozzle but shares serial prefix "094" with
  7158. # H2D, so a prefix-only check misclassified it (#1386).
  7159. from backend.app.utils.printer_models import is_dual_nozzle_model
  7160. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  7161. if is_dual_nozzle:
  7162. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  7163. command = {
  7164. "print": {
  7165. "command": "extrusion_cali_del",
  7166. "sequence_id": seq_id,
  7167. "extruder_id": extruder_id,
  7168. "nozzle_id": nozzle_id,
  7169. "filament_id": filament_id,
  7170. "cali_idx": cali_idx,
  7171. "nozzle_diameter": nozzle_diameter,
  7172. }
  7173. }
  7174. else:
  7175. # X1C/P1/A1 format: include all fields like the set command
  7176. # The delete command structure should match what set uses
  7177. command = {
  7178. "print": {
  7179. "command": "extrusion_cali_del",
  7180. "sequence_id": seq_id,
  7181. "filament_id": filament_id,
  7182. "cali_idx": cali_idx,
  7183. "setting_id": setting_id if setting_id else "",
  7184. "nozzle_diameter": nozzle_diameter,
  7185. "nozzle_id": nozzle_id,
  7186. "extruder_id": extruder_id,
  7187. }
  7188. }
  7189. command_json = json.dumps(command)
  7190. logger.info(
  7191. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  7192. )
  7193. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  7194. # QoS 1 for reliable delivery (at least once)
  7195. self._publish_cali_write(command, seq_id)
  7196. return seq_id
  7197. # =========================================================================
  7198. # Printer Control Commands
  7199. # =========================================================================
  7200. def pause_print(self) -> bool:
  7201. """Pause the current print job."""
  7202. if not self._client or not self.state.connected:
  7203. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  7204. return False
  7205. command = {"print": {"command": "pause", "sequence_id": "0"}}
  7206. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7207. logger.info("[%s] Sent pause print command", self.serial_number)
  7208. return True
  7209. def resume_print(self) -> bool:
  7210. """Resume a paused print job."""
  7211. if not self._client or not self.state.connected:
  7212. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  7213. return False
  7214. command = {"print": {"command": "resume", "sequence_id": "0"}}
  7215. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7216. logger.info("[%s] Sent resume print command", self.serial_number)
  7217. return True
  7218. def clear_hms_errors(self) -> bool:
  7219. """Clear HMS/print errors on the printer and locally."""
  7220. if not self._client or not self.state.connected:
  7221. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  7222. return False
  7223. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  7224. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7225. self.state.hms_errors = []
  7226. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  7227. return True
  7228. def _handle_skip_objects_answer(self, print_data: dict) -> None:
  7229. """The printer's answer to skip_objects: a refusal is logged and the
  7230. objects are no longer shown as skipped."""
  7231. obj_list = self._skip_commands.pop(str(print_data.get("sequence_id", "")), None)
  7232. result = str(print_data.get("result", "") or "").lower()
  7233. if obj_list is None or result in ("", "success"):
  7234. return
  7235. logger.error(
  7236. "[%s] Printer refused skipping objects %s: result=%s reason=%s",
  7237. self.serial_number,
  7238. obj_list,
  7239. print_data.get("result"),
  7240. print_data.get("reason", ""),
  7241. )
  7242. for oid in obj_list:
  7243. self._unconfirmed_skips.pop(oid, None)
  7244. self.state.skipped_objects = [oid for oid in self.state.skipped_objects if oid not in obj_list]
  7245. def _check_unconfirmed_skips(self) -> None:
  7246. """Log, once, a skip the printer's s_obj list never showed."""
  7247. if not self._unconfirmed_skips:
  7248. return
  7249. if self.state.state not in ("RUNNING", "PAUSE"):
  7250. # The print ended; its skips are moot.
  7251. self._unconfirmed_skips.clear()
  7252. self._skip_commands.clear()
  7253. return
  7254. now = time.monotonic()
  7255. # A copy: skip_objects adds to the dict from the event loop while this
  7256. # runs on the MQTT thread.
  7257. pending = list(self._unconfirmed_skips.items())
  7258. expired = [oid for oid, sent_at in pending if now - sent_at > SKIP_CONFIRM_TIMEOUT_S]
  7259. if not expired:
  7260. return
  7261. logger.error(
  7262. "[%s] Printer did not confirm skipping objects %s within %.0fs; they may still be printed",
  7263. self.serial_number,
  7264. sorted(expired),
  7265. SKIP_CONFIRM_TIMEOUT_S,
  7266. )
  7267. for oid in expired:
  7268. self._unconfirmed_skips.pop(oid, None)
  7269. def skip_objects(self, object_ids: list[int]) -> bool:
  7270. """Skip specific objects during a print.
  7271. This command tells the printer to skip printing the specified objects.
  7272. The object IDs come from the slice_info.config file in the 3MF.
  7273. Args:
  7274. object_ids: List of identify_id values from slice_info.config
  7275. Returns:
  7276. True if command was sent, False otherwise
  7277. """
  7278. if not self._client or not self.state.connected:
  7279. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  7280. return False
  7281. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  7282. logger.warning(
  7283. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  7284. )
  7285. return False
  7286. if not object_ids:
  7287. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  7288. return False
  7289. # Validate all IDs are integers
  7290. try:
  7291. obj_list = [int(oid) for oid in object_ids]
  7292. except (ValueError, TypeError) as e:
  7293. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  7294. return False
  7295. self._sequence_id += 1
  7296. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  7297. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7298. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  7299. sent_at = time.monotonic()
  7300. for oid in obj_list:
  7301. self._unconfirmed_skips.setdefault(oid, sent_at)
  7302. self._skip_commands[str(self._sequence_id)] = obj_list
  7303. # Track skipped objects in state
  7304. for oid in obj_list:
  7305. if oid not in self.state.skipped_objects:
  7306. self.state.skipped_objects.append(oid)
  7307. return True
  7308. def send_gcode(self, gcode: str) -> bool:
  7309. """Send G-code command(s) to the printer.
  7310. Multiple commands can be separated by newlines.
  7311. Args:
  7312. gcode: G-code command(s) to send
  7313. Returns:
  7314. True if command was sent, False otherwise
  7315. """
  7316. if not self._client or not self.state.connected:
  7317. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  7318. return False
  7319. self._sequence_id += 1
  7320. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  7321. # Use QoS 1 for reliable delivery (at least once)
  7322. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7323. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  7324. return True
  7325. def set_bed_temperature(self, target: int) -> bool:
  7326. """Set the bed target temperature.
  7327. Args:
  7328. target: Target temperature in Celsius (0 to turn off)
  7329. Returns:
  7330. True if command was sent, False otherwise
  7331. """
  7332. return self.send_gcode(f"M140 S{target}")
  7333. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  7334. """Set the nozzle target temperature.
  7335. Args:
  7336. target: Target temperature in Celsius (0 to turn off)
  7337. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  7338. Returns:
  7339. True if command was sent, False otherwise
  7340. """
  7341. # Use M104 for non-blocking
  7342. # Always use T parameter for H2D compatibility
  7343. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  7344. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  7345. # Track it locally so we can display it correctly
  7346. if result and nozzle == 1:
  7347. self.state.temperatures["nozzle_target"] = float(target)
  7348. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  7349. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  7350. return result
  7351. def set_chamber_temperature(self, target: int) -> bool:
  7352. """Set the chamber target temperature.
  7353. Args:
  7354. target: Target temperature in Celsius (0 to turn off heating)
  7355. Returns:
  7356. True if command was sent, False otherwise
  7357. """
  7358. # The H3C's heater only runs in the airduct's heating mode.
  7359. from backend.app.utils.printer_models import chamber_heater_needs_heating_mode
  7360. if target > 0 and self.state.airduct_mode != 1 and chamber_heater_needs_heating_mode(self.model):
  7361. logger.info(
  7362. "[%s] Chamber target %s°C: switching the airduct to heating mode first (H3C)",
  7363. self.serial_number,
  7364. target,
  7365. )
  7366. self.set_airduct_mode("heating")
  7367. # M141 sets chamber temperature
  7368. result = self.send_gcode(f"M141 S{target}")
  7369. # Track chamber target locally (MQTT reports encoded values that need filtering)
  7370. if result:
  7371. self.state.temperatures["chamber_target"] = float(target)
  7372. self.state.temperatures["_chamber_target_set_time"] = time.time()
  7373. # Update heating state immediately based on new target
  7374. current_temp = self.state.temperatures.get("chamber", 0)
  7375. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  7376. logger.info(
  7377. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  7378. )
  7379. return result
  7380. def set_print_speed(self, mode: int) -> bool:
  7381. """Set the print speed mode.
  7382. Args:
  7383. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  7384. Returns:
  7385. True if command was sent, False otherwise
  7386. """
  7387. if not self._client or not self.state.connected:
  7388. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  7389. return False
  7390. if mode not in (1, 2, 3, 4):
  7391. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  7392. return False
  7393. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  7394. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7395. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  7396. return True
  7397. def set_fan_speed(self, fan: int, speed: int) -> bool:
  7398. """Set fan speed.
  7399. Args:
  7400. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=second auxiliary).
  7401. Index 10 is the second auxiliary part cooling fan: left on the P2S
  7402. (an accessory kit), right on the X2D, where 2 is the left (#3373)
  7403. (airduct part id 10); Bambu's official machine profiles drive it with
  7404. "M106 P10" in start/layer-change gcode.
  7405. speed: Speed 0-255 (0=off, 255=full)
  7406. Returns:
  7407. True if command was sent, False otherwise
  7408. """
  7409. if fan not in (1, 2, 3, 10):
  7410. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  7411. return False
  7412. speed = max(0, min(255, speed)) # Clamp to 0-255
  7413. return self.send_gcode(f"M106 P{fan} S{speed}")
  7414. def set_airduct_mode(self, mode: str) -> bool:
  7415. """Set air conditioning mode (cooling or heating).
  7416. Args:
  7417. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  7418. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  7419. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  7420. closes top exhaust flap
  7421. Returns:
  7422. True if command was sent, False otherwise
  7423. """
  7424. if not self._client or not self.state.connected:
  7425. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  7426. return False
  7427. self._sequence_id += 1
  7428. mode_id = 0 if mode == "cooling" else 1
  7429. command = {
  7430. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  7431. }
  7432. # Use QoS 1 for reliable delivery
  7433. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7434. logger.info(
  7435. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  7436. )
  7437. return True
  7438. def set_chamber_light(self, on: bool) -> bool:
  7439. """Turn chamber light on or off.
  7440. Args:
  7441. on: True to turn on, False to turn off
  7442. Returns:
  7443. True if command was sent, False otherwise
  7444. """
  7445. if not self._client or not self.state.connected:
  7446. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  7447. return False
  7448. mode = "on" if on else "off"
  7449. # Control both chamber lights (some printers like H2D have two)
  7450. for led_node in ["chamber_light", "chamber_light2"]:
  7451. self._sequence_id += 1
  7452. command = {
  7453. "system": {
  7454. "command": "ledctrl",
  7455. "led_node": led_node,
  7456. "led_mode": mode,
  7457. "led_on_time": 500,
  7458. "led_off_time": 500,
  7459. "loop_times": 0,
  7460. "interval_time": 0,
  7461. "sequence_id": str(self._sequence_id),
  7462. }
  7463. }
  7464. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7465. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  7466. return True
  7467. def select_extruder(self, extruder: int) -> bool:
  7468. """Select the active extruder for dual-nozzle printers (H2D).
  7469. Args:
  7470. extruder: Extruder index (0=right, 1=left for H2D)
  7471. Returns:
  7472. True if command was sent, False otherwise
  7473. """
  7474. if extruder not in (0, 1):
  7475. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  7476. return False
  7477. if not self._client or not self.state.connected:
  7478. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  7479. return False
  7480. # H2D extruder switching via select_extruder command
  7481. # Command format captured from OrcaSlicer:
  7482. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  7483. # extruder_index: 0 = RIGHT, 1 = LEFT
  7484. self._sequence_id += 1
  7485. command = {
  7486. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  7487. }
  7488. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7489. logger.info(
  7490. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  7491. )
  7492. return True
  7493. def _ams_unit(self, ams_id: int) -> dict | None:
  7494. """AMS unit ``ams_id`` in the last status, or None."""
  7495. for unit in self.state.raw_data.get("ams") or []:
  7496. if isinstance(unit, dict) and _mqtt_int(unit.get("id")) == ams_id:
  7497. return unit
  7498. return None
  7499. def _rack_tray(self, tray_id: int | None) -> tuple[int, int, dict | None] | None:
  7500. """``(ams_id, slot, tray)`` of a rack AMS slot's global tray id (the AMS 3H's 28-36), else None."""
  7501. if not isinstance(tray_id, int):
  7502. return None
  7503. located = self.tray_layout.rack_slot(tray_id)
  7504. if located is None:
  7505. return None
  7506. ams_id, slot = located
  7507. unit = self._ams_unit(ams_id) or {}
  7508. tray = next(
  7509. (t for t in unit.get("tray") or [] if isinstance(t, dict) and _mqtt_int(t.get("id")) == slot),
  7510. None,
  7511. )
  7512. return ams_id, slot, tray
  7513. def rack_tray_has_filament(self, tray_id: int) -> bool:
  7514. """Whether rack AMS slot ``tray_id`` reports a filament type, which Studio requires before a Load.
  7515. The AMS 3H registers a spool only once it has pulled the filament in at the inlet.
  7516. """
  7517. rack = self._rack_tray(tray_id)
  7518. return bool(rack and rack[2] and rack[2].get("tray_type"))
  7519. @staticmethod
  7520. def _tray_mid_temp(tray: dict | None) -> int:
  7521. """Midpoint of a tray's nozzle_temp_min/max, or -1 (as Studio's ams_change_filament)."""
  7522. if tray is None:
  7523. return -1
  7524. low, high = _mqtt_int(tray.get("nozzle_temp_min")), _mqtt_int(tray.get("nozzle_temp_max"))
  7525. return (low + high) // 2 if low and high and low > 0 and high > 0 else -1
  7526. def _rack_change_filament(self, tray_id: int, load: bool) -> bool:
  7527. """Load AMS 3H slot ``tray_id`` into its own hotend, or unload that hotend.
  7528. As Studio 02.09 sends it for a direct-connected rack (PageFilament.cpp):
  7529. load targets 32 at slot k, unload 255 at slot 255 - k (the feeder to
  7530. retract). The AMS 3H can't rewind: an unload ends with a hand pull.
  7531. """
  7532. client = self._client
  7533. rack = self._rack_tray(tray_id)
  7534. if client is None or rack is None:
  7535. return False
  7536. ams_id, slot, tray = rack
  7537. on_head = self._rack_tray(self.state.tray_now)
  7538. self._sequence_id += 1
  7539. command = {
  7540. "print": {
  7541. "command": "ams_change_filament",
  7542. "sequence_id": str(self._sequence_id),
  7543. "ams_id": ams_id,
  7544. "target": ams_id if load else 255,
  7545. "slot_id": slot if load else 255 - slot,
  7546. "extruder_id": 0,
  7547. "curr_temp": self._tray_mid_temp(on_head[2] if on_head else None),
  7548. "tar_temp": self._tray_mid_temp(tray),
  7549. }
  7550. }
  7551. command_json = json.dumps(command)
  7552. logger.info(
  7553. "[%s] Publishing ams_change_filament (%s, AMS 3H slot %d): %s",
  7554. self.serial_number,
  7555. "load" if load else "unload",
  7556. slot + 1,
  7557. command_json,
  7558. )
  7559. client.publish(self.topic_publish, command_json, qos=1)
  7560. if load:
  7561. self.state.pending_tray_target = tray_id
  7562. self.state.pending_tray_target_at = time.monotonic()
  7563. else:
  7564. self.state.pending_tray_target = None
  7565. self.state.pending_tray_target_at = None
  7566. return True
  7567. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  7568. """Load filament from a specific AMS tray.
  7569. Args:
  7570. tray_id: Global tray ID — 0..15 for AMS slots, 24..27 for the A2L
  7571. AMS-Lite, 128..135 for an AMS-HT (its unit id), 254 for external spool
  7572. (single-external printers and Ext-L on dual-nozzle H2D),
  7573. 255 for Ext-R on dual-nozzle H2D.
  7574. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  7575. Sent only when given, matching BambuStudio: ``extruder_id`` is
  7576. an optional field on ``ams_change_filament``
  7577. (``DeviceManager::command_ams_change_filament``) and Studio
  7578. omits it unless a Filament Track Switch is installed. Without a
  7579. switch the firmware derives the hotend from the AMS's own
  7580. extruder binding and an explicit value is redundant; *with* one
  7581. every AMS reports 0xE and is bound to a switch inlet instead, so
  7582. the firmware has nothing to derive from and the load silently
  7583. does nothing until we name the hotend.
  7584. Returns:
  7585. True if command was sent, False otherwise
  7586. """
  7587. if not self._client or not self.state.connected:
  7588. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  7589. return False
  7590. if self.tray_layout.rack_units:
  7591. # Only an AMS 3H slot can be loaded: an external input or an AMS-B
  7592. # can't feed itself (Studio's CanAutoFeed).
  7593. rack = self._rack_tray(tray_id)
  7594. if rack is None or self.tray_layout.ams_type(rack[0]) != AmsType.ZMULTI_A:
  7595. logger.warning("[%s] Load: tray %s is not an AMS 3H slot", self.serial_number, tray_id)
  7596. return False
  7597. if not self.rack_tray_has_filament(tray_id):
  7598. logger.warning("[%s] Load: AMS 3H slot %d has no filament", self.serial_number, rack[1] + 1)
  7599. return False
  7600. return self._rack_change_filament(tray_id, load=True)
  7601. # Build the ams_change_filament command. Encoding differs by target type:
  7602. # - AMS slots (0..15, A2L 24..27, AMS-HT 128..135): see
  7603. # change_filament_wire_ids; curr/tar_temp = -1.
  7604. # - External spool (tray_id=254): legacy capture from a single-extruder
  7605. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  7606. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  7607. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  7608. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  7609. self._sequence_id += 1
  7610. wire_target = tray_id
  7611. if tray_id == 255:
  7612. ams_id = 255
  7613. slot_id = 0 # extruder index for the right nozzle
  7614. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  7615. if right_temp < 180:
  7616. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  7617. curr_temp = right_temp
  7618. tar_temp = right_temp
  7619. elif tray_id == 254:
  7620. ams_id = 255
  7621. slot_id = 254
  7622. curr_temp = -1
  7623. tar_temp = -1
  7624. else:
  7625. # A regular AMS, the A2L AMS-Lite (physical unit 16) or an AMS-HT
  7626. # (128-135), as BambuStudio addresses each.
  7627. ams_id, slot_id, wire_target = change_filament_wire_ids(tray_id, self.tray_layout)
  7628. curr_temp = -1
  7629. tar_temp = -1
  7630. command = {
  7631. "print": {
  7632. "command": "ams_change_filament",
  7633. "sequence_id": str(self._sequence_id),
  7634. "ams_id": ams_id,
  7635. "slot_id": slot_id,
  7636. "target": wire_target,
  7637. "curr_temp": curr_temp,
  7638. "tar_temp": tar_temp,
  7639. }
  7640. }
  7641. if extruder_id is not None:
  7642. command["print"]["extruder_id"] = int(extruder_id)
  7643. command_json = json.dumps(command)
  7644. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  7645. self._client.publish(self.topic_publish, command_json, qos=1)
  7646. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  7647. # Track this load request for H2D dual-nozzle disambiguation
  7648. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  7649. self.state.pending_tray_target = tray_id
  7650. self.state.pending_tray_target_at = time.monotonic()
  7651. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  7652. return True
  7653. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  7654. """Unload filament, optionally naming the slot to unload.
  7655. Args:
  7656. tray_id: Global tray ID of the slot being unloaded. When given, the
  7657. command is addressed to that slot's AMS and is only sent if an
  7658. extruder is actually fed from it — BambuStudio does the same
  7659. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  7660. nothing when none matches). When omitted, the pre-existing
  7661. behaviour is kept: unload whatever ``tray_now`` names.
  7662. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  7663. machine with both hotends loaded it names only one of them and an
  7664. unaddressed unload picks that one regardless of which slot the operator
  7665. clicked. Passing the slot is what makes the two hotends distinguishable.
  7666. Returns:
  7667. True if command was sent, False otherwise
  7668. """
  7669. if not self._client or not self.state.connected:
  7670. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  7671. return False
  7672. if self.tray_layout.rack_units:
  7673. # The hotend of the named AMS 3H slot, else of the one on the toolhead.
  7674. source = tray_id if tray_id is not None else self.state.tray_now
  7675. if self._rack_tray(source) is None:
  7676. logger.warning("[%s] Unload: no AMS 3H slot to unload (tray %s)", self.serial_number, source)
  7677. return False
  7678. return self._rack_change_filament(source, load=False)
  7679. # Get the currently loaded tray info
  7680. tray_now = self.state.tray_now
  7681. source_tray = tray_now if tray_id is None else tray_id
  7682. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  7683. # Determine source ams_id for the unload command
  7684. if source_tray == 255 or source_tray == 254:
  7685. ams_id = 255 # No filament or external spool
  7686. else:
  7687. # Source AMS: the A2L AMS-Lite as physical 16, an AMS-HT as its unit id.
  7688. ams_id = change_filament_wire_ids(source_tray, self.tray_layout)[0]
  7689. # Refuse an addressed unload of a slot no hotend is holding — but only on
  7690. # a printer that has more than one hotend, which is the only case the
  7691. # check exists for. With one hotend there is nothing to disambiguate:
  7692. # tray_now already names the loaded slot exactly, and running the check
  7693. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  7694. # very likely does, but single-nozzle machines do report the block —
  7695. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  7696. # an X1C on the maintainer's own network sends `device.extruder` — and
  7697. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  7698. # would 409 every unload on every X1C, P1S and A1.
  7699. #
  7700. # Gated on the runtime flag rather than on len(extruder_slots), which is
  7701. # rebuilt from each payload's array and would flip the check off for any
  7702. # frame that carried a short one; and deliberately not on
  7703. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  7704. # one single-nozzle machine as dual (#1386) — the false positive there is
  7705. # exactly the case this gate exists to keep out.
  7706. #
  7707. # The external spool is excluded for a different reason: 254/255 are not
  7708. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  7709. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  7710. local_slot = change_filament_wire_ids(tray_id, self.tray_layout)[1]
  7711. holder = next(
  7712. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  7713. None,
  7714. )
  7715. if holder is None:
  7716. logger.info(
  7717. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  7718. self.serial_number,
  7719. ams_id,
  7720. local_slot,
  7721. )
  7722. return False
  7723. logger.info(
  7724. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7725. )
  7726. # Command format from BambuStudio traffic capture:
  7727. # - No extruder_id field
  7728. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7729. # - slot_id=255 and target=255 for unload
  7730. # Get current nozzle temperature for the unload command
  7731. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7732. if nozzle_temp < 180:
  7733. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7734. self._sequence_id += 1
  7735. command = {
  7736. "print": {
  7737. "command": "ams_change_filament",
  7738. "sequence_id": str(self._sequence_id),
  7739. "ams_id": ams_id,
  7740. "slot_id": 255, # 255 = unload marker
  7741. "target": 255, # 255 = unload destination
  7742. "curr_temp": nozzle_temp,
  7743. "tar_temp": nozzle_temp,
  7744. }
  7745. }
  7746. command_json = json.dumps(command)
  7747. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7748. self._client.publish(self.topic_publish, command_json, qos=1)
  7749. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7750. # Clear tracked load request since we're unloading
  7751. self.state.pending_tray_target = None
  7752. self.state.pending_tray_target_at = None
  7753. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7754. return True
  7755. def ams_control(self, action: str) -> bool:
  7756. """Control AMS operations.
  7757. Args:
  7758. action: "resume", "reset", or "pause"
  7759. Returns:
  7760. True if command was sent, False otherwise
  7761. """
  7762. if not self._client or not self.state.connected:
  7763. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7764. return False
  7765. if action not in ("resume", "reset", "pause"):
  7766. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7767. return False
  7768. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7769. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7770. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7771. return True
  7772. async def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7773. """Trigger RFID re-read for a specific AMS tray.
  7774. Sends ``ams_get_rfid`` and waits for the printer's answer. Firmware
  7775. that refuses it (#3206: X1Plus on base 01.08.02.00 answers ``FAIL`` /
  7776. ``ERROR STATE``) gets the legacy ``M620 R<global tray>`` gcode instead,
  7777. which is what Bambu Studio sends to printers without the new protocol.
  7778. The fallback only follows an explicit refusal, so firmware that takes
  7779. ``ams_get_rfid`` never sees it.
  7780. Success means the printer accepted the request, not that the tag was
  7781. read: the slot updating in the next push is the only proof of that.
  7782. Args:
  7783. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7784. tray_id: Tray ID within the AMS (0-3)
  7785. Returns:
  7786. Tuple of (success, message)
  7787. """
  7788. if not self._client or not self.state.connected:
  7789. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7790. return False, "Printer not connected"
  7791. # Check if filament is currently loaded (tray_now != 255)
  7792. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7793. tray_now = self.state.tray_now
  7794. if tray_now != 255:
  7795. # Decode which tray is loaded for the message
  7796. layout = self.tray_layout
  7797. if tray_now == 254:
  7798. loaded_tray = "external spool"
  7799. elif (rack := layout.rack_slot(tray_now)) is not None:
  7800. loaded_tray = f"{unit_label(rack[0], layout.ams_type(rack[0]))} slot {rack[1] + 1}"
  7801. elif tray_now >= 0 and tray_now < 128:
  7802. loaded_ams, loaded_slot = layout.slot_key(tray_now)
  7803. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7804. else:
  7805. loaded_tray = f"tray {tray_now}"
  7806. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7807. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7808. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7809. wire_ams_id, wire_slot_id = ams_id, tray_id
  7810. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7811. wire_ams_id, wire_slot_id, _ = _a2l
  7812. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7813. refused = await self._send_rfid_command(
  7814. {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id}
  7815. )
  7816. if refused is None:
  7817. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7818. # M620 R only for what Bambu Studio sends it to: a model older than the
  7819. # newer protocol, on one of the four regular AMS units (the only ones
  7820. # with a legacy global tray index). Never during a job either: a
  7821. # gcode_line would be executed inside the running print.
  7822. from backend.app.utils.printer_models import uses_legacy_rfid_refresh
  7823. if (
  7824. not 0 <= wire_ams_id <= 3
  7825. or not uses_legacy_rfid_refresh(self.model)
  7826. or self.state.state in _ACTIVE_PRINT_STATES
  7827. ):
  7828. return False, f"Printer refused the RFID refresh: {refused}"
  7829. logger.info(
  7830. "[%s] ams_get_rfid refused (%s), falling back to M620 R%s",
  7831. self.serial_number,
  7832. refused,
  7833. legacy_tray_index(wire_ams_id, wire_slot_id),
  7834. )
  7835. legacy_refused = await self._send_rfid_command(
  7836. {"command": "gcode_line", "param": f"M620 R{legacy_tray_index(wire_ams_id, wire_slot_id)}\n"}
  7837. )
  7838. if legacy_refused is None:
  7839. return True, f"Refreshing AMS {ams_id} tray {tray_id} (legacy command)"
  7840. return False, f"Printer refused the RFID refresh: {legacy_refused}"
  7841. # The answer to ams_get_rfid was measured at 11ms in #3206's capture.
  7842. _rfid_ack_timeout: float = 3.0
  7843. async def _send_rfid_command(self, print_command: dict) -> str | None:
  7844. """Publish one RFID refresh command and wait for the printer's answer.
  7845. Returns the printer's reason when it answered ``FAIL``, else None.
  7846. No answer within ``_rfid_ack_timeout`` counts as accepted, because
  7847. silence is not evidence of refusal and older firmware may not answer
  7848. at all.
  7849. """
  7850. timeout = self._rfid_ack_timeout
  7851. self._sequence_id += 1
  7852. seq_id = str(self._sequence_id)
  7853. command = {"print": {**print_command, "sequence_id": seq_id}}
  7854. self._pending_rfid_acks[seq_id] = None
  7855. try:
  7856. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7857. deadline = time.monotonic() + timeout
  7858. while time.monotonic() < deadline:
  7859. ack = self._pending_rfid_acks.get(seq_id)
  7860. if ack is not None:
  7861. if str(ack.get("result", "")).lower() == "fail":
  7862. return str(ack.get("reason", "") or "") or "printer reported failure"
  7863. return None
  7864. await asyncio.sleep(0.05)
  7865. finally:
  7866. self._pending_rfid_acks.pop(seq_id, None)
  7867. logger.info(
  7868. "[%s] No answer to %s seq=%s within %.1fs", self.serial_number, print_command["command"], seq_id, timeout
  7869. )
  7870. return None
  7871. def ams_set_filament_setting(
  7872. self,
  7873. ams_id: int,
  7874. tray_id: int,
  7875. tray_info_idx: str,
  7876. tray_type: str,
  7877. tray_sub_brands: str,
  7878. tray_color: str,
  7879. nozzle_temp_min: int,
  7880. nozzle_temp_max: int,
  7881. setting_id: str = "",
  7882. ) -> bool:
  7883. """Set AMS tray filament settings (type, color, temperature).
  7884. Note: K value is set separately via extrusion_cali_sel command.
  7885. Args:
  7886. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7887. tray_id: Tray ID within the AMS (0-3)
  7888. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7889. tray_type: Filament type (e.g., "PLA", "PETG")
  7890. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  7891. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  7892. nozzle_temp_min: Minimum nozzle temperature
  7893. nozzle_temp_max: Maximum nozzle temperature
  7894. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  7895. Returns:
  7896. True if command was sent, False otherwise
  7897. """
  7898. if not self._client or not self.state.connected:
  7899. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  7900. return False
  7901. # Calculate mqtt IDs based on AMS type.
  7902. # External-spool convention verified against a BambuStudio→X1C packet capture
  7903. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  7904. # *global* tray index in `tray_id`, not a local position within the virtual
  7905. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  7906. # is what the original code was matching — but the request and response
  7907. # use different semantics for that field. Sending `tray_id: 0` is what
  7908. # the P1S in #1279 rejected with `result: "fail"`.
  7909. if ams_id == 255:
  7910. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7911. if len(vt_tray) > 1:
  7912. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7913. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7914. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7915. # captured Studio→H2D exchange confirms the correct value.
  7916. mqtt_ams_id = external_tray_id(tray_id)
  7917. mqtt_tray_id = 0
  7918. else:
  7919. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7920. mqtt_ams_id = 255
  7921. mqtt_tray_id = 254
  7922. slot_id = 0
  7923. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7924. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7925. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7926. mqtt_ams_id, slot_id, _ = _a2l
  7927. mqtt_tray_id = slot_id
  7928. elif self._rack_ams_type(ams_id) is not None:
  7929. # AMS 3H: unit 32 with its slot 0-8 in tray_id and slot_id (verified).
  7930. mqtt_ams_id = ams_id
  7931. mqtt_tray_id = slot_id = tray_id
  7932. elif ams_id <= 3:
  7933. mqtt_ams_id = ams_id
  7934. mqtt_tray_id = tray_id
  7935. slot_id = tray_id
  7936. else:
  7937. # AMS-HT: single tray per unit
  7938. mqtt_ams_id = ams_id
  7939. mqtt_tray_id = tray_id
  7940. slot_id = 0
  7941. command = {
  7942. "print": {
  7943. "command": "ams_filament_setting",
  7944. "ams_id": mqtt_ams_id,
  7945. "tray_id": mqtt_tray_id,
  7946. "slot_id": slot_id,
  7947. "tray_info_idx": tray_info_idx,
  7948. "tray_type": tray_type,
  7949. "tray_sub_brands": tray_sub_brands,
  7950. # UPPERCASE, always: lowercase hex is silently read as zeros by
  7951. # P1S firmware and acknowledged as a success (#2987).
  7952. "tray_color": wire_tray_color(tray_color),
  7953. "nozzle_temp_min": nozzle_temp_min,
  7954. "nozzle_temp_max": nozzle_temp_max,
  7955. "sequence_id": "0",
  7956. }
  7957. }
  7958. # Include setting_id if provided (helps slicer show correct profile)
  7959. if setting_id:
  7960. command["print"]["setting_id"] = setting_id
  7961. command_json = json.dumps(command)
  7962. logger.info(
  7963. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  7964. )
  7965. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  7966. self._client.publish(self.topic_publish, command_json, qos=1)
  7967. self._last_ams_cmd_time = time.monotonic()
  7968. return True
  7969. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  7970. """Reset an AMS slot to empty/unconfigured state.
  7971. Args:
  7972. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7973. tray_id: Tray ID within the AMS (0-3)
  7974. Returns:
  7975. True if command was sent, False otherwise
  7976. """
  7977. if not self._client or not self.state.connected:
  7978. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  7979. return False
  7980. # Calculate mqtt IDs based on AMS type — same convention as
  7981. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  7982. if ams_id == 255:
  7983. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7984. if len(vt_tray) > 1:
  7985. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7986. mqtt_ams_id = external_tray_id(tray_id)
  7987. mqtt_tray_id = 0
  7988. else:
  7989. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7990. mqtt_ams_id = 255
  7991. mqtt_tray_id = 254
  7992. slot_id = 0
  7993. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7994. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  7995. mqtt_ams_id, slot_id, _ = _a2l
  7996. mqtt_tray_id = slot_id
  7997. elif self._rack_ams_type(ams_id) is not None:
  7998. # AMS 3H: unit 32 with its slot 0-8 (see ams_set_filament_setting).
  7999. mqtt_ams_id = ams_id
  8000. mqtt_tray_id = slot_id = tray_id
  8001. elif ams_id <= 3:
  8002. mqtt_ams_id = ams_id
  8003. mqtt_tray_id = tray_id
  8004. slot_id = tray_id
  8005. else:
  8006. # AMS-HT: single tray per unit
  8007. mqtt_ams_id = ams_id
  8008. mqtt_tray_id = tray_id
  8009. slot_id = 0
  8010. command = {
  8011. "print": {
  8012. "command": "ams_filament_setting",
  8013. "ams_id": mqtt_ams_id,
  8014. "tray_id": mqtt_tray_id,
  8015. "slot_id": slot_id,
  8016. "tray_info_idx": "",
  8017. "tray_type": "",
  8018. "tray_sub_brands": "",
  8019. "tray_color": "00000000",
  8020. "nozzle_temp_min": 0,
  8021. "nozzle_temp_max": 0,
  8022. "sequence_id": "0",
  8023. }
  8024. }
  8025. command_json = json.dumps(command)
  8026. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  8027. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  8028. self._client.publish(self.topic_publish, command_json, qos=1)
  8029. self._last_ams_cmd_time = time.monotonic()
  8030. return True
  8031. def extrusion_cali_sel(
  8032. self,
  8033. ams_id: int,
  8034. tray_id: int,
  8035. cali_idx: int,
  8036. filament_id: str,
  8037. nozzle_diameter: str = "0.4",
  8038. ) -> bool:
  8039. """Set calibration profile (K value) for an AMS slot.
  8040. This command selects a K profile from the printer's calibration list.
  8041. Use cali_idx=-1 to use the default K value (0.020).
  8042. Note: Do NOT send setting_id in this command — BambuStudio never includes
  8043. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  8044. Args:
  8045. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  8046. tray_id: Tray ID within the AMS (0-3)
  8047. cali_idx: Calibration profile index (-1 for default)
  8048. filament_id: Filament preset ID (same as tray_info_idx)
  8049. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8050. Returns:
  8051. True if command was sent, False otherwise
  8052. """
  8053. if not self._client or not self.state.connected:
  8054. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  8055. return False
  8056. # Calculate mqtt IDs based on AMS type.
  8057. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  8058. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  8059. if ams_id == 255:
  8060. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  8061. # ams_filament_setting which uses LOCAL tray_id=0).
  8062. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8063. if len(vt_tray) > 1:
  8064. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8065. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  8066. mqtt_ams_id = external_tray_id(tray_id)
  8067. mqtt_tray_id = external_tray_id(tray_id)
  8068. else:
  8069. # Single external slot (X1C, P1S, A1): global tray_id=254
  8070. mqtt_ams_id = 254
  8071. mqtt_tray_id = 254
  8072. slot_id = 0
  8073. elif self._rack_ams_type(ams_id) is not None:
  8074. # AMS 3H: unit 32, slot k in tray_id and slot_id ({32, 8, 8} verified).
  8075. mqtt_ams_id = ams_id
  8076. mqtt_tray_id = slot_id = tray_id
  8077. elif ams_id <= 3:
  8078. mqtt_ams_id = ams_id
  8079. mqtt_tray_id = legacy_tray_index(ams_id, tray_id)
  8080. slot_id = tray_id
  8081. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8082. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  8083. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  8084. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  8085. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  8086. elif is_ams_ht_id(ams_id):
  8087. mqtt_ams_id = ams_id
  8088. mqtt_tray_id = tray_id
  8089. slot_id = 0
  8090. else:
  8091. mqtt_ams_id = ams_id
  8092. mqtt_tray_id = tray_id
  8093. slot_id = 0
  8094. command = {
  8095. "print": {
  8096. "command": "extrusion_cali_sel",
  8097. "cali_idx": cali_idx,
  8098. "filament_id": filament_id,
  8099. "nozzle_diameter": nozzle_diameter,
  8100. "ams_id": mqtt_ams_id,
  8101. "tray_id": mqtt_tray_id,
  8102. "slot_id": slot_id,
  8103. "sequence_id": "0",
  8104. }
  8105. }
  8106. command_json = json.dumps(command)
  8107. logger.info(
  8108. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  8109. )
  8110. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  8111. self._client.publish(self.topic_publish, command_json, qos=1)
  8112. return True
  8113. def extrusion_cali_set(
  8114. self,
  8115. tray_id: int,
  8116. k_value: float,
  8117. nozzle_diameter: str = "0.4",
  8118. nozzle_temp: int = 220,
  8119. filament_id: str = "",
  8120. setting_id: str = "",
  8121. name: str = "",
  8122. cali_idx: int = -1,
  8123. ) -> bool:
  8124. """Directly set K value (pressure advance) for a tray.
  8125. Uses the filaments array format required by current firmware.
  8126. Args:
  8127. tray_id: Global tray ID (ams_id * 4 + slot)
  8128. k_value: Pressure advance K value (e.g., 0.020)
  8129. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8130. nozzle_temp: Nozzle temperature for calibration reference
  8131. filament_id: Filament preset ID (e.g., "GFA02")
  8132. setting_id: Setting ID (e.g., "GFSA02_07")
  8133. name: Profile display name
  8134. cali_idx: Calibration index (-1 for new)
  8135. Returns:
  8136. True if command was sent, False otherwise
  8137. """
  8138. if not self._client or not self.state.connected:
  8139. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  8140. return False
  8141. # Was reusing the previous command's id — harmless while nothing
  8142. # correlated on it, but the printer echoes sequence_id back and the
  8143. # K-profile write path now matches acks by it (#2718).
  8144. self._sequence_id += 1
  8145. nozzle_id = f"HS00-{nozzle_diameter}"
  8146. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  8147. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  8148. # stays 0 (hardcoded, as for every other unit here).
  8149. wire_tray_id = tray_id
  8150. if (
  8151. 0 <= tray_id <= 253
  8152. and (_a2l := a2l_lite_wire_ids(self.tray_layout.slot_key(tray_id)[0], tray_id)) is not None
  8153. ):
  8154. wire_tray_id = _a2l[2]
  8155. filament_entry = {
  8156. "ams_id": 0,
  8157. "cali_idx": cali_idx,
  8158. "extruder_id": 0,
  8159. "filament_id": filament_id,
  8160. "k_value": f"{k_value:.6f}",
  8161. "n_coef": "1.400000",
  8162. "name": name,
  8163. "nozzle_diameter": nozzle_diameter,
  8164. "nozzle_id": nozzle_id,
  8165. "setting_id": setting_id,
  8166. "tray_id": wire_tray_id,
  8167. }
  8168. command = {
  8169. "print": {
  8170. "command": "extrusion_cali_set",
  8171. "filaments": [filament_entry],
  8172. "nozzle_diameter": nozzle_diameter,
  8173. "sequence_id": str(self._sequence_id),
  8174. }
  8175. }
  8176. command_json = json.dumps(command)
  8177. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  8178. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  8179. self._client.publish(self.topic_publish, command_json, qos=1)
  8180. return True
  8181. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  8182. """Dispatch the user's choice from the HMS-error modal as a printer command.
  8183. Args:
  8184. print_error: Canonical hex identifier for the fault — 8 chars for the
  8185. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  8186. (HMSError.full_code). Carried through unchanged from the route.
  8187. Converted to its DECIMAL string form for the `ignore` /
  8188. `idle_ignore` commands' `err` field, which is what the firmware
  8189. actually compares against the active fault. The pre-#1869
  8190. hex-string `err` was silently rejected because the firmware was
  8191. being asked to match `"05008051"` against int 0x05008051
  8192. (= 83918929 decimal) — see BambuStudio's
  8193. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  8194. `std::to_string(int m_error_code)`.
  8195. action: One of HMSAction's string values.
  8196. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  8197. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  8198. shapes; empty string is the no-job-id sentinel.
  8199. Returns False when the MQTT client is offline or when `action` is unknown
  8200. so the route surfaces it as a 4xx rather than a silent no-op.
  8201. """
  8202. if not self._client or not self.state.connected:
  8203. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  8204. return False
  8205. # Always re-push the full state after a command so the modal's underlying
  8206. # status query reflects the new error list (or absence) on the next tick.
  8207. def publish(payload: dict):
  8208. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  8209. self._client.publish(
  8210. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  8211. )
  8212. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  8213. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  8214. # every command_hms_* call). Our route hands us the hex string —
  8215. # convert. Falls back to the raw input if it's not parseable so the
  8216. # firmware can reject it and the route can surface 502 instead of us
  8217. # raising ValueError mid-dispatch.
  8218. try:
  8219. err_decimal = str(int(print_error, 16))
  8220. except ValueError:
  8221. err_decimal = print_error
  8222. def hms_resume():
  8223. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  8224. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  8225. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  8226. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  8227. # shape historically because it works, and changing it without a
  8228. # field test risks regressing a path that the user has confirmed.
  8229. publish(
  8230. {
  8231. "print": {
  8232. "command": "resume",
  8233. "param": "",
  8234. "sequence_id": "0",
  8235. }
  8236. }
  8237. )
  8238. def hms_stop():
  8239. # Same as hms_resume — plain shape, confirmed working by the user
  8240. # for "Stop Printing".
  8241. publish(
  8242. {
  8243. "print": {
  8244. "command": "stop",
  8245. "param": "",
  8246. "sequence_id": "0",
  8247. }
  8248. }
  8249. )
  8250. def hms_ignore_command():
  8251. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  8252. # what the "Ignore this and Resume" button actually publishes.
  8253. # Distinct from `idle_ignore`: this command has the firmware
  8254. # suppress the next re-check of the named fault AND resume the
  8255. # paused print in a single operation. The previous Bambuddy code
  8256. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  8257. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  8258. # the problem, re-check normally" so the firmware re-detected the
  8259. # wrong plate and re-paused with the same code (#1869).
  8260. #
  8261. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  8262. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  8263. # variant of "don't remind next time" lives on `idle_ignore`'s
  8264. # type=1, not as a separate ignore shape.
  8265. publish(
  8266. {
  8267. "print": {
  8268. "command": "ignore",
  8269. "err": err_decimal,
  8270. "param": "reserve",
  8271. "job_id": job_id or "",
  8272. "sequence_id": "0",
  8273. }
  8274. }
  8275. )
  8276. def hms_idle_ignore(persistent: bool = False):
  8277. # `idle_ignore` is BambuStudio's "dismiss this warning without
  8278. # resuming" command for non-pause warnings — what
  8279. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  8280. # type=0 dismisses once, type=1 suppresses the same warning
  8281. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  8282. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  8283. # NOT via the resume-bearing `ignore` command.
  8284. publish(
  8285. {
  8286. "print": {
  8287. "command": "idle_ignore",
  8288. "err": err_decimal,
  8289. "type": 1 if persistent else 0,
  8290. "sequence_id": "0",
  8291. }
  8292. }
  8293. )
  8294. def ams_control(param: str):
  8295. publish(
  8296. {
  8297. "print": {
  8298. "command": "ams_control",
  8299. "param": param,
  8300. "sequence_id": "0",
  8301. }
  8302. }
  8303. )
  8304. def clean_print_error():
  8305. # Matches the existing `clear_hms_errors` shape — Bambu does not
  8306. # expect `print_error` in the body; the command clears whatever
  8307. # error dialog is currently active on the printer.
  8308. publish(
  8309. {
  8310. "print": {
  8311. "command": "clean_print_error",
  8312. "sequence_id": "0",
  8313. }
  8314. }
  8315. )
  8316. def uiop_close():
  8317. # `err` is the 8-char hex short code (already a string from the
  8318. # frontend), uppercased for consistency with how BambuStudio sends it.
  8319. publish(
  8320. {
  8321. "system": {
  8322. "command": "uiop",
  8323. "name": "print_error",
  8324. "action": "close",
  8325. "source": 1,
  8326. "type": "dialog",
  8327. "err": print_error.upper(),
  8328. "sequence_id": "0",
  8329. }
  8330. }
  8331. )
  8332. match action:
  8333. case (
  8334. HMSAction.RESUME_PRINTING
  8335. | HMSAction.RESUME_PRINTING_DEFECTS
  8336. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  8337. | HMSAction.PROBLEM_SOLVED_RESUME
  8338. | HMSAction.FILAMENT_LOAD_RESUME
  8339. | HMSAction.PROCEED
  8340. ):
  8341. hms_resume()
  8342. case HMSAction.STOP_PRINTING:
  8343. hms_stop()
  8344. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  8345. # All three buttons map to BambuStudio's `command_hms_ignore`
  8346. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  8347. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  8348. # responsibility — the wire shape is identical.
  8349. hms_ignore_command()
  8350. case HMSAction.NO_REMINDER_NEXT_TIME:
  8351. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  8352. # `command_hms_idle_ignore` with type=0
  8353. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  8354. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  8355. # dismisses the dialog.
  8356. hms_idle_ignore(persistent=False)
  8357. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  8358. ams_control("done")
  8359. case (
  8360. HMSAction.RETRY_FILAMENT_EXTRUDED
  8361. | HMSAction.CONTINUE
  8362. | HMSAction.RETRY_PROBLEM_SOLVED
  8363. | HMSAction.DBL_CHECK_RETRY
  8364. ):
  8365. ams_control("resume")
  8366. case HMSAction.ABORT:
  8367. ams_control("abort")
  8368. case HMSAction.OK_BUTTON:
  8369. clean_print_error()
  8370. case HMSAction.DBL_CHECK_OK:
  8371. clean_print_error()
  8372. uiop_close()
  8373. case HMSAction.DBL_CHECK_RESUME:
  8374. # Plain resume — not HMS-aware, no err/job_id.
  8375. publish(
  8376. {
  8377. "print": {
  8378. "command": "resume",
  8379. "param": "",
  8380. "sequence_id": "0",
  8381. }
  8382. }
  8383. )
  8384. case HMSAction.REFRESH_NOZZLE:
  8385. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  8386. case HMSAction.TURN_OFF_FIRE_ALARM:
  8387. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  8388. case HMSAction.STOP_DRYING:
  8389. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  8390. case HMSAction.DISABLE_PURIFICATION:
  8391. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  8392. case (
  8393. HMSAction.CHECK_ASSISTANT
  8394. | HMSAction.JUMP_TO_LIVEVIEW
  8395. | HMSAction.OK_JUMP_RACK
  8396. | HMSAction.REMOVE_CLOSE_BTN
  8397. | HMSAction.LOAD_VIRTUAL_TRAY
  8398. | HMSAction.CANCLE
  8399. | HMSAction.DBL_CHECK_CANCEL
  8400. ):
  8401. # UI-only actions — the printer's own screen handles these; the
  8402. # modal still surfaces them so the user has parity with Studio.
  8403. pass
  8404. case _:
  8405. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  8406. return False
  8407. return True