bambu_mqtt.py 358 KB

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