bambu_mqtt.py 356 KB

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