bambu_mqtt.py 422 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376
  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 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. # AMS module name prefixes used in get_version responses.
  27. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  28. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  29. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  30. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  31. _AMS_MODULE_PREFIXES = ("ams/", "n3f/", "n3s/")
  32. # gcode_state values that mean the printer is not idle and must not be handed a
  33. # new start-print (#2598). The firmware rejects a project_file while busy with
  34. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  35. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  36. # are valid start targets and are deliberately excluded. Mirrors
  37. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  38. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  39. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  40. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  41. # ended the cycle on schedule or aborted it. More than this many minutes still on
  42. # the clock means it was cut short, and the firmware's own reason codes are worth
  43. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  44. # left), and the log said only "drying complete", so the report carried no
  45. # evidence of why. The margin absorbs a stale last observation between AMS
  46. # pushes; it is not a judgement about how short "short" is.
  47. _EARLY_DRY_END_MINUTES = 5
  48. # CONNACK reason codes that mean the printer actively refused our credentials,
  49. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  50. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  51. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  52. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  53. # code (or, on some firmware, the serial used as the username) is wrong.
  54. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  55. # Short, stable slugs recorded on the client and surfaced to the connection
  56. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  57. # frontend picks a localized message key off these.
  58. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  59. CONNECT_ERROR_REFUSED = "refused"
  60. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  61. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  62. OrcaSlicer reads bit 18 of the hex string via
  63. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  64. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  65. that doesn't yield a clean integer so downstream consumers preserve today's
  66. behaviour rather than treating "absent" as "OFF".
  67. """
  68. if not isinstance(cfg_raw, str) or not cfg_raw:
  69. return None
  70. try:
  71. return bool((int(cfg_raw, 16) >> 18) & 1)
  72. except ValueError:
  73. return None
  74. def is_printer_status_frame(print_data: dict) -> bool:
  75. """True when a ``print`` payload is the printer reporting its own state.
  76. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  77. `project_file` ack carries whatever Bambuddy put on the wire — including
  78. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  79. telemetry means reading our own request back as the printer's state
  80. (#3040). Only `push_status` (and the odd firmware that omits `command`
  81. entirely on a status frame) describes the printer.
  82. """
  83. command = print_data.get("command")
  84. return command is None or command == "push_status"
  85. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  86. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  87. # firmware is internally inconsistent about it:
  88. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  89. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  90. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  91. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  92. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  93. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  94. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  95. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  96. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  97. A2L_LITE_PHYSICAL_AMS_ID = 16
  98. A2L_LITE_NORMALIZED_AMS_ID = 6
  99. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  100. def normalize_am_unit_id(ams_id: int) -> int:
  101. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  102. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  103. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  104. through untouched.
  105. """
  106. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  107. def wire_tray_color(tray_color: str | None) -> str:
  108. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  109. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  110. as a zero, and does it silently: the command response echoes the value you
  111. sent and reports ``result: "success"``, so only the next AMS push shows what
  112. was really stored. Measured on the reporter's machine (#2987), where the
  113. spool's own ``rgba`` is stored lowercase and went out verbatim:
  114. sent 09ff00ff -> AMS reports 09000000
  115. sent ff5100ff -> AMS reports 00510000
  116. sent 090000FF -> AMS reports 090000FF
  117. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  118. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  119. longer matches the spool that asked for it and the assignment is deleted
  120. seconds after being made -- and re-assigning through the slot modal writes
  121. the mangled colour back, because the modal seeds itself from the tray.
  122. Applied here, at the one place the command is built, rather than in each of
  123. the four callers: a caller that forgets is exactly how this arrived.
  124. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  125. blank stays blank, which is how a slot is cleared.
  126. """
  127. return (tray_color or "").strip().lstrip("#").upper()
  128. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  129. """Translate a normalised A2L slot back to the physical wire form.
  130. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  131. (normalised id 6), else ``None`` for every other unit.
  132. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  133. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  134. confirmed by capture: the physical **global** tray value some commands put on
  135. the wire (load `target`, extrusion_cali `tray_id`) — we extrapolate it as
  136. 16*4+slot = 64-67 to stay consistent with the physical unit id. This is the
  137. single unverified encoding; a BambuStudio->A2L capture of a load or cali
  138. command would settle it, and it lives only here.
  139. """
  140. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  141. return None
  142. local_slot = tray_id % 4
  143. return (
  144. A2L_LITE_PHYSICAL_AMS_ID,
  145. local_slot,
  146. A2L_LITE_PHYSICAL_AMS_ID * 4 + local_slot,
  147. )
  148. def resolve_external_spools_in_mapping(ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool) -> object:
  149. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  150. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  151. dispatch both write an external spool there as -1 -- the same value as a
  152. slot that isn't fed at all -- and carry the real target only in
  153. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  154. list alone turns "printed from the external spool" into "unmapped", and
  155. usage then lands on whatever tray the fallback guesses.
  156. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  157. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  158. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  159. printers, which have one external spool that the wire always calls 255.
  160. ``{255, 255}`` is the unmapped marker and stays -1. Every other entry is
  161. left exactly as captured. Without a usable ``ams_mapping2`` the input is
  162. returned unchanged.
  163. """
  164. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  165. return ams_mapping
  166. if len(ams_mapping2) != len(ams_mapping):
  167. return ams_mapping
  168. resolved = list(ams_mapping)
  169. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  170. if flat != -1 or not isinstance(detail, dict):
  171. continue
  172. ams_id = detail.get("ams_id")
  173. slot_id = detail.get("slot_id")
  174. if ams_id not in (254, 255) or slot_id == 255:
  175. continue
  176. resolved[i] = ams_id if is_dual_nozzle else 254
  177. return resolved
  178. def apply_tray_exist_bits(
  179. units: list,
  180. tray_exist_bits_str: str | int | None,
  181. *,
  182. power_on_flag: bool = True,
  183. log_label: str | None = None,
  184. annotate_exists: bool = False,
  185. ) -> int:
  186. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  187. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  188. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  189. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  190. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  191. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  192. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  193. instead of guessing from payload shape (#1322, #147).
  194. Two callers share this helper to keep their views consistent:
  195. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  196. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  197. facing push_status (#1726 — without this the VP would forward stale
  198. per-tray fields for empty slots, and BambuStudio's Sync would render
  199. phantom loaded slots).
  200. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  201. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  202. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  203. so spool removal is detected without requiring a manual reconnect.
  204. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  205. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  206. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  207. authoritative empty signal for the HT — the only working clear path, since
  208. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  209. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  210. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  211. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  212. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  213. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  214. the raw physical id 16 get the same bit base as callers holding the
  215. normalised 6 (#2697).
  216. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  217. way). Ints are tolerated for defensive symmetry but typically not seen
  218. on the wire. ``None`` / empty / unparseable → no-op.
  219. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  220. every processed slot. This is firmware's authoritative "spool physically
  221. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  222. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  223. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  224. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  225. leaves it False so the ``exists`` key never reaches the slicer wire format.
  226. Mutates ``units`` in place. Returns the number of slots cleared.
  227. """
  228. if not tray_exist_bits_str:
  229. return 0
  230. try:
  231. if isinstance(tray_exist_bits_str, int):
  232. tray_exist_bits = tray_exist_bits_str
  233. else:
  234. tray_exist_bits = int(tray_exist_bits_str, 16)
  235. except (ValueError, TypeError):
  236. return 0
  237. if tray_exist_bits == 0 and not power_on_flag:
  238. return 0
  239. if not isinstance(units, list):
  240. return 0
  241. cleared = 0
  242. for ams_unit in units:
  243. if not isinstance(ams_unit, dict):
  244. continue
  245. ams_id_raw = ams_unit.get("id")
  246. if ams_id_raw is None:
  247. continue
  248. try:
  249. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  250. except (ValueError, TypeError):
  251. continue
  252. if not isinstance(ams_id, int):
  253. continue
  254. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  255. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  256. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  257. # the physical 16. Both mean bit base 24, so fold them together here
  258. # rather than relying on every caller to normalise first — reading 16 as
  259. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  260. ams_id = normalize_am_unit_id(ams_id)
  261. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  262. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  263. # Anything outside those ranges has no known bit layout — don't guess it.
  264. is_ht = 128 <= ams_id <= 135
  265. if not is_ht and not (0 <= ams_id <= 15):
  266. continue
  267. for tray in ams_unit.get("tray", []):
  268. if not isinstance(tray, dict):
  269. continue
  270. tray_id_raw = tray.get("id")
  271. if tray_id_raw is None:
  272. continue
  273. try:
  274. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  275. except (ValueError, TypeError):
  276. continue
  277. if not isinstance(tray_id, int):
  278. continue
  279. global_bit = (16 + (ams_id - 128)) if is_ht else (ams_id * 4 + tray_id)
  280. slot_exists = (tray_exist_bits >> global_bit) & 1
  281. if annotate_exists:
  282. tray["exists"] = bool(slot_exists)
  283. if slot_exists:
  284. continue
  285. tray["state"] = 9
  286. if tray.get("tray_type"):
  287. if log_label:
  288. logger.debug(
  289. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  290. f"(tray_exist_bits bit {global_bit} = 0)"
  291. )
  292. tray["tray_type"] = ""
  293. tray["tray_sub_brands"] = ""
  294. tray["tray_color"] = ""
  295. tray["tray_id_name"] = ""
  296. tray["tag_uid"] = "0000000000000000"
  297. tray["tray_uuid"] = "00000000000000000000000000000000"
  298. tray["tray_info_idx"] = ""
  299. tray["remain"] = 0
  300. cleared += 1
  301. return cleared
  302. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  303. #
  304. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  305. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  306. # rack position is never mistakable for the nozzle on the other carriage.
  307. #
  308. # Extruder indices are a different namespace that happens to overlap these
  309. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  310. # Nothing below may pass a value from one namespace to the other untranslated;
  311. # doing exactly that is what #2800 was.
  312. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  313. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  314. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  315. #
  316. # Briefly changed to the plate's own slot count on the strength of a single
  317. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  318. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  319. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  320. # a calibration job, so the length varies with whatever Studio is doing rather
  321. # than with the filament count -- which makes it the wrong thing to derive.
  322. _RACK_WIRE_SLOTS = 32
  323. # The two carriages, as extruder indices in the form the queue stores (already
  324. # translated through the file's physical_extruder_map).
  325. #
  326. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  327. #
  328. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  329. # extruder 1, AMS 1 and 2 feed extruder 0;
  330. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  331. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  332. # and that print completed. So extruder 1 is the fixed hotend and extruder
  333. # 0 is the rack;
  334. # - our own constants were internally inconsistent about it: physical nozzle
  335. # id N sits on extruder N (see the L/R split in PrintersPage), and
  336. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  337. # extruder index of 0.
  338. #
  339. # These were the other way round until then, which is what dispatched a plate
  340. # to the carriage that had not been levelled and printed its first layer in
  341. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  342. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  343. # which *wire* worked, and the extruder indices were only inferred from it by
  344. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  345. # wire result stands; the inference from it did not.
  346. _FIXED_EXTRUDER_ID = 1
  347. _RACK_EXTRUDER_ID = 0
  348. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  349. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  350. # outright, which would not start the job at all. Native BambuStudio captures
  351. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  352. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  353. _FIXED_NOZZLE_ID = 1
  354. def resolve_rack_nozzle_mapping(
  355. slot_extruders: list[int],
  356. rack_nozzle_id: int | None,
  357. ) -> list[int] | None:
  358. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  359. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  360. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  361. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  362. reports as live.
  363. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  364. when the mapping cannot be resolved with confidence -- in which case the
  365. caller omits the field entirely and the firmware falls back to its own
  366. nozzle pick, exactly as it did before this translation existed. Omitting
  367. is deliberately the failure mode: a *wrong* physical ID makes the printer
  368. level with one nozzle and print with another several millimetres off the
  369. bed, which is far worse than letting the firmware choose.
  370. Returns None specifically when:
  371. - a slot needs the rack but the printer has not reported a live rack
  372. position (mid-swap, or a stale connection);
  373. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  374. for a plate sliced for the fixed hotend only (#2800 capture), so this
  375. matches it rather than naming a nozzle it does not have to name;
  376. - a slot names a carriage that is neither of the two an H2C has, which
  377. means the file was mapped for a machine this translation does not model;
  378. - the plate needs more slots than the wire format carries;
  379. - the input is not a list of whole numbers.
  380. Total by construction: it raises nothing, because the only caller is
  381. building an MQTT print command with no exception handler above it and the
  382. queue item has already been committed as `printing` by then. An
  383. unparseable input has to degrade to "let the firmware pick", not to a job
  384. wedged in a state no print will ever leave.
  385. """
  386. if not isinstance(slot_extruders, list) or not slot_extruders:
  387. return None
  388. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  389. return None
  390. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  391. return None
  392. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  393. return None
  394. # Normalise first so the checks below, and the values that reach the wire,
  395. # are known ints. bool is an int subclass and would otherwise serialise as
  396. # a JSON `true`; None means "slot not printed" and is folded into -1.
  397. normalised: list[int] = []
  398. for extruder in slot_extruders:
  399. if extruder is None:
  400. normalised.append(-1)
  401. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  402. normalised.append(extruder)
  403. else:
  404. return None
  405. if _RACK_EXTRUDER_ID not in normalised:
  406. return None
  407. wire = [-1] * _RACK_WIRE_SLOTS
  408. for index, extruder in enumerate(normalised):
  409. if extruder < 0:
  410. continue
  411. if extruder == _RACK_EXTRUDER_ID:
  412. wire[index] = rack_nozzle_id
  413. elif extruder == _FIXED_EXTRUDER_ID:
  414. wire[index] = _FIXED_NOZZLE_ID
  415. else:
  416. # An H2C has these two carriages and no others. A third index is a
  417. # file mapped for something else, and forwarding it raw would name
  418. # a physical nozzle by an index that does not identify one.
  419. return None
  420. return wire
  421. # A rack position as the operator counts it (and as the printer card and
  422. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  423. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  424. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  425. _RACK_POSITION_BASE = 15
  426. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  427. def rack_position_to_nozzle_id(position: int) -> int | None:
  428. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  429. if not isinstance(position, int) or isinstance(position, bool):
  430. return None
  431. if position not in RACK_POSITIONS:
  432. return None
  433. return _RACK_POSITION_BASE + position
  434. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  435. """Whether a live rack slot can print a group wanting this nozzle.
  436. Mirrors the filter BambuStudio applies in its own picker: the position has
  437. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  438. and flow type. A mismatch here is not cosmetic -- it is the printer being
  439. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  440. """
  441. if not isinstance(slot, dict):
  442. return False
  443. slot_diameter = str(slot.get("diameter") or "").strip()
  444. slot_type = str(slot.get("type") or "").strip()
  445. if not slot_diameter and not slot_type:
  446. return False # empty position
  447. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  448. # the printer does not.
  449. try:
  450. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  451. return False
  452. except (TypeError, ValueError):
  453. return False
  454. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  455. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  456. # printer that omits the code is not thereby ruled ineligible.
  457. wanted = volume_type.strip().lower()
  458. if wanted and slot_type:
  459. is_high_flow = slot_type.upper().startswith("HH")
  460. if wanted.startswith("high flow") != is_high_flow:
  461. return False
  462. return True
  463. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  464. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  465. _RACK_CARRIAGE_NOZZLE_ID = 0
  466. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  467. """Live rack contents keyed by 1-based position, mounted nozzle included.
  468. The firmware omits a rack id entirely while that nozzle is picked up onto
  469. the carriage (#943) -- it does not send an empty placeholder. Taking the
  470. omission at face value would rule the nozzle ineligible for the very print
  471. that wants it, and it is the single most likely position to be picked,
  472. because it is the one the last print left mounted.
  473. The absent id is recoverable only when exactly one is missing: rack ids are
  474. fixed at 16..21, so a single gap alongside a loaded carriage is that
  475. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  476. with four nozzles in six positions looks the same -- so those stay absent
  477. and the caller treats them as empty.
  478. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  479. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  480. """
  481. by_position: dict[int, dict] = {}
  482. carriage: dict | None = None
  483. for slot in rack_slots or []:
  484. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  485. continue
  486. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  487. carriage = slot
  488. continue
  489. position = slot["id"] - _RACK_POSITION_BASE
  490. if position in RACK_POSITIONS:
  491. by_position[position] = slot
  492. missing = [position for position in RACK_POSITIONS if position not in by_position]
  493. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  494. by_position[missing[0]] = carriage
  495. return by_position
  496. def resolve_rack_plan_mapping(
  497. slot_groups: list[int],
  498. groups: dict[int, dict],
  499. choice: dict[int, int],
  500. rack_slots: list[dict],
  501. ) -> tuple[list[int] | None, str | None]:
  502. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  503. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  504. That one can only name the single live rack position, so a plate wanting a
  505. different hotend per group is unresolvable to it. Here each group carries
  506. its own position, which is the operator's choice (#1784) -- the 3MF states
  507. it nowhere, proven by dispatching one plate twice with different picks and
  508. diffing the two files down to float noise.
  509. ``choice`` may be partial or empty; groups it does not name are assigned
  510. from the live rack, preferring a position already loaded with the group's
  511. own filament colour and otherwise taking the lowest eligible one.
  512. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  513. is a sentence naming what could not be satisfied. The caller decides what
  514. to do with a failure, and the two cases differ: a stale *explicit* pick
  515. should stop the print, while a failed auto-assignment should degrade to
  516. letting the firmware choose, exactly as before this existed.
  517. """
  518. if not isinstance(slot_groups, list) or not slot_groups:
  519. return None, "the plate lists no filament slots"
  520. if len(slot_groups) > _RACK_WIRE_SLOTS:
  521. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  522. by_position = _rack_by_position(rack_slots)
  523. # Assign every rack-bound group a position before building the wire, so a
  524. # group can never be handed one an earlier group already took. Explicit
  525. # picks are placed first: an auto-assignment must yield to them rather than
  526. # claim a position the operator asked for.
  527. assigned: dict[int, int] = {}
  528. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  529. for group_id in rack_group_ids:
  530. position = choice.get(group_id)
  531. if position is None:
  532. continue
  533. group = groups[group_id]
  534. if rack_position_to_nozzle_id(position) is None:
  535. return None, f"rack position {position} does not exist"
  536. if position in assigned.values():
  537. return None, f"rack position {position} is picked for more than one filament group"
  538. slot = by_position.get(position)
  539. if slot is None:
  540. return None, f"the printer reports nothing at rack position {position}"
  541. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  542. return None, (
  543. f"rack position {position} holds a "
  544. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  545. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  546. )
  547. assigned[group_id] = position
  548. for group_id in rack_group_ids:
  549. if group_id in assigned:
  550. continue
  551. group = groups[group_id]
  552. eligible = [
  553. position
  554. for position in RACK_POSITIONS
  555. if position not in assigned.values()
  556. and position in by_position
  557. and _rack_slot_is_eligible(
  558. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  559. )
  560. ]
  561. if not eligible:
  562. return None, (
  563. f"no free rack position holds a {group.get('nozzle_diameter')} "
  564. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  565. )
  566. # Prefer a position already carrying this group's colour: picking it
  567. # means the operator does not have to move filament to make the print
  568. # match what they asked for.
  569. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  570. assigned[group_id] = next(
  571. (
  572. position
  573. for position in eligible
  574. if wanted_colour
  575. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  576. == wanted_colour
  577. ),
  578. eligible[0],
  579. )
  580. wire = [-1] * _RACK_WIRE_SLOTS
  581. for index, group_id in enumerate(slot_groups):
  582. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  583. continue # slot this plate does not print
  584. group = groups.get(group_id)
  585. if group is None:
  586. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  587. if not group.get("on_rack"):
  588. wire[index] = _FIXED_NOZZLE_ID
  589. continue
  590. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  591. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  592. return None, f"filament group {group_id} resolved to no rack position"
  593. wire[index] = nozzle_id
  594. if all(value == -1 for value in wire):
  595. return None, "the plate assigns no filament to a nozzle"
  596. return wire, None
  597. @dataclass
  598. class MQTTLogEntry:
  599. """Log entry for MQTT message debugging."""
  600. timestamp: str
  601. topic: str
  602. direction: str # "in" or "out"
  603. payload: dict
  604. @dataclass
  605. class HMSError:
  606. """Health Management System error from printer."""
  607. code: str
  608. attr: int # Attribute value for constructing wiki URL
  609. module: int
  610. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  611. # The bundled catalogue's sentence for this fault, resolved once here so
  612. # every surface that reports it — the status response, the WebSocket
  613. # broadcast, the completion payload, notifications — says the same thing.
  614. # None when the catalogue does not cover the code; `describe_fault` documents
  615. # the lookup and why the lossy `hms[]` collapse is kept as it was.
  616. # Replaces a `message` field that was never set or read anywhere.
  617. description: str | None = None
  618. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  619. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  620. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  621. # HMSError without explicitly passing actions can't silently land None on the schema
  622. # boundary and raise ValidationError at routes/printers.py response time.
  623. actions: list[str] = field(default_factory=list)
  624. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  625. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  626. job_id: str | None = None
  627. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  628. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  629. # 32-bit `print_error` path. The frontend echoes this back to
  630. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  631. # used to send caused the firmware to silently reject HMS commands on H2C
  632. # (#1830) and on `hms[]`-sourced faults generally.
  633. full_code: str = ""
  634. # HMS short codes the firmware emits during normal user-cancel sequences.
  635. # These aren't faults — they're status echoes that confirm the cancel happened.
  636. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  637. # so they don't drive the printer card's "X problem" badge, the red pip, or
  638. # any other consumer that treats hms_errors as the active-fault list.
  639. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  640. {
  641. "0300_400C", # "The task was canceled."
  642. "0500_400E", # "Printing was cancelled."
  643. }
  644. )
  645. # "MQTT command verification failed" — the printer's authorization/authentication
  646. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  647. # command it could not verify. Queries (get_version, extrusion_cali_get,
  648. # pushall) still answer, so the connection looks perfectly healthy while
  649. # project_file, gcode_line and ams_change_filament are all silently dropped —
  650. # which is exactly how it presents: uploads succeed, the printer echoes our
  651. # subtask_id, then sits at IDLE forever (#2732).
  652. #
  653. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  654. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  655. # "0500_0007", which matches nothing in any catalog.
  656. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  657. @dataclass
  658. class KProfile:
  659. """Pressure advance (K) calibration profile from printer."""
  660. slot_id: int
  661. extruder_id: int
  662. nozzle_id: str
  663. nozzle_diameter: str
  664. filament_id: str
  665. name: str
  666. k_value: str
  667. n_coef: str = "0.000000"
  668. ams_id: int = 0
  669. tray_id: int = -1
  670. setting_id: str | None = None
  671. @dataclass
  672. class NozzleInfo:
  673. """Nozzle hardware configuration."""
  674. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  675. nozzle_diameter: str = "" # e.g., "0.4"
  676. @dataclass
  677. class FilaSwitchState:
  678. """Filament Track Switch (FTS) accessory state.
  679. The FTS is an external accessory that mediates filament routing between an
  680. AMS and the printer's extruders. When installed, the AMS no longer has a
  681. fixed extruder assignment — any slot can be routed to any extruder via the
  682. track switch. Detected from print.device.fila_switch in MQTT.
  683. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  684. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  685. stable, operator-visible relationship — it is set on the printer's "Manual
  686. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  687. Field semantics below are taken from BambuStudio's own parser
  688. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  689. """
  690. installed: bool = False
  691. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  692. # the arrays are ordered B-then-A, which is the opposite of how they read.
  693. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  694. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  695. in_slots: list[int] = field(default_factory=list)
  696. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  697. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  698. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  699. # inlet is currently paired with which outlet is not reported at all.
  700. out_extruders: list[int] = field(default_factory=list)
  701. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  702. info: int = 0 # bit 0 = inlet has filament
  703. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  704. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  705. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  706. one of A/B.
  707. """
  708. index = {"A": 1, "B": 0}.get(inlet.upper())
  709. if index is None or index >= len(self.in_slots):
  710. return None
  711. raw = self.in_slots[index]
  712. if raw < 0:
  713. return None
  714. return (raw >> 8) & 0xFF, raw & 0xFF
  715. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  716. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  717. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  718. # as empty everywhere is strictly safer than reading it as the external spool.
  719. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  720. @dataclass
  721. class ExtruderSlot:
  722. """Which AMS slot an extruder is currently fed from.
  723. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  724. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  725. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  726. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  727. ``state.tray_now`` cannot answer this: it is a single value for the whole
  728. printer, so on a dual-nozzle machine with both hotends loaded it names only
  729. one of them. Unloading a specific slot needs to know which extruder is
  730. holding it, which is what this is for.
  731. """
  732. ams_id: int | None = None
  733. slot_id: int | None = None
  734. has_filament: bool = False
  735. def holds(self, ams_id: int, slot_id: int) -> bool:
  736. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  737. return self.ams_id == ams_id and self.slot_id == slot_id
  738. @dataclass
  739. class PrintOptions:
  740. """AI detection and print options from xcam data."""
  741. # Core AI detectors
  742. spaghetti_detector: bool = False
  743. print_halt: bool = False
  744. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  745. first_layer_inspector: bool = False
  746. printing_monitor: bool = False # AI print quality monitoring
  747. buildplate_marker_detector: bool = False
  748. allow_skip_parts: bool = False
  749. # Additional AI detectors - decoded from cfg bitmask
  750. nozzle_clumping_detector: bool = True
  751. nozzle_clumping_sensitivity: str = "medium"
  752. pileup_detector: bool = True
  753. pileup_sensitivity: str = "medium"
  754. airprint_detector: bool = True
  755. airprint_sensitivity: str = "medium"
  756. auto_recovery_step_loss: bool = True # Uses print.print_option command
  757. filament_tangle_detect: bool = False
  758. @dataclass
  759. class PrinterState:
  760. connected: bool = False
  761. state: str = "unknown"
  762. current_print: str | None = None
  763. subtask_name: str | None = None
  764. progress: float = 0.0
  765. remaining_time: int = 0
  766. layer_num: int = 0
  767. total_layers: int = 0
  768. temperatures: dict = field(default_factory=dict)
  769. raw_data: dict = field(default_factory=dict)
  770. gcode_file: str | None = None
  771. subtask_id: str | None = None
  772. hms_errors: list = field(default_factory=list) # List of HMSError
  773. kprofiles: list = field(default_factory=list) # List of KProfile
  774. sdcard: bool = False # SD card inserted
  775. # Whether the printer has ever actually told us about `sdcard`. Without this
  776. # the default False is indistinguishable from a real "no card", and any
  777. # consumer that treats False as evidence would act on silence — which is how
  778. # a storage gate turns into a regression for every printer whose firmware
  779. # simply doesn't publish the field (#2780).
  780. sdcard_reported: bool = False
  781. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  782. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  783. # whoever sent it (the slicer or us). Bambu states where the sliced file
  784. # went: `ftp://<name>` is external storage, which FTPS serves, while
  785. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  786. #
  787. # Two fields, because the two readers need different guarantees.
  788. # ``current_project_url`` belongs to the print now running and is cleared
  789. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  790. # "unknown" rather than inheriting the previous job's answer. That matters:
  791. # 18% of the print starts in #2780's bundle had no dispatch on the request
  792. # topic at all (touchscreen reprints, restart recovery), and a stale
  793. # internal-storage URL would make those skip an FTPS sweep that could have
  794. # found the file — losing an archive that works today.
  795. #
  796. # ``last_project_url`` is sticky and exists for reporting only: the
  797. # connection diagnostic is usually run *after* the print that prompted it,
  798. # by which point the per-print value is rightly gone.
  799. #
  800. # None means we never saw a dispatch — say nothing, don't guess.
  801. current_project_url: str | None = None
  802. last_project_url: str | None = None
  803. timelapse: bool = False # Timelapse recording active
  804. ipcam: bool = False # Live view / camera streaming enabled
  805. wifi_signal: int | None = None # WiFi signal strength in dBm
  806. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  807. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  808. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  809. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  810. # right. (The legacy parser below writes left -> [0], but it only ever runs
  811. # for single-nozzle printers -- every dual-nozzle model reports
  812. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  813. # than indexing it directly.
  814. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  815. # AI detection and print options
  816. print_options: PrintOptions = field(default_factory=PrintOptions)
  817. # Calibration stage tracking (from stg_cur and stg fields)
  818. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  819. stg: list = field(default_factory=list) # List of stages to execute
  820. # Air conditioning mode (0=cooling, 1=heating)
  821. airduct_mode: int = 0
  822. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  823. speed_level: int = 2
  824. # Chamber light on/off
  825. chamber_light: bool = False
  826. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  827. active_extruder: int = 0
  828. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  829. tray_now: int = 255
  830. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  831. # tray_tar = the slot the paused/loading print now expects
  832. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  833. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  834. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  835. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  836. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  837. tray_tar: int = 255
  838. tray_pre: int = 255
  839. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  840. last_loaded_tray: int = -1
  841. # Pending load target - used to track what tray we're loading for H2D disambiguation
  842. pending_tray_target: int | None = None
  843. # AMS status for filament change tracking (from print.ams.ams_status field)
  844. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  845. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  846. ams_status: int = 0
  847. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  848. ams_status_sub: int = 0 # ams_status & 0xFF
  849. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  850. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  851. mc_print_sub_stage: int = 0
  852. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  853. ams_mapping: list = field(default_factory=list)
  854. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  855. ams_extruder_map: dict = field(default_factory=dict)
  856. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  857. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  858. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  859. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  860. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  861. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  862. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  863. ams_switch_inlet: dict = field(default_factory=dict)
  864. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  865. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  866. # series). Empty elsewhere, which every reader has to tolerate — see
  867. # ExtruderSlot for why tray_now cannot stand in for it.
  868. extruder_slots: dict = field(default_factory=dict)
  869. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  870. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  871. # regex used to derive the plate number from the path always falls back to
  872. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  873. # Bambuddy dispatches the print itself we know the plate authoritatively;
  874. # we record it here and prefer it over the gcode_file regex. The subtask
  875. # field guards against staleness: if the printer is currently running a
  876. # different subtask (e.g. a Studio-direct dispatch), these values are
  877. # ignored. Cleared on disconnect.
  878. dispatched_plate_id: int | None = None
  879. dispatched_subtask: str | None = None
  880. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  881. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  882. h2d_extruder_snow: dict = field(default_factory=dict)
  883. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  884. nozzle_rack: list = field(default_factory=list)
  885. # H2C rack position currently mounted / being moved to, from
  886. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  887. # the six rack slots), not extruder indices, and they are what the
  888. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  889. # can tell us which hotend is in the carriage right now, so this is read
  890. # live rather than derived from the queued job.
  891. nozzle_rack_src_id: int | None = None
  892. nozzle_rack_tar_id: int | None = None
  893. # Timestamp of last AMS data update (for RFID refresh detection)
  894. last_ams_update: float = 0.0
  895. # Printable objects for skip object functionality: {identify_id: object_name}
  896. printable_objects: dict = field(default_factory=dict)
  897. # Objects that have been skipped during the current print
  898. skipped_objects: list = field(default_factory=list)
  899. # Fan speeds (0-100 percentage, None if not available for this model)
  900. cooling_fan_speed: int | None = None # Part cooling fan
  901. big_fan1_speed: int | None = None # Auxiliary fan
  902. big_fan2_speed: int | None = None # Chamber/exhaust fan
  903. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  904. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  905. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  906. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  907. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  908. left_aux_fan_speed: int | None = None
  909. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  910. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  911. # omits it, which is the case this flag exists to detect.
  912. #
  913. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  914. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  915. # harmless because only the P2S/X2D badge consults it — those models keep
  916. # their unconditional "Chamber Fan" badge — but do not read this as
  917. # "an exhaust kit is fitted" without also checking the model.
  918. exhaust_fan_present: bool = False
  919. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  920. # Used by usage tracker to split filament weight on mid-print tray switch
  921. tray_change_log: list = field(default_factory=list)
  922. # Firmware version info (from info.module[name="ota"].sw_ver)
  923. firmware_version: str | None = None
  924. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  925. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  926. developer_mode: bool | None = None
  927. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  928. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  929. # which uses the old protocol path; field not yet found). Consumers must treat
  930. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  931. ams_filament_backup: bool | None = None
  932. # Stage name mapping from BambuStudio DeviceManager.cpp
  933. STAGE_NAMES = {
  934. 0: "Printing",
  935. 1: "Auto bed leveling",
  936. 2: "Heatbed preheating",
  937. 3: "Vibration compensation",
  938. 4: "Changing filament",
  939. 5: "M400 pause",
  940. 6: "Paused (filament ran out)",
  941. 7: "Heating nozzle",
  942. 8: "Calibrating dynamic flow",
  943. 9: "Scanning bed surface",
  944. 10: "Inspecting first layer",
  945. 11: "Identifying build plate type",
  946. 12: "Calibrating Micro Lidar",
  947. 13: "Homing toolhead",
  948. 14: "Cleaning nozzle tip",
  949. 15: "Checking extruder temperature",
  950. 16: "Paused by the user",
  951. 17: "Pause (front cover fall off)",
  952. 18: "Calibrating the micro lidar",
  953. 19: "Calibrating flow ratio",
  954. 20: "Pause (nozzle temperature malfunction)",
  955. 21: "Pause (heatbed temperature malfunction)",
  956. 22: "Filament unloading",
  957. 23: "Pause (step loss)",
  958. 24: "Filament loading",
  959. 25: "Motor noise cancellation",
  960. 26: "Pause (AMS offline)",
  961. 27: "Pause (low speed of the heatbreak fan)",
  962. 28: "Pause (chamber temperature control problem)",
  963. 29: "Cooling chamber",
  964. 30: "Pause (Gcode inserted by user)",
  965. 31: "Motor noise showoff",
  966. 32: "Pause (nozzle clumping)",
  967. 33: "Pause (cutter error)",
  968. 34: "Pause (first layer error)",
  969. 35: "Pause (nozzle clog)",
  970. 36: "Measuring motion precision",
  971. 37: "Enhancing motion precision",
  972. 38: "Measure motion accuracy",
  973. 39: "Nozzle offset calibration",
  974. 40: "High temperature auto bed leveling",
  975. 41: "Auto Check: Quick Release Lever",
  976. 42: "Auto Check: Door and Upper Cover",
  977. 43: "Laser Calibration",
  978. 44: "Auto Check: Platform",
  979. 45: "Confirming BirdsEye Camera location",
  980. 46: "Calibrating BirdsEye Camera",
  981. 47: "Auto bed leveling - phase 1",
  982. 48: "Auto bed leveling - phase 2",
  983. 49: "Heating chamber",
  984. 50: "Cooling heatbed",
  985. 51: "Printing calibration lines",
  986. 52: "Auto Check: Material",
  987. 53: "Live View Camera Calibration",
  988. 54: "Waiting for heatbed temperature",
  989. 55: "Auto Check: Material Position",
  990. 56: "Cutting Module Offset Calibration",
  991. 57: "Measuring Surface",
  992. 58: "Thermal Preconditioning",
  993. 59: "Homing Blade Holder",
  994. 60: "Calibrating Camera Offset",
  995. 61: "Calibrating Blade Holder Position",
  996. 62: "Hotend Pick and Place Test",
  997. 63: "Waiting for Chamber temperature",
  998. 64: "Preparing Hotend",
  999. 65: "Calibrating nozzle clumping detection",
  1000. 66: "Purifying the chamber air",
  1001. 74: "Preparing", # Seen on H2D during print preparation
  1002. 77: "Preparing AMS",
  1003. }
  1004. def get_stage_name(stage: int) -> str:
  1005. """Get human-readable stage name from stage number."""
  1006. try:
  1007. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1008. except TypeError:
  1009. # `stage` is an int by convention only -- it comes straight out of the
  1010. # printer's JSON, and an unhashable value there would otherwise raise
  1011. # from inside the f-string that builds the stage-change log line, which
  1012. # is evaluated on every transition whatever the log level is set to.
  1013. # Labelling a value must not be able to abort the state update.
  1014. return f"Unknown stage ({stage})"
  1015. # #2547 end-of-print telemetry probe.
  1016. #
  1017. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1018. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1019. # but fires on no model in the field: across 247 support bundles there is not a
  1020. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1021. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1022. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1023. #
  1024. # We can't design a replacement from bundles we already have, because out of
  1025. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1026. # every other stage/action field is dropped unread. The obvious candidates
  1027. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1028. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1029. # own. Dumping the raw values for the window between the last object layer and
  1030. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1031. # anything — marks that moment.
  1032. #
  1033. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1034. # Nothing identifying, and nothing that could carry an access code.
  1035. _END_OF_PRINT_PROBE_FIELDS = (
  1036. "gcode_state",
  1037. "state",
  1038. "print_error",
  1039. "stg_cur",
  1040. "stg",
  1041. "stg_cd",
  1042. "mc_print_stage",
  1043. "mc_print_sub_stage",
  1044. "mc_action",
  1045. "mc_stage",
  1046. "print_real_action",
  1047. "print_gcode_action",
  1048. "spd_lvl",
  1049. "mc_percent",
  1050. "mc_remaining_time",
  1051. "layer_num",
  1052. "total_layer_num",
  1053. "home_flag",
  1054. "prepare_per",
  1055. )
  1056. # Frame budget for one print's probe. A long final layer can hold the window
  1057. # open for minutes at ~1 frame/second; this stops a single print from filling
  1058. # the log the user then has to upload.
  1059. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1060. # States that close the window. FINISH is the interesting one — the probe's
  1061. # whole job is to show what happened in the run-up to it.
  1062. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1063. class BambuMQTTClient:
  1064. """MQTT client for Bambu Lab printer communication."""
  1065. MQTT_PORT = 8883
  1066. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1067. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1068. _request_topic_cache: dict[str, bool] = {}
  1069. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1070. # the request topic. A SUBACK failure is the broker answering the question;
  1071. # a disconnect is only circumstantial, and any drop inside the window looks
  1072. # identical -- a network blip, the printer rebooting, the container being
  1073. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1074. # the rest of the process on a printer that supports it perfectly well
  1075. # (#2953). Require the drop to repeat before believing it; a printer that
  1076. # really does refuse the topic answers the same way every time and pays one
  1077. # extra reconnect for it.
  1078. _request_topic_probe_failures: dict[str, int] = {}
  1079. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1080. # Counter for generating unique MQTT client IDs across instances.
  1081. _client_instance_counter: int = 0
  1082. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1083. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1084. # every few seconds (and register_assignment_verification nudges a fresh
  1085. # pushall), so this only has to survive a couple of idle push intervals.
  1086. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1087. def __init__(
  1088. self,
  1089. ip_address: str,
  1090. serial_number: str,
  1091. access_code: str,
  1092. model: str | None = None,
  1093. on_state_change: Callable[[PrinterState], None] | None = None,
  1094. on_print_start: Callable[[dict], None] | None = None,
  1095. on_print_complete: Callable[[dict], None] | None = None,
  1096. on_ams_change: Callable[[list], None] | None = None,
  1097. on_layer_change: Callable[[int], None] | None = None,
  1098. on_print_progress: Callable[[int], None] | None = None,
  1099. on_bed_temp_update: Callable[[float], None] | None = None,
  1100. on_drying_complete: Callable[[int], None] | None = None,
  1101. on_print_running_observed: Callable[[dict], None] | None = None,
  1102. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1103. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1104. on_tray_change: Callable[[int, int], None] | None = None,
  1105. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1106. ):
  1107. self.ip_address = ip_address
  1108. self.serial_number = serial_number
  1109. self.access_code = access_code
  1110. self.model = model
  1111. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1112. self._debug_last: dict[str, object] = {}
  1113. self.on_state_change = on_state_change
  1114. self.on_print_start = on_print_start
  1115. self.on_print_complete = on_print_complete
  1116. self.on_ams_change = on_ams_change
  1117. # Fired when an AMS is moved to the switch's other inlet, which changes
  1118. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1119. self.on_fts_inlet_change = on_fts_inlet_change
  1120. self.on_layer_change = on_layer_change
  1121. # #2547: fired when `mc_percent` advances during a running print.
  1122. # `on_layer_change` stops firing the instant the final layer starts, so
  1123. # it is blind to the last few percent of a print — which is exactly the
  1124. # window the finish-photo frame bank needs to keep refreshing through.
  1125. # Progress is the one field that keeps ticking there and then freezes
  1126. # before the end G-code runs, so banking on it stays inside the print.
  1127. self.on_print_progress = on_print_progress
  1128. self.on_bed_temp_update = on_bed_temp_update
  1129. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1130. # the drying cycle just finished (auto- or manually-triggered).
  1131. # Receives the AMS id of the unit that finished drying.
  1132. self.on_drying_complete = on_drying_complete
  1133. # #1485 follow-up: fired the first time we see RUNNING state in a
  1134. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1135. # print, the #1304 first-push guard skipped the start event). Lets
  1136. # main.py capture a fresh timelapse baseline at restart-recovery
  1137. # time so the completion-time snapshot-diff still works. Receives
  1138. # the same shape as on_print_start (filename / subtask_name /
  1139. # remaining_time / raw_data / ams_mapping).
  1140. self.on_print_running_observed = on_print_running_observed
  1141. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1142. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1143. # with the process, and a long print outliving a restart would
  1144. # otherwise lose the segment boundaries the usage tracker splits on.
  1145. # Receives (global_tray_id, layer_num).
  1146. self.on_tray_change = on_tray_change
  1147. # #1721: fired the moment the printer enters the end-of-print
  1148. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1149. # we've hit the last layer / remaining_time<=0). This is the
  1150. # framing #1397 was after — toolhead parked, bed not yet
  1151. # dropped — but reached via a clean state signal instead of
  1152. # the per-layer M622 J1 macros which caused per-layer nozzle
  1153. # parks on slicer profiles with Timelapse Type = Smooth.
  1154. # A FINISH-state fallback below fires this same callback if
  1155. # stage 22 never arrives (cancel mid-print, external-spool-
  1156. # only prints, HMS halt before unload, firmware variants).
  1157. self.on_finish_photo_moment = on_finish_photo_moment
  1158. # #2582: fired after a spool assignment (ams_filament_setting +
  1159. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1160. # push landed or a timeout elapses without it. Receives
  1161. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1162. # tell the user "loaded" vs "assignment didn't take" instead of the
  1163. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1164. # feel random. See _check_assignment_verifications.
  1165. self.on_assignment_verified = on_assignment_verified
  1166. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1167. # value is the desired end-state we just pushed plus a monotonic
  1168. # deadline. Populated by register_assignment_verification, drained by
  1169. # _check_assignment_verifications on every AMS push.
  1170. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1171. # Per-AMS previous dry_time, used to detect the falling edge above.
  1172. # Seeded lazily as we observe each AMS unit.
  1173. self._previous_dry_times: dict[int, int] = {}
  1174. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1175. # A live cycle's countdown ticks once a minute; a command the firmware
  1176. # accepted but never actually started (observed on an H2D mid-print
  1177. # with two AMS-HT cycles already running: the third unit's timer sat
  1178. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1179. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1180. # reported as dry_countdown_stalled so the UI can stop claiming an
  1181. # active cycle that is not running.
  1182. self._dry_time_changed_at: dict[int, float] = {}
  1183. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1184. # last start. Bambu does not echo these back in the per-tick AMS push
  1185. # — only the dry_time countdown — so we cache what we sent to drive
  1186. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1187. self._drying_targets: dict[int, dict[str, object]] = {}
  1188. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1189. # ends a cycle far short of its duration, which on the telemetry alone
  1190. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1191. # log would otherwise blame the printer for our own decision (#2770).
  1192. self._drying_stops_sent: set[int] = set()
  1193. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1194. # for, so each is reported once rather than on every transition into it.
  1195. self._unnamed_stages_seen: set[int] = set()
  1196. self.state = PrinterState()
  1197. self._client: mqtt.Client | None = None
  1198. self._loop: asyncio.AbstractEventLoop | None = None
  1199. self._previous_gcode_state: str | None = None
  1200. self._previous_gcode_file: str | None = None
  1201. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1202. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1203. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1204. # #1721: one-shot guard so the end-of-print stage-22 detector
  1205. # and the FINISH-state fallback don't both fire on the same
  1206. # print. Reset to False on every print start.
  1207. self._finish_photo_captured: bool = False
  1208. # #2702: one-shot re-request of the layer total. Armed at print start
  1209. # when the starting frame carried no `total_layer_num`, spent on the
  1210. # first layer advance that still has no denominator. Bambu firmware
  1211. # only re-sends *changed* fields, so a total we never received (or
  1212. # dropped) is only recoverable via a full pushall.
  1213. self._total_layers_refresh_armed: bool = False
  1214. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1215. # window has run for a print so a late FINISH re-send can't reopen it.
  1216. self._eop_probe_armed: bool = True
  1217. self._eop_probe_open: bool = False
  1218. self._eop_probe_frames: int = 0
  1219. self._eop_probe_last: dict = {}
  1220. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1221. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1222. # The subtask_id minted for the most recent start_print() command. The
  1223. # printer echoes it back in status, but often not within the first few
  1224. # seconds — so on_print_start uses this as the id source when the
  1225. # printer hasn't reported it yet, letting queue/scheduled archives
  1226. # persist a restart-stable id from the moment they dispatch (#1485).
  1227. self.last_dispatch_subtask_id: str | None = None
  1228. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1229. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1230. self._logging_enabled: bool = False
  1231. self._last_message_time: float = 0.0 # Track when we last received a message
  1232. # Count of report-topic messages received since the last (re)connect.
  1233. # Lets check_staleness() distinguish "printer never sent a status
  1234. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1235. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1236. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1237. self._report_messages_since_connect: int = 0
  1238. self._zero_report_hint_logged: bool = False
  1239. # Set by mark_power_off() to the gcode_state held just before we
  1240. # optimistically forced the printer to "unknown" (#2629). Restored on
  1241. # the next inbound message, because message traffic proves the power
  1242. # was never actually cut. None whenever no power-off is presumed.
  1243. self._state_before_power_off: str | None = None
  1244. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1245. # printer's pushes verbatim to slicers connected to a virtual printer).
  1246. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1247. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1248. self._disconnection_event: threading.Event | None = None
  1249. self._previous_ams_hash: str | None = None # Track AMS changes
  1250. # Track external-spool (vt_tray) identity changes separately: the AMS
  1251. # hash above covers only AMS units, so an external-spool-only filament
  1252. # swap would never re-trigger inventory reconciliation (#2575).
  1253. self._previous_vt_tray_hash: str | None = None
  1254. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1255. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1256. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1257. # Track which (ams_id, field) warnings have already been emitted this connection
  1258. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1259. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1260. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1261. # keyed by the sequence_id we sent, so two concurrent requests for
  1262. # different nozzle sizes can't steal each other's response (#1748).
  1263. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1264. self._sequence_id: int = 0
  1265. self._pending_kprofile_requests: dict[str, dict] = {}
  1266. # The printer's calibration table, one bucket per nozzle diameter.
  1267. #
  1268. # An extrusion_cali_get response is the complete table for *one* nozzle
  1269. # size, and the printer answers whoever asks — including BambuStudio,
  1270. # whose queries land on the same report topic we subscribe to. Assigning
  1271. # each response straight to state.kprofiles therefore let any single
  1272. # answer stand for the whole printer: a GitHub backup probing
  1273. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1274. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1275. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1276. # card because H2-series trays carry no `k` of their own — the slot's
  1277. # K value is resolved from cali_idx against exactly this list.
  1278. #
  1279. # Keyed by diameter so a response only ever replaces the bucket it
  1280. # actually describes; state.kprofiles is then the union across buckets.
  1281. # An empty answer for a nozzle the printer doesn't have empties that
  1282. # bucket alone.
  1283. self._kprofiles_by_nozzle: dict[str, list] = {}
  1284. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1285. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1286. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1287. # by await_cali_ack.
  1288. self._pending_cali_acks: dict[str, dict | None] = {}
  1289. # Identifies the one project_file *we* dispatched, so its echo on the
  1290. # topic can be told apart from a slicer's. One-shot: consumed by the
  1291. # first frame that matches. See _project_file_key.
  1292. self._own_project_file_key: str | None = None
  1293. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1294. # Key: module_name, Value: timestamp when command was sent
  1295. self._xcam_hold_start: dict[str, float] = {}
  1296. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1297. # Track last requested tray ID for H2D dual-nozzle printers
  1298. # H2D only reports slot number (0-3) in tray_now, not global tray ID
  1299. # We use our tracked value to resolve the correct global ID
  1300. self._last_load_tray_id: int | None = None
  1301. # Captured ams_mapping from print commands on the request topic
  1302. # Intercepts slicer/Bambuddy print commands to get the slot-to-tray mapping
  1303. self._captured_ams_mapping: list[int] | None = None
  1304. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1305. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1306. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1307. self._has_a2l_am_unit: bool = False
  1308. # Why the last connection attempt was refused by the printer, or None
  1309. # when we have never seen a CONNACK failure since the last success.
  1310. # Without this a rejected access code was completely invisible: paho
  1311. # reports the follow-up disconnect as the generic "Unspecified error"
  1312. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1313. # printer stuck in a reconnect loop looked identical whether it was
  1314. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1315. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1316. # string, kept for the log line only.
  1317. self.last_connect_error: str | None = None
  1318. self.last_connect_error_name: str | None = None
  1319. # Request topic subscription tracking
  1320. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1321. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1322. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1323. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1324. self._request_topic_sub_mid: int | None = None
  1325. self._request_topic_sub_time: float = 0.0
  1326. self._request_topic_confirmed: bool = False
  1327. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1328. # we probe by sending an ams_filament_setting and checking the response.
  1329. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1330. self._dev_mode_probed: bool = False
  1331. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1332. self._dev_mode_probe_seq: str | None = None
  1333. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1334. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1335. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1336. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1337. # the printer reports it until the fault clears, so when a later hms[]
  1338. # arrives without it (user enabled Developer Mode and restarted the
  1339. # printer) we drop back to "unknown" and let the probe re-run instead of
  1340. # leaving a permanently-wrong False behind (#2732).
  1341. self._dev_mode_from_hms: bool = False
  1342. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1343. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1344. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1345. self._stale_reconnecting: bool = False
  1346. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1347. # when the frontend polls status faster than paho can reconnect.
  1348. self._last_stale_reconnect: float = 0.0
  1349. # Zombie session detection via ams_filament_setting response tracking (#887).
  1350. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1351. # that develop later (telemetry flows but publishes silently fail).
  1352. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1353. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1354. @property
  1355. def topic_subscribe(self) -> str:
  1356. return f"device/{self.serial_number}/report"
  1357. @property
  1358. def topic_publish(self) -> str:
  1359. return f"device/{self.serial_number}/request"
  1360. @property
  1361. def report_messages_since_connect(self) -> int:
  1362. """Count of report-topic messages received since the latest (re)connect.
  1363. Exposed for the connection diagnostic so it can distinguish "MQTT
  1364. broker accepted us but the printer never published" (typically a
  1365. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1366. bridge that happens to be idle right now. Zero immediately after a
  1367. fresh connect is normal; zero after a full status push cycle is the
  1368. wrong-serial failure mode.
  1369. """
  1370. return self._report_messages_since_connect
  1371. # Maximum time (seconds) without a message before considering connection stale
  1372. STALE_TIMEOUT = 60.0
  1373. def is_stale(self) -> bool:
  1374. """Check if the connection is stale (no messages for too long)."""
  1375. if self._last_message_time == 0:
  1376. return False # Never received a message yet
  1377. time_since_last = time.time() - self._last_message_time
  1378. return time_since_last > self.STALE_TIMEOUT
  1379. def mark_power_off(self) -> bool:
  1380. """Presume the printer lost power (smart plug switched off).
  1381. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1382. The presumption is undone by ``_on_message`` if the printer keeps
  1383. talking — inbound traffic proves the power was never cut (#2629).
  1384. Returns True when the state was actually changed.
  1385. """
  1386. if not self.state.connected:
  1387. return False
  1388. previous = self.state.state
  1389. # Blank the state BEFORE recording what to restore. This runs on the
  1390. # event loop while _on_message runs on the paho thread, and the restore
  1391. # is a two-step (read saved state, compare against "unknown"). Writing
  1392. # "unknown" first means an interleaved message either sees no saved
  1393. # state yet (and skips, leaving the next message to restore) or sees a
  1394. # consistent pair — never a saved state paired with a live state it
  1395. # then discards, which would strand the printer on "unknown".
  1396. self.state.connected = False
  1397. self.state.state = "unknown"
  1398. # Only the first mark wins: a second call before any message arrives
  1399. # must not overwrite the real state with the "unknown" it just wrote.
  1400. # Nothing to restore if the state was already blank.
  1401. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1402. self._state_before_power_off = previous
  1403. return True
  1404. def _restore_state_after_false_power_off(self) -> bool:
  1405. """Undo a presumed power-off once the printer proves it is alive.
  1406. ``connected`` self-heals on the next message, but ``state`` does not:
  1407. it is only rewritten when a payload carries ``gcode_state``, and the
  1408. steady-state ``push_status`` frames are partial. Without this the
  1409. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1410. and the queue scheduler treats the printer as not idle the whole time
  1411. (#2629). Returns True when a state was restored.
  1412. """
  1413. previous = self._state_before_power_off
  1414. self._state_before_power_off = None
  1415. if previous is None or self.state.state != "unknown":
  1416. return False
  1417. logger.info(
  1418. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1419. self.serial_number,
  1420. previous,
  1421. )
  1422. self.state.state = previous
  1423. return True
  1424. # Minimum seconds between stale reconnect attempts. Frontend polls
  1425. # status every few seconds — without a cooldown, each poll would
  1426. # force-close the socket before paho has time to reconnect.
  1427. STALE_RECONNECT_COOLDOWN = 30.0
  1428. def check_staleness(self) -> bool:
  1429. """Check staleness and update connected state if stale. Returns True if connected."""
  1430. if self.state.connected and self.is_stale():
  1431. # Don't force-close again if we already did recently — give paho
  1432. # time to reconnect and the printer time to send its first message.
  1433. now = time.time()
  1434. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1435. return self.state.connected
  1436. logger.warning(
  1437. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1438. )
  1439. # A connection that keeps going stale without ever receiving a
  1440. # status report is almost always a wrong or mis-cased serial
  1441. # number — the broker accepts the connection and the subscription
  1442. # regardless, but the printer publishes to device/<real-serial>/
  1443. # report, which is case-sensitive. Surface that once so the user
  1444. # has something actionable instead of an endless reconnect loop.
  1445. # Only meaningful once the *current* session has had time to receive
  1446. # something. _report_messages_since_connect is reset by _on_connect,
  1447. # so a reconnect that lands microseconds before this check leaves it
  1448. # at 0 for reasons that have nothing to do with the serial — which is
  1449. # how a healthy P1S ended up being told to go check its serial number
  1450. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1451. # on this session means the hint only fires when the printer really
  1452. # has published nothing to the topic we subscribed to.
  1453. # _connect_time of 0 means we have no timestamp to judge by (never went
  1454. # through _on_connect); fall back to the old unconditional behaviour
  1455. # rather than silently swallowing the hint.
  1456. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1457. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1458. self._zero_report_hint_logged = True
  1459. logger.warning(
  1460. "[%s] Connected and subscribed, but the printer has sent zero "
  1461. "status reports. The most common cause is a wrong or mis-cased "
  1462. "serial number — the device/<serial>/report MQTT topic is "
  1463. "case-sensitive. Verify the serial number configured in Bambuddy "
  1464. "exactly matches the printer.",
  1465. self.serial_number,
  1466. )
  1467. self._last_stale_reconnect = now
  1468. self.state.connected = False
  1469. if self.on_state_change:
  1470. self.on_state_change(self.state)
  1471. # Route based on caller thread — see force_reconnect_stale_session.
  1472. # check_staleness is normally called from FastAPI handlers (async,
  1473. # gets the hard-reset path) but the dispatcher exists for safety.
  1474. self._stale_reconnecting = True
  1475. self._reset_client_for_reconnect()
  1476. return self.state.connected
  1477. def force_reconnect_stale_session(self, reason: str) -> None:
  1478. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1479. # arriving but our publishes don't reach the printer.
  1480. #
  1481. # Two routing paths:
  1482. #
  1483. # Async-context callers (queue dispatch deadline)
  1484. # → full client teardown + fresh client_id. Wipes paho's client-side
  1485. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1486. # `project_file` from the broken session would otherwise replay on
  1487. # reconnect, mixing stale commands into the next dispatch and
  1488. # triggering 0500_4003 SD R/W on the printer.
  1489. #
  1490. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1491. # zombie detection, both inside `_update_state`)
  1492. # → socket-close fallback. There is no running loop on that thread to
  1493. # hand the rebuilt client, so close the socket and let paho's own
  1494. # loop detect the broken connection and auto-reconnect (same
  1495. # instance, same client_id — queue replay is theoretically possible
  1496. # here but those paths have always done socket-close and #1136 was
  1497. # specifically triggered from the dispatch path).
  1498. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1499. self._stale_reconnecting = True
  1500. self.state.connected = False
  1501. if self.on_state_change:
  1502. self.on_state_change(self.state)
  1503. self._reset_client_for_reconnect()
  1504. def _reset_client_for_reconnect(self) -> None:
  1505. """Route between hard-reset and socket-close based on caller thread.
  1506. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1507. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1508. answers that and identifies the caller in one go — paho's callback
  1509. thread has no loop; every legitimate hard-reset caller (FastAPI
  1510. handlers, background async tasks) does."""
  1511. try:
  1512. loop = asyncio.get_running_loop()
  1513. except RuntimeError:
  1514. loop = None
  1515. if loop is not None:
  1516. self._loop = loop
  1517. self._hard_reset_client()
  1518. else:
  1519. self._socket_close_for_reconnect()
  1520. def _hard_reset_client(self) -> None:
  1521. """Tear down the paho client entirely and rebuild it with a fresh
  1522. client_id, so the broker drops the old session and paho's local
  1523. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1524. Caller is responsible for setting ``_stale_reconnecting`` and
  1525. broadcasting the disconnected state.
  1526. Returns as fast as it can build a client: the old one's teardown is
  1527. handed off rather than waited on, because waiting on it is what
  1528. stopped the event loop in #3068. See ``retire_paho_client``."""
  1529. old_client = self._client
  1530. self._client = None
  1531. if old_client is not None:
  1532. retire_paho_client(old_client, self.serial_number)
  1533. # Skip reconnect if no asyncio loop is available (test environment or
  1534. # pre-init). The next initial connect() call from PrinterManager will
  1535. # set up the client fresh.
  1536. if self._loop is None:
  1537. return
  1538. try:
  1539. self.connect(loop=self._loop)
  1540. except Exception as e:
  1541. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1542. def _socket_close_for_reconnect(self) -> None:
  1543. """Close the underlying socket so paho's loop thread detects the
  1544. broken connection and triggers auto-reconnect on the SAME client
  1545. instance. Safe to call from paho's own network thread (the loop
  1546. polls the socket on every iteration and handles a closed socket
  1547. gracefully). Used as a fallback when hard-reset isn't safe; queue
  1548. replay remains theoretically possible here but #1136 specifically
  1549. traced through the dispatch-deadline path which now hard-resets."""
  1550. if self._client:
  1551. try:
  1552. sock = self._client.socket()
  1553. if sock:
  1554. sock.close()
  1555. except Exception:
  1556. pass
  1557. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1558. if rc == 0:
  1559. self.state.connected = True
  1560. self.last_connect_error = None
  1561. self.last_connect_error_name = None
  1562. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1563. # A dropped-and-restored MQTT session means the presumed power-off was
  1564. # real (or at least that the printer restarted): there is nothing
  1565. # legitimate left to restore, and the printer will send a full status
  1566. # push shortly. Dropping the saved state keeps a stale one from being
  1567. # broadcast ahead of the first real report (#2629, #1679).
  1568. self._state_before_power_off = None
  1569. # Reset per-connection warning state so warnings fire once per (re)connection
  1570. self._ams_version_warned = set()
  1571. # Preserve cached developer_mode across auto-reconnects to avoid
  1572. # re-probing on every reconnect. The probe (ams_filament_setting to
  1573. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1574. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1575. # once when developer_mode is truly unknown (first connect).
  1576. # Reset probe tracking so stale timeout state doesn't carry over.
  1577. self._dev_mode_probed = False
  1578. self._dev_mode_needs_probe = False
  1579. self._dev_mode_probe_seq = None
  1580. self._dev_mode_probe_time = 0.0
  1581. self._dev_mode_probe_failures = 0
  1582. self._connect_time = time.monotonic()
  1583. self._report_messages_since_connect = 0
  1584. self._last_ams_cmd_time = 0.0
  1585. self._ams_cmd_unanswered = 0
  1586. # Drop any assignment verifications that were mid-flight before the
  1587. # reconnect — their deadlines are stale and the tray state we would
  1588. # compare against is about to be re-pushed from scratch (#2582).
  1589. # Dropping is silent (no failure event) on purpose.
  1590. self._pending_assignments.clear()
  1591. client.subscribe(self.topic_subscribe)
  1592. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1593. if self._request_topic_supported:
  1594. result, mid = client.subscribe(self.topic_publish)
  1595. if result == mqtt.MQTT_ERR_SUCCESS:
  1596. self._request_topic_sub_mid = mid
  1597. self._request_topic_sub_time = time.time()
  1598. self._request_topic_confirmed = False
  1599. else:
  1600. logger.warning(
  1601. "[%s] Failed to send request topic subscription",
  1602. self.serial_number,
  1603. )
  1604. self._request_topic_supported = False
  1605. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1606. # Request full status update (includes nozzle info in push_status response)
  1607. self._request_push_all()
  1608. # Request firmware version info
  1609. self._request_version()
  1610. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1611. # The correct nozzle data comes from push_status.
  1612. # Prime K-profile request (Bambu printers often ignore first request)
  1613. self._prime_kprofile_request()
  1614. # Immediately broadcast connection state change
  1615. if self.on_state_change:
  1616. self.on_state_change(self.state)
  1617. else:
  1618. self.state.connected = False
  1619. self._record_connect_refusal(rc)
  1620. def _record_connect_refusal(self, rc) -> None:
  1621. """Log and remember why the printer refused the MQTT connection.
  1622. The failure branch of ``_on_connect`` used to be a bare
  1623. ``connected = False``, which threw away the only signal that says
  1624. *why* a printer never comes online. The user-visible result was a
  1625. 30-second reconnect loop logging nothing but paho's generic
  1626. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1627. powered-off printer, so "my printer won't print" reports could not be
  1628. triaged without a round trip (#2698).
  1629. Never logs the access code itself; the code is the likely culprit but
  1630. printing it would put a credential in every support bundle.
  1631. """
  1632. code = getattr(rc, "value", rc)
  1633. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1634. self.last_connect_error_name = name
  1635. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1636. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1637. logger.warning(
  1638. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1639. "or serial number is wrong — the access code changes every time LAN Only or "
  1640. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1641. self.serial_number,
  1642. name,
  1643. code,
  1644. )
  1645. else:
  1646. self.last_connect_error = CONNECT_ERROR_REFUSED
  1647. logger.warning(
  1648. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1649. self.serial_number,
  1650. name,
  1651. code,
  1652. )
  1653. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1654. """Handle SUBACK responses to detect request topic subscription rejection."""
  1655. if mid == self._request_topic_sub_mid:
  1656. for rc in reason_code_list:
  1657. if rc.is_failure:
  1658. logger.warning(
  1659. "[%s] Request topic subscription rejected (code=%d: %s). "
  1660. "ams_mapping capture from slicer-initiated prints unavailable.",
  1661. self.serial_number,
  1662. rc.value,
  1663. rc.getName(),
  1664. )
  1665. self._request_topic_supported = False
  1666. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1667. else:
  1668. logger.info(
  1669. "[%s] Request topic subscription accepted. "
  1670. "ams_mapping capture enabled for slicer-initiated prints.",
  1671. self.serial_number,
  1672. )
  1673. self._request_topic_confirmed = True
  1674. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  1675. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  1676. self._request_topic_sub_mid = None
  1677. self._request_topic_sub_time = 0.0
  1678. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  1679. # Always unblock disconnect() callers, regardless of whether we suppress
  1680. # the state broadcast below. disconnect() sets _disconnection_event and
  1681. # waits on it — every callback path must fire it.
  1682. if self._disconnection_event:
  1683. self._disconnection_event.set()
  1684. # If we intentionally closed the socket for stale reconnect, don't broadcast
  1685. # another state change — check_staleness() already set connected=False and
  1686. # notified the UI. Just log and let paho auto-reconnect.
  1687. if self._stale_reconnecting:
  1688. logger.info(
  1689. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  1690. self.serial_number,
  1691. rc,
  1692. )
  1693. return
  1694. # Ignore spurious disconnect callbacks if we've received a message recently
  1695. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  1696. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  1697. # — only suppress when rc indicates a clean/normal disconnect.
  1698. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  1699. time_since_last_message = time.time() - self._last_message_time
  1700. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  1701. logger.debug(
  1702. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  1703. )
  1704. return
  1705. # Carry the last CONNACK refusal into the disconnect line. paho reports
  1706. # the drop that follows a refused CONNACK as "Unspecified error", so on
  1707. # its own this line says nothing useful about a printer that is looping
  1708. # on bad credentials — and this is the line that fills a support bundle
  1709. # (#2698).
  1710. if self.last_connect_error:
  1711. logger.warning(
  1712. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  1713. self.serial_number,
  1714. rc,
  1715. disconnect_flags,
  1716. self.last_connect_error_name,
  1717. )
  1718. else:
  1719. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  1720. # Detect if request topic subscription caused the disconnect.
  1721. # If we just subscribed and got disconnected before any SUBACK confirmation,
  1722. # the broker likely killed the connection due to the unauthorized subscription.
  1723. if (
  1724. self._request_topic_sub_time > 0
  1725. and not self._request_topic_confirmed
  1726. and time.time() - self._request_topic_sub_time < 10.0
  1727. # A disconnect we asked for says nothing about the subscription.
  1728. and self._disconnection_event is None
  1729. ):
  1730. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  1731. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  1732. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  1733. logger.warning(
  1734. "[%s] Disconnected shortly after request topic subscription %d times. "
  1735. "Disabling request topic for this printer — ams_mapping capture from "
  1736. "slicer-initiated prints is unavailable, and their filament will be "
  1737. "attributed from the printer's own tray reporting instead.",
  1738. self.serial_number,
  1739. failures,
  1740. )
  1741. self._request_topic_supported = False
  1742. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1743. else:
  1744. logger.info(
  1745. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  1746. "Retrying it on the next connection before giving up.",
  1747. self.serial_number,
  1748. failures,
  1749. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  1750. )
  1751. self._request_topic_sub_mid = None
  1752. self._request_topic_sub_time = 0.0
  1753. self.state.connected = False
  1754. if self.on_state_change:
  1755. self.on_state_change(self.state)
  1756. def _on_message(self, client, userdata, msg):
  1757. for handler in self._raw_message_handlers:
  1758. try:
  1759. handler(msg.topic, msg.payload)
  1760. except Exception:
  1761. logger.exception(
  1762. "[%s] raw-message handler crashed for topic=%s",
  1763. self.serial_number,
  1764. msg.topic,
  1765. )
  1766. try:
  1767. try:
  1768. raw = msg.payload.decode()
  1769. except UnicodeDecodeError:
  1770. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  1771. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  1772. raw = msg.payload.decode(errors="replace")
  1773. logger.warning(
  1774. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  1775. self.serial_number,
  1776. msg.topic,
  1777. len(msg.payload),
  1778. )
  1779. payload = json.loads(raw)
  1780. # Track last message time - receiving a message proves we're connected
  1781. self._last_message_time = time.time()
  1782. self.state.connected = True
  1783. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  1784. if msg.topic == self.topic_publish:
  1785. # Record it before returning. This topic carries every command
  1786. # travelling *to* the printer, including the ones Bambu Studio
  1787. # sends, and it used to be the one thing an MQTT capture could
  1788. # never show -- which is why "what does Studio put in the drying
  1789. # command?" had no answer from a user's log (#2774). Filed as
  1790. # "out" so the direction filter groups it with our own commands
  1791. # rather than with printer telemetry; anything sent through
  1792. # send_command lands twice, once on publish and once on the
  1793. # broker's echo, and the pair is itself evidence the command
  1794. # reached the broker.
  1795. if self._logging_enabled:
  1796. self._message_log.append(
  1797. MQTTLogEntry(
  1798. timestamp=datetime.now(timezone.utc).isoformat(),
  1799. topic=msg.topic,
  1800. direction="out",
  1801. payload=payload,
  1802. )
  1803. )
  1804. self._handle_request_message(payload)
  1805. return
  1806. # Count status reports per connection so check_staleness() can tell
  1807. # "printer never sent a report" apart from a mid-session quiet gap.
  1808. if msg.topic == self.topic_subscribe:
  1809. self._report_messages_since_connect += 1
  1810. # Only report-topic traffic proves the *printer* is alive — the
  1811. # request topic also carries slicer/Bambuddy commands.
  1812. if self._state_before_power_off is not None:
  1813. if self._restore_state_after_false_power_off() and self.on_state_change:
  1814. self.on_state_change(self.state)
  1815. # Log message if logging is enabled
  1816. if self._logging_enabled:
  1817. self._message_log.append(
  1818. MQTTLogEntry(
  1819. timestamp=datetime.now(timezone.utc).isoformat(),
  1820. topic=msg.topic,
  1821. direction="in",
  1822. payload=payload,
  1823. )
  1824. )
  1825. self._process_message(payload)
  1826. except json.JSONDecodeError:
  1827. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  1828. def _handle_request_message(self, data: dict) -> None:
  1829. """Intercept print commands on the request topic to capture ams_mapping."""
  1830. print_data = data.get("print", {})
  1831. if not isinstance(print_data, dict):
  1832. return
  1833. command = print_data.get("command", "")
  1834. if command == "project_file":
  1835. # Where the dispatcher put the sliced file. Captured for every
  1836. # project_file, ours included: we publish to this same topic and
  1837. # subscribe to it, so whoever dispatched last wins, which is exactly
  1838. # the print the archive lookup is about to go looking for (#2780).
  1839. url = print_data.get("url")
  1840. if isinstance(url, str) and url:
  1841. self.state.current_project_url = url
  1842. self.state.last_project_url = url
  1843. if "ams_mapping" in print_data:
  1844. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  1845. logger.info(
  1846. "[%s] Captured ams_mapping from print command: %s",
  1847. self.serial_number,
  1848. self._captured_ams_mapping,
  1849. )
  1850. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  1851. # slicer-launched project_file passes through the request topic,
  1852. # log the full payload so we can diff Studio's field set against
  1853. # ours.
  1854. #
  1855. # This used to read `sequence_id != "20000"`, on the belief that
  1856. # 20000 was ours alone. It is not: 20000 is the slicer convention
  1857. # Bambuddy adopted -- bind_server documents the slicer sending it
  1858. # during detect, and measured on the wire OrcaSlicer dispatched
  1859. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  1860. # counting up from the same base. So the test swallowed whichever
  1861. # slicer dispatch happened to land on 20000, which on a fresh
  1862. # slicer start is the first one. Match our own dispatch instead.
  1863. if self._project_file_key(print_data) == self._own_project_file_key:
  1864. self._own_project_file_key = None
  1865. else:
  1866. logger.info(
  1867. "[%s] External project_file payload: %s",
  1868. self.serial_number,
  1869. json.dumps(print_data),
  1870. )
  1871. def _capture_report_project_file(self, print_data: dict) -> None:
  1872. """Read a print's destination off a ``project_file`` *response* (#1820).
  1873. ``_handle_request_message`` only ever sees the request topic, so a print
  1874. started from the printer's own touchscreen -- which publishes nothing --
  1875. left ``current_project_url`` at None, and the storage verdict fell
  1876. through to the ``sdcard`` fallback for the one case it was written for.
  1877. On an H2S that flag is True (its "card" is the internal eMMC), so the
  1878. verdict came back reachable and the ~110-connection sweep ran in full.
  1879. The printer does announce it: an unsolicited ``project_file`` response
  1880. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  1881. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  1882. This also covers an install nobody had in view: some brokers refuse the
  1883. request-topic subscription, and on those no print of any kind has ever
  1884. populated the field.
  1885. Both kinds of ``project_file`` on this topic are read -- the printer's
  1886. echo of a dispatch and a screen start -- because both name the
  1887. destination in ``url``, which is the only thing the verdict wants. What
  1888. this must NOT do is reuse ``_handle_request_message``'s "External
  1889. project_file payload" diagnostic: our own dispatch is echoed on *both*
  1890. topics, the request-topic echo arrives first and clears
  1891. ``_own_project_file_key``, so by the time this frame lands the key is
  1892. already None and every Bambuddy-started print would log itself as
  1893. someone else's.
  1894. """
  1895. # Same shape as _handle_request_message: the frame is whatever the
  1896. # printer put on the wire, and this is the first thing to touch it.
  1897. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  1898. return
  1899. # A refused dispatch names a file that was never written. Acting on it
  1900. # would pin an archive on a destination nothing ever went to.
  1901. if print_data.get("result") != "SUCCESS":
  1902. return
  1903. url = print_data.get("url")
  1904. if not isinstance(url, str) or not url:
  1905. return
  1906. if self.state.current_project_url != url:
  1907. logger.info(
  1908. "[%s] Print destination from the report topic: %s",
  1909. self.serial_number,
  1910. url,
  1911. )
  1912. self.state.current_project_url = url
  1913. self.state.last_project_url = url
  1914. # On a screen start this frame is the only place the mapping appears --
  1915. # no slicer ever sent one. Fill a gap only: when the request topic
  1916. # already captured this print's mapping that copy is the slicer's own,
  1917. # and the echo can arrive without the field at all.
  1918. if self._captured_ams_mapping is None and isinstance(print_data.get("ams_mapping"), list):
  1919. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  1920. logger.info(
  1921. "[%s] Captured ams_mapping from print response: %s",
  1922. self.serial_number,
  1923. self._captured_ams_mapping,
  1924. )
  1925. def _resolve_captured_mapping(self, print_data: dict) -> object:
  1926. """The ``ams_mapping`` of a project_file, with external spools resolved
  1927. from its ``ams_mapping2`` (#3166)."""
  1928. from backend.app.utils.printer_models import is_dual_nozzle_model
  1929. return resolve_external_spools_in_mapping(
  1930. print_data.get("ams_mapping"),
  1931. print_data.get("ams_mapping2"),
  1932. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  1933. )
  1934. @staticmethod
  1935. def _project_file_key(print_data: dict) -> str:
  1936. """Identity of a project_file dispatch, for telling ours from a slicer's.
  1937. Sequence id alone cannot do it -- every slicer counts up from the same
  1938. 20000 -- so this also carries the file and its destination, which differ
  1939. between any two real dispatches.
  1940. """
  1941. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  1942. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  1943. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  1944. The state dumps in the push_status handler fire whenever their field is
  1945. *present* in the frame — and a full push_status carries every field, so
  1946. they fire on every frame regardless of whether anything changed. Several
  1947. even say "updated" or "changes" in their own comment while doing nothing
  1948. of the sort.
  1949. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  1950. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  1951. minutes: the reporter enabled debug logging as asked and the support
  1952. bundle came back holding under five minutes of history, almost none of it
  1953. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  1954. these dumps.
  1955. Deduplicating on the value keeps every transition — which is the only part
  1956. anyone reads these lines for — and drops the steady-state repetition.
  1957. ``value`` must capture everything interpolated into ``msg``, or a change
  1958. will be swallowed; pass a tuple when the message renders several fields.
  1959. """
  1960. if not logger.isEnabledFor(logging.DEBUG):
  1961. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  1962. # and these clients outlive the toggle. Letting INFO-level frames warm
  1963. # the cache would be self-defeating: the operator turns debug on
  1964. # precisely to see the printer's current state, and a cache already
  1965. # holding every steady-state value would suppress that baseline until
  1966. # something happened to change. On an idle printer the bundle would
  1967. # come back with none of these lines at all.
  1968. #
  1969. # So while debug is off we record nothing and drop whatever we had.
  1970. # Every enable then starts cold and dumps a full baseline on the next
  1971. # frame, exactly as it did before this method existed.
  1972. self._debug_last.clear()
  1973. return
  1974. if self._debug_last.get(key) == value:
  1975. return
  1976. self._debug_last[key] = value
  1977. logger.debug(msg, *args)
  1978. def _process_message(self, payload: dict):
  1979. """Process incoming MQTT message from printer."""
  1980. # Handle top-level AMS data (comes outside of "print" key)
  1981. # Wrap in try/except to prevent breaking the MQTT connection
  1982. if "ams" in payload:
  1983. try:
  1984. self._handle_ams_data(payload["ams"])
  1985. except Exception as e:
  1986. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  1987. # Handle xcam data (camera settings and AI detection) at top level
  1988. if "xcam" in payload:
  1989. xcam_data = payload["xcam"]
  1990. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  1991. self._parse_xcam_data(xcam_data)
  1992. # Fire state change callback for top-level xcam (not nested in "print")
  1993. if "print" not in payload and self.on_state_change:
  1994. self.on_state_change(self.state)
  1995. # Handle system responses (accessories info, etc.)
  1996. if "system" in payload:
  1997. system_data = payload["system"]
  1998. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  1999. self._handle_system_response(system_data)
  2000. # Handle info responses (firmware version info from get_version command)
  2001. if "info" in payload:
  2002. info_data = payload["info"]
  2003. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2004. self._handle_version_info(info_data)
  2005. # Parse WiFi signal at top level (some printers send it here)
  2006. if "wifi_signal" in payload:
  2007. wifi_signal = payload["wifi_signal"]
  2008. if isinstance(wifi_signal, (int, float)):
  2009. self.state.wifi_signal = int(wifi_signal)
  2010. elif isinstance(wifi_signal, str):
  2011. try:
  2012. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2013. except ValueError:
  2014. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2015. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2016. from backend.app.utils.printer_models import has_ethernet
  2017. if has_ethernet(self.model):
  2018. self.state.wired_network = self.state.wifi_signal == -90
  2019. # Parse developer LAN mode from top-level "fun" field
  2020. # Some firmware versions send "fun" at the top level, others inside "print"
  2021. if "fun" in payload:
  2022. try:
  2023. fun_val = payload["fun"]
  2024. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2025. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2026. except (ValueError, TypeError):
  2027. pass
  2028. if "print" in payload:
  2029. print_data = payload["print"]
  2030. # Before anything reads the state: this is where a touchscreen-
  2031. # started print announces where its file lives, and the print-start
  2032. # handler asks ~2 s later (#1820).
  2033. self._capture_report_project_file(print_data)
  2034. # Check if xcam is nested inside print data
  2035. if "xcam" in print_data:
  2036. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2037. self._parse_xcam_data(print_data["xcam"])
  2038. # Log when we see gcode_state changes
  2039. if "gcode_state" in print_data:
  2040. logger.debug(
  2041. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2042. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2043. )
  2044. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2045. # new-protocol printers. Verified against OrcaSlicer's
  2046. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2047. # and live H2D ON/OFF capture 2026-06-20.
  2048. #
  2049. # Hold-timer guard: when the user just toggled via the badge, the
  2050. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2051. # for ~3 s before the firmware reflects the change. Without this
  2052. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2053. # Only from a status frame: a project_file ack echoes our own
  2054. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2055. # stuck on every family that doesn't repeat `cfg` in its periodic
  2056. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2057. new_backup = (
  2058. parse_ams_filament_backup_from_cfg(print_data.get("cfg"))
  2059. if is_printer_status_frame(print_data)
  2060. else None
  2061. )
  2062. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2063. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2064. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2065. logger.debug(
  2066. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2067. self.serial_number,
  2068. time.time() - hold_start,
  2069. )
  2070. else:
  2071. logger.info(
  2072. "[%s] AMS Filament Backup: %s",
  2073. self.serial_number,
  2074. "ON" if new_backup else "OFF",
  2075. )
  2076. self.state.ams_filament_backup = new_backup
  2077. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2078. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2079. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2080. if not self._is_dual_nozzle and "device" in print_data:
  2081. dev = print_data.get("device")
  2082. if isinstance(dev, dict):
  2083. ext_info = dev.get("extruder", {}).get("info", [])
  2084. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2085. self._is_dual_nozzle = True
  2086. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2087. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2088. # out of the AMS info bits, but only means anything once we know a
  2089. # switch is installed. Parsing them the other way round would lose
  2090. # the binding on every frame where the two arrive together.
  2091. self._parse_fila_switch(print_data)
  2092. # Handle AMS data that comes inside print key
  2093. if "ams" in print_data:
  2094. try:
  2095. self._handle_ams_data(print_data["ams"])
  2096. except Exception as e:
  2097. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2098. # Handle vir_slot (H2-series external spool data) — list of external trays
  2099. # Process vir_slot FIRST so it takes priority over vt_tray
  2100. if "vir_slot" in print_data:
  2101. vir_slot = print_data["vir_slot"]
  2102. if isinstance(vir_slot, list) and vir_slot:
  2103. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2104. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2105. # Remap id=255→254 for single-slot printers so active detection works.
  2106. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2107. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2108. vir_slot[0]["id"] = "254"
  2109. self.state.raw_data["vt_tray"] = vir_slot
  2110. # Handle vt_tray (virtual tray / external spool) data
  2111. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2112. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2113. # which would overwrite the correct multi-slot vir_slot data)
  2114. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2115. vt_tray = print_data["vt_tray"]
  2116. existing = self.state.raw_data.get("vt_tray")
  2117. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2118. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2119. pass # Keep the vir_slot data
  2120. else:
  2121. if isinstance(vt_tray, dict):
  2122. vt_tray = [vt_tray]
  2123. self.state.raw_data["vt_tray"] = vt_tray
  2124. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2125. # units, and _handle_ams_data runs before this block — so a change
  2126. # to the external spool alone (e.g. swapping generic TPU for generic
  2127. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2128. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2129. # external-spool identity changes here and fire the same callback.
  2130. self._maybe_trigger_external_spool_change()
  2131. # Parse ams_status directly from print data (NOT from print.ams)
  2132. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2133. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2134. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2135. if "ams_status" in print_data:
  2136. raw_ams_status = print_data["ams_status"]
  2137. if isinstance(raw_ams_status, str):
  2138. try:
  2139. self.state.ams_status = int(raw_ams_status)
  2140. except ValueError:
  2141. self.state.ams_status = 0
  2142. else:
  2143. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2144. # Compute main and sub status
  2145. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2146. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2147. # Log when ams_status changes (for filament change tracking debug)
  2148. self._debug_on_change(
  2149. "ams_status:print",
  2150. self.state.ams_status,
  2151. "[%s] ams_status: %s (main=%s, sub=%s)",
  2152. self.serial_number,
  2153. self.state.ams_status,
  2154. self.state.ams_status_main,
  2155. self.state.ams_status_sub,
  2156. )
  2157. # Check for command responses
  2158. if "command" in print_data:
  2159. cmd = print_data.get("command")
  2160. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2161. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2162. # INFO, not debug: this is the printer's verdict on a write
  2163. # the user just made, and it was invisible in support
  2164. # bundles for as long as it sat at DEBUG (#2718). Same
  2165. # reasoning as ams_filament_drying below.
  2166. logger.info(
  2167. "[%s] %s response: result=%s reason=%s seq=%s",
  2168. self.serial_number,
  2169. cmd,
  2170. print_data.get("result"),
  2171. print_data.get("reason", ""),
  2172. print_data.get("sequence_id"),
  2173. )
  2174. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2175. ack_seq = str(print_data.get("sequence_id", ""))
  2176. if ack_seq in self._pending_cali_acks:
  2177. self._pending_cali_acks[ack_seq] = print_data
  2178. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2179. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2180. # A refused ams_filament_setting is the printer's verdict on
  2181. # a write the user just made, and at DEBUG it never reached
  2182. # a support bundle: #2756 reported six manual Configure Slot
  2183. # attempts on an X1C, each returning HTTP 200 with the
  2184. # read-back still showing the previous profile, and no
  2185. # record of what the printer said about any of them. Same
  2186. # promotion as extrusion_cali_set (#2718) and
  2187. # ams_filament_drying (#1447) — but only on a non-success,
  2188. # because unlike those two this command is not rare: every
  2189. # spool assignment and every K-profile re-apply sends one,
  2190. # so promoting each ack would bury the interesting line.
  2191. #
  2192. # The developer-mode probe is excluded. It sends this exact
  2193. # command to the external slot precisely to see it refused
  2194. # on P1 firmware, so its failure is a normal reading rather
  2195. # than a fault. Its response is still matched below (this
  2196. # runs before _handle_dev_mode_probe_response clears the
  2197. # seq), and user-initiated commands can't be mistaken for
  2198. # it — they publish a hardcoded sequence_id of "0".
  2199. result = print_data.get("result")
  2200. is_dev_mode_probe = (
  2201. self._dev_mode_probe_seq is not None
  2202. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2203. )
  2204. if (
  2205. cmd == "ams_filament_setting"
  2206. and not is_dev_mode_probe
  2207. and isinstance(result, str)
  2208. and result.lower() != "success"
  2209. ):
  2210. logger.info(
  2211. "[%s] ams_filament_setting refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2212. self.serial_number,
  2213. result,
  2214. print_data.get("reason", ""),
  2215. print_data.get("ams_id"),
  2216. print_data.get("tray_id"),
  2217. )
  2218. # AMS drying responses are rare (user-initiated only) and the
  2219. # full payload — including `result` and any `reason` code —
  2220. # is the only way to diagnose silent rejections like #1447.
  2221. # INFO level so the body lands in support bundles by default.
  2222. elif cmd == "ams_filament_drying":
  2223. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2224. # Check for developer mode probe response
  2225. if (
  2226. cmd == "ams_filament_setting"
  2227. and self._dev_mode_probe_seq is not None
  2228. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2229. ):
  2230. self._handle_dev_mode_probe_response(print_data)
  2231. # Track user-initiated ams_filament_setting responses (#887
  2232. # zombie detection). Reset both the timer AND the unanswered
  2233. # counter on ANY response — the response proves the channel is
  2234. # alive, so the counter must not stay armed even when the
  2235. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2236. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2237. # caused #1164: one sluggish response (>10s) would set the
  2238. # counter to 1 and zero the timer; the late response arrived
  2239. # but was ignored by this branch (timer is 0); the counter
  2240. # stayed at 1 indefinitely; the very next slow response —
  2241. # possibly hours later, on a totally unrelated command — would
  2242. # take it to 2 and force-reconnect, surfacing as "filament
  2243. # config doesn't reach the printer ~6 changes in".
  2244. elif cmd == "ams_filament_setting":
  2245. self._last_ams_cmd_time = 0.0
  2246. self._ams_cmd_unanswered = 0
  2247. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2248. if is_kprofile_response:
  2249. self._handle_kprofile_response(print_data)
  2250. # An extrusion_cali_get response echoes the *requested* nozzle
  2251. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2252. # installed hardware. Feeding it to _update_state clobbered the real
  2253. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2254. # which then failed the #1899 dispatch guard. The response carries no
  2255. # status telemetry, so skip it; the true nozzle comes from pushall.
  2256. # (Same reasoning as get_accessories in _handle_system_response.)
  2257. if not is_kprofile_response:
  2258. self._update_state(print_data)
  2259. def _handle_system_response(self, data: dict):
  2260. """Handle system responses including accessories info.
  2261. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2262. The correct nozzle data comes from push_status, so we don't update
  2263. nozzle type/diameter from get_accessories. We just log the response
  2264. for debugging purposes.
  2265. """
  2266. command = data.get("command")
  2267. if command == "get_accessories":
  2268. # Log response for debugging - but DON'T use it to update nozzle data
  2269. # because it returns stale values (e.g., 'stainless_steel' when the
  2270. # actual nozzle is 'HH01' hardened steel high-flow)
  2271. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2272. def _handle_version_info(self, data: dict):
  2273. """Handle version info response from get_version command.
  2274. Parses firmware version from the 'ota' module in the module list.
  2275. Also extracts AMS unit firmware versions from AMS modules and stores
  2276. them on the corresponding AMS unit in raw_data so the status route can
  2277. expose them to the frontend.
  2278. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2279. - ``ams/<id>`` – original AMS
  2280. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2281. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2282. Message format:
  2283. {
  2284. "command": "get_version",
  2285. "module": [
  2286. {"name": "ota", "sw_ver": "01.08.05.00"},
  2287. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2288. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2289. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2290. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2291. ...
  2292. ]
  2293. }
  2294. """
  2295. modules = data.get("module", [])
  2296. if not isinstance(modules, list):
  2297. return
  2298. state_changed = False
  2299. for module in modules:
  2300. if not isinstance(module, dict):
  2301. continue
  2302. if module.get("name") == "ota":
  2303. version = module.get("sw_ver")
  2304. if version:
  2305. old_version = self.state.firmware_version
  2306. self.state.firmware_version = version
  2307. if old_version != version:
  2308. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2309. state_changed = True
  2310. break
  2311. # Extract AMS unit firmware versions from AMS modules.
  2312. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2313. # Always cache regardless of whether AMS data has arrived yet — get_version
  2314. # often arrives before the first push_status, so caching must be unconditional.
  2315. ams_raw = self.state.raw_data.get("ams")
  2316. for module in modules:
  2317. if not isinstance(module, dict):
  2318. continue
  2319. name = module.get("name", "")
  2320. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2321. continue
  2322. try:
  2323. ams_id = int(name.split("/", 1)[1])
  2324. except (ValueError, IndexError):
  2325. continue
  2326. sw_ver = module.get("sw_ver", "")
  2327. sn = module.get("sn", "")
  2328. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2329. module_type = name.split("/", 1)[0]
  2330. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2331. if sw_ver or sn or module_type:
  2332. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2333. state_changed = True
  2334. # Also directly update any AMS unit already present in raw_data
  2335. if ams_raw and isinstance(ams_raw, list):
  2336. for ams_unit in ams_raw:
  2337. if not isinstance(ams_unit, dict):
  2338. continue
  2339. try:
  2340. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2341. except (ValueError, TypeError):
  2342. unit_id = None
  2343. if unit_id == ams_id:
  2344. if sw_ver:
  2345. ams_unit["sw_ver"] = sw_ver
  2346. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2347. # Only set sn from version info if not already present in AMS data
  2348. if sn and not ams_unit.get("sn"):
  2349. ams_unit["sn"] = sn
  2350. if module_type:
  2351. ams_unit["module_type"] = module_type
  2352. break
  2353. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2354. # included in the broadcast (not just the printer firmware version).
  2355. if state_changed and self.on_state_change:
  2356. self.on_state_change(self.state)
  2357. # Warn if any AMS unit is still missing serial number or firmware version
  2358. # after processing the version info response. Warn only once per connection
  2359. # to avoid repeated noise on older firmware that doesn't report these fields.
  2360. if ams_raw and isinstance(ams_raw, list):
  2361. for ams_unit in ams_raw:
  2362. if not isinstance(ams_unit, dict):
  2363. continue
  2364. ams_id = ams_unit.get("id", "?")
  2365. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2366. key = (ams_id, "sn")
  2367. if key not in self._ams_version_warned:
  2368. self._ams_version_warned.add(key)
  2369. logger.warning(
  2370. "[%s] AMS unit %s: serial number not available in version info",
  2371. self.serial_number,
  2372. ams_id,
  2373. )
  2374. if not ams_unit.get("sw_ver"):
  2375. key = (ams_id, "sw_ver")
  2376. if key not in self._ams_version_warned:
  2377. self._ams_version_warned.add(key)
  2378. logger.warning(
  2379. "[%s] AMS unit %s: firmware version not available in version info",
  2380. self.serial_number,
  2381. ams_id,
  2382. )
  2383. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2384. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2385. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2386. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2387. sw_ver/sn fields without overwriting values already present.
  2388. """
  2389. if not ams_list or not isinstance(ams_list, list):
  2390. return
  2391. cache = self._ams_version_cache
  2392. if not cache:
  2393. return
  2394. for unit in ams_list:
  2395. if not isinstance(unit, dict):
  2396. continue
  2397. raw_id = unit.get("id")
  2398. try:
  2399. unit_id = int(raw_id) if raw_id is not None else None
  2400. except (ValueError, TypeError):
  2401. unit_id = None
  2402. if unit_id is None:
  2403. continue
  2404. cached = cache.get(unit_id)
  2405. if not cached:
  2406. continue
  2407. sw_ver = cached.get("sw_ver") or ""
  2408. sn = cached.get("sn") or ""
  2409. if sw_ver and not unit.get("sw_ver"):
  2410. unit["sw_ver"] = sw_ver
  2411. # Only set sn if not already present in AMS data
  2412. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2413. unit["sn"] = sn
  2414. module_type = cached.get("module_type") or ""
  2415. if module_type and not unit.get("module_type"):
  2416. unit["module_type"] = module_type
  2417. def _parse_xcam_data(self, xcam_data):
  2418. """Parse xcam data for camera settings and AI detection options."""
  2419. if not isinstance(xcam_data, dict):
  2420. return
  2421. current_time = time.time()
  2422. # Helper to check if we should accept incoming value for a module
  2423. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2424. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2425. """Check if we should accept an incoming xcam value.
  2426. OrcaSlicer pattern: After sending a command, ignore incoming data
  2427. for 3 seconds. After that, accept whatever the printer sends.
  2428. """
  2429. if module_name not in self._xcam_hold_start:
  2430. return True # No hold timer, accept incoming
  2431. hold_start = self._xcam_hold_start[module_name]
  2432. elapsed = current_time - hold_start
  2433. if elapsed > self._xcam_hold_time:
  2434. # Hold timer expired - accept incoming and clear hold
  2435. del self._xcam_hold_start[module_name]
  2436. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2437. return True
  2438. # Within hold period - ignore incoming data
  2439. logger.debug(
  2440. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2441. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2442. )
  2443. return False
  2444. # Log all xcam fields for debugging
  2445. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2446. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2447. # fields (spaghetti_detector, etc.) are often stale/cached.
  2448. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2449. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2450. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2451. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2452. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2453. # Sensitivity values: 0=low, 1=medium, 2=high
  2454. if "cfg" in xcam_data:
  2455. cfg = xcam_data["cfg"]
  2456. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2457. def decode_detector(start_bit):
  2458. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2459. sens_bits = (cfg >> start_bit) & 0x3
  2460. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2461. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2462. return enabled, sensitivity
  2463. # Spaghetti detector (bits 5-7)
  2464. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2465. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2466. old_value = self.state.print_options.spaghetti_detector
  2467. if cfg_spaghetti != old_value:
  2468. logger.debug(
  2469. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2470. )
  2471. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2472. # Check hold timer for sensitivity before accepting
  2473. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2474. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2475. logger.debug(
  2476. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2477. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2478. )
  2479. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2480. else:
  2481. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2482. elapsed = current_time - hold_start
  2483. if elapsed <= self._xcam_hold_time:
  2484. logger.debug(
  2485. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2486. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2487. )
  2488. else:
  2489. # Hold expired - accept from cfg
  2490. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2491. logger.debug(
  2492. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2493. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2494. )
  2495. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2496. del self._xcam_hold_start["halt_print_sensitivity"]
  2497. # Pileup detector (bits 8-10)
  2498. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2499. if should_accept_value("pileup_detector", cfg_pileup):
  2500. if cfg_pileup != self.state.print_options.pileup_detector:
  2501. logger.debug(
  2502. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2503. )
  2504. self.state.print_options.pileup_detector = cfg_pileup
  2505. # Pileup sensitivity with hold timer
  2506. if "pileup_sensitivity" not in self._xcam_hold_start:
  2507. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2508. logger.debug(
  2509. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2510. )
  2511. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2512. else:
  2513. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2514. elapsed = current_time - hold_start
  2515. if elapsed > self._xcam_hold_time:
  2516. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2517. logger.debug(
  2518. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2519. )
  2520. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2521. del self._xcam_hold_start["pileup_sensitivity"]
  2522. # Clump/nozzle clumping detector (bits 11-13)
  2523. cfg_clump, cfg_clump_sens = decode_detector(11)
  2524. if should_accept_value("clump_detector", cfg_clump):
  2525. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2526. logger.debug(
  2527. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2528. )
  2529. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2530. # Clump sensitivity with hold timer
  2531. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2532. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2533. logger.debug(
  2534. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2535. )
  2536. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2537. else:
  2538. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2539. elapsed = current_time - hold_start
  2540. if elapsed > self._xcam_hold_time:
  2541. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2542. logger.debug(
  2543. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2544. )
  2545. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2546. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2547. # Airprint detector (bits 14-16)
  2548. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2549. if should_accept_value("airprint_detector", cfg_airprint):
  2550. if cfg_airprint != self.state.print_options.airprint_detector:
  2551. logger.debug(
  2552. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2553. )
  2554. self.state.print_options.airprint_detector = cfg_airprint
  2555. # Airprint sensitivity with hold timer
  2556. if "airprint_sensitivity" not in self._xcam_hold_start:
  2557. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2558. logger.debug(
  2559. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2560. )
  2561. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2562. else:
  2563. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2564. elapsed = current_time - hold_start
  2565. if elapsed > self._xcam_hold_time:
  2566. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2567. logger.debug(
  2568. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2569. )
  2570. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2571. del self._xcam_hold_start["airprint_sensitivity"]
  2572. # Camera settings
  2573. if "ipcam_record" in xcam_data:
  2574. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2575. if "timelapse" in xcam_data:
  2576. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2577. # Track if timelapse was ever active during this print
  2578. if self.state.timelapse and self._was_running:
  2579. self._timelapse_during_print = True
  2580. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2581. if "print_halt" in xcam_data:
  2582. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  2583. # Skip halt_print_sensitivity field - it's always stale ("medium")
  2584. # We read the actual sensitivity from cfg bits 5-6 above
  2585. if "first_layer_inspector" in xcam_data:
  2586. new_value = bool(xcam_data.get("first_layer_inspector"))
  2587. if should_accept_value("first_layer_inspector", new_value):
  2588. self.state.print_options.first_layer_inspector = new_value
  2589. if "printing_monitor" in xcam_data:
  2590. new_value = bool(xcam_data.get("printing_monitor"))
  2591. if should_accept_value("printing_monitor", new_value):
  2592. self.state.print_options.printing_monitor = new_value
  2593. if "buildplate_marker_detector" in xcam_data:
  2594. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  2595. if should_accept_value("buildplate_marker_detector", new_value):
  2596. self.state.print_options.buildplate_marker_detector = new_value
  2597. if "allow_skip_parts" in xcam_data:
  2598. new_value = bool(xcam_data.get("allow_skip_parts"))
  2599. if should_accept_value("allow_skip_parts", new_value):
  2600. self.state.print_options.allow_skip_parts = new_value
  2601. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  2602. # individual boolean fields (which are not sent by the printer)
  2603. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  2604. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  2605. if "auto_recovery_step_loss" in xcam_data:
  2606. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  2607. if "filament_tangle_detect" in xcam_data:
  2608. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  2609. @staticmethod
  2610. def _resolve_local_slot_from_mapping(local_slot: int, mapping_raw: list | None) -> int | None:
  2611. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  2612. The MQTT mapping field is an array of snow-encoded values:
  2613. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  2614. Finds entries where the local slot matches, then computes the global tray ID.
  2615. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  2616. """
  2617. if not isinstance(mapping_raw, list) or not mapping_raw:
  2618. return None
  2619. candidates: set[int] = set()
  2620. for value in mapping_raw:
  2621. if not isinstance(value, int) or value >= 65535:
  2622. continue
  2623. ams_hw_id = value >> 8
  2624. slot = value & 0xFF
  2625. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  2626. candidates.add(ams_hw_id * 4 + local_slot)
  2627. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  2628. candidates.add(ams_hw_id)
  2629. if len(candidates) == 1:
  2630. return candidates.pop()
  2631. return None
  2632. def _maybe_trigger_external_spool_change(self):
  2633. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  2634. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  2635. an external-spool-only filament swap would otherwise never re-run the
  2636. inventory reconciliation that unlinks a stale ams_id=255 assignment
  2637. (#2575). The reconciliation reads vt_tray from live status itself, so we
  2638. just need to re-fire the callback with the current merged AMS data.
  2639. """
  2640. import hashlib
  2641. vt_tray = self.state.raw_data.get("vt_tray")
  2642. if not isinstance(vt_tray, list):
  2643. return
  2644. # Identity fields only — deliberately exclude `remain` so a print's
  2645. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  2646. fp_parts = [
  2647. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  2648. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  2649. for vt in vt_tray
  2650. if isinstance(vt, dict)
  2651. ]
  2652. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  2653. if vt_hash == self._previous_vt_tray_hash:
  2654. return
  2655. self._previous_vt_tray_hash = vt_hash
  2656. if self.on_ams_change:
  2657. logger.debug(
  2658. "[%s] External spool (vt_tray) changed, triggering sync callback",
  2659. self.serial_number,
  2660. )
  2661. self.on_ams_change(self.state.raw_data.get("ams") or [])
  2662. def _normalize_a2l_am_units(self, ams_list) -> None:
  2663. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  2664. id 16 -> 6 in place, as early as possible, so every downstream reader —
  2665. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  2666. the DB constraint — sees the normalised id and needs no special-casing.
  2667. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  2668. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  2669. both the dict-wrapped and bare-list AMS shapes.
  2670. """
  2671. if not isinstance(ams_list, list):
  2672. return
  2673. for unit in ams_list:
  2674. if not isinstance(unit, dict):
  2675. continue
  2676. try:
  2677. uid = int(unit.get("id"))
  2678. except (TypeError, ValueError):
  2679. continue
  2680. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  2681. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  2682. if not self._has_a2l_am_unit:
  2683. logger.info(
  2684. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  2685. self.serial_number,
  2686. A2L_LITE_NORMALIZED_AMS_ID,
  2687. )
  2688. self._has_a2l_am_unit = True
  2689. def _parse_fila_switch(self, data: dict) -> None:
  2690. """Read the Filament Track Switch block out of a print payload — #1162.
  2691. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  2692. separate from the rest of the state update because ``_handle_ams_data``
  2693. needs the answer before it parses the AMS info bits, and that runs first.
  2694. """
  2695. if not isinstance(data.get("device"), dict):
  2696. return
  2697. fs_data = data["device"].get("fila_switch")
  2698. if not isinstance(fs_data, dict):
  2699. return
  2700. in_raw = fs_data.get("in")
  2701. out_raw = fs_data.get("out")
  2702. self.state.fila_switch = FilaSwitchState(
  2703. installed=True,
  2704. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2705. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2706. stat=int(fs_data.get("stat", 0) or 0),
  2707. info=int(fs_data.get("info", 0) or 0),
  2708. )
  2709. def _parse_extruder_slots(self, data: dict) -> None:
  2710. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  2711. Absent on printers that do not report the block, in which case the
  2712. previous answer is kept rather than cleared: a partial payload carrying
  2713. only temperatures must not look like "both hotends are now empty".
  2714. """
  2715. device = data.get("device")
  2716. if not isinstance(device, dict):
  2717. return
  2718. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  2719. if not isinstance(info, list) or not info:
  2720. return
  2721. slots: dict[int, ExtruderSlot] = {}
  2722. for entry in info:
  2723. if not isinstance(entry, dict) or "id" not in entry:
  2724. continue
  2725. try:
  2726. ext_id = int(entry["id"])
  2727. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  2728. flags = int(entry.get("info", 0) or 0)
  2729. except (TypeError, ValueError):
  2730. continue
  2731. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  2732. ams_id = slot_id = None
  2733. else:
  2734. ams_id = (snow >> 8) & 0xFF
  2735. slot_id = snow & 0xFF
  2736. slots[ext_id] = ExtruderSlot(
  2737. ams_id=ams_id,
  2738. slot_id=slot_id,
  2739. has_filament=bool(flags & 0b10),
  2740. )
  2741. if slots:
  2742. self.state.extruder_slots = slots
  2743. def _handle_ams_data(self, ams_data):
  2744. """Handle AMS data changes for Spoolman integration.
  2745. This is called when we receive top-level AMS data in MQTT messages.
  2746. It detects changes and triggers the callback for Spoolman sync.
  2747. """
  2748. import hashlib
  2749. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  2750. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  2751. ams_list = None
  2752. if isinstance(ams_data, dict):
  2753. if "ams" in ams_data:
  2754. ams_list = ams_data["ams"]
  2755. self._normalize_a2l_am_units(ams_list)
  2756. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  2757. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  2758. if non_list_fields:
  2759. self._debug_on_change(
  2760. "ams_dict_fields",
  2761. non_list_fields,
  2762. "[%s] AMS dict fields: %s",
  2763. self.serial_number,
  2764. non_list_fields,
  2765. )
  2766. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  2767. # when checking if we're in filament change mode for tray_now disambiguation
  2768. if "ams_status" in ams_data:
  2769. raw_ams_status = ams_data["ams_status"]
  2770. if isinstance(raw_ams_status, str):
  2771. try:
  2772. self.state.ams_status = int(raw_ams_status)
  2773. except ValueError:
  2774. self.state.ams_status = 0
  2775. else:
  2776. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2777. # Compute main and sub status
  2778. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2779. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2780. self._debug_on_change(
  2781. "ams_status:ams",
  2782. self.state.ams_status,
  2783. "[%s] ams_status: %s (main=%s, sub=%s)",
  2784. self.serial_number,
  2785. self.state.ams_status,
  2786. self.state.ams_status_main,
  2787. self.state.ams_status_sub,
  2788. )
  2789. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  2790. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  2791. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  2792. # next compatible slot (#2587). Stored raw here; globalised at the API
  2793. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  2794. # these are local slot numbers (0-3), not global IDs.
  2795. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  2796. if _tk in ams_data:
  2797. _raw = ams_data[_tk]
  2798. if isinstance(_raw, str):
  2799. try:
  2800. _val = int(_raw)
  2801. except ValueError:
  2802. _val = 255
  2803. else:
  2804. _val = _raw if _raw is not None else 255
  2805. prev = getattr(self.state, _attr)
  2806. setattr(self.state, _attr, _val)
  2807. # Log changes only while paused — the moment the operator cares —
  2808. # so a healthy print's normal tar churn doesn't spam the log.
  2809. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  2810. logger.info(
  2811. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  2812. self.serial_number,
  2813. _tk,
  2814. _val,
  2815. )
  2816. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  2817. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  2818. if "tray_now" in ams_data:
  2819. raw_tray_now = ams_data["tray_now"]
  2820. # Convert string to int if needed
  2821. if isinstance(raw_tray_now, str):
  2822. try:
  2823. parsed_tray_now = int(raw_tray_now)
  2824. except ValueError:
  2825. parsed_tray_now = 255
  2826. else:
  2827. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  2828. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  2829. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  2830. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  2831. # — disambiguated below using MQTT mapping field
  2832. ams_map = self.state.ams_extruder_map
  2833. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  2834. # First, check if we have a pending target that matches this slot
  2835. pending_target = self.state.pending_tray_target
  2836. if pending_target is not None:
  2837. pending_slot = pending_target % 4
  2838. if pending_slot == parsed_tray_now:
  2839. # Slot matches our pending target - use the full global ID
  2840. logger.debug(
  2841. f"[{self.serial_number}] H2D tray_now disambiguation: "
  2842. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  2843. )
  2844. self.state.tray_now = pending_target
  2845. # Clear pending target now that load is confirmed
  2846. self.state.pending_tray_target = None
  2847. else:
  2848. # Slot doesn't match our pending target - something changed, use slot as-is
  2849. logger.warning(
  2850. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  2851. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  2852. )
  2853. self.state.tray_now = parsed_tray_now
  2854. # Clear pending target since it's stale
  2855. self.state.pending_tray_target = None
  2856. else:
  2857. # No pending target - use h2d_extruder_snow for accurate disambiguation
  2858. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  2859. active_ext = self.state.active_extruder # 0=right, 1=left
  2860. # Best source: use snow value from device.extruder.info if available
  2861. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  2862. if snow_tray is not None and snow_tray != 255:
  2863. # snow_tray is already normalized to global ID
  2864. # Verify the slot matches what we see in tray_now
  2865. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  2866. snow_slot = snow_tray % 4 if snow_tray < 128 else (0 if snow_tray <= 135 else -1)
  2867. if snow_slot == parsed_tray_now:
  2868. if self.state.tray_now != snow_tray:
  2869. logger.debug(
  2870. f"[{self.serial_number}] H2D tray_now from snow: "
  2871. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  2872. )
  2873. self.state.tray_now = snow_tray
  2874. else:
  2875. # Slot mismatch - snow field may not have updated yet, trust snow
  2876. logger.debug(
  2877. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  2878. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  2879. )
  2880. self.state.tray_now = snow_tray
  2881. else:
  2882. # Fallback: snow not available, use ams_extruder_map (less reliable)
  2883. # Find ALL AMS units on the active extruder
  2884. ams_on_extruder = []
  2885. for ams_id_str, ext_id in ams_map.items():
  2886. if ext_id == active_ext:
  2887. try:
  2888. ams_on_extruder.append(int(ams_id_str))
  2889. except ValueError:
  2890. pass # Skip AMS IDs that aren't valid integers
  2891. if len(ams_on_extruder) == 1:
  2892. # Single AMS on this extruder - unambiguous
  2893. active_ams_id = ams_on_extruder[0]
  2894. if 128 <= active_ams_id <= 135:
  2895. # AMS-HT: single slot per unit, global ID = unit ID
  2896. global_tray_id = active_ams_id
  2897. else:
  2898. global_tray_id = active_ams_id * 4 + parsed_tray_now
  2899. logger.debug(
  2900. f"[{self.serial_number}] H2D tray_now fallback: "
  2901. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  2902. )
  2903. self.state.tray_now = global_tray_id
  2904. elif len(ams_on_extruder) > 1:
  2905. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  2906. current_tray = self.state.tray_now
  2907. # Determine which AMS unit and slot the current tray belongs to
  2908. if 0 <= current_tray <= 15:
  2909. current_ams = current_tray // 4
  2910. current_slot = current_tray % 4
  2911. elif 128 <= current_tray <= 135:
  2912. current_ams = current_tray # AMS-HT: ID = tray ID
  2913. current_slot = 0
  2914. else:
  2915. current_ams = -1
  2916. current_slot = -1
  2917. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  2918. # Current is valid and matches slot - keep it
  2919. logger.debug(
  2920. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  2921. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  2922. )
  2923. else:
  2924. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  2925. if parsed_tray_now > 0:
  2926. candidates = [a for a in ams_on_extruder if a <= 3]
  2927. else:
  2928. candidates = ams_on_extruder
  2929. if len(candidates) == 1:
  2930. cand = candidates[0]
  2931. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  2932. logger.debug(
  2933. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  2934. f"narrowed to AMS {cand} -> global ID {resolved}"
  2935. )
  2936. self.state.tray_now = resolved
  2937. else:
  2938. # Genuinely ambiguous - use slot as-is (will be wrong for non-first AMS)
  2939. logger.warning(
  2940. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on extruder {active_ext}, "
  2941. f"no snow field, using slot {parsed_tray_now} (may be incorrect)"
  2942. )
  2943. self.state.tray_now = parsed_tray_now
  2944. else:
  2945. # No AMS on this extruder - use slot as-is
  2946. logger.warning(
  2947. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  2948. f"using slot {parsed_tray_now}"
  2949. )
  2950. self.state.tray_now = parsed_tray_now
  2951. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  2952. # Single-nozzle printer with tray_now in 0-3 range.
  2953. # #1822: H2S firmware reports tray_now as the AMS's idle
  2954. # slot (typically 0) when the active feed is actually the
  2955. # external spool. X1C / P1S / A1 correctly report 254 in
  2956. # that case; H2S does not. When the slicer-captured
  2957. # ams_mapping is all-external (every entry is 254, or -1
  2958. # when the command carried no ams_mapping2 to resolve it
  2959. # from, #3166), the print can only be feeding from the
  2960. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  2961. # AMS-only mappings are NOT overridden — there's no
  2962. # evidence the firmware misreports in those cases. Prints
  2963. # started without a captured mapping (printer-screen start,
  2964. # or before Bambuddy connected) fall through unchanged.
  2965. captured = self._captured_ams_mapping
  2966. if captured and all(s in (-1, 254, 255) for s in captured):
  2967. if self.state.tray_now != 254:
  2968. logger.debug(
  2969. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  2970. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  2971. )
  2972. self.state.tray_now = 254
  2973. else:
  2974. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  2975. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  2976. # (snow-encoded) to resolve the correct AMS unit.
  2977. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  2978. try:
  2979. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  2980. except (ValueError, TypeError):
  2981. ams_exist = 0
  2982. num_ams = bin(ams_exist).count("1")
  2983. if self._has_a2l_am_unit and num_ams <= 1:
  2984. # A2L AMS-Lite (normalised unit 6): the firmware reports
  2985. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  2986. # otherwise usage tracking keys the wrong spool (it would
  2987. # deduct from AMS 0's slot). Confirmed by capture:
  2988. # tray_now="2" while printing physical slot 3.
  2989. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  2990. elif num_ams > 1:
  2991. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  2992. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  2993. if self._has_a2l_am_unit:
  2994. # A2L Lite + a regular AMS attached together is out of
  2995. # scope: the flat mapping ids are unknown for that combo
  2996. # and could collide with AMS 0. Fall through to the
  2997. # mapping-based resolve, but warn — a capture is needed.
  2998. logger.warning(
  2999. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3000. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3001. self.serial_number,
  3002. )
  3003. mapping_raw = self.state.raw_data.get("mapping")
  3004. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3005. if resolved is not None:
  3006. if resolved != parsed_tray_now:
  3007. logger.debug(
  3008. f"[{self.serial_number}] Multi-AMS tray_now: "
  3009. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3010. )
  3011. self.state.tray_now = resolved
  3012. else:
  3013. # No mapping available (not printing, or ambiguous) — use as-is.
  3014. # This matches the old behavior and is correct for AMS 0.
  3015. self.state.tray_now = parsed_tray_now
  3016. else:
  3017. # Single AMS — local slot 0-3 equals global ID
  3018. self.state.tray_now = parsed_tray_now
  3019. else:
  3020. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3021. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3022. # During filament change, the printer sends 255 first (unload), then the slot.
  3023. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3024. # Trust the printer's reported value.
  3025. self.state.tray_now = parsed_tray_now
  3026. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3027. # Valid physical trays: 0-15 (regular AMS), 24-27 (A2L AMS-Lite,
  3028. # normalised unit 6), 128-135 (AMS-HT), 254 (external spool)
  3029. tn = self.state.tray_now
  3030. if (
  3031. (0 <= tn <= 15)
  3032. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  3033. or (128 <= tn <= 135)
  3034. or tn == 254
  3035. ):
  3036. # Log tray change for mid-print usage splitting. Gate on the
  3037. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3038. # new print, `_completion_triggered` set when on_print_complete
  3039. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3040. # firmware briefly transitions out of RUNNING during AMS
  3041. # auto-fallback (#957), so a literal-string gate misses the
  3042. # switch and the usage tracker double-credits at completion.
  3043. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3044. self.state.tray_change_log.append((tn, self.state.layer_num))
  3045. logger.info(
  3046. "[%s] Tray change during print: tray=%d at layer=%d",
  3047. self.serial_number,
  3048. tn,
  3049. self.state.layer_num,
  3050. )
  3051. if self.on_tray_change:
  3052. self.on_tray_change(tn, self.state.layer_num)
  3053. self.state.last_loaded_tray = self.state.tray_now
  3054. self._debug_on_change(
  3055. "tray_now",
  3056. self.state.tray_now,
  3057. "[%s] tray_now updated: %s",
  3058. self.serial_number,
  3059. self.state.tray_now,
  3060. )
  3061. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3062. # state when checking filament change mode for H2D disambiguation
  3063. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3064. # We've already processed the status fields above, so just return if no ams list
  3065. if ams_list is None:
  3066. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3067. return
  3068. elif isinstance(ams_data, list):
  3069. ams_list = ams_data
  3070. self._normalize_a2l_am_units(ams_list)
  3071. else:
  3072. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3073. return
  3074. # Merge AMS data instead of replacing, to handle partial updates
  3075. # During prints, the printer may only send updates for active AMS units
  3076. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3077. existing_ams = self.state.raw_data.get("ams", [])
  3078. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  3079. # Update existing units with new data, add new units
  3080. for ams_unit in ams_list:
  3081. ams_id = ams_unit.get("id")
  3082. if ams_id is not None:
  3083. existing_unit = existing_by_id.get(ams_id)
  3084. if existing_unit and "tray" in ams_unit:
  3085. # Deep merge trays to preserve fields from previous updates
  3086. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3087. merged_trays = []
  3088. for new_tray in ams_unit.get("tray", []):
  3089. tray_id = new_tray.get("id")
  3090. if tray_id is not None and tray_id in existing_trays:
  3091. # Merge: start with existing, update with new non-empty values
  3092. merged_tray = existing_trays[tray_id].copy()
  3093. # Detect slot-clearing updates (spool removal):
  3094. # When tray_type is explicitly empty, clear everything
  3095. # including RFID data (tag_uid/tray_uuid).
  3096. slot_clearing = new_tray.get("tray_type") == ""
  3097. # Some printers (e.g. H2D) only send {id, state} in
  3098. # incremental updates when a tray is not fully loaded.
  3099. # state=11 means loaded; other values (9=empty,
  3100. # 10=spool present but filament not in feeder) indicate
  3101. # the slot should be cleared. Without this, old
  3102. # tray_type/tray_color persist indefinitely (#784).
  3103. #
  3104. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3105. # tray high-temp dry box, id >= 128) reports its loaded
  3106. # tray as state=9, not 11 — it doesn't feed filament into
  3107. # a shared buffer the way a 4-slot AMS does. Applying the
  3108. # `state != 11 → empty` rule to an HT unit wiped a present
  3109. # spool on every power-on, when the printer sends a partial
  3110. # {id, state=9} for the HT tray (#2594). Skip the state
  3111. # heuristic for HT units — a genuine HT spool removal still
  3112. # clears via the explicit tray_type=="" case above and the
  3113. # tray_exist_bits cleanup below.
  3114. try:
  3115. _is_ht_unit = int(ams_id) >= 128
  3116. except (TypeError, ValueError):
  3117. _is_ht_unit = False
  3118. tray_state = new_tray.get("state")
  3119. if (
  3120. tray_state is not None
  3121. and tray_state != 11
  3122. and not _is_ht_unit
  3123. and "tray_type" not in new_tray
  3124. and merged_tray.get("tray_type")
  3125. ):
  3126. logger.info(
  3127. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3128. self.serial_number,
  3129. ams_id,
  3130. tray_id,
  3131. tray_state,
  3132. )
  3133. slot_clearing = True
  3134. # The incremental update only has {id, state} — inject
  3135. # empty values for all content fields so the merge loop
  3136. # below clears the stale data from merged_tray.
  3137. new_tray.update(
  3138. {
  3139. "tray_type": "",
  3140. "tray_sub_brands": "",
  3141. "tray_color": "",
  3142. "tray_id_name": "",
  3143. "tray_info_idx": "",
  3144. "tag_uid": "0000000000000000",
  3145. "tray_uuid": "00000000000000000000000000000000",
  3146. "remain": 0,
  3147. "k": None,
  3148. "cali_idx": None,
  3149. }
  3150. )
  3151. for key, value in new_tray.items():
  3152. # Fields that should always be updated (even with empty/zero values):
  3153. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3154. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3155. # tray_id_name: slot content indicators that must be cleared
  3156. # when a spool is removed (fixes #147 - old AMS empty slot)
  3157. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3158. # They are only cleared during spool removal (slot_clearing=True).
  3159. # Periodic AMS updates often include empty RFID fields which
  3160. # would overwrite valid data from the initial pushall.
  3161. always_update_fields = (
  3162. "remain",
  3163. "k",
  3164. "id",
  3165. "cali_idx",
  3166. "tray_type",
  3167. "tray_sub_brands",
  3168. "tray_info_idx",
  3169. "tray_color",
  3170. "tray_id_name",
  3171. )
  3172. if (
  3173. key in always_update_fields
  3174. or slot_clearing
  3175. or value
  3176. not in (
  3177. None,
  3178. "",
  3179. "0000000000000000",
  3180. "00000000000000000000000000000000",
  3181. )
  3182. ):
  3183. merged_tray[key] = value
  3184. merged_trays.append(merged_tray)
  3185. else:
  3186. merged_trays.append(new_tray)
  3187. # Update ams_unit with merged trays. Spread existing_unit
  3188. # FIRST so top-level fields the partial update omits —
  3189. # dry_time, info (which drives dry_status / dry_sub_status),
  3190. # humidity, temp — are preserved instead of dropped. The
  3191. # printer sends tray-bearing partials that carry no drying
  3192. # fields; without this, dry_time reads as absent → 0 and the
  3193. # falling-edge detector below fires a false "drying complete"
  3194. # (#1462). Mirrors the no-tray branch's merge semantics.
  3195. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3196. elif existing_unit:
  3197. # Partial update without tray data: merge new fields into existing
  3198. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3199. ams_unit = {**existing_unit, **ams_unit}
  3200. existing_by_id[ams_id] = ams_unit
  3201. # Convert back to list, sorted by ID for consistent ordering
  3202. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  3203. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3204. # Shared with the VP bridge cache so the slicer-facing view stays in
  3205. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3206. # for the full rationale and the printer-shutdown guard.
  3207. if isinstance(ams_data, dict):
  3208. apply_tray_exist_bits(
  3209. merged_ams,
  3210. ams_data.get("tray_exist_bits"),
  3211. power_on_flag=ams_data.get("power_on_flag", True),
  3212. log_label=self.serial_number,
  3213. annotate_exists=True,
  3214. )
  3215. self.state.raw_data["ams"] = merged_ams
  3216. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3217. self._apply_ams_version_cache(merged_ams)
  3218. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3219. self.state.last_ams_update = time.time()
  3220. self._debug_on_change(
  3221. "merged_ams",
  3222. (len(ams_list), len(merged_ams)),
  3223. "[%s] Merged AMS data: %s new units, %s total",
  3224. self.serial_number,
  3225. len(ams_list),
  3226. len(merged_ams),
  3227. )
  3228. # Extract ams_extruder_map from each AMS unit's info field
  3229. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3230. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3231. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3232. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3233. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3234. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3235. #
  3236. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3237. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3238. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3239. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3240. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3241. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3242. # the switch being installed.
  3243. #
  3244. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3245. # the full map. Merge into existing map to preserve entries from prior updates.
  3246. fts_installed = self.state.fila_switch.installed
  3247. inlet_moves: list[tuple[int, str]] = []
  3248. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3249. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3250. for ams_unit in merged_ams:
  3251. ams_id = ams_unit.get("id")
  3252. info = ams_unit.get("info")
  3253. if ams_id is not None and info is not None:
  3254. try:
  3255. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3256. info_val = int(str(info), 16)
  3257. # Extract 4 bits starting at bit 8 for extruder assignment
  3258. extruder_id = (info_val >> 8) & 0xF
  3259. if extruder_id == 0xE:
  3260. if fts_installed:
  3261. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3262. if inlet is not None:
  3263. previous = ams_switch_inlet.get(str(ams_id))
  3264. ams_switch_inlet[str(ams_id)] = inlet
  3265. self._debug_on_change(
  3266. f"ams_inlet:{ams_id}",
  3267. inlet,
  3268. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3269. self.serial_number,
  3270. ams_id,
  3271. info,
  3272. inlet,
  3273. )
  3274. if previous is not None and previous != inlet:
  3275. # Only a genuine move, never the first sighting:
  3276. # re-applying K-profiles on every reconnect would
  3277. # fight a binding the operator set deliberately.
  3278. logger.info(
  3279. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3280. self.serial_number,
  3281. ams_id,
  3282. inlet,
  3283. previous,
  3284. )
  3285. inlet_moves.append((int(ams_id), inlet))
  3286. continue
  3287. ams_extruder_map[str(ams_id)] = extruder_id
  3288. self._debug_on_change(
  3289. f"ams_info:{ams_id}",
  3290. (info, extruder_id),
  3291. "[%s] AMS %s info=0x%s -> extruder %s",
  3292. self.serial_number,
  3293. ams_id,
  3294. info,
  3295. extruder_id,
  3296. )
  3297. except (ValueError, TypeError):
  3298. pass # Skip AMS units with unparseable info bitmask values
  3299. if ams_extruder_map:
  3300. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3301. self.state.ams_extruder_map = ams_extruder_map
  3302. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3303. if ams_switch_inlet:
  3304. self.state.ams_switch_inlet = ams_switch_inlet
  3305. for moved_ams_id, moved_inlet in inlet_moves:
  3306. if self.on_fts_inlet_change:
  3307. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3308. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3309. # BambuStudio DevFilaSystem.cpp parses info bits:
  3310. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3311. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3312. for ams_unit in merged_ams:
  3313. info = ams_unit.get("info")
  3314. if info is not None:
  3315. try:
  3316. info_val = int(str(info), 16)
  3317. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3318. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3319. except (ValueError, TypeError):
  3320. pass # Skip unparseable info values
  3321. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3322. if "dry_sf_reason" in ams_unit:
  3323. sf_reason = ams_unit["dry_sf_reason"]
  3324. if isinstance(sf_reason, list):
  3325. ams_unit["dry_sf_reason"] = [
  3326. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3327. ]
  3328. else:
  3329. ams_unit["dry_sf_reason"] = []
  3330. # Persist updated drying fields back to raw_data
  3331. self.state.raw_data["ams"] = merged_ams
  3332. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3333. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3334. # — fire the callback so smart-plug auto-off-after-drying can run,
  3335. # and drop our cached target-cycle params so the badge stops claiming
  3336. # an active cycle. Works identically for queue-triggered, ambient,
  3337. # and manual drying because we observe the firmware-reported state.
  3338. for ams_unit in merged_ams:
  3339. try:
  3340. ams_id = int(ams_unit.get("id", -1))
  3341. except (TypeError, ValueError):
  3342. continue
  3343. if ams_id < 0:
  3344. continue
  3345. # The firmware phase outranks the stalled-countdown heuristic even
  3346. # on a transient-zero frame, which the completion guard below skips.
  3347. # Clear a previously raised flag before that early continue.
  3348. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3349. ams_unit["dry_countdown_stalled"] = False
  3350. # Only evaluate the edge when this update carries an explicit
  3351. # dry_time. An absent / unparseable value is NOT zero — treating
  3352. # it as 0 lets a tray-only partial fake a drying-complete edge
  3353. # (#1462). Skip without touching the remembered value so the
  3354. # next update that DOES carry dry_time sees the true previous.
  3355. raw_dry_time = ams_unit.get("dry_time")
  3356. if raw_dry_time is None:
  3357. continue
  3358. try:
  3359. current = int(raw_dry_time)
  3360. except (TypeError, ValueError):
  3361. continue
  3362. # A dry_time of 0 only means "finished" when the unit also reports
  3363. # an idle phase. Between the command ack and the countdown settling
  3364. # the firmware publishes a transient 0 while the AMS is still
  3365. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3366. # 12-hour cycle. Taking that at face value dropped the cached target
  3367. # (leaving the badge to guess the filament from tray 1, so a PLA
  3368. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3369. # schedules smart-plug auto-off. dry_status comes from the same info
  3370. # hex parsed above; when it is absent we let the edge through, so a
  3371. # firmware that never reports one still ends its cycles.
  3372. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3373. # Leave the remembered value alone, exactly as the absent-
  3374. # dry_time skip above does: whichever push ends the cycle for
  3375. # real must still see a non-zero previous.
  3376. logger.debug(
  3377. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3378. self.serial_number,
  3379. ams_id,
  3380. ams_unit.get("dry_status"),
  3381. )
  3382. continue
  3383. previous = self._previous_dry_times.get(ams_id, 0)
  3384. self._previous_dry_times[ams_id] = current
  3385. # Stall detection: stamp value CHANGES only — a live countdown
  3386. # decrements once a minute, so repeats of the same value within
  3387. # the minute must not refresh the stamp, and a frame without a
  3388. # dry_time never reaches here (the absent-value skip above).
  3389. now_mono = time.monotonic()
  3390. if current != previous or ams_id not in self._dry_time_changed_at:
  3391. self._dry_time_changed_at[ams_id] = now_mono
  3392. ams_unit["dry_countdown_stalled"] = bool(
  3393. current > 0
  3394. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  3395. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  3396. )
  3397. if previous > 0 and current == 0:
  3398. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  3399. if self.on_drying_complete:
  3400. self.on_drying_complete(ams_id)
  3401. # Create a hash of relevant AMS data to detect changes.
  3402. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  3403. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  3404. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  3405. # above but leaves the raw payload's tracked fields untouched — so a
  3406. # raw-based hash never flips and on_ams_change never fires, leaving the
  3407. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  3408. # always spans every unit, so a partial single-unit update can't produce a
  3409. # spuriously different hash from a full pushall.
  3410. ams_hash_data = []
  3411. for ams_unit in merged_ams:
  3412. for tray in ams_unit.get("tray", []):
  3413. # Include fields that matter for filament tracking
  3414. ams_hash_data.append(
  3415. f"{ams_unit.get('id')}:{tray.get('id')}:"
  3416. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  3417. )
  3418. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  3419. # Only trigger callback if AMS data actually changed
  3420. if ams_hash != self._previous_ams_hash:
  3421. self._previous_ams_hash = ams_hash
  3422. if self.on_ams_change:
  3423. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  3424. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  3425. # may lack fields like 'remain' that the merged state preserves
  3426. self.on_ams_change(merged_ams)
  3427. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  3428. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  3429. # or cali_idx — so an assignment that only swaps the filament id on an
  3430. # already-loaded slot would not flip the hash, and gating the check on
  3431. # it would miss exactly the confirmation we are after.
  3432. if self._pending_assignments:
  3433. self._check_assignment_verifications()
  3434. def _log_drying_cycle_end(
  3435. self,
  3436. ams_id: int,
  3437. remaining: int,
  3438. ams_unit: dict,
  3439. target: dict[str, object] | None,
  3440. ) -> None:
  3441. """Report a finished drying cycle, with the firmware's reason when it was
  3442. cut short (#2770).
  3443. A cycle that reaches its configured duration needs no explanation and
  3444. keeps the one-line "drying complete" it has always had. One that ends
  3445. with most of its countdown left was ended by somebody, and there are
  3446. only two candidates: a stop Bambuddy sent — the print-takes-priority
  3447. stop, or the user's Stop button — which is named as such, or the
  3448. firmware.
  3449. For the firmware case the only account of why lives in fields we already
  3450. parse but have never written down: the ``dry_status`` /
  3451. ``dry_sub_status`` phase from the info hex, the per-unit
  3452. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  3453. that moment. Logging them at INFO puts them in every support bundle by
  3454. default, which is what a report like #2770 needs before its cause can be
  3455. argued about at all.
  3456. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  3457. logged for every cycle, early or not, because they are what decides
  3458. whether auto-drying re-arms. Reconstructing them for #2770 meant
  3459. cross-referencing hourly alarm lines against 30-second scheduler debug
  3460. that was switched off at the time; one line here says it outright — a
  3461. cycle ending at 63 degC with the reading still above the threshold is
  3462. the whole shape of the re-arm loop.
  3463. """
  3464. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  3465. if ams_id in self._drying_stops_sent:
  3466. self._drying_stops_sent.discard(ams_id)
  3467. logger.info(
  3468. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  3469. self.serial_number,
  3470. ams_id,
  3471. remaining,
  3472. box,
  3473. )
  3474. return
  3475. if remaining <= _EARLY_DRY_END_MINUTES:
  3476. logger.info(
  3477. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  3478. self.serial_number,
  3479. ams_id,
  3480. remaining,
  3481. box,
  3482. )
  3483. return
  3484. requested_minutes: int | None = None
  3485. if target is not None:
  3486. try:
  3487. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  3488. except (TypeError, ValueError):
  3489. requested_minutes = None
  3490. logger.info(
  3491. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  3492. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  3493. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  3494. self.serial_number,
  3495. ams_id,
  3496. remaining,
  3497. requested_minutes if requested_minutes is not None else "?",
  3498. ams_unit.get("dry_status"),
  3499. ams_unit.get("dry_sub_status"),
  3500. ams_unit.get("dry_sf_reason") or [],
  3501. [e.full_code for e in self.state.hms_errors] or "none",
  3502. box,
  3503. )
  3504. def register_assignment_verification(
  3505. self,
  3506. ams_id: int,
  3507. tray_id: int,
  3508. tray_info_idx: str,
  3509. tray_color: str,
  3510. cali_idx: int | None,
  3511. ) -> None:
  3512. """Record an assignment we just pushed so subsequent AMS telemetry can
  3513. confirm the tray actually accepted it (#2582).
  3514. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  3515. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  3516. accepted filament id back in the per-tray push, so a match means the
  3517. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  3518. signal so we can specifically flag "filament loaded but K-profile not
  3519. applied", which is the exact symptom the reporter chased via flow-cal.
  3520. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  3521. there is nothing to verify and no record is stored.
  3522. """
  3523. want_idx = (tray_info_idx or "").strip().upper()
  3524. if not want_idx:
  3525. return
  3526. self._pending_assignments[(ams_id, tray_id)] = {
  3527. "tray_info_idx": want_idx,
  3528. "tray_color": (tray_color or "").strip().upper(),
  3529. "cali_idx": cali_idx,
  3530. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  3531. "last_seen_idx": None,
  3532. }
  3533. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  3534. """Locate the live tray dict for a pending verification.
  3535. External spools (ams_id 255) live in ``vt_tray`` under global ids
  3536. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  3537. report a single tray whose id may not equal the logical tray_id, so fall
  3538. back to the sole tray when an id match fails.
  3539. """
  3540. raw = self.state.raw_data or {}
  3541. if ams_id == 255:
  3542. want_ext = 254 + tray_id
  3543. for vt in raw.get("vt_tray", []) or []:
  3544. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  3545. return vt
  3546. return None
  3547. for unit in raw.get("ams", []) or []:
  3548. if str(unit.get("id")) != str(ams_id):
  3549. continue
  3550. trays = unit.get("tray", []) or []
  3551. for tray in trays:
  3552. if str(tray.get("id")) == str(tray_id):
  3553. return tray
  3554. if ams_id >= 128 and len(trays) == 1:
  3555. return trays[0]
  3556. return None
  3557. return None
  3558. def _check_assignment_verifications(self) -> None:
  3559. """Compare each pending assignment against live tray telemetry and fire
  3560. ``on_assignment_verified`` on a match or once the deadline passes.
  3561. Runs on every AMS push. Non-matching-but-still-within-window entries are
  3562. left in place for the next push. The timeout branch only fires when a
  3563. later push arrives after the deadline; if the printer goes silent we
  3564. simply never confirm, which is preferable to inventing a failure.
  3565. """
  3566. now = time.monotonic()
  3567. for key, want in list(self._pending_assignments.items()):
  3568. ams_id, tray_id = key
  3569. tray = self._find_verify_tray(ams_id, tray_id)
  3570. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  3571. if tray is not None and actual_idx:
  3572. want["last_seen_idx"] = actual_idx
  3573. if actual_idx and actual_idx == want["tray_info_idx"]:
  3574. self._pending_assignments.pop(key, None)
  3575. kprofile_applied = True
  3576. want_cali = want.get("cali_idx")
  3577. if want_cali is not None and want_cali >= 0:
  3578. actual_cali = tray.get("cali_idx")
  3579. kprofile_applied = actual_cali == want_cali
  3580. self._fire_assignment_verified(
  3581. ams_id,
  3582. tray_id,
  3583. True,
  3584. {
  3585. "tray_info_idx": actual_idx,
  3586. "kprofile_applied": kprofile_applied,
  3587. },
  3588. )
  3589. elif now >= want["deadline"]:
  3590. self._pending_assignments.pop(key, None)
  3591. self._fire_assignment_verified(
  3592. ams_id,
  3593. tray_id,
  3594. False,
  3595. {
  3596. "expected_tray_info_idx": want["tray_info_idx"],
  3597. "actual_tray_info_idx": want.get("last_seen_idx"),
  3598. # True when we saw the tray at least once (so the push
  3599. # channel is alive and the printer really stored a
  3600. # different/blank id) vs never observing it at all.
  3601. "saw_tray": want.get("last_seen_idx") is not None,
  3602. },
  3603. )
  3604. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  3605. if verified:
  3606. logger.info(
  3607. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  3608. self.serial_number,
  3609. ams_id,
  3610. tray_id,
  3611. detail.get("tray_info_idx"),
  3612. detail.get("kprofile_applied"),
  3613. )
  3614. else:
  3615. logger.warning(
  3616. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  3617. self.serial_number,
  3618. ams_id,
  3619. tray_id,
  3620. detail.get("expected_tray_info_idx"),
  3621. detail.get("actual_tray_info_idx"),
  3622. detail.get("saw_tray"),
  3623. )
  3624. if self.on_assignment_verified:
  3625. try:
  3626. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  3627. except Exception:
  3628. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  3629. @staticmethod
  3630. def _probe_number(value, fallback: float | None = None) -> float | None:
  3631. """Coerce a telemetry field to a number, or return `fallback`.
  3632. Firmware is inconsistent about whether these arrive as ints or as
  3633. numeric strings, and the probe must never raise on a surprise type.
  3634. """
  3635. try:
  3636. return float(value)
  3637. except (TypeError, ValueError):
  3638. return fallback
  3639. def _probe_end_of_print(self, data: dict) -> None:
  3640. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  3641. Opens on the first frame that looks like end-of-print (last object
  3642. layer reached, progress at 99+, or no remaining time), then logs each
  3643. frame in which any probed field changed, and closes on the transition
  3644. out of RUNNING. Armed once per print — see the module-level comment on
  3645. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  3646. currently see into.
  3647. Read-only with respect to printer state: this is instrumentation, and
  3648. nothing downstream may come to depend on it.
  3649. """
  3650. if not logger.isEnabledFor(logging.DEBUG):
  3651. return
  3652. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  3653. return
  3654. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  3655. if not present:
  3656. return
  3657. if not self._eop_probe_open:
  3658. # Open on any end-of-print signal. Read from the raw frame first so
  3659. # the frame that *carries* the signal is itself captured — state
  3660. # fields are only updated further down this same call.
  3661. layer = self._probe_number(data.get("layer_num"), self.state.layer_num) or 0
  3662. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  3663. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  3664. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  3665. at_last_layer = total > 0 and layer >= total
  3666. # `remaining <= 0` is only meaningful once the print has actually
  3667. # progressed — it reads 0 during the pre-print calibration too.
  3668. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  3669. if not (at_last_layer or percent >= 99 or out_of_time):
  3670. return
  3671. self._eop_probe_open = True
  3672. self._eop_probe_frames = 0
  3673. self._eop_probe_last = {}
  3674. logger.debug(
  3675. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  3676. self.serial_number,
  3677. layer,
  3678. total,
  3679. percent,
  3680. remaining,
  3681. )
  3682. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  3683. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  3684. self._eop_probe_last.update(present)
  3685. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  3686. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  3687. self._eop_probe_frames += 1
  3688. logger.debug(
  3689. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  3690. self.serial_number,
  3691. _END_OF_PRINT_PROBE_MAX_FRAMES,
  3692. )
  3693. return
  3694. if changed or closing:
  3695. self._eop_probe_frames += 1
  3696. logger.debug(
  3697. "[%s] EOP-PROBE %s%s: %s",
  3698. self.serial_number,
  3699. self._eop_probe_frames,
  3700. " CLOSE" if closing else "",
  3701. # `changed` on a closing frame can be empty; fall back to the
  3702. # full picture so the last line is always self-contained.
  3703. changed if changed else present,
  3704. )
  3705. if closing:
  3706. self._eop_probe_open = False
  3707. self._eop_probe_armed = False
  3708. self._eop_probe_last = {}
  3709. def _update_state(self, data: dict):
  3710. """Update printer state from message data."""
  3711. _previous_state = self.state.state
  3712. # #2547: instrumentation only — runs before any state mutation so the
  3713. # frame carrying an end-of-print signal is logged as it arrived.
  3714. try:
  3715. self._probe_end_of_print(data)
  3716. except Exception: # pragma: no cover - a probe must never break ingest
  3717. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  3718. # Update state fields
  3719. if "gcode_state" in data:
  3720. self.state.state = data["gcode_state"]
  3721. if "gcode_file" in data:
  3722. self.state.gcode_file = data["gcode_file"]
  3723. self.state.current_print = data["gcode_file"]
  3724. if "subtask_name" in data:
  3725. self.state.subtask_name = data["subtask_name"]
  3726. # Prefer subtask_name as current_print if available
  3727. if data["subtask_name"]:
  3728. self.state.current_print = data["subtask_name"]
  3729. if "subtask_id" in data:
  3730. self.state.subtask_id = data["subtask_id"]
  3731. if "mc_percent" in data:
  3732. # Billing: retain this frame's latest positive value immediately.
  3733. # A display-side abort may be the very next frame (and may omit
  3734. # mc_percent entirely), so retaining only the previous frame can
  3735. # lose the only usable estimate for proportional charging.
  3736. previous_progress = self.state.progress
  3737. new_progress = float(data["mc_percent"])
  3738. if new_progress > 0:
  3739. self._last_valid_progress = new_progress
  3740. self.state.progress = new_progress
  3741. # #2547: strictly-increasing only. The firmware resets progress to 0
  3742. # on cancel and re-reports the same percent on most frames; neither
  3743. # is the print advancing, and both would make the frame bank grab a
  3744. # camera frame for nothing.
  3745. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  3746. self.on_print_progress(int(self.state.progress))
  3747. if "mc_remaining_time" in data:
  3748. self.state.remaining_time = int(data["mc_remaining_time"])
  3749. if "mc_print_sub_stage" in data:
  3750. new_sub_stage = int(data["mc_print_sub_stage"])
  3751. if new_sub_stage != self.state.mc_print_sub_stage:
  3752. logger.debug(
  3753. f"[{self.serial_number}] mc_print_sub_stage changed: "
  3754. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  3755. )
  3756. self.state.mc_print_sub_stage = new_sub_stage
  3757. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  3758. # front because three places below consult it and they run in an order
  3759. # that is not the order they read most naturally in: the layer-advance
  3760. # refresh (#2702) must not fire on a frame that already answers it, the
  3761. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  3762. # reset must not discard a total that belongs to the starting print.
  3763. total_from_this_frame = 0
  3764. if "total_layer_num" in data:
  3765. try:
  3766. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  3767. except (TypeError, ValueError):
  3768. # Must not escape. `_on_message` catches only JSONDecodeError
  3769. # and paho is left at `suppress_exceptions = False`, so an
  3770. # exception raised here is re-raised on the network thread and
  3771. # takes the printer connection down over one unusable field.
  3772. # Treat it as "not reported": the refresh below then recovers
  3773. # the real total from a pushall.
  3774. logger.debug(
  3775. "[%s] ignoring unusable total_layer_num: %r",
  3776. self.serial_number,
  3777. data["total_layer_num"],
  3778. )
  3779. if "layer_num" in data:
  3780. try:
  3781. new_layer = int(data["layer_num"])
  3782. except (TypeError, ValueError):
  3783. # Contained for the same reason as `total_layer_num` above: an
  3784. # exception raised here escapes `_update_state` and paho
  3785. # re-raises it on the network thread. Losing this frame would
  3786. # also lose the print-start and completion detection further
  3787. # down, which is worse than losing a layer number.
  3788. #
  3789. # Held at the last known layer rather than substituted with 0:
  3790. # a fabricated 0 reads as the firmware's cancel reset, which
  3791. # would move `_last_valid_layer_num` and show layer 0 in the UI
  3792. # until the next good frame.
  3793. logger.debug(
  3794. "[%s] ignoring unusable layer_num: %r",
  3795. self.serial_number,
  3796. data["layer_num"],
  3797. )
  3798. new_layer = self.state.layer_num
  3799. old_layer = self.state.layer_num
  3800. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  3801. if old_layer > 0:
  3802. self._last_valid_layer_num = old_layer
  3803. self.state.layer_num = new_layer
  3804. # Trigger layer change callback if layer increased
  3805. if new_layer > old_layer and self.on_layer_change:
  3806. self.on_layer_change(new_layer)
  3807. # #2702: the print is demonstrably laying down layers but we still
  3808. # have no denominator, so the pushall requested at print start
  3809. # either went unanswered or raced the printer learning the total.
  3810. # Ask once more — by layer 1 the printer definitely knows it.
  3811. # One-shot: an unanswered pushall must not turn into a per-layer
  3812. # retry loop for the rest of the print.
  3813. if (
  3814. new_layer > old_layer
  3815. and self._total_layers_refresh_armed
  3816. and not self.state.total_layers
  3817. and not total_from_this_frame
  3818. ):
  3819. self._total_layers_refresh_armed = False
  3820. logger.debug(
  3821. "[%s] layer %s with no total_layer_num — re-requesting full status",
  3822. self.serial_number,
  3823. new_layer,
  3824. )
  3825. self._request_push_all()
  3826. # #2547: there is deliberately NO finish-photo trigger on the
  3827. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  3828. # moment the printer *starts* the final layer, not the moment it
  3829. # finishes it — on the H2C capture that closed #2547 the edge
  3830. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  3831. # filament change before the print actually ended, so the photo
  3832. # showed the toolhead mid-print over the part. Worse, the trigger
  3833. # latched `_finish_photo_captured`, locking out both the stage-22
  3834. # and FINISH triggers below for the rest of the print.
  3835. #
  3836. # #1867 (End G-code ejects the plate before FINISH) is handled
  3837. # where it belongs instead: `on_finish_photo_moment` prefers the
  3838. # in-print frame bank when the dispatcher recorded that it injected
  3839. # End G-code into this print. See services/print_dispatch_context.
  3840. if total_from_this_frame:
  3841. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  3842. # end — same shape as the `layer_num` reset guarded above. Applying
  3843. # only positive values preserves the last known good denominator so
  3844. # the usage-tracker split path (#1771) survives the reset frame.
  3845. self.state.total_layers = total_from_this_frame
  3846. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  3847. # Convert to 0-100 percentage for display
  3848. def parse_fan_speed(value: str | int | None) -> int | None:
  3849. if value is None:
  3850. return None
  3851. try:
  3852. speed = int(value)
  3853. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  3854. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  3855. if speed <= 15:
  3856. return round(speed * 100 / 15)
  3857. # If already a percentage (0-255 scale from some printers), convert
  3858. elif speed <= 255:
  3859. return round(speed * 100 / 255)
  3860. return speed
  3861. except (ValueError, TypeError):
  3862. return None
  3863. # Log fan fields once for debugging
  3864. if not hasattr(self, "_fan_fields_logged"):
  3865. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  3866. if fan_fields:
  3867. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  3868. self._fan_fields_logged = True
  3869. if "cooling_fan_speed" in data:
  3870. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  3871. if "big_fan1_speed" in data:
  3872. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  3873. if "big_fan2_speed" in data:
  3874. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  3875. if "heatbreak_fan_speed" in data:
  3876. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  3877. # Calibration stage tracking
  3878. if "stg_cur" in data:
  3879. new_stg = data["stg_cur"]
  3880. prev_stg = self.state.stg_cur
  3881. # Always log ANY stg_cur change for debugging filament operations
  3882. if new_stg != prev_stg:
  3883. logger.debug(
  3884. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  3885. )
  3886. # A stage we cannot name is the one worth seeing at the default
  3887. # log level: the DEBUG line above is off in normal running, so
  3888. # an unnamed stage otherwise reaches the user as "Unknown stage
  3889. # (72)" on a card with nothing behind it to say when it
  3890. # happened or what the printer was doing. Recorded once per
  3891. # stage number per session, with the stage it came from and the
  3892. # print state, which is what naming it later needs. Guarded on
  3893. # the int type because the field is whatever the firmware sent.
  3894. if (
  3895. isinstance(new_stg, int)
  3896. and not isinstance(new_stg, bool)
  3897. # -1 is Bambuddy's own "not in a stage" sentinel and the
  3898. # initial value of the field, not something the firmware
  3899. # reports; every print would otherwise report it on the way
  3900. # out of its last real stage.
  3901. and new_stg != -1
  3902. and new_stg not in STAGE_NAMES
  3903. and new_stg not in self._unnamed_stages_seen
  3904. ):
  3905. self._unnamed_stages_seen.add(new_stg)
  3906. logger.info(
  3907. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  3908. "state=%s progress=%s%% layer=%s/%s",
  3909. self.serial_number,
  3910. new_stg,
  3911. self.model,
  3912. prev_stg,
  3913. get_stage_name(prev_stg),
  3914. self.state.state,
  3915. self.state.progress,
  3916. self.state.layer_num,
  3917. self.state.total_layers,
  3918. )
  3919. self.state.stg_cur = new_stg
  3920. # #1721 end-of-print finish photo trigger.
  3921. # Stage 22 = "Filament unloading" fires at end-of-print AND
  3922. # during mid-print color swaps. The end-of-print gate
  3923. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  3924. # — those signals only line up at the real end. Edge-only
  3925. # (prev != 22) so the trigger fires once per stage entry.
  3926. if (
  3927. new_stg == 22
  3928. and prev_stg != 22
  3929. and self._was_running
  3930. and not self._finish_photo_captured
  3931. and self.on_finish_photo_moment
  3932. ):
  3933. progress = self.state.progress or 0.0
  3934. layer_num = self.state.layer_num or 0
  3935. total_layers = self.state.total_layers or 0
  3936. remaining = self.state.remaining_time or 0
  3937. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  3938. if is_end_of_print:
  3939. self._finish_photo_captured = True
  3940. logger.info(
  3941. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  3942. f"progress={progress}, layer={layer_num}/{total_layers}, "
  3943. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  3944. )
  3945. self.on_finish_photo_moment(
  3946. {
  3947. "trigger": "stage_22",
  3948. "filename": self._previous_gcode_file or self.state.gcode_file,
  3949. "subtask_name": self.state.subtask_name,
  3950. "timelapse_was_active": self._timelapse_during_print,
  3951. }
  3952. )
  3953. if "stg" in data:
  3954. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  3955. # Temperature data
  3956. temps = {}
  3957. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  3958. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  3959. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  3960. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  3961. # Log ALL keys in print data for H2D temperature discovery
  3962. all_keys = sorted(data.keys())
  3963. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  3964. self._temp_fields_logged = True
  3965. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  3966. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  3967. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  3968. self._vir_slot_logged = True
  3969. # Log nozzle hardware info fields (once)
  3970. nozzle_fields = {
  3971. k: v
  3972. for k, v in data.items()
  3973. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  3974. }
  3975. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  3976. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  3977. self._nozzle_fields_logged = True
  3978. # Parse active extruder from device.extruder.state bit 8
  3979. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  3980. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  3981. if "device" in data and isinstance(data.get("device"), dict):
  3982. device = data["device"]
  3983. # One-shot identification probe: surface whatever the firmware uses to
  3984. # name itself so an unknown model in a support bundle becomes self-
  3985. # diagnosing. INFO level so it shows up without debug logging. Falls
  3986. # back to dumping device.keys() if none of the known fields are present
  3987. # (so a future Bambu rename like `model_name` is still observable).
  3988. if not getattr(self, "_device_id_logged", False):
  3989. id_fields = {
  3990. k: device.get(k)
  3991. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  3992. if k in device
  3993. }
  3994. if id_fields:
  3995. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  3996. else:
  3997. logger.info(
  3998. "[%s] Device identification: no known id fields; device.keys=%s",
  3999. self.serial_number,
  4000. sorted(device.keys()),
  4001. )
  4002. self._device_id_logged = True
  4003. if "extruder" in device and "state" in device["extruder"]:
  4004. state_val = device["extruder"]["state"]
  4005. # Extract bit 8 for extruder position
  4006. new_extruder = (state_val >> 8) & 0x1
  4007. if new_extruder != self.state.active_extruder:
  4008. logger.debug(
  4009. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  4010. )
  4011. self.state.active_extruder = new_extruder
  4012. # Log device.extruder structure for active extruder
  4013. if "device" in data and isinstance(data.get("device"), dict):
  4014. device = data["device"]
  4015. if "extruder" in device:
  4016. ext_data = device["extruder"]
  4017. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4018. if "state" in ext_data:
  4019. state_val = ext_data["state"]
  4020. # Extract bits 12-14 (3 bits) for switch state
  4021. switch_state = (state_val >> 12) & 0x7
  4022. self._debug_on_change(
  4023. "extruder_state",
  4024. state_val,
  4025. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4026. self.serial_number,
  4027. state_val,
  4028. switch_state,
  4029. )
  4030. # Log 'cur' field if present (might indicate current/active extruder)
  4031. if "cur" in ext_data:
  4032. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4033. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4034. # it first. Repeated here so _update_state stays a complete "absorb this
  4035. # payload" step for any other caller; re-parsing the same block is free.
  4036. self._parse_fila_switch(data)
  4037. self._parse_extruder_slots(data)
  4038. if "bed_temper" in data:
  4039. temps["bed"] = float(data["bed_temper"])
  4040. if "bed_target_temper" in data:
  4041. temps["bed_target"] = float(data["bed_target_temper"])
  4042. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4043. has_h2d_extruder_info = (
  4044. "device" in data
  4045. and isinstance(data.get("device"), dict)
  4046. and "extruder" in data["device"]
  4047. and isinstance(data["device"]["extruder"].get("info"), list)
  4048. and len(data["device"]["extruder"]["info"]) >= 2
  4049. )
  4050. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4051. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4052. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4053. if "nozzle_temper" in data:
  4054. if has_h2d_extruder_info:
  4055. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4056. else:
  4057. temps["nozzle"] = float(data["nozzle_temper"])
  4058. if "nozzle_target_temper" in data:
  4059. if has_h2d_extruder_info:
  4060. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4061. else:
  4062. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4063. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4064. if not has_h2d_extruder_info:
  4065. # Try multiple possible field names used by different firmware versions
  4066. if "nozzle_temper_2" in data:
  4067. val = float(data["nozzle_temper_2"])
  4068. if -50 < val < 500: # Valid temp range
  4069. temps["nozzle_2"] = val
  4070. else:
  4071. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4072. elif "right_nozzle_temper" in data:
  4073. val = float(data["right_nozzle_temper"])
  4074. if -50 < val < 500: # Valid temp range
  4075. temps["nozzle_2"] = val
  4076. else:
  4077. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4078. if "nozzle_target_temper_2" in data:
  4079. val = float(data["nozzle_target_temper_2"])
  4080. if 0 <= val < 500: # Valid temp range
  4081. temps["nozzle_2_target"] = val
  4082. else:
  4083. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4084. elif "right_nozzle_target_temper" in data:
  4085. val = float(data["right_nozzle_target_temper"])
  4086. if 0 <= val < 500: # Valid temp range
  4087. temps["nozzle_2_target"] = val
  4088. else:
  4089. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4090. # Also check for left nozzle as primary (some H2 models)
  4091. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4092. temps["nozzle"] = float(data["left_nozzle_temper"])
  4093. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4094. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4095. if "chamber_temper" in data:
  4096. chamber_val = float(data["chamber_temper"])
  4097. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4098. # Check if we recently set the target locally (within 5 seconds)
  4099. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4100. respect_local = (time.time() - local_set_time) < 5.0
  4101. # H2D protocol: chamber_temper encoding indicates heater state
  4102. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4103. # - When < 500: direct Celsius current temp only - heater is OFF
  4104. if -50 < chamber_val < 100:
  4105. # Direct value = heater is OFF
  4106. temps["chamber"] = chamber_val
  4107. if not respect_local:
  4108. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4109. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4110. else:
  4111. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4112. # Try to decode if it looks like an encoded value
  4113. if chamber_val > 500:
  4114. mqtt_target = int(chamber_val) // 65536
  4115. current = int(chamber_val) % 65536
  4116. logger.debug(
  4117. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4118. )
  4119. if -50 < current < 100:
  4120. temps["chamber"] = float(current)
  4121. # Store decoded target for later use, but DON'T set chamber_heating here!
  4122. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4123. # which is the authoritative source the slicer uses.
  4124. if not respect_local:
  4125. if 0 <= mqtt_target <= 60:
  4126. # Store as "decoded" target - may be overridden by explicit target fields
  4127. temps["_chamber_decoded_target"] = float(mqtt_target)
  4128. # Chamber target temperature (set by print file or display)
  4129. if "mc_target_cham" in data:
  4130. mc_target = float(data["mc_target_cham"])
  4131. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4132. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4133. if 0 <= mc_target <= 60:
  4134. temps["chamber_target"] = mc_target
  4135. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4136. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4137. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4138. try:
  4139. if "info" in data and isinstance(data["info"], dict):
  4140. info_temp = data["info"].get("temp")
  4141. if info_temp is not None and "chamber" not in temps:
  4142. # Check for encoded value (target * 65536 + current)
  4143. if info_temp > 500:
  4144. # Decode: extract current temperature and target
  4145. target = info_temp // 65536
  4146. current = info_temp % 65536
  4147. temps["chamber"] = float(current)
  4148. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4149. if "_chamber_decoded_target" not in temps:
  4150. temps["_chamber_decoded_target"] = float(target)
  4151. logger.debug(
  4152. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4153. )
  4154. elif -50 < info_temp < 100:
  4155. # Valid direct temperature - heater is OFF
  4156. temps["chamber"] = float(info_temp)
  4157. temps["chamber_target"] = 0.0 # Direct value means heater off
  4158. self._debug_on_change(
  4159. "info_temp_direct",
  4160. info_temp,
  4161. "[%s] info.temp direct: %s°C (heater OFF)",
  4162. self.serial_number,
  4163. info_temp,
  4164. )
  4165. # H2D series: Dual extruder temps are in device.extruder.info array
  4166. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4167. if "device" in data and isinstance(data["device"], dict):
  4168. device = data["device"]
  4169. # Parse dual extruder temperatures
  4170. extruder_data = device.get("extruder", {})
  4171. extruder_info = extruder_data.get("info", [])
  4172. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4173. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4174. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4175. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4176. if has_h2d_extruder_info:
  4177. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4178. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4179. if "temp" in extruder_info[0]:
  4180. temp_val = extruder_info[0]["temp"]
  4181. if temp_val > 500:
  4182. # Encoded format: temp = target * 65536 + current
  4183. target = temp_val // 65536
  4184. current = temp_val % 65536
  4185. if -50 < current < 500:
  4186. temps["nozzle_2"] = float(current)
  4187. if 0 < target < 500:
  4188. temps["nozzle_2_target"] = float(target)
  4189. temps["nozzle_2_heating"] = target > 0 and current < target
  4190. elif -50 < temp_val < 500:
  4191. # Direct Celsius value = heater is OFF
  4192. temps["nozzle_2"] = float(temp_val)
  4193. temps["nozzle_2_target"] = 0.0
  4194. temps["nozzle_2_heating"] = False
  4195. # Left nozzle (extruder 1) - only for dual nozzle printers
  4196. # H2D protocol: temp field encoding depends on value
  4197. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4198. # - When < 500: direct Celsius current temp only - heater is OFF
  4199. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4200. ext1 = extruder_info[1]
  4201. temp_val = ext1["temp"]
  4202. # Check if we recently set the target locally (within 5 seconds)
  4203. # If so, don't let MQTT data overwrite it
  4204. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4205. respect_local_target = (time.time() - local_set_time) < 5.0
  4206. if temp_val > 500:
  4207. # Encoded format: temp = target * 65536 + current
  4208. target = temp_val // 65536
  4209. current = temp_val % 65536
  4210. if 0 < target < 500 and not respect_local_target:
  4211. temps["nozzle_target"] = float(target)
  4212. if -50 < current < 500:
  4213. temps["nozzle"] = float(current)
  4214. # Heating = encoded AND we're using the MQTT target (not local override)
  4215. # If local target is being respected, use local target to determine heating
  4216. if respect_local_target:
  4217. local_target = self.state.temperatures.get("nozzle_target", 0)
  4218. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4219. else:
  4220. temps["nozzle_heating"] = target > 0 and current < target
  4221. elif -50 < temp_val < 500:
  4222. # Direct Celsius = heater is OFF (or at target with heater off)
  4223. temps["nozzle"] = float(temp_val)
  4224. if not respect_local_target:
  4225. temps["nozzle_target"] = 0.0
  4226. temps["nozzle_heating"] = False # Direct = not heating
  4227. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  4228. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  4229. if has_h2d_extruder_info:
  4230. for ext_info in extruder_info:
  4231. ext_id = ext_info.get("id")
  4232. snow = ext_info.get("snow")
  4233. if ext_id is not None and snow is not None and ext_id <= 1:
  4234. # Normalize H2D snow value to global tray ID
  4235. ams_id = snow >> 8
  4236. slot = snow & 0xFF
  4237. if 0 <= ams_id <= 3:
  4238. # Regular AMS slot
  4239. global_tray = ams_id * 4 + (slot & 0x03)
  4240. old_val = self.state.h2d_extruder_snow.get(ext_id)
  4241. if old_val != global_tray:
  4242. logger.debug(
  4243. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  4244. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  4245. )
  4246. self.state.h2d_extruder_snow[ext_id] = global_tray
  4247. elif ams_id == 254 or ams_id == 255:
  4248. # External spool or unloaded
  4249. normalized = 254 if slot != 255 else 255
  4250. old_val = self.state.h2d_extruder_snow.get(ext_id)
  4251. if old_val != normalized:
  4252. logger.debug(
  4253. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  4254. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  4255. )
  4256. self.state.h2d_extruder_snow[ext_id] = normalized
  4257. elif 128 <= ams_id <= 135:
  4258. # External spool with hub mapping
  4259. old_val = self.state.h2d_extruder_snow.get(ext_id)
  4260. if old_val != ams_id:
  4261. logger.debug(
  4262. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  4263. f"raw={snow} -> external hub {ams_id}"
  4264. )
  4265. self.state.h2d_extruder_snow[ext_id] = ams_id
  4266. # Parse bed heating state from device.bed.info.temp encoding
  4267. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4268. bed_data = device.get("bed", {})
  4269. bed_info = bed_data.get("info", {})
  4270. if "temp" in bed_info:
  4271. temp_val = bed_info["temp"]
  4272. if temp_val > 500:
  4273. target = temp_val // 65536
  4274. current = temp_val % 65536
  4275. temps["bed_heating"] = target > 0 and current < target
  4276. else:
  4277. temps["bed_heating"] = False
  4278. # Parse chamber temp from device.ctc.info.temp if not already set
  4279. ctc_data = device.get("ctc", {})
  4280. ctc_info = ctc_data.get("info", {})
  4281. # Parse airduct mode (0=cooling, 1=heating)
  4282. airduct_data = device.get("airduct", {})
  4283. if "modeCur" in airduct_data:
  4284. new_mode = airduct_data["modeCur"]
  4285. if new_mode != self.state.airduct_mode:
  4286. logger.debug(
  4287. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4288. )
  4289. self.state.airduct_mode = new_mode
  4290. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4291. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4292. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4293. # AIR_FUN enum: 1=part cooling, 2=right aux, 3=chamber/exhaust,
  4294. # 10=left aux (FAN_REMOTE_COOLING_1). The airduct `parts` list only
  4295. # contains the fans that physically exist, so it doubles as a
  4296. # presence signal for the two P2S/X2D add-on kits:
  4297. # - id 10 (left auxiliary part cooling fan) — reported ONLY here,
  4298. # never mirrored into a flat big_fanX_speed field.
  4299. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4300. # big_fan2_speed, but the part is only listed when the External
  4301. # Exhaust Fan kit (get_version module "eef") is installed.
  4302. # `state` is already a 0-100 percentage.
  4303. parts = airduct_data.get("parts")
  4304. if isinstance(parts, list):
  4305. speeds: dict[int, int] = {}
  4306. for part in parts:
  4307. if not isinstance(part, dict):
  4308. continue
  4309. try:
  4310. # Studio reads the id with get_flag_bits(id, 4, 8),
  4311. # so mask after shifting for the same reason `state`
  4312. # is masked below. Every id seen in the wild
  4313. # (16/32/48/160) decodes identically either way —
  4314. # this is consistency, not a live bug.
  4315. part_id = (int(part["id"]) >> 4) & 0xFF
  4316. # `state` is bit-packed like its sibling `range`
  4317. # (end << 16 | start), so take only the low 8 bits —
  4318. # the same decode Bambu Studio does with
  4319. # get_flag_bits(state, 0, 8). Without the mask a
  4320. # packed value would clamp to 100 instead of
  4321. # decoding to the real percentage.
  4322. part_state = int(part["state"]) & 0xFF
  4323. except (KeyError, ValueError, TypeError):
  4324. continue
  4325. # Ids seen across the support-package archive:
  4326. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4327. # 6 (H2 series, unmapped), 10 left aux.
  4328. speeds[part_id] = max(0, min(100, part_state))
  4329. # Absence in this list is what tells us a kit is NOT fitted,
  4330. # so it may only be trusted when the list is a full
  4331. # inventory rather than a diff frame. `device.airduct` is
  4332. # pushed field by field — the `modeCur` handler above exists
  4333. # for exactly that reason — and a truncated `parts` read as
  4334. # gospel would retract both accessory badges mid-print and
  4335. # start rejecting `aux2` on a printer that has the fan.
  4336. #
  4337. # Every airduct layout in the support-package archive
  4338. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4339. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4340. # part cooling fan and the aux fan, neither of which is
  4341. # optional on any machine that reports an airduct at all.
  4342. # A list carrying both is therefore a complete inventory; a
  4343. # list missing either is a partial frame, and we take its
  4344. # speeds without touching presence.
  4345. is_full_inventory = 1 in speeds and 2 in speeds
  4346. left_aux_speed = speeds.get(10)
  4347. if left_aux_speed is None and not is_full_inventory:
  4348. # Partial frame that didn't mention the left aux fan —
  4349. # keep whatever we already knew about it.
  4350. left_aux_speed = self.state.left_aux_fan_speed
  4351. if left_aux_speed != self.state.left_aux_fan_speed:
  4352. logger.debug(
  4353. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4354. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4355. )
  4356. # A FULL parts list without id 10 means the left aux fan is
  4357. # not installed — report None so the UI can hide the widget.
  4358. self.state.left_aux_fan_speed = left_aux_speed
  4359. # id 3 present == chamber exhaust fan installed (base P2S
  4360. # omits it). Only ever retracted on a full inventory.
  4361. if 3 in speeds:
  4362. self.state.exhaust_fan_present = True
  4363. elif is_full_inventory:
  4364. self.state.exhaust_fan_present = False
  4365. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  4366. # Check if we recently set the target locally (within 5 seconds)
  4367. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4368. respect_local_target = (time.time() - local_set_time) < 5.0
  4369. # Log ctc_info contents for debugging
  4370. if ctc_info:
  4371. self._debug_on_change(
  4372. "ctc_info_keys",
  4373. tuple(ctc_info.keys()),
  4374. "[%s] ctc_info keys: %s",
  4375. self.serial_number,
  4376. list(ctc_info.keys()),
  4377. )
  4378. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  4379. # (what the slicer shows). This OVERRIDES any previously decoded target.
  4380. explicit_target = None
  4381. if "target" in ctc_info:
  4382. target_val = ctc_info["target"]
  4383. logger.debug(
  4384. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  4385. )
  4386. # Filter out invalid values (valid chamber target is 0-60°C)
  4387. if 0 <= target_val <= 60 and not respect_local_target:
  4388. explicit_target = float(target_val)
  4389. temps["chamber_target"] = explicit_target # Override any previous value
  4390. logger.debug(
  4391. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  4392. )
  4393. # Parse chamber temp from ctc.info.temp - may be encoded
  4394. if "temp" in ctc_info and "chamber" not in temps:
  4395. temp_val = ctc_info["temp"]
  4396. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  4397. if temp_val > 500:
  4398. # Encoded value: decode target and current
  4399. decoded_target = temp_val // 65536
  4400. current = temp_val % 65536
  4401. temps["chamber"] = float(current)
  4402. logger.debug(
  4403. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  4404. )
  4405. # Determine which target to use for heating state:
  4406. # Priority: local target > explicit target > decoded target
  4407. if respect_local_target:
  4408. local_target = self.state.temperatures.get("chamber_target", 0)
  4409. temps["chamber_heating"] = local_target > 0 and current < local_target
  4410. elif explicit_target is not None:
  4411. # Use explicit ctc.info.target - this is what slicer sees
  4412. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  4413. else:
  4414. # Fallback to decoded target only if no explicit target available
  4415. if not respect_local_target and "chamber_target" not in temps:
  4416. temps["chamber_target"] = float(decoded_target)
  4417. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  4418. else:
  4419. # Direct value (not encoded) - heater is OFF
  4420. temps["chamber"] = float(temp_val)
  4421. temps["chamber_heating"] = False
  4422. except Exception as e:
  4423. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  4424. if temps:
  4425. # Handle chamber_target: prefer explicit over decoded
  4426. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  4427. # No explicit target available, use decoded target from chamber_temper
  4428. temps["chamber_target"] = temps["_chamber_decoded_target"]
  4429. # Remove internal temp key before merging
  4430. temps.pop("_chamber_decoded_target", None)
  4431. # Merge new temps into existing, preserving valid values when new ones are filtered out
  4432. for key, value in temps.items():
  4433. self.state.temperatures[key] = value
  4434. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  4435. if "bed" in temps and self.on_bed_temp_update:
  4436. self.on_bed_temp_update(temps["bed"])
  4437. # Calculate chamber_heating after all targets are known
  4438. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  4439. if "chamber" in temps and "chamber_heating" not in temps:
  4440. current = self.state.temperatures.get("chamber", 0)
  4441. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4442. respect_local = (time.time() - local_set_time) < 5.0
  4443. if respect_local:
  4444. # Use locally-set target
  4445. target = self.state.temperatures.get("chamber_target", 0)
  4446. else:
  4447. # Use explicit/decoded target from MQTT
  4448. target = self.state.temperatures.get("chamber_target", 0)
  4449. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  4450. self._debug_on_change(
  4451. "chamber_heating",
  4452. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  4453. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  4454. self.serial_number,
  4455. target,
  4456. current,
  4457. self.state.temperatures["chamber_heating"],
  4458. respect_local,
  4459. )
  4460. # Debug: log chamber value if it was updated
  4461. if "chamber" in temps:
  4462. self._debug_on_change(
  4463. "chamber_temp",
  4464. (
  4465. self.state.temperatures.get("chamber"),
  4466. self.state.temperatures.get("chamber_target"),
  4467. self.state.temperatures.get("chamber_heating"),
  4468. ),
  4469. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  4470. self.serial_number,
  4471. self.state.temperatures.get("chamber"),
  4472. self.state.temperatures.get("chamber_target"),
  4473. self.state.temperatures.get("chamber_heating"),
  4474. )
  4475. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  4476. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  4477. if "nozzle" in temps and "nozzle_heating" not in temps:
  4478. current = self.state.temperatures.get("nozzle", 0)
  4479. target = self.state.temperatures.get("nozzle_target", 0)
  4480. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  4481. # Parse HMS (Health Management System) errors
  4482. if "hms" in data:
  4483. hms_list = data["hms"]
  4484. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  4485. self.state.hms_errors = []
  4486. verify_failed = False
  4487. if isinstance(hms_list, list):
  4488. for hms in hms_list:
  4489. if isinstance(hms, dict):
  4490. # HMS format: {"attr": attribute_code, "code": error_code}
  4491. # attr contains module/severity info, code contains error number
  4492. # Both are needed to construct the wiki URL
  4493. attr = hms.get("attr", 0)
  4494. code = hms.get("code", 0)
  4495. if isinstance(attr, str):
  4496. attr = int(attr.replace("0x", ""), 16) if attr else 0
  4497. if isinstance(code, str):
  4498. code = int(code.replace("0x", ""), 16) if code else 0
  4499. # Severity is in attr byte 1 (bits 8-15)
  4500. severity = (attr >> 8) & 0xF
  4501. # Module is in attr byte 3 (bits 24-31)
  4502. module = (attr >> 24) & 0xFF
  4503. # Skip non-error status codes — all real HMS errors
  4504. # have code >= 0x4000. Lower values are status/phase
  4505. # indicators that some firmware sends during normal printing.
  4506. if code < 0x4000:
  4507. continue
  4508. # Skip user-action echoes — the printer firmware emits these
  4509. # as part of normal user-cancel sequences. They're not faults
  4510. # and shouldn't count toward "X problem" badges or surface as
  4511. # red pips on the printer card. Backend's notification path
  4512. # already suppresses 0500_400E for the same reason.
  4513. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  4514. if short_code in _HMS_USER_ACTION_CODES:
  4515. continue
  4516. # Catalog has both 8-char keys (base class) and 16-char keys
  4517. # (specific variants). The full 16-char identifier preserves
  4518. # the 32 bits of `attr_low` + `code_high` that the short_code
  4519. # discards — that's the firmware's matching key, so try it
  4520. # first and fall back to the short form.
  4521. full_code = f"{attr:08X}{code:08X}"
  4522. if full_code == HMS_MQTT_VERIFY_FAILED:
  4523. verify_failed = True
  4524. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  4525. if not actions:
  4526. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4527. self.state.hms_errors.append(
  4528. HMSError(
  4529. code=f"0x{code:x}" if code else "0x0",
  4530. attr=attr,
  4531. module=module,
  4532. severity=severity if severity > 0 else 2,
  4533. actions=actions,
  4534. job_id=self.state.subtask_id,
  4535. full_code=full_code,
  4536. description=describe_fault(full_code),
  4537. )
  4538. )
  4539. self._apply_mqtt_verify_state(verify_failed)
  4540. # Parse print_error - this is a different error format than HMS
  4541. # print_error is a 32-bit integer where:
  4542. # - High 16 bits contain module info (e.g., 0x0500)
  4543. # - Low 16 bits contain error code (e.g., 0x8061)
  4544. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  4545. if "print_error" in data:
  4546. print_error = data["print_error"]
  4547. if print_error and print_error != 0:
  4548. # Extract components: MMMMEEEE -> MMMM_EEEE
  4549. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  4550. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  4551. # Values below 0x4000 are status/phase indicators, not real errors.
  4552. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  4553. # Some firmware sends low values like 0x0002 during normal printing.
  4554. if error < 0x4000:
  4555. pass # Skip — not a real error
  4556. else:
  4557. # Store in a format that matches the community error database
  4558. # attr stores the full 32-bit value for reconstruction
  4559. # code stores the short format string for lookup
  4560. short_code = f"{module:04X}_{error:04X}"
  4561. logger.debug(
  4562. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  4563. )
  4564. # Same user-action filter as the hms[] branch above — print_error
  4565. # carries the same cancel echoes (e.g. 0500_400E) and they must
  4566. # not surface as faults on the printer card.
  4567. if short_code in _HMS_USER_ACTION_CODES:
  4568. pass # cancel echo — silently drop
  4569. else:
  4570. # Only add if not already in HMS errors (avoid duplicates)
  4571. existing_short_codes = set()
  4572. for e in self.state.hms_errors:
  4573. # Extract short code from existing errors
  4574. e_module = (e.attr >> 16) & 0xFFFF
  4575. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  4576. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  4577. if short_code not in existing_short_codes:
  4578. # Bambu's HMS catalog keys by 3-letter device code (the SN
  4579. # prefix) and a 16-char short error code without the
  4580. # underscore separator we store internally.
  4581. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4582. # Bambu pushes the current job as `subtask_id` on the
  4583. # state stream; the HMS-action commands echo it back as
  4584. # `job_id`. The error payload itself doesn't carry the
  4585. # id, so snapshot it from the live state at parse time
  4586. # and freeze it on the HMSError so subsequent
  4587. # job changes don't invalidate the action.
  4588. job_id = self.state.subtask_id
  4589. logger.debug(
  4590. "[%s, %s] HMS available actions: %s (job_id=%s)",
  4591. self.serial_number[:3],
  4592. short_code.replace("_", ""),
  4593. actions,
  4594. job_id,
  4595. )
  4596. self.state.hms_errors.append(
  4597. HMSError(
  4598. code=f"0x{error:x}",
  4599. attr=print_error, # Store full value for display
  4600. module=module >> 8, # High byte of module (e.g., 0x05)
  4601. severity=3, # Warning level for print_error
  4602. actions=actions,
  4603. job_id=job_id,
  4604. # print_error is already 32-bit — `f"{print_error:08X}"`
  4605. # is the firmware's matching key with no truncation.
  4606. full_code=f"{print_error:08X}",
  4607. description=describe_fault(f"{print_error:08X}"),
  4608. )
  4609. )
  4610. # Parse home_flag first so SD-card detection below can prefer it.
  4611. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  4612. # bit 23 = door-open (X1 family only).
  4613. home_flag = None
  4614. if "home_flag" in data:
  4615. home_flag = data["home_flag"]
  4616. if home_flag < 0:
  4617. home_flag = home_flag & 0xFFFFFFFF
  4618. # SD card presence: the only remaining consumer is the firmware-update
  4619. # precondition check (firmware_update.py). Use the top-level `sdcard`
  4620. # field when present with a permissive truthy check covering the
  4621. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  4622. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  4623. # when a card is inserted, which caused the badge to flap before the
  4624. # badge was removed entirely.
  4625. if "sdcard" in data:
  4626. raw_sdcard = data["sdcard"]
  4627. if isinstance(raw_sdcard, str):
  4628. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  4629. else:
  4630. self.state.sdcard = bool(raw_sdcard)
  4631. self.state.sdcard_reported = True
  4632. if home_flag is not None:
  4633. store_to_sdcard = bool((home_flag >> 11) & 1)
  4634. if store_to_sdcard != self.state.store_to_sdcard:
  4635. logger.debug(
  4636. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  4637. )
  4638. self.state.store_to_sdcard = store_to_sdcard
  4639. # Door open detection — source depends on printer family:
  4640. # X1 series (X1, X1C, X1E): home_flag bit 23
  4641. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  4642. # Both share the same bitmask (0x00800000) but live in different fields.
  4643. model_upper = (self.model or "").upper().strip()
  4644. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  4645. if is_x1_family and home_flag is not None:
  4646. door_open = (home_flag & 0x00800000) != 0
  4647. if door_open != self.state.door_open:
  4648. logger.debug(
  4649. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  4650. self.serial_number,
  4651. self.state.door_open,
  4652. door_open,
  4653. home_flag,
  4654. )
  4655. self.state.door_open = door_open
  4656. elif not is_x1_family and "stat" in data:
  4657. try:
  4658. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  4659. door_open = (stat_value & 0x00800000) != 0
  4660. if door_open != self.state.door_open:
  4661. logger.debug(
  4662. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  4663. self.serial_number,
  4664. self.state.door_open,
  4665. door_open,
  4666. stat_value,
  4667. )
  4668. self.state.door_open = door_open
  4669. except (ValueError, TypeError):
  4670. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  4671. # Parse timelapse status (recording active during print). Status frames
  4672. # only — the project_file ack echoes back the per-job timelapse flag we
  4673. # asked for, which is a request, not the recorder's state (#3040).
  4674. if "timelapse" in data and is_printer_status_frame(data):
  4675. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  4676. self.state.timelapse = data["timelapse"] is True
  4677. # Track if timelapse was ever active during this print
  4678. if self.state.timelapse and self._was_running:
  4679. self._timelapse_during_print = True
  4680. # Parse ipcam/live view status
  4681. if "ipcam" in data:
  4682. ipcam_data = data["ipcam"]
  4683. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  4684. if isinstance(ipcam_data, dict):
  4685. # Check ipcam_record field for live view status
  4686. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  4687. # Check timelapse field (H2D sends it here, not in xcam)
  4688. if "timelapse" in ipcam_data:
  4689. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  4690. if timelapse_enabled != self.state.timelapse:
  4691. logger.debug(
  4692. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  4693. )
  4694. self.state.timelapse = timelapse_enabled
  4695. # Track if timelapse was ever active during this print
  4696. if self.state.timelapse and self._was_running:
  4697. self._timelapse_during_print = True
  4698. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  4699. else:
  4700. self.state.ipcam = ipcam_data is True
  4701. # Parse WiFi signal strength (dBm)
  4702. if "wifi_signal" in data:
  4703. wifi_signal = data["wifi_signal"]
  4704. self._debug_on_change(
  4705. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  4706. )
  4707. if isinstance(wifi_signal, (int, float)):
  4708. self.state.wifi_signal = int(wifi_signal)
  4709. elif isinstance(wifi_signal, str):
  4710. # Handle string format like "-52dBm"
  4711. try:
  4712. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  4713. except ValueError:
  4714. pass # Ignore unparseable wifi_signal strings; field is non-critical
  4715. # Detect ethernet connection: printers on ethernet with WiFi disabled
  4716. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  4717. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  4718. from backend.app.utils.printer_models import has_ethernet
  4719. if has_ethernet(self.model):
  4720. self.state.wired_network = self.state.wifi_signal == -90
  4721. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  4722. if "spd_lvl" in data:
  4723. new_speed = data["spd_lvl"]
  4724. if new_speed != self.state.speed_level:
  4725. logger.debug(
  4726. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  4727. )
  4728. self.state.speed_level = new_speed
  4729. # Parse skipped objects from printer status (s_obj field)
  4730. # This allows us to restore skipped objects state after reconnection
  4731. if "s_obj" in data:
  4732. s_obj = data["s_obj"]
  4733. if isinstance(s_obj, list):
  4734. # Update skipped objects from printer's list
  4735. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  4736. if new_skipped != self.state.skipped_objects:
  4737. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  4738. self.state.skipped_objects = new_skipped
  4739. # Parse chamber light status from lights_report
  4740. if "lights_report" in data:
  4741. lights = data["lights_report"]
  4742. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  4743. if isinstance(lights, list):
  4744. for light in lights:
  4745. if isinstance(light, dict) and light.get("node") == "chamber_light":
  4746. new_light_state = light.get("mode") == "on"
  4747. if new_light_state != self.state.chamber_light:
  4748. logger.debug(
  4749. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  4750. )
  4751. self.state.chamber_light = new_light_state
  4752. break
  4753. # Parse nozzle hardware info (single nozzle printers)
  4754. if "nozzle_type" in data:
  4755. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  4756. if "nozzle_diameter" in data:
  4757. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  4758. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  4759. # Left nozzle
  4760. if "left_nozzle_type" in data:
  4761. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  4762. if "left_nozzle_diameter" in data:
  4763. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  4764. # Right nozzle
  4765. if "right_nozzle_type" in data:
  4766. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  4767. if "right_nozzle_diameter" in data:
  4768. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  4769. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  4770. if "nozzle_type_2" in data:
  4771. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  4772. if "nozzle_diameter_2" in data:
  4773. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  4774. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  4775. if "device" in data and isinstance(data["device"], dict):
  4776. device = data["device"]
  4777. nozzle_data = device.get("nozzle", {})
  4778. # H2C rack position (#2800). `tar_id` is where the carriage is
  4779. # headed, `src_id` where it came from; mid-swap they differ, so
  4780. # dispatch prefers tar_id and falls back to src_id. Both are
  4781. # sticky — the field is only pushed when it changes, so an
  4782. # absent key must leave the last known value alone rather than
  4783. # reset it to None.
  4784. if isinstance(nozzle_data, dict):
  4785. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  4786. if key not in nozzle_data:
  4787. continue
  4788. try:
  4789. parsed_id = int(nozzle_data[key])
  4790. except (TypeError, ValueError):
  4791. continue
  4792. if getattr(self.state, attr) != parsed_id:
  4793. setattr(self.state, attr, parsed_id)
  4794. # DEBUG, not INFO: these move on every tool change, so
  4795. # a long multi-material print would otherwise write
  4796. # thousands of lines. The dispatch log records both
  4797. # values once per print, which is where triage needs
  4798. # them. Same reasoning as the one-shot `nozzle_info`
  4799. # log below.
  4800. logger.debug(
  4801. "[%s] Nozzle rack %s -> %s",
  4802. self.serial_number,
  4803. key,
  4804. parsed_id,
  4805. )
  4806. nozzle_info = nozzle_data.get("info", [])
  4807. if isinstance(nozzle_info, list):
  4808. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  4809. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  4810. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  4811. # for hover cards on both the L/R indicator and the nozzle rack card.
  4812. if nozzle_info:
  4813. self.state.nozzle_rack = sorted(
  4814. [
  4815. {
  4816. "id": n.get("id", i),
  4817. "type": str(n.get("type", "")),
  4818. "diameter": str(n.get("diameter", "")),
  4819. "wear": n.get("wear"),
  4820. "stat": n.get("stat"),
  4821. # H2C uses "tm", H2D uses "max_temp"
  4822. "max_temp": n.get("max_temp") or n.get("tm", 0),
  4823. # H2C uses "sn", H2D uses "serial_number"
  4824. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  4825. # H2C uses "color_m", H2D uses "filament_colour"
  4826. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  4827. # H2C uses "fila_id", H2D uses "filament_id"
  4828. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  4829. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  4830. }
  4831. for i, n in enumerate(nozzle_info)
  4832. ],
  4833. key=lambda x: x["id"],
  4834. )
  4835. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  4836. self._nozzle_rack_logged = True
  4837. logger.debug(
  4838. "[%s] Nozzle info: %d entries, IDs: %s",
  4839. self.serial_number,
  4840. len(nozzle_info),
  4841. [n.get("id") for n in nozzle_info],
  4842. )
  4843. for nozzle in nozzle_info:
  4844. idx = nozzle.get("id", 0)
  4845. if idx < len(self.state.nozzles):
  4846. if "type" in nozzle and nozzle["type"]:
  4847. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  4848. if "diameter" in nozzle:
  4849. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  4850. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  4851. # (these fields aren't sent in every MQTT push, only when changed)
  4852. ams_data = self.state.raw_data.get("ams")
  4853. vt_tray_data = self.state.raw_data.get("vt_tray")
  4854. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  4855. mapping_data = self.state.raw_data.get("mapping")
  4856. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  4857. # as a dict but consumers expect a list. Without this, the dev mode probe
  4858. # below can release the GIL (via publish), letting the event-loop thread
  4859. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  4860. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  4861. data["vt_tray"] = [data["vt_tray"]]
  4862. self.state.raw_data = data
  4863. # Restore preserved fields BEFORE any work that may release the GIL
  4864. # (e.g. _probe_developer_mode publishes an MQTT message).
  4865. if ams_data is not None:
  4866. self.state.raw_data["ams"] = ams_data
  4867. if vt_tray_data is not None:
  4868. self.state.raw_data["vt_tray"] = vt_tray_data
  4869. if ams_extruder_map_data is not None:
  4870. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  4871. if mapping_data is not None and "mapping" not in data:
  4872. self.state.raw_data["mapping"] = mapping_data
  4873. # Parse developer LAN mode from "fun" field
  4874. if "fun" in data:
  4875. try:
  4876. fun_val = data["fun"]
  4877. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  4878. self.state.developer_mode = (fun_int & 0x20000000) == 0
  4879. except (ValueError, TypeError):
  4880. pass
  4881. elif self.state.developer_mode is None and not self._dev_mode_probed:
  4882. # No "fun" field — A1/P1 series never send it, so we need to probe.
  4883. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  4884. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  4885. # after connect to let the MQTT session stabilize — probing too early
  4886. # can destabilize some firmware MQTT brokers (#887).
  4887. if not self._dev_mode_needs_probe and len(data) > 30:
  4888. # First full status without "fun" — mark that probe is needed
  4889. self._dev_mode_needs_probe = True
  4890. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  4891. self._probe_developer_mode()
  4892. elif self._dev_mode_needs_probe:
  4893. logger.debug(
  4894. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  4895. self.serial_number,
  4896. time.monotonic() - self._connect_time,
  4897. )
  4898. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  4899. # Probe was sent but no response yet — check for timeout.
  4900. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  4901. # may deliver status pushes but silently drop commands (#887).
  4902. elapsed = time.monotonic() - self._dev_mode_probe_time
  4903. if elapsed > 10.0:
  4904. self._dev_mode_probe_failures += 1
  4905. logger.warning(
  4906. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  4907. self.serial_number,
  4908. elapsed,
  4909. self._dev_mode_probe_failures,
  4910. )
  4911. self._dev_mode_probe_seq = None
  4912. if self._dev_mode_probe_failures >= 2:
  4913. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  4914. else:
  4915. # Allow retry on next full status message
  4916. self._dev_mode_probed = False
  4917. # Zombie session detection: if an ams_filament_setting command has been
  4918. # pending for >10s with no response, the publish path is likely dead (#887).
  4919. if self._last_ams_cmd_time > 0:
  4920. elapsed = time.monotonic() - self._last_ams_cmd_time
  4921. if elapsed > 10.0:
  4922. self._ams_cmd_unanswered += 1
  4923. logger.warning(
  4924. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  4925. self.serial_number,
  4926. elapsed,
  4927. self._ams_cmd_unanswered,
  4928. )
  4929. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  4930. if self._ams_cmd_unanswered >= 2:
  4931. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  4932. self._ams_cmd_unanswered = 0
  4933. # Log mapping data when received (for usage tracking debugging)
  4934. if "mapping" in data:
  4935. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  4936. # Log state transitions for debugging
  4937. if "gcode_state" in data:
  4938. logger.debug(
  4939. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  4940. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  4941. )
  4942. # Detect print start (state changes TO RUNNING with a file)
  4943. current_file = self.state.gcode_file or self.state.current_print
  4944. is_new_print = (
  4945. self.state.state == "RUNNING"
  4946. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  4947. and self._previous_gcode_state != "RUNNING"
  4948. and current_file
  4949. and not self._was_running # Prevent duplicates when resuming from PAUSE
  4950. )
  4951. # Also detect if file changed while running (new print started)
  4952. is_file_change = (
  4953. self.state.state == "RUNNING"
  4954. and current_file
  4955. and current_file != self._previous_gcode_file
  4956. and self._previous_gcode_file is not None
  4957. )
  4958. # Track RUNNING state for more robust completion detection
  4959. running_first_observed = False
  4960. if self.state.state == "RUNNING" and current_file:
  4961. if not self._was_running:
  4962. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  4963. # Check if timelapse was enabled in the same message (xcam parsed before this)
  4964. if self.state.timelapse:
  4965. self._timelapse_during_print = True
  4966. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  4967. # Mark this as the first RUNNING observation of the session.
  4968. # If is_new_print also fires below, on_print_start handles
  4969. # baseline capture and we suppress on_print_running_observed
  4970. # to avoid double-capture. If is_new_print does NOT fire
  4971. # (Bambuddy started mid-print — the #1304 guard suppressed
  4972. # it), main.py needs this hook to catch the restart-recovery
  4973. # case (#1485 follow-up).
  4974. running_first_observed = True
  4975. self._was_running = True
  4976. self._completion_triggered = False
  4977. if is_new_print or is_file_change:
  4978. # Clear any old HMS errors when a new print starts
  4979. self.state.hms_errors = []
  4980. # Reset layer tracking for new print (needed for layer-based timelapse)
  4981. self.state.layer_num = 0
  4982. # Reset total_layers so the previous print's value can't bleed into
  4983. # this print's usage-tracker split (#1771 follow-on to the
  4984. # preservation guard at the `total_layer_num` parse above — that
  4985. # guard ignores firmware-reset 0s, so the explicit reset has to
  4986. # happen here instead).
  4987. #
  4988. # #2702: reset to *this frame's* total, not to 0. The frame that
  4989. # trips the new-print detection can carry the new print's
  4990. # `total_layer_num` as well — the parse above has already applied
  4991. # it, and zeroing unconditionally threw it away. That looked
  4992. # harmless but is not recoverable: Bambu firmware sends only
  4993. # changed fields, so the printer never offers the total again, and
  4994. # the print runs to completion at `n/0` in the UI, in
  4995. # `{total_layers}` notifications, and as the usage-split
  4996. # denominator. The value only reappears on the next full pushall
  4997. # (reconnect / Force Refresh), which is why the symptom looked
  4998. # random and why a *stable* connection made it worse.
  4999. self.state.total_layers = total_from_this_frame
  5000. # If the starting frame brought no total, ask for one. Costs one
  5001. # MQTT message per print and covers the ordering where the printer
  5002. # published the total a frame or two before the state flip.
  5003. self._total_layers_refresh_armed = not total_from_this_frame
  5004. if self._total_layers_refresh_armed:
  5005. self._request_push_all()
  5006. # Reset completion tracking for new print
  5007. self._was_running = True
  5008. self._completion_triggered = False
  5009. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5010. self._finish_photo_captured = False
  5011. # #2547: rearm the end-of-print telemetry probe for the new print
  5012. self._eop_probe_armed = True
  5013. self._eop_probe_open = False
  5014. self._eop_probe_frames = 0
  5015. self._eop_probe_last = {}
  5016. # Reset last valid progress/layer for usage tracking
  5017. self._last_valid_progress = 0.0
  5018. self._last_valid_layer_num = 0
  5019. # Clear and seed tray change log for mid-print usage splitting
  5020. self.state.tray_change_log.clear()
  5021. tn = self.state.tray_now
  5022. if (
  5023. (0 <= tn <= 15)
  5024. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  5025. or (128 <= tn <= 135)
  5026. or tn == 254
  5027. ):
  5028. self.state.tray_change_log.append((tn, 0))
  5029. # Initialize timelapse tracking based on current state
  5030. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5031. # so self.state.timelapse may already be set from this message.
  5032. # We preserve that value instead of blindly resetting to False.
  5033. if self.state.timelapse:
  5034. self._timelapse_during_print = True
  5035. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5036. else:
  5037. self._timelapse_during_print = False
  5038. if (is_new_print or is_file_change) and self.on_print_start:
  5039. logger.info(
  5040. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5041. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5042. )
  5043. self.on_print_start(
  5044. {
  5045. "filename": current_file,
  5046. "subtask_name": self.state.subtask_name,
  5047. "remaining_time": self.state.remaining_time * 60
  5048. if self.state.remaining_time > 0
  5049. else None, # Convert minutes to seconds
  5050. "raw_data": data,
  5051. "ams_mapping": self._captured_ams_mapping,
  5052. }
  5053. )
  5054. elif running_first_observed and self.on_print_running_observed:
  5055. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5056. # print, so the #1304 first-push guard suppressed on_print_start,
  5057. # but we still need main.py to capture a fresh timelapse baseline
  5058. # before the printer uploads the in-flight MP4. Same payload
  5059. # shape as on_print_start so the consumer can reuse fields.
  5060. logger.info(
  5061. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5062. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5063. )
  5064. self.on_print_running_observed(
  5065. {
  5066. "filename": current_file,
  5067. "subtask_name": self.state.subtask_name,
  5068. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5069. "raw_data": data,
  5070. "ams_mapping": self._captured_ams_mapping,
  5071. }
  5072. )
  5073. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5074. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5075. # This handles cases where server restarts during a print
  5076. should_trigger_completion = (
  5077. self.state.state in ("FINISH", "FAILED")
  5078. and not self._completion_triggered
  5079. and self.on_print_complete
  5080. and (
  5081. self._previous_gcode_state == "RUNNING" # Normal transition
  5082. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5083. # Pre-print failure (#1111): printer rejected the job during setup
  5084. # — wrong nozzle size, AMS error, etc. The print never reaches
  5085. # RUNNING, so without this branch neither the RUNNING check nor
  5086. # _was_running match and the queue item stays stuck at "printing".
  5087. # Restricted to FAILED from pre-print states so a stale FAILED on
  5088. # first connection (prev=None) still can't accidentally fire.
  5089. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5090. )
  5091. )
  5092. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5093. if (
  5094. self.state.state == "IDLE"
  5095. and self._previous_gcode_state == "RUNNING"
  5096. and not self._completion_triggered
  5097. and self.on_print_complete
  5098. ):
  5099. should_trigger_completion = True
  5100. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5101. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5102. if (
  5103. not should_trigger_completion
  5104. and self.state.state in ("FINISH", "FAILED")
  5105. and self._previous_gcode_state != self.state.state
  5106. ):
  5107. logger.info(
  5108. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5109. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5110. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5111. )
  5112. # Mark as triggered so state is clean for the next print cycle
  5113. self._completion_triggered = True
  5114. if should_trigger_completion:
  5115. if self.state.state == "FINISH":
  5116. status = "completed"
  5117. elif self.state.state == "FAILED":
  5118. status = "failed"
  5119. else:
  5120. status = "aborted"
  5121. logger.info(
  5122. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5123. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5124. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5125. f"timelapse_during_print: {self._timelapse_during_print}"
  5126. )
  5127. timelapse_was_active = self._timelapse_during_print
  5128. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5129. # external-spool-only, HMS halt, or firmware variant that skips
  5130. # the unload phase) fire the finish-photo moment now. Bed has
  5131. # already dropped, framing is worse, but we still capture.
  5132. # Only on successful completion — aborted/failed prints don't
  5133. # produce a meaningful finish photo.
  5134. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5135. self._finish_photo_captured = True
  5136. logger.info(
  5137. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5138. f"stage-22 never fired; capturing at FINISH-state transition"
  5139. )
  5140. self.on_finish_photo_moment(
  5141. {
  5142. "trigger": "finish_state",
  5143. "filename": self._previous_gcode_file or current_file,
  5144. "subtask_name": self.state.subtask_name,
  5145. "timelapse_was_active": timelapse_was_active,
  5146. }
  5147. )
  5148. self._completion_triggered = True
  5149. self._was_running = False
  5150. self._timelapse_during_print = False # Reset for next print
  5151. # Include HMS errors for failure reason detection
  5152. hms_errors_data = (
  5153. [
  5154. {
  5155. "code": e.code,
  5156. "attr": e.attr,
  5157. "module": e.module,
  5158. "severity": e.severity,
  5159. # Carried so the queue's failure reason quotes the same
  5160. # sentence the status response and the broadcast do,
  5161. # rather than resolving the code a fourth time (#2926).
  5162. "description": e.description,
  5163. }
  5164. for e in self.state.hms_errors
  5165. ]
  5166. if self.state.hms_errors
  5167. else []
  5168. )
  5169. self.on_print_complete(
  5170. {
  5171. "status": status,
  5172. "filename": self._previous_gcode_file or current_file,
  5173. "subtask_name": self.state.subtask_name,
  5174. "raw_data": data,
  5175. "timelapse_was_active": timelapse_was_active,
  5176. "hms_errors": hms_errors_data,
  5177. "ams_mapping": self._captured_ams_mapping,
  5178. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5179. "last_progress": self._last_valid_progress,
  5180. "last_layer_num": self._last_valid_layer_num,
  5181. }
  5182. )
  5183. self._captured_ams_mapping = None
  5184. # Same lifecycle as the mapping above: it described *this* print.
  5185. # Leaving it set would hand the next print an answer about where a
  5186. # different file went, and a stale "internal storage" reading costs
  5187. # an archive that the FTPS sweep would have found (#2780).
  5188. self.state.current_project_url = None
  5189. self._previous_gcode_state = self.state.state
  5190. if current_file:
  5191. self._previous_gcode_file = current_file
  5192. if self.on_state_change:
  5193. self.on_state_change(self.state)
  5194. def _request_push_all(self):
  5195. """Request full status update from printer."""
  5196. if self._client:
  5197. message = {"pushing": {"command": "pushall"}}
  5198. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5199. def _probe_developer_mode(self):
  5200. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5201. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5202. For these, we detect developer mode by sending a harmless command and
  5203. checking whether the printer accepts or rejects it:
  5204. - result="success" → developer mode ON (commands accepted)
  5205. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5206. The probe re-sends the current external slot configuration so it's a no-op
  5207. when the command succeeds. If there's no external slot data yet, we send a
  5208. reset (empty filament) which is also safe.
  5209. """
  5210. if not self._client or not self.state.connected:
  5211. return
  5212. self._dev_mode_probed = True
  5213. self._dev_mode_probe_time = time.monotonic()
  5214. self._sequence_id += 1
  5215. seq = str(self._sequence_id)
  5216. self._dev_mode_probe_seq = seq
  5217. # Build probe command: re-send current external slot config (no-op on success)
  5218. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5219. current = vt_tray[0] if vt_tray else {}
  5220. command = {
  5221. "print": {
  5222. "command": "ams_filament_setting",
  5223. "ams_id": 255,
  5224. "tray_id": 0,
  5225. "slot_id": 0,
  5226. "tray_info_idx": current.get("tray_info_idx", ""),
  5227. "tray_type": current.get("tray_type", ""),
  5228. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5229. "tray_color": current.get("tray_color", "00000000"),
  5230. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5231. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5232. "sequence_id": seq,
  5233. }
  5234. }
  5235. setting_id = current.get("setting_id")
  5236. if setting_id:
  5237. command["print"]["setting_id"] = setting_id
  5238. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5239. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5240. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5241. """Reconcile developer_mode with the printer's own command-verification verdict.
  5242. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5243. control commands are being refused, so it outranks the probe in both
  5244. directions:
  5245. * present → developer_mode is definitively False, whatever the probe
  5246. concluded. The probe can only read the response to its own
  5247. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5248. instead, so the probe answers ENABLED while every print silently dies
  5249. (#2732).
  5250. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5251. probe, so a user who enables Developer Mode and restarts the printer
  5252. isn't stuck behind a verdict nothing would ever revisit.
  5253. A False that came from the probe or the ``fun`` bit is left alone — this
  5254. only ever unwinds its own latch.
  5255. """
  5256. if verify_failed:
  5257. if not self._dev_mode_from_hms:
  5258. logger.warning(
  5259. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5260. "rejecting control commands, so prints, temperature changes and filament "
  5261. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5262. self.serial_number,
  5263. HMS_MQTT_VERIFY_FAILED,
  5264. )
  5265. self._dev_mode_from_hms = True
  5266. self.state.developer_mode = False
  5267. return
  5268. if not self._dev_mode_from_hms:
  5269. return
  5270. logger.info(
  5271. "[%s] HMS %s cleared — re-probing developer mode",
  5272. self.serial_number,
  5273. HMS_MQTT_VERIFY_FAILED,
  5274. )
  5275. self._dev_mode_from_hms = False
  5276. self.state.developer_mode = None
  5277. self._dev_mode_probed = False
  5278. self._dev_mode_needs_probe = False
  5279. def _handle_dev_mode_probe_response(self, data: dict):
  5280. """Handle response to the developer mode probe command.
  5281. Sets developer_mode based on whether the printer accepted or rejected the command.
  5282. Three outcomes, not two. An explicit ``success`` proves commands are
  5283. accepted and an explicit verify-failure proves they are not, but anything
  5284. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5285. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5286. ``result`` at all, while refusing every control command and reporting
  5287. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5288. is what put ``developer_mode: pass`` in the support bundle of a printer
  5289. that had not accepted a command all day (#2732). Leaving it unknown makes
  5290. the connection diagnostic report ``skip``, which is the honest answer.
  5291. """
  5292. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5293. self._dev_mode_probe_failures = 0 # Reset on any response
  5294. result = data.get("result", "")
  5295. reason = data.get("reason", "")
  5296. if result == "failed" and "verify failed" in reason:
  5297. self.state.developer_mode = False
  5298. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5299. elif str(result).lower() == "success":
  5300. self.state.developer_mode = True
  5301. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5302. else:
  5303. # An HMS verdict already recorded here is real evidence; don't let an
  5304. # inconclusive probe response wipe it back to unknown.
  5305. if not self._dev_mode_from_hms:
  5306. self.state.developer_mode = None
  5307. logger.info(
  5308. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5309. "the printer neither confirmed nor refused the command",
  5310. self.serial_number,
  5311. result,
  5312. reason,
  5313. )
  5314. if self.on_state_change:
  5315. self.on_state_change(self.state)
  5316. def _request_version(self):
  5317. """Request firmware version info from printer."""
  5318. if self._client:
  5319. self._sequence_id += 1
  5320. message = {
  5321. "info": {
  5322. "sequence_id": str(self._sequence_id),
  5323. "command": "get_version",
  5324. }
  5325. }
  5326. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5327. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5328. def request_status_update(self) -> bool:
  5329. """Request a full status update from the printer (public API).
  5330. Sends both pushall and get_accessories commands to refresh all data
  5331. including nozzle hardware info.
  5332. Returns:
  5333. True if the request was sent, False if not connected.
  5334. """
  5335. if not self._client or not self.state.connected:
  5336. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5337. return False
  5338. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  5339. self._request_push_all()
  5340. # Note: get_accessories returns stale nozzle data on H2D.
  5341. # The correct nozzle data comes from push_status response.
  5342. return True
  5343. def _request_accessories(self):
  5344. """Request accessories info (nozzle type, etc.) from printer."""
  5345. if self._client:
  5346. self._sequence_id += 1
  5347. message = {
  5348. "system": {
  5349. "sequence_id": str(self._sequence_id),
  5350. "command": "get_accessories",
  5351. "accessory_type": "none",
  5352. }
  5353. }
  5354. logger.debug("[%s] Requesting accessories info", self.serial_number)
  5355. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5356. def _prime_kprofile_request(self):
  5357. """Send a priming K-profile request on connect.
  5358. Bambu printers often ignore the first K-profile request after connection,
  5359. so we send a dummy request on connect to 'prime' the system.
  5360. """
  5361. if self._client:
  5362. self._sequence_id += 1
  5363. command = {
  5364. "print": {
  5365. "command": "extrusion_cali_get",
  5366. "filament_id": "",
  5367. "nozzle_diameter": "0.4",
  5368. "sequence_id": str(self._sequence_id),
  5369. }
  5370. }
  5371. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  5372. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5373. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  5374. """Connect to the printer MQTT broker.
  5375. Args:
  5376. loop: The asyncio event loop to use for thread-safe callbacks.
  5377. If not provided, will try to get the running loop.
  5378. """
  5379. self._loop = loop
  5380. BambuMQTTClient._client_instance_counter += 1
  5381. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  5382. self._client = mqtt.Client(
  5383. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  5384. client_id=client_id,
  5385. protocol=mqtt.MQTTv311,
  5386. )
  5387. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  5388. # tracking (#1164). The default ceiling of 20 wedges sessions after
  5389. # ~16-20 cumulative commands; lifting it well above any realistic
  5390. # session count keeps QoS=1 working without changing wire-protocol
  5391. # behaviour across printer models.
  5392. self._client.max_inflight_messages_set(1000)
  5393. self._client.username_pw_set("bblp", self.access_code)
  5394. self._client.on_connect = self._on_connect
  5395. self._client.on_disconnect = self._on_disconnect
  5396. self._client.on_subscribe = self._on_subscribe
  5397. self._client.on_message = self._on_message
  5398. # TLS setup - Bambu uses self-signed certs
  5399. ssl_context = ssl.create_default_context()
  5400. ssl_context.check_hostname = False
  5401. ssl_context.verify_mode = ssl.CERT_NONE
  5402. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  5403. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  5404. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  5405. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  5406. # bare-metal installs whose build allows TLS 1.0.
  5407. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  5408. self._client.tls_set_context(ssl_context)
  5409. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  5410. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  5411. # Keepalive: paho sends PINGREQs at this interval, broker considers
  5412. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  5413. # real network loss (45s), not so aggressive that transient hiccups
  5414. # trigger false disconnects. Stale detection (60s no messages) handles
  5415. # the P1S/P1P firmware bug where the broker stops publishing but the
  5416. # TCP connection stays alive.
  5417. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  5418. self._client.loop_start()
  5419. def start_print(
  5420. self,
  5421. filename: str,
  5422. plate_id: int = 1,
  5423. ams_mapping: list[int] | None = None,
  5424. bed_levelling: str = "auto",
  5425. flow_cali: str = "auto",
  5426. vibration_cali: bool = True,
  5427. layer_inspect: bool = False,
  5428. timelapse: bool = False,
  5429. use_ams: bool = True,
  5430. nozzle_offset_cali: str = "auto",
  5431. nozzle_mapping: str | None = None,
  5432. nozzle_slot_extruders: str | None = None,
  5433. ):
  5434. """Start a print job on the printer.
  5435. The file should already be uploaded to the printer's root directory via FTP.
  5436. Args:
  5437. filename: Name of the uploaded file
  5438. plate_id: Plate number to print (default 1)
  5439. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  5440. Global tray ID = (ams_id * 4) + slot_id, external = 254
  5441. timelapse: Record timelapse video
  5442. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  5443. if the bed was levelled recently, matching BambuStudio).
  5444. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  5445. vibration_cali: Vibration compensation calibration
  5446. layer_inspect: First layer AI inspection
  5447. use_ams: Use AMS for automatic filament changes
  5448. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  5449. (dual-nozzle printers only — silently ignored on single-nozzle).
  5450. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  5451. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  5452. AND the printer is dual-nozzle, parsed and injected as the
  5453. `nozzle_mapping` array on the dispatched project_file so the
  5454. firmware honours the user's slicer pick instead of falling
  5455. back to "last matching nozzle" auto-pick. Silently ignored
  5456. on single-nozzle printers.
  5457. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  5458. MQTT extruder indices, derived from the 3MF when no
  5459. BambuStudio capture exists (#2800). Consulted only on
  5460. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  5461. not already supply one; resolved here into physical rack
  5462. positions using the live `device.nozzle` state. When it
  5463. cannot be resolved the field is omitted and the firmware
  5464. picks, as it did before this existed.
  5465. Returns True when the start command was published, False otherwise
  5466. (not connected, or the printer is already busy — see the run-state
  5467. guard below).
  5468. """
  5469. # Never dispatch project_file to a printer that is not idle (#2598).
  5470. # This is the single publish choke point for every dispatch path — the
  5471. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  5472. # forwarded job all funnel through here — so one guard covers them all.
  5473. # The firmware rejects a start while busy with 0500_4004 ("Device is
  5474. # busy and cannot start a new task"), and on an A1 mini that error
  5475. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  5476. # start targets; only the active-print states are refused. (A
  5477. # transport-level QoS-1 replay on reconnect would bypass this guard,
  5478. # but the dispatch/watchdog reconnect path hard-resets the client with a
  5479. # fresh client_id, so paho has no inflight project_file to replay there.)
  5480. if self.state.state in _ACTIVE_PRINT_STATES:
  5481. logger.warning(
  5482. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  5483. self.serial_number,
  5484. self.state.state,
  5485. filename,
  5486. )
  5487. return False
  5488. if self._client and self.state.connected:
  5489. # Bambu print command format — matches Bambu Studio's format.
  5490. # The calibration/leveling fields (timelapse, bed_leveling,
  5491. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  5492. # every model. An earlier revision integer-encoded them for the H2
  5493. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  5494. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  5495. # sends plain booleans, and the integer encoding made the H2S
  5496. # silently skip flow-dynamics calibration (#1478). use_ams is the
  5497. # one field that genuinely must stay boolean: H2D Pro firmware
  5498. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  5499. # what actually caused the wrong-extruder routing behind #1386.
  5500. # Dual-nozzle routing for external spool (254 = deputy/left,
  5501. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  5502. # H2 firmware family but is single-nozzle, despite sharing serial
  5503. # prefix "094" with H2D. Prefer runtime detection from
  5504. # device.extruder.info (set in _handle_push_status); fall back to
  5505. # model name for the brief window after connect before push data
  5506. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  5507. # as the primary signal.
  5508. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  5509. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  5510. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  5511. ams_mapping2 = []
  5512. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  5513. # ams_mapping and relies on ams_mapping2 for external spool details.
  5514. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  5515. # with 0700_8012 "Failed to get AMS mapping table".
  5516. flat_ams_mapping = []
  5517. if ams_mapping is not None:
  5518. for tray_id in ams_mapping:
  5519. # Ensure tray_id is an integer (may be string from JSON)
  5520. tray_id = int(tray_id) if tray_id is not None else -1
  5521. if tray_id == -1:
  5522. # Unmapped filament slot
  5523. flat_ams_mapping.append(-1)
  5524. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  5525. elif tray_id >= 254:
  5526. # External/virtual spool. BambuStudio convention:
  5527. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  5528. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  5529. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  5530. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  5531. # for external spool, but BambuStudio always sends ams_id=255
  5532. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  5533. # firmware to target AMS tray 0 instead of external spool, leading
  5534. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  5535. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  5536. flat_ams_mapping.append(-1)
  5537. ext_ams_id = tray_id if is_dual_nozzle else 255
  5538. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  5539. elif tray_id >= 128:
  5540. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  5541. flat_ams_mapping.append(tray_id)
  5542. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  5543. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  5544. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  5545. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  5546. # — both CONFIRMED against the firmware's own mapping
  5547. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  5548. _wire_ams, _wire_slot, _ = _a2l
  5549. flat_ams_mapping.append(_wire_slot)
  5550. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  5551. else:
  5552. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  5553. ams_id = tray_id // 4
  5554. slot_id = tray_id % 4
  5555. flat_ams_mapping.append(tray_id)
  5556. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  5557. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  5558. # printers — the mapping is authoritative about whether this print
  5559. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  5560. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  5561. # H2S falls through here now (#1386): it is single-nozzle and was
  5562. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  5563. # without an AMS attached.
  5564. #
  5565. # Two symmetric corrections:
  5566. #
  5567. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  5568. # use_ams=True even if it arrived False. A print sent to a Virtual
  5569. # Printer is sliced against the VP, which advertises no AMS, so the
  5570. # slicer sends use_ams=false and that gets stamped on the queue item
  5571. # — but at dispatch the scheduler colour-matches a real printer and
  5572. # resolves a real AMS slot. Without this, the stale False reaches the
  5573. # printer, which ignores the mapped slot and aborts at layer 0 on the
  5574. # empty external spool ("not enough filament"). Diagnosed by
  5575. # @Sawtaytoes (#2595, PR #2596).
  5576. #
  5577. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  5578. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  5579. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  5580. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  5581. # status-load race that persisted [-1] (#2589) — and treating it as
  5582. # external silently started the print against an empty feed. A genuine
  5583. # external selection is >=254; unresolved is -1; a loaded tray is
  5584. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  5585. # (or is recomputed upstream) instead of silently going external, and
  5586. # never gets force-enabled by (a) either.
  5587. if ams_mapping and not is_dual_nozzle:
  5588. has_real_tray = any(t is not None and 0 <= int(t) <= 253 for t in ams_mapping)
  5589. all_external = all(t is None or int(t) >= 254 for t in ams_mapping)
  5590. if has_real_tray and not use_ams:
  5591. use_ams = True
  5592. logger.info(
  5593. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  5594. self.serial_number,
  5595. )
  5596. elif use_ams and all_external:
  5597. use_ams = False
  5598. logger.info(
  5599. "[%s] All filament slots use external spool — setting use_ams=False",
  5600. self.serial_number,
  5601. )
  5602. # Unique per-submission identity fields. Hardcoded "0" values caused
  5603. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  5604. # continuations of the same job: the printer reuses gcode_start_time
  5605. # from the prior print with task_id=0, so observers latch onto a stale
  5606. # timestamp and report compounding durations on repeat replays (#1011).
  5607. # BambuStudio mints fresh IDs per submission; matching that behavior
  5608. # makes the printer emit a clean state-transition for each job.
  5609. # md5 is left empty — firmware historically accepts "" as "skip
  5610. # validation" (unlike Studio, we don't have the file's real md5 here
  5611. # without re-reading the upload, and sending a synthetic wrong digest
  5612. # risks activation of md5 verification on some firmwares).
  5613. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  5614. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  5615. # overflows and every submission ends up with the same task_id from
  5616. # the printer's perspective — the printer then treats a fresh dispatch
  5617. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  5618. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  5619. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  5620. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  5621. # Remember it so on_print_start can persist a restart-stable id on
  5622. # the archive even before the printer echoes subtask_id back (#1485).
  5623. self.last_dispatch_subtask_id = submission_id
  5624. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  5625. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  5626. # only if it wasn't done recently). The paired bool field is true
  5627. # only for the explicit "on" state — for "auto" the bool is false and
  5628. # the int carries the intent, exactly as BambuStudio's SelectMachine
  5629. # sends it. Unknown values fall back to auto.
  5630. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  5631. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  5632. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  5633. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  5634. command = {
  5635. "print": {
  5636. "sequence_id": "20000",
  5637. "command": "project_file",
  5638. "param": f"Metadata/plate_{plate_id}.gcode",
  5639. "url": f"ftp://{filename}",
  5640. "file": filename,
  5641. "md5": "",
  5642. "bed_type": "auto",
  5643. "timelapse": timelapse,
  5644. # bed_leveling stays a JSON bool (true only for "on") and
  5645. # auto_bed_leveling carries the tri-state int — the exact
  5646. # two-field shape BambuStudio sends. The int must stay a plain
  5647. # number, never quoted (#1478 boolean-family concern applies to
  5648. # the *_cali bools, not these companion ints).
  5649. "bed_leveling": bed_levelling == "on",
  5650. "auto_bed_leveling": bed_level_int,
  5651. "flow_cali": flow_cali == "on",
  5652. "vibration_cali": vibration_cali,
  5653. "layer_inspect": layer_inspect,
  5654. "use_ams": use_ams,
  5655. # No "cfg": it is the printer's device-config bitmask
  5656. # (auto-refill, detect-on-insert, chamber light, ...), not a
  5657. # per-job field — BambuStudio's PrintParams has no such
  5658. # member. We used to send "0"; firmware ignores it, but it
  5659. # comes straight back in the project_file ack (#3040).
  5660. # extrude_cali_flag gates flow-dynamics calibration:
  5661. # 0 = never, 1 = force every print, 2 = auto (run only if the
  5662. # filament wasn't calibrated recently). #1721 saw stage 8
  5663. # ("Calibrating dynamic flow") still queued when we send 2 —
  5664. # that is exactly the auto contract (the printer queues the
  5665. # stage and skips it at runtime if recent), not a bug, so 2 is
  5666. # the right wire value for "auto". off/on remain 0/1.
  5667. "extrude_cali_flag": flow_cali_int,
  5668. "extrude_cali_manual_mode": 0,
  5669. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  5670. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  5671. # again the auto contract, not a failure to suppress.
  5672. # BambuStudio exposes the toggle only for dual-nozzle
  5673. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  5674. # firmware never runs a calibration the head doesn't support.
  5675. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  5676. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  5677. "profile_id": "0",
  5678. "project_id": submission_id,
  5679. "subtask_id": submission_id,
  5680. "task_id": submission_id,
  5681. }
  5682. }
  5683. # P2S-specific parameter adjustments
  5684. # P2S printer doesn't support vibration calibration like X1/P1 series
  5685. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  5686. command["print"]["vibration_cali"] = False
  5687. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  5688. # Add AMS mapping if provided
  5689. if ams_mapping is not None:
  5690. command["print"]["ams_mapping"] = flat_ams_mapping
  5691. command["print"]["ams_mapping2"] = ams_mapping2
  5692. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  5693. # `nozzle_mapping` carries per-filament physical nozzle position
  5694. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  5695. # item; parse here so the wire ships an array, matching
  5696. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  5697. # defensively — single-nozzle firmwares would ignore the field
  5698. # but we err on the side of not emitting unrecognised fields. A
  5699. # parse failure is logged but never blocks the dispatch — the
  5700. # firmware will fall back to its auto-pick path, which is the
  5701. # pre-fix behaviour.
  5702. if is_dual_nozzle and nozzle_mapping:
  5703. try:
  5704. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  5705. except json.JSONDecodeError:
  5706. logger.warning(
  5707. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  5708. "project_file (firmware will auto-pick): %r",
  5709. self.serial_number,
  5710. nozzle_mapping,
  5711. )
  5712. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  5713. # never saw the job, so it can never override a real capture. The
  5714. # queue stores extruder indices per filament slot; the physical
  5715. # rack position they resolve to is only knowable here, because the
  5716. # mounted hotend can change between queueing and dispatch.
  5717. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  5718. try:
  5719. slot_extruders = json.loads(nozzle_slot_extruders)
  5720. except (json.JSONDecodeError, TypeError):
  5721. # TypeError covers a caller handing us the list itself
  5722. # rather than its JSON — the field is opaque by contract,
  5723. # and a print must not die over the difference.
  5724. slot_extruders = None
  5725. logger.warning(
  5726. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  5727. "omitting nozzle_mapping (firmware will auto-pick): %r",
  5728. self.serial_number,
  5729. nozzle_slot_extruders,
  5730. )
  5731. if isinstance(slot_extruders, list):
  5732. rack_nozzle_id = (
  5733. self.state.nozzle_rack_tar_id
  5734. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  5735. else self.state.nozzle_rack_src_id
  5736. )
  5737. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  5738. if resolved is None:
  5739. logger.info(
  5740. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  5741. "omitting nozzle_mapping so the firmware picks",
  5742. self.serial_number,
  5743. slot_extruders,
  5744. self.state.nozzle_rack_tar_id,
  5745. self.state.nozzle_rack_src_id,
  5746. )
  5747. else:
  5748. logger.info(
  5749. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  5750. self.serial_number,
  5751. slot_extruders,
  5752. rack_nozzle_id,
  5753. resolved,
  5754. )
  5755. command["print"]["nozzle_mapping"] = resolved
  5756. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  5757. # Remember this dispatch so its echo on the topic is recognised as
  5758. # ours rather than logged as a slicer's.
  5759. self._own_project_file_key = self._project_file_key(command["print"])
  5760. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5761. # Record what we dispatched so /cover can pick the right plate
  5762. # thumbnail even when the printer's gcode_file echo is just the
  5763. # 3MF filename without a plate path (#1166). Match the same
  5764. # subtask_name shape we send so the comparison in the cover route
  5765. # works against state.subtask_name reflected back via MQTT.
  5766. self.state.dispatched_plate_id = plate_id
  5767. self.state.dispatched_subtask = command["print"]["subtask_name"]
  5768. return True
  5769. else:
  5770. # Log why we couldn't send the command
  5771. if not self._client:
  5772. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  5773. elif not self.state.connected:
  5774. logger.error(
  5775. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  5776. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  5777. )
  5778. return False
  5779. def stop_print(self) -> bool:
  5780. """Stop the current print job."""
  5781. if self._client and self.state.connected:
  5782. command = {"print": {"command": "stop", "sequence_id": "0"}}
  5783. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5784. logger.info("[%s] Sent stop print command", self.serial_number)
  5785. return True
  5786. return False
  5787. def set_xcam_option(
  5788. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  5789. ) -> bool:
  5790. """Set an xcam (AI detection) option on the printer.
  5791. Args:
  5792. module_name: The xcam module to control (e.g., "spaghetti_detector",
  5793. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  5794. enabled: Whether to enable or disable the feature
  5795. print_halt: Whether to halt print on detection (only applies to some detectors)
  5796. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  5797. Returns:
  5798. True if command was sent, False if not connected
  5799. """
  5800. if not self._client or not self.state.connected:
  5801. return False
  5802. # auto_recovery_step_loss uses a different command format (print.print_option)
  5803. if module_name == "auto_recovery_step_loss":
  5804. return self._set_print_option("auto_recovery", enabled)
  5805. self._sequence_id += 1
  5806. # Build the xcam control command (exact OrcaSlicer format)
  5807. # Key findings from OrcaSlicer source:
  5808. # - Uses "xcam" wrapper (not "print")
  5809. # - print_halt is ALWAYS true (legacy protocol requirement)
  5810. # - Both "control" and "enable" are set to the same value
  5811. # - halt_print_sensitivity controls actual halt behavior
  5812. command = {
  5813. "xcam": {
  5814. "command": "xcam_control_set",
  5815. "sequence_id": str(self._sequence_id),
  5816. "module_name": module_name,
  5817. "control": enabled,
  5818. "enable": enabled, # old protocol compatibility
  5819. "print_halt": True, # ALWAYS true per OrcaSlicer
  5820. }
  5821. }
  5822. # Only add sensitivity if not "never_halt"
  5823. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  5824. # The module_name field determines which detector's sensitivity is being set
  5825. if sensitivity and sensitivity != "never_halt":
  5826. command["xcam"]["halt_print_sensitivity"] = sensitivity
  5827. command_json = json.dumps(command)
  5828. self._client.publish(self.topic_publish, command_json, qos=1)
  5829. logger.debug(
  5830. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  5831. )
  5832. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  5833. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  5834. # This prevents stale MQTT data from immediately overwriting our change
  5835. self._xcam_hold_start[module_name] = time.time()
  5836. # Update local state immediately for responsive UI
  5837. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  5838. # When spaghetti_detector sensitivity is changed, pileup also changes
  5839. if module_name == "spaghetti_detector":
  5840. self.state.print_options.spaghetti_detector = enabled
  5841. self.state.print_options.print_halt = print_halt
  5842. if sensitivity and sensitivity != "never_halt":
  5843. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  5844. self.state.print_options.halt_print_sensitivity = sensitivity
  5845. self.state.print_options.pileup_sensitivity = sensitivity
  5846. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  5847. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  5848. elif module_name == "first_layer_inspector":
  5849. self.state.print_options.first_layer_inspector = enabled
  5850. elif module_name == "printing_monitor":
  5851. self.state.print_options.printing_monitor = enabled
  5852. elif module_name == "buildplate_marker_detector":
  5853. self.state.print_options.buildplate_marker_detector = enabled
  5854. elif module_name == "allow_skip_parts":
  5855. self.state.print_options.allow_skip_parts = enabled
  5856. elif module_name == "pileup_detector":
  5857. self.state.print_options.pileup_detector = enabled
  5858. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  5859. elif module_name == "clump_detector":
  5860. self.state.print_options.nozzle_clumping_detector = enabled
  5861. if sensitivity and sensitivity != "never_halt":
  5862. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  5863. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  5864. elif module_name == "airprint_detector":
  5865. self.state.print_options.airprint_detector = enabled
  5866. if sensitivity and sensitivity != "never_halt":
  5867. self.state.print_options.airprint_sensitivity = sensitivity
  5868. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  5869. elif module_name == "auto_recovery_step_loss":
  5870. self.state.print_options.auto_recovery_step_loss = enabled
  5871. return True
  5872. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  5873. """Set a print option using the print.print_option command.
  5874. This is different from xcam_control_set and is used for options like:
  5875. - auto_recovery
  5876. - air_print_detect
  5877. - filament_tangle_detect
  5878. - nozzle_blob_detect
  5879. - sound_enable
  5880. Args:
  5881. option_name: The option to control (e.g., "auto_recovery")
  5882. enabled: Whether to enable or disable the option
  5883. Returns:
  5884. True if command was sent, False if not connected
  5885. """
  5886. if not self._client or not self.state.connected:
  5887. return False
  5888. self._sequence_id += 1
  5889. command = {
  5890. "print": {
  5891. "command": "print_option",
  5892. "sequence_id": str(self._sequence_id),
  5893. option_name: enabled,
  5894. }
  5895. }
  5896. command_json = json.dumps(command)
  5897. self._client.publish(self.topic_publish, command_json, qos=1)
  5898. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  5899. # Set hold timer
  5900. hold_key = f"print_option_{option_name}"
  5901. self._xcam_hold_start[hold_key] = time.time()
  5902. # Update local state immediately
  5903. if option_name == "auto_recovery":
  5904. self.state.print_options.auto_recovery_step_loss = enabled
  5905. elif option_name == "auto_switch_filament":
  5906. self.state.ams_filament_backup = enabled
  5907. return True
  5908. def set_ams_filament_backup(self, enabled: bool) -> bool:
  5909. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  5910. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  5911. shape from H2D capture 2026-06-20.
  5912. """
  5913. return self._set_print_option("auto_switch_filament", enabled)
  5914. def start_calibration(
  5915. self,
  5916. bed_leveling: bool = False,
  5917. vibration: bool = False,
  5918. motor_noise: bool = False,
  5919. nozzle_offset: bool = False,
  5920. high_temp_heatbed: bool = False,
  5921. ) -> bool:
  5922. """Start printer calibration with selected options.
  5923. Args:
  5924. bed_leveling: Run bed leveling calibration
  5925. vibration: Run vibration compensation calibration
  5926. motor_noise: Run motor noise cancellation calibration
  5927. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  5928. high_temp_heatbed: Run high-temperature heatbed calibration
  5929. Returns:
  5930. True if command was sent, False if not connected
  5931. """
  5932. if not self._client or not self.state.connected:
  5933. return False
  5934. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  5935. # Bit 0: xcam_cali (not exposed in UI)
  5936. # Bit 1: bed_leveling
  5937. # Bit 2: vibration
  5938. # Bit 3: motor_noise
  5939. # Bit 4: nozzle_cali
  5940. # Bit 5: bed_cali (high-temp heatbed)
  5941. # Bit 6: clumppos_cali (not exposed in UI)
  5942. option = 0
  5943. if bed_leveling:
  5944. option |= 1 << 1
  5945. if vibration:
  5946. option |= 1 << 2
  5947. if motor_noise:
  5948. option |= 1 << 3
  5949. if nozzle_offset:
  5950. option |= 1 << 4
  5951. if high_temp_heatbed:
  5952. option |= 1 << 5
  5953. if option == 0:
  5954. logger.warning("[%s] No calibration options selected", self.serial_number)
  5955. return False
  5956. self._sequence_id += 1
  5957. command = {
  5958. "print": {
  5959. "command": "calibration",
  5960. "sequence_id": str(self._sequence_id),
  5961. "option": option,
  5962. }
  5963. }
  5964. command_json = json.dumps(command)
  5965. self._client.publish(self.topic_publish, command_json, qos=1)
  5966. logger.info(
  5967. f"[{self.serial_number}] Starting calibration: "
  5968. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  5969. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  5970. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  5971. )
  5972. return True
  5973. def disconnect(self, timeout: float = 0):
  5974. """Disconnect from the printer.
  5975. Waits up to *timeout* for paho to report the disconnect, then lets the
  5976. client go without joining its network thread — the callers are route
  5977. handlers (printer edited, deleted, disconnected by hand) running on the
  5978. asyncio thread, and that join has no bound (#3068)."""
  5979. if self._client:
  5980. old_client = self._client
  5981. self._disconnection_event = threading.Event()
  5982. old_client.disconnect()
  5983. # The callback that sets this fires on paho's thread, so it has to
  5984. # be given its window before retire_paho_client detaches it.
  5985. self._disconnection_event.wait(timeout=timeout)
  5986. self._client = None
  5987. retire_paho_client(old_client, self.serial_number)
  5988. self.state.connected = False
  5989. # Deliberately no on_state_change here. paho's disconnect callback
  5990. # used to land during the join, but `_on_disconnect` suppresses
  5991. # itself for a clean disconnect of a printer that reported within
  5992. # the last 10s -- which is every healthy printer -- so a
  5993. # hand-disconnected printer never broadcast one. Announcing it now
  5994. # would fire the connected→disconnected edge in
  5995. # `on_printer_status_change` and notify the user their printer went
  5996. # offline a minute after they disconnected it on purpose (#1752).
  5997. # The callers drop the client from the manager anyway, so the next
  5998. # status read already shows it gone.
  5999. def send_command(self, command: dict):
  6000. """Send a command to the printer."""
  6001. if self._client and self.state.connected:
  6002. # Log outgoing message if logging is enabled
  6003. if self._logging_enabled:
  6004. self._message_log.append(
  6005. MQTTLogEntry(
  6006. timestamp=datetime.now(timezone.utc).isoformat(),
  6007. topic=self.topic_publish,
  6008. direction="out",
  6009. payload=command,
  6010. )
  6011. )
  6012. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6013. def enable_logging(self, enabled: bool = True):
  6014. """Enable or disable MQTT message logging."""
  6015. self._logging_enabled = enabled
  6016. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6017. def get_logs(self) -> list[MQTTLogEntry]:
  6018. """Get all logged MQTT messages."""
  6019. return list(self._message_log)
  6020. def clear_logs(self):
  6021. """Clear the message log."""
  6022. self._message_log.clear()
  6023. @property
  6024. def logging_enabled(self) -> bool:
  6025. """Check if logging is enabled."""
  6026. return self._logging_enabled
  6027. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6028. """Register a handler invoked for every incoming MQTT message.
  6029. Used by the VP MQTT bridge to republish the printer's report pushes to
  6030. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6031. on paho's network thread and must not block; exceptions are caught.
  6032. """
  6033. if handler not in self._raw_message_handlers:
  6034. self._raw_message_handlers.append(handler)
  6035. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6036. """Unregister a previously-registered raw-message handler."""
  6037. try:
  6038. self._raw_message_handlers.remove(handler)
  6039. except ValueError:
  6040. pass
  6041. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6042. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6043. Used by the VP MQTT bridge to forward slicer-originated commands without
  6044. going through send_command's sequence-id mangling. Returns False if the
  6045. underlying paho client isn't ready.
  6046. """
  6047. if self._client is None:
  6048. return False
  6049. try:
  6050. info = self._client.publish(topic, payload, qos=qos)
  6051. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6052. except Exception:
  6053. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6054. return False
  6055. def send_drying_command(
  6056. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6057. ):
  6058. """Send AMS drying start/stop command.
  6059. Args:
  6060. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6061. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6062. duration: Drying duration in hours
  6063. mode: 1=start, 0=stop
  6064. filament: Filament type string (e.g. "PLA", "PETG")
  6065. rotate_tray: Whether to rotate the spool during drying for even heat
  6066. """
  6067. if not self._client:
  6068. return False
  6069. self._sequence_id += 1
  6070. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6071. # not actually support drying, but keep the translation consistent). The
  6072. # _drying_targets dict below stays keyed by the normalised id so the
  6073. # on_drying_complete callback matches the telemetry.
  6074. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6075. command = {
  6076. "print": {
  6077. "sequence_id": str(self._sequence_id),
  6078. "command": "ams_filament_drying",
  6079. "ams_id": wire_ams_id,
  6080. "temp": temp,
  6081. "cooling_temp": 20 if mode == 1 else 0,
  6082. "duration": duration,
  6083. "humidity": 0,
  6084. "mode": mode,
  6085. "rotate_tray": rotate_tray,
  6086. "filament": filament,
  6087. "close_power_conflict": False,
  6088. }
  6089. }
  6090. # Log the full wire JSON at INFO so support bundles capture exactly
  6091. # what we sent — needed to diagnose silent rejections (#1447) where
  6092. # the printer ACKs the command but never starts/stops drying.
  6093. # Paired with the ams_filament_drying response-payload INFO log so
  6094. # both halves of the conversation land in the bundle by default.
  6095. wire_json = json.dumps(command)
  6096. self._client.publish(self.topic_publish, wire_json, qos=1)
  6097. logger.info(
  6098. "[%s] Sent ams_filament_drying: %s",
  6099. self.serial_number,
  6100. wire_json,
  6101. )
  6102. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6103. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6104. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6105. # say how much of the requested time the firmware actually ran (#2770).
  6106. if mode == 1:
  6107. self._drying_targets[ams_id] = {
  6108. "filament": filament or "",
  6109. "temp": int(temp),
  6110. "duration_hours": int(duration),
  6111. }
  6112. self._drying_stops_sent.discard(ams_id)
  6113. else:
  6114. self._drying_targets.pop(ams_id, None)
  6115. # Remember that this cycle's end is ours, so the cycle-end log
  6116. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6117. # stop always ends the cycle far short of its duration, which is
  6118. # otherwise indistinguishable from the firmware abandoning it.
  6119. self._drying_stops_sent.add(ams_id)
  6120. return True
  6121. @staticmethod
  6122. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6123. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6124. The printer reports ``nozzle_diameter`` **only on the response
  6125. envelope** — the per-filament entries carry just setting_id,
  6126. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6127. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6128. single-nozzle printers regardless of the installed nozzle (#1748),
  6129. which broke the K-Profiles display and, worse, the cali_idx cascade
  6130. in the inventory/Spoolman assign paths that matches on
  6131. nozzle_diameter. Fall back to the envelope value instead, and only
  6132. to "0.4" when the envelope has none either.
  6133. ``or`` rather than a dict default on purpose: it also covers an entry
  6134. that carries the key with an empty value, and stops ``str()`` turning
  6135. a missing envelope value into the literal "None".
  6136. """
  6137. profiles: list[KProfile] = []
  6138. for i, f in enumerate(filaments):
  6139. if not isinstance(f, dict):
  6140. continue
  6141. try:
  6142. profiles.append(
  6143. KProfile(
  6144. # cali_idx is the actual slot/calibration index from the printer
  6145. slot_id=f.get("cali_idx", i),
  6146. extruder_id=int(f.get("extruder_id", 0)),
  6147. nozzle_id=str(f.get("nozzle_id", "")),
  6148. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6149. filament_id=str(f.get("filament_id", "")),
  6150. name=str(f.get("name", "")),
  6151. k_value=str(f.get("k_value", "0.000000")),
  6152. n_coef=str(f.get("n_coef", "0.000000")),
  6153. ams_id=int(f.get("ams_id", 0)),
  6154. tray_id=int(f.get("tray_id", -1)),
  6155. setting_id=f.get("setting_id"),
  6156. )
  6157. )
  6158. except (ValueError, TypeError) as e:
  6159. # Skip malformed entries; the remaining profiles stay usable.
  6160. # Unsolicited broadcasts arrive constantly, so only a response
  6161. # someone is actually waiting on is worth a warning.
  6162. if log_errors:
  6163. logger.warning("Failed to parse K-profile: %s", e)
  6164. else:
  6165. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6166. return profiles
  6167. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6168. """File one calibration-table response under its nozzle diameter.
  6169. ``response_nozzle`` names the table the printer just sent, so that
  6170. bucket is replaced wholesale and every other one is left alone. When
  6171. the envelope carries no diameter, fall back to the diameters the parsed
  6172. profiles claim for themselves — and if there are none of those either,
  6173. keep what we have rather than dropping a table we cannot attribute.
  6174. ``state.kprofiles`` stays a flat list because that is what its readers
  6175. expect; the three assign paths already filter it by ``nozzle_diameter``
  6176. and were quietly finding nothing whenever the last response happened to
  6177. be for a different nozzle.
  6178. """
  6179. buckets: dict[str, list] = {}
  6180. if response_nozzle:
  6181. buckets[str(response_nozzle)] = list(profiles)
  6182. else:
  6183. for profile in profiles:
  6184. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6185. if not buckets:
  6186. return
  6187. self._kprofiles_by_nozzle.update(buckets)
  6188. self.state.kprofiles = [
  6189. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6190. ]
  6191. def _handle_kprofile_response(self, data: dict):
  6192. """Handle K-profile response from printer."""
  6193. response_nozzle = data.get("nozzle_diameter")
  6194. response_seq_id = str(data.get("sequence_id", ""))
  6195. filaments = data.get("filaments", [])
  6196. # Snapshot the map: the asyncio thread adds and removes entries while
  6197. # this MQTT callback thread walks it.
  6198. pending = dict(self._pending_kprofile_requests)
  6199. request = pending.get(response_seq_id)
  6200. if request is None and pending:
  6201. # Firmware that doesn't echo our sequence_id still has to be
  6202. # served, so fall back to the pre-#1748 rule of matching on the
  6203. # nozzle size. Only requests still waiting are eligible, and the
  6204. # sequence_id lookup above has already claimed any response that
  6205. # identifies itself, so this can no longer hand request A's
  6206. # answer to request B when both are in flight.
  6207. request = next(
  6208. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6209. None,
  6210. )
  6211. if pending:
  6212. logger.info(
  6213. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6214. self.serial_number,
  6215. response_nozzle,
  6216. response_seq_id or "?",
  6217. len(filaments),
  6218. request is not None,
  6219. )
  6220. if request is None and pending:
  6221. # A request is outstanding and this isn't its answer. The printer
  6222. # broadcasts extrusion_cali_get unsolicited, so letting this
  6223. # through would replace state.kprofiles with another nozzle's
  6224. # profiles while the caller is still waiting.
  6225. logger.debug(
  6226. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6227. self.serial_number,
  6228. response_nozzle,
  6229. response_seq_id or "?",
  6230. )
  6231. return
  6232. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6233. self._store_kprofiles(profiles, response_nozzle)
  6234. if request is None:
  6235. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6236. # nobody to wake. Worth a line — this is the printer answering
  6237. # somebody else (BambuStudio queries the same report topic), and
  6238. # until it was bucketed by nozzle it was also the quietest way for
  6239. # the AMS card's K values to change underneath us.
  6240. logger.debug(
  6241. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6242. self.serial_number,
  6243. response_nozzle or "?",
  6244. len(profiles),
  6245. )
  6246. return
  6247. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6248. request["profiles"] = profiles
  6249. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6250. # in a different thread than the event loop.
  6251. event = request["event"]
  6252. if self._loop and self._loop.is_running():
  6253. self._loop.call_soon_threadsafe(event.set)
  6254. else:
  6255. # Fallback for when loop is not available
  6256. event.set()
  6257. async def get_kprofiles(
  6258. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6259. ) -> list[KProfile]:
  6260. """Request K-profiles from the printer with retry logic.
  6261. Bambu printers sometimes ignore the first K-profile request, so we
  6262. implement retry logic to ensure reliable retrieval.
  6263. Args:
  6264. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6265. timeout: Timeout in seconds to wait for each response attempt
  6266. max_retries: Maximum number of retry attempts
  6267. Returns:
  6268. List of KProfile objects
  6269. """
  6270. if not self._client or not self.state.connected:
  6271. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6272. return []
  6273. # Capture current event loop for thread-safe callback
  6274. try:
  6275. self._loop = asyncio.get_running_loop()
  6276. except RuntimeError:
  6277. logger.warning("[%s] No running event loop", self.serial_number)
  6278. return []
  6279. for attempt in range(max_retries):
  6280. # Register this attempt under its own sequence_id so a concurrent
  6281. # request for a different nozzle size can't consume its response
  6282. # (#1748) — the pending map is keyed by exactly the id we send.
  6283. self._sequence_id += 1
  6284. seq_id = str(self._sequence_id)
  6285. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6286. self._pending_kprofile_requests[seq_id] = request
  6287. # Send the command with nozzle_diameter filter
  6288. command = {
  6289. "print": {
  6290. "command": "extrusion_cali_get",
  6291. "filament_id": "",
  6292. "nozzle_diameter": nozzle_diameter,
  6293. "sequence_id": seq_id,
  6294. }
  6295. }
  6296. logger.info(
  6297. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6298. )
  6299. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6300. # Wait for the response (the handler matches it back to this entry)
  6301. try:
  6302. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6303. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6304. profiles = request["profiles"] or []
  6305. logger.info(
  6306. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6307. )
  6308. return profiles
  6309. except TimeoutError:
  6310. logger.warning(
  6311. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  6312. )
  6313. if attempt < max_retries - 1:
  6314. # Brief delay before retry
  6315. await asyncio.sleep(0.5)
  6316. finally:
  6317. self._pending_kprofile_requests.pop(seq_id, None)
  6318. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  6319. return []
  6320. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  6321. """Publish a K-profile write and arm its ack slot.
  6322. Registration happens before the publish because the printer answers in
  6323. well under a second — measured at 70-150ms — which is comfortably
  6324. before an async caller gets back to awaiting.
  6325. """
  6326. self._pending_cali_acks[seq_id] = None
  6327. try:
  6328. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6329. except Exception:
  6330. self._pending_cali_acks.pop(seq_id, None)
  6331. raise
  6332. return True
  6333. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  6334. """Wait for the printer's verdict on a K-profile write.
  6335. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  6336. explicitly said ``result: "fail"`` — a timeout returns True with a
  6337. detail string, because "no answer" is not evidence of rejection and
  6338. older firmware may not answer at all. Callers that need certainty read
  6339. the calibration table back.
  6340. Polled rather than event-driven on purpose: the ack is filled in by the
  6341. MQTT callback thread, and polling a dict costs one lookup every 50ms
  6342. for at most a few hundred milliseconds, against the cross-thread
  6343. event plumbing it would otherwise take.
  6344. """
  6345. deadline = time.monotonic() + timeout
  6346. try:
  6347. while time.monotonic() < deadline:
  6348. ack = self._pending_cali_acks.get(seq_id)
  6349. if ack is not None:
  6350. result = str(ack.get("result", "")).lower()
  6351. reason = str(ack.get("reason", "") or "")
  6352. if result == "fail":
  6353. return (False, reason or "printer reported failure")
  6354. return (True, reason)
  6355. await asyncio.sleep(0.05)
  6356. finally:
  6357. self._pending_cali_acks.pop(seq_id, None)
  6358. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  6359. return (True, "no acknowledgement from printer")
  6360. def set_kprofile(
  6361. self,
  6362. filament_id: str,
  6363. name: str,
  6364. k_value: str,
  6365. nozzle_diameter: str = "0.4",
  6366. nozzle_id: str = "HS00-0.4",
  6367. extruder_id: int = 0,
  6368. setting_id: str | None = None,
  6369. slot_id: int = 0,
  6370. cali_idx: int | None = None,
  6371. ) -> str | None:
  6372. """Set/update a K-profile on the printer.
  6373. Args:
  6374. filament_id: Bambu filament identifier
  6375. name: Profile name
  6376. k_value: Pressure advance value (e.g., "0.020000")
  6377. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6378. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  6379. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6380. setting_id: Existing setting ID for updates, None for new
  6381. slot_id: Calibration index (cali_idx) for the profile
  6382. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  6383. Returns:
  6384. The sequence_id the command was sent under, so the caller can
  6385. await the printer's verdict via await_cali_ack. None if the
  6386. command could not be sent.
  6387. """
  6388. if not self._client or not self.state.connected:
  6389. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  6390. return None
  6391. self._sequence_id += 1
  6392. seq_id = str(self._sequence_id)
  6393. # Build the filament entry - printer uses cali_idx for profile identification
  6394. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  6395. # For edits, use the provided cali_idx or slot_id
  6396. if cali_idx is not None:
  6397. effective_cali_idx = cali_idx
  6398. else:
  6399. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6400. # Generate a setting_id for new profiles (required by printer)
  6401. # Format: "PF" + 17 random digits
  6402. import random
  6403. if not setting_id and slot_id == 0:
  6404. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6405. filament_entry = {
  6406. "ams_id": 0,
  6407. "cali_idx": effective_cali_idx,
  6408. "extruder_id": extruder_id,
  6409. "filament_id": filament_id,
  6410. "k_value": k_value,
  6411. "n_coef": "0.000000",
  6412. "name": name,
  6413. "nozzle_diameter": nozzle_diameter,
  6414. "nozzle_id": nozzle_id,
  6415. "setting_id": setting_id if setting_id else "",
  6416. # 0, not -1. Single-nozzle firmware validates this field and
  6417. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  6418. # applying the write anyway, so the rejection looked like noise.
  6419. # Measured on an X1C: flipping only this value turns the ack into
  6420. # `success` (#2718). BambuStudio always sends a real tray_id and
  6421. # defaults it to 0 for a manually entered profile.
  6422. "tray_id": 0,
  6423. }
  6424. command = {
  6425. "print": {
  6426. "command": "extrusion_cali_set",
  6427. "filaments": [filament_entry],
  6428. "nozzle_diameter": nozzle_diameter,
  6429. "sequence_id": seq_id,
  6430. }
  6431. }
  6432. command_json = json.dumps(command)
  6433. logger.info(
  6434. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  6435. )
  6436. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  6437. self._publish_cali_write(command, seq_id)
  6438. return seq_id
  6439. def set_kprofiles_batch(
  6440. self,
  6441. profiles: list[dict],
  6442. nozzle_diameter: str = "0.4",
  6443. ) -> str | None:
  6444. """Set multiple K-profiles in a single command (for dual-nozzle).
  6445. Args:
  6446. profiles: List of profile dicts, each with:
  6447. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  6448. nozzle_diameter: Common nozzle diameter for all profiles
  6449. Returns:
  6450. The sequence_id the command was sent under (see set_kprofile),
  6451. or None if it could not be sent.
  6452. """
  6453. if not self._client or not self.state.connected:
  6454. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  6455. return None
  6456. import random
  6457. self._sequence_id += 1
  6458. seq_id = str(self._sequence_id)
  6459. filament_entries = []
  6460. for p in profiles:
  6461. slot_id = p.get("slot_id", 0)
  6462. cali_idx = p.get("cali_idx")
  6463. if cali_idx is not None:
  6464. effective_cali_idx = cali_idx
  6465. else:
  6466. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6467. setting_id = p.get("setting_id")
  6468. if not setting_id and slot_id == 0:
  6469. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6470. filament_entries.append(
  6471. {
  6472. "ams_id": 0,
  6473. "cali_idx": effective_cali_idx,
  6474. "extruder_id": p.get("extruder_id", 0),
  6475. "filament_id": p.get("filament_id", ""),
  6476. "k_value": p.get("k_value", "0.020000"),
  6477. "n_coef": "0.000000",
  6478. "name": p.get("name", ""),
  6479. "nozzle_diameter": nozzle_diameter,
  6480. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  6481. "setting_id": setting_id if setting_id else "",
  6482. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  6483. # single-nozzle firmware even though the write lands (#2718).
  6484. "tray_id": 0,
  6485. }
  6486. )
  6487. command = {
  6488. "print": {
  6489. "command": "extrusion_cali_set",
  6490. "filaments": filament_entries,
  6491. "nozzle_diameter": nozzle_diameter,
  6492. "sequence_id": seq_id,
  6493. }
  6494. }
  6495. command_json = json.dumps(command)
  6496. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  6497. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  6498. self._publish_cali_write(command, seq_id)
  6499. return seq_id
  6500. def delete_kprofile(
  6501. self,
  6502. cali_idx: int,
  6503. filament_id: str,
  6504. nozzle_id: str,
  6505. nozzle_diameter: str = "0.4",
  6506. extruder_id: int = 0,
  6507. setting_id: str | None = None,
  6508. ) -> str | None:
  6509. """Delete a K-profile from the printer.
  6510. Args:
  6511. cali_idx: The calibration index (slot_id) of the profile to delete
  6512. filament_id: Bambu filament identifier
  6513. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  6514. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6515. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6516. setting_id: Unique setting identifier (for X1C series)
  6517. Returns:
  6518. The sequence_id the command was sent under (see set_kprofile),
  6519. or None if it could not be sent.
  6520. """
  6521. if not self._client or not self.state.connected:
  6522. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  6523. return None
  6524. self._sequence_id += 1
  6525. seq_id = str(self._sequence_id)
  6526. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  6527. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  6528. # Prefer runtime detection from device.extruder.info; fall back to
  6529. # model name. H2S is single-nozzle but shares serial prefix "094" with
  6530. # H2D, so a prefix-only check misclassified it (#1386).
  6531. from backend.app.utils.printer_models import is_dual_nozzle_model
  6532. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6533. if is_dual_nozzle:
  6534. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  6535. command = {
  6536. "print": {
  6537. "command": "extrusion_cali_del",
  6538. "sequence_id": seq_id,
  6539. "extruder_id": extruder_id,
  6540. "nozzle_id": nozzle_id,
  6541. "filament_id": filament_id,
  6542. "cali_idx": cali_idx,
  6543. "nozzle_diameter": nozzle_diameter,
  6544. }
  6545. }
  6546. else:
  6547. # X1C/P1/A1 format: include all fields like the set command
  6548. # The delete command structure should match what set uses
  6549. command = {
  6550. "print": {
  6551. "command": "extrusion_cali_del",
  6552. "sequence_id": seq_id,
  6553. "filament_id": filament_id,
  6554. "cali_idx": cali_idx,
  6555. "setting_id": setting_id if setting_id else "",
  6556. "nozzle_diameter": nozzle_diameter,
  6557. "nozzle_id": nozzle_id,
  6558. "extruder_id": extruder_id,
  6559. }
  6560. }
  6561. command_json = json.dumps(command)
  6562. logger.info(
  6563. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  6564. )
  6565. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  6566. # QoS 1 for reliable delivery (at least once)
  6567. self._publish_cali_write(command, seq_id)
  6568. return seq_id
  6569. # =========================================================================
  6570. # Printer Control Commands
  6571. # =========================================================================
  6572. def pause_print(self) -> bool:
  6573. """Pause the current print job."""
  6574. if not self._client or not self.state.connected:
  6575. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  6576. return False
  6577. command = {"print": {"command": "pause", "sequence_id": "0"}}
  6578. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6579. logger.info("[%s] Sent pause print command", self.serial_number)
  6580. return True
  6581. def resume_print(self) -> bool:
  6582. """Resume a paused print job."""
  6583. if not self._client or not self.state.connected:
  6584. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  6585. return False
  6586. command = {"print": {"command": "resume", "sequence_id": "0"}}
  6587. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6588. logger.info("[%s] Sent resume print command", self.serial_number)
  6589. return True
  6590. def clear_hms_errors(self) -> bool:
  6591. """Clear HMS/print errors on the printer and locally."""
  6592. if not self._client or not self.state.connected:
  6593. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  6594. return False
  6595. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  6596. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6597. self.state.hms_errors = []
  6598. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  6599. return True
  6600. def skip_objects(self, object_ids: list[int]) -> bool:
  6601. """Skip specific objects during a print.
  6602. This command tells the printer to skip printing the specified objects.
  6603. The object IDs come from the slice_info.config file in the 3MF.
  6604. Args:
  6605. object_ids: List of identify_id values from slice_info.config
  6606. Returns:
  6607. True if command was sent, False otherwise
  6608. """
  6609. if not self._client or not self.state.connected:
  6610. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  6611. return False
  6612. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  6613. logger.warning(
  6614. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  6615. )
  6616. return False
  6617. if not object_ids:
  6618. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  6619. return False
  6620. # Validate all IDs are integers
  6621. try:
  6622. obj_list = [int(oid) for oid in object_ids]
  6623. except (ValueError, TypeError) as e:
  6624. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  6625. return False
  6626. self._sequence_id += 1
  6627. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  6628. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6629. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  6630. # Track skipped objects in state
  6631. for oid in obj_list:
  6632. if oid not in self.state.skipped_objects:
  6633. self.state.skipped_objects.append(oid)
  6634. return True
  6635. def send_gcode(self, gcode: str) -> bool:
  6636. """Send G-code command(s) to the printer.
  6637. Multiple commands can be separated by newlines.
  6638. Args:
  6639. gcode: G-code command(s) to send
  6640. Returns:
  6641. True if command was sent, False otherwise
  6642. """
  6643. if not self._client or not self.state.connected:
  6644. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  6645. return False
  6646. self._sequence_id += 1
  6647. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  6648. # Use QoS 1 for reliable delivery (at least once)
  6649. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6650. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  6651. return True
  6652. def set_bed_temperature(self, target: int) -> bool:
  6653. """Set the bed target temperature.
  6654. Args:
  6655. target: Target temperature in Celsius (0 to turn off)
  6656. Returns:
  6657. True if command was sent, False otherwise
  6658. """
  6659. return self.send_gcode(f"M140 S{target}")
  6660. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  6661. """Set the nozzle target temperature.
  6662. Args:
  6663. target: Target temperature in Celsius (0 to turn off)
  6664. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  6665. Returns:
  6666. True if command was sent, False otherwise
  6667. """
  6668. # Use M104 for non-blocking
  6669. # Always use T parameter for H2D compatibility
  6670. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  6671. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  6672. # Track it locally so we can display it correctly
  6673. if result and nozzle == 1:
  6674. self.state.temperatures["nozzle_target"] = float(target)
  6675. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  6676. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  6677. return result
  6678. def set_chamber_temperature(self, target: int) -> bool:
  6679. """Set the chamber target temperature.
  6680. Args:
  6681. target: Target temperature in Celsius (0 to turn off heating)
  6682. Returns:
  6683. True if command was sent, False otherwise
  6684. """
  6685. # M141 sets chamber temperature
  6686. result = self.send_gcode(f"M141 S{target}")
  6687. # Track chamber target locally (MQTT reports encoded values that need filtering)
  6688. if result:
  6689. self.state.temperatures["chamber_target"] = float(target)
  6690. self.state.temperatures["_chamber_target_set_time"] = time.time()
  6691. # Update heating state immediately based on new target
  6692. current_temp = self.state.temperatures.get("chamber", 0)
  6693. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  6694. logger.info(
  6695. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  6696. )
  6697. return result
  6698. def set_print_speed(self, mode: int) -> bool:
  6699. """Set the print speed mode.
  6700. Args:
  6701. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  6702. Returns:
  6703. True if command was sent, False otherwise
  6704. """
  6705. if not self._client or not self.state.connected:
  6706. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  6707. return False
  6708. if mode not in (1, 2, 3, 4):
  6709. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  6710. return False
  6711. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  6712. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6713. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  6714. return True
  6715. def set_fan_speed(self, fan: int, speed: int) -> bool:
  6716. """Set fan speed.
  6717. Args:
  6718. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=left auxiliary).
  6719. Index 10 is the optional left auxiliary part cooling fan on P2S/X2D
  6720. (airduct part id 10); Bambu's official machine profiles drive it with
  6721. "M106 P10" in start/layer-change gcode.
  6722. speed: Speed 0-255 (0=off, 255=full)
  6723. Returns:
  6724. True if command was sent, False otherwise
  6725. """
  6726. if fan not in (1, 2, 3, 10):
  6727. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  6728. return False
  6729. speed = max(0, min(255, speed)) # Clamp to 0-255
  6730. return self.send_gcode(f"M106 P{fan} S{speed}")
  6731. def set_part_fan(self, speed: int) -> bool:
  6732. """Set part cooling fan speed (0-255)."""
  6733. return self.set_fan_speed(1, speed)
  6734. def set_aux_fan(self, speed: int) -> bool:
  6735. """Set auxiliary fan speed (0-255)."""
  6736. return self.set_fan_speed(2, speed)
  6737. def set_chamber_fan(self, speed: int) -> bool:
  6738. """Set chamber fan speed (0-255)."""
  6739. return self.set_fan_speed(3, speed)
  6740. def set_left_aux_fan(self, speed: int) -> bool:
  6741. """Set left auxiliary part cooling fan speed (0-255). P2S/X2D accessory."""
  6742. return self.set_fan_speed(10, speed)
  6743. def set_airduct_mode(self, mode: str) -> bool:
  6744. """Set air conditioning mode (cooling or heating).
  6745. Args:
  6746. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  6747. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  6748. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  6749. closes top exhaust flap
  6750. Returns:
  6751. True if command was sent, False otherwise
  6752. """
  6753. if not self._client or not self.state.connected:
  6754. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  6755. return False
  6756. self._sequence_id += 1
  6757. mode_id = 0 if mode == "cooling" else 1
  6758. command = {
  6759. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  6760. }
  6761. # Use QoS 1 for reliable delivery
  6762. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6763. logger.info(
  6764. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  6765. )
  6766. return True
  6767. def set_chamber_light(self, on: bool) -> bool:
  6768. """Turn chamber light on or off.
  6769. Args:
  6770. on: True to turn on, False to turn off
  6771. Returns:
  6772. True if command was sent, False otherwise
  6773. """
  6774. if not self._client or not self.state.connected:
  6775. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  6776. return False
  6777. mode = "on" if on else "off"
  6778. # Control both chamber lights (some printers like H2D have two)
  6779. for led_node in ["chamber_light", "chamber_light2"]:
  6780. self._sequence_id += 1
  6781. command = {
  6782. "system": {
  6783. "command": "ledctrl",
  6784. "led_node": led_node,
  6785. "led_mode": mode,
  6786. "led_on_time": 500,
  6787. "led_off_time": 500,
  6788. "loop_times": 0,
  6789. "interval_time": 0,
  6790. "sequence_id": str(self._sequence_id),
  6791. }
  6792. }
  6793. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6794. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  6795. return True
  6796. def select_extruder(self, extruder: int) -> bool:
  6797. """Select the active extruder for dual-nozzle printers (H2D).
  6798. Args:
  6799. extruder: Extruder index (0=right, 1=left for H2D)
  6800. Returns:
  6801. True if command was sent, False otherwise
  6802. """
  6803. if extruder not in (0, 1):
  6804. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  6805. return False
  6806. if not self._client or not self.state.connected:
  6807. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  6808. return False
  6809. # H2D extruder switching via select_extruder command
  6810. # Command format captured from OrcaSlicer:
  6811. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  6812. # extruder_index: 0 = RIGHT, 1 = LEFT
  6813. self._sequence_id += 1
  6814. command = {
  6815. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  6816. }
  6817. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6818. logger.info(
  6819. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  6820. )
  6821. return True
  6822. def home_axes(self, axes: str = "XYZ") -> bool:
  6823. """Run the printer's full auto-home sequence.
  6824. The ``axes`` argument is ignored: a bare ``G28`` is always sent so
  6825. Bambu firmware runs its safe multi-step routine (park toolhead →
  6826. home XY → home Z). Partial-axis variants like ``G28 Z`` skip the
  6827. toolhead-park step and can crash the bed into the toolhead on H2C
  6828. / H2D / H2S / X1 where Z-home moves the bed UP — see #1052.
  6829. """
  6830. return self.send_gcode("G28")
  6831. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  6832. """Move an axis by a relative distance.
  6833. Args:
  6834. axis: Axis to move ("X", "Y", or "Z")
  6835. distance: Distance to move in mm (positive or negative)
  6836. speed: Movement speed in mm/min
  6837. Returns:
  6838. True if command was sent, False otherwise
  6839. """
  6840. axis = axis.upper()
  6841. if axis not in ("X", "Y", "Z"):
  6842. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  6843. return False
  6844. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  6845. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  6846. return self.send_gcode(gcode)
  6847. def disable_motors(self) -> bool:
  6848. """Disable all stepper motors.
  6849. Warning: This will cause the printer to lose its position.
  6850. A homing operation will be required before printing.
  6851. Returns:
  6852. True if command was sent, False otherwise
  6853. """
  6854. return self.send_gcode("M18")
  6855. def enable_motors(self) -> bool:
  6856. """Enable all stepper motors.
  6857. Returns:
  6858. True if command was sent, False otherwise
  6859. """
  6860. return self.send_gcode("M17")
  6861. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  6862. """Load filament from a specific AMS tray.
  6863. Args:
  6864. tray_id: Global tray ID — 0..15 for AMS slots, 254 for external spool
  6865. (single-external printers and Ext-L on dual-nozzle H2D),
  6866. 255 for Ext-R on dual-nozzle H2D.
  6867. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  6868. Sent only when given, matching BambuStudio: ``extruder_id`` is
  6869. an optional field on ``ams_change_filament``
  6870. (``DeviceManager::command_ams_change_filament``) and Studio
  6871. omits it unless a Filament Track Switch is installed. Without a
  6872. switch the firmware derives the hotend from the AMS's own
  6873. extruder binding and an explicit value is redundant; *with* one
  6874. every AMS reports 0xE and is bound to a switch inlet instead, so
  6875. the firmware has nothing to derive from and the load silently
  6876. does nothing until we name the hotend.
  6877. Returns:
  6878. True if command was sent, False otherwise
  6879. """
  6880. if not self._client or not self.state.connected:
  6881. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  6882. return False
  6883. # Build the ams_change_filament command. Encoding differs by target type:
  6884. # - AMS slots (0..15): slot_id is the local slot, curr/tar_temp = -1.
  6885. # - External spool (tray_id=254): legacy capture from a single-extruder
  6886. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  6887. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  6888. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  6889. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  6890. self._sequence_id += 1
  6891. wire_target = tray_id
  6892. if tray_id == 255:
  6893. ams_id = 255
  6894. slot_id = 0 # extruder index for the right nozzle
  6895. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  6896. if right_temp < 180:
  6897. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  6898. curr_temp = right_temp
  6899. tar_temp = right_temp
  6900. elif tray_id == 254:
  6901. ams_id = 255
  6902. slot_id = 254
  6903. curr_temp = -1
  6904. tar_temp = -1
  6905. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  6906. # A2L AMS-Lite: physical unit 16 + local slot confirmed; the wire
  6907. # `target` (physical global 64-67) is extrapolated (no A2L load
  6908. # capture yet). See a2l_lite_wire_ids.
  6909. ams_id, slot_id, wire_target = _a2l
  6910. curr_temp = -1
  6911. tar_temp = -1
  6912. else:
  6913. ams_id = tray_id // 4
  6914. slot_id = tray_id % 4
  6915. curr_temp = -1
  6916. tar_temp = -1
  6917. command = {
  6918. "print": {
  6919. "command": "ams_change_filament",
  6920. "sequence_id": str(self._sequence_id),
  6921. "ams_id": ams_id,
  6922. "slot_id": slot_id,
  6923. "target": wire_target,
  6924. "curr_temp": curr_temp,
  6925. "tar_temp": tar_temp,
  6926. }
  6927. }
  6928. if extruder_id is not None:
  6929. command["print"]["extruder_id"] = int(extruder_id)
  6930. command_json = json.dumps(command)
  6931. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  6932. self._client.publish(self.topic_publish, command_json, qos=1)
  6933. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  6934. # Track this load request for H2D dual-nozzle disambiguation
  6935. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  6936. self._last_load_tray_id = tray_id
  6937. self.state.pending_tray_target = tray_id
  6938. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  6939. return True
  6940. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  6941. """Unload filament, optionally naming the slot to unload.
  6942. Args:
  6943. tray_id: Global tray ID of the slot being unloaded. When given, the
  6944. command is addressed to that slot's AMS and is only sent if an
  6945. extruder is actually fed from it — BambuStudio does the same
  6946. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  6947. nothing when none matches). When omitted, the pre-existing
  6948. behaviour is kept: unload whatever ``tray_now`` names.
  6949. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  6950. machine with both hotends loaded it names only one of them and an
  6951. unaddressed unload picks that one regardless of which slot the operator
  6952. clicked. Passing the slot is what makes the two hotends distinguishable.
  6953. Returns:
  6954. True if command was sent, False otherwise
  6955. """
  6956. if not self._client or not self.state.connected:
  6957. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  6958. return False
  6959. # Get the currently loaded tray info
  6960. tray_now = self.state.tray_now
  6961. source_tray = tray_now if tray_id is None else tray_id
  6962. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  6963. # Determine source ams_id for the unload command
  6964. if source_tray == 255 or source_tray == 254:
  6965. ams_id = 255 # No filament or external spool
  6966. elif (_a2l := a2l_lite_wire_ids(source_tray // 4, source_tray)) is not None:
  6967. ams_id = _a2l[0] # A2L AMS-Lite: normalised 6 -> physical 16
  6968. else:
  6969. ams_id = source_tray // 4 # Source AMS
  6970. # Refuse an addressed unload of a slot no hotend is holding — but only on
  6971. # a printer that has more than one hotend, which is the only case the
  6972. # check exists for. With one hotend there is nothing to disambiguate:
  6973. # tray_now already names the loaded slot exactly, and running the check
  6974. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  6975. # very likely does, but single-nozzle machines do report the block —
  6976. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  6977. # an X1C on the maintainer's own network sends `device.extruder` — and
  6978. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  6979. # would 409 every unload on every X1C, P1S and A1.
  6980. #
  6981. # Gated on the runtime flag rather than on len(extruder_slots), which is
  6982. # rebuilt from each payload's array and would flip the check off for any
  6983. # frame that carried a short one; and deliberately not on
  6984. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  6985. # one single-nozzle machine as dual (#1386) — the false positive there is
  6986. # exactly the case this gate exists to keep out.
  6987. #
  6988. # The external spool is excluded for a different reason: 254/255 are not
  6989. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  6990. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  6991. local_slot = _a2l[1] if (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None else tray_id % 4
  6992. holder = next(
  6993. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  6994. None,
  6995. )
  6996. if holder is None:
  6997. logger.info(
  6998. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  6999. self.serial_number,
  7000. ams_id,
  7001. local_slot,
  7002. )
  7003. return False
  7004. logger.info(
  7005. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7006. )
  7007. # Command format from BambuStudio traffic capture:
  7008. # - No extruder_id field
  7009. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7010. # - slot_id=255 and target=255 for unload
  7011. # Get current nozzle temperature for the unload command
  7012. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7013. if nozzle_temp < 180:
  7014. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7015. self._sequence_id += 1
  7016. command = {
  7017. "print": {
  7018. "command": "ams_change_filament",
  7019. "sequence_id": str(self._sequence_id),
  7020. "ams_id": ams_id,
  7021. "slot_id": 255, # 255 = unload marker
  7022. "target": 255, # 255 = unload destination
  7023. "curr_temp": nozzle_temp,
  7024. "tar_temp": nozzle_temp,
  7025. }
  7026. }
  7027. command_json = json.dumps(command)
  7028. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7029. self._client.publish(self.topic_publish, command_json, qos=1)
  7030. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7031. # Clear tracked load request since we're unloading
  7032. self._last_load_tray_id = None
  7033. self.state.pending_tray_target = None
  7034. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7035. return True
  7036. def ams_control(self, action: str) -> bool:
  7037. """Control AMS operations.
  7038. Args:
  7039. action: "resume", "reset", or "pause"
  7040. Returns:
  7041. True if command was sent, False otherwise
  7042. """
  7043. if not self._client or not self.state.connected:
  7044. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7045. return False
  7046. if action not in ("resume", "reset", "pause"):
  7047. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7048. return False
  7049. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7050. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7051. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7052. return True
  7053. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7054. """Trigger RFID re-read for a specific AMS tray.
  7055. Args:
  7056. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7057. tray_id: Tray ID within the AMS (0-3)
  7058. Returns:
  7059. Tuple of (success, message)
  7060. """
  7061. if not self._client or not self.state.connected:
  7062. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7063. return False, "Printer not connected"
  7064. # Check if filament is currently loaded (tray_now != 255)
  7065. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7066. tray_now = self.state.tray_now
  7067. if tray_now != 255:
  7068. # Decode which tray is loaded for the message
  7069. if tray_now == 254:
  7070. loaded_tray = "external spool"
  7071. elif tray_now >= 0 and tray_now < 128:
  7072. loaded_ams = tray_now // 4
  7073. loaded_slot = tray_now % 4
  7074. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7075. else:
  7076. loaded_tray = f"tray {tray_now}"
  7077. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7078. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7079. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7080. wire_ams_id, wire_slot_id = ams_id, tray_id
  7081. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7082. wire_ams_id, wire_slot_id, _ = _a2l
  7083. # Use ams_get_rfid command to trigger RFID re-read
  7084. # This command is used by Bambu Studio to re-read the RFID tag
  7085. command = {
  7086. "print": {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id, "sequence_id": "0"}
  7087. }
  7088. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7089. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7090. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7091. def ams_set_filament_setting(
  7092. self,
  7093. ams_id: int,
  7094. tray_id: int,
  7095. tray_info_idx: str,
  7096. tray_type: str,
  7097. tray_sub_brands: str,
  7098. tray_color: str,
  7099. nozzle_temp_min: int,
  7100. nozzle_temp_max: int,
  7101. setting_id: str = "",
  7102. ) -> bool:
  7103. """Set AMS tray filament settings (type, color, temperature).
  7104. Note: K value is set separately via extrusion_cali_sel command.
  7105. Args:
  7106. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7107. tray_id: Tray ID within the AMS (0-3)
  7108. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7109. tray_type: Filament type (e.g., "PLA", "PETG")
  7110. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  7111. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  7112. nozzle_temp_min: Minimum nozzle temperature
  7113. nozzle_temp_max: Maximum nozzle temperature
  7114. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  7115. Returns:
  7116. True if command was sent, False otherwise
  7117. """
  7118. if not self._client or not self.state.connected:
  7119. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  7120. return False
  7121. # Calculate mqtt IDs based on AMS type.
  7122. # External-spool convention verified against a BambuStudio→X1C packet capture
  7123. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  7124. # *global* tray index in `tray_id`, not a local position within the virtual
  7125. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  7126. # is what the original code was matching — but the request and response
  7127. # use different semantics for that field. Sending `tray_id: 0` is what
  7128. # the P1S in #1279 rejected with `result: "fail"`.
  7129. if ams_id == 255:
  7130. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7131. if len(vt_tray) > 1:
  7132. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7133. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7134. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7135. # captured Studio→H2D exchange confirms the correct value.
  7136. mqtt_ams_id = 254 + tray_id
  7137. mqtt_tray_id = 0
  7138. else:
  7139. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7140. mqtt_ams_id = 255
  7141. mqtt_tray_id = 254
  7142. slot_id = 0
  7143. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7144. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7145. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7146. mqtt_ams_id, slot_id, _ = _a2l
  7147. mqtt_tray_id = slot_id
  7148. elif ams_id <= 3:
  7149. mqtt_ams_id = ams_id
  7150. mqtt_tray_id = tray_id
  7151. slot_id = tray_id
  7152. else:
  7153. # AMS-HT: single tray per unit
  7154. mqtt_ams_id = ams_id
  7155. mqtt_tray_id = tray_id
  7156. slot_id = 0
  7157. command = {
  7158. "print": {
  7159. "command": "ams_filament_setting",
  7160. "ams_id": mqtt_ams_id,
  7161. "tray_id": mqtt_tray_id,
  7162. "slot_id": slot_id,
  7163. "tray_info_idx": tray_info_idx,
  7164. "tray_type": tray_type,
  7165. "tray_sub_brands": tray_sub_brands,
  7166. # UPPERCASE, always: lowercase hex is silently read as zeros by
  7167. # P1S firmware and acknowledged as a success (#2987).
  7168. "tray_color": wire_tray_color(tray_color),
  7169. "nozzle_temp_min": nozzle_temp_min,
  7170. "nozzle_temp_max": nozzle_temp_max,
  7171. "sequence_id": "0",
  7172. }
  7173. }
  7174. # Include setting_id if provided (helps slicer show correct profile)
  7175. if setting_id:
  7176. command["print"]["setting_id"] = setting_id
  7177. command_json = json.dumps(command)
  7178. logger.info(
  7179. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  7180. )
  7181. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  7182. self._client.publish(self.topic_publish, command_json, qos=1)
  7183. self._last_ams_cmd_time = time.monotonic()
  7184. return True
  7185. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  7186. """Reset an AMS slot to empty/unconfigured state.
  7187. Args:
  7188. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7189. tray_id: Tray ID within the AMS (0-3)
  7190. Returns:
  7191. True if command was sent, False otherwise
  7192. """
  7193. if not self._client or not self.state.connected:
  7194. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  7195. return False
  7196. # Calculate mqtt IDs based on AMS type — same convention as
  7197. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  7198. if ams_id == 255:
  7199. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7200. if len(vt_tray) > 1:
  7201. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7202. mqtt_ams_id = 254 + tray_id
  7203. mqtt_tray_id = 0
  7204. else:
  7205. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7206. mqtt_ams_id = 255
  7207. mqtt_tray_id = 254
  7208. slot_id = 0
  7209. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7210. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  7211. mqtt_ams_id, slot_id, _ = _a2l
  7212. mqtt_tray_id = slot_id
  7213. elif ams_id <= 3:
  7214. mqtt_ams_id = ams_id
  7215. mqtt_tray_id = tray_id
  7216. slot_id = tray_id
  7217. else:
  7218. # AMS-HT: single tray per unit
  7219. mqtt_ams_id = ams_id
  7220. mqtt_tray_id = tray_id
  7221. slot_id = 0
  7222. command = {
  7223. "print": {
  7224. "command": "ams_filament_setting",
  7225. "ams_id": mqtt_ams_id,
  7226. "tray_id": mqtt_tray_id,
  7227. "slot_id": slot_id,
  7228. "tray_info_idx": "",
  7229. "tray_type": "",
  7230. "tray_sub_brands": "",
  7231. "tray_color": "00000000",
  7232. "nozzle_temp_min": 0,
  7233. "nozzle_temp_max": 0,
  7234. "sequence_id": "0",
  7235. }
  7236. }
  7237. command_json = json.dumps(command)
  7238. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  7239. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  7240. self._client.publish(self.topic_publish, command_json, qos=1)
  7241. self._last_ams_cmd_time = time.monotonic()
  7242. return True
  7243. def extrusion_cali_sel(
  7244. self,
  7245. ams_id: int,
  7246. tray_id: int,
  7247. cali_idx: int,
  7248. filament_id: str,
  7249. nozzle_diameter: str = "0.4",
  7250. ) -> bool:
  7251. """Set calibration profile (K value) for an AMS slot.
  7252. This command selects a K profile from the printer's calibration list.
  7253. Use cali_idx=-1 to use the default K value (0.020).
  7254. Note: Do NOT send setting_id in this command — BambuStudio never includes
  7255. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  7256. Args:
  7257. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7258. tray_id: Tray ID within the AMS (0-3)
  7259. cali_idx: Calibration profile index (-1 for default)
  7260. filament_id: Filament preset ID (same as tray_info_idx)
  7261. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7262. Returns:
  7263. True if command was sent, False otherwise
  7264. """
  7265. if not self._client or not self.state.connected:
  7266. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  7267. return False
  7268. # Calculate mqtt IDs based on AMS type.
  7269. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  7270. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  7271. if ams_id == 255:
  7272. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  7273. # ams_filament_setting which uses LOCAL tray_id=0).
  7274. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7275. if len(vt_tray) > 1:
  7276. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7277. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  7278. mqtt_ams_id = 254 + tray_id
  7279. mqtt_tray_id = 254 + tray_id
  7280. else:
  7281. # Single external slot (X1C, P1S, A1): global tray_id=254
  7282. mqtt_ams_id = 254
  7283. mqtt_tray_id = 254
  7284. slot_id = 0
  7285. elif ams_id <= 3:
  7286. mqtt_ams_id = ams_id
  7287. mqtt_tray_id = ams_id * 4 + tray_id
  7288. slot_id = tray_id
  7289. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7290. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  7291. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  7292. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  7293. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  7294. elif ams_id >= 128 and ams_id <= 135:
  7295. mqtt_ams_id = ams_id
  7296. mqtt_tray_id = tray_id
  7297. slot_id = 0
  7298. else:
  7299. mqtt_ams_id = ams_id
  7300. mqtt_tray_id = tray_id
  7301. slot_id = 0
  7302. command = {
  7303. "print": {
  7304. "command": "extrusion_cali_sel",
  7305. "cali_idx": cali_idx,
  7306. "filament_id": filament_id,
  7307. "nozzle_diameter": nozzle_diameter,
  7308. "ams_id": mqtt_ams_id,
  7309. "tray_id": mqtt_tray_id,
  7310. "slot_id": slot_id,
  7311. "sequence_id": "0",
  7312. }
  7313. }
  7314. command_json = json.dumps(command)
  7315. logger.info(
  7316. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  7317. )
  7318. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  7319. self._client.publish(self.topic_publish, command_json, qos=1)
  7320. return True
  7321. def extrusion_cali_set(
  7322. self,
  7323. tray_id: int,
  7324. k_value: float,
  7325. nozzle_diameter: str = "0.4",
  7326. nozzle_temp: int = 220,
  7327. filament_id: str = "",
  7328. setting_id: str = "",
  7329. name: str = "",
  7330. cali_idx: int = -1,
  7331. ) -> bool:
  7332. """Directly set K value (pressure advance) for a tray.
  7333. Uses the filaments array format required by current firmware.
  7334. Args:
  7335. tray_id: Global tray ID (ams_id * 4 + slot)
  7336. k_value: Pressure advance K value (e.g., 0.020)
  7337. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7338. nozzle_temp: Nozzle temperature for calibration reference
  7339. filament_id: Filament preset ID (e.g., "GFA02")
  7340. setting_id: Setting ID (e.g., "GFSA02_07")
  7341. name: Profile display name
  7342. cali_idx: Calibration index (-1 for new)
  7343. Returns:
  7344. True if command was sent, False otherwise
  7345. """
  7346. if not self._client or not self.state.connected:
  7347. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  7348. return False
  7349. # Was reusing the previous command's id — harmless while nothing
  7350. # correlated on it, but the printer echoes sequence_id back and the
  7351. # K-profile write path now matches acks by it (#2718).
  7352. self._sequence_id += 1
  7353. nozzle_id = f"HS00-{nozzle_diameter}"
  7354. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  7355. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  7356. # stays 0 (hardcoded, as for every other unit here).
  7357. wire_tray_id = tray_id
  7358. if 0 <= tray_id <= 253 and (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  7359. wire_tray_id = _a2l[2]
  7360. filament_entry = {
  7361. "ams_id": 0,
  7362. "cali_idx": cali_idx,
  7363. "extruder_id": 0,
  7364. "filament_id": filament_id,
  7365. "k_value": f"{k_value:.6f}",
  7366. "n_coef": "1.400000",
  7367. "name": name,
  7368. "nozzle_diameter": nozzle_diameter,
  7369. "nozzle_id": nozzle_id,
  7370. "setting_id": setting_id,
  7371. "tray_id": wire_tray_id,
  7372. }
  7373. command = {
  7374. "print": {
  7375. "command": "extrusion_cali_set",
  7376. "filaments": [filament_entry],
  7377. "nozzle_diameter": nozzle_diameter,
  7378. "sequence_id": str(self._sequence_id),
  7379. }
  7380. }
  7381. command_json = json.dumps(command)
  7382. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  7383. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  7384. self._client.publish(self.topic_publish, command_json, qos=1)
  7385. return True
  7386. def set_timelapse(self, enable: bool) -> bool:
  7387. """Enable or disable timelapse recording.
  7388. Args:
  7389. enable: True to enable, False to disable
  7390. Returns:
  7391. True if command was sent, False otherwise
  7392. """
  7393. if not self._client or not self.state.connected:
  7394. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  7395. return False
  7396. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  7397. # First send the timelapse setting
  7398. timelapse_cmd = {
  7399. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  7400. }
  7401. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  7402. # Request status update
  7403. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7404. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  7405. return True
  7406. def set_liveview(self, enable: bool) -> bool:
  7407. """Enable or disable live view / camera streaming.
  7408. Args:
  7409. enable: True to enable, False to disable
  7410. Returns:
  7411. True if command was sent, False otherwise
  7412. """
  7413. if not self._client or not self.state.connected:
  7414. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  7415. return False
  7416. command = {
  7417. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  7418. }
  7419. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7420. # Request status update
  7421. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  7422. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  7423. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  7424. return True
  7425. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  7426. """Dispatch the user's choice from the HMS-error modal as a printer command.
  7427. Args:
  7428. print_error: Canonical hex identifier for the fault — 8 chars for the
  7429. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  7430. (HMSError.full_code). Carried through unchanged from the route.
  7431. Converted to its DECIMAL string form for the `ignore` /
  7432. `idle_ignore` commands' `err` field, which is what the firmware
  7433. actually compares against the active fault. The pre-#1869
  7434. hex-string `err` was silently rejected because the firmware was
  7435. being asked to match `"05008051"` against int 0x05008051
  7436. (= 83918929 decimal) — see BambuStudio's
  7437. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  7438. `std::to_string(int m_error_code)`.
  7439. action: One of HMSAction's string values.
  7440. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  7441. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  7442. shapes; empty string is the no-job-id sentinel.
  7443. Returns False when the MQTT client is offline or when `action` is unknown
  7444. so the route surfaces it as a 4xx rather than a silent no-op.
  7445. """
  7446. if not self._client or not self.state.connected:
  7447. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  7448. return False
  7449. # Always re-push the full state after a command so the modal's underlying
  7450. # status query reflects the new error list (or absence) on the next tick.
  7451. def publish(payload: dict):
  7452. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  7453. self._client.publish(
  7454. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  7455. )
  7456. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  7457. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  7458. # every command_hms_* call). Our route hands us the hex string —
  7459. # convert. Falls back to the raw input if it's not parseable so the
  7460. # firmware can reject it and the route can surface 502 instead of us
  7461. # raising ValueError mid-dispatch.
  7462. try:
  7463. err_decimal = str(int(print_error, 16))
  7464. except ValueError:
  7465. err_decimal = print_error
  7466. def hms_resume():
  7467. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  7468. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  7469. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  7470. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  7471. # shape historically because it works, and changing it without a
  7472. # field test risks regressing a path that the user has confirmed.
  7473. publish(
  7474. {
  7475. "print": {
  7476. "command": "resume",
  7477. "param": "",
  7478. "sequence_id": "0",
  7479. }
  7480. }
  7481. )
  7482. def hms_stop():
  7483. # Same as hms_resume — plain shape, confirmed working by the user
  7484. # for "Stop Printing".
  7485. publish(
  7486. {
  7487. "print": {
  7488. "command": "stop",
  7489. "param": "",
  7490. "sequence_id": "0",
  7491. }
  7492. }
  7493. )
  7494. def hms_ignore_command():
  7495. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  7496. # what the "Ignore this and Resume" button actually publishes.
  7497. # Distinct from `idle_ignore`: this command has the firmware
  7498. # suppress the next re-check of the named fault AND resume the
  7499. # paused print in a single operation. The previous Bambuddy code
  7500. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  7501. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  7502. # the problem, re-check normally" so the firmware re-detected the
  7503. # wrong plate and re-paused with the same code (#1869).
  7504. #
  7505. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  7506. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  7507. # variant of "don't remind next time" lives on `idle_ignore`'s
  7508. # type=1, not as a separate ignore shape.
  7509. publish(
  7510. {
  7511. "print": {
  7512. "command": "ignore",
  7513. "err": err_decimal,
  7514. "param": "reserve",
  7515. "job_id": job_id or "",
  7516. "sequence_id": "0",
  7517. }
  7518. }
  7519. )
  7520. def hms_idle_ignore(persistent: bool = False):
  7521. # `idle_ignore` is BambuStudio's "dismiss this warning without
  7522. # resuming" command for non-pause warnings — what
  7523. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  7524. # type=0 dismisses once, type=1 suppresses the same warning
  7525. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  7526. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  7527. # NOT via the resume-bearing `ignore` command.
  7528. publish(
  7529. {
  7530. "print": {
  7531. "command": "idle_ignore",
  7532. "err": err_decimal,
  7533. "type": 1 if persistent else 0,
  7534. "sequence_id": "0",
  7535. }
  7536. }
  7537. )
  7538. def ams_control(param: str):
  7539. publish(
  7540. {
  7541. "print": {
  7542. "command": "ams_control",
  7543. "param": param,
  7544. "sequence_id": "0",
  7545. }
  7546. }
  7547. )
  7548. def clean_print_error():
  7549. # Matches the existing `clear_hms_errors` shape — Bambu does not
  7550. # expect `print_error` in the body; the command clears whatever
  7551. # error dialog is currently active on the printer.
  7552. publish(
  7553. {
  7554. "print": {
  7555. "command": "clean_print_error",
  7556. "sequence_id": "0",
  7557. }
  7558. }
  7559. )
  7560. def uiop_close():
  7561. # `err` is the 8-char hex short code (already a string from the
  7562. # frontend), uppercased for consistency with how BambuStudio sends it.
  7563. publish(
  7564. {
  7565. "system": {
  7566. "command": "uiop",
  7567. "name": "print_error",
  7568. "action": "close",
  7569. "source": 1,
  7570. "type": "dialog",
  7571. "err": print_error.upper(),
  7572. "sequence_id": "0",
  7573. }
  7574. }
  7575. )
  7576. match action:
  7577. case (
  7578. HMSAction.RESUME_PRINTING
  7579. | HMSAction.RESUME_PRINTING_DEFECTS
  7580. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  7581. | HMSAction.PROBLEM_SOLVED_RESUME
  7582. | HMSAction.FILAMENT_LOAD_RESUME
  7583. | HMSAction.PROCEED
  7584. ):
  7585. hms_resume()
  7586. case HMSAction.STOP_PRINTING:
  7587. hms_stop()
  7588. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  7589. # All three buttons map to BambuStudio's `command_hms_ignore`
  7590. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  7591. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  7592. # responsibility — the wire shape is identical.
  7593. hms_ignore_command()
  7594. case HMSAction.NO_REMINDER_NEXT_TIME:
  7595. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  7596. # `command_hms_idle_ignore` with type=0
  7597. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  7598. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  7599. # dismisses the dialog.
  7600. hms_idle_ignore(persistent=False)
  7601. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  7602. ams_control("done")
  7603. case (
  7604. HMSAction.RETRY_FILAMENT_EXTRUDED
  7605. | HMSAction.CONTINUE
  7606. | HMSAction.RETRY_PROBLEM_SOLVED
  7607. | HMSAction.DBL_CHECK_RETRY
  7608. ):
  7609. ams_control("resume")
  7610. case HMSAction.ABORT:
  7611. ams_control("abort")
  7612. case HMSAction.OK_BUTTON:
  7613. clean_print_error()
  7614. case HMSAction.DBL_CHECK_OK:
  7615. clean_print_error()
  7616. uiop_close()
  7617. case HMSAction.DBL_CHECK_RESUME:
  7618. # Plain resume — not HMS-aware, no err/job_id.
  7619. publish(
  7620. {
  7621. "print": {
  7622. "command": "resume",
  7623. "param": "",
  7624. "sequence_id": "0",
  7625. }
  7626. }
  7627. )
  7628. case HMSAction.REFRESH_NOZZLE:
  7629. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  7630. case HMSAction.TURN_OFF_FIRE_ALARM:
  7631. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  7632. case HMSAction.STOP_DRYING:
  7633. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  7634. case HMSAction.DISABLE_PURIFICATION:
  7635. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  7636. case (
  7637. HMSAction.CHECK_ASSISTANT
  7638. | HMSAction.JUMP_TO_LIVEVIEW
  7639. | HMSAction.OK_JUMP_RACK
  7640. | HMSAction.REMOVE_CLOSE_BTN
  7641. | HMSAction.LOAD_VIRTUAL_TRAY
  7642. | HMSAction.CANCLE
  7643. | HMSAction.DBL_CHECK_CANCEL
  7644. ):
  7645. # UI-only actions — the printer's own screen handles these; the
  7646. # modal still surfaces them so the user has parity with Studio.
  7647. pass
  7648. case _:
  7649. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  7650. return False
  7651. return True