bambu_mqtt.py 436 KB

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