bambu_mqtt.py 418 KB

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