bambu_mqtt.py 363 KB

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