bambu_mqtt.py 401 KB

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