bambu_mqtt.py 447 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820
  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 retire_paho_client
  25. logger = logging.getLogger(__name__)
  26. # How long a manual load's tray target stays a hint for an H2D's tray_now: long
  27. # enough for a real load to report, short enough that a refused one cannot
  28. # relabel a later print's load of the same slot number (FW-C7).
  29. PENDING_TRAY_TARGET_TTL = 120.0
  30. # AMS module name prefixes used in get_version responses.
  31. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  32. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  33. # "ams_f1/<id>" – AMS Lite (A1, A1 Mini; the A2L reports id 16, stored as 6)
  34. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  35. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  36. _AMS_MODULE_PREFIXES = ("ams/", "ams_f1/", "n3f/", "n3s/")
  37. # gcode_state values that mean the printer is not idle and must not be handed a
  38. # new start-print (#2598). The firmware rejects a project_file while busy with
  39. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  40. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  41. # are valid start targets and are deliberately excluded. Mirrors
  42. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  43. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  44. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  45. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  46. # ended the cycle on schedule or aborted it. More than this many minutes still on
  47. # the clock means it was cut short, and the firmware's own reason codes are worth
  48. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  49. # left), and the log said only "drying complete", so the report carried no
  50. # evidence of why. The margin absorbs a stale last observation between AMS
  51. # pushes; it is not a judgement about how short "short" is.
  52. _EARLY_DRY_END_MINUTES = 5
  53. # CONNACK reason codes that mean the printer actively refused our credentials,
  54. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  55. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  56. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  57. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  58. # code (or, on some firmware, the serial used as the username) is wrong.
  59. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  60. # Short, stable slugs recorded on the client and surfaced to the connection
  61. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  62. # frontend picks a localized message key off these.
  63. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  64. CONNECT_ERROR_REFUSED = "refused"
  65. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  66. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  67. OrcaSlicer reads bit 18 of the hex string via
  68. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  69. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  70. that doesn't yield a clean integer so downstream consumers preserve today's
  71. behaviour rather than treating "absent" as "OFF".
  72. """
  73. if not isinstance(cfg_raw, str) or not cfg_raw:
  74. return None
  75. try:
  76. return bool((int(cfg_raw, 16) >> 18) & 1)
  77. except ValueError:
  78. return None
  79. def parse_ams_filament_backup_from_home_flag(home_flag: object) -> bool | None:
  80. """Extract AMS Filament Backup state from a push_status ``print.home_flag`` value.
  81. Bambu Studio reads bit 10 for every family (DeviceManager.cpp
  82. ``parse_home_flag``: ``SetAutoRefillEnabled((flag >> 10) & 0x1)``). It's
  83. the only source on the P1S, P1P, A1 and A1 Mini, which never send ``cfg``
  84. (#3259). On every printer that sends both, the two bits agree in all
  85. captured snapshots, ON and OFF alike. Returns ``None`` for anything that
  86. isn't an integer.
  87. """
  88. if isinstance(home_flag, bool) or not isinstance(home_flag, int):
  89. return None
  90. # Negative values are the 32-bit flag read as signed; bit 10 is the same.
  91. return bool((home_flag >> 10) & 1)
  92. def is_printer_status_frame(print_data: dict) -> bool:
  93. """True when a ``print`` payload is the printer reporting its own state.
  94. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  95. `project_file` ack carries whatever Bambuddy put on the wire — including
  96. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  97. telemetry means reading our own request back as the printer's state
  98. (#3040). Only `push_status` (and the odd firmware that omits `command`
  99. entirely on a status frame) describes the printer.
  100. """
  101. command = print_data.get("command")
  102. return command is None or command == "push_status"
  103. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  104. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  105. # firmware is internally inconsistent about it:
  106. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  107. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  108. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  109. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  110. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  111. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  112. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  113. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  114. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  115. A2L_LITE_PHYSICAL_AMS_ID = 16
  116. A2L_LITE_NORMALIZED_AMS_ID = 6
  117. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  118. def normalize_am_unit_id(ams_id: int) -> int:
  119. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  120. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  121. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  122. through untouched.
  123. """
  124. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  125. def wire_tray_color(tray_color: str | None) -> str:
  126. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  127. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  128. as a zero, and does it silently: the command response echoes the value you
  129. sent and reports ``result: "success"``, so only the next AMS push shows what
  130. was really stored. Measured on the reporter's machine (#2987), where the
  131. spool's own ``rgba`` is stored lowercase and went out verbatim:
  132. sent 09ff00ff -> AMS reports 09000000
  133. sent ff5100ff -> AMS reports 00510000
  134. sent 090000FF -> AMS reports 090000FF
  135. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  136. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  137. longer matches the spool that asked for it and the assignment is deleted
  138. seconds after being made -- and re-assigning through the slot modal writes
  139. the mangled colour back, because the modal seeds itself from the tray.
  140. Applied here, at the one place the command is built, rather than in each of
  141. the four callers: a caller that forgets is exactly how this arrived.
  142. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  143. blank stays blank, which is how a slot is cleared.
  144. """
  145. return (tray_color or "").strip().lstrip("#").upper()
  146. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  147. """Translate a normalised A2L slot back to the physical wire form.
  148. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  149. (normalised id 6), else ``None`` for every other unit.
  150. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  151. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  152. confirmed by capture: the physical **global** tray value the extrusion_cali
  153. commands put in `tray_id` — we extrapolate it as 16*4+slot = 64-67 to stay
  154. consistent with the physical unit id. BambuStudio's source sends 24+slot
  155. there instead (``GetTrayIndexMap``); a BambuStudio->A2L capture of a cali
  156. command would settle it, and it lives only here. Load's `target` is not this
  157. value: see ``change_filament_wire_ids``.
  158. """
  159. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  160. return None
  161. local_slot = tray_id % 4
  162. return (
  163. A2L_LITE_PHYSICAL_AMS_ID,
  164. local_slot,
  165. A2L_LITE_PHYSICAL_AMS_ID * 4 + local_slot,
  166. )
  167. def change_filament_wire_ids(tray_id: int) -> tuple[int, int, int]:
  168. """``(ams_id, slot_id, target)`` of ``ams_change_filament`` for an AMS tray.
  169. As BambuStudio's ``command_ams_change_filament`` builds them: a regular AMS
  170. is addressed by unit and local slot with the global tray as target; a unit
  171. id of 16 or more (the A2L AMS-Lite's physical 16, an AMS-HT's 128-135) has
  172. the unit id itself as target. An AMS-HT holds one tray, so its global tray
  173. id is its unit id and its slot is 0.
  174. """
  175. if 128 <= tray_id <= 135:
  176. return tray_id, 0, tray_id
  177. if (a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  178. return a2l[0], a2l[1], a2l[0]
  179. return tray_id // 4, tray_id % 4, tray_id
  180. def resolve_external_spools_in_mapping(ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool) -> object:
  181. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  182. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  183. dispatch both write an external spool there as -1 -- the same value as a
  184. slot that isn't fed at all -- and carry the real target only in
  185. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  186. list alone turns "printed from the external spool" into "unmapped", and
  187. usage then lands on whatever tray the fallback guesses.
  188. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  189. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  190. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  191. printers, which have one external spool that the wire always calls 255.
  192. ``{255, 255}`` is the unmapped marker and stays -1.
  193. An A2L AMS-Lite tray is the local slot 0-3 in the flat list and
  194. ``{ams_id: 16, slot_id: n}`` in ``ams_mapping2``; it becomes its normalised
  195. global tray 24+n. Kept local, it read as a regular AMS tray, so usage was
  196. charged to the wrong spool. Every other entry is left exactly as captured.
  197. Without a usable ``ams_mapping2`` the input is returned unchanged.
  198. """
  199. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  200. return ams_mapping
  201. if len(ams_mapping2) != len(ams_mapping):
  202. return ams_mapping
  203. resolved = list(ams_mapping)
  204. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  205. if not isinstance(detail, dict):
  206. continue
  207. ams_id = detail.get("ams_id")
  208. slot_id = detail.get("slot_id")
  209. if ams_id == A2L_LITE_PHYSICAL_AMS_ID and slot_id in (0, 1, 2, 3):
  210. resolved[i] = A2L_LITE_GLOBAL_BASE + slot_id
  211. continue
  212. if flat != -1 or ams_id not in (254, 255) or slot_id == 255:
  213. continue
  214. resolved[i] = ams_id if is_dual_nozzle else 254
  215. return resolved
  216. def unit_reported_absent(ams_id, ams_list: list, ams_exist_bits) -> bool:
  217. """Whether a push that doesn't list AMS unit ``ams_id`` says it is unplugged.
  218. ``ams_exist_bits`` (hex) has bit n set for AMS unit n, measured on an X1C
  219. (unit 1 -> "2", none -> "0") and an H2C (units 0, 1, 2 and HT 128 -> "17").
  220. So an AMS unit 0-3 whose bit is clear is gone. An empty unit list with no
  221. bits set means no unit at all, which is what the X1C sends with its AMS
  222. unplugged. Anything else is kept, as the merge always did: a partial push
  223. lists only some units, and the bits of an AMS HT or AMS Lite next to other
  224. units are not measured well enough to read.
  225. """
  226. if ams_exist_bits is None:
  227. return False
  228. try:
  229. bits = int(ams_exist_bits, 16) if isinstance(ams_exist_bits, str) else int(ams_exist_bits)
  230. unit = int(ams_id)
  231. except (TypeError, ValueError):
  232. return False
  233. if bits == 0 and not ams_list:
  234. return True
  235. return 0 <= unit <= 3 and not bits >> unit & 1
  236. def apply_tray_exist_bits(
  237. units: list,
  238. tray_exist_bits_str: str | int | None,
  239. *,
  240. power_on_flag: bool = True,
  241. log_label: str | None = None,
  242. annotate_exists: bool = False,
  243. ) -> int:
  244. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  245. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  246. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  247. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  248. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  249. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  250. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  251. instead of guessing from payload shape (#1322, #147).
  252. Two callers share this helper to keep their views consistent:
  253. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  254. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  255. facing push_status (#1726 — without this the VP would forward stale
  256. per-tray fields for empty slots, and BambuStudio's Sync would render
  257. phantom loaded slots).
  258. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  259. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  260. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  261. so spool removal is detected without requiring a manual reconnect.
  262. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  263. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  264. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  265. authoritative empty signal for the HT — the only working clear path, since
  266. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  267. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  268. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  269. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  270. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  271. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  272. the raw physical id 16 get the same bit base as callers holding the
  273. normalised 6 (#2697).
  274. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  275. way). Ints are tolerated for defensive symmetry but typically not seen
  276. on the wire. ``None`` / empty / unparseable → no-op.
  277. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  278. every processed slot. This is firmware's authoritative "spool physically
  279. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  280. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  281. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  282. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  283. leaves it False so the ``exists`` key never reaches the slicer wire format.
  284. Mutates ``units`` in place. Returns the number of slots cleared.
  285. """
  286. if not tray_exist_bits_str:
  287. return 0
  288. try:
  289. if isinstance(tray_exist_bits_str, int):
  290. tray_exist_bits = tray_exist_bits_str
  291. else:
  292. tray_exist_bits = int(tray_exist_bits_str, 16)
  293. except (ValueError, TypeError):
  294. return 0
  295. if tray_exist_bits == 0 and not power_on_flag:
  296. return 0
  297. if not isinstance(units, list):
  298. return 0
  299. cleared = 0
  300. for ams_unit in units:
  301. if not isinstance(ams_unit, dict):
  302. continue
  303. ams_id_raw = ams_unit.get("id")
  304. if ams_id_raw is None:
  305. continue
  306. try:
  307. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  308. except (ValueError, TypeError):
  309. continue
  310. if not isinstance(ams_id, int):
  311. continue
  312. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  313. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  314. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  315. # the physical 16. Both mean bit base 24, so fold them together here
  316. # rather than relying on every caller to normalise first — reading 16 as
  317. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  318. ams_id = normalize_am_unit_id(ams_id)
  319. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  320. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  321. # Anything outside those ranges has no known bit layout — don't guess it.
  322. is_ht = 128 <= ams_id <= 135
  323. if not is_ht and not (0 <= ams_id <= 15):
  324. continue
  325. for tray in ams_unit.get("tray", []):
  326. if not isinstance(tray, dict):
  327. continue
  328. tray_id_raw = tray.get("id")
  329. if tray_id_raw is None:
  330. continue
  331. try:
  332. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  333. except (ValueError, TypeError):
  334. continue
  335. if not isinstance(tray_id, int):
  336. continue
  337. global_bit = (16 + (ams_id - 128)) if is_ht else (ams_id * 4 + tray_id)
  338. slot_exists = (tray_exist_bits >> global_bit) & 1
  339. if annotate_exists:
  340. tray["exists"] = bool(slot_exists)
  341. if slot_exists:
  342. continue
  343. tray["state"] = 9
  344. if tray.get("tray_type"):
  345. if log_label:
  346. logger.debug(
  347. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  348. f"(tray_exist_bits bit {global_bit} = 0)"
  349. )
  350. tray["tray_type"] = ""
  351. tray["tray_sub_brands"] = ""
  352. tray["tray_color"] = ""
  353. tray["tray_id_name"] = ""
  354. tray["tag_uid"] = "0000000000000000"
  355. tray["tray_uuid"] = "00000000000000000000000000000000"
  356. tray["tray_info_idx"] = ""
  357. tray["remain"] = 0
  358. cleared += 1
  359. return cleared
  360. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  361. #
  362. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  363. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  364. # rack position is never mistakable for the nozzle on the other carriage.
  365. #
  366. # Extruder indices are a different namespace that happens to overlap these
  367. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  368. # Nothing below may pass a value from one namespace to the other untranslated;
  369. # doing exactly that is what #2800 was.
  370. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  371. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  372. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  373. #
  374. # Briefly changed to the plate's own slot count on the strength of a single
  375. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  376. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  377. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  378. # a calibration job, so the length varies with whatever Studio is doing rather
  379. # than with the filament count -- which makes it the wrong thing to derive.
  380. _RACK_WIRE_SLOTS = 32
  381. # The two carriages, as extruder indices in the form the queue stores (already
  382. # translated through the file's physical_extruder_map).
  383. #
  384. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  385. #
  386. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  387. # extruder 1, AMS 1 and 2 feed extruder 0;
  388. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  389. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  390. # and that print completed. So extruder 1 is the fixed hotend and extruder
  391. # 0 is the rack;
  392. # - our own constants were internally inconsistent about it: physical nozzle
  393. # id N sits on extruder N (see the L/R split in PrintersPage), and
  394. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  395. # extruder index of 0.
  396. #
  397. # These were the other way round until then, which is what dispatched a plate
  398. # to the carriage that had not been levelled and printed its first layer in
  399. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  400. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  401. # which *wire* worked, and the extruder indices were only inferred from it by
  402. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  403. # wire result stands; the inference from it did not.
  404. _FIXED_EXTRUDER_ID = 1
  405. _RACK_EXTRUDER_ID = 0
  406. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  407. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  408. # outright, which would not start the job at all. Native BambuStudio captures
  409. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  410. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  411. _FIXED_NOZZLE_ID = 1
  412. def resolve_rack_nozzle_mapping(
  413. slot_extruders: list[int],
  414. rack_nozzle_id: int | None,
  415. ) -> list[int] | None:
  416. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  417. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  418. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  419. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  420. reports as live.
  421. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  422. when the mapping cannot be resolved with confidence -- in which case the
  423. caller omits the field entirely and the firmware falls back to its own
  424. nozzle pick, exactly as it did before this translation existed. Omitting
  425. is deliberately the failure mode: a *wrong* physical ID makes the printer
  426. level with one nozzle and print with another several millimetres off the
  427. bed, which is far worse than letting the firmware choose.
  428. Returns None specifically when:
  429. - a slot needs the rack but the printer has not reported a live rack
  430. position (mid-swap, or a stale connection);
  431. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  432. for a plate sliced for the fixed hotend only (#2800 capture), so this
  433. matches it rather than naming a nozzle it does not have to name;
  434. - a slot names a carriage that is neither of the two an H2C has, which
  435. means the file was mapped for a machine this translation does not model;
  436. - the plate needs more slots than the wire format carries;
  437. - the input is not a list of whole numbers.
  438. Total by construction: it raises nothing, because the only caller is
  439. building an MQTT print command with no exception handler above it and the
  440. queue item has already been committed as `printing` by then. An
  441. unparseable input has to degrade to "let the firmware pick", not to a job
  442. wedged in a state no print will ever leave.
  443. """
  444. if not isinstance(slot_extruders, list) or not slot_extruders:
  445. return None
  446. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  447. return None
  448. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  449. return None
  450. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  451. return None
  452. # Normalise first so the checks below, and the values that reach the wire,
  453. # are known ints. bool is an int subclass and would otherwise serialise as
  454. # a JSON `true`; None means "slot not printed" and is folded into -1.
  455. normalised: list[int] = []
  456. for extruder in slot_extruders:
  457. if extruder is None:
  458. normalised.append(-1)
  459. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  460. normalised.append(extruder)
  461. else:
  462. return None
  463. if _RACK_EXTRUDER_ID not in normalised:
  464. return None
  465. wire = [-1] * _RACK_WIRE_SLOTS
  466. for index, extruder in enumerate(normalised):
  467. if extruder < 0:
  468. continue
  469. if extruder == _RACK_EXTRUDER_ID:
  470. wire[index] = rack_nozzle_id
  471. elif extruder == _FIXED_EXTRUDER_ID:
  472. wire[index] = _FIXED_NOZZLE_ID
  473. else:
  474. # An H2C has these two carriages and no others. A third index is a
  475. # file mapped for something else, and forwarding it raw would name
  476. # a physical nozzle by an index that does not identify one.
  477. return None
  478. return wire
  479. # A rack position as the operator counts it (and as the printer card and
  480. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  481. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  482. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  483. _RACK_POSITION_BASE = 15
  484. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  485. def rack_position_to_nozzle_id(position: int) -> int | None:
  486. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  487. if not isinstance(position, int) or isinstance(position, bool):
  488. return None
  489. if position not in RACK_POSITIONS:
  490. return None
  491. return _RACK_POSITION_BASE + position
  492. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  493. """Whether a live rack slot can print a group wanting this nozzle.
  494. Mirrors the filter BambuStudio applies in its own picker: the position has
  495. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  496. and flow type. A mismatch here is not cosmetic -- it is the printer being
  497. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  498. """
  499. if not isinstance(slot, dict):
  500. return False
  501. slot_diameter = str(slot.get("diameter") or "").strip()
  502. slot_type = str(slot.get("type") or "").strip()
  503. if not slot_diameter and not slot_type:
  504. return False # empty position
  505. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  506. # the printer does not.
  507. try:
  508. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  509. return False
  510. except (TypeError, ValueError):
  511. return False
  512. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  513. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  514. # printer that omits the code is not thereby ruled ineligible.
  515. wanted = volume_type.strip().lower()
  516. if wanted and slot_type:
  517. is_high_flow = slot_type.upper().startswith("HH")
  518. if wanted.startswith("high flow") != is_high_flow:
  519. return False
  520. return True
  521. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  522. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  523. _RACK_CARRIAGE_NOZZLE_ID = 0
  524. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  525. """Live rack contents keyed by 1-based position, mounted nozzle included.
  526. The firmware omits a rack id entirely while that nozzle is picked up onto
  527. the carriage (#943) -- it does not send an empty placeholder. Taking the
  528. omission at face value would rule the nozzle ineligible for the very print
  529. that wants it, and it is the single most likely position to be picked,
  530. because it is the one the last print left mounted.
  531. The absent id is recoverable only when exactly one is missing: rack ids are
  532. fixed at 16..21, so a single gap alongside a loaded carriage is that
  533. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  534. with four nozzles in six positions looks the same -- so those stay absent
  535. and the caller treats them as empty.
  536. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  537. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  538. """
  539. by_position: dict[int, dict] = {}
  540. carriage: dict | None = None
  541. for slot in rack_slots or []:
  542. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  543. continue
  544. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  545. carriage = slot
  546. continue
  547. position = slot["id"] - _RACK_POSITION_BASE
  548. if position in RACK_POSITIONS:
  549. by_position[position] = slot
  550. missing = [position for position in RACK_POSITIONS if position not in by_position]
  551. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  552. by_position[missing[0]] = carriage
  553. return by_position
  554. def resolve_rack_plan_mapping(
  555. slot_groups: list[int],
  556. groups: dict[int, dict],
  557. choice: dict[int, int],
  558. rack_slots: list[dict],
  559. ) -> tuple[list[int] | None, str | None]:
  560. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  561. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  562. That one can only name the single live rack position, so a plate wanting a
  563. different hotend per group is unresolvable to it. Here each group carries
  564. its own position, which is the operator's choice (#1784) -- the 3MF states
  565. it nowhere, proven by dispatching one plate twice with different picks and
  566. diffing the two files down to float noise.
  567. ``choice`` may be partial or empty; groups it does not name are assigned
  568. from the live rack, preferring a position already loaded with the group's
  569. own filament colour and otherwise taking the lowest eligible one.
  570. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  571. is a sentence naming what could not be satisfied. The caller decides what
  572. to do with a failure, and the two cases differ: a stale *explicit* pick
  573. should stop the print, while a failed auto-assignment should degrade to
  574. letting the firmware choose, exactly as before this existed.
  575. """
  576. if not isinstance(slot_groups, list) or not slot_groups:
  577. return None, "the plate lists no filament slots"
  578. if len(slot_groups) > _RACK_WIRE_SLOTS:
  579. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  580. by_position = _rack_by_position(rack_slots)
  581. # Assign every rack-bound group a position before building the wire, so a
  582. # group can never be handed one an earlier group already took. Explicit
  583. # picks are placed first: an auto-assignment must yield to them rather than
  584. # claim a position the operator asked for.
  585. assigned: dict[int, int] = {}
  586. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  587. for group_id in rack_group_ids:
  588. position = choice.get(group_id)
  589. if position is None:
  590. continue
  591. group = groups[group_id]
  592. if rack_position_to_nozzle_id(position) is None:
  593. return None, f"rack position {position} does not exist"
  594. if position in assigned.values():
  595. return None, f"rack position {position} is picked for more than one filament group"
  596. slot = by_position.get(position)
  597. if slot is None:
  598. return None, f"the printer reports nothing at rack position {position}"
  599. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  600. return None, (
  601. f"rack position {position} holds a "
  602. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  603. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  604. )
  605. assigned[group_id] = position
  606. for group_id in rack_group_ids:
  607. if group_id in assigned:
  608. continue
  609. group = groups[group_id]
  610. eligible = [
  611. position
  612. for position in RACK_POSITIONS
  613. if position not in assigned.values()
  614. and position in by_position
  615. and _rack_slot_is_eligible(
  616. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  617. )
  618. ]
  619. if not eligible:
  620. return None, (
  621. f"no free rack position holds a {group.get('nozzle_diameter')} "
  622. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  623. )
  624. # Prefer a position already carrying this group's colour: picking it
  625. # means the operator does not have to move filament to make the print
  626. # match what they asked for.
  627. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  628. assigned[group_id] = next(
  629. (
  630. position
  631. for position in eligible
  632. if wanted_colour
  633. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  634. == wanted_colour
  635. ),
  636. eligible[0],
  637. )
  638. wire = [-1] * _RACK_WIRE_SLOTS
  639. for index, group_id in enumerate(slot_groups):
  640. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  641. continue # slot this plate does not print
  642. group = groups.get(group_id)
  643. if group is None:
  644. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  645. if not group.get("on_rack"):
  646. wire[index] = _FIXED_NOZZLE_ID
  647. continue
  648. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  649. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  650. return None, f"filament group {group_id} resolved to no rack position"
  651. wire[index] = nozzle_id
  652. if all(value == -1 for value in wire):
  653. return None, "the plate assigns no filament to a nozzle"
  654. return wire, None
  655. @dataclass(frozen=True)
  656. class DryingCycleEnd:
  657. """What Bambuddy saw of one AMS drying cycle, reported when it ends (#2863).
  658. ``peak_minutes`` is the highest ``dry_time`` observed during the cycle and
  659. ``remaining_minutes`` the last one before the drop to 0. ``start_seen`` says
  660. whether the countdown was watched from its first minute; when it was not
  661. (Bambuddy started mid-cycle) the peak is only a lower bound on the length.
  662. ``target_temp`` / ``target_hours`` are known only for cycles Bambuddy itself
  663. started, because the printer never echoes them.
  664. """
  665. ams_id: int
  666. remaining_minutes: int
  667. peak_minutes: int
  668. start_seen: bool
  669. target_temp: int | None = None
  670. target_hours: int | None = None
  671. @dataclass
  672. class MQTTLogEntry:
  673. """Log entry for MQTT message debugging."""
  674. timestamp: str
  675. topic: str
  676. direction: str # "in" or "out"
  677. payload: dict
  678. @dataclass
  679. class HMSError:
  680. """Health Management System error from printer."""
  681. code: str
  682. attr: int # Attribute value for constructing wiki URL
  683. module: int
  684. # Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  685. # 3 notification, 0 invalid. From `code >> 16` for `hms[]` faults, and from
  686. # the error's first hex digit for `print_error` (#2728).
  687. severity: int
  688. # The bundled catalogue's sentence for this fault, resolved once here so
  689. # every surface that reports it — the status response, the WebSocket
  690. # broadcast, the completion payload, notifications — says the same thing.
  691. # None when Bambu publishes no text for the code; see `describe_fault`.
  692. # Replaces a `message` field that was never set or read anywhere.
  693. description: str | None = None
  694. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  695. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  696. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  697. # HMSError without explicitly passing actions can't silently land None on the schema
  698. # boundary and raise ValidationError at routes/printers.py response time.
  699. actions: list[str] = field(default_factory=list)
  700. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  701. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  702. job_id: str | None = None
  703. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  704. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  705. # 32-bit `print_error` path. The frontend echoes this back to
  706. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  707. # used to send caused the firmware to silently reject HMS commands on H2C
  708. # (#1830) and on `hms[]`-sourced faults generally.
  709. full_code: str = ""
  710. def completion_payload(self) -> dict:
  711. """This error as a print-complete payload carries it, for the failure reason."""
  712. return {
  713. "code": self.code,
  714. "attr": self.attr,
  715. "module": self.module,
  716. "severity": self.severity,
  717. # Lets the queue's failure reason label an `hms[]` fault
  718. # with its full code rather than a lossy short one (#2728).
  719. "full_code": self.full_code,
  720. # Carried so the queue's failure reason quotes the same
  721. # sentence the status response and the broadcast do,
  722. # rather than resolving the code a fourth time (#2926).
  723. "description": self.description,
  724. }
  725. # HMS short codes the firmware emits during normal user-cancel sequences.
  726. # These aren't faults — they're status echoes that confirm the cancel happened.
  727. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  728. # so they don't drive the printer card's "X problem" badge, the red pip, or
  729. # any other consumer that treats hms_errors as the active-fault list.
  730. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  731. {
  732. "0300_400C", # "The task was canceled."
  733. "0500_400E", # "Printing was cancelled."
  734. }
  735. )
  736. # "MQTT command verification failed" — the printer's authorization/authentication
  737. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  738. # command it could not verify. Queries (get_version, extrusion_cali_get,
  739. # pushall) still answer, so the connection looks perfectly healthy while
  740. # project_file, gcode_line and ams_change_filament are all silently dropped —
  741. # which is exactly how it presents: uploads succeed, the printer echoes our
  742. # subtask_id, then sits at IDLE forever (#2732).
  743. #
  744. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  745. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  746. # "0500_0007", which matches nothing in any catalog.
  747. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  748. @dataclass
  749. class KProfile:
  750. """Pressure advance (K) calibration profile from printer."""
  751. slot_id: int
  752. extruder_id: int
  753. nozzle_id: str
  754. nozzle_diameter: str
  755. filament_id: str
  756. name: str
  757. k_value: str
  758. n_coef: str = "0.000000"
  759. ams_id: int = 0
  760. tray_id: int = -1
  761. setting_id: str | None = None
  762. @dataclass
  763. class NozzleInfo:
  764. """Nozzle hardware configuration."""
  765. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  766. nozzle_diameter: str = "" # e.g., "0.4"
  767. # What await_cali_ack reports when the printer did not answer a K-profile write
  768. # in time. Not a refusal: firmware that predates the ack never answers.
  769. CALI_ACK_UNCONFIRMED = "no acknowledgement from printer"
  770. class KProfileReadError(Exception):
  771. """The printer's K-profile table could not be read: not connected, or no
  772. answer to any attempt. Not an empty table, which is a printer without
  773. profiles for that nozzle (#3404)."""
  774. # Time the printer has to list a skipped object in s_obj before the skip is
  775. # logged as not confirmed.
  776. SKIP_CONFIRM_TIMEOUT_S = 60.0
  777. # Answers to K-profile commands: they echo the command's own fields (the nozzle
  778. # diameter among them), never the printer's status.
  779. _KPROFILE_COMMAND_ANSWERS = frozenset(
  780. {"extrusion_cali_get", "extrusion_cali_set", "extrusion_cali_del", "extrusion_cali_sel"}
  781. )
  782. @dataclass
  783. class FilaSwitchState:
  784. """Filament Track Switch (FTS) accessory state.
  785. The FTS is an external accessory that mediates filament routing between an
  786. AMS and the printer's extruders. When installed, the AMS no longer has a
  787. fixed extruder assignment — any slot can be routed to any extruder via the
  788. track switch. Detected from print.device.fila_switch in MQTT.
  789. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  790. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  791. stable, operator-visible relationship — it is set on the printer's "Manual
  792. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  793. Field semantics below are taken from BambuStudio's own parser
  794. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  795. """
  796. installed: bool = False
  797. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  798. # the arrays are ordered B-then-A, which is the opposite of how they read.
  799. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  800. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  801. in_slots: list[int] = field(default_factory=list)
  802. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  803. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  804. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  805. # inlet is currently paired with which outlet is not reported at all.
  806. out_extruders: list[int] = field(default_factory=list)
  807. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  808. info: int = 0 # bit 0 = inlet has filament
  809. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  810. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  811. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  812. one of A/B.
  813. """
  814. index = {"A": 1, "B": 0}.get(inlet.upper())
  815. if index is None or index >= len(self.in_slots):
  816. return None
  817. raw = self.in_slots[index]
  818. if raw < 0:
  819. return None
  820. return (raw >> 8) & 0xFF, raw & 0xFF
  821. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  822. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  823. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  824. # as empty everywhere is strictly safer than reading it as the external spool.
  825. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  826. @dataclass
  827. class ExtruderSlot:
  828. """Which AMS slot an extruder is currently fed from.
  829. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  830. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  831. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  832. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  833. ``state.tray_now`` cannot answer this: it is a single value for the whole
  834. printer, so on a dual-nozzle machine with both hotends loaded it names only
  835. one of them. Unloading a specific slot needs to know which extruder is
  836. holding it, which is what this is for.
  837. """
  838. ams_id: int | None = None
  839. slot_id: int | None = None
  840. has_filament: bool = False
  841. def holds(self, ams_id: int, slot_id: int) -> bool:
  842. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  843. return self.ams_id == ams_id and self.slot_id == slot_id
  844. @dataclass
  845. class PrintOptions:
  846. """AI detection and print options from xcam data."""
  847. # Core AI detectors
  848. spaghetti_detector: bool = False
  849. print_halt: bool = False
  850. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  851. first_layer_inspector: bool = False
  852. printing_monitor: bool = False # AI print quality monitoring
  853. buildplate_marker_detector: bool = False
  854. allow_skip_parts: bool = False
  855. # Additional AI detectors - decoded from cfg bitmask
  856. nozzle_clumping_detector: bool = True
  857. nozzle_clumping_sensitivity: str = "medium"
  858. pileup_detector: bool = True
  859. pileup_sensitivity: str = "medium"
  860. airprint_detector: bool = True
  861. airprint_sensitivity: str = "medium"
  862. auto_recovery_step_loss: bool = True # Uses print.print_option command
  863. filament_tangle_detect: bool = False
  864. @dataclass
  865. class PrinterState:
  866. connected: bool = False
  867. state: str = "unknown"
  868. current_print: str | None = None
  869. subtask_name: str | None = None
  870. progress: float = 0.0
  871. remaining_time: int = 0
  872. layer_num: int = 0
  873. total_layers: int = 0
  874. temperatures: dict = field(default_factory=dict)
  875. raw_data: dict = field(default_factory=dict)
  876. gcode_file: str | None = None
  877. subtask_id: str | None = None
  878. hms_errors: list = field(default_factory=list) # List of HMSError
  879. kprofiles: list = field(default_factory=list) # List of KProfile
  880. sdcard: bool = False # SD card inserted
  881. # Whether the printer has ever actually told us about `sdcard`. Without this
  882. # the default False is indistinguishable from a real "no card", and any
  883. # consumer that treats False as evidence would act on silence — which is how
  884. # a storage gate turns into a regression for every printer whose firmware
  885. # simply doesn't publish the field (#2780).
  886. sdcard_reported: bool = False
  887. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  888. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  889. # whoever sent it (the slicer or us). Bambu states where the sliced file
  890. # went: `ftp://<name>` is external storage, which FTPS serves, while
  891. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  892. #
  893. # Two fields, because the two readers need different guarantees.
  894. # ``current_project_url`` belongs to the print now running and is cleared
  895. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  896. # "unknown" rather than inheriting the previous job's answer. That matters:
  897. # 18% of the print starts in #2780's bundle had no dispatch on the request
  898. # topic at all (touchscreen reprints, restart recovery), and a stale
  899. # internal-storage URL would make those skip an FTPS sweep that could have
  900. # found the file — losing an archive that works today.
  901. #
  902. # ``last_project_url`` is sticky and exists for reporting only: the
  903. # connection diagnostic is usually run *after* the print that prompted it,
  904. # by which point the per-print value is rightly gone.
  905. #
  906. # None means we never saw a dispatch — say nothing, don't guess.
  907. current_project_url: str | None = None
  908. last_project_url: str | None = None
  909. timelapse: bool = False # Timelapse recording active
  910. ipcam: bool = False # Live view / camera streaming enabled
  911. wifi_signal: int | None = None # WiFi signal strength in dBm
  912. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  913. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  914. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  915. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  916. # right. (The legacy parser below writes left -> [0], but it only ever runs
  917. # for single-nozzle printers -- every dual-nozzle model reports
  918. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  919. # than indexing it directly.
  920. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  921. # AI detection and print options
  922. print_options: PrintOptions = field(default_factory=PrintOptions)
  923. # Calibration stage tracking (from stg_cur and stg fields)
  924. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  925. stg: list = field(default_factory=list) # List of stages to execute
  926. # Air conditioning mode (0=cooling, 1=heating)
  927. airduct_mode: int = 0
  928. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  929. speed_level: int = 2
  930. # Chamber light on/off
  931. chamber_light: bool = False
  932. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  933. active_extruder: int = 0
  934. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  935. tray_now: int = 255
  936. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  937. # tray_tar = the slot the paused/loading print now expects
  938. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  939. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  940. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  941. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  942. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  943. tray_tar: int = 255
  944. tray_pre: int = 255
  945. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  946. last_loaded_tray: int = -1
  947. # Pending load target - used to track what tray we're loading for H2D disambiguation
  948. pending_tray_target: int | None = None
  949. # When it was set (time.monotonic): see PENDING_TRAY_TARGET_TTL.
  950. pending_tray_target_at: float | None = None
  951. # AMS status for filament change tracking (from print.ams.ams_status field)
  952. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  953. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  954. ams_status: int = 0
  955. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  956. ams_status_sub: int = 0 # ams_status & 0xFF
  957. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  958. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  959. mc_print_sub_stage: int = 0
  960. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  961. ams_mapping: list = field(default_factory=list)
  962. # The running print's AMS mapping (global tray per filament, -1 = none),
  963. # as captured from its print command. None when no print has one.
  964. print_ams_mapping: list | None = None
  965. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  966. ams_extruder_map: dict = field(default_factory=dict)
  967. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  968. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  969. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  970. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  971. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  972. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  973. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  974. ams_switch_inlet: dict = field(default_factory=dict)
  975. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  976. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  977. # series). Empty elsewhere, which every reader has to tolerate — see
  978. # ExtruderSlot for why tray_now cannot stand in for it.
  979. extruder_slots: dict = field(default_factory=dict)
  980. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  981. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  982. # regex used to derive the plate number from the path always falls back to
  983. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  984. # Bambuddy dispatches the print itself we know the plate authoritatively;
  985. # we record it here and prefer it over the gcode_file regex. The subtask
  986. # field guards against staleness: if the printer is currently running a
  987. # different subtask (e.g. a Studio-direct dispatch), these values are
  988. # ignored. Cleared on disconnect.
  989. dispatched_plate_id: int | None = None
  990. dispatched_subtask: str | None = None
  991. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  992. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  993. h2d_extruder_snow: dict = field(default_factory=dict)
  994. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  995. nozzle_rack: list = field(default_factory=list)
  996. # H2C rack position currently mounted / being moved to, from
  997. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  998. # the six rack slots), not extruder indices, and they are what the
  999. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  1000. # can tell us which hotend is in the carriage right now, so this is read
  1001. # live rather than derived from the queued job.
  1002. nozzle_rack_src_id: int | None = None
  1003. nozzle_rack_tar_id: int | None = None
  1004. # Timestamp of last AMS data update (for RFID refresh detection)
  1005. last_ams_update: float = 0.0
  1006. # Printable objects for skip object functionality: {identify_id: object_name}
  1007. printable_objects: dict = field(default_factory=dict)
  1008. # Objects that have been skipped during the current print
  1009. skipped_objects: list = field(default_factory=list)
  1010. # Pauses the slicer put into the running print, from its archived 3MF
  1011. # (#2984): threemf_tools.PausePoint, in print order. Empty when unknown.
  1012. pause_points: list = field(default_factory=list)
  1013. # Layers of those pauses a heads-up notification already went out for.
  1014. pause_warned_layers: set = field(default_factory=set)
  1015. # Fan speeds (0-100 percentage, None if not available for this model)
  1016. cooling_fan_speed: int | None = None # Part cooling fan
  1017. big_fan1_speed: int | None = None # Auxiliary fan
  1018. big_fan2_speed: int | None = None # Chamber/exhaust fan
  1019. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  1020. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  1021. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  1022. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  1023. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  1024. left_aux_fan_speed: int | None = None
  1025. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  1026. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  1027. # omits it, which is the case this flag exists to detect.
  1028. #
  1029. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  1030. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  1031. # harmless because only the P2S/X2D badge consults it — those models keep
  1032. # their unconditional "Chamber Fan" badge — but do not read this as
  1033. # "an exhaust kit is fitted" without also checking the model.
  1034. exhaust_fan_present: bool = False
  1035. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  1036. # Used by usage tracker to split filament weight on mid-print tray switch
  1037. tray_change_log: list = field(default_factory=list)
  1038. # Spools assigned to a tray during the current print, and the spool each
  1039. # assigned tray held at its start (services.spool_swaps, #3325).
  1040. spool_change_log: list = field(default_factory=list)
  1041. # Firmware version info (from info.module[name="ota"].sw_ver)
  1042. firmware_version: str | None = None
  1043. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  1044. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  1045. developer_mode: bool | None = None
  1046. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  1047. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  1048. # which uses the old protocol path; field not yet found). Consumers must treat
  1049. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  1050. ams_filament_backup: bool | None = None
  1051. # Stage name mapping from BambuStudio DeviceManager.cpp
  1052. STAGE_NAMES = {
  1053. 0: "Printing",
  1054. 1: "Auto bed leveling",
  1055. 2: "Heatbed preheating",
  1056. 3: "Vibration compensation",
  1057. 4: "Changing filament",
  1058. 5: "M400 pause",
  1059. 6: "Paused (filament ran out)",
  1060. 7: "Heating nozzle",
  1061. 8: "Calibrating dynamic flow",
  1062. 9: "Scanning bed surface",
  1063. 10: "Inspecting first layer",
  1064. 11: "Identifying build plate type",
  1065. 12: "Calibrating Micro Lidar",
  1066. 13: "Homing toolhead",
  1067. 14: "Cleaning nozzle tip",
  1068. 15: "Checking extruder temperature",
  1069. 16: "Paused by the user",
  1070. 17: "Pause (front cover fall off)",
  1071. 18: "Calibrating the micro lidar",
  1072. 19: "Calibrating flow ratio",
  1073. 20: "Pause (nozzle temperature malfunction)",
  1074. 21: "Pause (heatbed temperature malfunction)",
  1075. 22: "Filament unloading",
  1076. 23: "Pause (step loss)",
  1077. 24: "Filament loading",
  1078. 25: "Motor noise cancellation",
  1079. 26: "Pause (AMS offline)",
  1080. 27: "Pause (low speed of the heatbreak fan)",
  1081. 28: "Pause (chamber temperature control problem)",
  1082. 29: "Cooling chamber",
  1083. 30: "Pause (Gcode inserted by user)",
  1084. 31: "Motor noise showoff",
  1085. 32: "Pause (nozzle clumping)",
  1086. 33: "Pause (cutter error)",
  1087. 34: "Pause (first layer error)",
  1088. 35: "Pause (nozzle clog)",
  1089. 36: "Measuring motion precision",
  1090. 37: "Enhancing motion precision",
  1091. 38: "Measure motion accuracy",
  1092. 39: "Nozzle offset calibration",
  1093. 40: "High temperature auto bed leveling",
  1094. 41: "Auto Check: Quick Release Lever",
  1095. 42: "Auto Check: Door and Upper Cover",
  1096. 43: "Laser Calibration",
  1097. 44: "Auto Check: Platform",
  1098. 45: "Confirming BirdsEye Camera location",
  1099. 46: "Calibrating BirdsEye Camera",
  1100. 47: "Auto bed leveling - phase 1",
  1101. 48: "Auto bed leveling - phase 2",
  1102. 49: "Heating chamber",
  1103. 50: "Cooling heatbed",
  1104. 51: "Printing calibration lines",
  1105. 52: "Auto Check: Material",
  1106. 53: "Live View Camera Calibration",
  1107. 54: "Waiting for heatbed temperature",
  1108. 55: "Auto Check: Material Position",
  1109. 56: "Cutting Module Offset Calibration",
  1110. 57: "Measuring Surface",
  1111. 58: "Thermal Preconditioning",
  1112. 59: "Homing Blade Holder",
  1113. 60: "Calibrating Camera Offset",
  1114. 61: "Calibrating Blade Holder Position",
  1115. 62: "Hotend Pick and Place Test",
  1116. 63: "Waiting for Chamber temperature",
  1117. 64: "Preparing Hotend",
  1118. 65: "Calibrating nozzle clumping detection",
  1119. 66: "Purifying the chamber air",
  1120. 74: "Preparing", # Seen on H2D during print preparation
  1121. 77: "Preparing AMS",
  1122. }
  1123. def get_stage_name(stage: int) -> str:
  1124. """Get human-readable stage name from stage number."""
  1125. try:
  1126. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1127. except TypeError:
  1128. # `stage` is an int by convention only -- it comes straight out of the
  1129. # printer's JSON, and an unhashable value there would otherwise raise
  1130. # from inside the f-string that builds the stage-change log line, which
  1131. # is evaluated on every transition whatever the log level is set to.
  1132. # Labelling a value must not be able to abort the state update.
  1133. return f"Unknown stage ({stage})"
  1134. # #2547 end-of-print telemetry probe.
  1135. #
  1136. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1137. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1138. # but fires on no model in the field: across 247 support bundles there is not a
  1139. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1140. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1141. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1142. #
  1143. # We can't design a replacement from bundles we already have, because out of
  1144. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1145. # every other stage/action field is dropped unread. The obvious candidates
  1146. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1147. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1148. # own. Dumping the raw values for the window between the last object layer and
  1149. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1150. # anything — marks that moment.
  1151. #
  1152. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1153. # Nothing identifying, and nothing that could carry an access code.
  1154. _END_OF_PRINT_PROBE_FIELDS = (
  1155. "gcode_state",
  1156. "state",
  1157. "print_error",
  1158. "stg_cur",
  1159. "stg",
  1160. "stg_cd",
  1161. "mc_print_stage",
  1162. "mc_print_sub_stage",
  1163. "mc_action",
  1164. "mc_stage",
  1165. "print_real_action",
  1166. "print_gcode_action",
  1167. "spd_lvl",
  1168. "mc_percent",
  1169. "mc_remaining_time",
  1170. "layer_num",
  1171. "total_layer_num",
  1172. "home_flag",
  1173. "prepare_per",
  1174. )
  1175. # Frame budget for one print's probe. A long final layer can hold the window
  1176. # open for minutes at ~1 frame/second; this stops a single print from filling
  1177. # the log the user then has to upload.
  1178. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1179. # States that close the window. FINISH is the interesting one — the probe's
  1180. # whole job is to show what happened in the run-up to it.
  1181. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1182. class BambuMQTTClient:
  1183. """MQTT client for Bambu Lab printer communication."""
  1184. MQTT_PORT = 8883
  1185. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1186. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1187. _request_topic_cache: dict[str, bool] = {}
  1188. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1189. # the request topic. A SUBACK failure is the broker answering the question;
  1190. # a disconnect is only circumstantial, and any drop inside the window looks
  1191. # identical -- a network blip, the printer rebooting, the container being
  1192. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1193. # the rest of the process on a printer that supports it perfectly well
  1194. # (#2953). Require the drop to repeat before believing it; a printer that
  1195. # really does refuse the topic answers the same way every time and pays one
  1196. # extra reconnect for it.
  1197. _request_topic_probe_failures: dict[str, int] = {}
  1198. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1199. # Counter for generating unique MQTT client IDs across instances.
  1200. _client_instance_counter: int = 0
  1201. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1202. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1203. # every few seconds (and register_assignment_verification nudges a fresh
  1204. # pushall), so this only has to survive a couple of idle push intervals.
  1205. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1206. def __init__(
  1207. self,
  1208. ip_address: str,
  1209. serial_number: str,
  1210. access_code: str,
  1211. model: str | None = None,
  1212. on_state_change: Callable[[PrinterState], None] | None = None,
  1213. on_print_start: Callable[[dict], None] | None = None,
  1214. on_print_complete: Callable[[dict], None] | None = None,
  1215. on_ams_change: Callable[[list], None] | None = None,
  1216. on_layer_change: Callable[[int], None] | None = None,
  1217. on_print_progress: Callable[[int], None] | None = None,
  1218. on_bed_temp_update: Callable[[float], None] | None = None,
  1219. on_drying_complete: Callable[[int], None] | None = None,
  1220. on_drying_cycle_end: Callable[[DryingCycleEnd], None] | None = None,
  1221. on_print_running_observed: Callable[[dict], None] | None = None,
  1222. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1223. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1224. on_tray_change: Callable[[int, int], None] | None = None,
  1225. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1226. ):
  1227. self.ip_address = ip_address
  1228. self.serial_number = serial_number
  1229. self.access_code = access_code
  1230. self.model = model
  1231. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1232. self._debug_last: dict[str, object] = {}
  1233. self.on_state_change = on_state_change
  1234. self.on_print_start = on_print_start
  1235. self.on_print_complete = on_print_complete
  1236. self.on_ams_change = on_ams_change
  1237. # Fired when an AMS is moved to the switch's other inlet, which changes
  1238. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1239. self.on_fts_inlet_change = on_fts_inlet_change
  1240. self.on_layer_change = on_layer_change
  1241. # #2547: fired when `mc_percent` advances during a running print.
  1242. # `on_layer_change` stops firing the instant the final layer starts, so
  1243. # it is blind to the last few percent of a print — which is exactly the
  1244. # window the finish-photo frame bank needs to keep refreshing through.
  1245. # Progress is the one field that keeps ticking there and then freezes
  1246. # before the end G-code runs, so banking on it stays inside the print.
  1247. self.on_print_progress = on_print_progress
  1248. self.on_bed_temp_update = on_bed_temp_update
  1249. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1250. # the drying cycle just finished (auto- or manually-triggered).
  1251. # Receives the AMS id of the unit that finished drying.
  1252. self.on_drying_complete = on_drying_complete
  1253. # #2863: fired on the same edge with what was seen of the cycle, so the
  1254. # spools in that AMS can be stamped as dried.
  1255. self.on_drying_cycle_end = on_drying_cycle_end
  1256. # #1485 follow-up: fired the first time we see RUNNING state in a
  1257. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1258. # print, the #1304 first-push guard skipped the start event). Lets
  1259. # main.py capture a fresh timelapse baseline at restart-recovery
  1260. # time so the completion-time snapshot-diff still works. Receives
  1261. # the same shape as on_print_start (filename / subtask_name /
  1262. # remaining_time / raw_data / ams_mapping).
  1263. self.on_print_running_observed = on_print_running_observed
  1264. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1265. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1266. # with the process, and a long print outliving a restart would
  1267. # otherwise lose the segment boundaries the usage tracker splits on.
  1268. # Receives (global_tray_id, layer_num).
  1269. self.on_tray_change = on_tray_change
  1270. # #1721: fired the moment the printer enters the end-of-print
  1271. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1272. # we've hit the last layer / remaining_time<=0). This is the
  1273. # framing #1397 was after — toolhead parked, bed not yet
  1274. # dropped — but reached via a clean state signal instead of
  1275. # the per-layer M622 J1 macros which caused per-layer nozzle
  1276. # parks on slicer profiles with Timelapse Type = Smooth.
  1277. # A FINISH-state fallback below fires this same callback if
  1278. # stage 22 never arrives (cancel mid-print, external-spool-
  1279. # only prints, HMS halt before unload, firmware variants).
  1280. self.on_finish_photo_moment = on_finish_photo_moment
  1281. # #2582: fired after a spool assignment (ams_filament_setting +
  1282. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1283. # push landed or a timeout elapses without it. Receives
  1284. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1285. # tell the user "loaded" vs "assignment didn't take" instead of the
  1286. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1287. # feel random. See _check_assignment_verifications.
  1288. self.on_assignment_verified = on_assignment_verified
  1289. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1290. # value is the desired end-state we just pushed plus a monotonic
  1291. # deadline. Populated by register_assignment_verification, drained by
  1292. # _check_assignment_verifications on every AMS push.
  1293. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1294. # Per-AMS previous dry_time, used to detect the falling edge above.
  1295. # Seeded lazily as we observe each AMS unit.
  1296. self._previous_dry_times: dict[int, int] = {}
  1297. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1298. # A live cycle's countdown ticks once a minute; a command the firmware
  1299. # accepted but never actually started (observed on an H2D mid-print
  1300. # with two AMS-HT cycles already running: the third unit's timer sat
  1301. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1302. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1303. # reported as dry_countdown_stalled so the UI can stop claiming an
  1304. # active cycle that is not running.
  1305. self._dry_time_changed_at: dict[int, float] = {}
  1306. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1307. # last start. Bambu does not echo these back in the per-tick AMS push
  1308. # — only the dry_time countdown — so we cache what we sent to drive
  1309. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1310. self._drying_targets: dict[int, dict[str, object]] = {}
  1311. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1312. # ends a cycle far short of its duration, which on the telemetry alone
  1313. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1314. # log would otherwise blame the printer for our own decision (#2770).
  1315. self._drying_stops_sent: set[int] = set()
  1316. # Per-AMS record of the cycle in progress: the highest dry_time seen,
  1317. # whether its first minute was observed, and the target we sent for it.
  1318. # The target is copied here when the countdown starts because a stop
  1319. # drops _drying_targets before the cycle ends (#2863).
  1320. self._dry_cycles: dict[int, dict[str, object]] = {}
  1321. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1322. # for, so each is reported once rather than on every transition into it.
  1323. self._unnamed_stages_seen: set[int] = set()
  1324. self.state = PrinterState()
  1325. self._client: mqtt.Client | None = None
  1326. self._loop: asyncio.AbstractEventLoop | None = None
  1327. self._previous_gcode_state: str | None = None
  1328. self._previous_gcode_file: str | None = None
  1329. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1330. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1331. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1332. # #1721: one-shot guard so the end-of-print stage-22 detector
  1333. # and the FINISH-state fallback don't both fire on the same
  1334. # print. Reset to False on every print start.
  1335. self._finish_photo_captured: bool = False
  1336. # #2702: one-shot re-request of the layer total. Armed at print start
  1337. # when the starting frame carried no `total_layer_num`, spent on the
  1338. # first layer advance that still has no denominator. Bambu firmware
  1339. # only re-sends *changed* fields, so a total we never received (or
  1340. # dropped) is only recoverable via a full pushall.
  1341. self._total_layers_refresh_armed: bool = False
  1342. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1343. # window has run for a print so a late FINISH re-send can't reopen it.
  1344. self._eop_probe_armed: bool = True
  1345. self._eop_probe_open: bool = False
  1346. self._eop_probe_frames: int = 0
  1347. self._eop_probe_last: dict = {}
  1348. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1349. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1350. # #3317: the layer the previous print ended on. Right after a print
  1351. # starts, the printer can send one frame that still carries it (H2S:
  1352. # `layer_num` 357 with `mc_percent` 0, then 0 a second later). Taken at
  1353. # face value, the 0 that follows saved 357 as this print's last layer,
  1354. # and a print failing at layer 0 was charged as finished. Frames with
  1355. # this value are ignored until the new print reports another layer.
  1356. self._stale_layer_num: int = 0
  1357. # The subtask_id minted for the most recent start_print() command. The
  1358. # printer echoes it back in status, but often not within the first few
  1359. # seconds — so on_print_start uses this as the id source when the
  1360. # printer hasn't reported it yet, letting queue/scheduled archives
  1361. # persist a restart-stable id from the moment they dispatch (#1485).
  1362. self.last_dispatch_subtask_id: str | None = None
  1363. # The printer's answer to the last print start it refused, as (result,
  1364. # reason); cleared when the next start is sent. The start watchdog
  1365. # reads it to stop waiting for a print that will not come.
  1366. self.last_start_refusal: tuple[str, str | None] | None = None
  1367. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1368. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1369. self._logging_enabled: bool = False
  1370. self._last_message_time: float = 0.0 # Track when we last received a message
  1371. # Count of report-topic messages received since the last (re)connect.
  1372. # Lets check_staleness() distinguish "printer never sent a status
  1373. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1374. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1375. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1376. self._report_messages_since_connect: int = 0
  1377. self._zero_report_hint_logged: bool = False
  1378. # Set by mark_power_off() to the gcode_state held just before we
  1379. # optimistically forced the printer to "unknown" (#2629). Restored on
  1380. # the next inbound message, because message traffic proves the power
  1381. # was never actually cut. None whenever no power-off is presumed.
  1382. self._state_before_power_off: str | None = None
  1383. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1384. # printer's pushes verbatim to slicers connected to a virtual printer).
  1385. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1386. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1387. self._disconnection_event: threading.Event | None = None
  1388. self._previous_ams_hash: str | None = None # Track AMS changes
  1389. # Track external-spool (vt_tray) identity changes separately: the AMS
  1390. # hash above covers only AMS units, so an external-spool-only filament
  1391. # swap would never re-trigger inventory reconciliation (#2575).
  1392. self._previous_vt_tray_hash: str | None = None
  1393. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1394. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1395. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1396. # Track which (ams_id, field) warnings have already been emitted this connection
  1397. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1398. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1399. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1400. # keyed by the sequence_id we sent, so two concurrent requests for
  1401. # different nozzle sizes can't steal each other's response (#1748).
  1402. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1403. self._sequence_id: int = 0
  1404. self._pending_kprofile_requests: dict[str, dict] = {}
  1405. # The printer's calibration table, one bucket per nozzle diameter.
  1406. #
  1407. # An extrusion_cali_get response is the complete table for *one* nozzle
  1408. # size, and the printer answers whoever asks — including BambuStudio,
  1409. # whose queries land on the same report topic we subscribe to. Assigning
  1410. # each response straight to state.kprofiles therefore let any single
  1411. # answer stand for the whole printer: a GitHub backup probing
  1412. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1413. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1414. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1415. # card because H2-series trays carry no `k` of their own — the slot's
  1416. # K value is resolved from cali_idx against exactly this list.
  1417. #
  1418. # Keyed by diameter so a response only ever replaces the bucket it
  1419. # actually describes; state.kprofiles is then the union across buckets.
  1420. # An empty answer for a nozzle the printer doesn't have empties that
  1421. # bucket alone.
  1422. self._kprofiles_by_nozzle: dict[str, list] = {}
  1423. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1424. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1425. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1426. # by await_cali_ack.
  1427. self._pending_cali_acks: dict[str, dict | None] = {}
  1428. # Objects sent in skip_objects that the printer's s_obj list has not
  1429. # shown yet: object id -> when it was sent. And the ids of each
  1430. # command by its sequence_id, for its answer.
  1431. self._unconfirmed_skips: dict[int, float] = {}
  1432. self._skip_commands: dict[str, list[int]] = {}
  1433. # Acks for RFID re-reads (ams_get_rfid, and the M620 R gcode_line
  1434. # fallback), keyed the same way. Drained by ams_refresh_tray (#3206).
  1435. self._pending_rfid_acks: dict[str, dict | None] = {}
  1436. # Identifies the one project_file *we* dispatched, so its echo on the
  1437. # topic can be told apart from a slicer's. One-shot: consumed by the
  1438. # first frame that matches. See _project_file_key.
  1439. self._own_project_file_key: str | None = None
  1440. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1441. # Key: module_name, Value: timestamp when command was sent
  1442. self._xcam_hold_start: dict[str, float] = {}
  1443. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1444. # True once the printer has sent `cfg`; from then on AMS Filament Backup
  1445. # is read from cfg only, never from home_flag (#3259).
  1446. self._backup_cfg_seen: bool = False
  1447. # True once a full status report arrived without `cfg`; from then on
  1448. # home_flag bit 10 is read from every status frame (#3259).
  1449. self._backup_home_flag_trusted: bool = False
  1450. # Whether the frame being handled carried the nozzles' snow: only then
  1451. # may snow overrule the slot the same frame reports as tray_now.
  1452. self._snow_in_frame = False
  1453. # The captured ams_mapping lives on the state (print_ams_mapping), so
  1454. # the status the card reads carries it; see _captured_ams_mapping.
  1455. # The destination of the dispatch it was captured from.
  1456. self._captured_mapping_url: str | None = None
  1457. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1458. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1459. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1460. self._has_a2l_am_unit: bool = False
  1461. # Why the last connection attempt was refused by the printer, or None
  1462. # when we have never seen a CONNACK failure since the last success.
  1463. # Without this a rejected access code was completely invisible: paho
  1464. # reports the follow-up disconnect as the generic "Unspecified error"
  1465. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1466. # printer stuck in a reconnect loop looked identical whether it was
  1467. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1468. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1469. # string, kept for the log line only.
  1470. self.last_connect_error: str | None = None
  1471. self.last_connect_error_name: str | None = None
  1472. # Request topic subscription tracking
  1473. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1474. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1475. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1476. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1477. self._request_topic_sub_mid: int | None = None
  1478. self._request_topic_sub_time: float = 0.0
  1479. self._request_topic_confirmed: bool = False
  1480. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1481. # we probe by sending an ams_filament_setting and checking the response.
  1482. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1483. self._dev_mode_probed: bool = False
  1484. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1485. self._dev_mode_probe_seq: str | None = None
  1486. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1487. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1488. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1489. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1490. # the printer reports it until the fault clears, so when a later hms[]
  1491. # arrives without it (user enabled Developer Mode and restarted the
  1492. # printer) we drop back to "unknown" and let the probe re-run instead of
  1493. # leaving a permanently-wrong False behind (#2732).
  1494. self._dev_mode_from_hms: bool = False
  1495. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1496. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1497. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1498. self._stale_reconnecting: bool = False
  1499. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1500. # when the frontend polls status faster than paho can reconnect.
  1501. self._last_stale_reconnect: float = 0.0
  1502. # Zombie session detection via ams_filament_setting response tracking (#887).
  1503. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1504. # that develop later (telemetry flows but publishes silently fail).
  1505. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1506. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1507. @property
  1508. def topic_subscribe(self) -> str:
  1509. return f"device/{self.serial_number}/report"
  1510. @property
  1511. def topic_publish(self) -> str:
  1512. return f"device/{self.serial_number}/request"
  1513. @property
  1514. def report_messages_since_connect(self) -> int:
  1515. """Count of report-topic messages received since the latest (re)connect.
  1516. Exposed for the connection diagnostic so it can distinguish "MQTT
  1517. broker accepted us but the printer never published" (typically a
  1518. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1519. bridge that happens to be idle right now. Zero immediately after a
  1520. fresh connect is normal; zero after a full status push cycle is the
  1521. wrong-serial failure mode.
  1522. """
  1523. return self._report_messages_since_connect
  1524. # Maximum time (seconds) without a message before considering connection stale
  1525. STALE_TIMEOUT = 60.0
  1526. def is_stale(self) -> bool:
  1527. """Check if the connection is stale (no messages for too long)."""
  1528. if self._last_message_time == 0:
  1529. return False # Never received a message yet
  1530. time_since_last = time.time() - self._last_message_time
  1531. return time_since_last > self.STALE_TIMEOUT
  1532. def mark_power_off(self) -> bool:
  1533. """Presume the printer lost power (smart plug switched off).
  1534. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1535. The presumption is undone by ``_on_message`` if the printer keeps
  1536. talking — inbound traffic proves the power was never cut (#2629).
  1537. Returns True when the state was actually changed.
  1538. """
  1539. if not self.state.connected:
  1540. return False
  1541. previous = self.state.state
  1542. # Blank the state BEFORE recording what to restore. This runs on the
  1543. # event loop while _on_message runs on the paho thread, and the restore
  1544. # is a two-step (read saved state, compare against "unknown"). Writing
  1545. # "unknown" first means an interleaved message either sees no saved
  1546. # state yet (and skips, leaving the next message to restore) or sees a
  1547. # consistent pair — never a saved state paired with a live state it
  1548. # then discards, which would strand the printer on "unknown".
  1549. self.state.connected = False
  1550. self.state.state = "unknown"
  1551. # Only the first mark wins: a second call before any message arrives
  1552. # must not overwrite the real state with the "unknown" it just wrote.
  1553. # Nothing to restore if the state was already blank.
  1554. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1555. self._state_before_power_off = previous
  1556. return True
  1557. def _restore_state_after_false_power_off(self) -> bool:
  1558. """Undo a presumed power-off once the printer proves it is alive.
  1559. ``connected`` self-heals on the next message, but ``state`` does not:
  1560. it is only rewritten when a payload carries ``gcode_state``, and the
  1561. steady-state ``push_status`` frames are partial. Without this the
  1562. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1563. and the queue scheduler treats the printer as not idle the whole time
  1564. (#2629). Returns True when a state was restored.
  1565. """
  1566. previous = self._state_before_power_off
  1567. self._state_before_power_off = None
  1568. if previous is None or self.state.state != "unknown":
  1569. return False
  1570. logger.info(
  1571. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1572. self.serial_number,
  1573. previous,
  1574. )
  1575. self.state.state = previous
  1576. return True
  1577. # Minimum seconds between stale reconnect attempts. Frontend polls
  1578. # status every few seconds — without a cooldown, each poll would
  1579. # force-close the socket before paho has time to reconnect.
  1580. STALE_RECONNECT_COOLDOWN = 30.0
  1581. def check_staleness(self) -> bool:
  1582. """Check staleness and update connected state if stale. Returns True if connected."""
  1583. if self.state.connected and self.is_stale():
  1584. # Don't force-close again if we already did recently — give paho
  1585. # time to reconnect and the printer time to send its first message.
  1586. now = time.time()
  1587. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1588. return self.state.connected
  1589. logger.warning(
  1590. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1591. )
  1592. # A connection that keeps going stale without ever receiving a
  1593. # status report is almost always a wrong or mis-cased serial
  1594. # number — the broker accepts the connection and the subscription
  1595. # regardless, but the printer publishes to device/<real-serial>/
  1596. # report, which is case-sensitive. Surface that once so the user
  1597. # has something actionable instead of an endless reconnect loop.
  1598. # Only meaningful once the *current* session has had time to receive
  1599. # something. _report_messages_since_connect is reset by _on_connect,
  1600. # so a reconnect that lands microseconds before this check leaves it
  1601. # at 0 for reasons that have nothing to do with the serial — which is
  1602. # how a healthy P1S ended up being told to go check its serial number
  1603. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1604. # on this session means the hint only fires when the printer really
  1605. # has published nothing to the topic we subscribed to.
  1606. # _connect_time of 0 means we have no timestamp to judge by (never went
  1607. # through _on_connect); fall back to the old unconditional behaviour
  1608. # rather than silently swallowing the hint.
  1609. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1610. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1611. self._zero_report_hint_logged = True
  1612. logger.warning(
  1613. "[%s] Connected and subscribed, but the printer has sent zero "
  1614. "status reports. The most common cause is a wrong or mis-cased "
  1615. "serial number — the device/<serial>/report MQTT topic is "
  1616. "case-sensitive. Verify the serial number configured in Bambuddy "
  1617. "exactly matches the printer.",
  1618. self.serial_number,
  1619. )
  1620. self._last_stale_reconnect = now
  1621. self.state.connected = False
  1622. if self.on_state_change:
  1623. self.on_state_change(self.state)
  1624. # Route based on caller thread — see force_reconnect_stale_session.
  1625. # check_staleness is normally called from FastAPI handlers (async,
  1626. # gets the hard-reset path) but the dispatcher exists for safety.
  1627. self._stale_reconnecting = True
  1628. self._reset_client_for_reconnect()
  1629. return self.state.connected
  1630. def force_reconnect_stale_session(self, reason: str) -> None:
  1631. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1632. # arriving but our publishes don't reach the printer.
  1633. #
  1634. # Two routing paths:
  1635. #
  1636. # Async-context callers (queue dispatch deadline)
  1637. # → full client teardown + fresh client_id. Wipes paho's client-side
  1638. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1639. # `project_file` from the broken session would otherwise replay on
  1640. # reconnect, mixing stale commands into the next dispatch and
  1641. # triggering 0500_4003 SD R/W on the printer.
  1642. #
  1643. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1644. # zombie detection, both inside `_update_state`)
  1645. # → socket-close fallback. There is no running loop on that thread to
  1646. # hand the rebuilt client, so close the socket and let paho's own
  1647. # loop detect the broken connection and auto-reconnect (same
  1648. # instance, same client_id — queue replay is theoretically possible
  1649. # here but those paths have always done socket-close and #1136 was
  1650. # specifically triggered from the dispatch path).
  1651. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1652. self._stale_reconnecting = True
  1653. self.state.connected = False
  1654. if self.on_state_change:
  1655. self.on_state_change(self.state)
  1656. self._reset_client_for_reconnect()
  1657. def _reset_client_for_reconnect(self) -> None:
  1658. """Route between hard-reset and socket-close based on caller thread.
  1659. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1660. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1661. answers that and identifies the caller in one go — paho's callback
  1662. thread has no loop; every legitimate hard-reset caller (FastAPI
  1663. handlers, background async tasks) does."""
  1664. try:
  1665. loop = asyncio.get_running_loop()
  1666. except RuntimeError:
  1667. loop = None
  1668. if loop is not None:
  1669. self._loop = loop
  1670. self._hard_reset_client()
  1671. else:
  1672. self._socket_close_for_reconnect()
  1673. def _hard_reset_client(self) -> None:
  1674. """Tear down the paho client entirely and rebuild it with a fresh
  1675. client_id, so the broker drops the old session and paho's local
  1676. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1677. Caller is responsible for setting ``_stale_reconnecting`` and
  1678. broadcasting the disconnected state.
  1679. Returns as fast as it can build a client: the old one's teardown is
  1680. handed off rather than waited on, because waiting on it is what
  1681. stopped the event loop in #3068. See ``retire_paho_client``."""
  1682. old_client = self._client
  1683. self._client = None
  1684. if old_client is not None:
  1685. retire_paho_client(old_client, self.serial_number)
  1686. # Skip reconnect if no asyncio loop is available (test environment or
  1687. # pre-init). The next initial connect() call from PrinterManager will
  1688. # set up the client fresh.
  1689. if self._loop is None:
  1690. return
  1691. try:
  1692. self.connect(loop=self._loop)
  1693. except Exception as e:
  1694. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1695. def _socket_close_for_reconnect(self) -> None:
  1696. """Close the underlying socket so paho's loop thread detects the
  1697. broken connection and triggers auto-reconnect on the SAME client
  1698. instance. Safe to call from paho's own network thread (the loop
  1699. polls the socket on every iteration and handles a closed socket
  1700. gracefully). Used as a fallback when hard-reset isn't safe; queue
  1701. replay remains theoretically possible here but #1136 specifically
  1702. traced through the dispatch-deadline path which now hard-resets."""
  1703. if self._client:
  1704. try:
  1705. sock = self._client.socket()
  1706. if sock:
  1707. sock.close()
  1708. except Exception:
  1709. pass
  1710. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1711. if rc == 0:
  1712. self.state.connected = True
  1713. self.last_connect_error = None
  1714. self.last_connect_error_name = None
  1715. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1716. # A dropped-and-restored MQTT session means the presumed power-off was
  1717. # real (or at least that the printer restarted): there is nothing
  1718. # legitimate left to restore, and the printer will send a full status
  1719. # push shortly. Dropping the saved state keeps a stale one from being
  1720. # broadcast ahead of the first real report (#2629, #1679).
  1721. self._state_before_power_off = None
  1722. # Reset per-connection warning state so warnings fire once per (re)connection
  1723. self._ams_version_warned = set()
  1724. # Preserve cached developer_mode across auto-reconnects to avoid
  1725. # re-probing on every reconnect. The probe (ams_filament_setting to
  1726. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1727. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1728. # once when developer_mode is truly unknown (first connect).
  1729. # Reset probe tracking so stale timeout state doesn't carry over.
  1730. self._dev_mode_probed = False
  1731. self._dev_mode_needs_probe = False
  1732. self._dev_mode_probe_seq = None
  1733. self._dev_mode_probe_time = 0.0
  1734. self._dev_mode_probe_failures = 0
  1735. self._connect_time = time.monotonic()
  1736. self._report_messages_since_connect = 0
  1737. self._last_ams_cmd_time = 0.0
  1738. self._ams_cmd_unanswered = 0
  1739. # Drop any assignment verifications that were mid-flight before the
  1740. # reconnect — their deadlines are stale and the tray state we would
  1741. # compare against is about to be re-pushed from scratch (#2582).
  1742. # Dropping is silent (no failure event) on purpose.
  1743. self._pending_assignments.clear()
  1744. client.subscribe(self.topic_subscribe)
  1745. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1746. if self._request_topic_supported:
  1747. result, mid = client.subscribe(self.topic_publish)
  1748. if result == mqtt.MQTT_ERR_SUCCESS:
  1749. self._request_topic_sub_mid = mid
  1750. self._request_topic_sub_time = time.time()
  1751. self._request_topic_confirmed = False
  1752. else:
  1753. logger.warning(
  1754. "[%s] Failed to send request topic subscription",
  1755. self.serial_number,
  1756. )
  1757. self._request_topic_supported = False
  1758. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1759. # Request full status update (includes nozzle info in push_status response)
  1760. self._request_push_all()
  1761. # Request firmware version info
  1762. self._request_version()
  1763. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1764. # The correct nozzle data comes from push_status.
  1765. # Prime K-profile request (Bambu printers often ignore first request)
  1766. self._prime_kprofile_request()
  1767. # Immediately broadcast connection state change
  1768. if self.on_state_change:
  1769. self.on_state_change(self.state)
  1770. else:
  1771. self.state.connected = False
  1772. self._record_connect_refusal(rc)
  1773. def _record_connect_refusal(self, rc) -> None:
  1774. """Log and remember why the printer refused the MQTT connection.
  1775. The failure branch of ``_on_connect`` used to be a bare
  1776. ``connected = False``, which threw away the only signal that says
  1777. *why* a printer never comes online. The user-visible result was a
  1778. 30-second reconnect loop logging nothing but paho's generic
  1779. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1780. powered-off printer, so "my printer won't print" reports could not be
  1781. triaged without a round trip (#2698).
  1782. Never logs the access code itself; the code is the likely culprit but
  1783. printing it would put a credential in every support bundle.
  1784. """
  1785. code = getattr(rc, "value", rc)
  1786. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1787. self.last_connect_error_name = name
  1788. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1789. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1790. logger.warning(
  1791. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1792. "or serial number is wrong — the access code changes every time LAN Only or "
  1793. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1794. self.serial_number,
  1795. name,
  1796. code,
  1797. )
  1798. else:
  1799. self.last_connect_error = CONNECT_ERROR_REFUSED
  1800. logger.warning(
  1801. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1802. self.serial_number,
  1803. name,
  1804. code,
  1805. )
  1806. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1807. """Handle SUBACK responses to detect request topic subscription rejection."""
  1808. if mid == self._request_topic_sub_mid:
  1809. for rc in reason_code_list:
  1810. if rc.is_failure:
  1811. logger.warning(
  1812. "[%s] Request topic subscription rejected (code=%d: %s). "
  1813. "ams_mapping capture from slicer-initiated prints unavailable.",
  1814. self.serial_number,
  1815. rc.value,
  1816. rc.getName(),
  1817. )
  1818. self._request_topic_supported = False
  1819. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1820. else:
  1821. logger.info(
  1822. "[%s] Request topic subscription accepted. "
  1823. "ams_mapping capture enabled for slicer-initiated prints.",
  1824. self.serial_number,
  1825. )
  1826. self._request_topic_confirmed = True
  1827. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  1828. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  1829. self._request_topic_sub_mid = None
  1830. self._request_topic_sub_time = 0.0
  1831. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  1832. # Always unblock disconnect() callers, regardless of whether we suppress
  1833. # the state broadcast below. disconnect() sets _disconnection_event and
  1834. # waits on it — every callback path must fire it.
  1835. if self._disconnection_event:
  1836. self._disconnection_event.set()
  1837. # If we intentionally closed the socket for stale reconnect, don't broadcast
  1838. # another state change — check_staleness() already set connected=False and
  1839. # notified the UI. Just log and let paho auto-reconnect.
  1840. if self._stale_reconnecting:
  1841. logger.info(
  1842. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  1843. self.serial_number,
  1844. rc,
  1845. )
  1846. return
  1847. # Ignore spurious disconnect callbacks if we've received a message recently
  1848. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  1849. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  1850. # — only suppress when rc indicates a clean/normal disconnect.
  1851. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  1852. time_since_last_message = time.time() - self._last_message_time
  1853. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  1854. logger.debug(
  1855. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  1856. )
  1857. return
  1858. # Carry the last CONNACK refusal into the disconnect line. paho reports
  1859. # the drop that follows a refused CONNACK as "Unspecified error", so on
  1860. # its own this line says nothing useful about a printer that is looping
  1861. # on bad credentials — and this is the line that fills a support bundle
  1862. # (#2698).
  1863. if self.last_connect_error:
  1864. logger.warning(
  1865. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  1866. self.serial_number,
  1867. rc,
  1868. disconnect_flags,
  1869. self.last_connect_error_name,
  1870. )
  1871. else:
  1872. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  1873. # Detect if request topic subscription caused the disconnect.
  1874. # If we just subscribed and got disconnected before any SUBACK confirmation,
  1875. # the broker likely killed the connection due to the unauthorized subscription.
  1876. if (
  1877. self._request_topic_sub_time > 0
  1878. and not self._request_topic_confirmed
  1879. and time.time() - self._request_topic_sub_time < 10.0
  1880. # A disconnect we asked for says nothing about the subscription.
  1881. and self._disconnection_event is None
  1882. ):
  1883. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  1884. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  1885. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  1886. logger.warning(
  1887. "[%s] Disconnected shortly after request topic subscription %d times. "
  1888. "Disabling request topic for this printer — ams_mapping capture from "
  1889. "slicer-initiated prints is unavailable, and their filament will be "
  1890. "attributed from the printer's own tray reporting instead.",
  1891. self.serial_number,
  1892. failures,
  1893. )
  1894. self._request_topic_supported = False
  1895. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1896. else:
  1897. logger.info(
  1898. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  1899. "Retrying it on the next connection before giving up.",
  1900. self.serial_number,
  1901. failures,
  1902. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  1903. )
  1904. self._request_topic_sub_mid = None
  1905. self._request_topic_sub_time = 0.0
  1906. self.state.connected = False
  1907. if self.on_state_change:
  1908. self.on_state_change(self.state)
  1909. def _log_message(self, topic: str, direction: str, raw: str) -> None:
  1910. """Record a message for the MQTT Debug log, as it arrived.
  1911. Parsed again from the raw text rather than shared with the handlers:
  1912. processing keeps the payload's "print" dict as the new raw_data and
  1913. writes Bambuddy's merged AMS list and other state into it, so a shared
  1914. dict showed Bambuddy's state instead of what the printer sent (#3356).
  1915. """
  1916. self._message_log.append(
  1917. MQTTLogEntry(
  1918. timestamp=datetime.now(timezone.utc).isoformat(),
  1919. topic=topic,
  1920. direction=direction,
  1921. payload=json.loads(raw),
  1922. )
  1923. )
  1924. def _on_message(self, client, userdata, msg):
  1925. for handler in self._raw_message_handlers:
  1926. try:
  1927. handler(msg.topic, msg.payload)
  1928. except Exception:
  1929. logger.exception(
  1930. "[%s] raw-message handler crashed for topic=%s",
  1931. self.serial_number,
  1932. msg.topic,
  1933. )
  1934. try:
  1935. try:
  1936. raw = msg.payload.decode()
  1937. except UnicodeDecodeError:
  1938. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  1939. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  1940. raw = msg.payload.decode(errors="replace")
  1941. logger.warning(
  1942. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  1943. self.serial_number,
  1944. msg.topic,
  1945. len(msg.payload),
  1946. )
  1947. payload = json.loads(raw)
  1948. # Track last message time - receiving a message proves we're connected
  1949. self._last_message_time = time.time()
  1950. self.state.connected = True
  1951. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  1952. if msg.topic == self.topic_publish:
  1953. # Record it before returning. This topic carries every command
  1954. # travelling *to* the printer, including the ones Bambu Studio
  1955. # sends, and it used to be the one thing an MQTT capture could
  1956. # never show -- which is why "what does Studio put in the drying
  1957. # command?" had no answer from a user's log (#2774). Filed as
  1958. # "out" so the direction filter groups it with our own commands
  1959. # rather than with printer telemetry; anything we send
  1960. # lands twice, once on publish and once on the
  1961. # broker's echo, and the pair is itself evidence the command
  1962. # reached the broker.
  1963. if self._logging_enabled:
  1964. self._log_message(msg.topic, "out", raw)
  1965. self._handle_request_message(payload)
  1966. return
  1967. # Count status reports per connection so check_staleness() can tell
  1968. # "printer never sent a report" apart from a mid-session quiet gap.
  1969. if msg.topic == self.topic_subscribe:
  1970. self._report_messages_since_connect += 1
  1971. # Only report-topic traffic proves the *printer* is alive — the
  1972. # request topic also carries slicer/Bambuddy commands.
  1973. if self._state_before_power_off is not None:
  1974. if self._restore_state_after_false_power_off() and self.on_state_change:
  1975. self.on_state_change(self.state)
  1976. # Log message if logging is enabled
  1977. if self._logging_enabled:
  1978. self._log_message(msg.topic, "in", raw)
  1979. self._process_message(payload)
  1980. except json.JSONDecodeError:
  1981. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  1982. @property
  1983. def _captured_ams_mapping(self):
  1984. """The ams_mapping captured from the current print's command.
  1985. Kept on the state so the status shows it (the slot pills, #1762): the
  1986. printer's own push almost never carries one.
  1987. """
  1988. return self.state.print_ams_mapping
  1989. @_captured_ams_mapping.setter
  1990. def _captured_ams_mapping(self, mapping) -> None:
  1991. self.state.print_ams_mapping = mapping
  1992. def _handle_request_message(self, data: dict) -> None:
  1993. """Intercept print commands on the request topic to capture ams_mapping."""
  1994. print_data = data.get("print", {})
  1995. if not isinstance(print_data, dict):
  1996. return
  1997. command = print_data.get("command", "")
  1998. if command == "project_file":
  1999. # Where the dispatcher put the sliced file. Captured for every
  2000. # project_file, ours included: we publish to this same topic and
  2001. # subscribe to it, so whoever dispatched last wins, which is exactly
  2002. # the print the archive lookup is about to go looking for (#2780).
  2003. url = print_data.get("url")
  2004. if isinstance(url, str) and url:
  2005. self.state.current_project_url = url
  2006. self.state.last_project_url = url
  2007. if "ams_mapping" in print_data:
  2008. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2009. self._captured_mapping_url = url if isinstance(url, str) else None
  2010. logger.info(
  2011. "[%s] Captured ams_mapping from print command: %s",
  2012. self.serial_number,
  2013. self._captured_ams_mapping,
  2014. )
  2015. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  2016. # slicer-launched project_file passes through the request topic,
  2017. # log the full payload so we can diff Studio's field set against
  2018. # ours.
  2019. #
  2020. # This used to read `sequence_id != "20000"`, on the belief that
  2021. # 20000 was ours alone. It is not: 20000 is the slicer convention
  2022. # Bambuddy adopted -- bind_server documents the slicer sending it
  2023. # during detect, and measured on the wire OrcaSlicer dispatched
  2024. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  2025. # counting up from the same base. So the test swallowed whichever
  2026. # slicer dispatch happened to land on 20000, which on a fresh
  2027. # slicer start is the first one. Match our own dispatch instead.
  2028. if self._project_file_key(print_data) == self._own_project_file_key:
  2029. self._own_project_file_key = None
  2030. else:
  2031. logger.info(
  2032. "[%s] External project_file payload: %s",
  2033. self.serial_number,
  2034. json.dumps(print_data),
  2035. )
  2036. def _capture_report_project_file(self, print_data: dict) -> None:
  2037. """Read a print's destination off a ``project_file`` *response* (#1820).
  2038. ``_handle_request_message`` only ever sees the request topic, so a print
  2039. started from the printer's own touchscreen -- which publishes nothing --
  2040. left ``current_project_url`` at None, and the storage verdict fell
  2041. through to the ``sdcard`` fallback for the one case it was written for.
  2042. On an H2S that flag is True (its "card" is the internal eMMC), so the
  2043. verdict came back reachable and the ~110-connection sweep ran in full.
  2044. The printer does announce it: an unsolicited ``project_file`` response
  2045. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  2046. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  2047. This also covers an install nobody had in view: some brokers refuse the
  2048. request-topic subscription, and on those no print of any kind has ever
  2049. populated the field.
  2050. Both kinds of ``project_file`` on this topic are read -- the printer's
  2051. echo of a dispatch and a screen start -- because both name the
  2052. destination in ``url``, which is the only thing the verdict wants. What
  2053. this must NOT do is reuse ``_handle_request_message``'s "External
  2054. project_file payload" diagnostic: our own dispatch is echoed on *both*
  2055. topics, the request-topic echo arrives first and clears
  2056. ``_own_project_file_key``, so by the time this frame lands the key is
  2057. already None and every Bambuddy-started print would log itself as
  2058. someone else's.
  2059. """
  2060. # Same shape as _handle_request_message: the frame is whatever the
  2061. # printer put on the wire, and this is the first thing to touch it.
  2062. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  2063. return
  2064. # A refused dispatch names a file that was never written. Acting on it
  2065. # would pin an archive on a destination nothing ever went to. Logged:
  2066. # nothing else says the printer refused a print it was sent.
  2067. result = str(print_data.get("result") or "")
  2068. if result.upper() != "SUCCESS":
  2069. logger.info(
  2070. "[%s] Printer refused a print start (project_file): result=%s reason=%s url=%s",
  2071. self.serial_number,
  2072. result,
  2073. print_data.get("reason"),
  2074. print_data.get("url"),
  2075. )
  2076. self.last_start_refusal = (result, print_data.get("reason"))
  2077. return
  2078. url = print_data.get("url")
  2079. if not isinstance(url, str) or not url:
  2080. return
  2081. if self.state.current_project_url != url:
  2082. logger.info(
  2083. "[%s] Print destination from the report topic: %s",
  2084. self.serial_number,
  2085. url,
  2086. )
  2087. self.state.current_project_url = url
  2088. self.state.last_project_url = url
  2089. # On a screen start this frame is the only place the mapping appears --
  2090. # no slicer ever sent one. Fill a gap only: when the request topic
  2091. # already captured this print's mapping that copy is the slicer's own,
  2092. # and the echo can arrive without the field at all. A mapping captured
  2093. # for another destination is from a dispatch that never ran (refused,
  2094. # or cancelled before it started, so no completion cleared it).
  2095. stale = self._captured_ams_mapping is not None and self._captured_mapping_url != url
  2096. if (self._captured_ams_mapping is None or stale) and isinstance(print_data.get("ams_mapping"), list):
  2097. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2098. self._captured_mapping_url = url
  2099. logger.info(
  2100. "[%s] Captured ams_mapping from print response: %s",
  2101. self.serial_number,
  2102. self._captured_ams_mapping,
  2103. )
  2104. def _resolve_captured_mapping(self, print_data: dict) -> object:
  2105. """The ``ams_mapping`` of a project_file, with external spools resolved
  2106. from its ``ams_mapping2`` (#3166)."""
  2107. from backend.app.utils.printer_models import is_dual_nozzle_model
  2108. return resolve_external_spools_in_mapping(
  2109. print_data.get("ams_mapping"),
  2110. print_data.get("ams_mapping2"),
  2111. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  2112. )
  2113. @staticmethod
  2114. def _project_file_key(print_data: dict) -> str:
  2115. """Identity of a project_file dispatch, for telling ours from a slicer's.
  2116. Sequence id alone cannot do it -- every slicer counts up from the same
  2117. 20000 -- so this also carries the file and its destination, which differ
  2118. between any two real dispatches.
  2119. """
  2120. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  2121. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  2122. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  2123. The state dumps in the push_status handler fire whenever their field is
  2124. *present* in the frame — and a full push_status carries every field, so
  2125. they fire on every frame regardless of whether anything changed. Several
  2126. even say "updated" or "changes" in their own comment while doing nothing
  2127. of the sort.
  2128. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  2129. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  2130. minutes: the reporter enabled debug logging as asked and the support
  2131. bundle came back holding under five minutes of history, almost none of it
  2132. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  2133. these dumps.
  2134. Deduplicating on the value keeps every transition — which is the only part
  2135. anyone reads these lines for — and drops the steady-state repetition.
  2136. ``value`` must capture everything interpolated into ``msg``, or a change
  2137. will be swallowed; pass a tuple when the message renders several fields.
  2138. """
  2139. if not logger.isEnabledFor(logging.DEBUG):
  2140. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  2141. # and these clients outlive the toggle. Letting INFO-level frames warm
  2142. # the cache would be self-defeating: the operator turns debug on
  2143. # precisely to see the printer's current state, and a cache already
  2144. # holding every steady-state value would suppress that baseline until
  2145. # something happened to change. On an idle printer the bundle would
  2146. # come back with none of these lines at all.
  2147. #
  2148. # So while debug is off we record nothing and drop whatever we had.
  2149. # Every enable then starts cold and dumps a full baseline on the next
  2150. # frame, exactly as it did before this method existed.
  2151. self._debug_last.clear()
  2152. return
  2153. if self._debug_last.get(key) == value:
  2154. return
  2155. self._debug_last[key] = value
  2156. logger.debug(msg, *args)
  2157. def _process_message(self, payload: dict):
  2158. """Process incoming MQTT message from printer."""
  2159. # Handle top-level AMS data (comes outside of "print" key)
  2160. # Wrap in try/except to prevent breaking the MQTT connection
  2161. if "ams" in payload:
  2162. try:
  2163. self._snow_in_frame = False # a bare AMS frame carries no extruder data
  2164. self._handle_ams_data(payload["ams"])
  2165. except Exception as e:
  2166. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  2167. # Handle xcam data (camera settings and AI detection) at top level
  2168. if "xcam" in payload:
  2169. xcam_data = payload["xcam"]
  2170. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  2171. self._parse_xcam_data(xcam_data)
  2172. # Fire state change callback for top-level xcam (not nested in "print")
  2173. if "print" not in payload and self.on_state_change:
  2174. self.on_state_change(self.state)
  2175. # Handle system responses (accessories info, etc.)
  2176. if "system" in payload:
  2177. system_data = payload["system"]
  2178. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  2179. self._handle_system_response(system_data)
  2180. # Handle info responses (firmware version info from get_version command)
  2181. if "info" in payload:
  2182. info_data = payload["info"]
  2183. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2184. self._handle_version_info(info_data)
  2185. # Parse WiFi signal at top level (some printers send it here)
  2186. if "wifi_signal" in payload:
  2187. wifi_signal = payload["wifi_signal"]
  2188. if isinstance(wifi_signal, (int, float)):
  2189. self.state.wifi_signal = int(wifi_signal)
  2190. elif isinstance(wifi_signal, str):
  2191. try:
  2192. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2193. except ValueError:
  2194. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2195. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2196. from backend.app.utils.printer_models import has_ethernet
  2197. if has_ethernet(self.model):
  2198. self.state.wired_network = self.state.wifi_signal == -90
  2199. # Parse developer LAN mode from top-level "fun" field
  2200. # Some firmware versions send "fun" at the top level, others inside "print"
  2201. if "fun" in payload:
  2202. try:
  2203. fun_val = payload["fun"]
  2204. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2205. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2206. except (ValueError, TypeError):
  2207. pass
  2208. if "print" in payload:
  2209. print_data = payload["print"]
  2210. # Before anything reads the state: this is where a touchscreen-
  2211. # started print announces where its file lives, and the print-start
  2212. # handler asks ~2 s later (#1820).
  2213. self._capture_report_project_file(print_data)
  2214. # Check if xcam is nested inside print data
  2215. if "xcam" in print_data:
  2216. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2217. self._parse_xcam_data(print_data["xcam"])
  2218. # Log when we see gcode_state changes
  2219. if "gcode_state" in print_data:
  2220. logger.debug(
  2221. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2222. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2223. )
  2224. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2225. # new-protocol printers. Verified against OrcaSlicer's
  2226. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2227. # and live H2D ON/OFF capture 2026-06-20.
  2228. #
  2229. # Families without cfg (P1S, P1P, A1, A1 Mini) carry it in home_flag
  2230. # bit 10 (#3259). Trusted once a full status report (the same
  2231. # >30-key test as the developer-mode probe) arrived without cfg;
  2232. # from then on every status frame that carries home_flag is read,
  2233. # so a toggle in the slicer shows up without a Force Refresh (P1S
  2234. # capture: each toggle came in a 4-6 key update frame). Before
  2235. # that nothing is read from small frames, so a cfg printer can't
  2236. # be misread from a frame that arrives ahead of its first cfg.
  2237. # Printers that send cfg keep reading it alone.
  2238. #
  2239. # Hold-timer guard: when the user just toggled via the badge, the
  2240. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2241. # for ~3 s before the firmware reflects the change. Without this
  2242. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2243. # Only from a status frame: a project_file ack echoes our own
  2244. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2245. # stuck on every family that doesn't repeat `cfg` in its periodic
  2246. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2247. new_backup = None
  2248. if is_printer_status_frame(print_data):
  2249. if "cfg" in print_data:
  2250. self._backup_cfg_seen = True
  2251. new_backup = parse_ams_filament_backup_from_cfg(print_data["cfg"])
  2252. elif not self._backup_cfg_seen:
  2253. if len(print_data) > 30:
  2254. self._backup_home_flag_trusted = True
  2255. if self._backup_home_flag_trusted:
  2256. new_backup = parse_ams_filament_backup_from_home_flag(print_data.get("home_flag"))
  2257. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2258. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2259. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2260. logger.debug(
  2261. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2262. self.serial_number,
  2263. time.time() - hold_start,
  2264. )
  2265. else:
  2266. logger.info(
  2267. "[%s] AMS Filament Backup: %s",
  2268. self.serial_number,
  2269. "ON" if new_backup else "OFF",
  2270. )
  2271. self.state.ams_filament_backup = new_backup
  2272. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2273. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2274. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2275. if not self._is_dual_nozzle and "device" in print_data:
  2276. dev = print_data.get("device")
  2277. if isinstance(dev, dict):
  2278. ext_info = dev.get("extruder", {}).get("info", [])
  2279. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2280. self._is_dual_nozzle = True
  2281. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2282. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2283. # out of the AMS info bits, but only means anything once we know a
  2284. # switch is installed. Parsing them the other way round would lose
  2285. # the binding on every frame where the two arrive together.
  2286. self._parse_fila_switch(print_data)
  2287. # Before _handle_ams_data too: an H2D's tray_now is a bare slot that
  2288. # this frame's extruder data places (which nozzle, which AMS).
  2289. self._snow_in_frame = self._parse_extruder_position(print_data)
  2290. self._parse_extruder_slots(print_data)
  2291. # Handle AMS data that comes inside print key
  2292. if "ams" in print_data:
  2293. try:
  2294. self._handle_ams_data(print_data["ams"])
  2295. except Exception as e:
  2296. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2297. # Handle vir_slot (H2-series external spool data) — list of external trays
  2298. # Process vir_slot FIRST so it takes priority over vt_tray
  2299. if "vir_slot" in print_data:
  2300. vir_slot = print_data["vir_slot"]
  2301. if isinstance(vir_slot, list) and vir_slot:
  2302. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2303. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2304. # Remap id=255→254 for single-slot printers so active detection works.
  2305. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2306. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2307. vir_slot[0]["id"] = "254"
  2308. self.state.raw_data["vt_tray"] = vir_slot
  2309. # Handle vt_tray (virtual tray / external spool) data
  2310. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2311. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2312. # which would overwrite the correct multi-slot vir_slot data)
  2313. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2314. vt_tray = print_data["vt_tray"]
  2315. existing = self.state.raw_data.get("vt_tray")
  2316. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2317. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2318. pass # Keep the vir_slot data
  2319. else:
  2320. if isinstance(vt_tray, dict):
  2321. vt_tray = [vt_tray]
  2322. self.state.raw_data["vt_tray"] = vt_tray
  2323. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2324. # units, and _handle_ams_data runs before this block — so a change
  2325. # to the external spool alone (e.g. swapping generic TPU for generic
  2326. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2327. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2328. # external-spool identity changes here and fire the same callback.
  2329. self._maybe_trigger_external_spool_change()
  2330. # Parse ams_status directly from print data (NOT from print.ams)
  2331. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2332. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2333. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2334. if "ams_status" in print_data:
  2335. raw_ams_status = print_data["ams_status"]
  2336. if isinstance(raw_ams_status, str):
  2337. try:
  2338. self.state.ams_status = int(raw_ams_status)
  2339. except ValueError:
  2340. self.state.ams_status = 0
  2341. else:
  2342. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2343. # Compute main and sub status
  2344. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2345. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2346. # Log when ams_status changes (for filament change tracking debug)
  2347. self._debug_on_change(
  2348. "ams_status:print",
  2349. self.state.ams_status,
  2350. "[%s] ams_status: %s (main=%s, sub=%s)",
  2351. self.serial_number,
  2352. self.state.ams_status,
  2353. self.state.ams_status_main,
  2354. self.state.ams_status_sub,
  2355. )
  2356. # Check for command responses
  2357. if "command" in print_data:
  2358. cmd = print_data.get("command")
  2359. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2360. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2361. # INFO, not debug: this is the printer's verdict on a write
  2362. # the user just made, and it was invisible in support
  2363. # bundles for as long as it sat at DEBUG (#2718). Same
  2364. # reasoning as ams_filament_drying below.
  2365. logger.info(
  2366. "[%s] %s response: result=%s reason=%s seq=%s",
  2367. self.serial_number,
  2368. cmd,
  2369. print_data.get("result"),
  2370. print_data.get("reason", ""),
  2371. print_data.get("sequence_id"),
  2372. )
  2373. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2374. ack_seq = str(print_data.get("sequence_id", ""))
  2375. if ack_seq in self._pending_cali_acks:
  2376. self._pending_cali_acks[ack_seq] = print_data
  2377. elif cmd == "skip_objects":
  2378. self._handle_skip_objects_answer(print_data)
  2379. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2380. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2381. # A refused ams_filament_setting is the printer's verdict on
  2382. # a write the user just made, and at DEBUG it never reached
  2383. # a support bundle: #2756 reported six manual Configure Slot
  2384. # attempts on an X1C, each returning HTTP 200 with the
  2385. # read-back still showing the previous profile, and no
  2386. # record of what the printer said about any of them. Same
  2387. # promotion as extrusion_cali_set (#2718) and
  2388. # ams_filament_drying (#1447) — but only on a non-success,
  2389. # because unlike those two this command is not rare: every
  2390. # spool assignment and every K-profile re-apply sends one,
  2391. # so promoting each ack would bury the interesting line.
  2392. #
  2393. # The developer-mode probe is excluded. It sends this exact
  2394. # command to the external slot precisely to see it refused
  2395. # on P1 firmware, so its failure is a normal reading rather
  2396. # than a fault. Its response is still matched below (this
  2397. # runs before _handle_dev_mode_probe_response clears the
  2398. # seq), and user-initiated commands can't be mistaken for
  2399. # it — they publish a hardcoded sequence_id of "0".
  2400. result = print_data.get("result")
  2401. is_dev_mode_probe = (
  2402. self._dev_mode_probe_seq is not None
  2403. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2404. )
  2405. # extrusion_cali_sel too (FW-C3): every RFID re-read
  2406. # re-applies the spool's K-profile and logs "Applied PA
  2407. # profile", so its refusal must reach the bundle beside it.
  2408. # The printer's word, not a verdict: the extrusion_cali_*
  2409. # acks are known to say "fail" for writes that applied.
  2410. if not is_dev_mode_probe and isinstance(result, str) and result.lower() != "success":
  2411. logger.info(
  2412. "[%s] %s refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2413. self.serial_number,
  2414. cmd,
  2415. result,
  2416. print_data.get("reason", ""),
  2417. print_data.get("ams_id"),
  2418. print_data.get("tray_id"),
  2419. )
  2420. # AMS drying responses are rare (user-initiated only) and the
  2421. # full payload — including `result` and any `reason` code —
  2422. # is the only way to diagnose silent rejections like #1447.
  2423. # INFO level so the body lands in support bundles by default.
  2424. elif cmd == "ams_filament_drying":
  2425. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2426. # RFID re-reads are user-initiated and rare, and a refusal was
  2427. # invisible until #3206 (X1Plus answering FAIL / ERROR STATE).
  2428. # gcode_line acks are only of interest when they answer our
  2429. # M620 R fallback, so those are matched by sequence_id alone.
  2430. ack_seq = str(print_data.get("sequence_id", ""))
  2431. if (
  2432. cmd in ("ams_get_rfid", "gcode_line")
  2433. and ack_seq in self._pending_rfid_acks
  2434. and "result" in print_data
  2435. ):
  2436. logger.info(
  2437. "[%s] %s response: result=%s reason=%s seq=%s",
  2438. self.serial_number,
  2439. cmd,
  2440. print_data.get("result"),
  2441. print_data.get("reason", ""),
  2442. ack_seq,
  2443. )
  2444. self._pending_rfid_acks[ack_seq] = print_data
  2445. # Check for developer mode probe response
  2446. if (
  2447. cmd == "ams_filament_setting"
  2448. and self._dev_mode_probe_seq is not None
  2449. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2450. ):
  2451. self._handle_dev_mode_probe_response(print_data)
  2452. # Track user-initiated ams_filament_setting responses (#887
  2453. # zombie detection). Reset both the timer AND the unanswered
  2454. # counter on ANY response — the response proves the channel is
  2455. # alive, so the counter must not stay armed even when the
  2456. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2457. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2458. # caused #1164: one sluggish response (>10s) would set the
  2459. # counter to 1 and zero the timer; the late response arrived
  2460. # but was ignored by this branch (timer is 0); the counter
  2461. # stayed at 1 indefinitely; the very next slow response —
  2462. # possibly hours later, on a totally unrelated command — would
  2463. # take it to 2 and force-reconnect, surfacing as "filament
  2464. # config doesn't reach the printer ~6 changes in".
  2465. elif cmd == "ams_filament_setting":
  2466. self._last_ams_cmd_time = 0.0
  2467. self._ams_cmd_unanswered = 0
  2468. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2469. if is_kprofile_response:
  2470. self._handle_kprofile_response(print_data)
  2471. # An extrusion_cali_get response echoes the *requested* nozzle
  2472. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2473. # installed hardware. Feeding it to _update_state clobbered the real
  2474. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2475. # which then failed the #1899 dispatch guard. The response carries no
  2476. # status telemetry, so skip it; the true nozzle comes from pushall.
  2477. # (Same reasoning as get_accessories in _handle_system_response.)
  2478. # The answers to K-profile writes and selections echo the diameter
  2479. # the command named in the same way, so none of them is status.
  2480. if print_data.get("command") not in _KPROFILE_COMMAND_ANSWERS:
  2481. self._update_state(print_data)
  2482. def _handle_system_response(self, data: dict):
  2483. """Handle system responses including accessories info.
  2484. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2485. The correct nozzle data comes from push_status, so we don't update
  2486. nozzle type/diameter from get_accessories. We just log the response
  2487. for debugging purposes.
  2488. """
  2489. command = data.get("command")
  2490. if command == "get_accessories":
  2491. # Log response for debugging - but DON'T use it to update nozzle data
  2492. # because it returns stale values (e.g., 'stainless_steel' when the
  2493. # actual nozzle is 'HH01' hardened steel high-flow)
  2494. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2495. def _handle_version_info(self, data: dict):
  2496. """Handle version info response from get_version command.
  2497. Parses firmware version from the 'ota' module in the module list.
  2498. Also extracts AMS unit firmware versions from AMS modules and stores
  2499. them on the corresponding AMS unit in raw_data so the status route can
  2500. expose them to the frontend.
  2501. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2502. - ``ams/<id>`` – original AMS
  2503. - ``ams_f1/<id>`` – AMS Lite (#3348)
  2504. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2505. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2506. Message format:
  2507. {
  2508. "command": "get_version",
  2509. "module": [
  2510. {"name": "ota", "sw_ver": "01.08.05.00"},
  2511. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2512. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2513. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2514. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2515. ...
  2516. ]
  2517. }
  2518. """
  2519. modules = data.get("module", [])
  2520. if not isinstance(modules, list):
  2521. return
  2522. state_changed = False
  2523. for module in modules:
  2524. if not isinstance(module, dict):
  2525. continue
  2526. if module.get("name") == "ota":
  2527. version = module.get("sw_ver")
  2528. if version:
  2529. old_version = self.state.firmware_version
  2530. self.state.firmware_version = version
  2531. if old_version != version:
  2532. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2533. state_changed = True
  2534. break
  2535. # Extract AMS unit firmware versions from AMS modules.
  2536. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2537. # Always cache regardless of whether AMS data has arrived yet — get_version
  2538. # often arrives before the first push_status, so caching must be unconditional.
  2539. ams_raw = self.state.raw_data.get("ams")
  2540. for module in modules:
  2541. if not isinstance(module, dict):
  2542. continue
  2543. name = module.get("name", "")
  2544. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2545. continue
  2546. try:
  2547. # The A2L's AMS Lite is unit 16 here but stored as 6, like
  2548. # everywhere else it is ingested.
  2549. ams_id = normalize_am_unit_id(int(name.split("/", 1)[1]))
  2550. except (ValueError, IndexError):
  2551. continue
  2552. sw_ver = module.get("sw_ver", "")
  2553. sn = module.get("sn", "")
  2554. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2555. module_type = name.split("/", 1)[0]
  2556. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2557. if sw_ver or sn or module_type:
  2558. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2559. state_changed = True
  2560. # Also directly update any AMS unit already present in raw_data
  2561. if ams_raw and isinstance(ams_raw, list):
  2562. for ams_unit in ams_raw:
  2563. if not isinstance(ams_unit, dict):
  2564. continue
  2565. try:
  2566. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2567. except (ValueError, TypeError):
  2568. unit_id = None
  2569. if unit_id == ams_id:
  2570. if sw_ver:
  2571. ams_unit["sw_ver"] = sw_ver
  2572. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2573. # Only set sn from version info if not already present in AMS data
  2574. if sn and not ams_unit.get("sn"):
  2575. ams_unit["sn"] = sn
  2576. if module_type:
  2577. ams_unit["module_type"] = module_type
  2578. break
  2579. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2580. # included in the broadcast (not just the printer firmware version).
  2581. if state_changed and self.on_state_change:
  2582. self.on_state_change(self.state)
  2583. # Warn if any AMS unit is still missing serial number or firmware version
  2584. # after processing the version info response. Warn only once per connection
  2585. # to avoid repeated noise on older firmware that doesn't report these fields.
  2586. if ams_raw and isinstance(ams_raw, list):
  2587. for ams_unit in ams_raw:
  2588. if not isinstance(ams_unit, dict):
  2589. continue
  2590. ams_id = ams_unit.get("id", "?")
  2591. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2592. key = (ams_id, "sn")
  2593. if key not in self._ams_version_warned:
  2594. self._ams_version_warned.add(key)
  2595. logger.warning(
  2596. "[%s] AMS unit %s: serial number not available in version info",
  2597. self.serial_number,
  2598. ams_id,
  2599. )
  2600. if not ams_unit.get("sw_ver"):
  2601. key = (ams_id, "sw_ver")
  2602. if key not in self._ams_version_warned:
  2603. self._ams_version_warned.add(key)
  2604. logger.warning(
  2605. "[%s] AMS unit %s: firmware version not available in version info",
  2606. self.serial_number,
  2607. ams_id,
  2608. )
  2609. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2610. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2611. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2612. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2613. sw_ver/sn fields without overwriting values already present.
  2614. """
  2615. if not ams_list or not isinstance(ams_list, list):
  2616. return
  2617. cache = self._ams_version_cache
  2618. if not cache:
  2619. return
  2620. for unit in ams_list:
  2621. if not isinstance(unit, dict):
  2622. continue
  2623. raw_id = unit.get("id")
  2624. try:
  2625. unit_id = int(raw_id) if raw_id is not None else None
  2626. except (ValueError, TypeError):
  2627. unit_id = None
  2628. if unit_id is None:
  2629. continue
  2630. cached = cache.get(unit_id)
  2631. if not cached:
  2632. continue
  2633. sw_ver = cached.get("sw_ver") or ""
  2634. sn = cached.get("sn") or ""
  2635. if sw_ver and not unit.get("sw_ver"):
  2636. unit["sw_ver"] = sw_ver
  2637. # Only set sn if not already present in AMS data
  2638. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2639. unit["sn"] = sn
  2640. module_type = cached.get("module_type") or ""
  2641. if module_type and not unit.get("module_type"):
  2642. unit["module_type"] = module_type
  2643. def _parse_xcam_data(self, xcam_data):
  2644. """Parse xcam data for camera settings and AI detection options."""
  2645. if not isinstance(xcam_data, dict):
  2646. return
  2647. current_time = time.time()
  2648. # Helper to check if we should accept incoming value for a module
  2649. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2650. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2651. """Check if we should accept an incoming xcam value.
  2652. OrcaSlicer pattern: After sending a command, ignore incoming data
  2653. for 3 seconds. After that, accept whatever the printer sends.
  2654. """
  2655. if module_name not in self._xcam_hold_start:
  2656. return True # No hold timer, accept incoming
  2657. hold_start = self._xcam_hold_start[module_name]
  2658. elapsed = current_time - hold_start
  2659. if elapsed > self._xcam_hold_time:
  2660. # Hold timer expired - accept incoming and clear hold
  2661. del self._xcam_hold_start[module_name]
  2662. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2663. return True
  2664. # Within hold period - ignore incoming data
  2665. logger.debug(
  2666. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2667. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2668. )
  2669. return False
  2670. # Log all xcam fields for debugging
  2671. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2672. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2673. # fields (spaghetti_detector, etc.) are often stale/cached.
  2674. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2675. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2676. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2677. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2678. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2679. # Sensitivity values: 0=low, 1=medium, 2=high
  2680. if "cfg" in xcam_data:
  2681. cfg = xcam_data["cfg"]
  2682. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2683. def decode_detector(start_bit):
  2684. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2685. sens_bits = (cfg >> start_bit) & 0x3
  2686. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2687. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2688. return enabled, sensitivity
  2689. # Spaghetti detector (bits 5-7)
  2690. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2691. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2692. old_value = self.state.print_options.spaghetti_detector
  2693. if cfg_spaghetti != old_value:
  2694. logger.debug(
  2695. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2696. )
  2697. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2698. # Check hold timer for sensitivity before accepting
  2699. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2700. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2701. logger.debug(
  2702. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2703. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2704. )
  2705. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2706. else:
  2707. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2708. elapsed = current_time - hold_start
  2709. if elapsed <= self._xcam_hold_time:
  2710. logger.debug(
  2711. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2712. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2713. )
  2714. else:
  2715. # Hold expired - accept from cfg
  2716. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2717. logger.debug(
  2718. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2719. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2720. )
  2721. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2722. del self._xcam_hold_start["halt_print_sensitivity"]
  2723. # Pileup detector (bits 8-10)
  2724. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2725. if should_accept_value("pileup_detector", cfg_pileup):
  2726. if cfg_pileup != self.state.print_options.pileup_detector:
  2727. logger.debug(
  2728. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2729. )
  2730. self.state.print_options.pileup_detector = cfg_pileup
  2731. # Pileup sensitivity with hold timer
  2732. if "pileup_sensitivity" not in self._xcam_hold_start:
  2733. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2734. logger.debug(
  2735. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2736. )
  2737. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2738. else:
  2739. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2740. elapsed = current_time - hold_start
  2741. if elapsed > self._xcam_hold_time:
  2742. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2743. logger.debug(
  2744. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2745. )
  2746. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2747. del self._xcam_hold_start["pileup_sensitivity"]
  2748. # Clump/nozzle clumping detector (bits 11-13)
  2749. cfg_clump, cfg_clump_sens = decode_detector(11)
  2750. if should_accept_value("clump_detector", cfg_clump):
  2751. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2752. logger.debug(
  2753. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2754. )
  2755. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2756. # Clump sensitivity with hold timer
  2757. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2758. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2759. logger.debug(
  2760. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2761. )
  2762. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2763. else:
  2764. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2765. elapsed = current_time - hold_start
  2766. if elapsed > self._xcam_hold_time:
  2767. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2768. logger.debug(
  2769. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2770. )
  2771. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2772. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2773. # Airprint detector (bits 14-16)
  2774. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2775. if should_accept_value("airprint_detector", cfg_airprint):
  2776. if cfg_airprint != self.state.print_options.airprint_detector:
  2777. logger.debug(
  2778. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2779. )
  2780. self.state.print_options.airprint_detector = cfg_airprint
  2781. # Airprint sensitivity with hold timer
  2782. if "airprint_sensitivity" not in self._xcam_hold_start:
  2783. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2784. logger.debug(
  2785. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2786. )
  2787. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2788. else:
  2789. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2790. elapsed = current_time - hold_start
  2791. if elapsed > self._xcam_hold_time:
  2792. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2793. logger.debug(
  2794. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2795. )
  2796. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2797. del self._xcam_hold_start["airprint_sensitivity"]
  2798. # Camera settings
  2799. if "ipcam_record" in xcam_data:
  2800. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2801. if "timelapse" in xcam_data:
  2802. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2803. # Track if timelapse was ever active during this print
  2804. if self.state.timelapse and self._was_running:
  2805. self._timelapse_during_print = True
  2806. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2807. if "print_halt" in xcam_data:
  2808. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  2809. # Skip halt_print_sensitivity field - it's always stale ("medium")
  2810. # We read the actual sensitivity from cfg bits 5-6 above
  2811. if "first_layer_inspector" in xcam_data:
  2812. new_value = bool(xcam_data.get("first_layer_inspector"))
  2813. if should_accept_value("first_layer_inspector", new_value):
  2814. self.state.print_options.first_layer_inspector = new_value
  2815. if "printing_monitor" in xcam_data:
  2816. new_value = bool(xcam_data.get("printing_monitor"))
  2817. if should_accept_value("printing_monitor", new_value):
  2818. self.state.print_options.printing_monitor = new_value
  2819. if "buildplate_marker_detector" in xcam_data:
  2820. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  2821. if should_accept_value("buildplate_marker_detector", new_value):
  2822. self.state.print_options.buildplate_marker_detector = new_value
  2823. if "allow_skip_parts" in xcam_data:
  2824. new_value = bool(xcam_data.get("allow_skip_parts"))
  2825. if should_accept_value("allow_skip_parts", new_value):
  2826. self.state.print_options.allow_skip_parts = new_value
  2827. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  2828. # individual boolean fields (which are not sent by the printer)
  2829. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  2830. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  2831. if "auto_recovery_step_loss" in xcam_data:
  2832. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  2833. if "filament_tangle_detect" in xcam_data:
  2834. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  2835. @staticmethod
  2836. def _resolve_local_slot_from_mapping(
  2837. local_slot: int, mapping_raw: list | None, units: list[int] | None = None
  2838. ) -> int | None:
  2839. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  2840. The MQTT mapping field is an array of snow-encoded values:
  2841. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  2842. Finds entries where the local slot matches, then computes the global tray ID.
  2843. When several match and ``units`` is given (the AMS units on the active
  2844. extruder of a dual-nozzle printer), only those units' trays count.
  2845. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  2846. """
  2847. if not isinstance(mapping_raw, list) or not mapping_raw:
  2848. return None
  2849. candidates: dict[int, int] = {} # global tray ID -> AMS unit
  2850. for value in mapping_raw:
  2851. if not isinstance(value, int) or value >= 65535:
  2852. continue
  2853. ams_hw_id = value >> 8
  2854. slot = value & 0xFF
  2855. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  2856. candidates[ams_hw_id * 4 + local_slot] = ams_hw_id
  2857. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  2858. candidates[ams_hw_id] = ams_hw_id
  2859. if len(candidates) > 1 and units:
  2860. candidates = {tray: unit for tray, unit in candidates.items() if unit in units}
  2861. if len(candidates) == 1:
  2862. return next(iter(candidates))
  2863. return None
  2864. def _maybe_trigger_external_spool_change(self):
  2865. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  2866. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  2867. an external-spool-only filament swap would otherwise never re-run the
  2868. inventory reconciliation that unlinks a stale ams_id=255 assignment
  2869. (#2575). The reconciliation reads vt_tray from live status itself, so we
  2870. just need to re-fire the callback with the current merged AMS data.
  2871. """
  2872. import hashlib
  2873. vt_tray = self.state.raw_data.get("vt_tray")
  2874. if not isinstance(vt_tray, list):
  2875. return
  2876. # Identity fields only — deliberately exclude `remain` so a print's
  2877. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  2878. fp_parts = [
  2879. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  2880. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  2881. for vt in vt_tray
  2882. if isinstance(vt, dict)
  2883. ]
  2884. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  2885. if vt_hash == self._previous_vt_tray_hash:
  2886. return
  2887. self._previous_vt_tray_hash = vt_hash
  2888. if self.on_ams_change:
  2889. logger.debug(
  2890. "[%s] External spool (vt_tray) changed, triggering sync callback",
  2891. self.serial_number,
  2892. )
  2893. self.on_ams_change(self.state.raw_data.get("ams") or [])
  2894. def _normalize_a2l_am_units(self, ams_list) -> None:
  2895. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  2896. id 16 -> 6 in place, as early as possible, so every downstream reader —
  2897. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  2898. the DB constraint — sees the normalised id and needs no special-casing.
  2899. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  2900. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  2901. both the dict-wrapped and bare-list AMS shapes.
  2902. """
  2903. if not isinstance(ams_list, list):
  2904. return
  2905. for unit in ams_list:
  2906. if not isinstance(unit, dict):
  2907. continue
  2908. try:
  2909. uid = int(unit.get("id"))
  2910. except (TypeError, ValueError):
  2911. continue
  2912. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  2913. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  2914. if not self._has_a2l_am_unit:
  2915. logger.info(
  2916. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  2917. self.serial_number,
  2918. A2L_LITE_NORMALIZED_AMS_ID,
  2919. )
  2920. self._has_a2l_am_unit = True
  2921. def _parse_fila_switch(self, data: dict) -> None:
  2922. """Read the Filament Track Switch block out of a print payload — #1162.
  2923. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  2924. separate from the rest of the state update because ``_handle_ams_data``
  2925. needs the answer before it parses the AMS info bits, and that runs first.
  2926. """
  2927. if not isinstance(data.get("device"), dict):
  2928. return
  2929. fs_data = data["device"].get("fila_switch")
  2930. if not isinstance(fs_data, dict):
  2931. return
  2932. in_raw = fs_data.get("in")
  2933. out_raw = fs_data.get("out")
  2934. self.state.fila_switch = FilaSwitchState(
  2935. installed=True,
  2936. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2937. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2938. stat=int(fs_data.get("stat", 0) or 0),
  2939. info=int(fs_data.get("info", 0) or 0),
  2940. )
  2941. def _parse_extruder_position(self, data: dict) -> bool:
  2942. """Read which nozzle is active and which tray each nozzle holds.
  2943. From ``device.extruder``: ``state`` bit 8 is the active nozzle, each
  2944. ``info`` entry's ``snow`` names its AMS and slot. Run on a frame before
  2945. its AMS block, because an H2D's tray_now is a bare slot that only the
  2946. extruder data of the same frame places. Returns True when the frame
  2947. carried the active nozzle's snow. A malformed value is skipped, never
  2948. raised: this runs ahead of everything else the frame carries.
  2949. """
  2950. device = data.get("device")
  2951. extruder = device.get("extruder") if isinstance(device, dict) else None
  2952. if not isinstance(extruder, dict):
  2953. return False
  2954. try:
  2955. state_val = int(extruder["state"]) if "state" in extruder else None
  2956. except (TypeError, ValueError):
  2957. state_val = None
  2958. if state_val is not None:
  2959. # Extract bit 8 for extruder position
  2960. new_extruder = (state_val >> 8) & 0x1
  2961. if new_extruder != self.state.active_extruder:
  2962. logger.debug(
  2963. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  2964. )
  2965. self.state.active_extruder = new_extruder
  2966. extruder_info = extruder.get("info")
  2967. if not isinstance(extruder_info, list) or len(extruder_info) < 2:
  2968. return False
  2969. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  2970. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  2971. snow_read: set[int] = set()
  2972. for ext_info in extruder_info:
  2973. if not isinstance(ext_info, dict) or "id" not in ext_info or "snow" not in ext_info:
  2974. continue
  2975. try:
  2976. ext_id = int(ext_info["id"])
  2977. snow = int(ext_info["snow"])
  2978. except (TypeError, ValueError):
  2979. continue
  2980. if ext_id <= 1:
  2981. snow_read.add(ext_id)
  2982. # Normalize H2D snow value to global tray ID
  2983. ams_id = snow >> 8
  2984. slot = snow & 0xFF
  2985. if 0 <= ams_id <= 3:
  2986. # Regular AMS slot
  2987. global_tray = ams_id * 4 + (slot & 0x03)
  2988. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2989. if old_val != global_tray:
  2990. logger.debug(
  2991. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2992. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  2993. )
  2994. self.state.h2d_extruder_snow[ext_id] = global_tray
  2995. elif ams_id == 254 or ams_id == 255:
  2996. # External spool or unloaded
  2997. normalized = 254 if slot != 255 else 255
  2998. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2999. if old_val != normalized:
  3000. logger.debug(
  3001. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  3002. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  3003. )
  3004. self.state.h2d_extruder_snow[ext_id] = normalized
  3005. elif 128 <= ams_id <= 135:
  3006. # External spool with hub mapping
  3007. old_val = self.state.h2d_extruder_snow.get(ext_id)
  3008. if old_val != ams_id:
  3009. logger.debug(
  3010. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: raw={snow} -> external hub {ams_id}"
  3011. )
  3012. self.state.h2d_extruder_snow[ext_id] = ams_id
  3013. return self.state.active_extruder in snow_read
  3014. def _parse_extruder_slots(self, data: dict) -> None:
  3015. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  3016. Absent on printers that do not report the block, in which case the
  3017. previous answer is kept rather than cleared: a partial payload carrying
  3018. only temperatures must not look like "both hotends are now empty".
  3019. """
  3020. device = data.get("device")
  3021. if not isinstance(device, dict):
  3022. return
  3023. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  3024. if not isinstance(info, list) or not info:
  3025. return
  3026. slots: dict[int, ExtruderSlot] = {}
  3027. for entry in info:
  3028. if not isinstance(entry, dict) or "id" not in entry:
  3029. continue
  3030. try:
  3031. ext_id = int(entry["id"])
  3032. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  3033. flags = int(entry.get("info", 0) or 0)
  3034. except (TypeError, ValueError):
  3035. continue
  3036. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  3037. ams_id = slot_id = None
  3038. else:
  3039. ams_id = (snow >> 8) & 0xFF
  3040. slot_id = snow & 0xFF
  3041. slots[ext_id] = ExtruderSlot(
  3042. ams_id=ams_id,
  3043. slot_id=slot_id,
  3044. has_filament=bool(flags & 0b10),
  3045. )
  3046. if slots:
  3047. self.state.extruder_slots = slots
  3048. def _handle_ams_data(self, ams_data):
  3049. """Handle AMS data changes for Spoolman integration.
  3050. This is called when we receive top-level AMS data in MQTT messages.
  3051. It detects changes and triggers the callback for Spoolman sync.
  3052. """
  3053. import hashlib
  3054. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  3055. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  3056. ams_list = None
  3057. if isinstance(ams_data, dict):
  3058. if "ams" in ams_data:
  3059. ams_list = ams_data["ams"]
  3060. self._normalize_a2l_am_units(ams_list)
  3061. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  3062. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  3063. if non_list_fields:
  3064. self._debug_on_change(
  3065. "ams_dict_fields",
  3066. non_list_fields,
  3067. "[%s] AMS dict fields: %s",
  3068. self.serial_number,
  3069. non_list_fields,
  3070. )
  3071. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  3072. # when checking if we're in filament change mode for tray_now disambiguation
  3073. if "ams_status" in ams_data:
  3074. raw_ams_status = ams_data["ams_status"]
  3075. if isinstance(raw_ams_status, str):
  3076. try:
  3077. self.state.ams_status = int(raw_ams_status)
  3078. except ValueError:
  3079. self.state.ams_status = 0
  3080. else:
  3081. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  3082. # Compute main and sub status
  3083. self.state.ams_status_sub = self.state.ams_status & 0xFF
  3084. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  3085. self._debug_on_change(
  3086. "ams_status:ams",
  3087. self.state.ams_status,
  3088. "[%s] ams_status: %s (main=%s, sub=%s)",
  3089. self.serial_number,
  3090. self.state.ams_status,
  3091. self.state.ams_status_main,
  3092. self.state.ams_status_sub,
  3093. )
  3094. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  3095. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  3096. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  3097. # next compatible slot (#2587). Stored raw here; globalised at the API
  3098. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  3099. # these are local slot numbers (0-3), not global IDs.
  3100. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  3101. if _tk in ams_data:
  3102. _raw = ams_data[_tk]
  3103. if isinstance(_raw, str):
  3104. try:
  3105. _val = int(_raw)
  3106. except ValueError:
  3107. _val = 255
  3108. else:
  3109. _val = _raw if _raw is not None else 255
  3110. prev = getattr(self.state, _attr)
  3111. setattr(self.state, _attr, _val)
  3112. # Log changes only while paused — the moment the operator cares —
  3113. # so a healthy print's normal tar churn doesn't spam the log.
  3114. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  3115. logger.info(
  3116. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  3117. self.serial_number,
  3118. _tk,
  3119. _val,
  3120. )
  3121. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  3122. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  3123. if "tray_now" in ams_data:
  3124. raw_tray_now = ams_data["tray_now"]
  3125. # Convert string to int if needed
  3126. if isinstance(raw_tray_now, str):
  3127. try:
  3128. parsed_tray_now = int(raw_tray_now)
  3129. except ValueError:
  3130. parsed_tray_now = 255
  3131. else:
  3132. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  3133. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  3134. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  3135. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  3136. # — disambiguated below using MQTT mapping field
  3137. ams_map = self.state.ams_extruder_map
  3138. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3139. # First, check if we have a pending target that matches this slot
  3140. pending_target = self.state.pending_tray_target
  3141. pending_at = self.state.pending_tray_target_at
  3142. if (
  3143. pending_target is not None
  3144. and pending_at is not None
  3145. and time.monotonic() - pending_at > PENDING_TRAY_TARGET_TTL
  3146. ):
  3147. # A load the printer refused or dropped: nothing clears
  3148. # it (tray_now stays 255), and a print loading the same
  3149. # slot number on another AMS long after was shown as
  3150. # this target (FW-C7). Fall through to the snow field.
  3151. self.state.pending_tray_target = None
  3152. self.state.pending_tray_target_at = None
  3153. pending_target = None
  3154. if pending_target is not None:
  3155. # Same slot rule as the snow branch below: an AMS-HT
  3156. # (128-135) has its one tray in slot 0.
  3157. pending_slot = 0 if 128 <= pending_target <= 135 else pending_target % 4
  3158. if pending_slot == parsed_tray_now:
  3159. # Slot matches our pending target - use the full global ID
  3160. logger.debug(
  3161. f"[{self.serial_number}] H2D tray_now disambiguation: "
  3162. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  3163. )
  3164. self.state.tray_now = pending_target
  3165. # Clear pending target now that load is confirmed
  3166. self.state.pending_tray_target = None
  3167. else:
  3168. # Slot doesn't match our pending target - something changed, use slot as-is
  3169. logger.warning(
  3170. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  3171. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  3172. )
  3173. self.state.tray_now = parsed_tray_now
  3174. # Clear pending target since it's stale
  3175. self.state.pending_tray_target = None
  3176. else:
  3177. # No pending target - use h2d_extruder_snow for accurate disambiguation
  3178. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  3179. active_ext = self.state.active_extruder # 0=right, 1=left
  3180. # Best source: use snow value from device.extruder.info if available
  3181. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  3182. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  3183. snow_slot = (
  3184. None
  3185. if snow_tray is None
  3186. else snow_tray % 4
  3187. if snow_tray < 128
  3188. else (0 if snow_tray <= 135 else -1)
  3189. )
  3190. # A snow from an earlier frame may predate a swap: it
  3191. # names the tray only while it agrees with the slot.
  3192. snow_usable = (
  3193. snow_tray is not None
  3194. and snow_tray != 255
  3195. and (snow_slot == parsed_tray_now or self._snow_in_frame)
  3196. )
  3197. if snow_usable and snow_tray is not None:
  3198. # snow_tray is already normalized to global ID
  3199. if snow_slot == parsed_tray_now:
  3200. if self.state.tray_now != snow_tray:
  3201. logger.debug(
  3202. f"[{self.serial_number}] H2D tray_now from snow: "
  3203. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  3204. )
  3205. self.state.tray_now = snow_tray
  3206. else:
  3207. # Slot mismatch in one frame: the extruder's own
  3208. # report is the complete answer, trust snow
  3209. logger.debug(
  3210. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  3211. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  3212. )
  3213. self.state.tray_now = snow_tray
  3214. else:
  3215. # Fallback: snow not available, use ams_extruder_map (less reliable)
  3216. # Find ALL AMS units on the active extruder
  3217. ams_on_extruder = []
  3218. for ams_id_str, ext_id in ams_map.items():
  3219. if ext_id == active_ext:
  3220. try:
  3221. ams_on_extruder.append(int(ams_id_str))
  3222. except ValueError:
  3223. pass # Skip AMS IDs that aren't valid integers
  3224. # Several AMS (or none the map knows of) leave the
  3225. # slot ambiguous. The printer's own mapping names the
  3226. # trays the running print uses: one of them at this
  3227. # slot is the one feeding (#3242). Only while a print
  3228. # runs: an idle H2 keeps reporting the previous
  3229. # print's mapping.
  3230. mapped_tray = None
  3231. if len(ams_on_extruder) != 1 and self._was_running and not self._completion_triggered:
  3232. mapped_tray = self._resolve_local_slot_from_mapping(
  3233. parsed_tray_now, self.state.raw_data.get("mapping"), ams_on_extruder
  3234. )
  3235. if mapped_tray is not None:
  3236. if self.state.tray_now != mapped_tray:
  3237. logger.debug(
  3238. f"[{self.serial_number}] H2D tray_now: AMS {ams_on_extruder} on extruder "
  3239. f"{active_ext}, slot {parsed_tray_now} -> global ID {mapped_tray} (from mapping)"
  3240. )
  3241. self.state.tray_now = mapped_tray
  3242. elif len(ams_on_extruder) == 1:
  3243. # Single AMS on this extruder - unambiguous
  3244. active_ams_id = ams_on_extruder[0]
  3245. if 128 <= active_ams_id <= 135:
  3246. # AMS-HT: single slot per unit, global ID = unit ID
  3247. global_tray_id = active_ams_id
  3248. else:
  3249. global_tray_id = active_ams_id * 4 + parsed_tray_now
  3250. logger.debug(
  3251. f"[{self.serial_number}] H2D tray_now fallback: "
  3252. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  3253. )
  3254. self.state.tray_now = global_tray_id
  3255. elif len(ams_on_extruder) > 1:
  3256. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  3257. current_tray = self.state.tray_now
  3258. # Determine which AMS unit and slot the current tray belongs to
  3259. if 0 <= current_tray <= 15:
  3260. current_ams = current_tray // 4
  3261. current_slot = current_tray % 4
  3262. elif 128 <= current_tray <= 135:
  3263. current_ams = current_tray # AMS-HT: ID = tray ID
  3264. current_slot = 0
  3265. else:
  3266. current_ams = -1
  3267. current_slot = -1
  3268. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  3269. # Current is valid and matches slot - keep it
  3270. logger.debug(
  3271. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3272. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  3273. )
  3274. else:
  3275. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  3276. if parsed_tray_now > 0:
  3277. candidates = [a for a in ams_on_extruder if a <= 3]
  3278. else:
  3279. candidates = ams_on_extruder
  3280. if len(candidates) == 1:
  3281. cand = candidates[0]
  3282. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  3283. logger.debug(
  3284. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3285. f"narrowed to AMS {cand} -> global ID {resolved}"
  3286. )
  3287. self.state.tray_now = resolved
  3288. else:
  3289. # Genuinely ambiguous. This is the second between a
  3290. # filament change reaching the AMS report and the
  3291. # extruder's snow, which then names the tray. Using
  3292. # the bare slot would point at AMS 0 and put that
  3293. # tray in the usage change log (#3242), so keep the
  3294. # current tray until snow arrives.
  3295. logger.debug(
  3296. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on "
  3297. f"extruder {active_ext}, slot {parsed_tray_now} is ambiguous without snow, "
  3298. f"keeping {current_tray}"
  3299. )
  3300. else:
  3301. # No AMS on this extruder that the map knows of: the
  3302. # slot can't be placed, keep the current tray (#3242)
  3303. logger.debug(
  3304. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  3305. f"slot {parsed_tray_now} can't be placed without snow, keeping {self.state.tray_now}"
  3306. )
  3307. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3308. # Single-nozzle printer with tray_now in 0-3 range.
  3309. # #1822: H2S firmware reports tray_now as the AMS's idle
  3310. # slot (typically 0) when the active feed is actually the
  3311. # external spool. X1C / P1S / A1 correctly report 254 in
  3312. # that case; H2S does not. When the slicer-captured
  3313. # ams_mapping is all-external (every entry is 254, or -1
  3314. # when the command carried no ams_mapping2 to resolve it
  3315. # from, #3166), the print can only be feeding from the
  3316. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  3317. # AMS-only mappings are NOT overridden — there's no
  3318. # evidence the firmware misreports in those cases. Prints
  3319. # started without a captured mapping (printer-screen start,
  3320. # or before Bambuddy connected) fall through unchanged.
  3321. captured = self._captured_ams_mapping
  3322. if captured and all(s in (-1, 254, 255) for s in captured):
  3323. if self.state.tray_now != 254:
  3324. logger.debug(
  3325. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  3326. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  3327. )
  3328. self.state.tray_now = 254
  3329. else:
  3330. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  3331. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  3332. # (snow-encoded) to resolve the correct AMS unit.
  3333. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  3334. try:
  3335. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  3336. except (ValueError, TypeError):
  3337. ams_exist = 0
  3338. num_ams = bin(ams_exist).count("1")
  3339. if self._has_a2l_am_unit and num_ams <= 1:
  3340. # A2L AMS-Lite (normalised unit 6): the firmware reports
  3341. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  3342. # otherwise usage tracking keys the wrong spool (it would
  3343. # deduct from AMS 0's slot). Confirmed by capture:
  3344. # tray_now="2" while printing physical slot 3.
  3345. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  3346. elif num_ams > 1:
  3347. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  3348. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  3349. if self._has_a2l_am_unit:
  3350. # A2L Lite + a regular AMS attached together is out of
  3351. # scope: the flat mapping ids are unknown for that combo
  3352. # and could collide with AMS 0. Fall through to the
  3353. # mapping-based resolve, but warn — a capture is needed.
  3354. logger.warning(
  3355. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3356. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3357. self.serial_number,
  3358. )
  3359. mapping_raw = self.state.raw_data.get("mapping")
  3360. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3361. if resolved is not None:
  3362. if resolved != parsed_tray_now:
  3363. logger.debug(
  3364. f"[{self.serial_number}] Multi-AMS tray_now: "
  3365. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3366. )
  3367. self.state.tray_now = resolved
  3368. else:
  3369. # No mapping available (not printing, or ambiguous) — use as-is.
  3370. # This matches the old behavior and is correct for AMS 0.
  3371. self.state.tray_now = parsed_tray_now
  3372. else:
  3373. # Single AMS — local slot 0-3 equals global ID
  3374. self.state.tray_now = parsed_tray_now
  3375. else:
  3376. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3377. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3378. # During filament change, the printer sends 255 first (unload), then the slot.
  3379. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3380. # Trust the printer's reported value.
  3381. self.state.tray_now = parsed_tray_now
  3382. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3383. # Valid physical trays: 0-15 (regular AMS), 24-27 (A2L AMS-Lite,
  3384. # normalised unit 6), 128-135 (AMS-HT), 254 (external spool)
  3385. tn = self.state.tray_now
  3386. if (
  3387. (0 <= tn <= 15)
  3388. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  3389. or (128 <= tn <= 135)
  3390. or tn == 254
  3391. ):
  3392. # Log tray change for mid-print usage splitting. Gate on the
  3393. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3394. # new print, `_completion_triggered` set when on_print_complete
  3395. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3396. # firmware briefly transitions out of RUNNING during AMS
  3397. # auto-fallback (#957), so a literal-string gate misses the
  3398. # switch and the usage tracker double-credits at completion.
  3399. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3400. self.state.tray_change_log.append((tn, self.state.layer_num))
  3401. logger.info(
  3402. "[%s] Tray change during print: tray=%d at layer=%d",
  3403. self.serial_number,
  3404. tn,
  3405. self.state.layer_num,
  3406. )
  3407. if self.on_tray_change:
  3408. self.on_tray_change(tn, self.state.layer_num)
  3409. self.state.last_loaded_tray = self.state.tray_now
  3410. self._debug_on_change(
  3411. "tray_now",
  3412. self.state.tray_now,
  3413. "[%s] tray_now updated: %s",
  3414. self.serial_number,
  3415. self.state.tray_now,
  3416. )
  3417. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3418. # state when checking filament change mode for H2D disambiguation
  3419. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3420. # We've already processed the status fields above, so just return if no ams list
  3421. if ams_list is None:
  3422. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3423. return
  3424. elif isinstance(ams_data, list):
  3425. ams_list = ams_data
  3426. self._normalize_a2l_am_units(ams_list)
  3427. else:
  3428. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3429. return
  3430. # Merge AMS data instead of replacing, to handle partial updates
  3431. # During prints, the printer may only send updates for active AMS units
  3432. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3433. existing_ams = self.state.raw_data.get("ams", [])
  3434. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  3435. # Update existing units with new data, add new units
  3436. for ams_unit in ams_list:
  3437. ams_id = ams_unit.get("id")
  3438. if ams_id is not None:
  3439. existing_unit = existing_by_id.get(ams_id)
  3440. if existing_unit and "tray" in ams_unit:
  3441. # Deep merge trays to preserve fields from previous updates
  3442. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3443. merged_trays = []
  3444. for new_tray in ams_unit.get("tray", []):
  3445. tray_id = new_tray.get("id")
  3446. if tray_id is not None and tray_id in existing_trays:
  3447. # Merge: start with existing, update with new non-empty values
  3448. merged_tray = existing_trays[tray_id].copy()
  3449. # Detect slot-clearing updates (spool removal):
  3450. # When tray_type is explicitly empty, clear everything
  3451. # including RFID data (tag_uid/tray_uuid).
  3452. slot_clearing = new_tray.get("tray_type") == ""
  3453. # Some printers (e.g. H2D) only send {id, state} in
  3454. # incremental updates when a tray is not fully loaded.
  3455. # state=11 means loaded; other values (9=empty,
  3456. # 10=spool present but filament not in feeder) indicate
  3457. # the slot should be cleared. Without this, old
  3458. # tray_type/tray_color persist indefinitely (#784).
  3459. #
  3460. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3461. # tray high-temp dry box, id >= 128) reports its loaded
  3462. # tray as state=9, not 11 — it doesn't feed filament into
  3463. # a shared buffer the way a 4-slot AMS does. Applying the
  3464. # `state != 11 → empty` rule to an HT unit wiped a present
  3465. # spool on every power-on, when the printer sends a partial
  3466. # {id, state=9} for the HT tray (#2594). Skip the state
  3467. # heuristic for HT units — a genuine HT spool removal still
  3468. # clears via the explicit tray_type=="" case above and the
  3469. # tray_exist_bits cleanup below.
  3470. try:
  3471. _is_ht_unit = int(ams_id) >= 128
  3472. except (TypeError, ValueError):
  3473. _is_ht_unit = False
  3474. tray_state = new_tray.get("state")
  3475. if (
  3476. tray_state is not None
  3477. and tray_state != 11
  3478. and not _is_ht_unit
  3479. and "tray_type" not in new_tray
  3480. and merged_tray.get("tray_type")
  3481. ):
  3482. logger.info(
  3483. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3484. self.serial_number,
  3485. ams_id,
  3486. tray_id,
  3487. tray_state,
  3488. )
  3489. slot_clearing = True
  3490. # The incremental update only has {id, state} — inject
  3491. # empty values for all content fields so the merge loop
  3492. # below clears the stale data from merged_tray.
  3493. new_tray.update(
  3494. {
  3495. "tray_type": "",
  3496. "tray_sub_brands": "",
  3497. "tray_color": "",
  3498. "tray_id_name": "",
  3499. "tray_info_idx": "",
  3500. "tag_uid": "0000000000000000",
  3501. "tray_uuid": "00000000000000000000000000000000",
  3502. "remain": 0,
  3503. "k": None,
  3504. "cali_idx": None,
  3505. }
  3506. )
  3507. for key, value in new_tray.items():
  3508. # Fields that should always be updated (even with empty/zero values):
  3509. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3510. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3511. # tray_id_name: slot content indicators that must be cleared
  3512. # when a spool is removed (fixes #147 - old AMS empty slot)
  3513. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3514. # They are only cleared during spool removal (slot_clearing=True).
  3515. # Periodic AMS updates often include empty RFID fields which
  3516. # would overwrite valid data from the initial pushall.
  3517. always_update_fields = (
  3518. "remain",
  3519. "k",
  3520. "id",
  3521. "cali_idx",
  3522. "tray_type",
  3523. "tray_sub_brands",
  3524. "tray_info_idx",
  3525. "tray_color",
  3526. "tray_id_name",
  3527. )
  3528. if (
  3529. key in always_update_fields
  3530. or slot_clearing
  3531. or value
  3532. not in (
  3533. None,
  3534. "",
  3535. "0000000000000000",
  3536. "00000000000000000000000000000000",
  3537. )
  3538. ):
  3539. merged_tray[key] = value
  3540. merged_trays.append(merged_tray)
  3541. else:
  3542. merged_trays.append(new_tray)
  3543. # Update ams_unit with merged trays. Spread existing_unit
  3544. # FIRST so top-level fields the partial update omits —
  3545. # dry_time, info (which drives dry_status / dry_sub_status),
  3546. # humidity, temp — are preserved instead of dropped. The
  3547. # printer sends tray-bearing partials that carry no drying
  3548. # fields; without this, dry_time reads as absent → 0 and the
  3549. # falling-edge detector below fires a false "drying complete"
  3550. # (#1462). Mirrors the no-tray branch's merge semantics.
  3551. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3552. elif existing_unit:
  3553. # Partial update without tray data: merge new fields into existing
  3554. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3555. ams_unit = {**existing_unit, **ams_unit}
  3556. existing_by_id[ams_id] = ams_unit
  3557. # The merge keeps a unit the push doesn't list, so an unplugged AMS used
  3558. # to stay until Bambuddy restarted (#3356). Drop one only on the
  3559. # printer's own word that it is gone.
  3560. if isinstance(ams_data, dict):
  3561. listed = {ams_unit.get("id") for ams_unit in ams_list}
  3562. for ams_id in [i for i in existing_by_id if i not in listed]:
  3563. if unit_reported_absent(ams_id, ams_list, ams_data.get("ams_exist_bits")):
  3564. logger.info("[%s] AMS %s no longer attached, removing it", self.serial_number, ams_id)
  3565. del existing_by_id[ams_id]
  3566. # Convert back to list, sorted by ID for consistent ordering
  3567. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  3568. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3569. # Shared with the VP bridge cache so the slicer-facing view stays in
  3570. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3571. # for the full rationale and the printer-shutdown guard.
  3572. if isinstance(ams_data, dict):
  3573. apply_tray_exist_bits(
  3574. merged_ams,
  3575. ams_data.get("tray_exist_bits"),
  3576. power_on_flag=ams_data.get("power_on_flag", True),
  3577. log_label=self.serial_number,
  3578. annotate_exists=True,
  3579. )
  3580. self.state.raw_data["ams"] = merged_ams
  3581. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3582. self._apply_ams_version_cache(merged_ams)
  3583. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3584. self.state.last_ams_update = time.time()
  3585. self._debug_on_change(
  3586. "merged_ams",
  3587. (len(ams_list), len(merged_ams)),
  3588. "[%s] Merged AMS data: %s new units, %s total",
  3589. self.serial_number,
  3590. len(ams_list),
  3591. len(merged_ams),
  3592. )
  3593. # Extract ams_extruder_map from each AMS unit's info field
  3594. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3595. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3596. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3597. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3598. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3599. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3600. #
  3601. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3602. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3603. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3604. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3605. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3606. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3607. # the switch being installed.
  3608. #
  3609. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3610. # the full map. Merge into existing map to preserve entries from prior updates.
  3611. fts_installed = self.state.fila_switch.installed
  3612. inlet_moves: list[tuple[int, str]] = []
  3613. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3614. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3615. for ams_unit in merged_ams:
  3616. ams_id = ams_unit.get("id")
  3617. info = ams_unit.get("info")
  3618. if ams_id is not None and info is not None:
  3619. try:
  3620. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3621. info_val = int(str(info), 16)
  3622. # Extract 4 bits starting at bit 8 for extruder assignment
  3623. extruder_id = (info_val >> 8) & 0xF
  3624. if extruder_id == 0xE:
  3625. if fts_installed:
  3626. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3627. if inlet is not None:
  3628. previous = ams_switch_inlet.get(str(ams_id))
  3629. ams_switch_inlet[str(ams_id)] = inlet
  3630. self._debug_on_change(
  3631. f"ams_inlet:{ams_id}",
  3632. inlet,
  3633. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3634. self.serial_number,
  3635. ams_id,
  3636. info,
  3637. inlet,
  3638. )
  3639. if previous is not None and previous != inlet:
  3640. # Only a genuine move, never the first sighting:
  3641. # re-applying K-profiles on every reconnect would
  3642. # fight a binding the operator set deliberately.
  3643. logger.info(
  3644. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3645. self.serial_number,
  3646. ams_id,
  3647. inlet,
  3648. previous,
  3649. )
  3650. inlet_moves.append((int(ams_id), inlet))
  3651. continue
  3652. ams_extruder_map[str(ams_id)] = extruder_id
  3653. self._debug_on_change(
  3654. f"ams_info:{ams_id}",
  3655. (info, extruder_id),
  3656. "[%s] AMS %s info=0x%s -> extruder %s",
  3657. self.serial_number,
  3658. ams_id,
  3659. info,
  3660. extruder_id,
  3661. )
  3662. except (ValueError, TypeError):
  3663. pass # Skip AMS units with unparseable info bitmask values
  3664. if ams_extruder_map:
  3665. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3666. self.state.ams_extruder_map = ams_extruder_map
  3667. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3668. if ams_switch_inlet:
  3669. self.state.ams_switch_inlet = ams_switch_inlet
  3670. for moved_ams_id, moved_inlet in inlet_moves:
  3671. if self.on_fts_inlet_change:
  3672. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3673. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3674. # BambuStudio DevFilaSystem.cpp parses info bits:
  3675. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3676. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3677. for ams_unit in merged_ams:
  3678. info = ams_unit.get("info")
  3679. if info is not None:
  3680. try:
  3681. info_val = int(str(info), 16)
  3682. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3683. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3684. except (ValueError, TypeError):
  3685. pass # Skip unparseable info values
  3686. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3687. if "dry_sf_reason" in ams_unit:
  3688. sf_reason = ams_unit["dry_sf_reason"]
  3689. if isinstance(sf_reason, list):
  3690. ams_unit["dry_sf_reason"] = [
  3691. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3692. ]
  3693. else:
  3694. ams_unit["dry_sf_reason"] = []
  3695. # Persist updated drying fields back to raw_data
  3696. self.state.raw_data["ams"] = merged_ams
  3697. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3698. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3699. # — fire the callback so smart-plug auto-off-after-drying can run,
  3700. # and drop our cached target-cycle params so the badge stops claiming
  3701. # an active cycle. Works identically for queue-triggered, ambient,
  3702. # and manual drying because we observe the firmware-reported state.
  3703. for ams_unit in merged_ams:
  3704. try:
  3705. ams_id = int(ams_unit.get("id", -1))
  3706. except (TypeError, ValueError):
  3707. continue
  3708. if ams_id < 0:
  3709. continue
  3710. # The firmware phase outranks the stalled-countdown heuristic even
  3711. # on a transient-zero frame, which the completion guard below skips.
  3712. # Clear a previously raised flag before that early continue.
  3713. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3714. ams_unit["dry_countdown_stalled"] = False
  3715. # Only evaluate the edge when this update carries an explicit
  3716. # dry_time. An absent / unparseable value is NOT zero — treating
  3717. # it as 0 lets a tray-only partial fake a drying-complete edge
  3718. # (#1462). Skip without touching the remembered value so the
  3719. # next update that DOES carry dry_time sees the true previous.
  3720. raw_dry_time = ams_unit.get("dry_time")
  3721. if raw_dry_time is None:
  3722. continue
  3723. try:
  3724. current = int(raw_dry_time)
  3725. except (TypeError, ValueError):
  3726. continue
  3727. # A dry_time of 0 only means "finished" when the unit also reports
  3728. # an idle phase. Between the command ack and the countdown settling
  3729. # the firmware publishes a transient 0 while the AMS is still
  3730. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3731. # 12-hour cycle. Taking that at face value dropped the cached target
  3732. # (leaving the badge to guess the filament from tray 1, so a PLA
  3733. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3734. # schedules smart-plug auto-off. dry_status comes from the same info
  3735. # hex parsed above; when it is absent we let the edge through, so a
  3736. # firmware that never reports one still ends its cycles.
  3737. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3738. # Leave the remembered value alone, exactly as the absent-
  3739. # dry_time skip above does: whichever push ends the cycle for
  3740. # real must still see a non-zero previous.
  3741. logger.debug(
  3742. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3743. self.serial_number,
  3744. ams_id,
  3745. ams_unit.get("dry_status"),
  3746. )
  3747. continue
  3748. seen_before = ams_id in self._previous_dry_times
  3749. previous = self._previous_dry_times.get(ams_id, 0)
  3750. self._previous_dry_times[ams_id] = current
  3751. if current > 0:
  3752. cycle = self._dry_cycles.get(ams_id)
  3753. if cycle is None or previous == 0:
  3754. cycle = {
  3755. "peak": current,
  3756. # A rise from an observed 0 is the cycle's first minute.
  3757. # A first sighting already counting down is not.
  3758. "start_seen": seen_before,
  3759. "target": self._drying_targets.get(ams_id),
  3760. }
  3761. self._dry_cycles[ams_id] = cycle
  3762. elif current > int(cycle["peak"]):
  3763. cycle["peak"] = current
  3764. # Stall detection: stamp value CHANGES only — a live countdown
  3765. # decrements once a minute, so repeats of the same value within
  3766. # the minute must not refresh the stamp, and a frame without a
  3767. # dry_time never reaches here (the absent-value skip above).
  3768. now_mono = time.monotonic()
  3769. if current != previous or ams_id not in self._dry_time_changed_at:
  3770. self._dry_time_changed_at[ams_id] = now_mono
  3771. ams_unit["dry_countdown_stalled"] = bool(
  3772. current > 0
  3773. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  3774. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  3775. )
  3776. if previous > 0 and current == 0:
  3777. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  3778. if self.on_drying_complete:
  3779. self.on_drying_complete(ams_id)
  3780. cycle = self._dry_cycles.pop(ams_id, None) or {"peak": previous, "start_seen": False, "target": None}
  3781. if self.on_drying_cycle_end:
  3782. self.on_drying_cycle_end(self._drying_cycle_end(ams_id, previous, cycle))
  3783. # Create a hash of relevant AMS data to detect changes.
  3784. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  3785. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  3786. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  3787. # above but leaves the raw payload's tracked fields untouched — so a
  3788. # raw-based hash never flips and on_ams_change never fires, leaving the
  3789. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  3790. # always spans every unit, so a partial single-unit update can't produce a
  3791. # spuriously different hash from a full pushall.
  3792. ams_hash_data = []
  3793. for ams_unit in merged_ams:
  3794. for tray in ams_unit.get("tray", []):
  3795. # Include fields that matter for filament tracking
  3796. ams_hash_data.append(
  3797. f"{ams_unit.get('id')}:{tray.get('id')}:"
  3798. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  3799. )
  3800. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  3801. # Only trigger callback if AMS data actually changed
  3802. if ams_hash != self._previous_ams_hash:
  3803. self._previous_ams_hash = ams_hash
  3804. if self.on_ams_change:
  3805. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  3806. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  3807. # may lack fields like 'remain' that the merged state preserves
  3808. self.on_ams_change(merged_ams)
  3809. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  3810. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  3811. # or cali_idx — so an assignment that only swaps the filament id on an
  3812. # already-loaded slot would not flip the hash, and gating the check on
  3813. # it would miss exactly the confirmation we are after.
  3814. if self._pending_assignments:
  3815. self._check_assignment_verifications()
  3816. @staticmethod
  3817. def _drying_cycle_end(ams_id: int, remaining: int, cycle: dict[str, object]) -> DryingCycleEnd:
  3818. """Build the cycle-end report from the record kept while it ran."""
  3819. target = cycle.get("target")
  3820. target_temp: int | None = None
  3821. target_hours: int | None = None
  3822. if isinstance(target, dict):
  3823. try:
  3824. target_temp = int(target.get("temp") or 0) or None
  3825. target_hours = int(target.get("duration_hours") or 0) or None
  3826. except (TypeError, ValueError):
  3827. target_temp = target_hours = None
  3828. return DryingCycleEnd(
  3829. ams_id=ams_id,
  3830. remaining_minutes=remaining,
  3831. peak_minutes=max(int(cycle.get("peak") or 0), remaining),
  3832. start_seen=bool(cycle.get("start_seen")),
  3833. target_temp=target_temp,
  3834. target_hours=target_hours,
  3835. )
  3836. def _log_drying_cycle_end(
  3837. self,
  3838. ams_id: int,
  3839. remaining: int,
  3840. ams_unit: dict,
  3841. target: dict[str, object] | None,
  3842. ) -> None:
  3843. """Report a finished drying cycle, with the firmware's reason when it was
  3844. cut short (#2770).
  3845. A cycle that reaches its configured duration needs no explanation and
  3846. keeps the one-line "drying complete" it has always had. One that ends
  3847. with most of its countdown left was ended by somebody, and there are
  3848. only two candidates: a stop Bambuddy sent — the print-takes-priority
  3849. stop, or the user's Stop button — which is named as such, or the
  3850. firmware.
  3851. For the firmware case the only account of why lives in fields we already
  3852. parse but have never written down: the ``dry_status`` /
  3853. ``dry_sub_status`` phase from the info hex, the per-unit
  3854. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  3855. that moment. Logging them at INFO puts them in every support bundle by
  3856. default, which is what a report like #2770 needs before its cause can be
  3857. argued about at all.
  3858. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  3859. logged for every cycle, early or not, because they are what decides
  3860. whether auto-drying re-arms. Reconstructing them for #2770 meant
  3861. cross-referencing hourly alarm lines against 30-second scheduler debug
  3862. that was switched off at the time; one line here says it outright — a
  3863. cycle ending at 63 degC with the reading still above the threshold is
  3864. the whole shape of the re-arm loop.
  3865. """
  3866. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  3867. if ams_id in self._drying_stops_sent:
  3868. self._drying_stops_sent.discard(ams_id)
  3869. logger.info(
  3870. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  3871. self.serial_number,
  3872. ams_id,
  3873. remaining,
  3874. box,
  3875. )
  3876. return
  3877. if remaining <= _EARLY_DRY_END_MINUTES:
  3878. logger.info(
  3879. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  3880. self.serial_number,
  3881. ams_id,
  3882. remaining,
  3883. box,
  3884. )
  3885. return
  3886. requested_minutes: int | None = None
  3887. if target is not None:
  3888. try:
  3889. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  3890. except (TypeError, ValueError):
  3891. requested_minutes = None
  3892. logger.info(
  3893. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  3894. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  3895. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  3896. self.serial_number,
  3897. ams_id,
  3898. remaining,
  3899. requested_minutes if requested_minutes is not None else "?",
  3900. ams_unit.get("dry_status"),
  3901. ams_unit.get("dry_sub_status"),
  3902. ams_unit.get("dry_sf_reason") or [],
  3903. [e.full_code for e in self.state.hms_errors] or "none",
  3904. box,
  3905. )
  3906. def register_assignment_verification(
  3907. self,
  3908. ams_id: int,
  3909. tray_id: int,
  3910. tray_info_idx: str,
  3911. tray_color: str,
  3912. cali_idx: int | None,
  3913. ) -> None:
  3914. """Record an assignment we just pushed so subsequent AMS telemetry can
  3915. confirm the tray actually accepted it (#2582).
  3916. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  3917. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  3918. accepted filament id back in the per-tray push, so a match means the
  3919. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  3920. signal so we can specifically flag "filament loaded but K-profile not
  3921. applied", which is the exact symptom the reporter chased via flow-cal.
  3922. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  3923. there is nothing to verify and no record is stored.
  3924. """
  3925. want_idx = (tray_info_idx or "").strip().upper()
  3926. if not want_idx:
  3927. return
  3928. self._pending_assignments[(ams_id, tray_id)] = {
  3929. "tray_info_idx": want_idx,
  3930. "tray_color": (tray_color or "").strip().upper(),
  3931. "cali_idx": cali_idx,
  3932. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  3933. "last_seen_idx": None,
  3934. }
  3935. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  3936. """Locate the live tray dict for a pending verification.
  3937. External spools (ams_id 255) live in ``vt_tray`` under global ids
  3938. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  3939. report a single tray whose id may not equal the logical tray_id, so fall
  3940. back to the sole tray when an id match fails.
  3941. """
  3942. raw = self.state.raw_data or {}
  3943. if ams_id == 255:
  3944. want_ext = 254 + tray_id
  3945. for vt in raw.get("vt_tray", []) or []:
  3946. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  3947. return vt
  3948. return None
  3949. for unit in raw.get("ams", []) or []:
  3950. if str(unit.get("id")) != str(ams_id):
  3951. continue
  3952. trays = unit.get("tray", []) or []
  3953. for tray in trays:
  3954. if str(tray.get("id")) == str(tray_id):
  3955. return tray
  3956. if ams_id >= 128 and len(trays) == 1:
  3957. return trays[0]
  3958. return None
  3959. return None
  3960. def _check_assignment_verifications(self) -> None:
  3961. """Compare each pending assignment against live tray telemetry and fire
  3962. ``on_assignment_verified`` on a match or once the deadline passes.
  3963. Runs on every AMS push. Non-matching-but-still-within-window entries are
  3964. left in place for the next push. The timeout branch only fires when a
  3965. later push arrives after the deadline; if the printer goes silent we
  3966. simply never confirm, which is preferable to inventing a failure.
  3967. """
  3968. now = time.monotonic()
  3969. for key, want in list(self._pending_assignments.items()):
  3970. ams_id, tray_id = key
  3971. tray = self._find_verify_tray(ams_id, tray_id)
  3972. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  3973. if tray is not None and actual_idx:
  3974. want["last_seen_idx"] = actual_idx
  3975. if actual_idx and actual_idx == want["tray_info_idx"]:
  3976. self._pending_assignments.pop(key, None)
  3977. kprofile_applied = True
  3978. want_cali = want.get("cali_idx")
  3979. if want_cali is not None and want_cali >= 0:
  3980. actual_cali = tray.get("cali_idx")
  3981. kprofile_applied = actual_cali == want_cali
  3982. self._fire_assignment_verified(
  3983. ams_id,
  3984. tray_id,
  3985. True,
  3986. {
  3987. "tray_info_idx": actual_idx,
  3988. "kprofile_applied": kprofile_applied,
  3989. },
  3990. )
  3991. elif now >= want["deadline"]:
  3992. self._pending_assignments.pop(key, None)
  3993. self._fire_assignment_verified(
  3994. ams_id,
  3995. tray_id,
  3996. False,
  3997. {
  3998. "expected_tray_info_idx": want["tray_info_idx"],
  3999. "actual_tray_info_idx": want.get("last_seen_idx"),
  4000. # True when we saw the tray at least once (so the push
  4001. # channel is alive and the printer really stored a
  4002. # different/blank id) vs never observing it at all.
  4003. "saw_tray": want.get("last_seen_idx") is not None,
  4004. },
  4005. )
  4006. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  4007. if verified:
  4008. logger.info(
  4009. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  4010. self.serial_number,
  4011. ams_id,
  4012. tray_id,
  4013. detail.get("tray_info_idx"),
  4014. detail.get("kprofile_applied"),
  4015. )
  4016. else:
  4017. logger.warning(
  4018. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  4019. self.serial_number,
  4020. ams_id,
  4021. tray_id,
  4022. detail.get("expected_tray_info_idx"),
  4023. detail.get("actual_tray_info_idx"),
  4024. detail.get("saw_tray"),
  4025. )
  4026. if self.on_assignment_verified:
  4027. try:
  4028. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  4029. except Exception:
  4030. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  4031. @staticmethod
  4032. def _probe_number(value, fallback: float | None = None) -> float | None:
  4033. """Coerce a telemetry field to a number, or return `fallback`.
  4034. Firmware is inconsistent about whether these arrive as ints or as
  4035. numeric strings, and the probe must never raise on a surprise type.
  4036. """
  4037. try:
  4038. return float(value)
  4039. except (TypeError, ValueError):
  4040. return fallback
  4041. def _probe_end_of_print(self, data: dict) -> None:
  4042. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  4043. Opens on the first frame that looks like end-of-print (last object
  4044. layer reached, progress at 99+, or no remaining time), then logs each
  4045. frame in which any probed field changed, and closes on the transition
  4046. out of RUNNING. Armed once per print — see the module-level comment on
  4047. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  4048. currently see into.
  4049. Read-only with respect to printer state: this is instrumentation, and
  4050. nothing downstream may come to depend on it.
  4051. """
  4052. if not logger.isEnabledFor(logging.DEBUG):
  4053. return
  4054. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  4055. return
  4056. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  4057. if not present:
  4058. return
  4059. if not self._eop_probe_open:
  4060. # Open on any end-of-print signal. Read from the raw frame first so
  4061. # the frame that *carries* the signal is itself captured — state
  4062. # fields are only updated further down this same call.
  4063. frame_layer = data.get("layer_num")
  4064. if self._is_stale_layer(frame_layer):
  4065. frame_layer = None
  4066. layer = self._probe_number(frame_layer, self.state.layer_num) or 0
  4067. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  4068. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  4069. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  4070. at_last_layer = total > 0 and layer >= total
  4071. # `remaining <= 0` is only meaningful once the print has actually
  4072. # progressed — it reads 0 during the pre-print calibration too.
  4073. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  4074. if not (at_last_layer or percent >= 99 or out_of_time):
  4075. return
  4076. self._eop_probe_open = True
  4077. self._eop_probe_frames = 0
  4078. self._eop_probe_last = {}
  4079. logger.debug(
  4080. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  4081. self.serial_number,
  4082. layer,
  4083. total,
  4084. percent,
  4085. remaining,
  4086. )
  4087. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  4088. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  4089. self._eop_probe_last.update(present)
  4090. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  4091. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  4092. self._eop_probe_frames += 1
  4093. logger.debug(
  4094. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  4095. self.serial_number,
  4096. _END_OF_PRINT_PROBE_MAX_FRAMES,
  4097. )
  4098. return
  4099. if changed or closing:
  4100. self._eop_probe_frames += 1
  4101. logger.debug(
  4102. "[%s] EOP-PROBE %s%s: %s",
  4103. self.serial_number,
  4104. self._eop_probe_frames,
  4105. " CLOSE" if closing else "",
  4106. # `changed` on a closing frame can be empty; fall back to the
  4107. # full picture so the last line is always self-contained.
  4108. changed if changed else present,
  4109. )
  4110. if closing:
  4111. self._eop_probe_open = False
  4112. self._eop_probe_armed = False
  4113. self._eop_probe_last = {}
  4114. @property
  4115. def layer_before_new_print(self) -> int:
  4116. """The layer the printer was on when a print start was detected, until
  4117. it reports another (#3317); 0 when none.
  4118. For a print that is resumed rather than new, which a restart while it
  4119. was paused makes look new, that is the layer it is still on (#2984).
  4120. """
  4121. return self._stale_layer_num
  4122. def _is_stale_layer(self, value) -> bool:
  4123. """Whether a frame's `layer_num` is the previous print's last layer (#3317)."""
  4124. if not self._stale_layer_num:
  4125. return False
  4126. try:
  4127. return int(value) == self._stale_layer_num
  4128. except (TypeError, ValueError):
  4129. return False
  4130. def _update_state(self, data: dict):
  4131. """Update printer state from message data."""
  4132. _previous_state = self.state.state
  4133. # #2547: instrumentation only — runs before any state mutation so the
  4134. # frame carrying an end-of-print signal is logged as it arrived.
  4135. try:
  4136. self._probe_end_of_print(data)
  4137. except Exception: # pragma: no cover - a probe must never break ingest
  4138. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  4139. # Update state fields
  4140. if "gcode_state" in data:
  4141. self.state.state = data["gcode_state"]
  4142. if "gcode_file" in data:
  4143. self.state.gcode_file = data["gcode_file"]
  4144. self.state.current_print = data["gcode_file"]
  4145. # The answer to a print start the printer refused names the job it
  4146. # refused, not one it runs: read as status, its job id told the start
  4147. # watchdog the file had landed.
  4148. refused_start = (
  4149. data.get("command") == "project_file"
  4150. and data.get("result") is not None
  4151. and str(data["result"]).upper() != "SUCCESS"
  4152. )
  4153. if "subtask_name" in data and not refused_start:
  4154. self.state.subtask_name = data["subtask_name"]
  4155. # Prefer subtask_name as current_print if available
  4156. if data["subtask_name"]:
  4157. self.state.current_print = data["subtask_name"]
  4158. if "subtask_id" in data and not refused_start:
  4159. self.state.subtask_id = data["subtask_id"]
  4160. if "mc_percent" in data:
  4161. # Billing: retain this frame's latest positive value immediately.
  4162. # A display-side abort may be the very next frame (and may omit
  4163. # mc_percent entirely), so retaining only the previous frame can
  4164. # lose the only usable estimate for proportional charging.
  4165. previous_progress = self.state.progress
  4166. new_progress = float(data["mc_percent"])
  4167. if new_progress > 0:
  4168. self._last_valid_progress = new_progress
  4169. self.state.progress = new_progress
  4170. # #2547: strictly-increasing only. The firmware resets progress to 0
  4171. # on cancel and re-reports the same percent on most frames; neither
  4172. # is the print advancing, and both would make the frame bank grab a
  4173. # camera frame for nothing.
  4174. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  4175. self.on_print_progress(int(self.state.progress))
  4176. if "mc_remaining_time" in data:
  4177. self.state.remaining_time = int(data["mc_remaining_time"])
  4178. if "mc_print_sub_stage" in data:
  4179. new_sub_stage = int(data["mc_print_sub_stage"])
  4180. if new_sub_stage != self.state.mc_print_sub_stage:
  4181. logger.debug(
  4182. f"[{self.serial_number}] mc_print_sub_stage changed: "
  4183. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  4184. )
  4185. self.state.mc_print_sub_stage = new_sub_stage
  4186. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  4187. # front because three places below consult it and they run in an order
  4188. # that is not the order they read most naturally in: the layer-advance
  4189. # refresh (#2702) must not fire on a frame that already answers it, the
  4190. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  4191. # reset must not discard a total that belongs to the starting print.
  4192. total_from_this_frame = 0
  4193. if "total_layer_num" in data:
  4194. try:
  4195. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  4196. except (TypeError, ValueError):
  4197. # Must not escape. `_on_message` catches only JSONDecodeError
  4198. # and paho is left at `suppress_exceptions = False`, so an
  4199. # exception raised here is re-raised on the network thread and
  4200. # takes the printer connection down over one unusable field.
  4201. # Treat it as "not reported": the refresh below then recovers
  4202. # the real total from a pushall.
  4203. logger.debug(
  4204. "[%s] ignoring unusable total_layer_num: %r",
  4205. self.serial_number,
  4206. data["total_layer_num"],
  4207. )
  4208. if "layer_num" in data:
  4209. try:
  4210. new_layer = int(data["layer_num"])
  4211. except (TypeError, ValueError):
  4212. # Contained for the same reason as `total_layer_num` above: an
  4213. # exception raised here escapes `_update_state` and paho
  4214. # re-raises it on the network thread. Losing this frame would
  4215. # also lose the print-start and completion detection further
  4216. # down, which is worse than losing a layer number.
  4217. #
  4218. # Held at the last known layer rather than substituted with 0:
  4219. # a fabricated 0 reads as the firmware's cancel reset, which
  4220. # would move `_last_valid_layer_num` and show layer 0 in the UI
  4221. # until the next good frame.
  4222. logger.debug(
  4223. "[%s] ignoring unusable layer_num: %r",
  4224. self.serial_number,
  4225. data["layer_num"],
  4226. )
  4227. new_layer = self.state.layer_num
  4228. if self._is_stale_layer(new_layer):
  4229. logger.debug(
  4230. "[%s] ignoring layer_num %s: last layer of the previous print",
  4231. self.serial_number,
  4232. new_layer,
  4233. )
  4234. new_layer = self.state.layer_num
  4235. elif new_layer > 0:
  4236. # The new print reports a layer of its own; from here on the
  4237. # previous print's value is a layer this print can reach.
  4238. self._stale_layer_num = 0
  4239. old_layer = self.state.layer_num
  4240. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  4241. if old_layer > 0:
  4242. self._last_valid_layer_num = old_layer
  4243. self.state.layer_num = new_layer
  4244. # Trigger layer change callback if layer increased
  4245. if new_layer > old_layer and self.on_layer_change:
  4246. self.on_layer_change(new_layer)
  4247. # #2702: the print is demonstrably laying down layers but we still
  4248. # have no denominator, so the pushall requested at print start
  4249. # either went unanswered or raced the printer learning the total.
  4250. # Ask once more — by layer 1 the printer definitely knows it.
  4251. # One-shot: an unanswered pushall must not turn into a per-layer
  4252. # retry loop for the rest of the print.
  4253. if (
  4254. new_layer > old_layer
  4255. and self._total_layers_refresh_armed
  4256. and not self.state.total_layers
  4257. and not total_from_this_frame
  4258. ):
  4259. self._total_layers_refresh_armed = False
  4260. logger.debug(
  4261. "[%s] layer %s with no total_layer_num — re-requesting full status",
  4262. self.serial_number,
  4263. new_layer,
  4264. )
  4265. self._request_push_all()
  4266. # #2547: there is deliberately NO finish-photo trigger on the
  4267. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  4268. # moment the printer *starts* the final layer, not the moment it
  4269. # finishes it — on the H2C capture that closed #2547 the edge
  4270. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  4271. # filament change before the print actually ended, so the photo
  4272. # showed the toolhead mid-print over the part. Worse, the trigger
  4273. # latched `_finish_photo_captured`, locking out both the stage-22
  4274. # and FINISH triggers below for the rest of the print.
  4275. #
  4276. # #1867 (End G-code ejects the plate before FINISH) is handled
  4277. # where it belongs instead: `on_finish_photo_moment` prefers the
  4278. # in-print frame bank when the dispatcher recorded that it injected
  4279. # End G-code into this print. See services/print_dispatch_context.
  4280. if total_from_this_frame:
  4281. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  4282. # end — same shape as the `layer_num` reset guarded above. Applying
  4283. # only positive values preserves the last known good denominator so
  4284. # the usage-tracker split path (#1771) survives the reset frame.
  4285. self.state.total_layers = total_from_this_frame
  4286. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  4287. # Convert to 0-100 percentage for display
  4288. def parse_fan_speed(value: str | int | None) -> int | None:
  4289. if value is None:
  4290. return None
  4291. try:
  4292. speed = int(value)
  4293. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  4294. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  4295. if speed <= 15:
  4296. return round(speed * 100 / 15)
  4297. # If already a percentage (0-255 scale from some printers), convert
  4298. elif speed <= 255:
  4299. return round(speed * 100 / 255)
  4300. return speed
  4301. except (ValueError, TypeError):
  4302. return None
  4303. # Log fan fields once for debugging
  4304. if not hasattr(self, "_fan_fields_logged"):
  4305. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  4306. if fan_fields:
  4307. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  4308. self._fan_fields_logged = True
  4309. if "cooling_fan_speed" in data:
  4310. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  4311. if "big_fan1_speed" in data:
  4312. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  4313. if "big_fan2_speed" in data:
  4314. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  4315. if "heatbreak_fan_speed" in data:
  4316. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  4317. # Calibration stage tracking
  4318. if "stg_cur" in data:
  4319. new_stg = data["stg_cur"]
  4320. prev_stg = self.state.stg_cur
  4321. # Always log ANY stg_cur change for debugging filament operations
  4322. if new_stg != prev_stg:
  4323. logger.debug(
  4324. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  4325. )
  4326. # A stage we cannot name is the one worth seeing at the default
  4327. # log level: the DEBUG line above is off in normal running, so
  4328. # an unnamed stage otherwise reaches the user as "Unknown stage
  4329. # (72)" on a card with nothing behind it to say when it
  4330. # happened or what the printer was doing. Recorded once per
  4331. # stage number per session, with the stage it came from and the
  4332. # print state, which is what naming it later needs. Guarded on
  4333. # the int type because the field is whatever the firmware sent.
  4334. if (
  4335. isinstance(new_stg, int)
  4336. and not isinstance(new_stg, bool)
  4337. # -1 is Bambuddy's own "not in a stage" sentinel and the
  4338. # initial value of the field, not something the firmware
  4339. # reports; every print would otherwise report it on the way
  4340. # out of its last real stage.
  4341. and new_stg != -1
  4342. and new_stg not in STAGE_NAMES
  4343. and new_stg not in self._unnamed_stages_seen
  4344. ):
  4345. self._unnamed_stages_seen.add(new_stg)
  4346. logger.info(
  4347. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  4348. "state=%s progress=%s%% layer=%s/%s",
  4349. self.serial_number,
  4350. new_stg,
  4351. self.model,
  4352. prev_stg,
  4353. get_stage_name(prev_stg),
  4354. self.state.state,
  4355. self.state.progress,
  4356. self.state.layer_num,
  4357. self.state.total_layers,
  4358. )
  4359. self.state.stg_cur = new_stg
  4360. # #1721 end-of-print finish photo trigger.
  4361. # Stage 22 = "Filament unloading" fires at end-of-print AND
  4362. # during mid-print color swaps. The end-of-print gate
  4363. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  4364. # — those signals only line up at the real end. Edge-only
  4365. # (prev != 22) so the trigger fires once per stage entry.
  4366. if (
  4367. new_stg == 22
  4368. and prev_stg != 22
  4369. and self._was_running
  4370. and not self._finish_photo_captured
  4371. and self.on_finish_photo_moment
  4372. ):
  4373. progress = self.state.progress or 0.0
  4374. layer_num = self.state.layer_num or 0
  4375. total_layers = self.state.total_layers or 0
  4376. remaining = self.state.remaining_time or 0
  4377. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  4378. if is_end_of_print:
  4379. self._finish_photo_captured = True
  4380. logger.info(
  4381. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  4382. f"progress={progress}, layer={layer_num}/{total_layers}, "
  4383. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  4384. )
  4385. self.on_finish_photo_moment(
  4386. {
  4387. "trigger": "stage_22",
  4388. "filename": self._previous_gcode_file or self.state.gcode_file,
  4389. "subtask_name": self.state.subtask_name,
  4390. "timelapse_was_active": self._timelapse_during_print,
  4391. }
  4392. )
  4393. if "stg" in data:
  4394. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  4395. # Temperature data
  4396. temps = {}
  4397. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  4398. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  4399. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  4400. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  4401. # Log ALL keys in print data for H2D temperature discovery
  4402. all_keys = sorted(data.keys())
  4403. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  4404. self._temp_fields_logged = True
  4405. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  4406. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  4407. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  4408. self._vir_slot_logged = True
  4409. # Log nozzle hardware info fields (once)
  4410. nozzle_fields = {
  4411. k: v
  4412. for k, v in data.items()
  4413. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  4414. }
  4415. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  4416. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  4417. self._nozzle_fields_logged = True
  4418. # Parse active extruder from device.extruder.state bit 8
  4419. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  4420. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  4421. if "device" in data and isinstance(data.get("device"), dict):
  4422. device = data["device"]
  4423. # One-shot identification probe: surface whatever the firmware uses to
  4424. # name itself so an unknown model in a support bundle becomes self-
  4425. # diagnosing. INFO level so it shows up without debug logging. Falls
  4426. # back to dumping device.keys() if none of the known fields are present
  4427. # (so a future Bambu rename like `model_name` is still observable).
  4428. if not getattr(self, "_device_id_logged", False):
  4429. id_fields = {
  4430. k: device.get(k)
  4431. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  4432. if k in device
  4433. }
  4434. if id_fields:
  4435. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  4436. else:
  4437. logger.info(
  4438. "[%s] Device identification: no known id fields; device.keys=%s",
  4439. self.serial_number,
  4440. sorted(device.keys()),
  4441. )
  4442. self._device_id_logged = True
  4443. self._parse_extruder_position(data)
  4444. # Log device.extruder structure for active extruder
  4445. if "device" in data and isinstance(data.get("device"), dict):
  4446. device = data["device"]
  4447. if "extruder" in device:
  4448. ext_data = device["extruder"]
  4449. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4450. if "state" in ext_data:
  4451. state_val = ext_data["state"]
  4452. # Extract bits 12-14 (3 bits) for switch state
  4453. switch_state = (state_val >> 12) & 0x7
  4454. self._debug_on_change(
  4455. "extruder_state",
  4456. state_val,
  4457. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4458. self.serial_number,
  4459. state_val,
  4460. switch_state,
  4461. )
  4462. # Log 'cur' field if present (might indicate current/active extruder)
  4463. if "cur" in ext_data:
  4464. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4465. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4466. # it first. Repeated here so _update_state stays a complete "absorb this
  4467. # payload" step for any other caller; re-parsing the same block is free.
  4468. self._parse_fila_switch(data)
  4469. self._parse_extruder_slots(data)
  4470. if "bed_temper" in data:
  4471. temps["bed"] = float(data["bed_temper"])
  4472. if "bed_target_temper" in data:
  4473. temps["bed_target"] = float(data["bed_target_temper"])
  4474. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4475. has_h2d_extruder_info = (
  4476. "device" in data
  4477. and isinstance(data.get("device"), dict)
  4478. and "extruder" in data["device"]
  4479. and isinstance(data["device"]["extruder"].get("info"), list)
  4480. and len(data["device"]["extruder"]["info"]) >= 2
  4481. )
  4482. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4483. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4484. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4485. if "nozzle_temper" in data:
  4486. if has_h2d_extruder_info:
  4487. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4488. else:
  4489. temps["nozzle"] = float(data["nozzle_temper"])
  4490. if "nozzle_target_temper" in data:
  4491. if has_h2d_extruder_info:
  4492. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4493. else:
  4494. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4495. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4496. if not has_h2d_extruder_info:
  4497. # Try multiple possible field names used by different firmware versions
  4498. if "nozzle_temper_2" in data:
  4499. val = float(data["nozzle_temper_2"])
  4500. if -50 < val < 500: # Valid temp range
  4501. temps["nozzle_2"] = val
  4502. else:
  4503. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4504. elif "right_nozzle_temper" in data:
  4505. val = float(data["right_nozzle_temper"])
  4506. if -50 < val < 500: # Valid temp range
  4507. temps["nozzle_2"] = val
  4508. else:
  4509. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4510. if "nozzle_target_temper_2" in data:
  4511. val = float(data["nozzle_target_temper_2"])
  4512. if 0 <= val < 500: # Valid temp range
  4513. temps["nozzle_2_target"] = val
  4514. else:
  4515. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4516. elif "right_nozzle_target_temper" in data:
  4517. val = float(data["right_nozzle_target_temper"])
  4518. if 0 <= val < 500: # Valid temp range
  4519. temps["nozzle_2_target"] = val
  4520. else:
  4521. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4522. # Also check for left nozzle as primary (some H2 models)
  4523. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4524. temps["nozzle"] = float(data["left_nozzle_temper"])
  4525. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4526. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4527. if "chamber_temper" in data:
  4528. chamber_val = float(data["chamber_temper"])
  4529. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4530. # Check if we recently set the target locally (within 5 seconds)
  4531. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4532. respect_local = (time.time() - local_set_time) < 5.0
  4533. # H2D protocol: chamber_temper encoding indicates heater state
  4534. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4535. # - When < 500: direct Celsius current temp only - heater is OFF
  4536. if -50 < chamber_val < 100:
  4537. # Direct value = heater is OFF
  4538. temps["chamber"] = chamber_val
  4539. if not respect_local:
  4540. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4541. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4542. else:
  4543. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4544. # Try to decode if it looks like an encoded value
  4545. if chamber_val > 500:
  4546. mqtt_target = int(chamber_val) // 65536
  4547. current = int(chamber_val) % 65536
  4548. logger.debug(
  4549. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4550. )
  4551. if -50 < current < 100:
  4552. temps["chamber"] = float(current)
  4553. # Store decoded target for later use, but DON'T set chamber_heating here!
  4554. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4555. # which is the authoritative source the slicer uses.
  4556. if not respect_local:
  4557. if 0 <= mqtt_target <= 60:
  4558. # Store as "decoded" target - may be overridden by explicit target fields
  4559. temps["_chamber_decoded_target"] = float(mqtt_target)
  4560. # Chamber target temperature (set by print file or display)
  4561. if "mc_target_cham" in data:
  4562. mc_target = float(data["mc_target_cham"])
  4563. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4564. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4565. if 0 <= mc_target <= 60:
  4566. temps["chamber_target"] = mc_target
  4567. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4568. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4569. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4570. try:
  4571. if "info" in data and isinstance(data["info"], dict):
  4572. info_temp = data["info"].get("temp")
  4573. if info_temp is not None and "chamber" not in temps:
  4574. # Check for encoded value (target * 65536 + current)
  4575. if info_temp > 500:
  4576. # Decode: extract current temperature and target
  4577. target = info_temp // 65536
  4578. current = info_temp % 65536
  4579. temps["chamber"] = float(current)
  4580. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4581. if "_chamber_decoded_target" not in temps:
  4582. temps["_chamber_decoded_target"] = float(target)
  4583. logger.debug(
  4584. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4585. )
  4586. elif -50 < info_temp < 100:
  4587. # Valid direct temperature - heater is OFF
  4588. temps["chamber"] = float(info_temp)
  4589. temps["chamber_target"] = 0.0 # Direct value means heater off
  4590. self._debug_on_change(
  4591. "info_temp_direct",
  4592. info_temp,
  4593. "[%s] info.temp direct: %s°C (heater OFF)",
  4594. self.serial_number,
  4595. info_temp,
  4596. )
  4597. # H2D series: Dual extruder temps are in device.extruder.info array
  4598. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4599. if "device" in data and isinstance(data["device"], dict):
  4600. device = data["device"]
  4601. # Parse dual extruder temperatures
  4602. extruder_data = device.get("extruder", {})
  4603. extruder_info = extruder_data.get("info", [])
  4604. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4605. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4606. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4607. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4608. if has_h2d_extruder_info:
  4609. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4610. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4611. if "temp" in extruder_info[0]:
  4612. temp_val = extruder_info[0]["temp"]
  4613. if temp_val > 500:
  4614. # Encoded format: temp = target * 65536 + current
  4615. target = temp_val // 65536
  4616. current = temp_val % 65536
  4617. if -50 < current < 500:
  4618. temps["nozzle_2"] = float(current)
  4619. if 0 < target < 500:
  4620. temps["nozzle_2_target"] = float(target)
  4621. temps["nozzle_2_heating"] = target > 0 and current < target
  4622. elif -50 < temp_val < 500:
  4623. # Direct Celsius value = heater is OFF
  4624. temps["nozzle_2"] = float(temp_val)
  4625. temps["nozzle_2_target"] = 0.0
  4626. temps["nozzle_2_heating"] = False
  4627. # Left nozzle (extruder 1) - only for dual nozzle printers
  4628. # H2D protocol: temp field encoding depends on value
  4629. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4630. # - When < 500: direct Celsius current temp only - heater is OFF
  4631. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4632. ext1 = extruder_info[1]
  4633. temp_val = ext1["temp"]
  4634. # Check if we recently set the target locally (within 5 seconds)
  4635. # If so, don't let MQTT data overwrite it
  4636. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4637. respect_local_target = (time.time() - local_set_time) < 5.0
  4638. if temp_val > 500:
  4639. # Encoded format: temp = target * 65536 + current
  4640. target = temp_val // 65536
  4641. current = temp_val % 65536
  4642. if 0 < target < 500 and not respect_local_target:
  4643. temps["nozzle_target"] = float(target)
  4644. if -50 < current < 500:
  4645. temps["nozzle"] = float(current)
  4646. # Heating = encoded AND we're using the MQTT target (not local override)
  4647. # If local target is being respected, use local target to determine heating
  4648. if respect_local_target:
  4649. local_target = self.state.temperatures.get("nozzle_target", 0)
  4650. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4651. else:
  4652. temps["nozzle_heating"] = target > 0 and current < target
  4653. elif -50 < temp_val < 500:
  4654. # Direct Celsius = heater is OFF (or at target with heater off)
  4655. temps["nozzle"] = float(temp_val)
  4656. if not respect_local_target:
  4657. temps["nozzle_target"] = 0.0
  4658. temps["nozzle_heating"] = False # Direct = not heating
  4659. # The extruder snow is read by _parse_extruder_position, before the
  4660. # AMS block of the same frame (tray_now resolution needs it first).
  4661. # Parse bed heating state from device.bed.info.temp encoding
  4662. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4663. bed_data = device.get("bed", {})
  4664. bed_info = bed_data.get("info", {})
  4665. if "temp" in bed_info:
  4666. temp_val = bed_info["temp"]
  4667. if temp_val > 500:
  4668. target = temp_val // 65536
  4669. current = temp_val % 65536
  4670. temps["bed_heating"] = target > 0 and current < target
  4671. else:
  4672. temps["bed_heating"] = False
  4673. # Parse chamber temp from device.ctc.info.temp if not already set
  4674. ctc_data = device.get("ctc", {})
  4675. ctc_info = ctc_data.get("info", {})
  4676. # Parse airduct mode (0=cooling, 1=heating)
  4677. airduct_data = device.get("airduct", {})
  4678. if "modeCur" in airduct_data:
  4679. new_mode = airduct_data["modeCur"]
  4680. if new_mode != self.state.airduct_mode:
  4681. logger.debug(
  4682. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4683. )
  4684. self.state.airduct_mode = new_mode
  4685. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4686. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4687. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4688. # AIR_FUN enum: 1=part cooling, 2=aux, 3=chamber/exhaust,
  4689. # 10=second aux (FAN_REMOTE_COOLING_1). Aux 2 is the right fan and
  4690. # 10 the left on the P2S, the other way round on the X2D (#3373;
  4691. # Bambu Studio's N7.json / N6.json). The airduct `parts` list only
  4692. # contains the fans that physically exist, so it doubles as a
  4693. # presence signal for the two P2S/X2D add-on kits:
  4694. # - id 10 (second auxiliary part cooling fan) — reported ONLY here,
  4695. # never mirrored into a flat big_fanX_speed field.
  4696. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4697. # big_fan2_speed, but the part is only listed when the External
  4698. # Exhaust Fan kit (get_version module "eef") is installed.
  4699. # `state` is already a 0-100 percentage.
  4700. parts = airduct_data.get("parts")
  4701. if isinstance(parts, list):
  4702. speeds: dict[int, int] = {}
  4703. for part in parts:
  4704. if not isinstance(part, dict):
  4705. continue
  4706. try:
  4707. # Studio reads the id with get_flag_bits(id, 4, 8),
  4708. # so mask after shifting for the same reason `state`
  4709. # is masked below. Every id seen in the wild
  4710. # (16/32/48/160) decodes identically either way —
  4711. # this is consistency, not a live bug.
  4712. part_id = (int(part["id"]) >> 4) & 0xFF
  4713. # `state` is bit-packed like its sibling `range`
  4714. # (end << 16 | start), so take only the low 8 bits —
  4715. # the same decode Bambu Studio does with
  4716. # get_flag_bits(state, 0, 8). Without the mask a
  4717. # packed value would clamp to 100 instead of
  4718. # decoding to the real percentage.
  4719. part_state = int(part["state"]) & 0xFF
  4720. except (KeyError, ValueError, TypeError):
  4721. continue
  4722. # Ids seen across the support-package archive:
  4723. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4724. # 6 (H2 series, unmapped), 10 second aux.
  4725. speeds[part_id] = max(0, min(100, part_state))
  4726. # Absence in this list is what tells us a kit is NOT fitted,
  4727. # so it may only be trusted when the list is a full
  4728. # inventory rather than a diff frame. `device.airduct` is
  4729. # pushed field by field — the `modeCur` handler above exists
  4730. # for exactly that reason — and a truncated `parts` read as
  4731. # gospel would retract both accessory badges mid-print and
  4732. # start rejecting `aux2` on a printer that has the fan.
  4733. #
  4734. # Every airduct layout in the support-package archive
  4735. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4736. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4737. # part cooling fan and the aux fan, neither of which is
  4738. # optional on any machine that reports an airduct at all.
  4739. # A list carrying both is therefore a complete inventory; a
  4740. # list missing either is a partial frame, and we take its
  4741. # speeds without touching presence.
  4742. is_full_inventory = 1 in speeds and 2 in speeds
  4743. left_aux_speed = speeds.get(10)
  4744. if left_aux_speed is None and not is_full_inventory:
  4745. # Partial frame that didn't mention the second aux fan —
  4746. # keep whatever we already knew about it.
  4747. left_aux_speed = self.state.left_aux_fan_speed
  4748. if left_aux_speed != self.state.left_aux_fan_speed:
  4749. logger.debug(
  4750. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4751. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4752. )
  4753. # A FULL parts list without id 10 means the second aux fan is
  4754. # not installed — report None so the UI can hide the widget.
  4755. self.state.left_aux_fan_speed = left_aux_speed
  4756. # id 3 present == chamber exhaust fan installed (base P2S
  4757. # omits it). Only ever retracted on a full inventory.
  4758. if 3 in speeds:
  4759. self.state.exhaust_fan_present = True
  4760. elif is_full_inventory:
  4761. self.state.exhaust_fan_present = False
  4762. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  4763. # Check if we recently set the target locally (within 5 seconds)
  4764. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4765. respect_local_target = (time.time() - local_set_time) < 5.0
  4766. # Log ctc_info contents for debugging
  4767. if ctc_info:
  4768. self._debug_on_change(
  4769. "ctc_info_keys",
  4770. tuple(ctc_info.keys()),
  4771. "[%s] ctc_info keys: %s",
  4772. self.serial_number,
  4773. list(ctc_info.keys()),
  4774. )
  4775. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  4776. # (what the slicer shows). This OVERRIDES any previously decoded target.
  4777. explicit_target = None
  4778. if "target" in ctc_info:
  4779. target_val = ctc_info["target"]
  4780. logger.debug(
  4781. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  4782. )
  4783. # Filter out invalid values (valid chamber target is 0-60°C)
  4784. if 0 <= target_val <= 60 and not respect_local_target:
  4785. explicit_target = float(target_val)
  4786. temps["chamber_target"] = explicit_target # Override any previous value
  4787. logger.debug(
  4788. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  4789. )
  4790. # Parse chamber temp from ctc.info.temp - may be encoded
  4791. if "temp" in ctc_info and "chamber" not in temps:
  4792. temp_val = ctc_info["temp"]
  4793. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  4794. if temp_val > 500:
  4795. # Encoded value: decode target and current
  4796. decoded_target = temp_val // 65536
  4797. current = temp_val % 65536
  4798. temps["chamber"] = float(current)
  4799. logger.debug(
  4800. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  4801. )
  4802. # Determine which target to use for heating state:
  4803. # Priority: local target > explicit target > decoded target
  4804. if respect_local_target:
  4805. local_target = self.state.temperatures.get("chamber_target", 0)
  4806. temps["chamber_heating"] = local_target > 0 and current < local_target
  4807. elif explicit_target is not None:
  4808. # Use explicit ctc.info.target - this is what slicer sees
  4809. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  4810. else:
  4811. # Fallback to decoded target only if no explicit target available
  4812. if not respect_local_target and "chamber_target" not in temps:
  4813. temps["chamber_target"] = float(decoded_target)
  4814. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  4815. else:
  4816. # Direct value (not encoded) - heater is OFF
  4817. temps["chamber"] = float(temp_val)
  4818. temps["chamber_heating"] = False
  4819. except Exception as e:
  4820. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  4821. if temps:
  4822. # Handle chamber_target: prefer explicit over decoded
  4823. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  4824. # No explicit target available, use decoded target from chamber_temper
  4825. temps["chamber_target"] = temps["_chamber_decoded_target"]
  4826. # Remove internal temp key before merging
  4827. temps.pop("_chamber_decoded_target", None)
  4828. # Merge new temps into existing, preserving valid values when new ones are filtered out
  4829. for key, value in temps.items():
  4830. self.state.temperatures[key] = value
  4831. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  4832. if "bed" in temps and self.on_bed_temp_update:
  4833. self.on_bed_temp_update(temps["bed"])
  4834. # Calculate chamber_heating after all targets are known
  4835. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  4836. if "chamber" in temps and "chamber_heating" not in temps:
  4837. current = self.state.temperatures.get("chamber", 0)
  4838. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4839. respect_local = (time.time() - local_set_time) < 5.0
  4840. if respect_local:
  4841. # Use locally-set target
  4842. target = self.state.temperatures.get("chamber_target", 0)
  4843. else:
  4844. # Use explicit/decoded target from MQTT
  4845. target = self.state.temperatures.get("chamber_target", 0)
  4846. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  4847. self._debug_on_change(
  4848. "chamber_heating",
  4849. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  4850. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  4851. self.serial_number,
  4852. target,
  4853. current,
  4854. self.state.temperatures["chamber_heating"],
  4855. respect_local,
  4856. )
  4857. # Debug: log chamber value if it was updated
  4858. if "chamber" in temps:
  4859. self._debug_on_change(
  4860. "chamber_temp",
  4861. (
  4862. self.state.temperatures.get("chamber"),
  4863. self.state.temperatures.get("chamber_target"),
  4864. self.state.temperatures.get("chamber_heating"),
  4865. ),
  4866. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  4867. self.serial_number,
  4868. self.state.temperatures.get("chamber"),
  4869. self.state.temperatures.get("chamber_target"),
  4870. self.state.temperatures.get("chamber_heating"),
  4871. )
  4872. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  4873. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  4874. if "nozzle" in temps and "nozzle_heating" not in temps:
  4875. current = self.state.temperatures.get("nozzle", 0)
  4876. target = self.state.temperatures.get("nozzle_target", 0)
  4877. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  4878. # Parse HMS (Health Management System) errors
  4879. if "hms" in data:
  4880. hms_list = data["hms"]
  4881. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  4882. self.state.hms_errors = []
  4883. verify_failed = False
  4884. if isinstance(hms_list, list):
  4885. for hms in hms_list:
  4886. if isinstance(hms, dict):
  4887. # HMS format: {"attr": attribute_code, "code": error_code}
  4888. # attr contains module/severity info, code contains error number
  4889. # Both are needed to construct the wiki URL
  4890. attr = hms.get("attr", 0)
  4891. code = hms.get("code", 0)
  4892. if isinstance(attr, str):
  4893. attr = int(attr.replace("0x", ""), 16) if attr else 0
  4894. if isinstance(code, str):
  4895. code = int(code.replace("0x", ""), 16) if code else 0
  4896. # attr is module, module no., part, part no. (a byte each);
  4897. # code is the alert level (high 16 bits) then the error
  4898. # (low 16). The level is 1 error (task stopped), 2 warning
  4899. # (task paused), 3 notification; 0 is invalid. This is how
  4900. # Bambu Studio decodes it (DevHMSItem::parse_hms_info). It
  4901. # used to be read from attr bits 8-15, which is the part
  4902. # byte (#2728).
  4903. severity = (code >> 16) & 0xFFFF
  4904. # Module is in attr byte 3 (bits 24-31)
  4905. module = (attr >> 24) & 0xFF
  4906. # Skip non-error status codes. A real fault has a level of
  4907. # at least 1 in the high half, so its code is >= 0x10000
  4908. # and clears this; lower values are status/phase
  4909. # indicators some firmware sends during normal printing.
  4910. if code < 0x4000:
  4911. continue
  4912. # Skip user-action echoes — the printer firmware emits these
  4913. # as part of normal user-cancel sequences. They're not faults
  4914. # and shouldn't count toward "X problem" badges or surface as
  4915. # red pips on the printer card. Backend's notification path
  4916. # already suppresses 0500_400E for the same reason.
  4917. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  4918. if short_code in _HMS_USER_ACTION_CODES:
  4919. continue
  4920. # The full 16-char identifier is the firmware's matching key
  4921. # and the HMS catalogue's key for this kind of fault; the
  4922. # short code discards the part and alert-level groups. The
  4923. # action table still has some short-form entries, so that
  4924. # lookup falls back to it.
  4925. full_code = f"{attr:08X}{code:08X}"
  4926. if full_code == HMS_MQTT_VERIFY_FAILED:
  4927. verify_failed = True
  4928. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  4929. if not actions:
  4930. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4931. self.state.hms_errors.append(
  4932. HMSError(
  4933. code=f"0x{code:x}" if code else "0x0",
  4934. attr=attr,
  4935. module=module,
  4936. # No fallback: 0 is Bambu's "invalid" level, and
  4937. # promoting it would render it as a fault.
  4938. severity=severity,
  4939. actions=actions,
  4940. job_id=self.state.subtask_id,
  4941. full_code=full_code,
  4942. description=describe_fault(full_code, self.serial_number[:3]),
  4943. )
  4944. )
  4945. self._apply_mqtt_verify_state(verify_failed)
  4946. # Parse print_error - this is a different error format than HMS
  4947. # print_error is a 32-bit integer where:
  4948. # - High 16 bits contain module info (e.g., 0x0500)
  4949. # - Low 16 bits contain error code (e.g., 0x8061)
  4950. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  4951. if "print_error" in data:
  4952. print_error = data["print_error"]
  4953. if print_error and print_error != 0:
  4954. # Extract components: MMMMEEEE -> MMMM_EEEE
  4955. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  4956. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  4957. # Values below 0x4000 are status/phase indicators, not real errors.
  4958. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  4959. # Some firmware sends low values like 0x0002 during normal printing.
  4960. if error < 0x4000:
  4961. pass # Skip — not a real error
  4962. else:
  4963. # Store in a format that matches the community error database
  4964. # attr stores the full 32-bit value for reconstruction
  4965. # code stores the short format string for lookup
  4966. short_code = f"{module:04X}_{error:04X}"
  4967. logger.debug(
  4968. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  4969. )
  4970. # Same user-action filter as the hms[] branch above — print_error
  4971. # carries the same cancel echoes (e.g. 0500_400E) and they must
  4972. # not surface as faults on the printer card.
  4973. if short_code in _HMS_USER_ACTION_CODES:
  4974. pass # cancel echo — silently drop
  4975. else:
  4976. # Only add if not already in HMS errors (avoid duplicates)
  4977. existing_short_codes = set()
  4978. for e in self.state.hms_errors:
  4979. # Extract short code from existing errors
  4980. e_module = (e.attr >> 16) & 0xFFFF
  4981. # The low half only: an hms[] code carries its alert
  4982. # level above it (0x18061 for 0500_8061), and read
  4983. # whole it never matched, listing the fault twice (M-U9).
  4984. e_error = (int(e.code.replace("0x", ""), 16) & 0xFFFF) if e.code else 0
  4985. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  4986. if short_code not in existing_short_codes:
  4987. # Bambu's HMS catalog keys by 3-letter device code (the SN
  4988. # prefix) and a 16-char short error code without the
  4989. # underscore separator we store internally.
  4990. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4991. # Bambu pushes the current job as `subtask_id` on the
  4992. # state stream; the HMS-action commands echo it back as
  4993. # `job_id`. The error payload itself doesn't carry the
  4994. # id, so snapshot it from the live state at parse time
  4995. # and freeze it on the HMSError so subsequent
  4996. # job changes don't invalidate the action.
  4997. job_id = self.state.subtask_id
  4998. logger.debug(
  4999. "[%s, %s] HMS available actions: %s (job_id=%s)",
  5000. self.serial_number[:3],
  5001. short_code.replace("_", ""),
  5002. actions,
  5003. job_id,
  5004. )
  5005. self.state.hms_errors.append(
  5006. HMSError(
  5007. code=f"0x{error:x}",
  5008. attr=print_error, # Store full value for display
  5009. module=module >> 8, # High byte of module (e.g., 0x05)
  5010. # print_error has no level field; its error
  5011. # number's first digit carries it instead.
  5012. severity=alert_level_from_print_error(error),
  5013. actions=actions,
  5014. job_id=job_id,
  5015. # print_error is already 32-bit — `f"{print_error:08X}"`
  5016. # is the firmware's matching key with no truncation.
  5017. full_code=f"{print_error:08X}",
  5018. description=describe_fault(f"{print_error:08X}", self.serial_number[:3]),
  5019. )
  5020. )
  5021. # Parse home_flag first so SD-card detection below can prefer it.
  5022. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  5023. # bit 23 = door-open (X1 family only).
  5024. home_flag = None
  5025. if "home_flag" in data:
  5026. home_flag = data["home_flag"]
  5027. if home_flag < 0:
  5028. home_flag = home_flag & 0xFFFFFFFF
  5029. # SD card presence: the only remaining consumer is the firmware-update
  5030. # precondition check (firmware_update.py). Use the top-level `sdcard`
  5031. # field when present with a permissive truthy check covering the
  5032. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  5033. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  5034. # when a card is inserted, which caused the badge to flap before the
  5035. # badge was removed entirely.
  5036. if "sdcard" in data:
  5037. raw_sdcard = data["sdcard"]
  5038. if isinstance(raw_sdcard, str):
  5039. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  5040. else:
  5041. self.state.sdcard = bool(raw_sdcard)
  5042. self.state.sdcard_reported = True
  5043. if home_flag is not None:
  5044. store_to_sdcard = bool((home_flag >> 11) & 1)
  5045. if store_to_sdcard != self.state.store_to_sdcard:
  5046. logger.debug(
  5047. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  5048. )
  5049. self.state.store_to_sdcard = store_to_sdcard
  5050. # Door open detection — source depends on printer family:
  5051. # X1 series (X1, X1C, X1E): home_flag bit 23
  5052. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  5053. # Both share the same bitmask (0x00800000) but live in different fields.
  5054. model_upper = (self.model or "").upper().strip()
  5055. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  5056. if is_x1_family and home_flag is not None:
  5057. door_open = (home_flag & 0x00800000) != 0
  5058. if door_open != self.state.door_open:
  5059. logger.debug(
  5060. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  5061. self.serial_number,
  5062. self.state.door_open,
  5063. door_open,
  5064. home_flag,
  5065. )
  5066. self.state.door_open = door_open
  5067. elif not is_x1_family and "stat" in data:
  5068. try:
  5069. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  5070. door_open = (stat_value & 0x00800000) != 0
  5071. if door_open != self.state.door_open:
  5072. logger.debug(
  5073. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  5074. self.serial_number,
  5075. self.state.door_open,
  5076. door_open,
  5077. stat_value,
  5078. )
  5079. self.state.door_open = door_open
  5080. except (ValueError, TypeError):
  5081. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  5082. # Parse timelapse status (recording active during print). Status frames
  5083. # only — the project_file ack echoes back the per-job timelapse flag we
  5084. # asked for, which is a request, not the recorder's state (#3040).
  5085. if "timelapse" in data and is_printer_status_frame(data):
  5086. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  5087. self.state.timelapse = data["timelapse"] is True
  5088. # Track if timelapse was ever active during this print
  5089. if self.state.timelapse and self._was_running:
  5090. self._timelapse_during_print = True
  5091. # Parse ipcam/live view status
  5092. if "ipcam" in data:
  5093. ipcam_data = data["ipcam"]
  5094. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  5095. if isinstance(ipcam_data, dict):
  5096. # Check ipcam_record field for live view status
  5097. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  5098. # Check timelapse field (H2D sends it here, not in xcam)
  5099. if "timelapse" in ipcam_data:
  5100. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  5101. if timelapse_enabled != self.state.timelapse:
  5102. logger.debug(
  5103. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  5104. )
  5105. self.state.timelapse = timelapse_enabled
  5106. # Track if timelapse was ever active during this print
  5107. if self.state.timelapse and self._was_running:
  5108. self._timelapse_during_print = True
  5109. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  5110. else:
  5111. self.state.ipcam = ipcam_data is True
  5112. # Parse WiFi signal strength (dBm)
  5113. if "wifi_signal" in data:
  5114. wifi_signal = data["wifi_signal"]
  5115. self._debug_on_change(
  5116. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  5117. )
  5118. if isinstance(wifi_signal, (int, float)):
  5119. self.state.wifi_signal = int(wifi_signal)
  5120. elif isinstance(wifi_signal, str):
  5121. # Handle string format like "-52dBm"
  5122. try:
  5123. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  5124. except ValueError:
  5125. pass # Ignore unparseable wifi_signal strings; field is non-critical
  5126. # Detect ethernet connection: printers on ethernet with WiFi disabled
  5127. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  5128. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  5129. from backend.app.utils.printer_models import has_ethernet
  5130. if has_ethernet(self.model):
  5131. self.state.wired_network = self.state.wifi_signal == -90
  5132. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5133. if "spd_lvl" in data:
  5134. new_speed = data["spd_lvl"]
  5135. if new_speed != self.state.speed_level:
  5136. logger.debug(
  5137. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  5138. )
  5139. self.state.speed_level = new_speed
  5140. # Parse skipped objects from printer status (s_obj field)
  5141. # This allows us to restore skipped objects state after reconnection
  5142. if "s_obj" in data:
  5143. s_obj = data["s_obj"]
  5144. if isinstance(s_obj, list):
  5145. # Update skipped objects from printer's list
  5146. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  5147. if new_skipped != self.state.skipped_objects:
  5148. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  5149. self.state.skipped_objects = new_skipped
  5150. for oid in new_skipped:
  5151. self._unconfirmed_skips.pop(oid, None)
  5152. self._check_unconfirmed_skips()
  5153. # Parse chamber light status from lights_report
  5154. if "lights_report" in data:
  5155. lights = data["lights_report"]
  5156. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  5157. if isinstance(lights, list):
  5158. for light in lights:
  5159. if isinstance(light, dict) and light.get("node") == "chamber_light":
  5160. new_light_state = light.get("mode") == "on"
  5161. if new_light_state != self.state.chamber_light:
  5162. logger.debug(
  5163. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  5164. )
  5165. self.state.chamber_light = new_light_state
  5166. break
  5167. # Parse nozzle hardware info (single nozzle printers)
  5168. if "nozzle_type" in data:
  5169. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  5170. if "nozzle_diameter" in data:
  5171. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  5172. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  5173. # Left nozzle
  5174. if "left_nozzle_type" in data:
  5175. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  5176. if "left_nozzle_diameter" in data:
  5177. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  5178. # Right nozzle
  5179. if "right_nozzle_type" in data:
  5180. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  5181. if "right_nozzle_diameter" in data:
  5182. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  5183. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  5184. if "nozzle_type_2" in data:
  5185. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  5186. if "nozzle_diameter_2" in data:
  5187. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  5188. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  5189. if "device" in data and isinstance(data["device"], dict):
  5190. device = data["device"]
  5191. nozzle_data = device.get("nozzle", {})
  5192. # H2C rack position (#2800). `tar_id` is where the carriage is
  5193. # headed, `src_id` where it came from; mid-swap they differ, so
  5194. # dispatch prefers tar_id and falls back to src_id. Both are
  5195. # sticky — the field is only pushed when it changes, so an
  5196. # absent key must leave the last known value alone rather than
  5197. # reset it to None.
  5198. if isinstance(nozzle_data, dict):
  5199. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  5200. if key not in nozzle_data:
  5201. continue
  5202. try:
  5203. parsed_id = int(nozzle_data[key])
  5204. except (TypeError, ValueError):
  5205. continue
  5206. if getattr(self.state, attr) != parsed_id:
  5207. setattr(self.state, attr, parsed_id)
  5208. # DEBUG, not INFO: these move on every tool change, so
  5209. # a long multi-material print would otherwise write
  5210. # thousands of lines. The dispatch log records both
  5211. # values once per print, which is where triage needs
  5212. # them. Same reasoning as the one-shot `nozzle_info`
  5213. # log below.
  5214. logger.debug(
  5215. "[%s] Nozzle rack %s -> %s",
  5216. self.serial_number,
  5217. key,
  5218. parsed_id,
  5219. )
  5220. nozzle_info = nozzle_data.get("info", [])
  5221. if isinstance(nozzle_info, list):
  5222. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  5223. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  5224. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  5225. # for hover cards on both the L/R indicator and the nozzle rack card.
  5226. if nozzle_info:
  5227. self.state.nozzle_rack = sorted(
  5228. [
  5229. {
  5230. "id": n.get("id", i),
  5231. "type": str(n.get("type", "")),
  5232. "diameter": str(n.get("diameter", "")),
  5233. "wear": n.get("wear"),
  5234. "stat": n.get("stat"),
  5235. # H2C uses "tm", H2D uses "max_temp"
  5236. "max_temp": n.get("max_temp") or n.get("tm", 0),
  5237. # H2C uses "sn", H2D uses "serial_number"
  5238. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  5239. # H2C uses "color_m", H2D uses "filament_colour"
  5240. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  5241. # H2C uses "fila_id", H2D uses "filament_id"
  5242. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  5243. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  5244. }
  5245. for i, n in enumerate(nozzle_info)
  5246. ],
  5247. key=lambda x: x["id"],
  5248. )
  5249. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  5250. self._nozzle_rack_logged = True
  5251. logger.debug(
  5252. "[%s] Nozzle info: %d entries, IDs: %s",
  5253. self.serial_number,
  5254. len(nozzle_info),
  5255. [n.get("id") for n in nozzle_info],
  5256. )
  5257. for nozzle in nozzle_info:
  5258. idx = nozzle.get("id", 0)
  5259. if idx < len(self.state.nozzles):
  5260. if "type" in nozzle and nozzle["type"]:
  5261. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  5262. if "diameter" in nozzle:
  5263. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  5264. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  5265. # (these fields aren't sent in every MQTT push, only when changed)
  5266. ams_data = self.state.raw_data.get("ams")
  5267. vt_tray_data = self.state.raw_data.get("vt_tray")
  5268. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  5269. mapping_data = self.state.raw_data.get("mapping")
  5270. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  5271. # as a dict but consumers expect a list. Without this, the dev mode probe
  5272. # below can release the GIL (via publish), letting the event-loop thread
  5273. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  5274. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  5275. data["vt_tray"] = [data["vt_tray"]]
  5276. self.state.raw_data = data
  5277. # Restore preserved fields BEFORE any work that may release the GIL
  5278. # (e.g. _probe_developer_mode publishes an MQTT message).
  5279. if ams_data is not None:
  5280. self.state.raw_data["ams"] = ams_data
  5281. if vt_tray_data is not None:
  5282. self.state.raw_data["vt_tray"] = vt_tray_data
  5283. if ams_extruder_map_data is not None:
  5284. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  5285. if mapping_data is not None and "mapping" not in data:
  5286. self.state.raw_data["mapping"] = mapping_data
  5287. # Parse developer LAN mode from "fun" field
  5288. if "fun" in data:
  5289. try:
  5290. fun_val = data["fun"]
  5291. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  5292. self.state.developer_mode = (fun_int & 0x20000000) == 0
  5293. except (ValueError, TypeError):
  5294. pass
  5295. elif self.state.developer_mode is None and not self._dev_mode_probed:
  5296. # No "fun" field — A1/P1 series never send it, so we need to probe.
  5297. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  5298. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  5299. # after connect to let the MQTT session stabilize — probing too early
  5300. # can destabilize some firmware MQTT brokers (#887).
  5301. if not self._dev_mode_needs_probe and len(data) > 30:
  5302. # First full status without "fun" — mark that probe is needed
  5303. self._dev_mode_needs_probe = True
  5304. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  5305. self._probe_developer_mode()
  5306. elif self._dev_mode_needs_probe:
  5307. logger.debug(
  5308. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  5309. self.serial_number,
  5310. time.monotonic() - self._connect_time,
  5311. )
  5312. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  5313. # Probe was sent but no response yet — check for timeout.
  5314. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  5315. # may deliver status pushes but silently drop commands (#887).
  5316. elapsed = time.monotonic() - self._dev_mode_probe_time
  5317. if elapsed > 10.0:
  5318. self._dev_mode_probe_failures += 1
  5319. logger.warning(
  5320. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  5321. self.serial_number,
  5322. elapsed,
  5323. self._dev_mode_probe_failures,
  5324. )
  5325. self._dev_mode_probe_seq = None
  5326. if self._dev_mode_probe_failures >= 2:
  5327. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  5328. else:
  5329. # Allow retry on next full status message
  5330. self._dev_mode_probed = False
  5331. # Zombie session detection: if an ams_filament_setting command has been
  5332. # pending for >10s with no response, the publish path is likely dead (#887).
  5333. if self._last_ams_cmd_time > 0:
  5334. elapsed = time.monotonic() - self._last_ams_cmd_time
  5335. if elapsed > 10.0:
  5336. self._ams_cmd_unanswered += 1
  5337. logger.warning(
  5338. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  5339. self.serial_number,
  5340. elapsed,
  5341. self._ams_cmd_unanswered,
  5342. )
  5343. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  5344. if self._ams_cmd_unanswered >= 2:
  5345. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  5346. self._ams_cmd_unanswered = 0
  5347. # Log mapping data when received (for usage tracking debugging)
  5348. if "mapping" in data:
  5349. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  5350. # Log state transitions for debugging
  5351. if "gcode_state" in data:
  5352. logger.debug(
  5353. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  5354. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  5355. )
  5356. # Detect print start (state changes TO RUNNING with a file)
  5357. current_file = self.state.gcode_file or self.state.current_print
  5358. is_new_print = (
  5359. self.state.state == "RUNNING"
  5360. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  5361. and self._previous_gcode_state != "RUNNING"
  5362. and current_file
  5363. and not self._was_running # Prevent duplicates when resuming from PAUSE
  5364. )
  5365. # Also detect if file changed while running (new print started)
  5366. is_file_change = (
  5367. self.state.state == "RUNNING"
  5368. and current_file
  5369. and current_file != self._previous_gcode_file
  5370. and self._previous_gcode_file is not None
  5371. )
  5372. # Track RUNNING state for more robust completion detection
  5373. running_first_observed = False
  5374. if self.state.state == "RUNNING" and current_file:
  5375. if not self._was_running:
  5376. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  5377. # Check if timelapse was enabled in the same message (xcam parsed before this)
  5378. if self.state.timelapse:
  5379. self._timelapse_during_print = True
  5380. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  5381. # Mark this as the first RUNNING observation of the session.
  5382. # If is_new_print also fires below, on_print_start handles
  5383. # baseline capture and we suppress on_print_running_observed
  5384. # to avoid double-capture. If is_new_print does NOT fire
  5385. # (Bambuddy started mid-print — the #1304 guard suppressed
  5386. # it), main.py needs this hook to catch the restart-recovery
  5387. # case (#1485 follow-up).
  5388. running_first_observed = True
  5389. self._was_running = True
  5390. self._completion_triggered = False
  5391. if is_new_print or is_file_change:
  5392. # Clear any old HMS errors when a new print starts
  5393. self.state.hms_errors = []
  5394. # The last print's pauses; this one's come from its 3MF (#2984).
  5395. self.state.pause_points = []
  5396. self.state.pause_warned_layers = set()
  5397. # Reset layer tracking for new print (needed for layer-based timelapse)
  5398. # #3317: only above 1. Every print reports layer 1 first, which
  5399. # clears a higher value; a previous print that ended on layer 1
  5400. # would make this print's own first layer look stale.
  5401. self._stale_layer_num = self.state.layer_num if self.state.layer_num > 1 else 0
  5402. self.state.layer_num = 0
  5403. # Reset total_layers so the previous print's value can't bleed into
  5404. # this print's usage-tracker split (#1771 follow-on to the
  5405. # preservation guard at the `total_layer_num` parse above — that
  5406. # guard ignores firmware-reset 0s, so the explicit reset has to
  5407. # happen here instead).
  5408. #
  5409. # #2702: reset to *this frame's* total, not to 0. The frame that
  5410. # trips the new-print detection can carry the new print's
  5411. # `total_layer_num` as well — the parse above has already applied
  5412. # it, and zeroing unconditionally threw it away. That looked
  5413. # harmless but is not recoverable: Bambu firmware sends only
  5414. # changed fields, so the printer never offers the total again, and
  5415. # the print runs to completion at `n/0` in the UI, in
  5416. # `{total_layers}` notifications, and as the usage-split
  5417. # denominator. The value only reappears on the next full pushall
  5418. # (reconnect / Force Refresh), which is why the symptom looked
  5419. # random and why a *stable* connection made it worse.
  5420. self.state.total_layers = total_from_this_frame
  5421. # If the starting frame brought no total, ask for one. Costs one
  5422. # MQTT message per print and covers the ordering where the printer
  5423. # published the total a frame or two before the state flip.
  5424. self._total_layers_refresh_armed = not total_from_this_frame
  5425. if self._total_layers_refresh_armed:
  5426. self._request_push_all()
  5427. # Reset completion tracking for new print
  5428. self._was_running = True
  5429. self._completion_triggered = False
  5430. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5431. self._finish_photo_captured = False
  5432. # #2547: rearm the end-of-print telemetry probe for the new print
  5433. self._eop_probe_armed = True
  5434. self._eop_probe_open = False
  5435. self._eop_probe_frames = 0
  5436. self._eop_probe_last = {}
  5437. # Reset last valid progress/layer for usage tracking
  5438. self._last_valid_progress = 0.0
  5439. self._last_valid_layer_num = 0
  5440. # Clear and seed tray change log for mid-print usage splitting
  5441. self.state.tray_change_log.clear()
  5442. # Seeded with the assigned spools by usage_tracker.on_print_start.
  5443. self.state.spool_change_log = []
  5444. tn = self.state.tray_now
  5445. if (
  5446. (0 <= tn <= 15)
  5447. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  5448. or (128 <= tn <= 135)
  5449. or tn == 254
  5450. ):
  5451. self.state.tray_change_log.append((tn, 0))
  5452. # Initialize timelapse tracking based on current state
  5453. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5454. # so self.state.timelapse may already be set from this message.
  5455. # We preserve that value instead of blindly resetting to False.
  5456. if self.state.timelapse:
  5457. self._timelapse_during_print = True
  5458. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5459. else:
  5460. self._timelapse_during_print = False
  5461. if (is_new_print or is_file_change) and self.on_print_start:
  5462. logger.info(
  5463. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5464. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5465. )
  5466. self.on_print_start(
  5467. {
  5468. "filename": current_file,
  5469. "subtask_name": self.state.subtask_name,
  5470. "remaining_time": self.state.remaining_time * 60
  5471. if self.state.remaining_time > 0
  5472. else None, # Convert minutes to seconds
  5473. "raw_data": data,
  5474. "ams_mapping": self._captured_ams_mapping,
  5475. }
  5476. )
  5477. elif running_first_observed and self.on_print_running_observed:
  5478. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5479. # print, so the #1304 first-push guard suppressed on_print_start,
  5480. # but we still need main.py to capture a fresh timelapse baseline
  5481. # before the printer uploads the in-flight MP4. Same payload
  5482. # shape as on_print_start so the consumer can reuse fields.
  5483. logger.info(
  5484. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5485. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5486. )
  5487. self.on_print_running_observed(
  5488. {
  5489. "filename": current_file,
  5490. "subtask_name": self.state.subtask_name,
  5491. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5492. "raw_data": data,
  5493. "ams_mapping": self._captured_ams_mapping,
  5494. }
  5495. )
  5496. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5497. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5498. # This handles cases where server restarts during a print
  5499. should_trigger_completion = (
  5500. self.state.state in ("FINISH", "FAILED")
  5501. and not self._completion_triggered
  5502. and self.on_print_complete
  5503. and (
  5504. self._previous_gcode_state == "RUNNING" # Normal transition
  5505. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5506. # Pre-print failure (#1111): printer rejected the job during setup
  5507. # — wrong nozzle size, AMS error, etc. The print never reaches
  5508. # RUNNING, so without this branch neither the RUNNING check nor
  5509. # _was_running match and the queue item stays stuck at "printing".
  5510. # Restricted to FAILED from pre-print states so a stale FAILED on
  5511. # first connection (prev=None) still can't accidentally fire.
  5512. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5513. )
  5514. )
  5515. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5516. if (
  5517. self.state.state == "IDLE"
  5518. and self._previous_gcode_state == "RUNNING"
  5519. and not self._completion_triggered
  5520. and self.on_print_complete
  5521. ):
  5522. should_trigger_completion = True
  5523. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5524. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5525. if (
  5526. not should_trigger_completion
  5527. and self.state.state in ("FINISH", "FAILED")
  5528. and self._previous_gcode_state != self.state.state
  5529. ):
  5530. logger.info(
  5531. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5532. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5533. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5534. )
  5535. # Mark as triggered so state is clean for the next print cycle
  5536. self._completion_triggered = True
  5537. if should_trigger_completion:
  5538. if self.state.state == "FINISH":
  5539. status = "completed"
  5540. elif self.state.state == "FAILED":
  5541. status = "failed"
  5542. else:
  5543. status = "aborted"
  5544. logger.info(
  5545. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5546. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5547. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5548. f"timelapse_during_print: {self._timelapse_during_print}"
  5549. )
  5550. timelapse_was_active = self._timelapse_during_print
  5551. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5552. # external-spool-only, HMS halt, or firmware variant that skips
  5553. # the unload phase) fire the finish-photo moment now. Bed has
  5554. # already dropped, framing is worse, but we still capture.
  5555. # Only on successful completion — aborted/failed prints don't
  5556. # produce a meaningful finish photo.
  5557. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5558. self._finish_photo_captured = True
  5559. logger.info(
  5560. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5561. f"stage-22 never fired; capturing at FINISH-state transition"
  5562. )
  5563. self.on_finish_photo_moment(
  5564. {
  5565. "trigger": "finish_state",
  5566. "filename": self._previous_gcode_file or current_file,
  5567. "subtask_name": self.state.subtask_name,
  5568. "timelapse_was_active": timelapse_was_active,
  5569. }
  5570. )
  5571. self._completion_triggered = True
  5572. self._was_running = False
  5573. self._timelapse_during_print = False # Reset for next print
  5574. # Include HMS errors for failure reason detection
  5575. hms_errors_data = [e.completion_payload() for e in self.state.hms_errors or []]
  5576. self.on_print_complete(
  5577. {
  5578. "status": status,
  5579. "subtask_id": self.state.subtask_id,
  5580. "filename": self._previous_gcode_file or current_file,
  5581. "subtask_name": self.state.subtask_name,
  5582. "raw_data": data,
  5583. "timelapse_was_active": timelapse_was_active,
  5584. "hms_errors": hms_errors_data,
  5585. "ams_mapping": self._captured_ams_mapping,
  5586. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5587. "last_progress": self._last_valid_progress,
  5588. "last_layer_num": self._last_valid_layer_num,
  5589. }
  5590. )
  5591. self._captured_ams_mapping = None
  5592. # Same lifecycle as the mapping above: it described *this* print.
  5593. # Leaving it set would hand the next print an answer about where a
  5594. # different file went, and a stale "internal storage" reading costs
  5595. # an archive that the FTPS sweep would have found (#2780).
  5596. self.state.current_project_url = None
  5597. self._previous_gcode_state = self.state.state
  5598. if current_file:
  5599. self._previous_gcode_file = current_file
  5600. if self.on_state_change:
  5601. self.on_state_change(self.state)
  5602. def _request_push_all(self):
  5603. """Request full status update from printer."""
  5604. if self._client:
  5605. message = {"pushing": {"command": "pushall"}}
  5606. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5607. def _probe_developer_mode(self):
  5608. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5609. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5610. For these, we detect developer mode by sending a harmless command and
  5611. checking whether the printer accepts or rejects it:
  5612. - result="success" → developer mode ON (commands accepted)
  5613. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5614. The probe re-sends the current external slot configuration so it's a no-op
  5615. when the command succeeds. If there's no external slot data yet, we send a
  5616. reset (empty filament) which is also safe.
  5617. """
  5618. if not self._client or not self.state.connected:
  5619. return
  5620. self._dev_mode_probed = True
  5621. self._dev_mode_probe_time = time.monotonic()
  5622. self._sequence_id += 1
  5623. seq = str(self._sequence_id)
  5624. self._dev_mode_probe_seq = seq
  5625. # Build probe command: re-send current external slot config (no-op on success)
  5626. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5627. current = vt_tray[0] if vt_tray else {}
  5628. command = {
  5629. "print": {
  5630. "command": "ams_filament_setting",
  5631. "ams_id": 255,
  5632. "tray_id": 0,
  5633. "slot_id": 0,
  5634. "tray_info_idx": current.get("tray_info_idx", ""),
  5635. "tray_type": current.get("tray_type", ""),
  5636. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5637. "tray_color": current.get("tray_color", "00000000"),
  5638. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5639. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5640. "sequence_id": seq,
  5641. }
  5642. }
  5643. setting_id = current.get("setting_id")
  5644. if setting_id:
  5645. command["print"]["setting_id"] = setting_id
  5646. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5647. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5648. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5649. """Reconcile developer_mode with the printer's own command-verification verdict.
  5650. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5651. control commands are being refused, so it outranks the probe in both
  5652. directions:
  5653. * present → developer_mode is definitively False, whatever the probe
  5654. concluded. The probe can only read the response to its own
  5655. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5656. instead, so the probe answers ENABLED while every print silently dies
  5657. (#2732).
  5658. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5659. probe, so a user who enables Developer Mode and restarts the printer
  5660. isn't stuck behind a verdict nothing would ever revisit.
  5661. A False that came from the probe or the ``fun`` bit is left alone — this
  5662. only ever unwinds its own latch.
  5663. """
  5664. if verify_failed:
  5665. if not self._dev_mode_from_hms:
  5666. logger.warning(
  5667. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5668. "rejecting control commands, so prints, temperature changes and filament "
  5669. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5670. self.serial_number,
  5671. HMS_MQTT_VERIFY_FAILED,
  5672. )
  5673. self._dev_mode_from_hms = True
  5674. self.state.developer_mode = False
  5675. return
  5676. if not self._dev_mode_from_hms:
  5677. return
  5678. logger.info(
  5679. "[%s] HMS %s cleared — re-probing developer mode",
  5680. self.serial_number,
  5681. HMS_MQTT_VERIFY_FAILED,
  5682. )
  5683. self._dev_mode_from_hms = False
  5684. self.state.developer_mode = None
  5685. self._dev_mode_probed = False
  5686. self._dev_mode_needs_probe = False
  5687. def _handle_dev_mode_probe_response(self, data: dict):
  5688. """Handle response to the developer mode probe command.
  5689. Sets developer_mode based on whether the printer accepted or rejected the command.
  5690. Three outcomes, not two. An explicit ``success`` proves commands are
  5691. accepted and an explicit verify-failure proves they are not, but anything
  5692. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5693. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5694. ``result`` at all, while refusing every control command and reporting
  5695. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5696. is what put ``developer_mode: pass`` in the support bundle of a printer
  5697. that had not accepted a command all day (#2732). Leaving it unknown makes
  5698. the connection diagnostic report ``skip``, which is the honest answer.
  5699. """
  5700. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5701. self._dev_mode_probe_failures = 0 # Reset on any response
  5702. result = data.get("result", "")
  5703. reason = data.get("reason", "")
  5704. if result == "failed" and "verify failed" in reason:
  5705. self.state.developer_mode = False
  5706. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5707. elif str(result).lower() == "success":
  5708. self.state.developer_mode = True
  5709. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5710. else:
  5711. # An HMS verdict already recorded here is real evidence; don't let an
  5712. # inconclusive probe response wipe it back to unknown.
  5713. if not self._dev_mode_from_hms:
  5714. self.state.developer_mode = None
  5715. logger.info(
  5716. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5717. "the printer neither confirmed nor refused the command",
  5718. self.serial_number,
  5719. result,
  5720. reason,
  5721. )
  5722. if self.on_state_change:
  5723. self.on_state_change(self.state)
  5724. def _request_version(self):
  5725. """Request firmware version info from printer."""
  5726. if self._client:
  5727. self._sequence_id += 1
  5728. message = {
  5729. "info": {
  5730. "sequence_id": str(self._sequence_id),
  5731. "command": "get_version",
  5732. }
  5733. }
  5734. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5735. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5736. def request_status_update(self) -> bool:
  5737. """Request a full status update from the printer (public API).
  5738. Sends both pushall and get_accessories commands to refresh all data
  5739. including nozzle hardware info.
  5740. Returns:
  5741. True if the request was sent, False if not connected.
  5742. """
  5743. if not self._client or not self.state.connected:
  5744. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5745. return False
  5746. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  5747. self._request_push_all()
  5748. # Note: get_accessories returns stale nozzle data on H2D.
  5749. # The correct nozzle data comes from push_status response.
  5750. return True
  5751. def _prime_kprofile_request(self):
  5752. """Send a priming K-profile request on connect.
  5753. Bambu printers often ignore the first K-profile request after connection,
  5754. so we send a dummy request on connect to 'prime' the system.
  5755. """
  5756. if self._client:
  5757. self._sequence_id += 1
  5758. command = {
  5759. "print": {
  5760. "command": "extrusion_cali_get",
  5761. "filament_id": "",
  5762. "nozzle_diameter": "0.4",
  5763. "sequence_id": str(self._sequence_id),
  5764. }
  5765. }
  5766. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  5767. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5768. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  5769. """Connect to the printer MQTT broker.
  5770. Args:
  5771. loop: The asyncio event loop to use for thread-safe callbacks.
  5772. If not provided, will try to get the running loop.
  5773. """
  5774. self._loop = loop
  5775. BambuMQTTClient._client_instance_counter += 1
  5776. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  5777. self._client = mqtt.Client(
  5778. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  5779. client_id=client_id,
  5780. protocol=mqtt.MQTTv311,
  5781. )
  5782. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  5783. # tracking (#1164). The default ceiling of 20 wedges sessions after
  5784. # ~16-20 cumulative commands; lifting it well above any realistic
  5785. # session count keeps QoS=1 working without changing wire-protocol
  5786. # behaviour across printer models.
  5787. self._client.max_inflight_messages_set(1000)
  5788. self._client.username_pw_set("bblp", self.access_code)
  5789. self._client.on_connect = self._on_connect
  5790. self._client.on_disconnect = self._on_disconnect
  5791. self._client.on_subscribe = self._on_subscribe
  5792. self._client.on_message = self._on_message
  5793. # TLS setup - Bambu uses self-signed certs
  5794. ssl_context = ssl.create_default_context()
  5795. ssl_context.check_hostname = False
  5796. ssl_context.verify_mode = ssl.CERT_NONE
  5797. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  5798. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  5799. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  5800. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  5801. # bare-metal installs whose build allows TLS 1.0.
  5802. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  5803. self._client.tls_set_context(ssl_context)
  5804. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  5805. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  5806. # Keepalive: paho sends PINGREQs at this interval, broker considers
  5807. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  5808. # real network loss (45s), not so aggressive that transient hiccups
  5809. # trigger false disconnects. Stale detection (60s no messages) handles
  5810. # the P1S/P1P firmware bug where the broker stops publishing but the
  5811. # TCP connection stays alive.
  5812. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  5813. self._client.loop_start()
  5814. def start_print(
  5815. self,
  5816. filename: str,
  5817. plate_id: int = 1,
  5818. ams_mapping: list[int] | None = None,
  5819. bed_levelling: str = "auto",
  5820. flow_cali: str = "auto",
  5821. vibration_cali: bool = True,
  5822. layer_inspect: bool = False,
  5823. timelapse: bool = False,
  5824. use_ams: bool = True,
  5825. nozzle_offset_cali: str = "auto",
  5826. nozzle_mapping: str | None = None,
  5827. nozzle_slot_extruders: str | None = None,
  5828. plate_uses_only_external: bool = False,
  5829. ):
  5830. """Start a print job on the printer.
  5831. The file should already be uploaded to the printer's root directory via FTP.
  5832. Args:
  5833. filename: Name of the uploaded file
  5834. plate_id: Plate number to print (default 1)
  5835. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  5836. Global tray ID = (ams_id * 4) + slot_id, external = 254
  5837. timelapse: Record timelapse video
  5838. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  5839. if the bed was levelled recently, matching BambuStudio).
  5840. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  5841. vibration_cali: Vibration compensation calibration
  5842. layer_inspect: First layer AI inspection
  5843. use_ams: Use AMS for automatic filament changes
  5844. plate_uses_only_external: The caller determined from the plate's
  5845. own filament list that it prints only from the spool holder;
  5846. use_ams=False then stands even if the mapping names a real
  5847. tray (one another plate of the file uses, #3087)
  5848. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  5849. (dual-nozzle printers only — silently ignored on single-nozzle).
  5850. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  5851. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  5852. AND the printer is dual-nozzle, parsed and injected as the
  5853. `nozzle_mapping` array on the dispatched project_file so the
  5854. firmware honours the user's slicer pick instead of falling
  5855. back to "last matching nozzle" auto-pick. Silently ignored
  5856. on single-nozzle printers.
  5857. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  5858. MQTT extruder indices, derived from the 3MF when no
  5859. BambuStudio capture exists (#2800). Consulted only on
  5860. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  5861. not already supply one; resolved here into physical rack
  5862. positions using the live `device.nozzle` state. When it
  5863. cannot be resolved the field is omitted and the firmware
  5864. picks, as it did before this existed.
  5865. Returns True when the start command was published, False otherwise
  5866. (not connected, or the printer is already busy — see the run-state
  5867. guard below).
  5868. """
  5869. # Never dispatch project_file to a printer that is not idle (#2598).
  5870. # This is the single publish choke point for every dispatch path — the
  5871. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  5872. # forwarded job all funnel through here — so one guard covers them all.
  5873. # The firmware rejects a start while busy with 0500_4004 ("Device is
  5874. # busy and cannot start a new task"), and on an A1 mini that error
  5875. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  5876. # start targets; only the active-print states are refused. (A
  5877. # transport-level QoS-1 replay on reconnect would bypass this guard,
  5878. # but the dispatch/watchdog reconnect path hard-resets the client with a
  5879. # fresh client_id, so paho has no inflight project_file to replay there.)
  5880. if self.state.state in _ACTIVE_PRINT_STATES:
  5881. logger.warning(
  5882. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  5883. self.serial_number,
  5884. self.state.state,
  5885. filename,
  5886. )
  5887. return False
  5888. if self._client and self.state.connected:
  5889. # Bambu print command format — matches Bambu Studio's format.
  5890. # The calibration/leveling fields (timelapse, bed_leveling,
  5891. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  5892. # every model. An earlier revision integer-encoded them for the H2
  5893. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  5894. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  5895. # sends plain booleans, and the integer encoding made the H2S
  5896. # silently skip flow-dynamics calibration (#1478). use_ams is the
  5897. # one field that genuinely must stay boolean: H2D Pro firmware
  5898. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  5899. # what actually caused the wrong-extruder routing behind #1386.
  5900. # Dual-nozzle routing for external spool (254 = deputy/left,
  5901. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  5902. # H2 firmware family but is single-nozzle, despite sharing serial
  5903. # prefix "094" with H2D. Prefer runtime detection from
  5904. # device.extruder.info (set in _handle_push_status); fall back to
  5905. # model name for the brief window after connect before push data
  5906. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  5907. # as the primary signal.
  5908. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  5909. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  5910. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  5911. ams_mapping2 = []
  5912. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  5913. # ams_mapping and relies on ams_mapping2 for external spool details.
  5914. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  5915. # with 0700_8012 "Failed to get AMS mapping table".
  5916. flat_ams_mapping = []
  5917. if ams_mapping is not None:
  5918. for tray_id in ams_mapping:
  5919. # Ensure tray_id is an integer (may be string from JSON)
  5920. tray_id = int(tray_id) if tray_id is not None else -1
  5921. if tray_id == -1:
  5922. # Unmapped filament slot
  5923. flat_ams_mapping.append(-1)
  5924. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  5925. elif tray_id >= 254:
  5926. # External/virtual spool. BambuStudio convention:
  5927. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  5928. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  5929. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  5930. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  5931. # for external spool, but BambuStudio always sends ams_id=255
  5932. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  5933. # firmware to target AMS tray 0 instead of external spool, leading
  5934. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  5935. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  5936. flat_ams_mapping.append(-1)
  5937. ext_ams_id = tray_id if is_dual_nozzle else 255
  5938. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  5939. elif tray_id >= 128:
  5940. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  5941. flat_ams_mapping.append(tray_id)
  5942. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  5943. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  5944. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  5945. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  5946. # — both CONFIRMED against the firmware's own mapping
  5947. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  5948. _wire_ams, _wire_slot, _ = _a2l
  5949. flat_ams_mapping.append(_wire_slot)
  5950. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  5951. else:
  5952. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  5953. ams_id = tray_id // 4
  5954. slot_id = tray_id % 4
  5955. flat_ams_mapping.append(tray_id)
  5956. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  5957. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  5958. # printers — the mapping is authoritative about whether this print
  5959. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  5960. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  5961. # H2S falls through here now (#1386): it is single-nozzle and was
  5962. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  5963. # without an AMS attached.
  5964. #
  5965. # Two symmetric corrections:
  5966. #
  5967. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  5968. # use_ams=True even if it arrived False. A print sent to a Virtual
  5969. # Printer is sliced against the VP, which advertises no AMS, so the
  5970. # slicer sends use_ams=false and that gets stamped on the queue item
  5971. # — but at dispatch the scheduler colour-matches a real printer and
  5972. # resolves a real AMS slot. Without this, the stale False reaches the
  5973. # printer, which ignores the mapped slot and aborts at layer 0 on the
  5974. # empty external spool ("not enough filament"). Diagnosed by
  5975. # @Sawtaytoes (#2595, PR #2596).
  5976. #
  5977. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  5978. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  5979. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  5980. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  5981. # status-load race that persisted [-1] (#2589) — and treating it as
  5982. # external silently started the print against an empty feed. A genuine
  5983. # external selection is >=254; unresolved is -1; a loaded tray is
  5984. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  5985. # (or is recomputed upstream) instead of silently going external, and
  5986. # never gets force-enabled by (a) either.
  5987. if ams_mapping and not is_dual_nozzle:
  5988. has_real_tray = any(t is not None and 0 <= int(t) <= 253 for t in ams_mapping)
  5989. all_external = all(t is None or int(t) >= 254 for t in ams_mapping)
  5990. # (Not when the scheduler worked out from the plate's own
  5991. # filament list that it prints only from the spool holder: a
  5992. # real tray here is then one another plate of the file uses.)
  5993. if has_real_tray and not use_ams and not plate_uses_only_external:
  5994. use_ams = True
  5995. logger.info(
  5996. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  5997. self.serial_number,
  5998. )
  5999. elif use_ams and all_external:
  6000. use_ams = False
  6001. logger.info(
  6002. "[%s] All filament slots use external spool — setting use_ams=False",
  6003. self.serial_number,
  6004. )
  6005. # (c) A single-nozzle printer that reported no AMS at all can only
  6006. # print from the spool holder, whatever the mapping says. With
  6007. # nothing set on the holder the matcher resolves no mapping, so
  6008. # neither (a) nor (b) ran and the print went out as use_ams=True,
  6009. # which the firmware refuses with 07FF_8012 "Failed to get AMS
  6010. # mapping table" (#3356). An empty raw_data["ams"] is the
  6011. # printer's own report of no AMS; a missing key means no AMS
  6012. # push has been handled yet (a reconnect), which changes nothing.
  6013. if use_ams and not is_dual_nozzle and self.state.raw_data.get("ams") == []:
  6014. use_ams = False
  6015. logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
  6016. # Unique per-submission identity fields. Hardcoded "0" values caused
  6017. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  6018. # continuations of the same job: the printer reuses gcode_start_time
  6019. # from the prior print with task_id=0, so observers latch onto a stale
  6020. # timestamp and report compounding durations on repeat replays (#1011).
  6021. # BambuStudio mints fresh IDs per submission; matching that behavior
  6022. # makes the printer emit a clean state-transition for each job.
  6023. # md5 is left empty — firmware historically accepts "" as "skip
  6024. # validation" (unlike Studio, we don't have the file's real md5 here
  6025. # without re-reading the upload, and sending a synthetic wrong digest
  6026. # risks activation of md5 verification on some firmwares).
  6027. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  6028. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  6029. # overflows and every submission ends up with the same task_id from
  6030. # the printer's perspective — the printer then treats a fresh dispatch
  6031. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  6032. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  6033. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  6034. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  6035. # Remember it so on_print_start can persist a restart-stable id on
  6036. # the archive even before the printer echoes subtask_id back (#1485).
  6037. self.last_dispatch_subtask_id = submission_id
  6038. self.last_start_refusal = None
  6039. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  6040. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  6041. # only if it wasn't done recently). The paired bool field is true
  6042. # only for the explicit "on" state — for "auto" the bool is false and
  6043. # the int carries the intent, exactly as BambuStudio's SelectMachine
  6044. # sends it. Unknown values fall back to auto.
  6045. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  6046. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  6047. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  6048. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  6049. command = {
  6050. "print": {
  6051. "sequence_id": "20000",
  6052. "command": "project_file",
  6053. "param": f"Metadata/plate_{plate_id}.gcode",
  6054. "url": f"ftp://{filename}",
  6055. "file": filename,
  6056. "md5": "",
  6057. "bed_type": "auto",
  6058. "timelapse": timelapse,
  6059. # bed_leveling stays a JSON bool (true only for "on") and
  6060. # auto_bed_leveling carries the tri-state int — the exact
  6061. # two-field shape BambuStudio sends. The int must stay a plain
  6062. # number, never quoted (#1478 boolean-family concern applies to
  6063. # the *_cali bools, not these companion ints).
  6064. "bed_leveling": bed_levelling == "on",
  6065. "auto_bed_leveling": bed_level_int,
  6066. "flow_cali": flow_cali == "on",
  6067. "vibration_cali": vibration_cali,
  6068. "layer_inspect": layer_inspect,
  6069. "use_ams": use_ams,
  6070. # No "cfg": it is the printer's device-config bitmask
  6071. # (auto-refill, detect-on-insert, chamber light, ...), not a
  6072. # per-job field — BambuStudio's PrintParams has no such
  6073. # member. We used to send "0"; firmware ignores it, but it
  6074. # comes straight back in the project_file ack (#3040).
  6075. # extrude_cali_flag gates flow-dynamics calibration:
  6076. # 0 = never, 1 = force every print, 2 = auto (run only if the
  6077. # filament wasn't calibrated recently). #1721 saw stage 8
  6078. # ("Calibrating dynamic flow") still queued when we send 2 —
  6079. # that is exactly the auto contract (the printer queues the
  6080. # stage and skips it at runtime if recent), not a bug, so 2 is
  6081. # the right wire value for "auto". off/on remain 0/1.
  6082. "extrude_cali_flag": flow_cali_int,
  6083. "extrude_cali_manual_mode": 0,
  6084. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  6085. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  6086. # again the auto contract, not a failure to suppress.
  6087. # BambuStudio exposes the toggle only for dual-nozzle
  6088. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  6089. # firmware never runs a calibration the head doesn't support.
  6090. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  6091. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  6092. "profile_id": "0",
  6093. "project_id": submission_id,
  6094. "subtask_id": submission_id,
  6095. "task_id": submission_id,
  6096. }
  6097. }
  6098. # P2S-specific parameter adjustments
  6099. # P2S printer doesn't support vibration calibration like X1/P1 series
  6100. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  6101. command["print"]["vibration_cali"] = False
  6102. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  6103. # Add AMS mapping if provided
  6104. if ams_mapping is not None:
  6105. command["print"]["ams_mapping"] = flat_ams_mapping
  6106. command["print"]["ams_mapping2"] = ams_mapping2
  6107. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  6108. # `nozzle_mapping` carries per-filament physical nozzle position
  6109. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  6110. # item; parse here so the wire ships an array, matching
  6111. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  6112. # defensively — single-nozzle firmwares would ignore the field
  6113. # but we err on the side of not emitting unrecognised fields. A
  6114. # parse failure is logged but never blocks the dispatch — the
  6115. # firmware will fall back to its auto-pick path, which is the
  6116. # pre-fix behaviour.
  6117. if is_dual_nozzle and nozzle_mapping:
  6118. try:
  6119. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  6120. except json.JSONDecodeError:
  6121. logger.warning(
  6122. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  6123. "project_file (firmware will auto-pick): %r",
  6124. self.serial_number,
  6125. nozzle_mapping,
  6126. )
  6127. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  6128. # never saw the job, so it can never override a real capture. The
  6129. # queue stores extruder indices per filament slot; the physical
  6130. # rack position they resolve to is only knowable here, because the
  6131. # mounted hotend can change between queueing and dispatch.
  6132. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  6133. try:
  6134. slot_extruders = json.loads(nozzle_slot_extruders)
  6135. except (json.JSONDecodeError, TypeError):
  6136. # TypeError covers a caller handing us the list itself
  6137. # rather than its JSON — the field is opaque by contract,
  6138. # and a print must not die over the difference.
  6139. slot_extruders = None
  6140. logger.warning(
  6141. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  6142. "omitting nozzle_mapping (firmware will auto-pick): %r",
  6143. self.serial_number,
  6144. nozzle_slot_extruders,
  6145. )
  6146. if isinstance(slot_extruders, list):
  6147. rack_nozzle_id = (
  6148. self.state.nozzle_rack_tar_id
  6149. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  6150. else self.state.nozzle_rack_src_id
  6151. )
  6152. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  6153. if resolved is None:
  6154. logger.info(
  6155. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  6156. "omitting nozzle_mapping so the firmware picks",
  6157. self.serial_number,
  6158. slot_extruders,
  6159. self.state.nozzle_rack_tar_id,
  6160. self.state.nozzle_rack_src_id,
  6161. )
  6162. else:
  6163. logger.info(
  6164. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  6165. self.serial_number,
  6166. slot_extruders,
  6167. rack_nozzle_id,
  6168. resolved,
  6169. )
  6170. command["print"]["nozzle_mapping"] = resolved
  6171. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  6172. # Remember this dispatch so its echo on the topic is recognised as
  6173. # ours rather than logged as a slicer's.
  6174. self._own_project_file_key = self._project_file_key(command["print"])
  6175. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6176. # Record what we dispatched so /cover can pick the right plate
  6177. # thumbnail even when the printer's gcode_file echo is just the
  6178. # 3MF filename without a plate path (#1166). Match the same
  6179. # subtask_name shape we send so the comparison in the cover route
  6180. # works against state.subtask_name reflected back via MQTT.
  6181. self.state.dispatched_plate_id = plate_id
  6182. self.state.dispatched_subtask = command["print"]["subtask_name"]
  6183. return True
  6184. else:
  6185. # Log why we couldn't send the command
  6186. if not self._client:
  6187. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  6188. elif not self.state.connected:
  6189. logger.error(
  6190. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  6191. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  6192. )
  6193. return False
  6194. def stop_print(self) -> bool:
  6195. """Stop the current print job."""
  6196. if self._client and self.state.connected:
  6197. command = {"print": {"command": "stop", "sequence_id": "0"}}
  6198. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6199. logger.info("[%s] Sent stop print command", self.serial_number)
  6200. return True
  6201. return False
  6202. def set_xcam_option(
  6203. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  6204. ) -> bool:
  6205. """Set an xcam (AI detection) option on the printer.
  6206. Args:
  6207. module_name: The xcam module to control (e.g., "spaghetti_detector",
  6208. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  6209. enabled: Whether to enable or disable the feature
  6210. print_halt: Whether to halt print on detection (only applies to some detectors)
  6211. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  6212. Returns:
  6213. True if command was sent, False if not connected
  6214. """
  6215. if not self._client or not self.state.connected:
  6216. return False
  6217. # auto_recovery_step_loss uses a different command format (print.print_option)
  6218. if module_name == "auto_recovery_step_loss":
  6219. return self._set_print_option("auto_recovery", enabled)
  6220. self._sequence_id += 1
  6221. # Build the xcam control command (exact OrcaSlicer format)
  6222. # Key findings from OrcaSlicer source:
  6223. # - Uses "xcam" wrapper (not "print")
  6224. # - print_halt is ALWAYS true (legacy protocol requirement)
  6225. # - Both "control" and "enable" are set to the same value
  6226. # - halt_print_sensitivity controls actual halt behavior
  6227. command = {
  6228. "xcam": {
  6229. "command": "xcam_control_set",
  6230. "sequence_id": str(self._sequence_id),
  6231. "module_name": module_name,
  6232. "control": enabled,
  6233. "enable": enabled, # old protocol compatibility
  6234. "print_halt": True, # ALWAYS true per OrcaSlicer
  6235. }
  6236. }
  6237. # Only add sensitivity if not "never_halt"
  6238. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  6239. # The module_name field determines which detector's sensitivity is being set
  6240. if sensitivity and sensitivity != "never_halt":
  6241. command["xcam"]["halt_print_sensitivity"] = sensitivity
  6242. command_json = json.dumps(command)
  6243. self._client.publish(self.topic_publish, command_json, qos=1)
  6244. logger.debug(
  6245. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  6246. )
  6247. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  6248. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  6249. # This prevents stale MQTT data from immediately overwriting our change
  6250. self._xcam_hold_start[module_name] = time.time()
  6251. # Update local state immediately for responsive UI
  6252. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  6253. # When spaghetti_detector sensitivity is changed, pileup also changes
  6254. if module_name == "spaghetti_detector":
  6255. self.state.print_options.spaghetti_detector = enabled
  6256. self.state.print_options.print_halt = print_halt
  6257. if sensitivity and sensitivity != "never_halt":
  6258. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  6259. self.state.print_options.halt_print_sensitivity = sensitivity
  6260. self.state.print_options.pileup_sensitivity = sensitivity
  6261. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  6262. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  6263. elif module_name == "first_layer_inspector":
  6264. self.state.print_options.first_layer_inspector = enabled
  6265. elif module_name == "printing_monitor":
  6266. self.state.print_options.printing_monitor = enabled
  6267. elif module_name == "buildplate_marker_detector":
  6268. self.state.print_options.buildplate_marker_detector = enabled
  6269. elif module_name == "allow_skip_parts":
  6270. self.state.print_options.allow_skip_parts = enabled
  6271. elif module_name == "pileup_detector":
  6272. self.state.print_options.pileup_detector = enabled
  6273. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  6274. elif module_name == "clump_detector":
  6275. self.state.print_options.nozzle_clumping_detector = enabled
  6276. if sensitivity and sensitivity != "never_halt":
  6277. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  6278. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  6279. elif module_name == "airprint_detector":
  6280. self.state.print_options.airprint_detector = enabled
  6281. if sensitivity and sensitivity != "never_halt":
  6282. self.state.print_options.airprint_sensitivity = sensitivity
  6283. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  6284. elif module_name == "auto_recovery_step_loss":
  6285. self.state.print_options.auto_recovery_step_loss = enabled
  6286. return True
  6287. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  6288. """Set a print option using the print.print_option command.
  6289. This is different from xcam_control_set and is used for options like:
  6290. - auto_recovery
  6291. - air_print_detect
  6292. - filament_tangle_detect
  6293. - nozzle_blob_detect
  6294. - sound_enable
  6295. Args:
  6296. option_name: The option to control (e.g., "auto_recovery")
  6297. enabled: Whether to enable or disable the option
  6298. Returns:
  6299. True if command was sent, False if not connected
  6300. """
  6301. if not self._client or not self.state.connected:
  6302. return False
  6303. self._sequence_id += 1
  6304. command = {
  6305. "print": {
  6306. "command": "print_option",
  6307. "sequence_id": str(self._sequence_id),
  6308. option_name: enabled,
  6309. }
  6310. }
  6311. command_json = json.dumps(command)
  6312. self._client.publish(self.topic_publish, command_json, qos=1)
  6313. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  6314. # Set hold timer
  6315. hold_key = f"print_option_{option_name}"
  6316. self._xcam_hold_start[hold_key] = time.time()
  6317. # Update local state immediately
  6318. if option_name == "auto_recovery":
  6319. self.state.print_options.auto_recovery_step_loss = enabled
  6320. elif option_name == "auto_switch_filament":
  6321. self.state.ams_filament_backup = enabled
  6322. return True
  6323. def set_ams_filament_backup(self, enabled: bool) -> bool:
  6324. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  6325. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  6326. shape from H2D capture 2026-06-20.
  6327. """
  6328. return self._set_print_option("auto_switch_filament", enabled)
  6329. def start_calibration(
  6330. self,
  6331. bed_leveling: bool = False,
  6332. vibration: bool = False,
  6333. motor_noise: bool = False,
  6334. nozzle_offset: bool = False,
  6335. high_temp_heatbed: bool = False,
  6336. ) -> bool:
  6337. """Start printer calibration with selected options.
  6338. Args:
  6339. bed_leveling: Run bed leveling calibration
  6340. vibration: Run vibration compensation calibration
  6341. motor_noise: Run motor noise cancellation calibration
  6342. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  6343. high_temp_heatbed: Run high-temperature heatbed calibration
  6344. Returns:
  6345. True if command was sent, False if not connected
  6346. """
  6347. if not self._client or not self.state.connected:
  6348. return False
  6349. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  6350. # Bit 0: xcam_cali (not exposed in UI)
  6351. # Bit 1: bed_leveling
  6352. # Bit 2: vibration
  6353. # Bit 3: motor_noise
  6354. # Bit 4: nozzle_cali
  6355. # Bit 5: bed_cali (high-temp heatbed)
  6356. # Bit 6: clumppos_cali (not exposed in UI)
  6357. option = 0
  6358. if bed_leveling:
  6359. option |= 1 << 1
  6360. if vibration:
  6361. option |= 1 << 2
  6362. if motor_noise:
  6363. option |= 1 << 3
  6364. if nozzle_offset:
  6365. option |= 1 << 4
  6366. if high_temp_heatbed:
  6367. option |= 1 << 5
  6368. if option == 0:
  6369. logger.warning("[%s] No calibration options selected", self.serial_number)
  6370. return False
  6371. self._sequence_id += 1
  6372. command = {
  6373. "print": {
  6374. "command": "calibration",
  6375. "sequence_id": str(self._sequence_id),
  6376. "option": option,
  6377. }
  6378. }
  6379. command_json = json.dumps(command)
  6380. self._client.publish(self.topic_publish, command_json, qos=1)
  6381. logger.info(
  6382. f"[{self.serial_number}] Starting calibration: "
  6383. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  6384. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  6385. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  6386. )
  6387. return True
  6388. def disconnect(self, timeout: float = 0):
  6389. """Disconnect from the printer.
  6390. Waits up to *timeout* for paho to report the disconnect, then lets the
  6391. client go without joining its network thread — the callers are route
  6392. handlers (printer edited, deleted, disconnected by hand) running on the
  6393. asyncio thread, and that join has no bound (#3068)."""
  6394. if self._client:
  6395. old_client = self._client
  6396. self._disconnection_event = threading.Event()
  6397. old_client.disconnect()
  6398. # The callback that sets this fires on paho's thread, so it has to
  6399. # be given its window before retire_paho_client detaches it.
  6400. self._disconnection_event.wait(timeout=timeout)
  6401. self._client = None
  6402. retire_paho_client(old_client, self.serial_number)
  6403. self.state.connected = False
  6404. # Deliberately no on_state_change here. paho's disconnect callback
  6405. # used to land during the join, but `_on_disconnect` suppresses
  6406. # itself for a clean disconnect of a printer that reported within
  6407. # the last 10s -- which is every healthy printer -- so a
  6408. # hand-disconnected printer never broadcast one. Announcing it now
  6409. # would fire the connected→disconnected edge in
  6410. # `on_printer_status_change` and notify the user their printer went
  6411. # offline a minute after they disconnected it on purpose (#1752).
  6412. # The callers drop the client from the manager anyway, so the next
  6413. # status read already shows it gone.
  6414. def enable_logging(self, enabled: bool = True):
  6415. """Enable or disable MQTT message logging."""
  6416. self._logging_enabled = enabled
  6417. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6418. def get_logs(self) -> list[MQTTLogEntry]:
  6419. """Get all logged MQTT messages."""
  6420. return list(self._message_log)
  6421. def clear_logs(self):
  6422. """Clear the message log."""
  6423. self._message_log.clear()
  6424. @property
  6425. def logging_enabled(self) -> bool:
  6426. """Check if logging is enabled."""
  6427. return self._logging_enabled
  6428. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6429. """Register a handler invoked for every incoming MQTT message.
  6430. Used by the VP MQTT bridge to republish the printer's report pushes to
  6431. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6432. on paho's network thread and must not block; exceptions are caught.
  6433. """
  6434. if handler not in self._raw_message_handlers:
  6435. self._raw_message_handlers.append(handler)
  6436. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6437. """Unregister a previously-registered raw-message handler."""
  6438. try:
  6439. self._raw_message_handlers.remove(handler)
  6440. except ValueError:
  6441. pass
  6442. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6443. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6444. Used by the VP MQTT bridge to forward slicer-originated commands without
  6445. giving it one of our own sequence ids. Returns False if the
  6446. underlying paho client isn't ready.
  6447. """
  6448. if self._client is None:
  6449. return False
  6450. try:
  6451. info = self._client.publish(topic, payload, qos=qos)
  6452. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6453. except Exception:
  6454. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6455. return False
  6456. def send_drying_command(
  6457. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6458. ):
  6459. """Send AMS drying start/stop command.
  6460. Args:
  6461. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6462. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6463. duration: Drying duration in hours
  6464. mode: 1=start, 0=stop
  6465. filament: Filament type string (e.g. "PLA", "PETG")
  6466. rotate_tray: Whether to rotate the spool during drying for even heat
  6467. """
  6468. if not self._client:
  6469. return False
  6470. self._sequence_id += 1
  6471. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6472. # not actually support drying, but keep the translation consistent). The
  6473. # _drying_targets dict below stays keyed by the normalised id so the
  6474. # on_drying_complete callback matches the telemetry.
  6475. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6476. command = {
  6477. "print": {
  6478. "sequence_id": str(self._sequence_id),
  6479. "command": "ams_filament_drying",
  6480. "ams_id": wire_ams_id,
  6481. "temp": temp,
  6482. "cooling_temp": 20 if mode == 1 else 0,
  6483. "duration": duration,
  6484. "humidity": 0,
  6485. "mode": mode,
  6486. "rotate_tray": rotate_tray,
  6487. "filament": filament,
  6488. "close_power_conflict": False,
  6489. }
  6490. }
  6491. # Log the full wire JSON at INFO so support bundles capture exactly
  6492. # what we sent — needed to diagnose silent rejections (#1447) where
  6493. # the printer ACKs the command but never starts/stops drying.
  6494. # Paired with the ams_filament_drying response-payload INFO log so
  6495. # both halves of the conversation land in the bundle by default.
  6496. wire_json = json.dumps(command)
  6497. self._client.publish(self.topic_publish, wire_json, qos=1)
  6498. logger.info(
  6499. "[%s] Sent ams_filament_drying: %s",
  6500. self.serial_number,
  6501. wire_json,
  6502. )
  6503. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6504. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6505. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6506. # say how much of the requested time the firmware actually ran (#2770).
  6507. if mode == 1:
  6508. self._drying_targets[ams_id] = {
  6509. "filament": filament or "",
  6510. "temp": int(temp),
  6511. "duration_hours": int(duration),
  6512. }
  6513. self._drying_stops_sent.discard(ams_id)
  6514. # A start sent while a cycle is still counting down replaces it
  6515. # without dry_time passing through 0; begin a fresh record so the
  6516. # new target and length are the ones reported (#2863).
  6517. self._dry_cycles.pop(ams_id, None)
  6518. else:
  6519. self._drying_targets.pop(ams_id, None)
  6520. # Remember that this cycle's end is ours, so the cycle-end log
  6521. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6522. # stop always ends the cycle far short of its duration, which is
  6523. # otherwise indistinguishable from the firmware abandoning it.
  6524. self._drying_stops_sent.add(ams_id)
  6525. return True
  6526. @staticmethod
  6527. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6528. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6529. The printer reports ``nozzle_diameter`` **only on the response
  6530. envelope** — the per-filament entries carry just setting_id,
  6531. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6532. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6533. single-nozzle printers regardless of the installed nozzle (#1748),
  6534. which broke the K-Profiles display and, worse, the cali_idx cascade
  6535. in the inventory/Spoolman assign paths that matches on
  6536. nozzle_diameter. Fall back to the envelope value instead, and only
  6537. to "0.4" when the envelope has none either.
  6538. ``or`` rather than a dict default on purpose: it also covers an entry
  6539. that carries the key with an empty value, and stops ``str()`` turning
  6540. a missing envelope value into the literal "None".
  6541. """
  6542. profiles: list[KProfile] = []
  6543. for i, f in enumerate(filaments):
  6544. if not isinstance(f, dict):
  6545. continue
  6546. try:
  6547. profiles.append(
  6548. KProfile(
  6549. # cali_idx is the actual slot/calibration index from the printer
  6550. slot_id=f.get("cali_idx", i),
  6551. extruder_id=int(f.get("extruder_id", 0)),
  6552. nozzle_id=str(f.get("nozzle_id", "")),
  6553. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6554. filament_id=str(f.get("filament_id", "")),
  6555. name=str(f.get("name", "")),
  6556. k_value=str(f.get("k_value", "0.000000")),
  6557. n_coef=str(f.get("n_coef", "0.000000")),
  6558. ams_id=int(f.get("ams_id", 0)),
  6559. tray_id=int(f.get("tray_id", -1)),
  6560. setting_id=f.get("setting_id"),
  6561. )
  6562. )
  6563. except (ValueError, TypeError) as e:
  6564. # Skip malformed entries; the remaining profiles stay usable.
  6565. # Unsolicited broadcasts arrive constantly, so only a response
  6566. # someone is actually waiting on is worth a warning.
  6567. if log_errors:
  6568. logger.warning("Failed to parse K-profile: %s", e)
  6569. else:
  6570. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6571. return profiles
  6572. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6573. """File one calibration-table response under its nozzle diameter.
  6574. ``response_nozzle`` names the table the printer just sent, so that
  6575. bucket is replaced wholesale and every other one is left alone. When
  6576. the envelope carries no diameter, fall back to the diameters the parsed
  6577. profiles claim for themselves — and if there are none of those either,
  6578. keep what we have rather than dropping a table we cannot attribute.
  6579. ``state.kprofiles`` stays a flat list because that is what its readers
  6580. expect; the three assign paths already filter it by ``nozzle_diameter``
  6581. and were quietly finding nothing whenever the last response happened to
  6582. be for a different nozzle.
  6583. """
  6584. buckets: dict[str, list] = {}
  6585. if response_nozzle:
  6586. buckets[str(response_nozzle)] = list(profiles)
  6587. else:
  6588. for profile in profiles:
  6589. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6590. if not buckets:
  6591. return
  6592. self._kprofiles_by_nozzle.update(buckets)
  6593. self.state.kprofiles = [
  6594. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6595. ]
  6596. def _handle_kprofile_response(self, data: dict):
  6597. """Handle K-profile response from printer."""
  6598. response_nozzle = data.get("nozzle_diameter")
  6599. response_seq_id = str(data.get("sequence_id", ""))
  6600. filaments = data.get("filaments", [])
  6601. # Snapshot the map: the asyncio thread adds and removes entries while
  6602. # this MQTT callback thread walks it.
  6603. pending = dict(self._pending_kprofile_requests)
  6604. request = pending.get(response_seq_id)
  6605. if request is None and pending:
  6606. # Firmware that doesn't echo our sequence_id still has to be
  6607. # served, so fall back to the pre-#1748 rule of matching on the
  6608. # nozzle size. Only requests still waiting are eligible, and the
  6609. # sequence_id lookup above has already claimed any response that
  6610. # identifies itself, so this can no longer hand request A's
  6611. # answer to request B when both are in flight.
  6612. request = next(
  6613. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6614. None,
  6615. )
  6616. if pending:
  6617. logger.info(
  6618. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6619. self.serial_number,
  6620. response_nozzle,
  6621. response_seq_id or "?",
  6622. len(filaments),
  6623. request is not None,
  6624. )
  6625. if request is None and pending:
  6626. # A request is outstanding and this isn't its answer. The printer
  6627. # broadcasts extrusion_cali_get unsolicited, so letting this
  6628. # through would replace state.kprofiles with another nozzle's
  6629. # profiles while the caller is still waiting.
  6630. logger.debug(
  6631. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6632. self.serial_number,
  6633. response_nozzle,
  6634. response_seq_id or "?",
  6635. )
  6636. return
  6637. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6638. self._store_kprofiles(profiles, response_nozzle)
  6639. if request is None:
  6640. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6641. # nobody to wake. Worth a line — this is the printer answering
  6642. # somebody else (BambuStudio queries the same report topic), and
  6643. # until it was bucketed by nozzle it was also the quietest way for
  6644. # the AMS card's K values to change underneath us.
  6645. logger.debug(
  6646. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6647. self.serial_number,
  6648. response_nozzle or "?",
  6649. len(profiles),
  6650. )
  6651. return
  6652. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6653. request["profiles"] = profiles
  6654. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6655. # in a different thread than the event loop.
  6656. event = request["event"]
  6657. if self._loop and self._loop.is_running():
  6658. self._loop.call_soon_threadsafe(event.set)
  6659. else:
  6660. # Fallback for when loop is not available
  6661. event.set()
  6662. async def get_kprofiles(
  6663. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6664. ) -> list[KProfile]:
  6665. """Request K-profiles from the printer with retry logic.
  6666. Bambu printers sometimes ignore the first K-profile request, so we
  6667. implement retry logic to ensure reliable retrieval.
  6668. Args:
  6669. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6670. timeout: Timeout in seconds to wait for each response attempt
  6671. max_retries: Maximum number of retry attempts
  6672. Returns:
  6673. List of KProfile objects; empty when the printer has none for
  6674. the nozzle.
  6675. Raises:
  6676. KProfileReadError: not connected, or no answer to any attempt.
  6677. Returning an empty list made that a printer without profiles
  6678. (#3404).
  6679. """
  6680. if not self._client or not self.state.connected:
  6681. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6682. raise KProfileReadError("Printer not connected")
  6683. # Capture current event loop for thread-safe callback
  6684. try:
  6685. self._loop = asyncio.get_running_loop()
  6686. except RuntimeError:
  6687. logger.warning("[%s] No running event loop", self.serial_number)
  6688. raise KProfileReadError("No running event loop") from None
  6689. for attempt in range(max_retries):
  6690. # Register this attempt under its own sequence_id so a concurrent
  6691. # request for a different nozzle size can't consume its response
  6692. # (#1748) — the pending map is keyed by exactly the id we send.
  6693. self._sequence_id += 1
  6694. seq_id = str(self._sequence_id)
  6695. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6696. self._pending_kprofile_requests[seq_id] = request
  6697. # Send the command with nozzle_diameter filter
  6698. command = {
  6699. "print": {
  6700. "command": "extrusion_cali_get",
  6701. "filament_id": "",
  6702. "nozzle_diameter": nozzle_diameter,
  6703. "sequence_id": seq_id,
  6704. }
  6705. }
  6706. logger.info(
  6707. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6708. )
  6709. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6710. # Wait for the response (the handler matches it back to this entry)
  6711. try:
  6712. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6713. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6714. profiles = request["profiles"] or []
  6715. logger.info(
  6716. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6717. )
  6718. return profiles
  6719. except TimeoutError:
  6720. logger.warning(
  6721. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  6722. )
  6723. if attempt < max_retries - 1:
  6724. # Brief delay before retry
  6725. await asyncio.sleep(0.5)
  6726. finally:
  6727. self._pending_kprofile_requests.pop(seq_id, None)
  6728. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  6729. raise KProfileReadError("The printer did not answer the K-profile request")
  6730. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  6731. """Publish a K-profile write and arm its ack slot.
  6732. Registration happens before the publish because the printer answers in
  6733. well under a second — measured at 70-150ms — which is comfortably
  6734. before an async caller gets back to awaiting.
  6735. """
  6736. self._pending_cali_acks[seq_id] = None
  6737. try:
  6738. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6739. except Exception:
  6740. self._pending_cali_acks.pop(seq_id, None)
  6741. raise
  6742. return True
  6743. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  6744. """Wait for the printer's verdict on a K-profile write.
  6745. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  6746. explicitly said ``result: "fail"`` — a timeout returns True with a
  6747. detail string, because "no answer" is not evidence of rejection and
  6748. older firmware may not answer at all. Callers that need certainty read
  6749. the calibration table back.
  6750. Polled rather than event-driven on purpose: the ack is filled in by the
  6751. MQTT callback thread, and polling a dict costs one lookup every 50ms
  6752. for at most a few hundred milliseconds, against the cross-thread
  6753. event plumbing it would otherwise take.
  6754. """
  6755. deadline = time.monotonic() + timeout
  6756. try:
  6757. while time.monotonic() < deadline:
  6758. ack = self._pending_cali_acks.get(seq_id)
  6759. if ack is not None:
  6760. result = str(ack.get("result", "")).lower()
  6761. reason = str(ack.get("reason", "") or "")
  6762. if result == "fail":
  6763. return (False, reason or "printer reported failure")
  6764. return (True, reason)
  6765. await asyncio.sleep(0.05)
  6766. finally:
  6767. self._pending_cali_acks.pop(seq_id, None)
  6768. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  6769. return (True, CALI_ACK_UNCONFIRMED)
  6770. def set_kprofile(
  6771. self,
  6772. filament_id: str,
  6773. name: str,
  6774. k_value: str,
  6775. nozzle_diameter: str = "0.4",
  6776. nozzle_id: str = "HS00-0.4",
  6777. extruder_id: int = 0,
  6778. setting_id: str | None = None,
  6779. slot_id: int = 0,
  6780. cali_idx: int | None = None,
  6781. ) -> str | None:
  6782. """Set/update a K-profile on the printer.
  6783. Args:
  6784. filament_id: Bambu filament identifier
  6785. name: Profile name
  6786. k_value: Pressure advance value (e.g., "0.020000")
  6787. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6788. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  6789. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6790. setting_id: Existing setting ID for updates, None for new
  6791. slot_id: Calibration index (cali_idx) for the profile
  6792. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  6793. Returns:
  6794. The sequence_id the command was sent under, so the caller can
  6795. await the printer's verdict via await_cali_ack. None if the
  6796. command could not be sent.
  6797. """
  6798. if not self._client or not self.state.connected:
  6799. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  6800. return None
  6801. self._sequence_id += 1
  6802. seq_id = str(self._sequence_id)
  6803. # Build the filament entry - printer uses cali_idx for profile identification
  6804. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  6805. # For edits, use the provided cali_idx or slot_id
  6806. if cali_idx is not None:
  6807. effective_cali_idx = cali_idx
  6808. else:
  6809. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6810. # Generate a setting_id for new profiles (required by printer)
  6811. # Format: "PF" + 17 random digits
  6812. import random
  6813. if not setting_id and slot_id == 0:
  6814. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6815. filament_entry = {
  6816. "ams_id": 0,
  6817. "cali_idx": effective_cali_idx,
  6818. "extruder_id": extruder_id,
  6819. "filament_id": filament_id,
  6820. "k_value": k_value,
  6821. "n_coef": "0.000000",
  6822. "name": name,
  6823. "nozzle_diameter": nozzle_diameter,
  6824. "nozzle_id": nozzle_id,
  6825. "setting_id": setting_id if setting_id else "",
  6826. # 0, not -1. Single-nozzle firmware validates this field and
  6827. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  6828. # applying the write anyway, so the rejection looked like noise.
  6829. # Measured on an X1C: flipping only this value turns the ack into
  6830. # `success` (#2718). BambuStudio always sends a real tray_id and
  6831. # defaults it to 0 for a manually entered profile.
  6832. "tray_id": 0,
  6833. }
  6834. command = {
  6835. "print": {
  6836. "command": "extrusion_cali_set",
  6837. "filaments": [filament_entry],
  6838. "nozzle_diameter": nozzle_diameter,
  6839. "sequence_id": seq_id,
  6840. }
  6841. }
  6842. command_json = json.dumps(command)
  6843. logger.info(
  6844. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  6845. )
  6846. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  6847. self._publish_cali_write(command, seq_id)
  6848. return seq_id
  6849. def set_kprofiles_batch(
  6850. self,
  6851. profiles: list[dict],
  6852. nozzle_diameter: str = "0.4",
  6853. ) -> str | None:
  6854. """Set multiple K-profiles in a single command (for dual-nozzle).
  6855. Args:
  6856. profiles: List of profile dicts, each with:
  6857. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  6858. nozzle_diameter: Common nozzle diameter for all profiles
  6859. Returns:
  6860. The sequence_id the command was sent under (see set_kprofile),
  6861. or None if it could not be sent.
  6862. """
  6863. if not self._client or not self.state.connected:
  6864. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  6865. return None
  6866. import random
  6867. self._sequence_id += 1
  6868. seq_id = str(self._sequence_id)
  6869. filament_entries = []
  6870. for p in profiles:
  6871. slot_id = p.get("slot_id", 0)
  6872. cali_idx = p.get("cali_idx")
  6873. if cali_idx is not None:
  6874. effective_cali_idx = cali_idx
  6875. else:
  6876. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6877. setting_id = p.get("setting_id")
  6878. if not setting_id and slot_id == 0:
  6879. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6880. filament_entries.append(
  6881. {
  6882. "ams_id": 0,
  6883. "cali_idx": effective_cali_idx,
  6884. "extruder_id": p.get("extruder_id", 0),
  6885. "filament_id": p.get("filament_id", ""),
  6886. "k_value": p.get("k_value", "0.020000"),
  6887. "n_coef": "0.000000",
  6888. "name": p.get("name", ""),
  6889. "nozzle_diameter": nozzle_diameter,
  6890. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  6891. "setting_id": setting_id if setting_id else "",
  6892. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  6893. # single-nozzle firmware even though the write lands (#2718).
  6894. "tray_id": 0,
  6895. }
  6896. )
  6897. command = {
  6898. "print": {
  6899. "command": "extrusion_cali_set",
  6900. "filaments": filament_entries,
  6901. "nozzle_diameter": nozzle_diameter,
  6902. "sequence_id": seq_id,
  6903. }
  6904. }
  6905. command_json = json.dumps(command)
  6906. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  6907. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  6908. self._publish_cali_write(command, seq_id)
  6909. return seq_id
  6910. def delete_kprofile(
  6911. self,
  6912. cali_idx: int,
  6913. filament_id: str,
  6914. nozzle_id: str,
  6915. nozzle_diameter: str = "0.4",
  6916. extruder_id: int = 0,
  6917. setting_id: str | None = None,
  6918. ) -> str | None:
  6919. """Delete a K-profile from the printer.
  6920. Args:
  6921. cali_idx: The calibration index (slot_id) of the profile to delete
  6922. filament_id: Bambu filament identifier
  6923. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  6924. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6925. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6926. setting_id: Unique setting identifier (for X1C series)
  6927. Returns:
  6928. The sequence_id the command was sent under (see set_kprofile),
  6929. or None if it could not be sent.
  6930. """
  6931. if not self._client or not self.state.connected:
  6932. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  6933. return None
  6934. self._sequence_id += 1
  6935. seq_id = str(self._sequence_id)
  6936. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  6937. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  6938. # Prefer runtime detection from device.extruder.info; fall back to
  6939. # model name. H2S is single-nozzle but shares serial prefix "094" with
  6940. # H2D, so a prefix-only check misclassified it (#1386).
  6941. from backend.app.utils.printer_models import is_dual_nozzle_model
  6942. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6943. if is_dual_nozzle:
  6944. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  6945. command = {
  6946. "print": {
  6947. "command": "extrusion_cali_del",
  6948. "sequence_id": seq_id,
  6949. "extruder_id": extruder_id,
  6950. "nozzle_id": nozzle_id,
  6951. "filament_id": filament_id,
  6952. "cali_idx": cali_idx,
  6953. "nozzle_diameter": nozzle_diameter,
  6954. }
  6955. }
  6956. else:
  6957. # X1C/P1/A1 format: include all fields like the set command
  6958. # The delete command structure should match what set uses
  6959. command = {
  6960. "print": {
  6961. "command": "extrusion_cali_del",
  6962. "sequence_id": seq_id,
  6963. "filament_id": filament_id,
  6964. "cali_idx": cali_idx,
  6965. "setting_id": setting_id if setting_id else "",
  6966. "nozzle_diameter": nozzle_diameter,
  6967. "nozzle_id": nozzle_id,
  6968. "extruder_id": extruder_id,
  6969. }
  6970. }
  6971. command_json = json.dumps(command)
  6972. logger.info(
  6973. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  6974. )
  6975. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  6976. # QoS 1 for reliable delivery (at least once)
  6977. self._publish_cali_write(command, seq_id)
  6978. return seq_id
  6979. # =========================================================================
  6980. # Printer Control Commands
  6981. # =========================================================================
  6982. def pause_print(self) -> bool:
  6983. """Pause the current print job."""
  6984. if not self._client or not self.state.connected:
  6985. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  6986. return False
  6987. command = {"print": {"command": "pause", "sequence_id": "0"}}
  6988. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6989. logger.info("[%s] Sent pause print command", self.serial_number)
  6990. return True
  6991. def resume_print(self) -> bool:
  6992. """Resume a paused print job."""
  6993. if not self._client or not self.state.connected:
  6994. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  6995. return False
  6996. command = {"print": {"command": "resume", "sequence_id": "0"}}
  6997. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6998. logger.info("[%s] Sent resume print command", self.serial_number)
  6999. return True
  7000. def clear_hms_errors(self) -> bool:
  7001. """Clear HMS/print errors on the printer and locally."""
  7002. if not self._client or not self.state.connected:
  7003. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  7004. return False
  7005. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  7006. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7007. self.state.hms_errors = []
  7008. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  7009. return True
  7010. def _handle_skip_objects_answer(self, print_data: dict) -> None:
  7011. """The printer's answer to skip_objects: a refusal is logged and the
  7012. objects are no longer shown as skipped."""
  7013. obj_list = self._skip_commands.pop(str(print_data.get("sequence_id", "")), None)
  7014. result = str(print_data.get("result", "") or "").lower()
  7015. if obj_list is None or result in ("", "success"):
  7016. return
  7017. logger.error(
  7018. "[%s] Printer refused skipping objects %s: result=%s reason=%s",
  7019. self.serial_number,
  7020. obj_list,
  7021. print_data.get("result"),
  7022. print_data.get("reason", ""),
  7023. )
  7024. for oid in obj_list:
  7025. self._unconfirmed_skips.pop(oid, None)
  7026. self.state.skipped_objects = [oid for oid in self.state.skipped_objects if oid not in obj_list]
  7027. def _check_unconfirmed_skips(self) -> None:
  7028. """Log, once, a skip the printer's s_obj list never showed."""
  7029. if not self._unconfirmed_skips:
  7030. return
  7031. if self.state.state not in ("RUNNING", "PAUSE"):
  7032. # The print ended; its skips are moot.
  7033. self._unconfirmed_skips.clear()
  7034. self._skip_commands.clear()
  7035. return
  7036. now = time.monotonic()
  7037. # A copy: skip_objects adds to the dict from the event loop while this
  7038. # runs on the MQTT thread.
  7039. pending = list(self._unconfirmed_skips.items())
  7040. expired = [oid for oid, sent_at in pending if now - sent_at > SKIP_CONFIRM_TIMEOUT_S]
  7041. if not expired:
  7042. return
  7043. logger.error(
  7044. "[%s] Printer did not confirm skipping objects %s within %.0fs; they may still be printed",
  7045. self.serial_number,
  7046. sorted(expired),
  7047. SKIP_CONFIRM_TIMEOUT_S,
  7048. )
  7049. for oid in expired:
  7050. self._unconfirmed_skips.pop(oid, None)
  7051. def skip_objects(self, object_ids: list[int]) -> bool:
  7052. """Skip specific objects during a print.
  7053. This command tells the printer to skip printing the specified objects.
  7054. The object IDs come from the slice_info.config file in the 3MF.
  7055. Args:
  7056. object_ids: List of identify_id values from slice_info.config
  7057. Returns:
  7058. True if command was sent, False otherwise
  7059. """
  7060. if not self._client or not self.state.connected:
  7061. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  7062. return False
  7063. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  7064. logger.warning(
  7065. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  7066. )
  7067. return False
  7068. if not object_ids:
  7069. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  7070. return False
  7071. # Validate all IDs are integers
  7072. try:
  7073. obj_list = [int(oid) for oid in object_ids]
  7074. except (ValueError, TypeError) as e:
  7075. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  7076. return False
  7077. self._sequence_id += 1
  7078. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  7079. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7080. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  7081. sent_at = time.monotonic()
  7082. for oid in obj_list:
  7083. self._unconfirmed_skips.setdefault(oid, sent_at)
  7084. self._skip_commands[str(self._sequence_id)] = obj_list
  7085. # Track skipped objects in state
  7086. for oid in obj_list:
  7087. if oid not in self.state.skipped_objects:
  7088. self.state.skipped_objects.append(oid)
  7089. return True
  7090. def send_gcode(self, gcode: str) -> bool:
  7091. """Send G-code command(s) to the printer.
  7092. Multiple commands can be separated by newlines.
  7093. Args:
  7094. gcode: G-code command(s) to send
  7095. Returns:
  7096. True if command was sent, False otherwise
  7097. """
  7098. if not self._client or not self.state.connected:
  7099. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  7100. return False
  7101. self._sequence_id += 1
  7102. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  7103. # Use QoS 1 for reliable delivery (at least once)
  7104. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7105. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  7106. return True
  7107. def set_bed_temperature(self, target: int) -> bool:
  7108. """Set the bed target temperature.
  7109. Args:
  7110. target: Target temperature in Celsius (0 to turn off)
  7111. Returns:
  7112. True if command was sent, False otherwise
  7113. """
  7114. return self.send_gcode(f"M140 S{target}")
  7115. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  7116. """Set the nozzle target temperature.
  7117. Args:
  7118. target: Target temperature in Celsius (0 to turn off)
  7119. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  7120. Returns:
  7121. True if command was sent, False otherwise
  7122. """
  7123. # Use M104 for non-blocking
  7124. # Always use T parameter for H2D compatibility
  7125. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  7126. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  7127. # Track it locally so we can display it correctly
  7128. if result and nozzle == 1:
  7129. self.state.temperatures["nozzle_target"] = float(target)
  7130. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  7131. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  7132. return result
  7133. def set_chamber_temperature(self, target: int) -> bool:
  7134. """Set the chamber target temperature.
  7135. Args:
  7136. target: Target temperature in Celsius (0 to turn off heating)
  7137. Returns:
  7138. True if command was sent, False otherwise
  7139. """
  7140. # M141 sets chamber temperature
  7141. result = self.send_gcode(f"M141 S{target}")
  7142. # Track chamber target locally (MQTT reports encoded values that need filtering)
  7143. if result:
  7144. self.state.temperatures["chamber_target"] = float(target)
  7145. self.state.temperatures["_chamber_target_set_time"] = time.time()
  7146. # Update heating state immediately based on new target
  7147. current_temp = self.state.temperatures.get("chamber", 0)
  7148. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  7149. logger.info(
  7150. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  7151. )
  7152. return result
  7153. def set_print_speed(self, mode: int) -> bool:
  7154. """Set the print speed mode.
  7155. Args:
  7156. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  7157. Returns:
  7158. True if command was sent, False otherwise
  7159. """
  7160. if not self._client or not self.state.connected:
  7161. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  7162. return False
  7163. if mode not in (1, 2, 3, 4):
  7164. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  7165. return False
  7166. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  7167. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7168. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  7169. return True
  7170. def set_fan_speed(self, fan: int, speed: int) -> bool:
  7171. """Set fan speed.
  7172. Args:
  7173. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=second auxiliary).
  7174. Index 10 is the second auxiliary part cooling fan: left on the P2S
  7175. (an accessory kit), right on the X2D, where 2 is the left (#3373)
  7176. (airduct part id 10); Bambu's official machine profiles drive it with
  7177. "M106 P10" in start/layer-change gcode.
  7178. speed: Speed 0-255 (0=off, 255=full)
  7179. Returns:
  7180. True if command was sent, False otherwise
  7181. """
  7182. if fan not in (1, 2, 3, 10):
  7183. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  7184. return False
  7185. speed = max(0, min(255, speed)) # Clamp to 0-255
  7186. return self.send_gcode(f"M106 P{fan} S{speed}")
  7187. def set_airduct_mode(self, mode: str) -> bool:
  7188. """Set air conditioning mode (cooling or heating).
  7189. Args:
  7190. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  7191. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  7192. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  7193. closes top exhaust flap
  7194. Returns:
  7195. True if command was sent, False otherwise
  7196. """
  7197. if not self._client or not self.state.connected:
  7198. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  7199. return False
  7200. self._sequence_id += 1
  7201. mode_id = 0 if mode == "cooling" else 1
  7202. command = {
  7203. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  7204. }
  7205. # Use QoS 1 for reliable delivery
  7206. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7207. logger.info(
  7208. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  7209. )
  7210. return True
  7211. def set_chamber_light(self, on: bool) -> bool:
  7212. """Turn chamber light on or off.
  7213. Args:
  7214. on: True to turn on, False to turn off
  7215. Returns:
  7216. True if command was sent, False otherwise
  7217. """
  7218. if not self._client or not self.state.connected:
  7219. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  7220. return False
  7221. mode = "on" if on else "off"
  7222. # Control both chamber lights (some printers like H2D have two)
  7223. for led_node in ["chamber_light", "chamber_light2"]:
  7224. self._sequence_id += 1
  7225. command = {
  7226. "system": {
  7227. "command": "ledctrl",
  7228. "led_node": led_node,
  7229. "led_mode": mode,
  7230. "led_on_time": 500,
  7231. "led_off_time": 500,
  7232. "loop_times": 0,
  7233. "interval_time": 0,
  7234. "sequence_id": str(self._sequence_id),
  7235. }
  7236. }
  7237. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7238. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  7239. return True
  7240. def select_extruder(self, extruder: int) -> bool:
  7241. """Select the active extruder for dual-nozzle printers (H2D).
  7242. Args:
  7243. extruder: Extruder index (0=right, 1=left for H2D)
  7244. Returns:
  7245. True if command was sent, False otherwise
  7246. """
  7247. if extruder not in (0, 1):
  7248. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  7249. return False
  7250. if not self._client or not self.state.connected:
  7251. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  7252. return False
  7253. # H2D extruder switching via select_extruder command
  7254. # Command format captured from OrcaSlicer:
  7255. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  7256. # extruder_index: 0 = RIGHT, 1 = LEFT
  7257. self._sequence_id += 1
  7258. command = {
  7259. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  7260. }
  7261. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7262. logger.info(
  7263. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  7264. )
  7265. return True
  7266. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  7267. """Load filament from a specific AMS tray.
  7268. Args:
  7269. tray_id: Global tray ID — 0..15 for AMS slots, 24..27 for the A2L
  7270. AMS-Lite, 128..135 for an AMS-HT (its unit id), 254 for external spool
  7271. (single-external printers and Ext-L on dual-nozzle H2D),
  7272. 255 for Ext-R on dual-nozzle H2D.
  7273. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  7274. Sent only when given, matching BambuStudio: ``extruder_id`` is
  7275. an optional field on ``ams_change_filament``
  7276. (``DeviceManager::command_ams_change_filament``) and Studio
  7277. omits it unless a Filament Track Switch is installed. Without a
  7278. switch the firmware derives the hotend from the AMS's own
  7279. extruder binding and an explicit value is redundant; *with* one
  7280. every AMS reports 0xE and is bound to a switch inlet instead, so
  7281. the firmware has nothing to derive from and the load silently
  7282. does nothing until we name the hotend.
  7283. Returns:
  7284. True if command was sent, False otherwise
  7285. """
  7286. if not self._client or not self.state.connected:
  7287. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  7288. return False
  7289. # Build the ams_change_filament command. Encoding differs by target type:
  7290. # - AMS slots (0..15, A2L 24..27, AMS-HT 128..135): see
  7291. # change_filament_wire_ids; curr/tar_temp = -1.
  7292. # - External spool (tray_id=254): legacy capture from a single-extruder
  7293. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  7294. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  7295. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  7296. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  7297. self._sequence_id += 1
  7298. wire_target = tray_id
  7299. if tray_id == 255:
  7300. ams_id = 255
  7301. slot_id = 0 # extruder index for the right nozzle
  7302. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  7303. if right_temp < 180:
  7304. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  7305. curr_temp = right_temp
  7306. tar_temp = right_temp
  7307. elif tray_id == 254:
  7308. ams_id = 255
  7309. slot_id = 254
  7310. curr_temp = -1
  7311. tar_temp = -1
  7312. else:
  7313. # A regular AMS, the A2L AMS-Lite (physical unit 16) or an AMS-HT
  7314. # (128-135), as BambuStudio addresses each.
  7315. ams_id, slot_id, wire_target = change_filament_wire_ids(tray_id)
  7316. curr_temp = -1
  7317. tar_temp = -1
  7318. command = {
  7319. "print": {
  7320. "command": "ams_change_filament",
  7321. "sequence_id": str(self._sequence_id),
  7322. "ams_id": ams_id,
  7323. "slot_id": slot_id,
  7324. "target": wire_target,
  7325. "curr_temp": curr_temp,
  7326. "tar_temp": tar_temp,
  7327. }
  7328. }
  7329. if extruder_id is not None:
  7330. command["print"]["extruder_id"] = int(extruder_id)
  7331. command_json = json.dumps(command)
  7332. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  7333. self._client.publish(self.topic_publish, command_json, qos=1)
  7334. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  7335. # Track this load request for H2D dual-nozzle disambiguation
  7336. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  7337. self.state.pending_tray_target = tray_id
  7338. self.state.pending_tray_target_at = time.monotonic()
  7339. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  7340. return True
  7341. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  7342. """Unload filament, optionally naming the slot to unload.
  7343. Args:
  7344. tray_id: Global tray ID of the slot being unloaded. When given, the
  7345. command is addressed to that slot's AMS and is only sent if an
  7346. extruder is actually fed from it — BambuStudio does the same
  7347. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  7348. nothing when none matches). When omitted, the pre-existing
  7349. behaviour is kept: unload whatever ``tray_now`` names.
  7350. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  7351. machine with both hotends loaded it names only one of them and an
  7352. unaddressed unload picks that one regardless of which slot the operator
  7353. clicked. Passing the slot is what makes the two hotends distinguishable.
  7354. Returns:
  7355. True if command was sent, False otherwise
  7356. """
  7357. if not self._client or not self.state.connected:
  7358. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  7359. return False
  7360. # Get the currently loaded tray info
  7361. tray_now = self.state.tray_now
  7362. source_tray = tray_now if tray_id is None else tray_id
  7363. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  7364. # Determine source ams_id for the unload command
  7365. if source_tray == 255 or source_tray == 254:
  7366. ams_id = 255 # No filament or external spool
  7367. else:
  7368. # Source AMS: the A2L AMS-Lite as physical 16, an AMS-HT as its unit id.
  7369. ams_id = change_filament_wire_ids(source_tray)[0]
  7370. # Refuse an addressed unload of a slot no hotend is holding — but only on
  7371. # a printer that has more than one hotend, which is the only case the
  7372. # check exists for. With one hotend there is nothing to disambiguate:
  7373. # tray_now already names the loaded slot exactly, and running the check
  7374. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  7375. # very likely does, but single-nozzle machines do report the block —
  7376. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  7377. # an X1C on the maintainer's own network sends `device.extruder` — and
  7378. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  7379. # would 409 every unload on every X1C, P1S and A1.
  7380. #
  7381. # Gated on the runtime flag rather than on len(extruder_slots), which is
  7382. # rebuilt from each payload's array and would flip the check off for any
  7383. # frame that carried a short one; and deliberately not on
  7384. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  7385. # one single-nozzle machine as dual (#1386) — the false positive there is
  7386. # exactly the case this gate exists to keep out.
  7387. #
  7388. # The external spool is excluded for a different reason: 254/255 are not
  7389. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  7390. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  7391. local_slot = change_filament_wire_ids(tray_id)[1]
  7392. holder = next(
  7393. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  7394. None,
  7395. )
  7396. if holder is None:
  7397. logger.info(
  7398. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  7399. self.serial_number,
  7400. ams_id,
  7401. local_slot,
  7402. )
  7403. return False
  7404. logger.info(
  7405. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7406. )
  7407. # Command format from BambuStudio traffic capture:
  7408. # - No extruder_id field
  7409. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7410. # - slot_id=255 and target=255 for unload
  7411. # Get current nozzle temperature for the unload command
  7412. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7413. if nozzle_temp < 180:
  7414. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7415. self._sequence_id += 1
  7416. command = {
  7417. "print": {
  7418. "command": "ams_change_filament",
  7419. "sequence_id": str(self._sequence_id),
  7420. "ams_id": ams_id,
  7421. "slot_id": 255, # 255 = unload marker
  7422. "target": 255, # 255 = unload destination
  7423. "curr_temp": nozzle_temp,
  7424. "tar_temp": nozzle_temp,
  7425. }
  7426. }
  7427. command_json = json.dumps(command)
  7428. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7429. self._client.publish(self.topic_publish, command_json, qos=1)
  7430. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7431. # Clear tracked load request since we're unloading
  7432. self.state.pending_tray_target = None
  7433. self.state.pending_tray_target_at = None
  7434. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7435. return True
  7436. def ams_control(self, action: str) -> bool:
  7437. """Control AMS operations.
  7438. Args:
  7439. action: "resume", "reset", or "pause"
  7440. Returns:
  7441. True if command was sent, False otherwise
  7442. """
  7443. if not self._client or not self.state.connected:
  7444. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7445. return False
  7446. if action not in ("resume", "reset", "pause"):
  7447. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7448. return False
  7449. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7450. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7451. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7452. return True
  7453. async def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7454. """Trigger RFID re-read for a specific AMS tray.
  7455. Sends ``ams_get_rfid`` and waits for the printer's answer. Firmware
  7456. that refuses it (#3206: X1Plus on base 01.08.02.00 answers ``FAIL`` /
  7457. ``ERROR STATE``) gets the legacy ``M620 R<global tray>`` gcode instead,
  7458. which is what Bambu Studio sends to printers without the new protocol.
  7459. The fallback only follows an explicit refusal, so firmware that takes
  7460. ``ams_get_rfid`` never sees it.
  7461. Success means the printer accepted the request, not that the tag was
  7462. read: the slot updating in the next push is the only proof of that.
  7463. Args:
  7464. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7465. tray_id: Tray ID within the AMS (0-3)
  7466. Returns:
  7467. Tuple of (success, message)
  7468. """
  7469. if not self._client or not self.state.connected:
  7470. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7471. return False, "Printer not connected"
  7472. # Check if filament is currently loaded (tray_now != 255)
  7473. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7474. tray_now = self.state.tray_now
  7475. if tray_now != 255:
  7476. # Decode which tray is loaded for the message
  7477. if tray_now == 254:
  7478. loaded_tray = "external spool"
  7479. elif tray_now >= 0 and tray_now < 128:
  7480. loaded_ams = tray_now // 4
  7481. loaded_slot = tray_now % 4
  7482. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7483. else:
  7484. loaded_tray = f"tray {tray_now}"
  7485. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7486. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7487. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7488. wire_ams_id, wire_slot_id = ams_id, tray_id
  7489. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7490. wire_ams_id, wire_slot_id, _ = _a2l
  7491. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7492. refused = await self._send_rfid_command(
  7493. {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id}
  7494. )
  7495. if refused is None:
  7496. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7497. # M620 R only for what Bambu Studio sends it to: a model older than the
  7498. # newer protocol, on one of the four regular AMS units (the only ones
  7499. # with a legacy global tray index). Never during a job either: a
  7500. # gcode_line would be executed inside the running print.
  7501. from backend.app.utils.printer_models import uses_legacy_rfid_refresh
  7502. if (
  7503. not 0 <= wire_ams_id <= 3
  7504. or not uses_legacy_rfid_refresh(self.model)
  7505. or self.state.state in _ACTIVE_PRINT_STATES
  7506. ):
  7507. return False, f"Printer refused the RFID refresh: {refused}"
  7508. logger.info(
  7509. "[%s] ams_get_rfid refused (%s), falling back to M620 R%s",
  7510. self.serial_number,
  7511. refused,
  7512. wire_ams_id * 4 + wire_slot_id,
  7513. )
  7514. legacy_refused = await self._send_rfid_command(
  7515. {"command": "gcode_line", "param": f"M620 R{wire_ams_id * 4 + wire_slot_id}\n"}
  7516. )
  7517. if legacy_refused is None:
  7518. return True, f"Refreshing AMS {ams_id} tray {tray_id} (legacy command)"
  7519. return False, f"Printer refused the RFID refresh: {legacy_refused}"
  7520. # The answer to ams_get_rfid was measured at 11ms in #3206's capture.
  7521. _rfid_ack_timeout: float = 3.0
  7522. async def _send_rfid_command(self, print_command: dict) -> str | None:
  7523. """Publish one RFID refresh command and wait for the printer's answer.
  7524. Returns the printer's reason when it answered ``FAIL``, else None.
  7525. No answer within ``_rfid_ack_timeout`` counts as accepted, because
  7526. silence is not evidence of refusal and older firmware may not answer
  7527. at all.
  7528. """
  7529. timeout = self._rfid_ack_timeout
  7530. self._sequence_id += 1
  7531. seq_id = str(self._sequence_id)
  7532. command = {"print": {**print_command, "sequence_id": seq_id}}
  7533. self._pending_rfid_acks[seq_id] = None
  7534. try:
  7535. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7536. deadline = time.monotonic() + timeout
  7537. while time.monotonic() < deadline:
  7538. ack = self._pending_rfid_acks.get(seq_id)
  7539. if ack is not None:
  7540. if str(ack.get("result", "")).lower() == "fail":
  7541. return str(ack.get("reason", "") or "") or "printer reported failure"
  7542. return None
  7543. await asyncio.sleep(0.05)
  7544. finally:
  7545. self._pending_rfid_acks.pop(seq_id, None)
  7546. logger.info(
  7547. "[%s] No answer to %s seq=%s within %.1fs", self.serial_number, print_command["command"], seq_id, timeout
  7548. )
  7549. return None
  7550. def ams_set_filament_setting(
  7551. self,
  7552. ams_id: int,
  7553. tray_id: int,
  7554. tray_info_idx: str,
  7555. tray_type: str,
  7556. tray_sub_brands: str,
  7557. tray_color: str,
  7558. nozzle_temp_min: int,
  7559. nozzle_temp_max: int,
  7560. setting_id: str = "",
  7561. ) -> bool:
  7562. """Set AMS tray filament settings (type, color, temperature).
  7563. Note: K value is set separately via extrusion_cali_sel command.
  7564. Args:
  7565. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7566. tray_id: Tray ID within the AMS (0-3)
  7567. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7568. tray_type: Filament type (e.g., "PLA", "PETG")
  7569. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  7570. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  7571. nozzle_temp_min: Minimum nozzle temperature
  7572. nozzle_temp_max: Maximum nozzle temperature
  7573. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  7574. Returns:
  7575. True if command was sent, False otherwise
  7576. """
  7577. if not self._client or not self.state.connected:
  7578. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  7579. return False
  7580. # Calculate mqtt IDs based on AMS type.
  7581. # External-spool convention verified against a BambuStudio→X1C packet capture
  7582. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  7583. # *global* tray index in `tray_id`, not a local position within the virtual
  7584. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  7585. # is what the original code was matching — but the request and response
  7586. # use different semantics for that field. Sending `tray_id: 0` is what
  7587. # the P1S in #1279 rejected with `result: "fail"`.
  7588. if ams_id == 255:
  7589. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7590. if len(vt_tray) > 1:
  7591. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7592. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7593. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7594. # captured Studio→H2D exchange confirms the correct value.
  7595. mqtt_ams_id = 254 + tray_id
  7596. mqtt_tray_id = 0
  7597. else:
  7598. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7599. mqtt_ams_id = 255
  7600. mqtt_tray_id = 254
  7601. slot_id = 0
  7602. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7603. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7604. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7605. mqtt_ams_id, slot_id, _ = _a2l
  7606. mqtt_tray_id = slot_id
  7607. elif ams_id <= 3:
  7608. mqtt_ams_id = ams_id
  7609. mqtt_tray_id = tray_id
  7610. slot_id = tray_id
  7611. else:
  7612. # AMS-HT: single tray per unit
  7613. mqtt_ams_id = ams_id
  7614. mqtt_tray_id = tray_id
  7615. slot_id = 0
  7616. command = {
  7617. "print": {
  7618. "command": "ams_filament_setting",
  7619. "ams_id": mqtt_ams_id,
  7620. "tray_id": mqtt_tray_id,
  7621. "slot_id": slot_id,
  7622. "tray_info_idx": tray_info_idx,
  7623. "tray_type": tray_type,
  7624. "tray_sub_brands": tray_sub_brands,
  7625. # UPPERCASE, always: lowercase hex is silently read as zeros by
  7626. # P1S firmware and acknowledged as a success (#2987).
  7627. "tray_color": wire_tray_color(tray_color),
  7628. "nozzle_temp_min": nozzle_temp_min,
  7629. "nozzle_temp_max": nozzle_temp_max,
  7630. "sequence_id": "0",
  7631. }
  7632. }
  7633. # Include setting_id if provided (helps slicer show correct profile)
  7634. if setting_id:
  7635. command["print"]["setting_id"] = setting_id
  7636. command_json = json.dumps(command)
  7637. logger.info(
  7638. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  7639. )
  7640. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  7641. self._client.publish(self.topic_publish, command_json, qos=1)
  7642. self._last_ams_cmd_time = time.monotonic()
  7643. return True
  7644. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  7645. """Reset an AMS slot to empty/unconfigured state.
  7646. Args:
  7647. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7648. tray_id: Tray ID within the AMS (0-3)
  7649. Returns:
  7650. True if command was sent, False otherwise
  7651. """
  7652. if not self._client or not self.state.connected:
  7653. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  7654. return False
  7655. # Calculate mqtt IDs based on AMS type — same convention as
  7656. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  7657. if ams_id == 255:
  7658. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7659. if len(vt_tray) > 1:
  7660. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7661. mqtt_ams_id = 254 + tray_id
  7662. mqtt_tray_id = 0
  7663. else:
  7664. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7665. mqtt_ams_id = 255
  7666. mqtt_tray_id = 254
  7667. slot_id = 0
  7668. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7669. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  7670. mqtt_ams_id, slot_id, _ = _a2l
  7671. mqtt_tray_id = slot_id
  7672. elif ams_id <= 3:
  7673. mqtt_ams_id = ams_id
  7674. mqtt_tray_id = tray_id
  7675. slot_id = tray_id
  7676. else:
  7677. # AMS-HT: single tray per unit
  7678. mqtt_ams_id = ams_id
  7679. mqtt_tray_id = tray_id
  7680. slot_id = 0
  7681. command = {
  7682. "print": {
  7683. "command": "ams_filament_setting",
  7684. "ams_id": mqtt_ams_id,
  7685. "tray_id": mqtt_tray_id,
  7686. "slot_id": slot_id,
  7687. "tray_info_idx": "",
  7688. "tray_type": "",
  7689. "tray_sub_brands": "",
  7690. "tray_color": "00000000",
  7691. "nozzle_temp_min": 0,
  7692. "nozzle_temp_max": 0,
  7693. "sequence_id": "0",
  7694. }
  7695. }
  7696. command_json = json.dumps(command)
  7697. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  7698. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  7699. self._client.publish(self.topic_publish, command_json, qos=1)
  7700. self._last_ams_cmd_time = time.monotonic()
  7701. return True
  7702. def extrusion_cali_sel(
  7703. self,
  7704. ams_id: int,
  7705. tray_id: int,
  7706. cali_idx: int,
  7707. filament_id: str,
  7708. nozzle_diameter: str = "0.4",
  7709. ) -> bool:
  7710. """Set calibration profile (K value) for an AMS slot.
  7711. This command selects a K profile from the printer's calibration list.
  7712. Use cali_idx=-1 to use the default K value (0.020).
  7713. Note: Do NOT send setting_id in this command — BambuStudio never includes
  7714. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  7715. Args:
  7716. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7717. tray_id: Tray ID within the AMS (0-3)
  7718. cali_idx: Calibration profile index (-1 for default)
  7719. filament_id: Filament preset ID (same as tray_info_idx)
  7720. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7721. Returns:
  7722. True if command was sent, False otherwise
  7723. """
  7724. if not self._client or not self.state.connected:
  7725. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  7726. return False
  7727. # Calculate mqtt IDs based on AMS type.
  7728. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  7729. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  7730. if ams_id == 255:
  7731. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  7732. # ams_filament_setting which uses LOCAL tray_id=0).
  7733. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7734. if len(vt_tray) > 1:
  7735. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7736. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  7737. mqtt_ams_id = 254 + tray_id
  7738. mqtt_tray_id = 254 + tray_id
  7739. else:
  7740. # Single external slot (X1C, P1S, A1): global tray_id=254
  7741. mqtt_ams_id = 254
  7742. mqtt_tray_id = 254
  7743. slot_id = 0
  7744. elif ams_id <= 3:
  7745. mqtt_ams_id = ams_id
  7746. mqtt_tray_id = ams_id * 4 + tray_id
  7747. slot_id = tray_id
  7748. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7749. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  7750. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  7751. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  7752. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  7753. elif ams_id >= 128 and ams_id <= 135:
  7754. mqtt_ams_id = ams_id
  7755. mqtt_tray_id = tray_id
  7756. slot_id = 0
  7757. else:
  7758. mqtt_ams_id = ams_id
  7759. mqtt_tray_id = tray_id
  7760. slot_id = 0
  7761. command = {
  7762. "print": {
  7763. "command": "extrusion_cali_sel",
  7764. "cali_idx": cali_idx,
  7765. "filament_id": filament_id,
  7766. "nozzle_diameter": nozzle_diameter,
  7767. "ams_id": mqtt_ams_id,
  7768. "tray_id": mqtt_tray_id,
  7769. "slot_id": slot_id,
  7770. "sequence_id": "0",
  7771. }
  7772. }
  7773. command_json = json.dumps(command)
  7774. logger.info(
  7775. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  7776. )
  7777. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  7778. self._client.publish(self.topic_publish, command_json, qos=1)
  7779. return True
  7780. def extrusion_cali_set(
  7781. self,
  7782. tray_id: int,
  7783. k_value: float,
  7784. nozzle_diameter: str = "0.4",
  7785. nozzle_temp: int = 220,
  7786. filament_id: str = "",
  7787. setting_id: str = "",
  7788. name: str = "",
  7789. cali_idx: int = -1,
  7790. ) -> bool:
  7791. """Directly set K value (pressure advance) for a tray.
  7792. Uses the filaments array format required by current firmware.
  7793. Args:
  7794. tray_id: Global tray ID (ams_id * 4 + slot)
  7795. k_value: Pressure advance K value (e.g., 0.020)
  7796. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7797. nozzle_temp: Nozzle temperature for calibration reference
  7798. filament_id: Filament preset ID (e.g., "GFA02")
  7799. setting_id: Setting ID (e.g., "GFSA02_07")
  7800. name: Profile display name
  7801. cali_idx: Calibration index (-1 for new)
  7802. Returns:
  7803. True if command was sent, False otherwise
  7804. """
  7805. if not self._client or not self.state.connected:
  7806. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  7807. return False
  7808. # Was reusing the previous command's id — harmless while nothing
  7809. # correlated on it, but the printer echoes sequence_id back and the
  7810. # K-profile write path now matches acks by it (#2718).
  7811. self._sequence_id += 1
  7812. nozzle_id = f"HS00-{nozzle_diameter}"
  7813. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  7814. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  7815. # stays 0 (hardcoded, as for every other unit here).
  7816. wire_tray_id = tray_id
  7817. if 0 <= tray_id <= 253 and (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  7818. wire_tray_id = _a2l[2]
  7819. filament_entry = {
  7820. "ams_id": 0,
  7821. "cali_idx": cali_idx,
  7822. "extruder_id": 0,
  7823. "filament_id": filament_id,
  7824. "k_value": f"{k_value:.6f}",
  7825. "n_coef": "1.400000",
  7826. "name": name,
  7827. "nozzle_diameter": nozzle_diameter,
  7828. "nozzle_id": nozzle_id,
  7829. "setting_id": setting_id,
  7830. "tray_id": wire_tray_id,
  7831. }
  7832. command = {
  7833. "print": {
  7834. "command": "extrusion_cali_set",
  7835. "filaments": [filament_entry],
  7836. "nozzle_diameter": nozzle_diameter,
  7837. "sequence_id": str(self._sequence_id),
  7838. }
  7839. }
  7840. command_json = json.dumps(command)
  7841. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  7842. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  7843. self._client.publish(self.topic_publish, command_json, qos=1)
  7844. return True
  7845. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  7846. """Dispatch the user's choice from the HMS-error modal as a printer command.
  7847. Args:
  7848. print_error: Canonical hex identifier for the fault — 8 chars for the
  7849. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  7850. (HMSError.full_code). Carried through unchanged from the route.
  7851. Converted to its DECIMAL string form for the `ignore` /
  7852. `idle_ignore` commands' `err` field, which is what the firmware
  7853. actually compares against the active fault. The pre-#1869
  7854. hex-string `err` was silently rejected because the firmware was
  7855. being asked to match `"05008051"` against int 0x05008051
  7856. (= 83918929 decimal) — see BambuStudio's
  7857. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  7858. `std::to_string(int m_error_code)`.
  7859. action: One of HMSAction's string values.
  7860. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  7861. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  7862. shapes; empty string is the no-job-id sentinel.
  7863. Returns False when the MQTT client is offline or when `action` is unknown
  7864. so the route surfaces it as a 4xx rather than a silent no-op.
  7865. """
  7866. if not self._client or not self.state.connected:
  7867. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  7868. return False
  7869. # Always re-push the full state after a command so the modal's underlying
  7870. # status query reflects the new error list (or absence) on the next tick.
  7871. def publish(payload: dict):
  7872. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  7873. self._client.publish(
  7874. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  7875. )
  7876. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  7877. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  7878. # every command_hms_* call). Our route hands us the hex string —
  7879. # convert. Falls back to the raw input if it's not parseable so the
  7880. # firmware can reject it and the route can surface 502 instead of us
  7881. # raising ValueError mid-dispatch.
  7882. try:
  7883. err_decimal = str(int(print_error, 16))
  7884. except ValueError:
  7885. err_decimal = print_error
  7886. def hms_resume():
  7887. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  7888. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  7889. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  7890. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  7891. # shape historically because it works, and changing it without a
  7892. # field test risks regressing a path that the user has confirmed.
  7893. publish(
  7894. {
  7895. "print": {
  7896. "command": "resume",
  7897. "param": "",
  7898. "sequence_id": "0",
  7899. }
  7900. }
  7901. )
  7902. def hms_stop():
  7903. # Same as hms_resume — plain shape, confirmed working by the user
  7904. # for "Stop Printing".
  7905. publish(
  7906. {
  7907. "print": {
  7908. "command": "stop",
  7909. "param": "",
  7910. "sequence_id": "0",
  7911. }
  7912. }
  7913. )
  7914. def hms_ignore_command():
  7915. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  7916. # what the "Ignore this and Resume" button actually publishes.
  7917. # Distinct from `idle_ignore`: this command has the firmware
  7918. # suppress the next re-check of the named fault AND resume the
  7919. # paused print in a single operation. The previous Bambuddy code
  7920. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  7921. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  7922. # the problem, re-check normally" so the firmware re-detected the
  7923. # wrong plate and re-paused with the same code (#1869).
  7924. #
  7925. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  7926. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  7927. # variant of "don't remind next time" lives on `idle_ignore`'s
  7928. # type=1, not as a separate ignore shape.
  7929. publish(
  7930. {
  7931. "print": {
  7932. "command": "ignore",
  7933. "err": err_decimal,
  7934. "param": "reserve",
  7935. "job_id": job_id or "",
  7936. "sequence_id": "0",
  7937. }
  7938. }
  7939. )
  7940. def hms_idle_ignore(persistent: bool = False):
  7941. # `idle_ignore` is BambuStudio's "dismiss this warning without
  7942. # resuming" command for non-pause warnings — what
  7943. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  7944. # type=0 dismisses once, type=1 suppresses the same warning
  7945. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  7946. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  7947. # NOT via the resume-bearing `ignore` command.
  7948. publish(
  7949. {
  7950. "print": {
  7951. "command": "idle_ignore",
  7952. "err": err_decimal,
  7953. "type": 1 if persistent else 0,
  7954. "sequence_id": "0",
  7955. }
  7956. }
  7957. )
  7958. def ams_control(param: str):
  7959. publish(
  7960. {
  7961. "print": {
  7962. "command": "ams_control",
  7963. "param": param,
  7964. "sequence_id": "0",
  7965. }
  7966. }
  7967. )
  7968. def clean_print_error():
  7969. # Matches the existing `clear_hms_errors` shape — Bambu does not
  7970. # expect `print_error` in the body; the command clears whatever
  7971. # error dialog is currently active on the printer.
  7972. publish(
  7973. {
  7974. "print": {
  7975. "command": "clean_print_error",
  7976. "sequence_id": "0",
  7977. }
  7978. }
  7979. )
  7980. def uiop_close():
  7981. # `err` is the 8-char hex short code (already a string from the
  7982. # frontend), uppercased for consistency with how BambuStudio sends it.
  7983. publish(
  7984. {
  7985. "system": {
  7986. "command": "uiop",
  7987. "name": "print_error",
  7988. "action": "close",
  7989. "source": 1,
  7990. "type": "dialog",
  7991. "err": print_error.upper(),
  7992. "sequence_id": "0",
  7993. }
  7994. }
  7995. )
  7996. match action:
  7997. case (
  7998. HMSAction.RESUME_PRINTING
  7999. | HMSAction.RESUME_PRINTING_DEFECTS
  8000. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  8001. | HMSAction.PROBLEM_SOLVED_RESUME
  8002. | HMSAction.FILAMENT_LOAD_RESUME
  8003. | HMSAction.PROCEED
  8004. ):
  8005. hms_resume()
  8006. case HMSAction.STOP_PRINTING:
  8007. hms_stop()
  8008. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  8009. # All three buttons map to BambuStudio's `command_hms_ignore`
  8010. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  8011. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  8012. # responsibility — the wire shape is identical.
  8013. hms_ignore_command()
  8014. case HMSAction.NO_REMINDER_NEXT_TIME:
  8015. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  8016. # `command_hms_idle_ignore` with type=0
  8017. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  8018. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  8019. # dismisses the dialog.
  8020. hms_idle_ignore(persistent=False)
  8021. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  8022. ams_control("done")
  8023. case (
  8024. HMSAction.RETRY_FILAMENT_EXTRUDED
  8025. | HMSAction.CONTINUE
  8026. | HMSAction.RETRY_PROBLEM_SOLVED
  8027. | HMSAction.DBL_CHECK_RETRY
  8028. ):
  8029. ams_control("resume")
  8030. case HMSAction.ABORT:
  8031. ams_control("abort")
  8032. case HMSAction.OK_BUTTON:
  8033. clean_print_error()
  8034. case HMSAction.DBL_CHECK_OK:
  8035. clean_print_error()
  8036. uiop_close()
  8037. case HMSAction.DBL_CHECK_RESUME:
  8038. # Plain resume — not HMS-aware, no err/job_id.
  8039. publish(
  8040. {
  8041. "print": {
  8042. "command": "resume",
  8043. "param": "",
  8044. "sequence_id": "0",
  8045. }
  8046. }
  8047. )
  8048. case HMSAction.REFRESH_NOZZLE:
  8049. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  8050. case HMSAction.TURN_OFF_FIRE_ALARM:
  8051. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  8052. case HMSAction.STOP_DRYING:
  8053. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  8054. case HMSAction.DISABLE_PURIFICATION:
  8055. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  8056. case (
  8057. HMSAction.CHECK_ASSISTANT
  8058. | HMSAction.JUMP_TO_LIVEVIEW
  8059. | HMSAction.OK_JUMP_RACK
  8060. | HMSAction.REMOVE_CLOSE_BTN
  8061. | HMSAction.LOAD_VIRTUAL_TRAY
  8062. | HMSAction.CANCLE
  8063. | HMSAction.DBL_CHECK_CANCEL
  8064. ):
  8065. # UI-only actions — the printer's own screen handles these; the
  8066. # modal still surfaces them so the user has parity with Studio.
  8067. pass
  8068. case _:
  8069. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  8070. return False
  8071. return True