bambu_mqtt.py 375 KB

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