bambu_mqtt.py 448 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839
  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 discard_queued_publishes, retire_paho_client
  25. logger = logging.getLogger(__name__)
  26. # How long a manual load's tray target stays a hint for an H2D's tray_now: long
  27. # enough for a real load to report, short enough that a refused one cannot
  28. # relabel a later print's load of the same slot number (FW-C7).
  29. PENDING_TRAY_TARGET_TTL = 120.0
  30. # AMS module name prefixes used in get_version responses.
  31. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  32. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  33. # "ams_f1/<id>" – AMS Lite (A1, A1 Mini; the A2L reports id 16, stored as 6)
  34. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  35. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  36. _AMS_MODULE_PREFIXES = ("ams/", "ams_f1/", "n3f/", "n3s/")
  37. # gcode_state values that mean the printer is not idle and must not be handed a
  38. # new start-print (#2598). The firmware rejects a project_file while busy with
  39. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  40. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  41. # are valid start targets and are deliberately excluded. Mirrors
  42. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  43. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  44. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  45. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  46. # ended the cycle on schedule or aborted it. More than this many minutes still on
  47. # the clock means it was cut short, and the firmware's own reason codes are worth
  48. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  49. # left), and the log said only "drying complete", so the report carried no
  50. # evidence of why. The margin absorbs a stale last observation between AMS
  51. # pushes; it is not a judgement about how short "short" is.
  52. _EARLY_DRY_END_MINUTES = 5
  53. # CONNACK reason codes that mean the printer actively refused our credentials,
  54. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  55. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  56. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  57. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  58. # code (or, on some firmware, the serial used as the username) is wrong.
  59. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  60. # Short, stable slugs recorded on the client and surfaced to the connection
  61. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  62. # frontend picks a localized message key off these.
  63. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  64. CONNECT_ERROR_REFUSED = "refused"
  65. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  66. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  67. OrcaSlicer reads bit 18 of the hex string via
  68. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  69. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  70. that doesn't yield a clean integer so downstream consumers preserve today's
  71. behaviour rather than treating "absent" as "OFF".
  72. """
  73. if not isinstance(cfg_raw, str) or not cfg_raw:
  74. return None
  75. try:
  76. return bool((int(cfg_raw, 16) >> 18) & 1)
  77. except ValueError:
  78. return None
  79. def parse_ams_filament_backup_from_home_flag(home_flag: object) -> bool | None:
  80. """Extract AMS Filament Backup state from a push_status ``print.home_flag`` value.
  81. Bambu Studio reads bit 10 for every family (DeviceManager.cpp
  82. ``parse_home_flag``: ``SetAutoRefillEnabled((flag >> 10) & 0x1)``). It's
  83. the only source on the P1S, P1P, A1 and A1 Mini, which never send ``cfg``
  84. (#3259). On every printer that sends both, the two bits agree in all
  85. captured snapshots, ON and OFF alike. Returns ``None`` for anything that
  86. isn't an integer.
  87. """
  88. if isinstance(home_flag, bool) or not isinstance(home_flag, int):
  89. return None
  90. # Negative values are the 32-bit flag read as signed; bit 10 is the same.
  91. return bool((home_flag >> 10) & 1)
  92. def is_printer_status_frame(print_data: dict) -> bool:
  93. """True when a ``print`` payload is the printer reporting its own state.
  94. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  95. `project_file` ack carries whatever Bambuddy put on the wire — including
  96. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  97. telemetry means reading our own request back as the printer's state
  98. (#3040). Only `push_status` (and the odd firmware that omits `command`
  99. entirely on a status frame) describes the printer.
  100. """
  101. command = print_data.get("command")
  102. return command is None or command == "push_status"
  103. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  104. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  105. # firmware is internally inconsistent about it:
  106. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  107. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  108. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  109. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  110. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  111. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  112. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  113. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  114. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  115. A2L_LITE_PHYSICAL_AMS_ID = 16
  116. A2L_LITE_NORMALIZED_AMS_ID = 6
  117. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  118. def normalize_am_unit_id(ams_id: int) -> int:
  119. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  120. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  121. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  122. through untouched.
  123. """
  124. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  125. def wire_tray_color(tray_color: str | None) -> str:
  126. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  127. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  128. as a zero, and does it silently: the command response echoes the value you
  129. sent and reports ``result: "success"``, so only the next AMS push shows what
  130. was really stored. Measured on the reporter's machine (#2987), where the
  131. spool's own ``rgba`` is stored lowercase and went out verbatim:
  132. sent 09ff00ff -> AMS reports 09000000
  133. sent ff5100ff -> AMS reports 00510000
  134. sent 090000FF -> AMS reports 090000FF
  135. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  136. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  137. longer matches the spool that asked for it and the assignment is deleted
  138. seconds after being made -- and re-assigning through the slot modal writes
  139. the mangled colour back, because the modal seeds itself from the tray.
  140. Applied here, at the one place the command is built, rather than in each of
  141. the four callers: a caller that forgets is exactly how this arrived.
  142. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  143. blank stays blank, which is how a slot is cleared.
  144. """
  145. return (tray_color or "").strip().lstrip("#").upper()
  146. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  147. """Translate a normalised A2L slot back to the physical wire form.
  148. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  149. (normalised id 6), else ``None`` for every other unit.
  150. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  151. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  152. confirmed by capture: the physical **global** tray value the extrusion_cali
  153. commands put in `tray_id` — we extrapolate it as 16*4+slot = 64-67 to stay
  154. consistent with the physical unit id. BambuStudio's source sends 24+slot
  155. there instead (``GetTrayIndexMap``); a BambuStudio->A2L capture of a cali
  156. command would settle it, and it lives only here. Load's `target` is not this
  157. value: see ``change_filament_wire_ids``.
  158. """
  159. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  160. return None
  161. local_slot = tray_id % 4
  162. return (
  163. A2L_LITE_PHYSICAL_AMS_ID,
  164. local_slot,
  165. A2L_LITE_PHYSICAL_AMS_ID * 4 + local_slot,
  166. )
  167. def change_filament_wire_ids(tray_id: int) -> tuple[int, int, int]:
  168. """``(ams_id, slot_id, target)`` of ``ams_change_filament`` for an AMS tray.
  169. As BambuStudio's ``command_ams_change_filament`` builds them: a regular AMS
  170. is addressed by unit and local slot with the global tray as target; a unit
  171. id of 16 or more (the A2L AMS-Lite's physical 16, an AMS-HT's 128-135) has
  172. the unit id itself as target. An AMS-HT holds one tray, so its global tray
  173. id is its unit id and its slot is 0.
  174. """
  175. if 128 <= tray_id <= 135:
  176. return tray_id, 0, tray_id
  177. if (a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  178. return a2l[0], a2l[1], a2l[0]
  179. return tray_id // 4, tray_id % 4, tray_id
  180. def resolve_external_spools_in_mapping(ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool) -> object:
  181. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  182. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  183. dispatch both write an external spool there as -1 -- the same value as a
  184. slot that isn't fed at all -- and carry the real target only in
  185. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  186. list alone turns "printed from the external spool" into "unmapped", and
  187. usage then lands on whatever tray the fallback guesses.
  188. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  189. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  190. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  191. printers, which have one external spool that the wire always calls 255.
  192. ``{255, 255}`` is the unmapped marker and stays -1.
  193. An A2L AMS-Lite tray is the local slot 0-3 in the flat list and
  194. ``{ams_id: 16, slot_id: n}`` in ``ams_mapping2``; it becomes its normalised
  195. global tray 24+n. Kept local, it read as a regular AMS tray, so usage was
  196. charged to the wrong spool. Every other entry is left exactly as captured.
  197. Without a usable ``ams_mapping2`` the input is returned unchanged.
  198. """
  199. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  200. return ams_mapping
  201. if len(ams_mapping2) != len(ams_mapping):
  202. return ams_mapping
  203. resolved = list(ams_mapping)
  204. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  205. if not isinstance(detail, dict):
  206. continue
  207. ams_id = detail.get("ams_id")
  208. slot_id = detail.get("slot_id")
  209. if ams_id == A2L_LITE_PHYSICAL_AMS_ID and slot_id in (0, 1, 2, 3):
  210. resolved[i] = A2L_LITE_GLOBAL_BASE + slot_id
  211. continue
  212. if flat != -1 or ams_id not in (254, 255) or slot_id == 255:
  213. continue
  214. resolved[i] = ams_id if is_dual_nozzle else 254
  215. return resolved
  216. def unit_reported_absent(ams_id, ams_list: list, ams_exist_bits) -> bool:
  217. """Whether a push that doesn't list AMS unit ``ams_id`` says it is unplugged.
  218. ``ams_exist_bits`` (hex) has bit n set for AMS unit n, measured on an X1C
  219. (unit 1 -> "2", none -> "0") and an H2C (units 0, 1, 2 and HT 128 -> "17").
  220. So an AMS unit 0-3 whose bit is clear is gone. An empty unit list with no
  221. bits set means no unit at all, which is what the X1C sends with its AMS
  222. unplugged. Anything else is kept, as the merge always did: a partial push
  223. lists only some units, and the bits of an AMS HT or AMS Lite next to other
  224. units are not measured well enough to read.
  225. """
  226. if ams_exist_bits is None:
  227. return False
  228. try:
  229. bits = int(ams_exist_bits, 16) if isinstance(ams_exist_bits, str) else int(ams_exist_bits)
  230. unit = int(ams_id)
  231. except (TypeError, ValueError):
  232. return False
  233. if bits == 0 and not ams_list:
  234. return True
  235. return 0 <= unit <= 3 and not bits >> unit & 1
  236. def apply_tray_exist_bits(
  237. units: list,
  238. tray_exist_bits_str: str | int | None,
  239. *,
  240. power_on_flag: bool = True,
  241. log_label: str | None = None,
  242. annotate_exists: bool = False,
  243. ) -> int:
  244. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  245. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  246. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  247. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  248. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  249. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  250. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  251. instead of guessing from payload shape (#1322, #147).
  252. Two callers share this helper to keep their views consistent:
  253. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  254. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  255. facing push_status (#1726 — without this the VP would forward stale
  256. per-tray fields for empty slots, and BambuStudio's Sync would render
  257. phantom loaded slots).
  258. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  259. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  260. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  261. so spool removal is detected without requiring a manual reconnect.
  262. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  263. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  264. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  265. authoritative empty signal for the HT — the only working clear path, since
  266. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  267. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  268. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  269. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  270. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  271. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  272. the raw physical id 16 get the same bit base as callers holding the
  273. normalised 6 (#2697).
  274. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  275. way). Ints are tolerated for defensive symmetry but typically not seen
  276. on the wire. ``None`` / empty / unparseable → no-op.
  277. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  278. every processed slot. This is firmware's authoritative "spool physically
  279. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  280. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  281. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  282. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  283. leaves it False so the ``exists`` key never reaches the slicer wire format.
  284. Mutates ``units`` in place. Returns the number of slots cleared.
  285. """
  286. if not tray_exist_bits_str:
  287. return 0
  288. try:
  289. if isinstance(tray_exist_bits_str, int):
  290. tray_exist_bits = tray_exist_bits_str
  291. else:
  292. tray_exist_bits = int(tray_exist_bits_str, 16)
  293. except (ValueError, TypeError):
  294. return 0
  295. if tray_exist_bits == 0 and not power_on_flag:
  296. return 0
  297. if not isinstance(units, list):
  298. return 0
  299. cleared = 0
  300. for ams_unit in units:
  301. if not isinstance(ams_unit, dict):
  302. continue
  303. ams_id_raw = ams_unit.get("id")
  304. if ams_id_raw is None:
  305. continue
  306. try:
  307. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  308. except (ValueError, TypeError):
  309. continue
  310. if not isinstance(ams_id, int):
  311. continue
  312. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  313. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  314. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  315. # the physical 16. Both mean bit base 24, so fold them together here
  316. # rather than relying on every caller to normalise first — reading 16 as
  317. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  318. ams_id = normalize_am_unit_id(ams_id)
  319. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  320. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  321. # Anything outside those ranges has no known bit layout — don't guess it.
  322. is_ht = 128 <= ams_id <= 135
  323. if not is_ht and not (0 <= ams_id <= 15):
  324. continue
  325. for tray in ams_unit.get("tray", []):
  326. if not isinstance(tray, dict):
  327. continue
  328. tray_id_raw = tray.get("id")
  329. if tray_id_raw is None:
  330. continue
  331. try:
  332. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  333. except (ValueError, TypeError):
  334. continue
  335. if not isinstance(tray_id, int):
  336. continue
  337. global_bit = (16 + (ams_id - 128)) if is_ht else (ams_id * 4 + tray_id)
  338. slot_exists = (tray_exist_bits >> global_bit) & 1
  339. if annotate_exists:
  340. tray["exists"] = bool(slot_exists)
  341. if slot_exists:
  342. continue
  343. tray["state"] = 9
  344. if tray.get("tray_type"):
  345. if log_label:
  346. logger.debug(
  347. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  348. f"(tray_exist_bits bit {global_bit} = 0)"
  349. )
  350. tray["tray_type"] = ""
  351. tray["tray_sub_brands"] = ""
  352. tray["tray_color"] = ""
  353. tray["tray_id_name"] = ""
  354. tray["tag_uid"] = "0000000000000000"
  355. tray["tray_uuid"] = "00000000000000000000000000000000"
  356. tray["tray_info_idx"] = ""
  357. tray["remain"] = 0
  358. cleared += 1
  359. return cleared
  360. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  361. #
  362. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  363. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  364. # rack position is never mistakable for the nozzle on the other carriage.
  365. #
  366. # Extruder indices are a different namespace that happens to overlap these
  367. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  368. # Nothing below may pass a value from one namespace to the other untranslated;
  369. # doing exactly that is what #2800 was.
  370. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  371. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  372. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  373. #
  374. # Briefly changed to the plate's own slot count on the strength of a single
  375. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  376. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  377. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  378. # a calibration job, so the length varies with whatever Studio is doing rather
  379. # than with the filament count -- which makes it the wrong thing to derive.
  380. _RACK_WIRE_SLOTS = 32
  381. # The two carriages, as extruder indices in the form the queue stores (already
  382. # translated through the file's physical_extruder_map).
  383. #
  384. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  385. #
  386. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  387. # extruder 1, AMS 1 and 2 feed extruder 0;
  388. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  389. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  390. # and that print completed. So extruder 1 is the fixed hotend and extruder
  391. # 0 is the rack;
  392. # - our own constants were internally inconsistent about it: physical nozzle
  393. # id N sits on extruder N (see the L/R split in PrintersPage), and
  394. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  395. # extruder index of 0.
  396. #
  397. # These were the other way round until then, which is what dispatched a plate
  398. # to the carriage that had not been levelled and printed its first layer in
  399. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  400. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  401. # which *wire* worked, and the extruder indices were only inferred from it by
  402. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  403. # wire result stands; the inference from it did not.
  404. _FIXED_EXTRUDER_ID = 1
  405. _RACK_EXTRUDER_ID = 0
  406. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  407. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  408. # outright, which would not start the job at all. Native BambuStudio captures
  409. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  410. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  411. _FIXED_NOZZLE_ID = 1
  412. def resolve_rack_nozzle_mapping(
  413. slot_extruders: list[int],
  414. rack_nozzle_id: int | None,
  415. ) -> list[int] | None:
  416. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  417. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  418. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  419. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  420. reports as live.
  421. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  422. when the mapping cannot be resolved with confidence -- in which case the
  423. caller omits the field entirely and the firmware falls back to its own
  424. nozzle pick, exactly as it did before this translation existed. Omitting
  425. is deliberately the failure mode: a *wrong* physical ID makes the printer
  426. level with one nozzle and print with another several millimetres off the
  427. bed, which is far worse than letting the firmware choose.
  428. Returns None specifically when:
  429. - a slot needs the rack but the printer has not reported a live rack
  430. position (mid-swap, or a stale connection);
  431. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  432. for a plate sliced for the fixed hotend only (#2800 capture), so this
  433. matches it rather than naming a nozzle it does not have to name;
  434. - a slot names a carriage that is neither of the two an H2C has, which
  435. means the file was mapped for a machine this translation does not model;
  436. - the plate needs more slots than the wire format carries;
  437. - the input is not a list of whole numbers.
  438. Total by construction: it raises nothing, because the only caller is
  439. building an MQTT print command with no exception handler above it and the
  440. queue item has already been committed as `printing` by then. An
  441. unparseable input has to degrade to "let the firmware pick", not to a job
  442. wedged in a state no print will ever leave.
  443. """
  444. if not isinstance(slot_extruders, list) or not slot_extruders:
  445. return None
  446. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  447. return None
  448. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  449. return None
  450. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  451. return None
  452. # Normalise first so the checks below, and the values that reach the wire,
  453. # are known ints. bool is an int subclass and would otherwise serialise as
  454. # a JSON `true`; None means "slot not printed" and is folded into -1.
  455. normalised: list[int] = []
  456. for extruder in slot_extruders:
  457. if extruder is None:
  458. normalised.append(-1)
  459. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  460. normalised.append(extruder)
  461. else:
  462. return None
  463. if _RACK_EXTRUDER_ID not in normalised:
  464. return None
  465. wire = [-1] * _RACK_WIRE_SLOTS
  466. for index, extruder in enumerate(normalised):
  467. if extruder < 0:
  468. continue
  469. if extruder == _RACK_EXTRUDER_ID:
  470. wire[index] = rack_nozzle_id
  471. elif extruder == _FIXED_EXTRUDER_ID:
  472. wire[index] = _FIXED_NOZZLE_ID
  473. else:
  474. # An H2C has these two carriages and no others. A third index is a
  475. # file mapped for something else, and forwarding it raw would name
  476. # a physical nozzle by an index that does not identify one.
  477. return None
  478. return wire
  479. # A rack position as the operator counts it (and as the printer card and
  480. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  481. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  482. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  483. _RACK_POSITION_BASE = 15
  484. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  485. def rack_position_to_nozzle_id(position: int) -> int | None:
  486. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  487. if not isinstance(position, int) or isinstance(position, bool):
  488. return None
  489. if position not in RACK_POSITIONS:
  490. return None
  491. return _RACK_POSITION_BASE + position
  492. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  493. """Whether a live rack slot can print a group wanting this nozzle.
  494. Mirrors the filter BambuStudio applies in its own picker: the position has
  495. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  496. and flow type. A mismatch here is not cosmetic -- it is the printer being
  497. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  498. """
  499. if not isinstance(slot, dict):
  500. return False
  501. slot_diameter = str(slot.get("diameter") or "").strip()
  502. slot_type = str(slot.get("type") or "").strip()
  503. if not slot_diameter and not slot_type:
  504. return False # empty position
  505. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  506. # the printer does not.
  507. try:
  508. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  509. return False
  510. except (TypeError, ValueError):
  511. return False
  512. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  513. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  514. # printer that omits the code is not thereby ruled ineligible.
  515. wanted = volume_type.strip().lower()
  516. if wanted and slot_type:
  517. is_high_flow = slot_type.upper().startswith("HH")
  518. if wanted.startswith("high flow") != is_high_flow:
  519. return False
  520. return True
  521. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  522. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  523. _RACK_CARRIAGE_NOZZLE_ID = 0
  524. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  525. """Live rack contents keyed by 1-based position, mounted nozzle included.
  526. The firmware omits a rack id entirely while that nozzle is picked up onto
  527. the carriage (#943) -- it does not send an empty placeholder. Taking the
  528. omission at face value would rule the nozzle ineligible for the very print
  529. that wants it, and it is the single most likely position to be picked,
  530. because it is the one the last print left mounted.
  531. The absent id is recoverable only when exactly one is missing: rack ids are
  532. fixed at 16..21, so a single gap alongside a loaded carriage is that
  533. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  534. with four nozzles in six positions looks the same -- so those stay absent
  535. and the caller treats them as empty.
  536. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  537. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  538. """
  539. by_position: dict[int, dict] = {}
  540. carriage: dict | None = None
  541. for slot in rack_slots or []:
  542. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  543. continue
  544. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  545. carriage = slot
  546. continue
  547. position = slot["id"] - _RACK_POSITION_BASE
  548. if position in RACK_POSITIONS:
  549. by_position[position] = slot
  550. missing = [position for position in RACK_POSITIONS if position not in by_position]
  551. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  552. by_position[missing[0]] = carriage
  553. return by_position
  554. def resolve_rack_plan_mapping(
  555. slot_groups: list[int],
  556. groups: dict[int, dict],
  557. choice: dict[int, int],
  558. rack_slots: list[dict],
  559. ) -> tuple[list[int] | None, str | None]:
  560. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  561. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  562. That one can only name the single live rack position, so a plate wanting a
  563. different hotend per group is unresolvable to it. Here each group carries
  564. its own position, which is the operator's choice (#1784) -- the 3MF states
  565. it nowhere, proven by dispatching one plate twice with different picks and
  566. diffing the two files down to float noise.
  567. ``choice`` may be partial or empty; groups it does not name are assigned
  568. from the live rack, preferring a position already loaded with the group's
  569. own filament colour and otherwise taking the lowest eligible one.
  570. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  571. is a sentence naming what could not be satisfied. The caller decides what
  572. to do with a failure, and the two cases differ: a stale *explicit* pick
  573. should stop the print, while a failed auto-assignment should degrade to
  574. letting the firmware choose, exactly as before this existed.
  575. """
  576. if not isinstance(slot_groups, list) or not slot_groups:
  577. return None, "the plate lists no filament slots"
  578. if len(slot_groups) > _RACK_WIRE_SLOTS:
  579. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  580. by_position = _rack_by_position(rack_slots)
  581. # Assign every rack-bound group a position before building the wire, so a
  582. # group can never be handed one an earlier group already took. Explicit
  583. # picks are placed first: an auto-assignment must yield to them rather than
  584. # claim a position the operator asked for.
  585. assigned: dict[int, int] = {}
  586. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  587. for group_id in rack_group_ids:
  588. position = choice.get(group_id)
  589. if position is None:
  590. continue
  591. group = groups[group_id]
  592. if rack_position_to_nozzle_id(position) is None:
  593. return None, f"rack position {position} does not exist"
  594. if position in assigned.values():
  595. return None, f"rack position {position} is picked for more than one filament group"
  596. slot = by_position.get(position)
  597. if slot is None:
  598. return None, f"the printer reports nothing at rack position {position}"
  599. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  600. return None, (
  601. f"rack position {position} holds a "
  602. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  603. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  604. )
  605. assigned[group_id] = position
  606. for group_id in rack_group_ids:
  607. if group_id in assigned:
  608. continue
  609. group = groups[group_id]
  610. eligible = [
  611. position
  612. for position in RACK_POSITIONS
  613. if position not in assigned.values()
  614. and position in by_position
  615. and _rack_slot_is_eligible(
  616. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  617. )
  618. ]
  619. if not eligible:
  620. return None, (
  621. f"no free rack position holds a {group.get('nozzle_diameter')} "
  622. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  623. )
  624. # Prefer a position already carrying this group's colour: picking it
  625. # means the operator does not have to move filament to make the print
  626. # match what they asked for.
  627. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  628. assigned[group_id] = next(
  629. (
  630. position
  631. for position in eligible
  632. if wanted_colour
  633. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  634. == wanted_colour
  635. ),
  636. eligible[0],
  637. )
  638. wire = [-1] * _RACK_WIRE_SLOTS
  639. for index, group_id in enumerate(slot_groups):
  640. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  641. continue # slot this plate does not print
  642. group = groups.get(group_id)
  643. if group is None:
  644. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  645. if not group.get("on_rack"):
  646. wire[index] = _FIXED_NOZZLE_ID
  647. continue
  648. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  649. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  650. return None, f"filament group {group_id} resolved to no rack position"
  651. wire[index] = nozzle_id
  652. if all(value == -1 for value in wire):
  653. return None, "the plate assigns no filament to a nozzle"
  654. return wire, None
  655. @dataclass(frozen=True)
  656. class DryingCycleEnd:
  657. """What Bambuddy saw of one AMS drying cycle, reported when it ends (#2863).
  658. ``peak_minutes`` is the highest ``dry_time`` observed during the cycle and
  659. ``remaining_minutes`` the last one before the drop to 0. ``start_seen`` says
  660. whether the countdown was watched from its first minute; when it was not
  661. (Bambuddy started mid-cycle) the peak is only a lower bound on the length.
  662. ``target_temp`` / ``target_hours`` are known only for cycles Bambuddy itself
  663. started, because the printer never echoes them.
  664. """
  665. ams_id: int
  666. remaining_minutes: int
  667. peak_minutes: int
  668. start_seen: bool
  669. target_temp: int | None = None
  670. target_hours: int | None = None
  671. @dataclass
  672. class MQTTLogEntry:
  673. """Log entry for MQTT message debugging."""
  674. timestamp: str
  675. topic: str
  676. direction: str # "in" or "out"
  677. payload: dict
  678. @dataclass
  679. class HMSError:
  680. """Health Management System error from printer."""
  681. code: str
  682. attr: int # Attribute value for constructing wiki URL
  683. module: int
  684. # Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  685. # 3 notification, 0 invalid. From `code >> 16` for `hms[]` faults, and from
  686. # the error's first hex digit for `print_error` (#2728).
  687. severity: int
  688. # The bundled catalogue's sentence for this fault, resolved once here so
  689. # every surface that reports it — the status response, the WebSocket
  690. # broadcast, the completion payload, notifications — says the same thing.
  691. # None when Bambu publishes no text for the code; see `describe_fault`.
  692. # Replaces a `message` field that was never set or read anywhere.
  693. description: str | None = None
  694. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  695. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  696. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  697. # HMSError without explicitly passing actions can't silently land None on the schema
  698. # boundary and raise ValidationError at routes/printers.py response time.
  699. actions: list[str] = field(default_factory=list)
  700. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  701. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  702. job_id: str | None = None
  703. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  704. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  705. # 32-bit `print_error` path. The frontend echoes this back to
  706. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  707. # used to send caused the firmware to silently reject HMS commands on H2C
  708. # (#1830) and on `hms[]`-sourced faults generally.
  709. full_code: str = ""
  710. def completion_payload(self) -> dict:
  711. """This error as a print-complete payload carries it, for the failure reason."""
  712. return {
  713. "code": self.code,
  714. "attr": self.attr,
  715. "module": self.module,
  716. "severity": self.severity,
  717. # Lets the queue's failure reason label an `hms[]` fault
  718. # with its full code rather than a lossy short one (#2728).
  719. "full_code": self.full_code,
  720. # Carried so the queue's failure reason quotes the same
  721. # sentence the status response and the broadcast do,
  722. # rather than resolving the code a fourth time (#2926).
  723. "description": self.description,
  724. }
  725. # HMS short codes the firmware emits during normal user-cancel sequences.
  726. # These aren't faults — they're status echoes that confirm the cancel happened.
  727. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  728. # so they don't drive the printer card's "X problem" badge, the red pip, or
  729. # any other consumer that treats hms_errors as the active-fault list.
  730. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  731. {
  732. "0300_400C", # "The task was canceled."
  733. "0500_400E", # "Printing was cancelled."
  734. }
  735. )
  736. # "MQTT command verification failed" — the printer's authorization/authentication
  737. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  738. # command it could not verify. Queries (get_version, extrusion_cali_get,
  739. # pushall) still answer, so the connection looks perfectly healthy while
  740. # project_file, gcode_line and ams_change_filament are all silently dropped —
  741. # which is exactly how it presents: uploads succeed, the printer echoes our
  742. # subtask_id, then sits at IDLE forever (#2732).
  743. #
  744. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  745. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  746. # "0500_0007", which matches nothing in any catalog.
  747. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  748. @dataclass
  749. class KProfile:
  750. """Pressure advance (K) calibration profile from printer."""
  751. slot_id: int
  752. extruder_id: int
  753. nozzle_id: str
  754. nozzle_diameter: str
  755. filament_id: str
  756. name: str
  757. k_value: str
  758. n_coef: str = "0.000000"
  759. ams_id: int = 0
  760. tray_id: int = -1
  761. setting_id: str | None = None
  762. @dataclass
  763. class NozzleInfo:
  764. """Nozzle hardware configuration."""
  765. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  766. nozzle_diameter: str = "" # e.g., "0.4"
  767. # What await_cali_ack reports when the printer did not answer a K-profile write
  768. # in time. Not a refusal: firmware that predates the ack never answers.
  769. CALI_ACK_UNCONFIRMED = "no acknowledgement from printer"
  770. class KProfileReadError(Exception):
  771. """The printer's K-profile table could not be read: not connected, or no
  772. answer to any attempt. Not an empty table, which is a printer without
  773. profiles for that nozzle (#3404)."""
  774. # Time the printer has to list a skipped object in s_obj before the skip is
  775. # logged as not confirmed.
  776. SKIP_CONFIRM_TIMEOUT_S = 60.0
  777. # Answers to K-profile commands: they echo the command's own fields (the nozzle
  778. # diameter among them), never the printer's status.
  779. _KPROFILE_COMMAND_ANSWERS = frozenset(
  780. {"extrusion_cali_get", "extrusion_cali_set", "extrusion_cali_del", "extrusion_cali_sel"}
  781. )
  782. @dataclass
  783. class FilaSwitchState:
  784. """Filament Track Switch (FTS) accessory state.
  785. The FTS is an external accessory that mediates filament routing between an
  786. AMS and the printer's extruders. When installed, the AMS no longer has a
  787. fixed extruder assignment — any slot can be routed to any extruder via the
  788. track switch. Detected from print.device.fila_switch in MQTT.
  789. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  790. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  791. stable, operator-visible relationship — it is set on the printer's "Manual
  792. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  793. Field semantics below are taken from BambuStudio's own parser
  794. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  795. """
  796. installed: bool = False
  797. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  798. # the arrays are ordered B-then-A, which is the opposite of how they read.
  799. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  800. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  801. in_slots: list[int] = field(default_factory=list)
  802. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  803. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  804. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  805. # inlet is currently paired with which outlet is not reported at all.
  806. out_extruders: list[int] = field(default_factory=list)
  807. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  808. info: int = 0 # bit 0 = inlet has filament
  809. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  810. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  811. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  812. one of A/B.
  813. """
  814. index = {"A": 1, "B": 0}.get(inlet.upper())
  815. if index is None or index >= len(self.in_slots):
  816. return None
  817. raw = self.in_slots[index]
  818. if raw < 0:
  819. return None
  820. return (raw >> 8) & 0xFF, raw & 0xFF
  821. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  822. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  823. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  824. # as empty everywhere is strictly safer than reading it as the external spool.
  825. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  826. @dataclass
  827. class ExtruderSlot:
  828. """Which AMS slot an extruder is currently fed from.
  829. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  830. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  831. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  832. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  833. ``state.tray_now`` cannot answer this: it is a single value for the whole
  834. printer, so on a dual-nozzle machine with both hotends loaded it names only
  835. one of them. Unloading a specific slot needs to know which extruder is
  836. holding it, which is what this is for.
  837. """
  838. ams_id: int | None = None
  839. slot_id: int | None = None
  840. has_filament: bool = False
  841. def holds(self, ams_id: int, slot_id: int) -> bool:
  842. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  843. return self.ams_id == ams_id and self.slot_id == slot_id
  844. @dataclass
  845. class PrintOptions:
  846. """AI detection and print options from xcam data."""
  847. # Core AI detectors
  848. spaghetti_detector: bool = False
  849. print_halt: bool = False
  850. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  851. first_layer_inspector: bool = False
  852. printing_monitor: bool = False # AI print quality monitoring
  853. buildplate_marker_detector: bool = False
  854. allow_skip_parts: bool = False
  855. # Additional AI detectors - decoded from cfg bitmask
  856. nozzle_clumping_detector: bool = True
  857. nozzle_clumping_sensitivity: str = "medium"
  858. pileup_detector: bool = True
  859. pileup_sensitivity: str = "medium"
  860. airprint_detector: bool = True
  861. airprint_sensitivity: str = "medium"
  862. auto_recovery_step_loss: bool = True # Uses print.print_option command
  863. filament_tangle_detect: bool = False
  864. @dataclass
  865. class PrinterState:
  866. connected: bool = False
  867. state: str = "unknown"
  868. current_print: str | None = None
  869. subtask_name: str | None = None
  870. progress: float = 0.0
  871. remaining_time: int = 0
  872. layer_num: int = 0
  873. total_layers: int = 0
  874. temperatures: dict = field(default_factory=dict)
  875. raw_data: dict = field(default_factory=dict)
  876. gcode_file: str | None = None
  877. subtask_id: str | None = None
  878. hms_errors: list = field(default_factory=list) # List of HMSError
  879. kprofiles: list = field(default_factory=list) # List of KProfile
  880. sdcard: bool = False # SD card inserted
  881. # Whether the printer has ever actually told us about `sdcard`. Without this
  882. # the default False is indistinguishable from a real "no card", and any
  883. # consumer that treats False as evidence would act on silence — which is how
  884. # a storage gate turns into a regression for every printer whose firmware
  885. # simply doesn't publish the field (#2780).
  886. sdcard_reported: bool = False
  887. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  888. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  889. # whoever sent it (the slicer or us). Bambu states where the sliced file
  890. # went: `ftp://<name>` is external storage, which FTPS serves, while
  891. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  892. #
  893. # Two fields, because the two readers need different guarantees.
  894. # ``current_project_url`` belongs to the print now running and is cleared
  895. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  896. # "unknown" rather than inheriting the previous job's answer. That matters:
  897. # 18% of the print starts in #2780's bundle had no dispatch on the request
  898. # topic at all (touchscreen reprints, restart recovery), and a stale
  899. # internal-storage URL would make those skip an FTPS sweep that could have
  900. # found the file — losing an archive that works today.
  901. #
  902. # ``last_project_url`` is sticky and exists for reporting only: the
  903. # connection diagnostic is usually run *after* the print that prompted it,
  904. # by which point the per-print value is rightly gone.
  905. #
  906. # None means we never saw a dispatch — say nothing, don't guess.
  907. current_project_url: str | None = None
  908. last_project_url: str | None = None
  909. timelapse: bool = False # Timelapse recording active
  910. ipcam: bool = False # Live view / camera streaming enabled
  911. wifi_signal: int | None = None # WiFi signal strength in dBm
  912. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  913. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  914. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  915. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  916. # right. (The legacy parser below writes left -> [0], but it only ever runs
  917. # for single-nozzle printers -- every dual-nozzle model reports
  918. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  919. # than indexing it directly.
  920. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  921. # AI detection and print options
  922. print_options: PrintOptions = field(default_factory=PrintOptions)
  923. # Calibration stage tracking (from stg_cur and stg fields)
  924. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  925. stg: list = field(default_factory=list) # List of stages to execute
  926. # Air conditioning mode (0=cooling, 1=heating)
  927. airduct_mode: int = 0
  928. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  929. speed_level: int = 2
  930. # Chamber light on/off
  931. chamber_light: bool = False
  932. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  933. active_extruder: int = 0
  934. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  935. tray_now: int = 255
  936. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  937. # tray_tar = the slot the paused/loading print now expects
  938. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  939. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  940. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  941. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  942. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  943. tray_tar: int = 255
  944. tray_pre: int = 255
  945. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  946. last_loaded_tray: int = -1
  947. # Pending load target - used to track what tray we're loading for H2D disambiguation
  948. pending_tray_target: int | None = None
  949. # When it was set (time.monotonic): see PENDING_TRAY_TARGET_TTL.
  950. pending_tray_target_at: float | None = None
  951. # AMS status for filament change tracking (from print.ams.ams_status field)
  952. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  953. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  954. ams_status: int = 0
  955. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  956. ams_status_sub: int = 0 # ams_status & 0xFF
  957. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  958. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  959. mc_print_sub_stage: int = 0
  960. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  961. ams_mapping: list = field(default_factory=list)
  962. # The running print's AMS mapping (global tray per filament, -1 = none),
  963. # as captured from its print command. None when no print has one.
  964. print_ams_mapping: list | None = None
  965. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  966. ams_extruder_map: dict = field(default_factory=dict)
  967. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  968. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  969. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  970. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  971. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  972. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  973. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  974. ams_switch_inlet: dict = field(default_factory=dict)
  975. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  976. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  977. # series). Empty elsewhere, which every reader has to tolerate — see
  978. # ExtruderSlot for why tray_now cannot stand in for it.
  979. extruder_slots: dict = field(default_factory=dict)
  980. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  981. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  982. # regex used to derive the plate number from the path always falls back to
  983. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  984. # Bambuddy dispatches the print itself we know the plate authoritatively;
  985. # we record it here and prefer it over the gcode_file regex. The subtask
  986. # field guards against staleness: if the printer is currently running a
  987. # different subtask (e.g. a Studio-direct dispatch), these values are
  988. # ignored. Cleared on disconnect.
  989. dispatched_plate_id: int | None = None
  990. dispatched_subtask: str | None = None
  991. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  992. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  993. h2d_extruder_snow: dict = field(default_factory=dict)
  994. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  995. nozzle_rack: list = field(default_factory=list)
  996. # H2C rack position currently mounted / being moved to, from
  997. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  998. # the six rack slots), not extruder indices, and they are what the
  999. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  1000. # can tell us which hotend is in the carriage right now, so this is read
  1001. # live rather than derived from the queued job.
  1002. nozzle_rack_src_id: int | None = None
  1003. nozzle_rack_tar_id: int | None = None
  1004. # Timestamp of last AMS data update (for RFID refresh detection)
  1005. last_ams_update: float = 0.0
  1006. # Printable objects for skip object functionality: {identify_id: object_name}
  1007. printable_objects: dict = field(default_factory=dict)
  1008. # Objects that have been skipped during the current print
  1009. skipped_objects: list = field(default_factory=list)
  1010. # Pauses the slicer put into the running print, from its archived 3MF
  1011. # (#2984): threemf_tools.PausePoint, in print order. Empty when unknown.
  1012. pause_points: list = field(default_factory=list)
  1013. # Layers of those pauses a heads-up notification already went out for.
  1014. pause_warned_layers: set = field(default_factory=set)
  1015. # Fan speeds (0-100 percentage, None if not available for this model)
  1016. cooling_fan_speed: int | None = None # Part cooling fan
  1017. big_fan1_speed: int | None = None # Auxiliary fan
  1018. big_fan2_speed: int | None = None # Chamber/exhaust fan
  1019. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  1020. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  1021. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  1022. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  1023. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  1024. left_aux_fan_speed: int | None = None
  1025. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  1026. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  1027. # omits it, which is the case this flag exists to detect.
  1028. #
  1029. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  1030. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  1031. # harmless because only the P2S/X2D badge consults it — those models keep
  1032. # their unconditional "Chamber Fan" badge — but do not read this as
  1033. # "an exhaust kit is fitted" without also checking the model.
  1034. exhaust_fan_present: bool = False
  1035. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  1036. # Used by usage tracker to split filament weight on mid-print tray switch
  1037. tray_change_log: list = field(default_factory=list)
  1038. # Spools assigned to a tray during the current print, and the spool each
  1039. # assigned tray held at its start (services.spool_swaps, #3325).
  1040. spool_change_log: list = field(default_factory=list)
  1041. # Firmware version info (from info.module[name="ota"].sw_ver)
  1042. firmware_version: str | None = None
  1043. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  1044. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  1045. developer_mode: bool | None = None
  1046. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  1047. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  1048. # which uses the old protocol path; field not yet found). Consumers must treat
  1049. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  1050. ams_filament_backup: bool | None = None
  1051. # Stage name mapping from BambuStudio DeviceManager.cpp
  1052. STAGE_NAMES = {
  1053. 0: "Printing",
  1054. 1: "Auto bed leveling",
  1055. 2: "Heatbed preheating",
  1056. 3: "Vibration compensation",
  1057. 4: "Changing filament",
  1058. 5: "M400 pause",
  1059. 6: "Paused (filament ran out)",
  1060. 7: "Heating nozzle",
  1061. 8: "Calibrating dynamic flow",
  1062. 9: "Scanning bed surface",
  1063. 10: "Inspecting first layer",
  1064. 11: "Identifying build plate type",
  1065. 12: "Calibrating Micro Lidar",
  1066. 13: "Homing toolhead",
  1067. 14: "Cleaning nozzle tip",
  1068. 15: "Checking extruder temperature",
  1069. 16: "Paused by the user",
  1070. 17: "Pause (front cover fall off)",
  1071. 18: "Calibrating the micro lidar",
  1072. 19: "Calibrating flow ratio",
  1073. 20: "Pause (nozzle temperature malfunction)",
  1074. 21: "Pause (heatbed temperature malfunction)",
  1075. 22: "Filament unloading",
  1076. 23: "Pause (step loss)",
  1077. 24: "Filament loading",
  1078. 25: "Motor noise cancellation",
  1079. 26: "Pause (AMS offline)",
  1080. 27: "Pause (low speed of the heatbreak fan)",
  1081. 28: "Pause (chamber temperature control problem)",
  1082. 29: "Cooling chamber",
  1083. 30: "Pause (Gcode inserted by user)",
  1084. 31: "Motor noise showoff",
  1085. 32: "Pause (nozzle clumping)",
  1086. 33: "Pause (cutter error)",
  1087. 34: "Pause (first layer error)",
  1088. 35: "Pause (nozzle clog)",
  1089. 36: "Measuring motion precision",
  1090. 37: "Enhancing motion precision",
  1091. 38: "Measure motion accuracy",
  1092. 39: "Nozzle offset calibration",
  1093. 40: "High temperature auto bed leveling",
  1094. 41: "Auto Check: Quick Release Lever",
  1095. 42: "Auto Check: Door and Upper Cover",
  1096. 43: "Laser Calibration",
  1097. 44: "Auto Check: Platform",
  1098. 45: "Confirming BirdsEye Camera location",
  1099. 46: "Calibrating BirdsEye Camera",
  1100. 47: "Auto bed leveling - phase 1",
  1101. 48: "Auto bed leveling - phase 2",
  1102. 49: "Heating chamber",
  1103. 50: "Cooling heatbed",
  1104. 51: "Printing calibration lines",
  1105. 52: "Auto Check: Material",
  1106. 53: "Live View Camera Calibration",
  1107. 54: "Waiting for heatbed temperature",
  1108. 55: "Auto Check: Material Position",
  1109. 56: "Cutting Module Offset Calibration",
  1110. 57: "Measuring Surface",
  1111. 58: "Thermal Preconditioning",
  1112. 59: "Homing Blade Holder",
  1113. 60: "Calibrating Camera Offset",
  1114. 61: "Calibrating Blade Holder Position",
  1115. 62: "Hotend Pick and Place Test",
  1116. 63: "Waiting for Chamber temperature",
  1117. 64: "Preparing Hotend",
  1118. 65: "Calibrating nozzle clumping detection",
  1119. 66: "Purifying the chamber air",
  1120. 74: "Preparing", # Seen on H2D during print preparation
  1121. 77: "Preparing AMS",
  1122. }
  1123. def get_stage_name(stage: int) -> str:
  1124. """Get human-readable stage name from stage number."""
  1125. try:
  1126. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1127. except TypeError:
  1128. # `stage` is an int by convention only -- it comes straight out of the
  1129. # printer's JSON, and an unhashable value there would otherwise raise
  1130. # from inside the f-string that builds the stage-change log line, which
  1131. # is evaluated on every transition whatever the log level is set to.
  1132. # Labelling a value must not be able to abort the state update.
  1133. return f"Unknown stage ({stage})"
  1134. # #2547 end-of-print telemetry probe.
  1135. #
  1136. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1137. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1138. # but fires on no model in the field: across 247 support bundles there is not a
  1139. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1140. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1141. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1142. #
  1143. # We can't design a replacement from bundles we already have, because out of
  1144. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1145. # every other stage/action field is dropped unread. The obvious candidates
  1146. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1147. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1148. # own. Dumping the raw values for the window between the last object layer and
  1149. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1150. # anything — marks that moment.
  1151. #
  1152. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1153. # Nothing identifying, and nothing that could carry an access code.
  1154. _END_OF_PRINT_PROBE_FIELDS = (
  1155. "gcode_state",
  1156. "state",
  1157. "print_error",
  1158. "stg_cur",
  1159. "stg",
  1160. "stg_cd",
  1161. "mc_print_stage",
  1162. "mc_print_sub_stage",
  1163. "mc_action",
  1164. "mc_stage",
  1165. "print_real_action",
  1166. "print_gcode_action",
  1167. "spd_lvl",
  1168. "mc_percent",
  1169. "mc_remaining_time",
  1170. "layer_num",
  1171. "total_layer_num",
  1172. "home_flag",
  1173. "prepare_per",
  1174. )
  1175. # Frame budget for one print's probe. A long final layer can hold the window
  1176. # open for minutes at ~1 frame/second; this stops a single print from filling
  1177. # the log the user then has to upload.
  1178. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1179. # States that close the window. FINISH is the interesting one — the probe's
  1180. # whole job is to show what happened in the run-up to it.
  1181. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1182. class BambuMQTTClient:
  1183. """MQTT client for Bambu Lab printer communication."""
  1184. MQTT_PORT = 8883
  1185. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1186. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1187. _request_topic_cache: dict[str, bool] = {}
  1188. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1189. # the request topic. A SUBACK failure is the broker answering the question;
  1190. # a disconnect is only circumstantial, and any drop inside the window looks
  1191. # identical -- a network blip, the printer rebooting, the container being
  1192. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1193. # the rest of the process on a printer that supports it perfectly well
  1194. # (#2953). Require the drop to repeat before believing it; a printer that
  1195. # really does refuse the topic answers the same way every time and pays one
  1196. # extra reconnect for it.
  1197. _request_topic_probe_failures: dict[str, int] = {}
  1198. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1199. # Counter for generating unique MQTT client IDs across instances.
  1200. _client_instance_counter: int = 0
  1201. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1202. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1203. # every few seconds (and register_assignment_verification nudges a fresh
  1204. # pushall), so this only has to survive a couple of idle push intervals.
  1205. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1206. def __init__(
  1207. self,
  1208. ip_address: str,
  1209. serial_number: str,
  1210. access_code: str,
  1211. model: str | None = None,
  1212. on_state_change: Callable[[PrinterState], None] | None = None,
  1213. on_print_start: Callable[[dict], None] | None = None,
  1214. on_print_complete: Callable[[dict], None] | None = None,
  1215. on_ams_change: Callable[[list], None] | None = None,
  1216. on_layer_change: Callable[[int], None] | None = None,
  1217. on_print_progress: Callable[[int], None] | None = None,
  1218. on_bed_temp_update: Callable[[float], None] | None = None,
  1219. on_drying_complete: Callable[[int], None] | None = None,
  1220. on_drying_cycle_end: Callable[[DryingCycleEnd], None] | None = None,
  1221. on_print_running_observed: Callable[[dict], None] | None = None,
  1222. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1223. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1224. on_tray_change: Callable[[int, int], None] | None = None,
  1225. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1226. ):
  1227. self.ip_address = ip_address
  1228. self.serial_number = serial_number
  1229. self.access_code = access_code
  1230. self.model = model
  1231. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1232. self._debug_last: dict[str, object] = {}
  1233. self.on_state_change = on_state_change
  1234. self.on_print_start = on_print_start
  1235. self.on_print_complete = on_print_complete
  1236. self.on_ams_change = on_ams_change
  1237. # Fired when an AMS is moved to the switch's other inlet, which changes
  1238. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1239. self.on_fts_inlet_change = on_fts_inlet_change
  1240. self.on_layer_change = on_layer_change
  1241. # #2547: fired when `mc_percent` advances during a running print.
  1242. # `on_layer_change` stops firing the instant the final layer starts, so
  1243. # it is blind to the last few percent of a print — which is exactly the
  1244. # window the finish-photo frame bank needs to keep refreshing through.
  1245. # Progress is the one field that keeps ticking there and then freezes
  1246. # before the end G-code runs, so banking on it stays inside the print.
  1247. self.on_print_progress = on_print_progress
  1248. self.on_bed_temp_update = on_bed_temp_update
  1249. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1250. # the drying cycle just finished (auto- or manually-triggered).
  1251. # Receives the AMS id of the unit that finished drying.
  1252. self.on_drying_complete = on_drying_complete
  1253. # #2863: fired on the same edge with what was seen of the cycle, so the
  1254. # spools in that AMS can be stamped as dried.
  1255. self.on_drying_cycle_end = on_drying_cycle_end
  1256. # #1485 follow-up: fired the first time we see RUNNING state in a
  1257. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1258. # print, the #1304 first-push guard skipped the start event). Lets
  1259. # main.py capture a fresh timelapse baseline at restart-recovery
  1260. # time so the completion-time snapshot-diff still works. Receives
  1261. # the same shape as on_print_start (filename / subtask_name /
  1262. # remaining_time / raw_data / ams_mapping).
  1263. self.on_print_running_observed = on_print_running_observed
  1264. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1265. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1266. # with the process, and a long print outliving a restart would
  1267. # otherwise lose the segment boundaries the usage tracker splits on.
  1268. # Receives (global_tray_id, layer_num).
  1269. self.on_tray_change = on_tray_change
  1270. # #1721: fired the moment the printer enters the end-of-print
  1271. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1272. # we've hit the last layer / remaining_time<=0). This is the
  1273. # framing #1397 was after — toolhead parked, bed not yet
  1274. # dropped — but reached via a clean state signal instead of
  1275. # the per-layer M622 J1 macros which caused per-layer nozzle
  1276. # parks on slicer profiles with Timelapse Type = Smooth.
  1277. # A FINISH-state fallback below fires this same callback if
  1278. # stage 22 never arrives (cancel mid-print, external-spool-
  1279. # only prints, HMS halt before unload, firmware variants).
  1280. self.on_finish_photo_moment = on_finish_photo_moment
  1281. # #2582: fired after a spool assignment (ams_filament_setting +
  1282. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1283. # push landed or a timeout elapses without it. Receives
  1284. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1285. # tell the user "loaded" vs "assignment didn't take" instead of the
  1286. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1287. # feel random. See _check_assignment_verifications.
  1288. self.on_assignment_verified = on_assignment_verified
  1289. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1290. # value is the desired end-state we just pushed plus a monotonic
  1291. # deadline. Populated by register_assignment_verification, drained by
  1292. # _check_assignment_verifications on every AMS push.
  1293. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1294. # Per-AMS previous dry_time, used to detect the falling edge above.
  1295. # Seeded lazily as we observe each AMS unit.
  1296. self._previous_dry_times: dict[int, int] = {}
  1297. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1298. # A live cycle's countdown ticks once a minute; a command the firmware
  1299. # accepted but never actually started (observed on an H2D mid-print
  1300. # with two AMS-HT cycles already running: the third unit's timer sat
  1301. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1302. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1303. # reported as dry_countdown_stalled so the UI can stop claiming an
  1304. # active cycle that is not running.
  1305. self._dry_time_changed_at: dict[int, float] = {}
  1306. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1307. # last start. Bambu does not echo these back in the per-tick AMS push
  1308. # — only the dry_time countdown — so we cache what we sent to drive
  1309. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1310. self._drying_targets: dict[int, dict[str, object]] = {}
  1311. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1312. # ends a cycle far short of its duration, which on the telemetry alone
  1313. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1314. # log would otherwise blame the printer for our own decision (#2770).
  1315. self._drying_stops_sent: set[int] = set()
  1316. # Per-AMS record of the cycle in progress: the highest dry_time seen,
  1317. # whether its first minute was observed, and the target we sent for it.
  1318. # The target is copied here when the countdown starts because a stop
  1319. # drops _drying_targets before the cycle ends (#2863).
  1320. self._dry_cycles: dict[int, dict[str, object]] = {}
  1321. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1322. # for, so each is reported once rather than on every transition into it.
  1323. self._unnamed_stages_seen: set[int] = set()
  1324. self.state = PrinterState()
  1325. self._client: mqtt.Client | None = None
  1326. self._loop: asyncio.AbstractEventLoop | None = None
  1327. self._previous_gcode_state: str | None = None
  1328. self._previous_gcode_file: str | None = None
  1329. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1330. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1331. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1332. # #1721: one-shot guard so the end-of-print stage-22 detector
  1333. # and the FINISH-state fallback don't both fire on the same
  1334. # print. Reset to False on every print start.
  1335. self._finish_photo_captured: bool = False
  1336. # #2702: one-shot re-request of the layer total. Armed at print start
  1337. # when the starting frame carried no `total_layer_num`, spent on the
  1338. # first layer advance that still has no denominator. Bambu firmware
  1339. # only re-sends *changed* fields, so a total we never received (or
  1340. # dropped) is only recoverable via a full pushall.
  1341. self._total_layers_refresh_armed: bool = False
  1342. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1343. # window has run for a print so a late FINISH re-send can't reopen it.
  1344. self._eop_probe_armed: bool = True
  1345. self._eop_probe_open: bool = False
  1346. self._eop_probe_frames: int = 0
  1347. self._eop_probe_last: dict = {}
  1348. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1349. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1350. # #3317: the layer the previous print ended on. Right after a print
  1351. # starts, the printer can send one frame that still carries it (H2S:
  1352. # `layer_num` 357 with `mc_percent` 0, then 0 a second later). Taken at
  1353. # face value, the 0 that follows saved 357 as this print's last layer,
  1354. # and a print failing at layer 0 was charged as finished. Frames with
  1355. # this value are ignored until the new print reports another layer.
  1356. self._stale_layer_num: int = 0
  1357. # The subtask_id minted for the most recent start_print() command. The
  1358. # printer echoes it back in status, but often not within the first few
  1359. # seconds — so on_print_start uses this as the id source when the
  1360. # printer hasn't reported it yet, letting queue/scheduled archives
  1361. # persist a restart-stable id from the moment they dispatch (#1485).
  1362. self.last_dispatch_subtask_id: str | None = None
  1363. # The printer's answer to the last print start it refused, as (result,
  1364. # reason); cleared when the next start is sent. The start watchdog
  1365. # reads it to stop waiting for a print that will not come.
  1366. self.last_start_refusal: tuple[str, str | None] | None = None
  1367. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1368. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1369. self._logging_enabled: bool = False
  1370. self._last_message_time: float = 0.0 # Track when we last received a message
  1371. # Count of report-topic messages received since the last (re)connect.
  1372. # Lets check_staleness() distinguish "printer never sent a status
  1373. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1374. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1375. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1376. self._report_messages_since_connect: int = 0
  1377. self._zero_report_hint_logged: bool = False
  1378. # Set by mark_power_off() to the gcode_state held just before we
  1379. # optimistically forced the printer to "unknown" (#2629). Restored on
  1380. # the next inbound message, because message traffic proves the power
  1381. # was never actually cut. None whenever no power-off is presumed.
  1382. self._state_before_power_off: str | None = None
  1383. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1384. # printer's pushes verbatim to slicers connected to a virtual printer).
  1385. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1386. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1387. self._disconnection_event: threading.Event | None = None
  1388. self._previous_ams_hash: str | None = None # Track AMS changes
  1389. # Track external-spool (vt_tray) identity changes separately: the AMS
  1390. # hash above covers only AMS units, so an external-spool-only filament
  1391. # swap would never re-trigger inventory reconciliation (#2575).
  1392. self._previous_vt_tray_hash: str | None = None
  1393. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1394. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1395. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1396. # Track which (ams_id, field) warnings have already been emitted this connection
  1397. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1398. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1399. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1400. # keyed by the sequence_id we sent, so two concurrent requests for
  1401. # different nozzle sizes can't steal each other's response (#1748).
  1402. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1403. self._sequence_id: int = 0
  1404. self._pending_kprofile_requests: dict[str, dict] = {}
  1405. # The printer's calibration table, one bucket per nozzle diameter.
  1406. #
  1407. # An extrusion_cali_get response is the complete table for *one* nozzle
  1408. # size, and the printer answers whoever asks — including BambuStudio,
  1409. # whose queries land on the same report topic we subscribe to. Assigning
  1410. # each response straight to state.kprofiles therefore let any single
  1411. # answer stand for the whole printer: a GitHub backup probing
  1412. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1413. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1414. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1415. # card because H2-series trays carry no `k` of their own — the slot's
  1416. # K value is resolved from cali_idx against exactly this list.
  1417. #
  1418. # Keyed by diameter so a response only ever replaces the bucket it
  1419. # actually describes; state.kprofiles is then the union across buckets.
  1420. # An empty answer for a nozzle the printer doesn't have empties that
  1421. # bucket alone.
  1422. self._kprofiles_by_nozzle: dict[str, list] = {}
  1423. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1424. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1425. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1426. # by await_cali_ack.
  1427. self._pending_cali_acks: dict[str, dict | None] = {}
  1428. # Objects sent in skip_objects that the printer's s_obj list has not
  1429. # shown yet: object id -> when it was sent. And the ids of each
  1430. # command by its sequence_id, for its answer.
  1431. self._unconfirmed_skips: dict[int, float] = {}
  1432. self._skip_commands: dict[str, list[int]] = {}
  1433. # Acks for RFID re-reads (ams_get_rfid, and the M620 R gcode_line
  1434. # fallback), keyed the same way. Drained by ams_refresh_tray (#3206).
  1435. self._pending_rfid_acks: dict[str, dict | None] = {}
  1436. # Identifies the one project_file *we* dispatched, so its echo on the
  1437. # topic can be told apart from a slicer's. One-shot: consumed by the
  1438. # first frame that matches. See _project_file_key.
  1439. self._own_project_file_key: str | None = None
  1440. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1441. # Key: module_name, Value: timestamp when command was sent
  1442. self._xcam_hold_start: dict[str, float] = {}
  1443. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1444. # True once the printer has sent `cfg`; from then on AMS Filament Backup
  1445. # is read from cfg only, never from home_flag (#3259).
  1446. self._backup_cfg_seen: bool = False
  1447. # True once a full status report arrived without `cfg`; from then on
  1448. # home_flag bit 10 is read from every status frame (#3259).
  1449. self._backup_home_flag_trusted: bool = False
  1450. # Whether the frame being handled carried the nozzles' snow: only then
  1451. # may snow overrule the slot the same frame reports as tray_now.
  1452. self._snow_in_frame = False
  1453. # The captured ams_mapping lives on the state (print_ams_mapping), so
  1454. # the status the card reads carries it; see _captured_ams_mapping.
  1455. # The destination of the dispatch it was captured from.
  1456. self._captured_mapping_url: str | None = None
  1457. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1458. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1459. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1460. self._has_a2l_am_unit: bool = False
  1461. # Why the last connection attempt was refused by the printer, or None
  1462. # when we have never seen a CONNACK failure since the last success.
  1463. # Without this a rejected access code was completely invisible: paho
  1464. # reports the follow-up disconnect as the generic "Unspecified error"
  1465. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1466. # printer stuck in a reconnect loop looked identical whether it was
  1467. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1468. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1469. # string, kept for the log line only.
  1470. self.last_connect_error: str | None = None
  1471. self.last_connect_error_name: str | None = None
  1472. # Request topic subscription tracking
  1473. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1474. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1475. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1476. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1477. self._request_topic_sub_mid: int | None = None
  1478. self._request_topic_sub_time: float = 0.0
  1479. self._request_topic_confirmed: bool = False
  1480. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1481. # we probe by sending an ams_filament_setting and checking the response.
  1482. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1483. self._dev_mode_probed: bool = False
  1484. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1485. self._dev_mode_probe_seq: str | None = None
  1486. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1487. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1488. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1489. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1490. # the printer reports it until the fault clears, so when a later hms[]
  1491. # arrives without it (user enabled Developer Mode and restarted the
  1492. # printer) we drop back to "unknown" and let the probe re-run instead of
  1493. # leaving a permanently-wrong False behind (#2732).
  1494. self._dev_mode_from_hms: bool = False
  1495. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1496. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1497. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1498. self._stale_reconnecting: bool = False
  1499. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1500. # when the frontend polls status faster than paho can reconnect.
  1501. self._last_stale_reconnect: float = 0.0
  1502. # Zombie session detection via ams_filament_setting response tracking (#887).
  1503. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1504. # that develop later (telemetry flows but publishes silently fail).
  1505. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1506. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1507. @property
  1508. def topic_subscribe(self) -> str:
  1509. return f"device/{self.serial_number}/report"
  1510. @property
  1511. def topic_publish(self) -> str:
  1512. return f"device/{self.serial_number}/request"
  1513. @property
  1514. def report_messages_since_connect(self) -> int:
  1515. """Count of report-topic messages received since the latest (re)connect.
  1516. Exposed for the connection diagnostic so it can distinguish "MQTT
  1517. broker accepted us but the printer never published" (typically a
  1518. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1519. bridge that happens to be idle right now. Zero immediately after a
  1520. fresh connect is normal; zero after a full status push cycle is the
  1521. wrong-serial failure mode.
  1522. """
  1523. return self._report_messages_since_connect
  1524. # Maximum time (seconds) without a message before considering connection stale
  1525. STALE_TIMEOUT = 60.0
  1526. def is_stale(self) -> bool:
  1527. """Check if the connection is stale (no messages for too long)."""
  1528. if self._last_message_time == 0:
  1529. return False # Never received a message yet
  1530. time_since_last = time.time() - self._last_message_time
  1531. return time_since_last > self.STALE_TIMEOUT
  1532. def mark_power_off(self) -> bool:
  1533. """Presume the printer lost power (smart plug switched off).
  1534. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1535. The presumption is undone by ``_on_message`` if the printer keeps
  1536. talking — inbound traffic proves the power was never cut (#2629).
  1537. Returns True when the state was actually changed.
  1538. """
  1539. if not self.state.connected:
  1540. return False
  1541. previous = self.state.state
  1542. # Blank the state BEFORE recording what to restore. This runs on the
  1543. # event loop while _on_message runs on the paho thread, and the restore
  1544. # is a two-step (read saved state, compare against "unknown"). Writing
  1545. # "unknown" first means an interleaved message either sees no saved
  1546. # state yet (and skips, leaving the next message to restore) or sees a
  1547. # consistent pair — never a saved state paired with a live state it
  1548. # then discards, which would strand the printer on "unknown".
  1549. self.state.connected = False
  1550. self.state.state = "unknown"
  1551. # Only the first mark wins: a second call before any message arrives
  1552. # must not overwrite the real state with the "unknown" it just wrote.
  1553. # Nothing to restore if the state was already blank.
  1554. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1555. self._state_before_power_off = previous
  1556. return True
  1557. def _restore_state_after_false_power_off(self) -> bool:
  1558. """Undo a presumed power-off once the printer proves it is alive.
  1559. ``connected`` self-heals on the next message, but ``state`` does not:
  1560. it is only rewritten when a payload carries ``gcode_state``, and the
  1561. steady-state ``push_status`` frames are partial. Without this the
  1562. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1563. and the queue scheduler treats the printer as not idle the whole time
  1564. (#2629). Returns True when a state was restored.
  1565. """
  1566. previous = self._state_before_power_off
  1567. self._state_before_power_off = None
  1568. if previous is None or self.state.state != "unknown":
  1569. return False
  1570. logger.info(
  1571. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1572. self.serial_number,
  1573. previous,
  1574. )
  1575. self.state.state = previous
  1576. return True
  1577. # Minimum seconds between stale reconnect attempts. Frontend polls
  1578. # status every few seconds — without a cooldown, each poll would
  1579. # force-close the socket before paho has time to reconnect.
  1580. STALE_RECONNECT_COOLDOWN = 30.0
  1581. def check_staleness(self) -> bool:
  1582. """Check staleness and update connected state if stale. Returns True if connected."""
  1583. if self.state.connected and self.is_stale():
  1584. # Don't force-close again if we already did recently — give paho
  1585. # time to reconnect and the printer time to send its first message.
  1586. now = time.time()
  1587. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1588. return self.state.connected
  1589. logger.warning(
  1590. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1591. )
  1592. # A connection that keeps going stale without ever receiving a
  1593. # status report is almost always a wrong or mis-cased serial
  1594. # number — the broker accepts the connection and the subscription
  1595. # regardless, but the printer publishes to device/<real-serial>/
  1596. # report, which is case-sensitive. Surface that once so the user
  1597. # has something actionable instead of an endless reconnect loop.
  1598. # Only meaningful once the *current* session has had time to receive
  1599. # something. _report_messages_since_connect is reset by _on_connect,
  1600. # so a reconnect that lands microseconds before this check leaves it
  1601. # at 0 for reasons that have nothing to do with the serial — which is
  1602. # how a healthy P1S ended up being told to go check its serial number
  1603. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1604. # on this session means the hint only fires when the printer really
  1605. # has published nothing to the topic we subscribed to.
  1606. # _connect_time of 0 means we have no timestamp to judge by (never went
  1607. # through _on_connect); fall back to the old unconditional behaviour
  1608. # rather than silently swallowing the hint.
  1609. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1610. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1611. self._zero_report_hint_logged = True
  1612. logger.warning(
  1613. "[%s] Connected and subscribed, but the printer has sent zero "
  1614. "status reports. The most common cause is a wrong or mis-cased "
  1615. "serial number — the device/<serial>/report MQTT topic is "
  1616. "case-sensitive. Verify the serial number configured in Bambuddy "
  1617. "exactly matches the printer.",
  1618. self.serial_number,
  1619. )
  1620. self._last_stale_reconnect = now
  1621. self.state.connected = False
  1622. if self.on_state_change:
  1623. self.on_state_change(self.state)
  1624. # Route based on caller thread — see force_reconnect_stale_session.
  1625. # check_staleness is normally called from FastAPI handlers (async,
  1626. # gets the hard-reset path) but the dispatcher exists for safety.
  1627. self._stale_reconnecting = True
  1628. self._reset_client_for_reconnect()
  1629. return self.state.connected
  1630. def force_reconnect_stale_session(self, reason: str) -> None:
  1631. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1632. # arriving but our publishes don't reach the printer.
  1633. #
  1634. # Two routing paths:
  1635. #
  1636. # Async-context callers (queue dispatch deadline)
  1637. # → full client teardown + fresh client_id. Wipes paho's client-side
  1638. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1639. # `project_file` from the broken session would otherwise replay on
  1640. # reconnect, mixing stale commands into the next dispatch and
  1641. # triggering 0500_4003 SD R/W on the printer.
  1642. #
  1643. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1644. # zombie detection, both inside `_update_state`)
  1645. # → socket-close fallback. There is no running loop on that thread to
  1646. # hand the rebuilt client, so close the socket and let paho's own
  1647. # loop detect the broken connection and auto-reconnect (same
  1648. # instance, same client_id). paho would re-send its old outbox on
  1649. # that reconnect; _on_connect empties it first (#3454).
  1650. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1651. self._stale_reconnecting = True
  1652. self.state.connected = False
  1653. if self.on_state_change:
  1654. self.on_state_change(self.state)
  1655. self._reset_client_for_reconnect()
  1656. def _reset_client_for_reconnect(self) -> None:
  1657. """Route between hard-reset and socket-close based on caller thread.
  1658. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1659. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1660. answers that and identifies the caller in one go — paho's callback
  1661. thread has no loop; every legitimate hard-reset caller (FastAPI
  1662. handlers, background async tasks) does."""
  1663. try:
  1664. loop = asyncio.get_running_loop()
  1665. except RuntimeError:
  1666. loop = None
  1667. if loop is not None:
  1668. self._loop = loop
  1669. self._hard_reset_client()
  1670. else:
  1671. self._socket_close_for_reconnect()
  1672. def _hard_reset_client(self) -> None:
  1673. """Tear down the paho client entirely and rebuild it with a fresh
  1674. client_id, so the broker drops the old session and paho's local
  1675. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1676. Caller is responsible for setting ``_stale_reconnecting`` and
  1677. broadcasting the disconnected state.
  1678. Returns as fast as it can build a client: the old one's teardown is
  1679. handed off rather than waited on, because waiting on it is what
  1680. stopped the event loop in #3068. See ``retire_paho_client``."""
  1681. old_client = self._client
  1682. self._client = None
  1683. if old_client is not None:
  1684. retire_paho_client(old_client, self.serial_number)
  1685. # Skip reconnect if no asyncio loop is available (test environment or
  1686. # pre-init). The next initial connect() call from PrinterManager will
  1687. # set up the client fresh.
  1688. if self._loop is None:
  1689. return
  1690. try:
  1691. self.connect(loop=self._loop)
  1692. except Exception as e:
  1693. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1694. def _socket_close_for_reconnect(self) -> None:
  1695. """Close the underlying socket so paho's loop thread detects the
  1696. broken connection and triggers auto-reconnect on the SAME client
  1697. instance. Safe to call from paho's own network thread (the loop
  1698. polls the socket on every iteration and handles a closed socket
  1699. gracefully). Used as a fallback when hard-reset isn't safe. The old
  1700. outbox is not re-sent: _on_connect empties it first (#3454)."""
  1701. if self._client:
  1702. try:
  1703. sock = self._client.socket()
  1704. if sock:
  1705. sock.close()
  1706. except Exception:
  1707. pass
  1708. def _drop_previous_connection_commands(self, client) -> None:
  1709. """Forget every command queued on an earlier connection (#3454).
  1710. Called first in on_connect, which paho runs before it re-sends its
  1711. old outbox. Makes every printer command at most once per connection;
  1712. a command lost in the seconds before a drop is clicked again."""
  1713. dropped = discard_queued_publishes(client)
  1714. if dropped is None:
  1715. logger.warning(
  1716. "[%s] Cannot clear paho's outbox on reconnect (paho internals changed); "
  1717. "commands from the previous connection may be sent again",
  1718. self.serial_number,
  1719. )
  1720. elif dropped:
  1721. logger.info(
  1722. "[%s] Dropped %d command(s) queued on the previous MQTT connection",
  1723. self.serial_number,
  1724. dropped,
  1725. )
  1726. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1727. if rc == 0:
  1728. # First, before anything here publishes on the new connection.
  1729. self._drop_previous_connection_commands(client)
  1730. self.state.connected = True
  1731. self.last_connect_error = None
  1732. self.last_connect_error_name = None
  1733. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1734. # A dropped-and-restored MQTT session means the presumed power-off was
  1735. # real (or at least that the printer restarted): there is nothing
  1736. # legitimate left to restore, and the printer will send a full status
  1737. # push shortly. Dropping the saved state keeps a stale one from being
  1738. # broadcast ahead of the first real report (#2629, #1679).
  1739. self._state_before_power_off = None
  1740. # Reset per-connection warning state so warnings fire once per (re)connection
  1741. self._ams_version_warned = set()
  1742. # Preserve cached developer_mode across auto-reconnects to avoid
  1743. # re-probing on every reconnect. The probe (ams_filament_setting to
  1744. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1745. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1746. # once when developer_mode is truly unknown (first connect).
  1747. # Reset probe tracking so stale timeout state doesn't carry over.
  1748. self._dev_mode_probed = False
  1749. self._dev_mode_needs_probe = False
  1750. self._dev_mode_probe_seq = None
  1751. self._dev_mode_probe_time = 0.0
  1752. self._dev_mode_probe_failures = 0
  1753. self._connect_time = time.monotonic()
  1754. self._report_messages_since_connect = 0
  1755. self._last_ams_cmd_time = 0.0
  1756. self._ams_cmd_unanswered = 0
  1757. # Drop any assignment verifications that were mid-flight before the
  1758. # reconnect — their deadlines are stale and the tray state we would
  1759. # compare against is about to be re-pushed from scratch (#2582).
  1760. # Dropping is silent (no failure event) on purpose.
  1761. self._pending_assignments.clear()
  1762. client.subscribe(self.topic_subscribe)
  1763. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1764. if self._request_topic_supported:
  1765. result, mid = client.subscribe(self.topic_publish)
  1766. if result == mqtt.MQTT_ERR_SUCCESS:
  1767. self._request_topic_sub_mid = mid
  1768. self._request_topic_sub_time = time.time()
  1769. self._request_topic_confirmed = False
  1770. else:
  1771. logger.warning(
  1772. "[%s] Failed to send request topic subscription",
  1773. self.serial_number,
  1774. )
  1775. self._request_topic_supported = False
  1776. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1777. # Request full status update (includes nozzle info in push_status response)
  1778. self._request_push_all()
  1779. # Request firmware version info
  1780. self._request_version()
  1781. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1782. # The correct nozzle data comes from push_status.
  1783. # Prime K-profile request (Bambu printers often ignore first request)
  1784. self._prime_kprofile_request()
  1785. # Immediately broadcast connection state change
  1786. if self.on_state_change:
  1787. self.on_state_change(self.state)
  1788. else:
  1789. self.state.connected = False
  1790. self._record_connect_refusal(rc)
  1791. def _record_connect_refusal(self, rc) -> None:
  1792. """Log and remember why the printer refused the MQTT connection.
  1793. The failure branch of ``_on_connect`` used to be a bare
  1794. ``connected = False``, which threw away the only signal that says
  1795. *why* a printer never comes online. The user-visible result was a
  1796. 30-second reconnect loop logging nothing but paho's generic
  1797. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1798. powered-off printer, so "my printer won't print" reports could not be
  1799. triaged without a round trip (#2698).
  1800. Never logs the access code itself; the code is the likely culprit but
  1801. printing it would put a credential in every support bundle.
  1802. """
  1803. code = getattr(rc, "value", rc)
  1804. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1805. self.last_connect_error_name = name
  1806. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1807. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1808. logger.warning(
  1809. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1810. "or serial number is wrong — the access code changes every time LAN Only or "
  1811. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1812. self.serial_number,
  1813. name,
  1814. code,
  1815. )
  1816. else:
  1817. self.last_connect_error = CONNECT_ERROR_REFUSED
  1818. logger.warning(
  1819. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1820. self.serial_number,
  1821. name,
  1822. code,
  1823. )
  1824. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1825. """Handle SUBACK responses to detect request topic subscription rejection."""
  1826. if mid == self._request_topic_sub_mid:
  1827. for rc in reason_code_list:
  1828. if rc.is_failure:
  1829. logger.warning(
  1830. "[%s] Request topic subscription rejected (code=%d: %s). "
  1831. "ams_mapping capture from slicer-initiated prints unavailable.",
  1832. self.serial_number,
  1833. rc.value,
  1834. rc.getName(),
  1835. )
  1836. self._request_topic_supported = False
  1837. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1838. else:
  1839. logger.info(
  1840. "[%s] Request topic subscription accepted. "
  1841. "ams_mapping capture enabled for slicer-initiated prints.",
  1842. self.serial_number,
  1843. )
  1844. self._request_topic_confirmed = True
  1845. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  1846. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  1847. self._request_topic_sub_mid = None
  1848. self._request_topic_sub_time = 0.0
  1849. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  1850. # Always unblock disconnect() callers, regardless of whether we suppress
  1851. # the state broadcast below. disconnect() sets _disconnection_event and
  1852. # waits on it — every callback path must fire it.
  1853. if self._disconnection_event:
  1854. self._disconnection_event.set()
  1855. # If we intentionally closed the socket for stale reconnect, don't broadcast
  1856. # another state change — check_staleness() already set connected=False and
  1857. # notified the UI. Just log and let paho auto-reconnect.
  1858. if self._stale_reconnecting:
  1859. logger.info(
  1860. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  1861. self.serial_number,
  1862. rc,
  1863. )
  1864. return
  1865. # Ignore spurious disconnect callbacks if we've received a message recently
  1866. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  1867. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  1868. # — only suppress when rc indicates a clean/normal disconnect.
  1869. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  1870. time_since_last_message = time.time() - self._last_message_time
  1871. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  1872. logger.debug(
  1873. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  1874. )
  1875. return
  1876. # Carry the last CONNACK refusal into the disconnect line. paho reports
  1877. # the drop that follows a refused CONNACK as "Unspecified error", so on
  1878. # its own this line says nothing useful about a printer that is looping
  1879. # on bad credentials — and this is the line that fills a support bundle
  1880. # (#2698).
  1881. if self.last_connect_error:
  1882. logger.warning(
  1883. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  1884. self.serial_number,
  1885. rc,
  1886. disconnect_flags,
  1887. self.last_connect_error_name,
  1888. )
  1889. else:
  1890. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  1891. # Detect if request topic subscription caused the disconnect.
  1892. # If we just subscribed and got disconnected before any SUBACK confirmation,
  1893. # the broker likely killed the connection due to the unauthorized subscription.
  1894. if (
  1895. self._request_topic_sub_time > 0
  1896. and not self._request_topic_confirmed
  1897. and time.time() - self._request_topic_sub_time < 10.0
  1898. # A disconnect we asked for says nothing about the subscription.
  1899. and self._disconnection_event is None
  1900. ):
  1901. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  1902. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  1903. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  1904. logger.warning(
  1905. "[%s] Disconnected shortly after request topic subscription %d times. "
  1906. "Disabling request topic for this printer — ams_mapping capture from "
  1907. "slicer-initiated prints is unavailable, and their filament will be "
  1908. "attributed from the printer's own tray reporting instead.",
  1909. self.serial_number,
  1910. failures,
  1911. )
  1912. self._request_topic_supported = False
  1913. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1914. else:
  1915. logger.info(
  1916. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  1917. "Retrying it on the next connection before giving up.",
  1918. self.serial_number,
  1919. failures,
  1920. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  1921. )
  1922. self._request_topic_sub_mid = None
  1923. self._request_topic_sub_time = 0.0
  1924. self.state.connected = False
  1925. if self.on_state_change:
  1926. self.on_state_change(self.state)
  1927. def _log_message(self, topic: str, direction: str, raw: str) -> None:
  1928. """Record a message for the MQTT Debug log, as it arrived.
  1929. Parsed again from the raw text rather than shared with the handlers:
  1930. processing keeps the payload's "print" dict as the new raw_data and
  1931. writes Bambuddy's merged AMS list and other state into it, so a shared
  1932. dict showed Bambuddy's state instead of what the printer sent (#3356).
  1933. """
  1934. self._message_log.append(
  1935. MQTTLogEntry(
  1936. timestamp=datetime.now(timezone.utc).isoformat(),
  1937. topic=topic,
  1938. direction=direction,
  1939. payload=json.loads(raw),
  1940. )
  1941. )
  1942. def _on_message(self, client, userdata, msg):
  1943. for handler in self._raw_message_handlers:
  1944. try:
  1945. handler(msg.topic, msg.payload)
  1946. except Exception:
  1947. logger.exception(
  1948. "[%s] raw-message handler crashed for topic=%s",
  1949. self.serial_number,
  1950. msg.topic,
  1951. )
  1952. try:
  1953. try:
  1954. raw = msg.payload.decode()
  1955. except UnicodeDecodeError:
  1956. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  1957. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  1958. raw = msg.payload.decode(errors="replace")
  1959. logger.warning(
  1960. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  1961. self.serial_number,
  1962. msg.topic,
  1963. len(msg.payload),
  1964. )
  1965. payload = json.loads(raw)
  1966. # Track last message time - receiving a message proves we're connected
  1967. self._last_message_time = time.time()
  1968. self.state.connected = True
  1969. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  1970. if msg.topic == self.topic_publish:
  1971. # Record it before returning. This topic carries every command
  1972. # travelling *to* the printer, including the ones Bambu Studio
  1973. # sends, and it used to be the one thing an MQTT capture could
  1974. # never show -- which is why "what does Studio put in the drying
  1975. # command?" had no answer from a user's log (#2774). Filed as
  1976. # "out" so the direction filter groups it with our own commands
  1977. # rather than with printer telemetry; anything we send
  1978. # lands twice, once on publish and once on the
  1979. # broker's echo, and the pair is itself evidence the command
  1980. # reached the broker.
  1981. if self._logging_enabled:
  1982. self._log_message(msg.topic, "out", raw)
  1983. self._handle_request_message(payload)
  1984. return
  1985. # Count status reports per connection so check_staleness() can tell
  1986. # "printer never sent a report" apart from a mid-session quiet gap.
  1987. if msg.topic == self.topic_subscribe:
  1988. self._report_messages_since_connect += 1
  1989. # Only report-topic traffic proves the *printer* is alive — the
  1990. # request topic also carries slicer/Bambuddy commands.
  1991. if self._state_before_power_off is not None:
  1992. if self._restore_state_after_false_power_off() and self.on_state_change:
  1993. self.on_state_change(self.state)
  1994. # Log message if logging is enabled
  1995. if self._logging_enabled:
  1996. self._log_message(msg.topic, "in", raw)
  1997. self._process_message(payload)
  1998. except json.JSONDecodeError:
  1999. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  2000. @property
  2001. def _captured_ams_mapping(self):
  2002. """The ams_mapping captured from the current print's command.
  2003. Kept on the state so the status shows it (the slot pills, #1762): the
  2004. printer's own push almost never carries one.
  2005. """
  2006. return self.state.print_ams_mapping
  2007. @_captured_ams_mapping.setter
  2008. def _captured_ams_mapping(self, mapping) -> None:
  2009. self.state.print_ams_mapping = mapping
  2010. def _handle_request_message(self, data: dict) -> None:
  2011. """Intercept print commands on the request topic to capture ams_mapping."""
  2012. print_data = data.get("print", {})
  2013. if not isinstance(print_data, dict):
  2014. return
  2015. command = print_data.get("command", "")
  2016. if command == "project_file":
  2017. # Where the dispatcher put the sliced file. Captured for every
  2018. # project_file, ours included: we publish to this same topic and
  2019. # subscribe to it, so whoever dispatched last wins, which is exactly
  2020. # the print the archive lookup is about to go looking for (#2780).
  2021. url = print_data.get("url")
  2022. if isinstance(url, str) and url:
  2023. self.state.current_project_url = url
  2024. self.state.last_project_url = url
  2025. if "ams_mapping" in print_data:
  2026. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2027. self._captured_mapping_url = url if isinstance(url, str) else None
  2028. logger.info(
  2029. "[%s] Captured ams_mapping from print command: %s",
  2030. self.serial_number,
  2031. self._captured_ams_mapping,
  2032. )
  2033. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  2034. # slicer-launched project_file passes through the request topic,
  2035. # log the full payload so we can diff Studio's field set against
  2036. # ours.
  2037. #
  2038. # This used to read `sequence_id != "20000"`, on the belief that
  2039. # 20000 was ours alone. It is not: 20000 is the slicer convention
  2040. # Bambuddy adopted -- bind_server documents the slicer sending it
  2041. # during detect, and measured on the wire OrcaSlicer dispatched
  2042. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  2043. # counting up from the same base. So the test swallowed whichever
  2044. # slicer dispatch happened to land on 20000, which on a fresh
  2045. # slicer start is the first one. Match our own dispatch instead.
  2046. if self._project_file_key(print_data) == self._own_project_file_key:
  2047. self._own_project_file_key = None
  2048. else:
  2049. logger.info(
  2050. "[%s] External project_file payload: %s",
  2051. self.serial_number,
  2052. json.dumps(print_data),
  2053. )
  2054. def _capture_report_project_file(self, print_data: dict) -> None:
  2055. """Read a print's destination off a ``project_file`` *response* (#1820).
  2056. ``_handle_request_message`` only ever sees the request topic, so a print
  2057. started from the printer's own touchscreen -- which publishes nothing --
  2058. left ``current_project_url`` at None, and the storage verdict fell
  2059. through to the ``sdcard`` fallback for the one case it was written for.
  2060. On an H2S that flag is True (its "card" is the internal eMMC), so the
  2061. verdict came back reachable and the ~110-connection sweep ran in full.
  2062. The printer does announce it: an unsolicited ``project_file`` response
  2063. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  2064. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  2065. This also covers an install nobody had in view: some brokers refuse the
  2066. request-topic subscription, and on those no print of any kind has ever
  2067. populated the field.
  2068. Both kinds of ``project_file`` on this topic are read -- the printer's
  2069. echo of a dispatch and a screen start -- because both name the
  2070. destination in ``url``, which is the only thing the verdict wants. What
  2071. this must NOT do is reuse ``_handle_request_message``'s "External
  2072. project_file payload" diagnostic: our own dispatch is echoed on *both*
  2073. topics, the request-topic echo arrives first and clears
  2074. ``_own_project_file_key``, so by the time this frame lands the key is
  2075. already None and every Bambuddy-started print would log itself as
  2076. someone else's.
  2077. """
  2078. # Same shape as _handle_request_message: the frame is whatever the
  2079. # printer put on the wire, and this is the first thing to touch it.
  2080. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  2081. return
  2082. # A refused dispatch names a file that was never written. Acting on it
  2083. # would pin an archive on a destination nothing ever went to. Logged:
  2084. # nothing else says the printer refused a print it was sent.
  2085. result = str(print_data.get("result") or "")
  2086. if result.upper() != "SUCCESS":
  2087. logger.info(
  2088. "[%s] Printer refused a print start (project_file): result=%s reason=%s url=%s",
  2089. self.serial_number,
  2090. result,
  2091. print_data.get("reason"),
  2092. print_data.get("url"),
  2093. )
  2094. self.last_start_refusal = (result, print_data.get("reason"))
  2095. return
  2096. url = print_data.get("url")
  2097. if not isinstance(url, str) or not url:
  2098. return
  2099. if self.state.current_project_url != url:
  2100. logger.info(
  2101. "[%s] Print destination from the report topic: %s",
  2102. self.serial_number,
  2103. url,
  2104. )
  2105. self.state.current_project_url = url
  2106. self.state.last_project_url = url
  2107. # On a screen start this frame is the only place the mapping appears --
  2108. # no slicer ever sent one. Fill a gap only: when the request topic
  2109. # already captured this print's mapping that copy is the slicer's own,
  2110. # and the echo can arrive without the field at all. A mapping captured
  2111. # for another destination is from a dispatch that never ran (refused,
  2112. # or cancelled before it started, so no completion cleared it).
  2113. stale = self._captured_ams_mapping is not None and self._captured_mapping_url != url
  2114. if (self._captured_ams_mapping is None or stale) and isinstance(print_data.get("ams_mapping"), list):
  2115. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2116. self._captured_mapping_url = url
  2117. logger.info(
  2118. "[%s] Captured ams_mapping from print response: %s",
  2119. self.serial_number,
  2120. self._captured_ams_mapping,
  2121. )
  2122. def _resolve_captured_mapping(self, print_data: dict) -> object:
  2123. """The ``ams_mapping`` of a project_file, with external spools resolved
  2124. from its ``ams_mapping2`` (#3166)."""
  2125. from backend.app.utils.printer_models import is_dual_nozzle_model
  2126. return resolve_external_spools_in_mapping(
  2127. print_data.get("ams_mapping"),
  2128. print_data.get("ams_mapping2"),
  2129. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  2130. )
  2131. @staticmethod
  2132. def _project_file_key(print_data: dict) -> str:
  2133. """Identity of a project_file dispatch, for telling ours from a slicer's.
  2134. Sequence id alone cannot do it -- every slicer counts up from the same
  2135. 20000 -- so this also carries the file and its destination, which differ
  2136. between any two real dispatches.
  2137. """
  2138. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  2139. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  2140. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  2141. The state dumps in the push_status handler fire whenever their field is
  2142. *present* in the frame — and a full push_status carries every field, so
  2143. they fire on every frame regardless of whether anything changed. Several
  2144. even say "updated" or "changes" in their own comment while doing nothing
  2145. of the sort.
  2146. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  2147. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  2148. minutes: the reporter enabled debug logging as asked and the support
  2149. bundle came back holding under five minutes of history, almost none of it
  2150. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  2151. these dumps.
  2152. Deduplicating on the value keeps every transition — which is the only part
  2153. anyone reads these lines for — and drops the steady-state repetition.
  2154. ``value`` must capture everything interpolated into ``msg``, or a change
  2155. will be swallowed; pass a tuple when the message renders several fields.
  2156. """
  2157. if not logger.isEnabledFor(logging.DEBUG):
  2158. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  2159. # and these clients outlive the toggle. Letting INFO-level frames warm
  2160. # the cache would be self-defeating: the operator turns debug on
  2161. # precisely to see the printer's current state, and a cache already
  2162. # holding every steady-state value would suppress that baseline until
  2163. # something happened to change. On an idle printer the bundle would
  2164. # come back with none of these lines at all.
  2165. #
  2166. # So while debug is off we record nothing and drop whatever we had.
  2167. # Every enable then starts cold and dumps a full baseline on the next
  2168. # frame, exactly as it did before this method existed.
  2169. self._debug_last.clear()
  2170. return
  2171. if self._debug_last.get(key) == value:
  2172. return
  2173. self._debug_last[key] = value
  2174. logger.debug(msg, *args)
  2175. def _process_message(self, payload: dict):
  2176. """Process incoming MQTT message from printer."""
  2177. # Handle top-level AMS data (comes outside of "print" key)
  2178. # Wrap in try/except to prevent breaking the MQTT connection
  2179. if "ams" in payload:
  2180. try:
  2181. self._snow_in_frame = False # a bare AMS frame carries no extruder data
  2182. self._handle_ams_data(payload["ams"])
  2183. except Exception as e:
  2184. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  2185. # Handle xcam data (camera settings and AI detection) at top level
  2186. if "xcam" in payload:
  2187. xcam_data = payload["xcam"]
  2188. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  2189. self._parse_xcam_data(xcam_data)
  2190. # Fire state change callback for top-level xcam (not nested in "print")
  2191. if "print" not in payload and self.on_state_change:
  2192. self.on_state_change(self.state)
  2193. # Handle system responses (accessories info, etc.)
  2194. if "system" in payload:
  2195. system_data = payload["system"]
  2196. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  2197. self._handle_system_response(system_data)
  2198. # Handle info responses (firmware version info from get_version command)
  2199. if "info" in payload:
  2200. info_data = payload["info"]
  2201. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2202. self._handle_version_info(info_data)
  2203. # Parse WiFi signal at top level (some printers send it here)
  2204. if "wifi_signal" in payload:
  2205. wifi_signal = payload["wifi_signal"]
  2206. if isinstance(wifi_signal, (int, float)):
  2207. self.state.wifi_signal = int(wifi_signal)
  2208. elif isinstance(wifi_signal, str):
  2209. try:
  2210. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2211. except ValueError:
  2212. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2213. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2214. from backend.app.utils.printer_models import has_ethernet
  2215. if has_ethernet(self.model):
  2216. self.state.wired_network = self.state.wifi_signal == -90
  2217. # Parse developer LAN mode from top-level "fun" field
  2218. # Some firmware versions send "fun" at the top level, others inside "print"
  2219. if "fun" in payload:
  2220. try:
  2221. fun_val = payload["fun"]
  2222. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2223. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2224. except (ValueError, TypeError):
  2225. pass
  2226. if "print" in payload:
  2227. print_data = payload["print"]
  2228. # Before anything reads the state: this is where a touchscreen-
  2229. # started print announces where its file lives, and the print-start
  2230. # handler asks ~2 s later (#1820).
  2231. self._capture_report_project_file(print_data)
  2232. # Check if xcam is nested inside print data
  2233. if "xcam" in print_data:
  2234. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2235. self._parse_xcam_data(print_data["xcam"])
  2236. # Log when we see gcode_state changes
  2237. if "gcode_state" in print_data:
  2238. logger.debug(
  2239. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2240. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2241. )
  2242. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2243. # new-protocol printers. Verified against OrcaSlicer's
  2244. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2245. # and live H2D ON/OFF capture 2026-06-20.
  2246. #
  2247. # Families without cfg (P1S, P1P, A1, A1 Mini) carry it in home_flag
  2248. # bit 10 (#3259). Trusted once a full status report (the same
  2249. # >30-key test as the developer-mode probe) arrived without cfg;
  2250. # from then on every status frame that carries home_flag is read,
  2251. # so a toggle in the slicer shows up without a Force Refresh (P1S
  2252. # capture: each toggle came in a 4-6 key update frame). Before
  2253. # that nothing is read from small frames, so a cfg printer can't
  2254. # be misread from a frame that arrives ahead of its first cfg.
  2255. # Printers that send cfg keep reading it alone.
  2256. #
  2257. # Hold-timer guard: when the user just toggled via the badge, the
  2258. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2259. # for ~3 s before the firmware reflects the change. Without this
  2260. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2261. # Only from a status frame: a project_file ack echoes our own
  2262. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2263. # stuck on every family that doesn't repeat `cfg` in its periodic
  2264. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2265. new_backup = None
  2266. if is_printer_status_frame(print_data):
  2267. if "cfg" in print_data:
  2268. self._backup_cfg_seen = True
  2269. new_backup = parse_ams_filament_backup_from_cfg(print_data["cfg"])
  2270. elif not self._backup_cfg_seen:
  2271. if len(print_data) > 30:
  2272. self._backup_home_flag_trusted = True
  2273. if self._backup_home_flag_trusted:
  2274. new_backup = parse_ams_filament_backup_from_home_flag(print_data.get("home_flag"))
  2275. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2276. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2277. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2278. logger.debug(
  2279. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2280. self.serial_number,
  2281. time.time() - hold_start,
  2282. )
  2283. else:
  2284. logger.info(
  2285. "[%s] AMS Filament Backup: %s",
  2286. self.serial_number,
  2287. "ON" if new_backup else "OFF",
  2288. )
  2289. self.state.ams_filament_backup = new_backup
  2290. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2291. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2292. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2293. if not self._is_dual_nozzle and "device" in print_data:
  2294. dev = print_data.get("device")
  2295. if isinstance(dev, dict):
  2296. ext_info = dev.get("extruder", {}).get("info", [])
  2297. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2298. self._is_dual_nozzle = True
  2299. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2300. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2301. # out of the AMS info bits, but only means anything once we know a
  2302. # switch is installed. Parsing them the other way round would lose
  2303. # the binding on every frame where the two arrive together.
  2304. self._parse_fila_switch(print_data)
  2305. # Before _handle_ams_data too: an H2D's tray_now is a bare slot that
  2306. # this frame's extruder data places (which nozzle, which AMS).
  2307. self._snow_in_frame = self._parse_extruder_position(print_data)
  2308. self._parse_extruder_slots(print_data)
  2309. # Handle AMS data that comes inside print key
  2310. if "ams" in print_data:
  2311. try:
  2312. self._handle_ams_data(print_data["ams"])
  2313. except Exception as e:
  2314. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2315. # Handle vir_slot (H2-series external spool data) — list of external trays
  2316. # Process vir_slot FIRST so it takes priority over vt_tray
  2317. if "vir_slot" in print_data:
  2318. vir_slot = print_data["vir_slot"]
  2319. if isinstance(vir_slot, list) and vir_slot:
  2320. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2321. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2322. # Remap id=255→254 for single-slot printers so active detection works.
  2323. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2324. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2325. vir_slot[0]["id"] = "254"
  2326. self.state.raw_data["vt_tray"] = vir_slot
  2327. # Handle vt_tray (virtual tray / external spool) data
  2328. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2329. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2330. # which would overwrite the correct multi-slot vir_slot data)
  2331. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2332. vt_tray = print_data["vt_tray"]
  2333. existing = self.state.raw_data.get("vt_tray")
  2334. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2335. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2336. pass # Keep the vir_slot data
  2337. else:
  2338. if isinstance(vt_tray, dict):
  2339. vt_tray = [vt_tray]
  2340. self.state.raw_data["vt_tray"] = vt_tray
  2341. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2342. # units, and _handle_ams_data runs before this block — so a change
  2343. # to the external spool alone (e.g. swapping generic TPU for generic
  2344. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2345. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2346. # external-spool identity changes here and fire the same callback.
  2347. self._maybe_trigger_external_spool_change()
  2348. # Parse ams_status directly from print data (NOT from print.ams)
  2349. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2350. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2351. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2352. if "ams_status" in print_data:
  2353. raw_ams_status = print_data["ams_status"]
  2354. if isinstance(raw_ams_status, str):
  2355. try:
  2356. self.state.ams_status = int(raw_ams_status)
  2357. except ValueError:
  2358. self.state.ams_status = 0
  2359. else:
  2360. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2361. # Compute main and sub status
  2362. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2363. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2364. # Log when ams_status changes (for filament change tracking debug)
  2365. self._debug_on_change(
  2366. "ams_status:print",
  2367. self.state.ams_status,
  2368. "[%s] ams_status: %s (main=%s, sub=%s)",
  2369. self.serial_number,
  2370. self.state.ams_status,
  2371. self.state.ams_status_main,
  2372. self.state.ams_status_sub,
  2373. )
  2374. # Check for command responses
  2375. if "command" in print_data:
  2376. cmd = print_data.get("command")
  2377. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2378. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2379. # INFO, not debug: this is the printer's verdict on a write
  2380. # the user just made, and it was invisible in support
  2381. # bundles for as long as it sat at DEBUG (#2718). Same
  2382. # reasoning as ams_filament_drying below.
  2383. logger.info(
  2384. "[%s] %s response: result=%s reason=%s seq=%s",
  2385. self.serial_number,
  2386. cmd,
  2387. print_data.get("result"),
  2388. print_data.get("reason", ""),
  2389. print_data.get("sequence_id"),
  2390. )
  2391. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2392. ack_seq = str(print_data.get("sequence_id", ""))
  2393. if ack_seq in self._pending_cali_acks:
  2394. self._pending_cali_acks[ack_seq] = print_data
  2395. elif cmd == "skip_objects":
  2396. self._handle_skip_objects_answer(print_data)
  2397. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2398. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2399. # A refused ams_filament_setting is the printer's verdict on
  2400. # a write the user just made, and at DEBUG it never reached
  2401. # a support bundle: #2756 reported six manual Configure Slot
  2402. # attempts on an X1C, each returning HTTP 200 with the
  2403. # read-back still showing the previous profile, and no
  2404. # record of what the printer said about any of them. Same
  2405. # promotion as extrusion_cali_set (#2718) and
  2406. # ams_filament_drying (#1447) — but only on a non-success,
  2407. # because unlike those two this command is not rare: every
  2408. # spool assignment and every K-profile re-apply sends one,
  2409. # so promoting each ack would bury the interesting line.
  2410. #
  2411. # The developer-mode probe is excluded. It sends this exact
  2412. # command to the external slot precisely to see it refused
  2413. # on P1 firmware, so its failure is a normal reading rather
  2414. # than a fault. Its response is still matched below (this
  2415. # runs before _handle_dev_mode_probe_response clears the
  2416. # seq), and user-initiated commands can't be mistaken for
  2417. # it — they publish a hardcoded sequence_id of "0".
  2418. result = print_data.get("result")
  2419. is_dev_mode_probe = (
  2420. self._dev_mode_probe_seq is not None
  2421. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2422. )
  2423. # extrusion_cali_sel too (FW-C3): every RFID re-read
  2424. # re-applies the spool's K-profile and logs "Applied PA
  2425. # profile", so its refusal must reach the bundle beside it.
  2426. # The printer's word, not a verdict: the extrusion_cali_*
  2427. # acks are known to say "fail" for writes that applied.
  2428. if not is_dev_mode_probe and isinstance(result, str) and result.lower() != "success":
  2429. logger.info(
  2430. "[%s] %s refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2431. self.serial_number,
  2432. cmd,
  2433. result,
  2434. print_data.get("reason", ""),
  2435. print_data.get("ams_id"),
  2436. print_data.get("tray_id"),
  2437. )
  2438. # AMS drying responses are rare (user-initiated only) and the
  2439. # full payload — including `result` and any `reason` code —
  2440. # is the only way to diagnose silent rejections like #1447.
  2441. # INFO level so the body lands in support bundles by default.
  2442. elif cmd == "ams_filament_drying":
  2443. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2444. # RFID re-reads are user-initiated and rare, and a refusal was
  2445. # invisible until #3206 (X1Plus answering FAIL / ERROR STATE).
  2446. # gcode_line acks are only of interest when they answer our
  2447. # M620 R fallback, so those are matched by sequence_id alone.
  2448. ack_seq = str(print_data.get("sequence_id", ""))
  2449. if (
  2450. cmd in ("ams_get_rfid", "gcode_line")
  2451. and ack_seq in self._pending_rfid_acks
  2452. and "result" in print_data
  2453. ):
  2454. logger.info(
  2455. "[%s] %s response: result=%s reason=%s seq=%s",
  2456. self.serial_number,
  2457. cmd,
  2458. print_data.get("result"),
  2459. print_data.get("reason", ""),
  2460. ack_seq,
  2461. )
  2462. self._pending_rfid_acks[ack_seq] = print_data
  2463. # Check for developer mode probe response
  2464. if (
  2465. cmd == "ams_filament_setting"
  2466. and self._dev_mode_probe_seq is not None
  2467. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2468. ):
  2469. self._handle_dev_mode_probe_response(print_data)
  2470. # Track user-initiated ams_filament_setting responses (#887
  2471. # zombie detection). Reset both the timer AND the unanswered
  2472. # counter on ANY response — the response proves the channel is
  2473. # alive, so the counter must not stay armed even when the
  2474. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2475. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2476. # caused #1164: one sluggish response (>10s) would set the
  2477. # counter to 1 and zero the timer; the late response arrived
  2478. # but was ignored by this branch (timer is 0); the counter
  2479. # stayed at 1 indefinitely; the very next slow response —
  2480. # possibly hours later, on a totally unrelated command — would
  2481. # take it to 2 and force-reconnect, surfacing as "filament
  2482. # config doesn't reach the printer ~6 changes in".
  2483. elif cmd == "ams_filament_setting":
  2484. self._last_ams_cmd_time = 0.0
  2485. self._ams_cmd_unanswered = 0
  2486. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2487. if is_kprofile_response:
  2488. self._handle_kprofile_response(print_data)
  2489. # An extrusion_cali_get response echoes the *requested* nozzle
  2490. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2491. # installed hardware. Feeding it to _update_state clobbered the real
  2492. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2493. # which then failed the #1899 dispatch guard. The response carries no
  2494. # status telemetry, so skip it; the true nozzle comes from pushall.
  2495. # (Same reasoning as get_accessories in _handle_system_response.)
  2496. # The answers to K-profile writes and selections echo the diameter
  2497. # the command named in the same way, so none of them is status.
  2498. if print_data.get("command") not in _KPROFILE_COMMAND_ANSWERS:
  2499. self._update_state(print_data)
  2500. def _handle_system_response(self, data: dict):
  2501. """Handle system responses including accessories info.
  2502. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2503. The correct nozzle data comes from push_status, so we don't update
  2504. nozzle type/diameter from get_accessories. We just log the response
  2505. for debugging purposes.
  2506. """
  2507. command = data.get("command")
  2508. if command == "get_accessories":
  2509. # Log response for debugging - but DON'T use it to update nozzle data
  2510. # because it returns stale values (e.g., 'stainless_steel' when the
  2511. # actual nozzle is 'HH01' hardened steel high-flow)
  2512. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2513. def _handle_version_info(self, data: dict):
  2514. """Handle version info response from get_version command.
  2515. Parses firmware version from the 'ota' module in the module list.
  2516. Also extracts AMS unit firmware versions from AMS modules and stores
  2517. them on the corresponding AMS unit in raw_data so the status route can
  2518. expose them to the frontend.
  2519. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2520. - ``ams/<id>`` – original AMS
  2521. - ``ams_f1/<id>`` – AMS Lite (#3348)
  2522. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2523. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2524. Message format:
  2525. {
  2526. "command": "get_version",
  2527. "module": [
  2528. {"name": "ota", "sw_ver": "01.08.05.00"},
  2529. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2530. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2531. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2532. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2533. ...
  2534. ]
  2535. }
  2536. """
  2537. modules = data.get("module", [])
  2538. if not isinstance(modules, list):
  2539. return
  2540. state_changed = False
  2541. for module in modules:
  2542. if not isinstance(module, dict):
  2543. continue
  2544. if module.get("name") == "ota":
  2545. version = module.get("sw_ver")
  2546. if version:
  2547. old_version = self.state.firmware_version
  2548. self.state.firmware_version = version
  2549. if old_version != version:
  2550. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2551. state_changed = True
  2552. break
  2553. # Extract AMS unit firmware versions from AMS modules.
  2554. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2555. # Always cache regardless of whether AMS data has arrived yet — get_version
  2556. # often arrives before the first push_status, so caching must be unconditional.
  2557. ams_raw = self.state.raw_data.get("ams")
  2558. for module in modules:
  2559. if not isinstance(module, dict):
  2560. continue
  2561. name = module.get("name", "")
  2562. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2563. continue
  2564. try:
  2565. # The A2L's AMS Lite is unit 16 here but stored as 6, like
  2566. # everywhere else it is ingested.
  2567. ams_id = normalize_am_unit_id(int(name.split("/", 1)[1]))
  2568. except (ValueError, IndexError):
  2569. continue
  2570. sw_ver = module.get("sw_ver", "")
  2571. sn = module.get("sn", "")
  2572. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2573. module_type = name.split("/", 1)[0]
  2574. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2575. if sw_ver or sn or module_type:
  2576. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2577. state_changed = True
  2578. # Also directly update any AMS unit already present in raw_data
  2579. if ams_raw and isinstance(ams_raw, list):
  2580. for ams_unit in ams_raw:
  2581. if not isinstance(ams_unit, dict):
  2582. continue
  2583. try:
  2584. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2585. except (ValueError, TypeError):
  2586. unit_id = None
  2587. if unit_id == ams_id:
  2588. if sw_ver:
  2589. ams_unit["sw_ver"] = sw_ver
  2590. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2591. # Only set sn from version info if not already present in AMS data
  2592. if sn and not ams_unit.get("sn"):
  2593. ams_unit["sn"] = sn
  2594. if module_type:
  2595. ams_unit["module_type"] = module_type
  2596. break
  2597. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2598. # included in the broadcast (not just the printer firmware version).
  2599. if state_changed and self.on_state_change:
  2600. self.on_state_change(self.state)
  2601. # Warn if any AMS unit is still missing serial number or firmware version
  2602. # after processing the version info response. Warn only once per connection
  2603. # to avoid repeated noise on older firmware that doesn't report these fields.
  2604. if ams_raw and isinstance(ams_raw, list):
  2605. for ams_unit in ams_raw:
  2606. if not isinstance(ams_unit, dict):
  2607. continue
  2608. ams_id = ams_unit.get("id", "?")
  2609. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2610. key = (ams_id, "sn")
  2611. if key not in self._ams_version_warned:
  2612. self._ams_version_warned.add(key)
  2613. logger.warning(
  2614. "[%s] AMS unit %s: serial number not available in version info",
  2615. self.serial_number,
  2616. ams_id,
  2617. )
  2618. if not ams_unit.get("sw_ver"):
  2619. key = (ams_id, "sw_ver")
  2620. if key not in self._ams_version_warned:
  2621. self._ams_version_warned.add(key)
  2622. logger.warning(
  2623. "[%s] AMS unit %s: firmware version not available in version info",
  2624. self.serial_number,
  2625. ams_id,
  2626. )
  2627. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2628. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2629. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2630. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2631. sw_ver/sn fields without overwriting values already present.
  2632. """
  2633. if not ams_list or not isinstance(ams_list, list):
  2634. return
  2635. cache = self._ams_version_cache
  2636. if not cache:
  2637. return
  2638. for unit in ams_list:
  2639. if not isinstance(unit, dict):
  2640. continue
  2641. raw_id = unit.get("id")
  2642. try:
  2643. unit_id = int(raw_id) if raw_id is not None else None
  2644. except (ValueError, TypeError):
  2645. unit_id = None
  2646. if unit_id is None:
  2647. continue
  2648. cached = cache.get(unit_id)
  2649. if not cached:
  2650. continue
  2651. sw_ver = cached.get("sw_ver") or ""
  2652. sn = cached.get("sn") or ""
  2653. if sw_ver and not unit.get("sw_ver"):
  2654. unit["sw_ver"] = sw_ver
  2655. # Only set sn if not already present in AMS data
  2656. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2657. unit["sn"] = sn
  2658. module_type = cached.get("module_type") or ""
  2659. if module_type and not unit.get("module_type"):
  2660. unit["module_type"] = module_type
  2661. def _parse_xcam_data(self, xcam_data):
  2662. """Parse xcam data for camera settings and AI detection options."""
  2663. if not isinstance(xcam_data, dict):
  2664. return
  2665. current_time = time.time()
  2666. # Helper to check if we should accept incoming value for a module
  2667. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2668. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2669. """Check if we should accept an incoming xcam value.
  2670. OrcaSlicer pattern: After sending a command, ignore incoming data
  2671. for 3 seconds. After that, accept whatever the printer sends.
  2672. """
  2673. if module_name not in self._xcam_hold_start:
  2674. return True # No hold timer, accept incoming
  2675. hold_start = self._xcam_hold_start[module_name]
  2676. elapsed = current_time - hold_start
  2677. if elapsed > self._xcam_hold_time:
  2678. # Hold timer expired - accept incoming and clear hold
  2679. del self._xcam_hold_start[module_name]
  2680. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2681. return True
  2682. # Within hold period - ignore incoming data
  2683. logger.debug(
  2684. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2685. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2686. )
  2687. return False
  2688. # Log all xcam fields for debugging
  2689. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2690. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2691. # fields (spaghetti_detector, etc.) are often stale/cached.
  2692. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2693. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2694. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2695. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2696. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2697. # Sensitivity values: 0=low, 1=medium, 2=high
  2698. if "cfg" in xcam_data:
  2699. cfg = xcam_data["cfg"]
  2700. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2701. def decode_detector(start_bit):
  2702. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2703. sens_bits = (cfg >> start_bit) & 0x3
  2704. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2705. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2706. return enabled, sensitivity
  2707. # Spaghetti detector (bits 5-7)
  2708. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2709. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2710. old_value = self.state.print_options.spaghetti_detector
  2711. if cfg_spaghetti != old_value:
  2712. logger.debug(
  2713. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2714. )
  2715. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2716. # Check hold timer for sensitivity before accepting
  2717. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2718. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2719. logger.debug(
  2720. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2721. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2722. )
  2723. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2724. else:
  2725. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2726. elapsed = current_time - hold_start
  2727. if elapsed <= self._xcam_hold_time:
  2728. logger.debug(
  2729. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2730. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2731. )
  2732. else:
  2733. # Hold expired - accept from cfg
  2734. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2735. logger.debug(
  2736. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2737. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2738. )
  2739. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2740. del self._xcam_hold_start["halt_print_sensitivity"]
  2741. # Pileup detector (bits 8-10)
  2742. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2743. if should_accept_value("pileup_detector", cfg_pileup):
  2744. if cfg_pileup != self.state.print_options.pileup_detector:
  2745. logger.debug(
  2746. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2747. )
  2748. self.state.print_options.pileup_detector = cfg_pileup
  2749. # Pileup sensitivity with hold timer
  2750. if "pileup_sensitivity" not in self._xcam_hold_start:
  2751. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2752. logger.debug(
  2753. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2754. )
  2755. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2756. else:
  2757. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2758. elapsed = current_time - hold_start
  2759. if elapsed > self._xcam_hold_time:
  2760. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2761. logger.debug(
  2762. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2763. )
  2764. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2765. del self._xcam_hold_start["pileup_sensitivity"]
  2766. # Clump/nozzle clumping detector (bits 11-13)
  2767. cfg_clump, cfg_clump_sens = decode_detector(11)
  2768. if should_accept_value("clump_detector", cfg_clump):
  2769. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2770. logger.debug(
  2771. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2772. )
  2773. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2774. # Clump sensitivity with hold timer
  2775. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2776. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2777. logger.debug(
  2778. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2779. )
  2780. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2781. else:
  2782. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2783. elapsed = current_time - hold_start
  2784. if elapsed > self._xcam_hold_time:
  2785. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2786. logger.debug(
  2787. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2788. )
  2789. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2790. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2791. # Airprint detector (bits 14-16)
  2792. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2793. if should_accept_value("airprint_detector", cfg_airprint):
  2794. if cfg_airprint != self.state.print_options.airprint_detector:
  2795. logger.debug(
  2796. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2797. )
  2798. self.state.print_options.airprint_detector = cfg_airprint
  2799. # Airprint sensitivity with hold timer
  2800. if "airprint_sensitivity" not in self._xcam_hold_start:
  2801. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2802. logger.debug(
  2803. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2804. )
  2805. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2806. else:
  2807. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2808. elapsed = current_time - hold_start
  2809. if elapsed > self._xcam_hold_time:
  2810. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2811. logger.debug(
  2812. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2813. )
  2814. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2815. del self._xcam_hold_start["airprint_sensitivity"]
  2816. # Camera settings
  2817. if "ipcam_record" in xcam_data:
  2818. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2819. if "timelapse" in xcam_data:
  2820. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2821. # Track if timelapse was ever active during this print
  2822. if self.state.timelapse and self._was_running:
  2823. self._timelapse_during_print = True
  2824. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2825. if "print_halt" in xcam_data:
  2826. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  2827. # Skip halt_print_sensitivity field - it's always stale ("medium")
  2828. # We read the actual sensitivity from cfg bits 5-6 above
  2829. if "first_layer_inspector" in xcam_data:
  2830. new_value = bool(xcam_data.get("first_layer_inspector"))
  2831. if should_accept_value("first_layer_inspector", new_value):
  2832. self.state.print_options.first_layer_inspector = new_value
  2833. if "printing_monitor" in xcam_data:
  2834. new_value = bool(xcam_data.get("printing_monitor"))
  2835. if should_accept_value("printing_monitor", new_value):
  2836. self.state.print_options.printing_monitor = new_value
  2837. if "buildplate_marker_detector" in xcam_data:
  2838. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  2839. if should_accept_value("buildplate_marker_detector", new_value):
  2840. self.state.print_options.buildplate_marker_detector = new_value
  2841. if "allow_skip_parts" in xcam_data:
  2842. new_value = bool(xcam_data.get("allow_skip_parts"))
  2843. if should_accept_value("allow_skip_parts", new_value):
  2844. self.state.print_options.allow_skip_parts = new_value
  2845. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  2846. # individual boolean fields (which are not sent by the printer)
  2847. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  2848. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  2849. if "auto_recovery_step_loss" in xcam_data:
  2850. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  2851. if "filament_tangle_detect" in xcam_data:
  2852. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  2853. @staticmethod
  2854. def _resolve_local_slot_from_mapping(
  2855. local_slot: int, mapping_raw: list | None, units: list[int] | None = None
  2856. ) -> int | None:
  2857. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  2858. The MQTT mapping field is an array of snow-encoded values:
  2859. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  2860. Finds entries where the local slot matches, then computes the global tray ID.
  2861. When several match and ``units`` is given (the AMS units on the active
  2862. extruder of a dual-nozzle printer), only those units' trays count.
  2863. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  2864. """
  2865. if not isinstance(mapping_raw, list) or not mapping_raw:
  2866. return None
  2867. candidates: dict[int, int] = {} # global tray ID -> AMS unit
  2868. for value in mapping_raw:
  2869. if not isinstance(value, int) or value >= 65535:
  2870. continue
  2871. ams_hw_id = value >> 8
  2872. slot = value & 0xFF
  2873. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  2874. candidates[ams_hw_id * 4 + local_slot] = ams_hw_id
  2875. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  2876. candidates[ams_hw_id] = ams_hw_id
  2877. if len(candidates) > 1 and units:
  2878. candidates = {tray: unit for tray, unit in candidates.items() if unit in units}
  2879. if len(candidates) == 1:
  2880. return next(iter(candidates))
  2881. return None
  2882. def _maybe_trigger_external_spool_change(self):
  2883. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  2884. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  2885. an external-spool-only filament swap would otherwise never re-run the
  2886. inventory reconciliation that unlinks a stale ams_id=255 assignment
  2887. (#2575). The reconciliation reads vt_tray from live status itself, so we
  2888. just need to re-fire the callback with the current merged AMS data.
  2889. """
  2890. import hashlib
  2891. vt_tray = self.state.raw_data.get("vt_tray")
  2892. if not isinstance(vt_tray, list):
  2893. return
  2894. # Identity fields only — deliberately exclude `remain` so a print's
  2895. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  2896. fp_parts = [
  2897. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  2898. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  2899. for vt in vt_tray
  2900. if isinstance(vt, dict)
  2901. ]
  2902. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  2903. if vt_hash == self._previous_vt_tray_hash:
  2904. return
  2905. self._previous_vt_tray_hash = vt_hash
  2906. if self.on_ams_change:
  2907. logger.debug(
  2908. "[%s] External spool (vt_tray) changed, triggering sync callback",
  2909. self.serial_number,
  2910. )
  2911. self.on_ams_change(self.state.raw_data.get("ams") or [])
  2912. def _normalize_a2l_am_units(self, ams_list) -> None:
  2913. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  2914. id 16 -> 6 in place, as early as possible, so every downstream reader —
  2915. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  2916. the DB constraint — sees the normalised id and needs no special-casing.
  2917. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  2918. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  2919. both the dict-wrapped and bare-list AMS shapes.
  2920. """
  2921. if not isinstance(ams_list, list):
  2922. return
  2923. for unit in ams_list:
  2924. if not isinstance(unit, dict):
  2925. continue
  2926. try:
  2927. uid = int(unit.get("id"))
  2928. except (TypeError, ValueError):
  2929. continue
  2930. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  2931. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  2932. if not self._has_a2l_am_unit:
  2933. logger.info(
  2934. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  2935. self.serial_number,
  2936. A2L_LITE_NORMALIZED_AMS_ID,
  2937. )
  2938. self._has_a2l_am_unit = True
  2939. def _parse_fila_switch(self, data: dict) -> None:
  2940. """Read the Filament Track Switch block out of a print payload — #1162.
  2941. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  2942. separate from the rest of the state update because ``_handle_ams_data``
  2943. needs the answer before it parses the AMS info bits, and that runs first.
  2944. """
  2945. if not isinstance(data.get("device"), dict):
  2946. return
  2947. fs_data = data["device"].get("fila_switch")
  2948. if not isinstance(fs_data, dict):
  2949. return
  2950. in_raw = fs_data.get("in")
  2951. out_raw = fs_data.get("out")
  2952. self.state.fila_switch = FilaSwitchState(
  2953. installed=True,
  2954. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2955. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2956. stat=int(fs_data.get("stat", 0) or 0),
  2957. info=int(fs_data.get("info", 0) or 0),
  2958. )
  2959. def _parse_extruder_position(self, data: dict) -> bool:
  2960. """Read which nozzle is active and which tray each nozzle holds.
  2961. From ``device.extruder``: ``state`` bit 8 is the active nozzle, each
  2962. ``info`` entry's ``snow`` names its AMS and slot. Run on a frame before
  2963. its AMS block, because an H2D's tray_now is a bare slot that only the
  2964. extruder data of the same frame places. Returns True when the frame
  2965. carried the active nozzle's snow. A malformed value is skipped, never
  2966. raised: this runs ahead of everything else the frame carries.
  2967. """
  2968. device = data.get("device")
  2969. extruder = device.get("extruder") if isinstance(device, dict) else None
  2970. if not isinstance(extruder, dict):
  2971. return False
  2972. try:
  2973. state_val = int(extruder["state"]) if "state" in extruder else None
  2974. except (TypeError, ValueError):
  2975. state_val = None
  2976. if state_val is not None:
  2977. # Extract bit 8 for extruder position
  2978. new_extruder = (state_val >> 8) & 0x1
  2979. if new_extruder != self.state.active_extruder:
  2980. logger.debug(
  2981. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  2982. )
  2983. self.state.active_extruder = new_extruder
  2984. extruder_info = extruder.get("info")
  2985. if not isinstance(extruder_info, list) or len(extruder_info) < 2:
  2986. return False
  2987. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  2988. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  2989. snow_read: set[int] = set()
  2990. for ext_info in extruder_info:
  2991. if not isinstance(ext_info, dict) or "id" not in ext_info or "snow" not in ext_info:
  2992. continue
  2993. try:
  2994. ext_id = int(ext_info["id"])
  2995. snow = int(ext_info["snow"])
  2996. except (TypeError, ValueError):
  2997. continue
  2998. if ext_id <= 1:
  2999. snow_read.add(ext_id)
  3000. # Normalize H2D snow value to global tray ID
  3001. ams_id = snow >> 8
  3002. slot = snow & 0xFF
  3003. if 0 <= ams_id <= 3:
  3004. # Regular AMS slot
  3005. global_tray = ams_id * 4 + (slot & 0x03)
  3006. old_val = self.state.h2d_extruder_snow.get(ext_id)
  3007. if old_val != global_tray:
  3008. logger.debug(
  3009. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  3010. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  3011. )
  3012. self.state.h2d_extruder_snow[ext_id] = global_tray
  3013. elif ams_id == 254 or ams_id == 255:
  3014. # External spool or unloaded
  3015. normalized = 254 if slot != 255 else 255
  3016. old_val = self.state.h2d_extruder_snow.get(ext_id)
  3017. if old_val != normalized:
  3018. logger.debug(
  3019. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  3020. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  3021. )
  3022. self.state.h2d_extruder_snow[ext_id] = normalized
  3023. elif 128 <= ams_id <= 135:
  3024. # External spool with hub mapping
  3025. old_val = self.state.h2d_extruder_snow.get(ext_id)
  3026. if old_val != ams_id:
  3027. logger.debug(
  3028. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: raw={snow} -> external hub {ams_id}"
  3029. )
  3030. self.state.h2d_extruder_snow[ext_id] = ams_id
  3031. return self.state.active_extruder in snow_read
  3032. def _parse_extruder_slots(self, data: dict) -> None:
  3033. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  3034. Absent on printers that do not report the block, in which case the
  3035. previous answer is kept rather than cleared: a partial payload carrying
  3036. only temperatures must not look like "both hotends are now empty".
  3037. """
  3038. device = data.get("device")
  3039. if not isinstance(device, dict):
  3040. return
  3041. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  3042. if not isinstance(info, list) or not info:
  3043. return
  3044. slots: dict[int, ExtruderSlot] = {}
  3045. for entry in info:
  3046. if not isinstance(entry, dict) or "id" not in entry:
  3047. continue
  3048. try:
  3049. ext_id = int(entry["id"])
  3050. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  3051. flags = int(entry.get("info", 0) or 0)
  3052. except (TypeError, ValueError):
  3053. continue
  3054. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  3055. ams_id = slot_id = None
  3056. else:
  3057. ams_id = (snow >> 8) & 0xFF
  3058. slot_id = snow & 0xFF
  3059. slots[ext_id] = ExtruderSlot(
  3060. ams_id=ams_id,
  3061. slot_id=slot_id,
  3062. has_filament=bool(flags & 0b10),
  3063. )
  3064. if slots:
  3065. self.state.extruder_slots = slots
  3066. def _handle_ams_data(self, ams_data):
  3067. """Handle AMS data changes for Spoolman integration.
  3068. This is called when we receive top-level AMS data in MQTT messages.
  3069. It detects changes and triggers the callback for Spoolman sync.
  3070. """
  3071. import hashlib
  3072. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  3073. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  3074. ams_list = None
  3075. if isinstance(ams_data, dict):
  3076. if "ams" in ams_data:
  3077. ams_list = ams_data["ams"]
  3078. self._normalize_a2l_am_units(ams_list)
  3079. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  3080. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  3081. if non_list_fields:
  3082. self._debug_on_change(
  3083. "ams_dict_fields",
  3084. non_list_fields,
  3085. "[%s] AMS dict fields: %s",
  3086. self.serial_number,
  3087. non_list_fields,
  3088. )
  3089. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  3090. # when checking if we're in filament change mode for tray_now disambiguation
  3091. if "ams_status" in ams_data:
  3092. raw_ams_status = ams_data["ams_status"]
  3093. if isinstance(raw_ams_status, str):
  3094. try:
  3095. self.state.ams_status = int(raw_ams_status)
  3096. except ValueError:
  3097. self.state.ams_status = 0
  3098. else:
  3099. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  3100. # Compute main and sub status
  3101. self.state.ams_status_sub = self.state.ams_status & 0xFF
  3102. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  3103. self._debug_on_change(
  3104. "ams_status:ams",
  3105. self.state.ams_status,
  3106. "[%s] ams_status: %s (main=%s, sub=%s)",
  3107. self.serial_number,
  3108. self.state.ams_status,
  3109. self.state.ams_status_main,
  3110. self.state.ams_status_sub,
  3111. )
  3112. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  3113. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  3114. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  3115. # next compatible slot (#2587). Stored raw here; globalised at the API
  3116. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  3117. # these are local slot numbers (0-3), not global IDs.
  3118. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  3119. if _tk in ams_data:
  3120. _raw = ams_data[_tk]
  3121. if isinstance(_raw, str):
  3122. try:
  3123. _val = int(_raw)
  3124. except ValueError:
  3125. _val = 255
  3126. else:
  3127. _val = _raw if _raw is not None else 255
  3128. prev = getattr(self.state, _attr)
  3129. setattr(self.state, _attr, _val)
  3130. # Log changes only while paused — the moment the operator cares —
  3131. # so a healthy print's normal tar churn doesn't spam the log.
  3132. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  3133. logger.info(
  3134. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  3135. self.serial_number,
  3136. _tk,
  3137. _val,
  3138. )
  3139. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  3140. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  3141. if "tray_now" in ams_data:
  3142. raw_tray_now = ams_data["tray_now"]
  3143. # Convert string to int if needed
  3144. if isinstance(raw_tray_now, str):
  3145. try:
  3146. parsed_tray_now = int(raw_tray_now)
  3147. except ValueError:
  3148. parsed_tray_now = 255
  3149. else:
  3150. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  3151. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  3152. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  3153. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  3154. # — disambiguated below using MQTT mapping field
  3155. ams_map = self.state.ams_extruder_map
  3156. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3157. # First, check if we have a pending target that matches this slot
  3158. pending_target = self.state.pending_tray_target
  3159. pending_at = self.state.pending_tray_target_at
  3160. if (
  3161. pending_target is not None
  3162. and pending_at is not None
  3163. and time.monotonic() - pending_at > PENDING_TRAY_TARGET_TTL
  3164. ):
  3165. # A load the printer refused or dropped: nothing clears
  3166. # it (tray_now stays 255), and a print loading the same
  3167. # slot number on another AMS long after was shown as
  3168. # this target (FW-C7). Fall through to the snow field.
  3169. self.state.pending_tray_target = None
  3170. self.state.pending_tray_target_at = None
  3171. pending_target = None
  3172. if pending_target is not None:
  3173. # Same slot rule as the snow branch below: an AMS-HT
  3174. # (128-135) has its one tray in slot 0.
  3175. pending_slot = 0 if 128 <= pending_target <= 135 else pending_target % 4
  3176. if pending_slot == parsed_tray_now:
  3177. # Slot matches our pending target - use the full global ID
  3178. logger.debug(
  3179. f"[{self.serial_number}] H2D tray_now disambiguation: "
  3180. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  3181. )
  3182. self.state.tray_now = pending_target
  3183. # Clear pending target now that load is confirmed
  3184. self.state.pending_tray_target = None
  3185. else:
  3186. # Slot doesn't match our pending target - something changed, use slot as-is
  3187. logger.warning(
  3188. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  3189. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  3190. )
  3191. self.state.tray_now = parsed_tray_now
  3192. # Clear pending target since it's stale
  3193. self.state.pending_tray_target = None
  3194. else:
  3195. # No pending target - use h2d_extruder_snow for accurate disambiguation
  3196. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  3197. active_ext = self.state.active_extruder # 0=right, 1=left
  3198. # Best source: use snow value from device.extruder.info if available
  3199. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  3200. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  3201. snow_slot = (
  3202. None
  3203. if snow_tray is None
  3204. else snow_tray % 4
  3205. if snow_tray < 128
  3206. else (0 if snow_tray <= 135 else -1)
  3207. )
  3208. # A snow from an earlier frame may predate a swap: it
  3209. # names the tray only while it agrees with the slot.
  3210. snow_usable = (
  3211. snow_tray is not None
  3212. and snow_tray != 255
  3213. and (snow_slot == parsed_tray_now or self._snow_in_frame)
  3214. )
  3215. if snow_usable and snow_tray is not None:
  3216. # snow_tray is already normalized to global ID
  3217. if snow_slot == parsed_tray_now:
  3218. if self.state.tray_now != snow_tray:
  3219. logger.debug(
  3220. f"[{self.serial_number}] H2D tray_now from snow: "
  3221. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  3222. )
  3223. self.state.tray_now = snow_tray
  3224. else:
  3225. # Slot mismatch in one frame: the extruder's own
  3226. # report is the complete answer, trust snow
  3227. logger.debug(
  3228. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  3229. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  3230. )
  3231. self.state.tray_now = snow_tray
  3232. else:
  3233. # Fallback: snow not available, use ams_extruder_map (less reliable)
  3234. # Find ALL AMS units on the active extruder
  3235. ams_on_extruder = []
  3236. for ams_id_str, ext_id in ams_map.items():
  3237. if ext_id == active_ext:
  3238. try:
  3239. ams_on_extruder.append(int(ams_id_str))
  3240. except ValueError:
  3241. pass # Skip AMS IDs that aren't valid integers
  3242. # Several AMS (or none the map knows of) leave the
  3243. # slot ambiguous. The printer's own mapping names the
  3244. # trays the running print uses: one of them at this
  3245. # slot is the one feeding (#3242). Only while a print
  3246. # runs: an idle H2 keeps reporting the previous
  3247. # print's mapping.
  3248. mapped_tray = None
  3249. if len(ams_on_extruder) != 1 and self._was_running and not self._completion_triggered:
  3250. mapped_tray = self._resolve_local_slot_from_mapping(
  3251. parsed_tray_now, self.state.raw_data.get("mapping"), ams_on_extruder
  3252. )
  3253. if mapped_tray is not None:
  3254. if self.state.tray_now != mapped_tray:
  3255. logger.debug(
  3256. f"[{self.serial_number}] H2D tray_now: AMS {ams_on_extruder} on extruder "
  3257. f"{active_ext}, slot {parsed_tray_now} -> global ID {mapped_tray} (from mapping)"
  3258. )
  3259. self.state.tray_now = mapped_tray
  3260. elif len(ams_on_extruder) == 1:
  3261. # Single AMS on this extruder - unambiguous
  3262. active_ams_id = ams_on_extruder[0]
  3263. if 128 <= active_ams_id <= 135:
  3264. # AMS-HT: single slot per unit, global ID = unit ID
  3265. global_tray_id = active_ams_id
  3266. else:
  3267. global_tray_id = active_ams_id * 4 + parsed_tray_now
  3268. logger.debug(
  3269. f"[{self.serial_number}] H2D tray_now fallback: "
  3270. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  3271. )
  3272. self.state.tray_now = global_tray_id
  3273. elif len(ams_on_extruder) > 1:
  3274. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  3275. current_tray = self.state.tray_now
  3276. # Determine which AMS unit and slot the current tray belongs to
  3277. if 0 <= current_tray <= 15:
  3278. current_ams = current_tray // 4
  3279. current_slot = current_tray % 4
  3280. elif 128 <= current_tray <= 135:
  3281. current_ams = current_tray # AMS-HT: ID = tray ID
  3282. current_slot = 0
  3283. else:
  3284. current_ams = -1
  3285. current_slot = -1
  3286. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  3287. # Current is valid and matches slot - keep it
  3288. logger.debug(
  3289. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3290. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  3291. )
  3292. else:
  3293. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  3294. if parsed_tray_now > 0:
  3295. candidates = [a for a in ams_on_extruder if a <= 3]
  3296. else:
  3297. candidates = ams_on_extruder
  3298. if len(candidates) == 1:
  3299. cand = candidates[0]
  3300. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  3301. logger.debug(
  3302. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3303. f"narrowed to AMS {cand} -> global ID {resolved}"
  3304. )
  3305. self.state.tray_now = resolved
  3306. else:
  3307. # Genuinely ambiguous. This is the second between a
  3308. # filament change reaching the AMS report and the
  3309. # extruder's snow, which then names the tray. Using
  3310. # the bare slot would point at AMS 0 and put that
  3311. # tray in the usage change log (#3242), so keep the
  3312. # current tray until snow arrives.
  3313. logger.debug(
  3314. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on "
  3315. f"extruder {active_ext}, slot {parsed_tray_now} is ambiguous without snow, "
  3316. f"keeping {current_tray}"
  3317. )
  3318. else:
  3319. # No AMS on this extruder that the map knows of: the
  3320. # slot can't be placed, keep the current tray (#3242)
  3321. logger.debug(
  3322. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  3323. f"slot {parsed_tray_now} can't be placed without snow, keeping {self.state.tray_now}"
  3324. )
  3325. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3326. # Single-nozzle printer with tray_now in 0-3 range.
  3327. # #1822: H2S firmware reports tray_now as the AMS's idle
  3328. # slot (typically 0) when the active feed is actually the
  3329. # external spool. X1C / P1S / A1 correctly report 254 in
  3330. # that case; H2S does not. When the slicer-captured
  3331. # ams_mapping is all-external (every entry is 254, or -1
  3332. # when the command carried no ams_mapping2 to resolve it
  3333. # from, #3166), the print can only be feeding from the
  3334. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  3335. # AMS-only mappings are NOT overridden — there's no
  3336. # evidence the firmware misreports in those cases. Prints
  3337. # started without a captured mapping (printer-screen start,
  3338. # or before Bambuddy connected) fall through unchanged.
  3339. captured = self._captured_ams_mapping
  3340. if captured and all(s in (-1, 254, 255) for s in captured):
  3341. if self.state.tray_now != 254:
  3342. logger.debug(
  3343. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  3344. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  3345. )
  3346. self.state.tray_now = 254
  3347. else:
  3348. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  3349. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  3350. # (snow-encoded) to resolve the correct AMS unit.
  3351. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  3352. try:
  3353. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  3354. except (ValueError, TypeError):
  3355. ams_exist = 0
  3356. num_ams = bin(ams_exist).count("1")
  3357. if self._has_a2l_am_unit and num_ams <= 1:
  3358. # A2L AMS-Lite (normalised unit 6): the firmware reports
  3359. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  3360. # otherwise usage tracking keys the wrong spool (it would
  3361. # deduct from AMS 0's slot). Confirmed by capture:
  3362. # tray_now="2" while printing physical slot 3.
  3363. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  3364. elif num_ams > 1:
  3365. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  3366. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  3367. if self._has_a2l_am_unit:
  3368. # A2L Lite + a regular AMS attached together is out of
  3369. # scope: the flat mapping ids are unknown for that combo
  3370. # and could collide with AMS 0. Fall through to the
  3371. # mapping-based resolve, but warn — a capture is needed.
  3372. logger.warning(
  3373. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3374. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3375. self.serial_number,
  3376. )
  3377. mapping_raw = self.state.raw_data.get("mapping")
  3378. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3379. if resolved is not None:
  3380. if resolved != parsed_tray_now:
  3381. logger.debug(
  3382. f"[{self.serial_number}] Multi-AMS tray_now: "
  3383. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3384. )
  3385. self.state.tray_now = resolved
  3386. else:
  3387. # No mapping available (not printing, or ambiguous) — use as-is.
  3388. # This matches the old behavior and is correct for AMS 0.
  3389. self.state.tray_now = parsed_tray_now
  3390. else:
  3391. # Single AMS — local slot 0-3 equals global ID
  3392. self.state.tray_now = parsed_tray_now
  3393. else:
  3394. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3395. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3396. # During filament change, the printer sends 255 first (unload), then the slot.
  3397. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3398. # Trust the printer's reported value.
  3399. self.state.tray_now = parsed_tray_now
  3400. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3401. # Valid physical trays: 0-15 (regular AMS), 24-27 (A2L AMS-Lite,
  3402. # normalised unit 6), 128-135 (AMS-HT), 254 (external spool)
  3403. tn = self.state.tray_now
  3404. if (
  3405. (0 <= tn <= 15)
  3406. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  3407. or (128 <= tn <= 135)
  3408. or tn == 254
  3409. ):
  3410. # Log tray change for mid-print usage splitting. Gate on the
  3411. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3412. # new print, `_completion_triggered` set when on_print_complete
  3413. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3414. # firmware briefly transitions out of RUNNING during AMS
  3415. # auto-fallback (#957), so a literal-string gate misses the
  3416. # switch and the usage tracker double-credits at completion.
  3417. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3418. self.state.tray_change_log.append((tn, self.state.layer_num))
  3419. logger.info(
  3420. "[%s] Tray change during print: tray=%d at layer=%d",
  3421. self.serial_number,
  3422. tn,
  3423. self.state.layer_num,
  3424. )
  3425. if self.on_tray_change:
  3426. self.on_tray_change(tn, self.state.layer_num)
  3427. self.state.last_loaded_tray = self.state.tray_now
  3428. self._debug_on_change(
  3429. "tray_now",
  3430. self.state.tray_now,
  3431. "[%s] tray_now updated: %s",
  3432. self.serial_number,
  3433. self.state.tray_now,
  3434. )
  3435. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3436. # state when checking filament change mode for H2D disambiguation
  3437. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3438. # We've already processed the status fields above, so just return if no ams list
  3439. if ams_list is None:
  3440. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3441. return
  3442. elif isinstance(ams_data, list):
  3443. ams_list = ams_data
  3444. self._normalize_a2l_am_units(ams_list)
  3445. else:
  3446. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3447. return
  3448. # Merge AMS data instead of replacing, to handle partial updates
  3449. # During prints, the printer may only send updates for active AMS units
  3450. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3451. existing_ams = self.state.raw_data.get("ams", [])
  3452. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  3453. # Update existing units with new data, add new units
  3454. for ams_unit in ams_list:
  3455. ams_id = ams_unit.get("id")
  3456. if ams_id is not None:
  3457. existing_unit = existing_by_id.get(ams_id)
  3458. if existing_unit and "tray" in ams_unit:
  3459. # Deep merge trays to preserve fields from previous updates
  3460. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3461. merged_trays = []
  3462. for new_tray in ams_unit.get("tray", []):
  3463. tray_id = new_tray.get("id")
  3464. if tray_id is not None and tray_id in existing_trays:
  3465. # Merge: start with existing, update with new non-empty values
  3466. merged_tray = existing_trays[tray_id].copy()
  3467. # Detect slot-clearing updates (spool removal):
  3468. # When tray_type is explicitly empty, clear everything
  3469. # including RFID data (tag_uid/tray_uuid).
  3470. slot_clearing = new_tray.get("tray_type") == ""
  3471. # Some printers (e.g. H2D) only send {id, state} in
  3472. # incremental updates when a tray is not fully loaded.
  3473. # state=11 means loaded; other values (9=empty,
  3474. # 10=spool present but filament not in feeder) indicate
  3475. # the slot should be cleared. Without this, old
  3476. # tray_type/tray_color persist indefinitely (#784).
  3477. #
  3478. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3479. # tray high-temp dry box, id >= 128) reports its loaded
  3480. # tray as state=9, not 11 — it doesn't feed filament into
  3481. # a shared buffer the way a 4-slot AMS does. Applying the
  3482. # `state != 11 → empty` rule to an HT unit wiped a present
  3483. # spool on every power-on, when the printer sends a partial
  3484. # {id, state=9} for the HT tray (#2594). Skip the state
  3485. # heuristic for HT units — a genuine HT spool removal still
  3486. # clears via the explicit tray_type=="" case above and the
  3487. # tray_exist_bits cleanup below.
  3488. try:
  3489. _is_ht_unit = int(ams_id) >= 128
  3490. except (TypeError, ValueError):
  3491. _is_ht_unit = False
  3492. tray_state = new_tray.get("state")
  3493. if (
  3494. tray_state is not None
  3495. and tray_state != 11
  3496. and not _is_ht_unit
  3497. and "tray_type" not in new_tray
  3498. and merged_tray.get("tray_type")
  3499. ):
  3500. logger.info(
  3501. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3502. self.serial_number,
  3503. ams_id,
  3504. tray_id,
  3505. tray_state,
  3506. )
  3507. slot_clearing = True
  3508. # The incremental update only has {id, state} — inject
  3509. # empty values for all content fields so the merge loop
  3510. # below clears the stale data from merged_tray.
  3511. new_tray.update(
  3512. {
  3513. "tray_type": "",
  3514. "tray_sub_brands": "",
  3515. "tray_color": "",
  3516. "tray_id_name": "",
  3517. "tray_info_idx": "",
  3518. "tag_uid": "0000000000000000",
  3519. "tray_uuid": "00000000000000000000000000000000",
  3520. "remain": 0,
  3521. "k": None,
  3522. "cali_idx": None,
  3523. }
  3524. )
  3525. for key, value in new_tray.items():
  3526. # Fields that should always be updated (even with empty/zero values):
  3527. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3528. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3529. # tray_id_name: slot content indicators that must be cleared
  3530. # when a spool is removed (fixes #147 - old AMS empty slot)
  3531. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3532. # They are only cleared during spool removal (slot_clearing=True).
  3533. # Periodic AMS updates often include empty RFID fields which
  3534. # would overwrite valid data from the initial pushall.
  3535. always_update_fields = (
  3536. "remain",
  3537. "k",
  3538. "id",
  3539. "cali_idx",
  3540. "tray_type",
  3541. "tray_sub_brands",
  3542. "tray_info_idx",
  3543. "tray_color",
  3544. "tray_id_name",
  3545. )
  3546. if (
  3547. key in always_update_fields
  3548. or slot_clearing
  3549. or value
  3550. not in (
  3551. None,
  3552. "",
  3553. "0000000000000000",
  3554. "00000000000000000000000000000000",
  3555. )
  3556. ):
  3557. merged_tray[key] = value
  3558. merged_trays.append(merged_tray)
  3559. else:
  3560. merged_trays.append(new_tray)
  3561. # Update ams_unit with merged trays. Spread existing_unit
  3562. # FIRST so top-level fields the partial update omits —
  3563. # dry_time, info (which drives dry_status / dry_sub_status),
  3564. # humidity, temp — are preserved instead of dropped. The
  3565. # printer sends tray-bearing partials that carry no drying
  3566. # fields; without this, dry_time reads as absent → 0 and the
  3567. # falling-edge detector below fires a false "drying complete"
  3568. # (#1462). Mirrors the no-tray branch's merge semantics.
  3569. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3570. elif existing_unit:
  3571. # Partial update without tray data: merge new fields into existing
  3572. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3573. ams_unit = {**existing_unit, **ams_unit}
  3574. existing_by_id[ams_id] = ams_unit
  3575. # The merge keeps a unit the push doesn't list, so an unplugged AMS used
  3576. # to stay until Bambuddy restarted (#3356). Drop one only on the
  3577. # printer's own word that it is gone.
  3578. if isinstance(ams_data, dict):
  3579. listed = {ams_unit.get("id") for ams_unit in ams_list}
  3580. for ams_id in [i for i in existing_by_id if i not in listed]:
  3581. if unit_reported_absent(ams_id, ams_list, ams_data.get("ams_exist_bits")):
  3582. logger.info("[%s] AMS %s no longer attached, removing it", self.serial_number, ams_id)
  3583. del existing_by_id[ams_id]
  3584. # Convert back to list, sorted by ID for consistent ordering
  3585. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  3586. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3587. # Shared with the VP bridge cache so the slicer-facing view stays in
  3588. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3589. # for the full rationale and the printer-shutdown guard.
  3590. if isinstance(ams_data, dict):
  3591. apply_tray_exist_bits(
  3592. merged_ams,
  3593. ams_data.get("tray_exist_bits"),
  3594. power_on_flag=ams_data.get("power_on_flag", True),
  3595. log_label=self.serial_number,
  3596. annotate_exists=True,
  3597. )
  3598. self.state.raw_data["ams"] = merged_ams
  3599. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3600. self._apply_ams_version_cache(merged_ams)
  3601. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3602. self.state.last_ams_update = time.time()
  3603. self._debug_on_change(
  3604. "merged_ams",
  3605. (len(ams_list), len(merged_ams)),
  3606. "[%s] Merged AMS data: %s new units, %s total",
  3607. self.serial_number,
  3608. len(ams_list),
  3609. len(merged_ams),
  3610. )
  3611. # Extract ams_extruder_map from each AMS unit's info field
  3612. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3613. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3614. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3615. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3616. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3617. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3618. #
  3619. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3620. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3621. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3622. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3623. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3624. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3625. # the switch being installed.
  3626. #
  3627. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3628. # the full map. Merge into existing map to preserve entries from prior updates.
  3629. fts_installed = self.state.fila_switch.installed
  3630. inlet_moves: list[tuple[int, str]] = []
  3631. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3632. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3633. for ams_unit in merged_ams:
  3634. ams_id = ams_unit.get("id")
  3635. info = ams_unit.get("info")
  3636. if ams_id is not None and info is not None:
  3637. try:
  3638. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3639. info_val = int(str(info), 16)
  3640. # Extract 4 bits starting at bit 8 for extruder assignment
  3641. extruder_id = (info_val >> 8) & 0xF
  3642. if extruder_id == 0xE:
  3643. if fts_installed:
  3644. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3645. if inlet is not None:
  3646. previous = ams_switch_inlet.get(str(ams_id))
  3647. ams_switch_inlet[str(ams_id)] = inlet
  3648. self._debug_on_change(
  3649. f"ams_inlet:{ams_id}",
  3650. inlet,
  3651. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3652. self.serial_number,
  3653. ams_id,
  3654. info,
  3655. inlet,
  3656. )
  3657. if previous is not None and previous != inlet:
  3658. # Only a genuine move, never the first sighting:
  3659. # re-applying K-profiles on every reconnect would
  3660. # fight a binding the operator set deliberately.
  3661. logger.info(
  3662. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3663. self.serial_number,
  3664. ams_id,
  3665. inlet,
  3666. previous,
  3667. )
  3668. inlet_moves.append((int(ams_id), inlet))
  3669. continue
  3670. ams_extruder_map[str(ams_id)] = extruder_id
  3671. self._debug_on_change(
  3672. f"ams_info:{ams_id}",
  3673. (info, extruder_id),
  3674. "[%s] AMS %s info=0x%s -> extruder %s",
  3675. self.serial_number,
  3676. ams_id,
  3677. info,
  3678. extruder_id,
  3679. )
  3680. except (ValueError, TypeError):
  3681. pass # Skip AMS units with unparseable info bitmask values
  3682. if ams_extruder_map:
  3683. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3684. self.state.ams_extruder_map = ams_extruder_map
  3685. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3686. if ams_switch_inlet:
  3687. self.state.ams_switch_inlet = ams_switch_inlet
  3688. for moved_ams_id, moved_inlet in inlet_moves:
  3689. if self.on_fts_inlet_change:
  3690. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3691. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3692. # BambuStudio DevFilaSystem.cpp parses info bits:
  3693. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3694. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3695. for ams_unit in merged_ams:
  3696. info = ams_unit.get("info")
  3697. if info is not None:
  3698. try:
  3699. info_val = int(str(info), 16)
  3700. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3701. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3702. except (ValueError, TypeError):
  3703. pass # Skip unparseable info values
  3704. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3705. if "dry_sf_reason" in ams_unit:
  3706. sf_reason = ams_unit["dry_sf_reason"]
  3707. if isinstance(sf_reason, list):
  3708. ams_unit["dry_sf_reason"] = [
  3709. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3710. ]
  3711. else:
  3712. ams_unit["dry_sf_reason"] = []
  3713. # Persist updated drying fields back to raw_data
  3714. self.state.raw_data["ams"] = merged_ams
  3715. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3716. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3717. # — fire the callback so smart-plug auto-off-after-drying can run,
  3718. # and drop our cached target-cycle params so the badge stops claiming
  3719. # an active cycle. Works identically for queue-triggered, ambient,
  3720. # and manual drying because we observe the firmware-reported state.
  3721. for ams_unit in merged_ams:
  3722. try:
  3723. ams_id = int(ams_unit.get("id", -1))
  3724. except (TypeError, ValueError):
  3725. continue
  3726. if ams_id < 0:
  3727. continue
  3728. # The firmware phase outranks the stalled-countdown heuristic even
  3729. # on a transient-zero frame, which the completion guard below skips.
  3730. # Clear a previously raised flag before that early continue.
  3731. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3732. ams_unit["dry_countdown_stalled"] = False
  3733. # Only evaluate the edge when this update carries an explicit
  3734. # dry_time. An absent / unparseable value is NOT zero — treating
  3735. # it as 0 lets a tray-only partial fake a drying-complete edge
  3736. # (#1462). Skip without touching the remembered value so the
  3737. # next update that DOES carry dry_time sees the true previous.
  3738. raw_dry_time = ams_unit.get("dry_time")
  3739. if raw_dry_time is None:
  3740. continue
  3741. try:
  3742. current = int(raw_dry_time)
  3743. except (TypeError, ValueError):
  3744. continue
  3745. # A dry_time of 0 only means "finished" when the unit also reports
  3746. # an idle phase. Between the command ack and the countdown settling
  3747. # the firmware publishes a transient 0 while the AMS is still
  3748. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3749. # 12-hour cycle. Taking that at face value dropped the cached target
  3750. # (leaving the badge to guess the filament from tray 1, so a PLA
  3751. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3752. # schedules smart-plug auto-off. dry_status comes from the same info
  3753. # hex parsed above; when it is absent we let the edge through, so a
  3754. # firmware that never reports one still ends its cycles.
  3755. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3756. # Leave the remembered value alone, exactly as the absent-
  3757. # dry_time skip above does: whichever push ends the cycle for
  3758. # real must still see a non-zero previous.
  3759. logger.debug(
  3760. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3761. self.serial_number,
  3762. ams_id,
  3763. ams_unit.get("dry_status"),
  3764. )
  3765. continue
  3766. seen_before = ams_id in self._previous_dry_times
  3767. previous = self._previous_dry_times.get(ams_id, 0)
  3768. self._previous_dry_times[ams_id] = current
  3769. if current > 0:
  3770. cycle = self._dry_cycles.get(ams_id)
  3771. if cycle is None or previous == 0:
  3772. cycle = {
  3773. "peak": current,
  3774. # A rise from an observed 0 is the cycle's first minute.
  3775. # A first sighting already counting down is not.
  3776. "start_seen": seen_before,
  3777. "target": self._drying_targets.get(ams_id),
  3778. }
  3779. self._dry_cycles[ams_id] = cycle
  3780. elif current > int(cycle["peak"]):
  3781. cycle["peak"] = current
  3782. # Stall detection: stamp value CHANGES only — a live countdown
  3783. # decrements once a minute, so repeats of the same value within
  3784. # the minute must not refresh the stamp, and a frame without a
  3785. # dry_time never reaches here (the absent-value skip above).
  3786. now_mono = time.monotonic()
  3787. if current != previous or ams_id not in self._dry_time_changed_at:
  3788. self._dry_time_changed_at[ams_id] = now_mono
  3789. ams_unit["dry_countdown_stalled"] = bool(
  3790. current > 0
  3791. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  3792. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  3793. )
  3794. if previous > 0 and current == 0:
  3795. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  3796. if self.on_drying_complete:
  3797. self.on_drying_complete(ams_id)
  3798. cycle = self._dry_cycles.pop(ams_id, None) or {"peak": previous, "start_seen": False, "target": None}
  3799. if self.on_drying_cycle_end:
  3800. self.on_drying_cycle_end(self._drying_cycle_end(ams_id, previous, cycle))
  3801. # Create a hash of relevant AMS data to detect changes.
  3802. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  3803. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  3804. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  3805. # above but leaves the raw payload's tracked fields untouched — so a
  3806. # raw-based hash never flips and on_ams_change never fires, leaving the
  3807. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  3808. # always spans every unit, so a partial single-unit update can't produce a
  3809. # spuriously different hash from a full pushall.
  3810. ams_hash_data = []
  3811. for ams_unit in merged_ams:
  3812. for tray in ams_unit.get("tray", []):
  3813. # Include fields that matter for filament tracking
  3814. ams_hash_data.append(
  3815. f"{ams_unit.get('id')}:{tray.get('id')}:"
  3816. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  3817. )
  3818. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  3819. # Only trigger callback if AMS data actually changed
  3820. if ams_hash != self._previous_ams_hash:
  3821. self._previous_ams_hash = ams_hash
  3822. if self.on_ams_change:
  3823. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  3824. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  3825. # may lack fields like 'remain' that the merged state preserves
  3826. self.on_ams_change(merged_ams)
  3827. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  3828. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  3829. # or cali_idx — so an assignment that only swaps the filament id on an
  3830. # already-loaded slot would not flip the hash, and gating the check on
  3831. # it would miss exactly the confirmation we are after.
  3832. if self._pending_assignments:
  3833. self._check_assignment_verifications()
  3834. @staticmethod
  3835. def _drying_cycle_end(ams_id: int, remaining: int, cycle: dict[str, object]) -> DryingCycleEnd:
  3836. """Build the cycle-end report from the record kept while it ran."""
  3837. target = cycle.get("target")
  3838. target_temp: int | None = None
  3839. target_hours: int | None = None
  3840. if isinstance(target, dict):
  3841. try:
  3842. target_temp = int(target.get("temp") or 0) or None
  3843. target_hours = int(target.get("duration_hours") or 0) or None
  3844. except (TypeError, ValueError):
  3845. target_temp = target_hours = None
  3846. return DryingCycleEnd(
  3847. ams_id=ams_id,
  3848. remaining_minutes=remaining,
  3849. peak_minutes=max(int(cycle.get("peak") or 0), remaining),
  3850. start_seen=bool(cycle.get("start_seen")),
  3851. target_temp=target_temp,
  3852. target_hours=target_hours,
  3853. )
  3854. def _log_drying_cycle_end(
  3855. self,
  3856. ams_id: int,
  3857. remaining: int,
  3858. ams_unit: dict,
  3859. target: dict[str, object] | None,
  3860. ) -> None:
  3861. """Report a finished drying cycle, with the firmware's reason when it was
  3862. cut short (#2770).
  3863. A cycle that reaches its configured duration needs no explanation and
  3864. keeps the one-line "drying complete" it has always had. One that ends
  3865. with most of its countdown left was ended by somebody, and there are
  3866. only two candidates: a stop Bambuddy sent — the print-takes-priority
  3867. stop, or the user's Stop button — which is named as such, or the
  3868. firmware.
  3869. For the firmware case the only account of why lives in fields we already
  3870. parse but have never written down: the ``dry_status`` /
  3871. ``dry_sub_status`` phase from the info hex, the per-unit
  3872. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  3873. that moment. Logging them at INFO puts them in every support bundle by
  3874. default, which is what a report like #2770 needs before its cause can be
  3875. argued about at all.
  3876. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  3877. logged for every cycle, early or not, because they are what decides
  3878. whether auto-drying re-arms. Reconstructing them for #2770 meant
  3879. cross-referencing hourly alarm lines against 30-second scheduler debug
  3880. that was switched off at the time; one line here says it outright — a
  3881. cycle ending at 63 degC with the reading still above the threshold is
  3882. the whole shape of the re-arm loop.
  3883. """
  3884. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  3885. if ams_id in self._drying_stops_sent:
  3886. self._drying_stops_sent.discard(ams_id)
  3887. logger.info(
  3888. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  3889. self.serial_number,
  3890. ams_id,
  3891. remaining,
  3892. box,
  3893. )
  3894. return
  3895. if remaining <= _EARLY_DRY_END_MINUTES:
  3896. logger.info(
  3897. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  3898. self.serial_number,
  3899. ams_id,
  3900. remaining,
  3901. box,
  3902. )
  3903. return
  3904. requested_minutes: int | None = None
  3905. if target is not None:
  3906. try:
  3907. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  3908. except (TypeError, ValueError):
  3909. requested_minutes = None
  3910. logger.info(
  3911. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  3912. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  3913. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  3914. self.serial_number,
  3915. ams_id,
  3916. remaining,
  3917. requested_minutes if requested_minutes is not None else "?",
  3918. ams_unit.get("dry_status"),
  3919. ams_unit.get("dry_sub_status"),
  3920. ams_unit.get("dry_sf_reason") or [],
  3921. [e.full_code for e in self.state.hms_errors] or "none",
  3922. box,
  3923. )
  3924. def register_assignment_verification(
  3925. self,
  3926. ams_id: int,
  3927. tray_id: int,
  3928. tray_info_idx: str,
  3929. tray_color: str,
  3930. cali_idx: int | None,
  3931. ) -> None:
  3932. """Record an assignment we just pushed so subsequent AMS telemetry can
  3933. confirm the tray actually accepted it (#2582).
  3934. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  3935. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  3936. accepted filament id back in the per-tray push, so a match means the
  3937. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  3938. signal so we can specifically flag "filament loaded but K-profile not
  3939. applied", which is the exact symptom the reporter chased via flow-cal.
  3940. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  3941. there is nothing to verify and no record is stored.
  3942. """
  3943. want_idx = (tray_info_idx or "").strip().upper()
  3944. if not want_idx:
  3945. return
  3946. self._pending_assignments[(ams_id, tray_id)] = {
  3947. "tray_info_idx": want_idx,
  3948. "tray_color": (tray_color or "").strip().upper(),
  3949. "cali_idx": cali_idx,
  3950. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  3951. "last_seen_idx": None,
  3952. }
  3953. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  3954. """Locate the live tray dict for a pending verification.
  3955. External spools (ams_id 255) live in ``vt_tray`` under global ids
  3956. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  3957. report a single tray whose id may not equal the logical tray_id, so fall
  3958. back to the sole tray when an id match fails.
  3959. """
  3960. raw = self.state.raw_data or {}
  3961. if ams_id == 255:
  3962. want_ext = 254 + tray_id
  3963. for vt in raw.get("vt_tray", []) or []:
  3964. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  3965. return vt
  3966. return None
  3967. for unit in raw.get("ams", []) or []:
  3968. if str(unit.get("id")) != str(ams_id):
  3969. continue
  3970. trays = unit.get("tray", []) or []
  3971. for tray in trays:
  3972. if str(tray.get("id")) == str(tray_id):
  3973. return tray
  3974. if ams_id >= 128 and len(trays) == 1:
  3975. return trays[0]
  3976. return None
  3977. return None
  3978. def _check_assignment_verifications(self) -> None:
  3979. """Compare each pending assignment against live tray telemetry and fire
  3980. ``on_assignment_verified`` on a match or once the deadline passes.
  3981. Runs on every AMS push. Non-matching-but-still-within-window entries are
  3982. left in place for the next push. The timeout branch only fires when a
  3983. later push arrives after the deadline; if the printer goes silent we
  3984. simply never confirm, which is preferable to inventing a failure.
  3985. """
  3986. now = time.monotonic()
  3987. for key, want in list(self._pending_assignments.items()):
  3988. ams_id, tray_id = key
  3989. tray = self._find_verify_tray(ams_id, tray_id)
  3990. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  3991. if tray is not None and actual_idx:
  3992. want["last_seen_idx"] = actual_idx
  3993. if actual_idx and actual_idx == want["tray_info_idx"]:
  3994. self._pending_assignments.pop(key, None)
  3995. kprofile_applied = True
  3996. want_cali = want.get("cali_idx")
  3997. if want_cali is not None and want_cali >= 0:
  3998. actual_cali = tray.get("cali_idx")
  3999. kprofile_applied = actual_cali == want_cali
  4000. self._fire_assignment_verified(
  4001. ams_id,
  4002. tray_id,
  4003. True,
  4004. {
  4005. "tray_info_idx": actual_idx,
  4006. "kprofile_applied": kprofile_applied,
  4007. },
  4008. )
  4009. elif now >= want["deadline"]:
  4010. self._pending_assignments.pop(key, None)
  4011. self._fire_assignment_verified(
  4012. ams_id,
  4013. tray_id,
  4014. False,
  4015. {
  4016. "expected_tray_info_idx": want["tray_info_idx"],
  4017. "actual_tray_info_idx": want.get("last_seen_idx"),
  4018. # True when we saw the tray at least once (so the push
  4019. # channel is alive and the printer really stored a
  4020. # different/blank id) vs never observing it at all.
  4021. "saw_tray": want.get("last_seen_idx") is not None,
  4022. },
  4023. )
  4024. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  4025. if verified:
  4026. logger.info(
  4027. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  4028. self.serial_number,
  4029. ams_id,
  4030. tray_id,
  4031. detail.get("tray_info_idx"),
  4032. detail.get("kprofile_applied"),
  4033. )
  4034. else:
  4035. logger.warning(
  4036. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  4037. self.serial_number,
  4038. ams_id,
  4039. tray_id,
  4040. detail.get("expected_tray_info_idx"),
  4041. detail.get("actual_tray_info_idx"),
  4042. detail.get("saw_tray"),
  4043. )
  4044. if self.on_assignment_verified:
  4045. try:
  4046. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  4047. except Exception:
  4048. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  4049. @staticmethod
  4050. def _probe_number(value, fallback: float | None = None) -> float | None:
  4051. """Coerce a telemetry field to a number, or return `fallback`.
  4052. Firmware is inconsistent about whether these arrive as ints or as
  4053. numeric strings, and the probe must never raise on a surprise type.
  4054. """
  4055. try:
  4056. return float(value)
  4057. except (TypeError, ValueError):
  4058. return fallback
  4059. def _probe_end_of_print(self, data: dict) -> None:
  4060. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  4061. Opens on the first frame that looks like end-of-print (last object
  4062. layer reached, progress at 99+, or no remaining time), then logs each
  4063. frame in which any probed field changed, and closes on the transition
  4064. out of RUNNING. Armed once per print — see the module-level comment on
  4065. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  4066. currently see into.
  4067. Read-only with respect to printer state: this is instrumentation, and
  4068. nothing downstream may come to depend on it.
  4069. """
  4070. if not logger.isEnabledFor(logging.DEBUG):
  4071. return
  4072. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  4073. return
  4074. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  4075. if not present:
  4076. return
  4077. if not self._eop_probe_open:
  4078. # Open on any end-of-print signal. Read from the raw frame first so
  4079. # the frame that *carries* the signal is itself captured — state
  4080. # fields are only updated further down this same call.
  4081. frame_layer = data.get("layer_num")
  4082. if self._is_stale_layer(frame_layer):
  4083. frame_layer = None
  4084. layer = self._probe_number(frame_layer, self.state.layer_num) or 0
  4085. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  4086. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  4087. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  4088. at_last_layer = total > 0 and layer >= total
  4089. # `remaining <= 0` is only meaningful once the print has actually
  4090. # progressed — it reads 0 during the pre-print calibration too.
  4091. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  4092. if not (at_last_layer or percent >= 99 or out_of_time):
  4093. return
  4094. self._eop_probe_open = True
  4095. self._eop_probe_frames = 0
  4096. self._eop_probe_last = {}
  4097. logger.debug(
  4098. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  4099. self.serial_number,
  4100. layer,
  4101. total,
  4102. percent,
  4103. remaining,
  4104. )
  4105. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  4106. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  4107. self._eop_probe_last.update(present)
  4108. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  4109. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  4110. self._eop_probe_frames += 1
  4111. logger.debug(
  4112. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  4113. self.serial_number,
  4114. _END_OF_PRINT_PROBE_MAX_FRAMES,
  4115. )
  4116. return
  4117. if changed or closing:
  4118. self._eop_probe_frames += 1
  4119. logger.debug(
  4120. "[%s] EOP-PROBE %s%s: %s",
  4121. self.serial_number,
  4122. self._eop_probe_frames,
  4123. " CLOSE" if closing else "",
  4124. # `changed` on a closing frame can be empty; fall back to the
  4125. # full picture so the last line is always self-contained.
  4126. changed if changed else present,
  4127. )
  4128. if closing:
  4129. self._eop_probe_open = False
  4130. self._eop_probe_armed = False
  4131. self._eop_probe_last = {}
  4132. @property
  4133. def layer_before_new_print(self) -> int:
  4134. """The layer the printer was on when a print start was detected, until
  4135. it reports another (#3317); 0 when none.
  4136. For a print that is resumed rather than new, which a restart while it
  4137. was paused makes look new, that is the layer it is still on (#2984).
  4138. """
  4139. return self._stale_layer_num
  4140. def _is_stale_layer(self, value) -> bool:
  4141. """Whether a frame's `layer_num` is the previous print's last layer (#3317)."""
  4142. if not self._stale_layer_num:
  4143. return False
  4144. try:
  4145. return int(value) == self._stale_layer_num
  4146. except (TypeError, ValueError):
  4147. return False
  4148. def _update_state(self, data: dict):
  4149. """Update printer state from message data."""
  4150. _previous_state = self.state.state
  4151. # #2547: instrumentation only — runs before any state mutation so the
  4152. # frame carrying an end-of-print signal is logged as it arrived.
  4153. try:
  4154. self._probe_end_of_print(data)
  4155. except Exception: # pragma: no cover - a probe must never break ingest
  4156. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  4157. # Update state fields
  4158. if "gcode_state" in data:
  4159. self.state.state = data["gcode_state"]
  4160. if "gcode_file" in data:
  4161. self.state.gcode_file = data["gcode_file"]
  4162. self.state.current_print = data["gcode_file"]
  4163. # The answer to a print start the printer refused names the job it
  4164. # refused, not one it runs: read as status, its job id told the start
  4165. # watchdog the file had landed.
  4166. refused_start = (
  4167. data.get("command") == "project_file"
  4168. and data.get("result") is not None
  4169. and str(data["result"]).upper() != "SUCCESS"
  4170. )
  4171. if "subtask_name" in data and not refused_start:
  4172. self.state.subtask_name = data["subtask_name"]
  4173. # Prefer subtask_name as current_print if available
  4174. if data["subtask_name"]:
  4175. self.state.current_print = data["subtask_name"]
  4176. if "subtask_id" in data and not refused_start:
  4177. self.state.subtask_id = data["subtask_id"]
  4178. if "mc_percent" in data:
  4179. # Billing: retain this frame's latest positive value immediately.
  4180. # A display-side abort may be the very next frame (and may omit
  4181. # mc_percent entirely), so retaining only the previous frame can
  4182. # lose the only usable estimate for proportional charging.
  4183. previous_progress = self.state.progress
  4184. new_progress = float(data["mc_percent"])
  4185. if new_progress > 0:
  4186. self._last_valid_progress = new_progress
  4187. self.state.progress = new_progress
  4188. # #2547: strictly-increasing only. The firmware resets progress to 0
  4189. # on cancel and re-reports the same percent on most frames; neither
  4190. # is the print advancing, and both would make the frame bank grab a
  4191. # camera frame for nothing.
  4192. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  4193. self.on_print_progress(int(self.state.progress))
  4194. if "mc_remaining_time" in data:
  4195. self.state.remaining_time = int(data["mc_remaining_time"])
  4196. if "mc_print_sub_stage" in data:
  4197. new_sub_stage = int(data["mc_print_sub_stage"])
  4198. if new_sub_stage != self.state.mc_print_sub_stage:
  4199. logger.debug(
  4200. f"[{self.serial_number}] mc_print_sub_stage changed: "
  4201. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  4202. )
  4203. self.state.mc_print_sub_stage = new_sub_stage
  4204. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  4205. # front because three places below consult it and they run in an order
  4206. # that is not the order they read most naturally in: the layer-advance
  4207. # refresh (#2702) must not fire on a frame that already answers it, the
  4208. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  4209. # reset must not discard a total that belongs to the starting print.
  4210. total_from_this_frame = 0
  4211. if "total_layer_num" in data:
  4212. try:
  4213. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  4214. except (TypeError, ValueError):
  4215. # Must not escape. `_on_message` catches only JSONDecodeError
  4216. # and paho is left at `suppress_exceptions = False`, so an
  4217. # exception raised here is re-raised on the network thread and
  4218. # takes the printer connection down over one unusable field.
  4219. # Treat it as "not reported": the refresh below then recovers
  4220. # the real total from a pushall.
  4221. logger.debug(
  4222. "[%s] ignoring unusable total_layer_num: %r",
  4223. self.serial_number,
  4224. data["total_layer_num"],
  4225. )
  4226. if "layer_num" in data:
  4227. try:
  4228. new_layer = int(data["layer_num"])
  4229. except (TypeError, ValueError):
  4230. # Contained for the same reason as `total_layer_num` above: an
  4231. # exception raised here escapes `_update_state` and paho
  4232. # re-raises it on the network thread. Losing this frame would
  4233. # also lose the print-start and completion detection further
  4234. # down, which is worse than losing a layer number.
  4235. #
  4236. # Held at the last known layer rather than substituted with 0:
  4237. # a fabricated 0 reads as the firmware's cancel reset, which
  4238. # would move `_last_valid_layer_num` and show layer 0 in the UI
  4239. # until the next good frame.
  4240. logger.debug(
  4241. "[%s] ignoring unusable layer_num: %r",
  4242. self.serial_number,
  4243. data["layer_num"],
  4244. )
  4245. new_layer = self.state.layer_num
  4246. if self._is_stale_layer(new_layer):
  4247. logger.debug(
  4248. "[%s] ignoring layer_num %s: last layer of the previous print",
  4249. self.serial_number,
  4250. new_layer,
  4251. )
  4252. new_layer = self.state.layer_num
  4253. elif new_layer > 0:
  4254. # The new print reports a layer of its own; from here on the
  4255. # previous print's value is a layer this print can reach.
  4256. self._stale_layer_num = 0
  4257. old_layer = self.state.layer_num
  4258. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  4259. if old_layer > 0:
  4260. self._last_valid_layer_num = old_layer
  4261. self.state.layer_num = new_layer
  4262. # Trigger layer change callback if layer increased
  4263. if new_layer > old_layer and self.on_layer_change:
  4264. self.on_layer_change(new_layer)
  4265. # #2702: the print is demonstrably laying down layers but we still
  4266. # have no denominator, so the pushall requested at print start
  4267. # either went unanswered or raced the printer learning the total.
  4268. # Ask once more — by layer 1 the printer definitely knows it.
  4269. # One-shot: an unanswered pushall must not turn into a per-layer
  4270. # retry loop for the rest of the print.
  4271. if (
  4272. new_layer > old_layer
  4273. and self._total_layers_refresh_armed
  4274. and not self.state.total_layers
  4275. and not total_from_this_frame
  4276. ):
  4277. self._total_layers_refresh_armed = False
  4278. logger.debug(
  4279. "[%s] layer %s with no total_layer_num — re-requesting full status",
  4280. self.serial_number,
  4281. new_layer,
  4282. )
  4283. self._request_push_all()
  4284. # #2547: there is deliberately NO finish-photo trigger on the
  4285. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  4286. # moment the printer *starts* the final layer, not the moment it
  4287. # finishes it — on the H2C capture that closed #2547 the edge
  4288. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  4289. # filament change before the print actually ended, so the photo
  4290. # showed the toolhead mid-print over the part. Worse, the trigger
  4291. # latched `_finish_photo_captured`, locking out both the stage-22
  4292. # and FINISH triggers below for the rest of the print.
  4293. #
  4294. # #1867 (End G-code ejects the plate before FINISH) is handled
  4295. # where it belongs instead: `on_finish_photo_moment` prefers the
  4296. # in-print frame bank when the dispatcher recorded that it injected
  4297. # End G-code into this print. See services/print_dispatch_context.
  4298. if total_from_this_frame:
  4299. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  4300. # end — same shape as the `layer_num` reset guarded above. Applying
  4301. # only positive values preserves the last known good denominator so
  4302. # the usage-tracker split path (#1771) survives the reset frame.
  4303. self.state.total_layers = total_from_this_frame
  4304. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  4305. # Convert to 0-100 percentage for display
  4306. def parse_fan_speed(value: str | int | None) -> int | None:
  4307. if value is None:
  4308. return None
  4309. try:
  4310. speed = int(value)
  4311. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  4312. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  4313. if speed <= 15:
  4314. return round(speed * 100 / 15)
  4315. # If already a percentage (0-255 scale from some printers), convert
  4316. elif speed <= 255:
  4317. return round(speed * 100 / 255)
  4318. return speed
  4319. except (ValueError, TypeError):
  4320. return None
  4321. # Log fan fields once for debugging
  4322. if not hasattr(self, "_fan_fields_logged"):
  4323. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  4324. if fan_fields:
  4325. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  4326. self._fan_fields_logged = True
  4327. if "cooling_fan_speed" in data:
  4328. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  4329. if "big_fan1_speed" in data:
  4330. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  4331. if "big_fan2_speed" in data:
  4332. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  4333. if "heatbreak_fan_speed" in data:
  4334. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  4335. # Calibration stage tracking
  4336. if "stg_cur" in data:
  4337. new_stg = data["stg_cur"]
  4338. prev_stg = self.state.stg_cur
  4339. # Always log ANY stg_cur change for debugging filament operations
  4340. if new_stg != prev_stg:
  4341. logger.debug(
  4342. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  4343. )
  4344. # A stage we cannot name is the one worth seeing at the default
  4345. # log level: the DEBUG line above is off in normal running, so
  4346. # an unnamed stage otherwise reaches the user as "Unknown stage
  4347. # (72)" on a card with nothing behind it to say when it
  4348. # happened or what the printer was doing. Recorded once per
  4349. # stage number per session, with the stage it came from and the
  4350. # print state, which is what naming it later needs. Guarded on
  4351. # the int type because the field is whatever the firmware sent.
  4352. if (
  4353. isinstance(new_stg, int)
  4354. and not isinstance(new_stg, bool)
  4355. # -1 is Bambuddy's own "not in a stage" sentinel and the
  4356. # initial value of the field, not something the firmware
  4357. # reports; every print would otherwise report it on the way
  4358. # out of its last real stage.
  4359. and new_stg != -1
  4360. and new_stg not in STAGE_NAMES
  4361. and new_stg not in self._unnamed_stages_seen
  4362. ):
  4363. self._unnamed_stages_seen.add(new_stg)
  4364. logger.info(
  4365. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  4366. "state=%s progress=%s%% layer=%s/%s",
  4367. self.serial_number,
  4368. new_stg,
  4369. self.model,
  4370. prev_stg,
  4371. get_stage_name(prev_stg),
  4372. self.state.state,
  4373. self.state.progress,
  4374. self.state.layer_num,
  4375. self.state.total_layers,
  4376. )
  4377. self.state.stg_cur = new_stg
  4378. # #1721 end-of-print finish photo trigger.
  4379. # Stage 22 = "Filament unloading" fires at end-of-print AND
  4380. # during mid-print color swaps. The end-of-print gate
  4381. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  4382. # — those signals only line up at the real end. Edge-only
  4383. # (prev != 22) so the trigger fires once per stage entry.
  4384. if (
  4385. new_stg == 22
  4386. and prev_stg != 22
  4387. and self._was_running
  4388. and not self._finish_photo_captured
  4389. and self.on_finish_photo_moment
  4390. ):
  4391. progress = self.state.progress or 0.0
  4392. layer_num = self.state.layer_num or 0
  4393. total_layers = self.state.total_layers or 0
  4394. remaining = self.state.remaining_time or 0
  4395. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  4396. if is_end_of_print:
  4397. self._finish_photo_captured = True
  4398. logger.info(
  4399. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  4400. f"progress={progress}, layer={layer_num}/{total_layers}, "
  4401. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  4402. )
  4403. self.on_finish_photo_moment(
  4404. {
  4405. "trigger": "stage_22",
  4406. "filename": self._previous_gcode_file or self.state.gcode_file,
  4407. "subtask_name": self.state.subtask_name,
  4408. "timelapse_was_active": self._timelapse_during_print,
  4409. }
  4410. )
  4411. if "stg" in data:
  4412. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  4413. # Temperature data
  4414. temps = {}
  4415. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  4416. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  4417. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  4418. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  4419. # Log ALL keys in print data for H2D temperature discovery
  4420. all_keys = sorted(data.keys())
  4421. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  4422. self._temp_fields_logged = True
  4423. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  4424. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  4425. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  4426. self._vir_slot_logged = True
  4427. # Log nozzle hardware info fields (once)
  4428. nozzle_fields = {
  4429. k: v
  4430. for k, v in data.items()
  4431. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  4432. }
  4433. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  4434. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  4435. self._nozzle_fields_logged = True
  4436. # Parse active extruder from device.extruder.state bit 8
  4437. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  4438. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  4439. if "device" in data and isinstance(data.get("device"), dict):
  4440. device = data["device"]
  4441. # One-shot identification probe: surface whatever the firmware uses to
  4442. # name itself so an unknown model in a support bundle becomes self-
  4443. # diagnosing. INFO level so it shows up without debug logging. Falls
  4444. # back to dumping device.keys() if none of the known fields are present
  4445. # (so a future Bambu rename like `model_name` is still observable).
  4446. if not getattr(self, "_device_id_logged", False):
  4447. id_fields = {
  4448. k: device.get(k)
  4449. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  4450. if k in device
  4451. }
  4452. if id_fields:
  4453. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  4454. else:
  4455. logger.info(
  4456. "[%s] Device identification: no known id fields; device.keys=%s",
  4457. self.serial_number,
  4458. sorted(device.keys()),
  4459. )
  4460. self._device_id_logged = True
  4461. self._parse_extruder_position(data)
  4462. # Log device.extruder structure for active extruder
  4463. if "device" in data and isinstance(data.get("device"), dict):
  4464. device = data["device"]
  4465. if "extruder" in device:
  4466. ext_data = device["extruder"]
  4467. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4468. if "state" in ext_data:
  4469. state_val = ext_data["state"]
  4470. # Extract bits 12-14 (3 bits) for switch state
  4471. switch_state = (state_val >> 12) & 0x7
  4472. self._debug_on_change(
  4473. "extruder_state",
  4474. state_val,
  4475. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4476. self.serial_number,
  4477. state_val,
  4478. switch_state,
  4479. )
  4480. # Log 'cur' field if present (might indicate current/active extruder)
  4481. if "cur" in ext_data:
  4482. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4483. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4484. # it first. Repeated here so _update_state stays a complete "absorb this
  4485. # payload" step for any other caller; re-parsing the same block is free.
  4486. self._parse_fila_switch(data)
  4487. self._parse_extruder_slots(data)
  4488. if "bed_temper" in data:
  4489. temps["bed"] = float(data["bed_temper"])
  4490. if "bed_target_temper" in data:
  4491. temps["bed_target"] = float(data["bed_target_temper"])
  4492. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4493. has_h2d_extruder_info = (
  4494. "device" in data
  4495. and isinstance(data.get("device"), dict)
  4496. and "extruder" in data["device"]
  4497. and isinstance(data["device"]["extruder"].get("info"), list)
  4498. and len(data["device"]["extruder"]["info"]) >= 2
  4499. )
  4500. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4501. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4502. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4503. if "nozzle_temper" in data:
  4504. if has_h2d_extruder_info:
  4505. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4506. else:
  4507. temps["nozzle"] = float(data["nozzle_temper"])
  4508. if "nozzle_target_temper" in data:
  4509. if has_h2d_extruder_info:
  4510. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4511. else:
  4512. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4513. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4514. if not has_h2d_extruder_info:
  4515. # Try multiple possible field names used by different firmware versions
  4516. if "nozzle_temper_2" in data:
  4517. val = float(data["nozzle_temper_2"])
  4518. if -50 < val < 500: # Valid temp range
  4519. temps["nozzle_2"] = val
  4520. else:
  4521. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4522. elif "right_nozzle_temper" in data:
  4523. val = float(data["right_nozzle_temper"])
  4524. if -50 < val < 500: # Valid temp range
  4525. temps["nozzle_2"] = val
  4526. else:
  4527. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4528. if "nozzle_target_temper_2" in data:
  4529. val = float(data["nozzle_target_temper_2"])
  4530. if 0 <= val < 500: # Valid temp range
  4531. temps["nozzle_2_target"] = val
  4532. else:
  4533. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4534. elif "right_nozzle_target_temper" in data:
  4535. val = float(data["right_nozzle_target_temper"])
  4536. if 0 <= val < 500: # Valid temp range
  4537. temps["nozzle_2_target"] = val
  4538. else:
  4539. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4540. # Also check for left nozzle as primary (some H2 models)
  4541. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4542. temps["nozzle"] = float(data["left_nozzle_temper"])
  4543. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4544. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4545. if "chamber_temper" in data:
  4546. chamber_val = float(data["chamber_temper"])
  4547. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4548. # Check if we recently set the target locally (within 5 seconds)
  4549. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4550. respect_local = (time.time() - local_set_time) < 5.0
  4551. # H2D protocol: chamber_temper encoding indicates heater state
  4552. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4553. # - When < 500: direct Celsius current temp only - heater is OFF
  4554. if -50 < chamber_val < 100:
  4555. # Direct value = heater is OFF
  4556. temps["chamber"] = chamber_val
  4557. if not respect_local:
  4558. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4559. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4560. else:
  4561. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4562. # Try to decode if it looks like an encoded value
  4563. if chamber_val > 500:
  4564. mqtt_target = int(chamber_val) // 65536
  4565. current = int(chamber_val) % 65536
  4566. logger.debug(
  4567. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4568. )
  4569. if -50 < current < 100:
  4570. temps["chamber"] = float(current)
  4571. # Store decoded target for later use, but DON'T set chamber_heating here!
  4572. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4573. # which is the authoritative source the slicer uses.
  4574. if not respect_local:
  4575. if 0 <= mqtt_target <= 60:
  4576. # Store as "decoded" target - may be overridden by explicit target fields
  4577. temps["_chamber_decoded_target"] = float(mqtt_target)
  4578. # Chamber target temperature (set by print file or display)
  4579. if "mc_target_cham" in data:
  4580. mc_target = float(data["mc_target_cham"])
  4581. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4582. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4583. if 0 <= mc_target <= 60:
  4584. temps["chamber_target"] = mc_target
  4585. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4586. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4587. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4588. try:
  4589. if "info" in data and isinstance(data["info"], dict):
  4590. info_temp = data["info"].get("temp")
  4591. if info_temp is not None and "chamber" not in temps:
  4592. # Check for encoded value (target * 65536 + current)
  4593. if info_temp > 500:
  4594. # Decode: extract current temperature and target
  4595. target = info_temp // 65536
  4596. current = info_temp % 65536
  4597. temps["chamber"] = float(current)
  4598. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4599. if "_chamber_decoded_target" not in temps:
  4600. temps["_chamber_decoded_target"] = float(target)
  4601. logger.debug(
  4602. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4603. )
  4604. elif -50 < info_temp < 100:
  4605. # Valid direct temperature - heater is OFF
  4606. temps["chamber"] = float(info_temp)
  4607. temps["chamber_target"] = 0.0 # Direct value means heater off
  4608. self._debug_on_change(
  4609. "info_temp_direct",
  4610. info_temp,
  4611. "[%s] info.temp direct: %s°C (heater OFF)",
  4612. self.serial_number,
  4613. info_temp,
  4614. )
  4615. # H2D series: Dual extruder temps are in device.extruder.info array
  4616. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4617. if "device" in data and isinstance(data["device"], dict):
  4618. device = data["device"]
  4619. # Parse dual extruder temperatures
  4620. extruder_data = device.get("extruder", {})
  4621. extruder_info = extruder_data.get("info", [])
  4622. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4623. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4624. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4625. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4626. if has_h2d_extruder_info:
  4627. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4628. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4629. if "temp" in extruder_info[0]:
  4630. temp_val = extruder_info[0]["temp"]
  4631. if temp_val > 500:
  4632. # Encoded format: temp = target * 65536 + current
  4633. target = temp_val // 65536
  4634. current = temp_val % 65536
  4635. if -50 < current < 500:
  4636. temps["nozzle_2"] = float(current)
  4637. if 0 < target < 500:
  4638. temps["nozzle_2_target"] = float(target)
  4639. temps["nozzle_2_heating"] = target > 0 and current < target
  4640. elif -50 < temp_val < 500:
  4641. # Direct Celsius value = heater is OFF
  4642. temps["nozzle_2"] = float(temp_val)
  4643. temps["nozzle_2_target"] = 0.0
  4644. temps["nozzle_2_heating"] = False
  4645. # Left nozzle (extruder 1) - only for dual nozzle printers
  4646. # H2D protocol: temp field encoding depends on value
  4647. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4648. # - When < 500: direct Celsius current temp only - heater is OFF
  4649. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4650. ext1 = extruder_info[1]
  4651. temp_val = ext1["temp"]
  4652. # Check if we recently set the target locally (within 5 seconds)
  4653. # If so, don't let MQTT data overwrite it
  4654. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4655. respect_local_target = (time.time() - local_set_time) < 5.0
  4656. if temp_val > 500:
  4657. # Encoded format: temp = target * 65536 + current
  4658. target = temp_val // 65536
  4659. current = temp_val % 65536
  4660. if 0 < target < 500 and not respect_local_target:
  4661. temps["nozzle_target"] = float(target)
  4662. if -50 < current < 500:
  4663. temps["nozzle"] = float(current)
  4664. # Heating = encoded AND we're using the MQTT target (not local override)
  4665. # If local target is being respected, use local target to determine heating
  4666. if respect_local_target:
  4667. local_target = self.state.temperatures.get("nozzle_target", 0)
  4668. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4669. else:
  4670. temps["nozzle_heating"] = target > 0 and current < target
  4671. elif -50 < temp_val < 500:
  4672. # Direct Celsius = heater is OFF (or at target with heater off)
  4673. temps["nozzle"] = float(temp_val)
  4674. if not respect_local_target:
  4675. temps["nozzle_target"] = 0.0
  4676. temps["nozzle_heating"] = False # Direct = not heating
  4677. # The extruder snow is read by _parse_extruder_position, before the
  4678. # AMS block of the same frame (tray_now resolution needs it first).
  4679. # Parse bed heating state from device.bed.info.temp encoding
  4680. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4681. bed_data = device.get("bed", {})
  4682. bed_info = bed_data.get("info", {})
  4683. if "temp" in bed_info:
  4684. temp_val = bed_info["temp"]
  4685. if temp_val > 500:
  4686. target = temp_val // 65536
  4687. current = temp_val % 65536
  4688. temps["bed_heating"] = target > 0 and current < target
  4689. else:
  4690. temps["bed_heating"] = False
  4691. # Parse chamber temp from device.ctc.info.temp if not already set
  4692. ctc_data = device.get("ctc", {})
  4693. ctc_info = ctc_data.get("info", {})
  4694. # Parse airduct mode (0=cooling, 1=heating)
  4695. airduct_data = device.get("airduct", {})
  4696. if "modeCur" in airduct_data:
  4697. new_mode = airduct_data["modeCur"]
  4698. if new_mode != self.state.airduct_mode:
  4699. logger.debug(
  4700. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4701. )
  4702. self.state.airduct_mode = new_mode
  4703. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4704. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4705. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4706. # AIR_FUN enum: 1=part cooling, 2=aux, 3=chamber/exhaust,
  4707. # 10=second aux (FAN_REMOTE_COOLING_1). Aux 2 is the right fan and
  4708. # 10 the left on the P2S, the other way round on the X2D (#3373;
  4709. # Bambu Studio's N7.json / N6.json). The airduct `parts` list only
  4710. # contains the fans that physically exist, so it doubles as a
  4711. # presence signal for the two P2S/X2D add-on kits:
  4712. # - id 10 (second auxiliary part cooling fan) — reported ONLY here,
  4713. # never mirrored into a flat big_fanX_speed field.
  4714. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4715. # big_fan2_speed, but the part is only listed when the External
  4716. # Exhaust Fan kit (get_version module "eef") is installed.
  4717. # `state` is already a 0-100 percentage.
  4718. parts = airduct_data.get("parts")
  4719. if isinstance(parts, list):
  4720. speeds: dict[int, int] = {}
  4721. for part in parts:
  4722. if not isinstance(part, dict):
  4723. continue
  4724. try:
  4725. # Studio reads the id with get_flag_bits(id, 4, 8),
  4726. # so mask after shifting for the same reason `state`
  4727. # is masked below. Every id seen in the wild
  4728. # (16/32/48/160) decodes identically either way —
  4729. # this is consistency, not a live bug.
  4730. part_id = (int(part["id"]) >> 4) & 0xFF
  4731. # `state` is bit-packed like its sibling `range`
  4732. # (end << 16 | start), so take only the low 8 bits —
  4733. # the same decode Bambu Studio does with
  4734. # get_flag_bits(state, 0, 8). Without the mask a
  4735. # packed value would clamp to 100 instead of
  4736. # decoding to the real percentage.
  4737. part_state = int(part["state"]) & 0xFF
  4738. except (KeyError, ValueError, TypeError):
  4739. continue
  4740. # Ids seen across the support-package archive:
  4741. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4742. # 6 (H2 series, unmapped), 10 second aux.
  4743. speeds[part_id] = max(0, min(100, part_state))
  4744. # Absence in this list is what tells us a kit is NOT fitted,
  4745. # so it may only be trusted when the list is a full
  4746. # inventory rather than a diff frame. `device.airduct` is
  4747. # pushed field by field — the `modeCur` handler above exists
  4748. # for exactly that reason — and a truncated `parts` read as
  4749. # gospel would retract both accessory badges mid-print and
  4750. # start rejecting `aux2` on a printer that has the fan.
  4751. #
  4752. # Every airduct layout in the support-package archive
  4753. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4754. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4755. # part cooling fan and the aux fan, neither of which is
  4756. # optional on any machine that reports an airduct at all.
  4757. # A list carrying both is therefore a complete inventory; a
  4758. # list missing either is a partial frame, and we take its
  4759. # speeds without touching presence.
  4760. is_full_inventory = 1 in speeds and 2 in speeds
  4761. left_aux_speed = speeds.get(10)
  4762. if left_aux_speed is None and not is_full_inventory:
  4763. # Partial frame that didn't mention the second aux fan —
  4764. # keep whatever we already knew about it.
  4765. left_aux_speed = self.state.left_aux_fan_speed
  4766. if left_aux_speed != self.state.left_aux_fan_speed:
  4767. logger.debug(
  4768. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4769. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4770. )
  4771. # A FULL parts list without id 10 means the second aux fan is
  4772. # not installed — report None so the UI can hide the widget.
  4773. self.state.left_aux_fan_speed = left_aux_speed
  4774. # id 3 present == chamber exhaust fan installed (base P2S
  4775. # omits it). Only ever retracted on a full inventory.
  4776. if 3 in speeds:
  4777. self.state.exhaust_fan_present = True
  4778. elif is_full_inventory:
  4779. self.state.exhaust_fan_present = False
  4780. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  4781. # Check if we recently set the target locally (within 5 seconds)
  4782. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4783. respect_local_target = (time.time() - local_set_time) < 5.0
  4784. # Log ctc_info contents for debugging
  4785. if ctc_info:
  4786. self._debug_on_change(
  4787. "ctc_info_keys",
  4788. tuple(ctc_info.keys()),
  4789. "[%s] ctc_info keys: %s",
  4790. self.serial_number,
  4791. list(ctc_info.keys()),
  4792. )
  4793. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  4794. # (what the slicer shows). This OVERRIDES any previously decoded target.
  4795. explicit_target = None
  4796. if "target" in ctc_info:
  4797. target_val = ctc_info["target"]
  4798. logger.debug(
  4799. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  4800. )
  4801. # Filter out invalid values (valid chamber target is 0-60°C)
  4802. if 0 <= target_val <= 60 and not respect_local_target:
  4803. explicit_target = float(target_val)
  4804. temps["chamber_target"] = explicit_target # Override any previous value
  4805. logger.debug(
  4806. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  4807. )
  4808. # Parse chamber temp from ctc.info.temp - may be encoded
  4809. if "temp" in ctc_info and "chamber" not in temps:
  4810. temp_val = ctc_info["temp"]
  4811. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  4812. if temp_val > 500:
  4813. # Encoded value: decode target and current
  4814. decoded_target = temp_val // 65536
  4815. current = temp_val % 65536
  4816. temps["chamber"] = float(current)
  4817. logger.debug(
  4818. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  4819. )
  4820. # Determine which target to use for heating state:
  4821. # Priority: local target > explicit target > decoded target
  4822. if respect_local_target:
  4823. local_target = self.state.temperatures.get("chamber_target", 0)
  4824. temps["chamber_heating"] = local_target > 0 and current < local_target
  4825. elif explicit_target is not None:
  4826. # Use explicit ctc.info.target - this is what slicer sees
  4827. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  4828. else:
  4829. # Fallback to decoded target only if no explicit target available
  4830. if not respect_local_target and "chamber_target" not in temps:
  4831. temps["chamber_target"] = float(decoded_target)
  4832. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  4833. else:
  4834. # Direct value (not encoded) - heater is OFF
  4835. temps["chamber"] = float(temp_val)
  4836. temps["chamber_heating"] = False
  4837. except Exception as e:
  4838. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  4839. if temps:
  4840. # Handle chamber_target: prefer explicit over decoded
  4841. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  4842. # No explicit target available, use decoded target from chamber_temper
  4843. temps["chamber_target"] = temps["_chamber_decoded_target"]
  4844. # Remove internal temp key before merging
  4845. temps.pop("_chamber_decoded_target", None)
  4846. # Merge new temps into existing, preserving valid values when new ones are filtered out
  4847. for key, value in temps.items():
  4848. self.state.temperatures[key] = value
  4849. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  4850. if "bed" in temps and self.on_bed_temp_update:
  4851. self.on_bed_temp_update(temps["bed"])
  4852. # Calculate chamber_heating after all targets are known
  4853. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  4854. if "chamber" in temps and "chamber_heating" not in temps:
  4855. current = self.state.temperatures.get("chamber", 0)
  4856. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4857. respect_local = (time.time() - local_set_time) < 5.0
  4858. if respect_local:
  4859. # Use locally-set target
  4860. target = self.state.temperatures.get("chamber_target", 0)
  4861. else:
  4862. # Use explicit/decoded target from MQTT
  4863. target = self.state.temperatures.get("chamber_target", 0)
  4864. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  4865. self._debug_on_change(
  4866. "chamber_heating",
  4867. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  4868. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  4869. self.serial_number,
  4870. target,
  4871. current,
  4872. self.state.temperatures["chamber_heating"],
  4873. respect_local,
  4874. )
  4875. # Debug: log chamber value if it was updated
  4876. if "chamber" in temps:
  4877. self._debug_on_change(
  4878. "chamber_temp",
  4879. (
  4880. self.state.temperatures.get("chamber"),
  4881. self.state.temperatures.get("chamber_target"),
  4882. self.state.temperatures.get("chamber_heating"),
  4883. ),
  4884. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  4885. self.serial_number,
  4886. self.state.temperatures.get("chamber"),
  4887. self.state.temperatures.get("chamber_target"),
  4888. self.state.temperatures.get("chamber_heating"),
  4889. )
  4890. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  4891. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  4892. if "nozzle" in temps and "nozzle_heating" not in temps:
  4893. current = self.state.temperatures.get("nozzle", 0)
  4894. target = self.state.temperatures.get("nozzle_target", 0)
  4895. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  4896. # Parse HMS (Health Management System) errors
  4897. if "hms" in data:
  4898. hms_list = data["hms"]
  4899. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  4900. self.state.hms_errors = []
  4901. verify_failed = False
  4902. if isinstance(hms_list, list):
  4903. for hms in hms_list:
  4904. if isinstance(hms, dict):
  4905. # HMS format: {"attr": attribute_code, "code": error_code}
  4906. # attr contains module/severity info, code contains error number
  4907. # Both are needed to construct the wiki URL
  4908. attr = hms.get("attr", 0)
  4909. code = hms.get("code", 0)
  4910. if isinstance(attr, str):
  4911. attr = int(attr.replace("0x", ""), 16) if attr else 0
  4912. if isinstance(code, str):
  4913. code = int(code.replace("0x", ""), 16) if code else 0
  4914. # attr is module, module no., part, part no. (a byte each);
  4915. # code is the alert level (high 16 bits) then the error
  4916. # (low 16). The level is 1 error (task stopped), 2 warning
  4917. # (task paused), 3 notification; 0 is invalid. This is how
  4918. # Bambu Studio decodes it (DevHMSItem::parse_hms_info). It
  4919. # used to be read from attr bits 8-15, which is the part
  4920. # byte (#2728).
  4921. severity = (code >> 16) & 0xFFFF
  4922. # Module is in attr byte 3 (bits 24-31)
  4923. module = (attr >> 24) & 0xFF
  4924. # Skip non-error status codes. A real fault has a level of
  4925. # at least 1 in the high half, so its code is >= 0x10000
  4926. # and clears this; lower values are status/phase
  4927. # indicators some firmware sends during normal printing.
  4928. if code < 0x4000:
  4929. continue
  4930. # Skip user-action echoes — the printer firmware emits these
  4931. # as part of normal user-cancel sequences. They're not faults
  4932. # and shouldn't count toward "X problem" badges or surface as
  4933. # red pips on the printer card. Backend's notification path
  4934. # already suppresses 0500_400E for the same reason.
  4935. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  4936. if short_code in _HMS_USER_ACTION_CODES:
  4937. continue
  4938. # The full 16-char identifier is the firmware's matching key
  4939. # and the HMS catalogue's key for this kind of fault; the
  4940. # short code discards the part and alert-level groups. The
  4941. # action table still has some short-form entries, so that
  4942. # lookup falls back to it.
  4943. full_code = f"{attr:08X}{code:08X}"
  4944. if full_code == HMS_MQTT_VERIFY_FAILED:
  4945. verify_failed = True
  4946. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  4947. if not actions:
  4948. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  4949. self.state.hms_errors.append(
  4950. HMSError(
  4951. code=f"0x{code:x}" if code else "0x0",
  4952. attr=attr,
  4953. module=module,
  4954. # No fallback: 0 is Bambu's "invalid" level, and
  4955. # promoting it would render it as a fault.
  4956. severity=severity,
  4957. actions=actions,
  4958. job_id=self.state.subtask_id,
  4959. full_code=full_code,
  4960. description=describe_fault(full_code, self.serial_number[:3]),
  4961. )
  4962. )
  4963. self._apply_mqtt_verify_state(verify_failed)
  4964. # Parse print_error - this is a different error format than HMS
  4965. # print_error is a 32-bit integer where:
  4966. # - High 16 bits contain module info (e.g., 0x0500)
  4967. # - Low 16 bits contain error code (e.g., 0x8061)
  4968. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  4969. if "print_error" in data:
  4970. print_error = data["print_error"]
  4971. if print_error and print_error != 0:
  4972. # Extract components: MMMMEEEE -> MMMM_EEEE
  4973. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  4974. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  4975. # Values below 0x4000 are status/phase indicators, not real errors.
  4976. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  4977. # Some firmware sends low values like 0x0002 during normal printing.
  4978. if error < 0x4000:
  4979. pass # Skip — not a real error
  4980. else:
  4981. # Store in a format that matches the community error database
  4982. # attr stores the full 32-bit value for reconstruction
  4983. # code stores the short format string for lookup
  4984. short_code = f"{module:04X}_{error:04X}"
  4985. logger.debug(
  4986. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  4987. )
  4988. # Same user-action filter as the hms[] branch above — print_error
  4989. # carries the same cancel echoes (e.g. 0500_400E) and they must
  4990. # not surface as faults on the printer card.
  4991. if short_code in _HMS_USER_ACTION_CODES:
  4992. pass # cancel echo — silently drop
  4993. else:
  4994. # Only add if not already in HMS errors (avoid duplicates)
  4995. existing_short_codes = set()
  4996. for e in self.state.hms_errors:
  4997. # Extract short code from existing errors
  4998. e_module = (e.attr >> 16) & 0xFFFF
  4999. # The low half only: an hms[] code carries its alert
  5000. # level above it (0x18061 for 0500_8061), and read
  5001. # whole it never matched, listing the fault twice (M-U9).
  5002. e_error = (int(e.code.replace("0x", ""), 16) & 0xFFFF) if e.code else 0
  5003. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  5004. if short_code not in existing_short_codes:
  5005. # Bambu's HMS catalog keys by 3-letter device code (the SN
  5006. # prefix) and a 16-char short error code without the
  5007. # underscore separator we store internally.
  5008. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5009. # Bambu pushes the current job as `subtask_id` on the
  5010. # state stream; the HMS-action commands echo it back as
  5011. # `job_id`. The error payload itself doesn't carry the
  5012. # id, so snapshot it from the live state at parse time
  5013. # and freeze it on the HMSError so subsequent
  5014. # job changes don't invalidate the action.
  5015. job_id = self.state.subtask_id
  5016. logger.debug(
  5017. "[%s, %s] HMS available actions: %s (job_id=%s)",
  5018. self.serial_number[:3],
  5019. short_code.replace("_", ""),
  5020. actions,
  5021. job_id,
  5022. )
  5023. self.state.hms_errors.append(
  5024. HMSError(
  5025. code=f"0x{error:x}",
  5026. attr=print_error, # Store full value for display
  5027. module=module >> 8, # High byte of module (e.g., 0x05)
  5028. # print_error has no level field; its error
  5029. # number's first digit carries it instead.
  5030. severity=alert_level_from_print_error(error),
  5031. actions=actions,
  5032. job_id=job_id,
  5033. # print_error is already 32-bit — `f"{print_error:08X}"`
  5034. # is the firmware's matching key with no truncation.
  5035. full_code=f"{print_error:08X}",
  5036. description=describe_fault(f"{print_error:08X}", self.serial_number[:3]),
  5037. )
  5038. )
  5039. # Parse home_flag first so SD-card detection below can prefer it.
  5040. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  5041. # bit 23 = door-open (X1 family only).
  5042. home_flag = None
  5043. if "home_flag" in data:
  5044. home_flag = data["home_flag"]
  5045. if home_flag < 0:
  5046. home_flag = home_flag & 0xFFFFFFFF
  5047. # SD card presence: the only remaining consumer is the firmware-update
  5048. # precondition check (firmware_update.py). Use the top-level `sdcard`
  5049. # field when present with a permissive truthy check covering the
  5050. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  5051. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  5052. # when a card is inserted, which caused the badge to flap before the
  5053. # badge was removed entirely.
  5054. if "sdcard" in data:
  5055. raw_sdcard = data["sdcard"]
  5056. if isinstance(raw_sdcard, str):
  5057. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  5058. else:
  5059. self.state.sdcard = bool(raw_sdcard)
  5060. self.state.sdcard_reported = True
  5061. if home_flag is not None:
  5062. store_to_sdcard = bool((home_flag >> 11) & 1)
  5063. if store_to_sdcard != self.state.store_to_sdcard:
  5064. logger.debug(
  5065. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  5066. )
  5067. self.state.store_to_sdcard = store_to_sdcard
  5068. # Door open detection — source depends on printer family:
  5069. # X1 series (X1, X1C, X1E): home_flag bit 23
  5070. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  5071. # Both share the same bitmask (0x00800000) but live in different fields.
  5072. model_upper = (self.model or "").upper().strip()
  5073. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  5074. if is_x1_family and home_flag is not None:
  5075. door_open = (home_flag & 0x00800000) != 0
  5076. if door_open != self.state.door_open:
  5077. logger.debug(
  5078. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  5079. self.serial_number,
  5080. self.state.door_open,
  5081. door_open,
  5082. home_flag,
  5083. )
  5084. self.state.door_open = door_open
  5085. elif not is_x1_family and "stat" in data:
  5086. try:
  5087. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  5088. door_open = (stat_value & 0x00800000) != 0
  5089. if door_open != self.state.door_open:
  5090. logger.debug(
  5091. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  5092. self.serial_number,
  5093. self.state.door_open,
  5094. door_open,
  5095. stat_value,
  5096. )
  5097. self.state.door_open = door_open
  5098. except (ValueError, TypeError):
  5099. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  5100. # Parse timelapse status (recording active during print). Status frames
  5101. # only — the project_file ack echoes back the per-job timelapse flag we
  5102. # asked for, which is a request, not the recorder's state (#3040).
  5103. if "timelapse" in data and is_printer_status_frame(data):
  5104. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  5105. self.state.timelapse = data["timelapse"] is True
  5106. # Track if timelapse was ever active during this print
  5107. if self.state.timelapse and self._was_running:
  5108. self._timelapse_during_print = True
  5109. # Parse ipcam/live view status
  5110. if "ipcam" in data:
  5111. ipcam_data = data["ipcam"]
  5112. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  5113. if isinstance(ipcam_data, dict):
  5114. # Check ipcam_record field for live view status
  5115. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  5116. # Check timelapse field (H2D sends it here, not in xcam)
  5117. if "timelapse" in ipcam_data:
  5118. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  5119. if timelapse_enabled != self.state.timelapse:
  5120. logger.debug(
  5121. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  5122. )
  5123. self.state.timelapse = timelapse_enabled
  5124. # Track if timelapse was ever active during this print
  5125. if self.state.timelapse and self._was_running:
  5126. self._timelapse_during_print = True
  5127. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  5128. else:
  5129. self.state.ipcam = ipcam_data is True
  5130. # Parse WiFi signal strength (dBm)
  5131. if "wifi_signal" in data:
  5132. wifi_signal = data["wifi_signal"]
  5133. self._debug_on_change(
  5134. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  5135. )
  5136. if isinstance(wifi_signal, (int, float)):
  5137. self.state.wifi_signal = int(wifi_signal)
  5138. elif isinstance(wifi_signal, str):
  5139. # Handle string format like "-52dBm"
  5140. try:
  5141. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  5142. except ValueError:
  5143. pass # Ignore unparseable wifi_signal strings; field is non-critical
  5144. # Detect ethernet connection: printers on ethernet with WiFi disabled
  5145. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  5146. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  5147. from backend.app.utils.printer_models import has_ethernet
  5148. if has_ethernet(self.model):
  5149. self.state.wired_network = self.state.wifi_signal == -90
  5150. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5151. if "spd_lvl" in data:
  5152. new_speed = data["spd_lvl"]
  5153. if new_speed != self.state.speed_level:
  5154. logger.debug(
  5155. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  5156. )
  5157. self.state.speed_level = new_speed
  5158. # Parse skipped objects from printer status (s_obj field)
  5159. # This allows us to restore skipped objects state after reconnection
  5160. if "s_obj" in data:
  5161. s_obj = data["s_obj"]
  5162. if isinstance(s_obj, list):
  5163. # Update skipped objects from printer's list
  5164. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  5165. if new_skipped != self.state.skipped_objects:
  5166. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  5167. self.state.skipped_objects = new_skipped
  5168. for oid in new_skipped:
  5169. self._unconfirmed_skips.pop(oid, None)
  5170. self._check_unconfirmed_skips()
  5171. # Parse chamber light status from lights_report
  5172. if "lights_report" in data:
  5173. lights = data["lights_report"]
  5174. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  5175. if isinstance(lights, list):
  5176. for light in lights:
  5177. if isinstance(light, dict) and light.get("node") == "chamber_light":
  5178. new_light_state = light.get("mode") == "on"
  5179. if new_light_state != self.state.chamber_light:
  5180. logger.debug(
  5181. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  5182. )
  5183. self.state.chamber_light = new_light_state
  5184. break
  5185. # Parse nozzle hardware info (single nozzle printers)
  5186. if "nozzle_type" in data:
  5187. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  5188. if "nozzle_diameter" in data:
  5189. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  5190. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  5191. # Left nozzle
  5192. if "left_nozzle_type" in data:
  5193. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  5194. if "left_nozzle_diameter" in data:
  5195. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  5196. # Right nozzle
  5197. if "right_nozzle_type" in data:
  5198. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  5199. if "right_nozzle_diameter" in data:
  5200. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  5201. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  5202. if "nozzle_type_2" in data:
  5203. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  5204. if "nozzle_diameter_2" in data:
  5205. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  5206. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  5207. if "device" in data and isinstance(data["device"], dict):
  5208. device = data["device"]
  5209. nozzle_data = device.get("nozzle", {})
  5210. # H2C rack position (#2800). `tar_id` is where the carriage is
  5211. # headed, `src_id` where it came from; mid-swap they differ, so
  5212. # dispatch prefers tar_id and falls back to src_id. Both are
  5213. # sticky — the field is only pushed when it changes, so an
  5214. # absent key must leave the last known value alone rather than
  5215. # reset it to None.
  5216. if isinstance(nozzle_data, dict):
  5217. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  5218. if key not in nozzle_data:
  5219. continue
  5220. try:
  5221. parsed_id = int(nozzle_data[key])
  5222. except (TypeError, ValueError):
  5223. continue
  5224. if getattr(self.state, attr) != parsed_id:
  5225. setattr(self.state, attr, parsed_id)
  5226. # DEBUG, not INFO: these move on every tool change, so
  5227. # a long multi-material print would otherwise write
  5228. # thousands of lines. The dispatch log records both
  5229. # values once per print, which is where triage needs
  5230. # them. Same reasoning as the one-shot `nozzle_info`
  5231. # log below.
  5232. logger.debug(
  5233. "[%s] Nozzle rack %s -> %s",
  5234. self.serial_number,
  5235. key,
  5236. parsed_id,
  5237. )
  5238. nozzle_info = nozzle_data.get("info", [])
  5239. if isinstance(nozzle_info, list):
  5240. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  5241. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  5242. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  5243. # for hover cards on both the L/R indicator and the nozzle rack card.
  5244. if nozzle_info:
  5245. self.state.nozzle_rack = sorted(
  5246. [
  5247. {
  5248. "id": n.get("id", i),
  5249. "type": str(n.get("type", "")),
  5250. "diameter": str(n.get("diameter", "")),
  5251. "wear": n.get("wear"),
  5252. "stat": n.get("stat"),
  5253. # H2C uses "tm", H2D uses "max_temp"
  5254. "max_temp": n.get("max_temp") or n.get("tm", 0),
  5255. # H2C uses "sn", H2D uses "serial_number"
  5256. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  5257. # H2C uses "color_m", H2D uses "filament_colour"
  5258. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  5259. # H2C uses "fila_id", H2D uses "filament_id"
  5260. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  5261. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  5262. }
  5263. for i, n in enumerate(nozzle_info)
  5264. ],
  5265. key=lambda x: x["id"],
  5266. )
  5267. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  5268. self._nozzle_rack_logged = True
  5269. logger.debug(
  5270. "[%s] Nozzle info: %d entries, IDs: %s",
  5271. self.serial_number,
  5272. len(nozzle_info),
  5273. [n.get("id") for n in nozzle_info],
  5274. )
  5275. for nozzle in nozzle_info:
  5276. idx = nozzle.get("id", 0)
  5277. if idx < len(self.state.nozzles):
  5278. if "type" in nozzle and nozzle["type"]:
  5279. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  5280. if "diameter" in nozzle:
  5281. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  5282. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  5283. # (these fields aren't sent in every MQTT push, only when changed)
  5284. ams_data = self.state.raw_data.get("ams")
  5285. vt_tray_data = self.state.raw_data.get("vt_tray")
  5286. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  5287. mapping_data = self.state.raw_data.get("mapping")
  5288. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  5289. # as a dict but consumers expect a list. Without this, the dev mode probe
  5290. # below can release the GIL (via publish), letting the event-loop thread
  5291. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  5292. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  5293. data["vt_tray"] = [data["vt_tray"]]
  5294. self.state.raw_data = data
  5295. # Restore preserved fields BEFORE any work that may release the GIL
  5296. # (e.g. _probe_developer_mode publishes an MQTT message).
  5297. if ams_data is not None:
  5298. self.state.raw_data["ams"] = ams_data
  5299. if vt_tray_data is not None:
  5300. self.state.raw_data["vt_tray"] = vt_tray_data
  5301. if ams_extruder_map_data is not None:
  5302. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  5303. if mapping_data is not None and "mapping" not in data:
  5304. self.state.raw_data["mapping"] = mapping_data
  5305. # Parse developer LAN mode from "fun" field
  5306. if "fun" in data:
  5307. try:
  5308. fun_val = data["fun"]
  5309. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  5310. self.state.developer_mode = (fun_int & 0x20000000) == 0
  5311. except (ValueError, TypeError):
  5312. pass
  5313. elif self.state.developer_mode is None and not self._dev_mode_probed:
  5314. # No "fun" field — A1/P1 series never send it, so we need to probe.
  5315. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  5316. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  5317. # after connect to let the MQTT session stabilize — probing too early
  5318. # can destabilize some firmware MQTT brokers (#887).
  5319. if not self._dev_mode_needs_probe and len(data) > 30:
  5320. # First full status without "fun" — mark that probe is needed
  5321. self._dev_mode_needs_probe = True
  5322. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  5323. self._probe_developer_mode()
  5324. elif self._dev_mode_needs_probe:
  5325. logger.debug(
  5326. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  5327. self.serial_number,
  5328. time.monotonic() - self._connect_time,
  5329. )
  5330. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  5331. # Probe was sent but no response yet — check for timeout.
  5332. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  5333. # may deliver status pushes but silently drop commands (#887).
  5334. elapsed = time.monotonic() - self._dev_mode_probe_time
  5335. if elapsed > 10.0:
  5336. self._dev_mode_probe_failures += 1
  5337. logger.warning(
  5338. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  5339. self.serial_number,
  5340. elapsed,
  5341. self._dev_mode_probe_failures,
  5342. )
  5343. self._dev_mode_probe_seq = None
  5344. if self._dev_mode_probe_failures >= 2:
  5345. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  5346. else:
  5347. # Allow retry on next full status message
  5348. self._dev_mode_probed = False
  5349. # Zombie session detection: if an ams_filament_setting command has been
  5350. # pending for >10s with no response, the publish path is likely dead (#887).
  5351. if self._last_ams_cmd_time > 0:
  5352. elapsed = time.monotonic() - self._last_ams_cmd_time
  5353. if elapsed > 10.0:
  5354. self._ams_cmd_unanswered += 1
  5355. logger.warning(
  5356. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  5357. self.serial_number,
  5358. elapsed,
  5359. self._ams_cmd_unanswered,
  5360. )
  5361. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  5362. if self._ams_cmd_unanswered >= 2:
  5363. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  5364. self._ams_cmd_unanswered = 0
  5365. # Log mapping data when received (for usage tracking debugging)
  5366. if "mapping" in data:
  5367. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  5368. # Log state transitions for debugging
  5369. if "gcode_state" in data:
  5370. logger.debug(
  5371. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  5372. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  5373. )
  5374. # Detect print start (state changes TO RUNNING with a file)
  5375. current_file = self.state.gcode_file or self.state.current_print
  5376. is_new_print = (
  5377. self.state.state == "RUNNING"
  5378. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  5379. and self._previous_gcode_state != "RUNNING"
  5380. and current_file
  5381. and not self._was_running # Prevent duplicates when resuming from PAUSE
  5382. )
  5383. # Also detect if file changed while running (new print started)
  5384. is_file_change = (
  5385. self.state.state == "RUNNING"
  5386. and current_file
  5387. and current_file != self._previous_gcode_file
  5388. and self._previous_gcode_file is not None
  5389. )
  5390. # Track RUNNING state for more robust completion detection
  5391. running_first_observed = False
  5392. if self.state.state == "RUNNING" and current_file:
  5393. if not self._was_running:
  5394. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  5395. # Check if timelapse was enabled in the same message (xcam parsed before this)
  5396. if self.state.timelapse:
  5397. self._timelapse_during_print = True
  5398. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  5399. # Mark this as the first RUNNING observation of the session.
  5400. # If is_new_print also fires below, on_print_start handles
  5401. # baseline capture and we suppress on_print_running_observed
  5402. # to avoid double-capture. If is_new_print does NOT fire
  5403. # (Bambuddy started mid-print — the #1304 guard suppressed
  5404. # it), main.py needs this hook to catch the restart-recovery
  5405. # case (#1485 follow-up).
  5406. running_first_observed = True
  5407. self._was_running = True
  5408. self._completion_triggered = False
  5409. if is_new_print or is_file_change:
  5410. # Clear any old HMS errors when a new print starts
  5411. self.state.hms_errors = []
  5412. # The last print's pauses; this one's come from its 3MF (#2984).
  5413. self.state.pause_points = []
  5414. self.state.pause_warned_layers = set()
  5415. # Reset layer tracking for new print (needed for layer-based timelapse)
  5416. # #3317: only above 1. Every print reports layer 1 first, which
  5417. # clears a higher value; a previous print that ended on layer 1
  5418. # would make this print's own first layer look stale.
  5419. self._stale_layer_num = self.state.layer_num if self.state.layer_num > 1 else 0
  5420. self.state.layer_num = 0
  5421. # Reset total_layers so the previous print's value can't bleed into
  5422. # this print's usage-tracker split (#1771 follow-on to the
  5423. # preservation guard at the `total_layer_num` parse above — that
  5424. # guard ignores firmware-reset 0s, so the explicit reset has to
  5425. # happen here instead).
  5426. #
  5427. # #2702: reset to *this frame's* total, not to 0. The frame that
  5428. # trips the new-print detection can carry the new print's
  5429. # `total_layer_num` as well — the parse above has already applied
  5430. # it, and zeroing unconditionally threw it away. That looked
  5431. # harmless but is not recoverable: Bambu firmware sends only
  5432. # changed fields, so the printer never offers the total again, and
  5433. # the print runs to completion at `n/0` in the UI, in
  5434. # `{total_layers}` notifications, and as the usage-split
  5435. # denominator. The value only reappears on the next full pushall
  5436. # (reconnect / Force Refresh), which is why the symptom looked
  5437. # random and why a *stable* connection made it worse.
  5438. self.state.total_layers = total_from_this_frame
  5439. # If the starting frame brought no total, ask for one. Costs one
  5440. # MQTT message per print and covers the ordering where the printer
  5441. # published the total a frame or two before the state flip.
  5442. self._total_layers_refresh_armed = not total_from_this_frame
  5443. if self._total_layers_refresh_armed:
  5444. self._request_push_all()
  5445. # Reset completion tracking for new print
  5446. self._was_running = True
  5447. self._completion_triggered = False
  5448. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5449. self._finish_photo_captured = False
  5450. # #2547: rearm the end-of-print telemetry probe for the new print
  5451. self._eop_probe_armed = True
  5452. self._eop_probe_open = False
  5453. self._eop_probe_frames = 0
  5454. self._eop_probe_last = {}
  5455. # Reset last valid progress/layer for usage tracking
  5456. self._last_valid_progress = 0.0
  5457. self._last_valid_layer_num = 0
  5458. # Clear and seed tray change log for mid-print usage splitting
  5459. self.state.tray_change_log.clear()
  5460. # Seeded with the assigned spools by usage_tracker.on_print_start.
  5461. self.state.spool_change_log = []
  5462. tn = self.state.tray_now
  5463. if (
  5464. (0 <= tn <= 15)
  5465. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  5466. or (128 <= tn <= 135)
  5467. or tn == 254
  5468. ):
  5469. self.state.tray_change_log.append((tn, 0))
  5470. # Initialize timelapse tracking based on current state
  5471. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5472. # so self.state.timelapse may already be set from this message.
  5473. # We preserve that value instead of blindly resetting to False.
  5474. if self.state.timelapse:
  5475. self._timelapse_during_print = True
  5476. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5477. else:
  5478. self._timelapse_during_print = False
  5479. if (is_new_print or is_file_change) and self.on_print_start:
  5480. logger.info(
  5481. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5482. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5483. )
  5484. self.on_print_start(
  5485. {
  5486. "filename": current_file,
  5487. "subtask_name": self.state.subtask_name,
  5488. "remaining_time": self.state.remaining_time * 60
  5489. if self.state.remaining_time > 0
  5490. else None, # Convert minutes to seconds
  5491. "raw_data": data,
  5492. "ams_mapping": self._captured_ams_mapping,
  5493. }
  5494. )
  5495. elif running_first_observed and self.on_print_running_observed:
  5496. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5497. # print, so the #1304 first-push guard suppressed on_print_start,
  5498. # but we still need main.py to capture a fresh timelapse baseline
  5499. # before the printer uploads the in-flight MP4. Same payload
  5500. # shape as on_print_start so the consumer can reuse fields.
  5501. logger.info(
  5502. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5503. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5504. )
  5505. self.on_print_running_observed(
  5506. {
  5507. "filename": current_file,
  5508. "subtask_name": self.state.subtask_name,
  5509. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5510. "raw_data": data,
  5511. "ams_mapping": self._captured_ams_mapping,
  5512. }
  5513. )
  5514. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5515. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5516. # This handles cases where server restarts during a print
  5517. should_trigger_completion = (
  5518. self.state.state in ("FINISH", "FAILED")
  5519. and not self._completion_triggered
  5520. and self.on_print_complete
  5521. and (
  5522. self._previous_gcode_state == "RUNNING" # Normal transition
  5523. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5524. # Pre-print failure (#1111): printer rejected the job during setup
  5525. # — wrong nozzle size, AMS error, etc. The print never reaches
  5526. # RUNNING, so without this branch neither the RUNNING check nor
  5527. # _was_running match and the queue item stays stuck at "printing".
  5528. # Restricted to FAILED from pre-print states so a stale FAILED on
  5529. # first connection (prev=None) still can't accidentally fire.
  5530. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5531. )
  5532. )
  5533. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5534. if (
  5535. self.state.state == "IDLE"
  5536. and self._previous_gcode_state == "RUNNING"
  5537. and not self._completion_triggered
  5538. and self.on_print_complete
  5539. ):
  5540. should_trigger_completion = True
  5541. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5542. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5543. if (
  5544. not should_trigger_completion
  5545. and self.state.state in ("FINISH", "FAILED")
  5546. and self._previous_gcode_state != self.state.state
  5547. ):
  5548. logger.info(
  5549. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5550. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5551. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5552. )
  5553. # Mark as triggered so state is clean for the next print cycle
  5554. self._completion_triggered = True
  5555. if should_trigger_completion:
  5556. if self.state.state == "FINISH":
  5557. status = "completed"
  5558. elif self.state.state == "FAILED":
  5559. status = "failed"
  5560. else:
  5561. status = "aborted"
  5562. logger.info(
  5563. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5564. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5565. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5566. f"timelapse_during_print: {self._timelapse_during_print}"
  5567. )
  5568. timelapse_was_active = self._timelapse_during_print
  5569. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5570. # external-spool-only, HMS halt, or firmware variant that skips
  5571. # the unload phase) fire the finish-photo moment now. Bed has
  5572. # already dropped, framing is worse, but we still capture.
  5573. # Only on successful completion — aborted/failed prints don't
  5574. # produce a meaningful finish photo.
  5575. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5576. self._finish_photo_captured = True
  5577. logger.info(
  5578. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5579. f"stage-22 never fired; capturing at FINISH-state transition"
  5580. )
  5581. self.on_finish_photo_moment(
  5582. {
  5583. "trigger": "finish_state",
  5584. "filename": self._previous_gcode_file or current_file,
  5585. "subtask_name": self.state.subtask_name,
  5586. "timelapse_was_active": timelapse_was_active,
  5587. }
  5588. )
  5589. self._completion_triggered = True
  5590. self._was_running = False
  5591. self._timelapse_during_print = False # Reset for next print
  5592. # Include HMS errors for failure reason detection
  5593. hms_errors_data = [e.completion_payload() for e in self.state.hms_errors or []]
  5594. self.on_print_complete(
  5595. {
  5596. "status": status,
  5597. "subtask_id": self.state.subtask_id,
  5598. "filename": self._previous_gcode_file or current_file,
  5599. "subtask_name": self.state.subtask_name,
  5600. "raw_data": data,
  5601. "timelapse_was_active": timelapse_was_active,
  5602. "hms_errors": hms_errors_data,
  5603. "ams_mapping": self._captured_ams_mapping,
  5604. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5605. "last_progress": self._last_valid_progress,
  5606. "last_layer_num": self._last_valid_layer_num,
  5607. }
  5608. )
  5609. self._captured_ams_mapping = None
  5610. # Same lifecycle as the mapping above: it described *this* print.
  5611. # Leaving it set would hand the next print an answer about where a
  5612. # different file went, and a stale "internal storage" reading costs
  5613. # an archive that the FTPS sweep would have found (#2780).
  5614. self.state.current_project_url = None
  5615. self._previous_gcode_state = self.state.state
  5616. if current_file:
  5617. self._previous_gcode_file = current_file
  5618. if self.on_state_change:
  5619. self.on_state_change(self.state)
  5620. def _request_push_all(self):
  5621. """Request full status update from printer."""
  5622. if self._client:
  5623. message = {"pushing": {"command": "pushall"}}
  5624. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5625. def _probe_developer_mode(self):
  5626. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5627. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5628. For these, we detect developer mode by sending a harmless command and
  5629. checking whether the printer accepts or rejects it:
  5630. - result="success" → developer mode ON (commands accepted)
  5631. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5632. The probe re-sends the current external slot configuration so it's a no-op
  5633. when the command succeeds. If there's no external slot data yet, we send a
  5634. reset (empty filament) which is also safe.
  5635. """
  5636. if not self._client or not self.state.connected:
  5637. return
  5638. self._dev_mode_probed = True
  5639. self._dev_mode_probe_time = time.monotonic()
  5640. self._sequence_id += 1
  5641. seq = str(self._sequence_id)
  5642. self._dev_mode_probe_seq = seq
  5643. # Build probe command: re-send current external slot config (no-op on success)
  5644. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5645. current = vt_tray[0] if vt_tray else {}
  5646. command = {
  5647. "print": {
  5648. "command": "ams_filament_setting",
  5649. "ams_id": 255,
  5650. "tray_id": 0,
  5651. "slot_id": 0,
  5652. "tray_info_idx": current.get("tray_info_idx", ""),
  5653. "tray_type": current.get("tray_type", ""),
  5654. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5655. "tray_color": current.get("tray_color", "00000000"),
  5656. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5657. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5658. "sequence_id": seq,
  5659. }
  5660. }
  5661. setting_id = current.get("setting_id")
  5662. if setting_id:
  5663. command["print"]["setting_id"] = setting_id
  5664. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5665. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5666. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5667. """Reconcile developer_mode with the printer's own command-verification verdict.
  5668. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5669. control commands are being refused, so it outranks the probe in both
  5670. directions:
  5671. * present → developer_mode is definitively False, whatever the probe
  5672. concluded. The probe can only read the response to its own
  5673. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5674. instead, so the probe answers ENABLED while every print silently dies
  5675. (#2732).
  5676. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5677. probe, so a user who enables Developer Mode and restarts the printer
  5678. isn't stuck behind a verdict nothing would ever revisit.
  5679. A False that came from the probe or the ``fun`` bit is left alone — this
  5680. only ever unwinds its own latch.
  5681. """
  5682. if verify_failed:
  5683. if not self._dev_mode_from_hms:
  5684. logger.warning(
  5685. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5686. "rejecting control commands, so prints, temperature changes and filament "
  5687. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5688. self.serial_number,
  5689. HMS_MQTT_VERIFY_FAILED,
  5690. )
  5691. self._dev_mode_from_hms = True
  5692. self.state.developer_mode = False
  5693. return
  5694. if not self._dev_mode_from_hms:
  5695. return
  5696. logger.info(
  5697. "[%s] HMS %s cleared — re-probing developer mode",
  5698. self.serial_number,
  5699. HMS_MQTT_VERIFY_FAILED,
  5700. )
  5701. self._dev_mode_from_hms = False
  5702. self.state.developer_mode = None
  5703. self._dev_mode_probed = False
  5704. self._dev_mode_needs_probe = False
  5705. def _handle_dev_mode_probe_response(self, data: dict):
  5706. """Handle response to the developer mode probe command.
  5707. Sets developer_mode based on whether the printer accepted or rejected the command.
  5708. Three outcomes, not two. An explicit ``success`` proves commands are
  5709. accepted and an explicit verify-failure proves they are not, but anything
  5710. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5711. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5712. ``result`` at all, while refusing every control command and reporting
  5713. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5714. is what put ``developer_mode: pass`` in the support bundle of a printer
  5715. that had not accepted a command all day (#2732). Leaving it unknown makes
  5716. the connection diagnostic report ``skip``, which is the honest answer.
  5717. """
  5718. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5719. self._dev_mode_probe_failures = 0 # Reset on any response
  5720. result = data.get("result", "")
  5721. reason = data.get("reason", "")
  5722. if result == "failed" and "verify failed" in reason:
  5723. self.state.developer_mode = False
  5724. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5725. elif str(result).lower() == "success":
  5726. self.state.developer_mode = True
  5727. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5728. else:
  5729. # An HMS verdict already recorded here is real evidence; don't let an
  5730. # inconclusive probe response wipe it back to unknown.
  5731. if not self._dev_mode_from_hms:
  5732. self.state.developer_mode = None
  5733. logger.info(
  5734. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5735. "the printer neither confirmed nor refused the command",
  5736. self.serial_number,
  5737. result,
  5738. reason,
  5739. )
  5740. if self.on_state_change:
  5741. self.on_state_change(self.state)
  5742. def _request_version(self):
  5743. """Request firmware version info from printer."""
  5744. if self._client:
  5745. self._sequence_id += 1
  5746. message = {
  5747. "info": {
  5748. "sequence_id": str(self._sequence_id),
  5749. "command": "get_version",
  5750. }
  5751. }
  5752. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5753. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5754. def request_status_update(self) -> bool:
  5755. """Request a full status update from the printer (public API).
  5756. Sends both pushall and get_accessories commands to refresh all data
  5757. including nozzle hardware info.
  5758. Returns:
  5759. True if the request was sent, False if not connected.
  5760. """
  5761. if not self._client or not self.state.connected:
  5762. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5763. return False
  5764. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  5765. self._request_push_all()
  5766. # Note: get_accessories returns stale nozzle data on H2D.
  5767. # The correct nozzle data comes from push_status response.
  5768. return True
  5769. def _prime_kprofile_request(self):
  5770. """Send a priming K-profile request on connect.
  5771. Bambu printers often ignore the first K-profile request after connection,
  5772. so we send a dummy request on connect to 'prime' the system.
  5773. """
  5774. if self._client:
  5775. self._sequence_id += 1
  5776. command = {
  5777. "print": {
  5778. "command": "extrusion_cali_get",
  5779. "filament_id": "",
  5780. "nozzle_diameter": "0.4",
  5781. "sequence_id": str(self._sequence_id),
  5782. }
  5783. }
  5784. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  5785. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5786. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  5787. """Connect to the printer MQTT broker.
  5788. Args:
  5789. loop: The asyncio event loop to use for thread-safe callbacks.
  5790. If not provided, will try to get the running loop.
  5791. """
  5792. self._loop = loop
  5793. BambuMQTTClient._client_instance_counter += 1
  5794. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  5795. self._client = mqtt.Client(
  5796. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  5797. client_id=client_id,
  5798. protocol=mqtt.MQTTv311,
  5799. )
  5800. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  5801. # tracking (#1164). The default ceiling of 20 wedges sessions after
  5802. # ~16-20 cumulative commands; lifting it well above any realistic
  5803. # session count keeps QoS=1 working without changing wire-protocol
  5804. # behaviour across printer models.
  5805. self._client.max_inflight_messages_set(1000)
  5806. self._client.username_pw_set("bblp", self.access_code)
  5807. self._client.on_connect = self._on_connect
  5808. self._client.on_disconnect = self._on_disconnect
  5809. self._client.on_subscribe = self._on_subscribe
  5810. self._client.on_message = self._on_message
  5811. # TLS setup - Bambu uses self-signed certs
  5812. ssl_context = ssl.create_default_context()
  5813. ssl_context.check_hostname = False
  5814. ssl_context.verify_mode = ssl.CERT_NONE
  5815. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  5816. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  5817. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  5818. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  5819. # bare-metal installs whose build allows TLS 1.0.
  5820. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  5821. self._client.tls_set_context(ssl_context)
  5822. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  5823. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  5824. # Keepalive: paho sends PINGREQs at this interval, broker considers
  5825. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  5826. # real network loss (45s), not so aggressive that transient hiccups
  5827. # trigger false disconnects. Stale detection (60s no messages) handles
  5828. # the P1S/P1P firmware bug where the broker stops publishing but the
  5829. # TCP connection stays alive.
  5830. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  5831. self._client.loop_start()
  5832. def start_print(
  5833. self,
  5834. filename: str,
  5835. plate_id: int = 1,
  5836. ams_mapping: list[int] | None = None,
  5837. bed_levelling: str = "auto",
  5838. flow_cali: str = "auto",
  5839. vibration_cali: bool = True,
  5840. layer_inspect: bool = False,
  5841. timelapse: bool = False,
  5842. use_ams: bool = True,
  5843. nozzle_offset_cali: str = "auto",
  5844. nozzle_mapping: str | None = None,
  5845. nozzle_slot_extruders: str | None = None,
  5846. plate_uses_only_external: bool = False,
  5847. ):
  5848. """Start a print job on the printer.
  5849. The file should already be uploaded to the printer's root directory via FTP.
  5850. Args:
  5851. filename: Name of the uploaded file
  5852. plate_id: Plate number to print (default 1)
  5853. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  5854. Global tray ID = (ams_id * 4) + slot_id, external = 254
  5855. timelapse: Record timelapse video
  5856. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  5857. if the bed was levelled recently, matching BambuStudio).
  5858. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  5859. vibration_cali: Vibration compensation calibration
  5860. layer_inspect: First layer AI inspection
  5861. use_ams: Use AMS for automatic filament changes
  5862. plate_uses_only_external: The caller determined from the plate's
  5863. own filament list that it prints only from the spool holder;
  5864. use_ams=False then stands even if the mapping names a real
  5865. tray (one another plate of the file uses, #3087)
  5866. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  5867. (dual-nozzle printers only — silently ignored on single-nozzle).
  5868. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  5869. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  5870. AND the printer is dual-nozzle, parsed and injected as the
  5871. `nozzle_mapping` array on the dispatched project_file so the
  5872. firmware honours the user's slicer pick instead of falling
  5873. back to "last matching nozzle" auto-pick. Silently ignored
  5874. on single-nozzle printers.
  5875. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  5876. MQTT extruder indices, derived from the 3MF when no
  5877. BambuStudio capture exists (#2800). Consulted only on
  5878. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  5879. not already supply one; resolved here into physical rack
  5880. positions using the live `device.nozzle` state. When it
  5881. cannot be resolved the field is omitted and the firmware
  5882. picks, as it did before this existed.
  5883. Returns True when the start command was published, False otherwise
  5884. (not connected, or the printer is already busy — see the run-state
  5885. guard below).
  5886. """
  5887. # Never dispatch project_file to a printer that is not idle (#2598).
  5888. # This is the single publish choke point for every dispatch path — the
  5889. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  5890. # forwarded job all funnel through here — so one guard covers them all.
  5891. # The firmware rejects a start while busy with 0500_4004 ("Device is
  5892. # busy and cannot start a new task"), and on an A1 mini that error
  5893. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  5894. # start targets; only the active-print states are refused. (A
  5895. # transport-level QoS-1 replay on reconnect would bypass this guard;
  5896. # _on_connect empties paho's outbox before it can re-send (#3454).)
  5897. if self.state.state in _ACTIVE_PRINT_STATES:
  5898. logger.warning(
  5899. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  5900. self.serial_number,
  5901. self.state.state,
  5902. filename,
  5903. )
  5904. return False
  5905. if self._client and self.state.connected:
  5906. # Bambu print command format — matches Bambu Studio's format.
  5907. # The calibration/leveling fields (timelapse, bed_leveling,
  5908. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  5909. # every model. An earlier revision integer-encoded them for the H2
  5910. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  5911. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  5912. # sends plain booleans, and the integer encoding made the H2S
  5913. # silently skip flow-dynamics calibration (#1478). use_ams is the
  5914. # one field that genuinely must stay boolean: H2D Pro firmware
  5915. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  5916. # what actually caused the wrong-extruder routing behind #1386.
  5917. # Dual-nozzle routing for external spool (254 = deputy/left,
  5918. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  5919. # H2 firmware family but is single-nozzle, despite sharing serial
  5920. # prefix "094" with H2D. Prefer runtime detection from
  5921. # device.extruder.info (set in _handle_push_status); fall back to
  5922. # model name for the brief window after connect before push data
  5923. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  5924. # as the primary signal.
  5925. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  5926. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  5927. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  5928. ams_mapping2 = []
  5929. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  5930. # ams_mapping and relies on ams_mapping2 for external spool details.
  5931. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  5932. # with 0700_8012 "Failed to get AMS mapping table".
  5933. flat_ams_mapping = []
  5934. if ams_mapping is not None:
  5935. for tray_id in ams_mapping:
  5936. # Ensure tray_id is an integer (may be string from JSON)
  5937. tray_id = int(tray_id) if tray_id is not None else -1
  5938. if tray_id == -1:
  5939. # Unmapped filament slot
  5940. flat_ams_mapping.append(-1)
  5941. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  5942. elif tray_id >= 254:
  5943. # External/virtual spool. BambuStudio convention:
  5944. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  5945. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  5946. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  5947. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  5948. # for external spool, but BambuStudio always sends ams_id=255
  5949. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  5950. # firmware to target AMS tray 0 instead of external spool, leading
  5951. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  5952. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  5953. flat_ams_mapping.append(-1)
  5954. ext_ams_id = tray_id if is_dual_nozzle else 255
  5955. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  5956. elif tray_id >= 128:
  5957. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  5958. flat_ams_mapping.append(tray_id)
  5959. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  5960. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  5961. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  5962. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  5963. # — both CONFIRMED against the firmware's own mapping
  5964. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  5965. _wire_ams, _wire_slot, _ = _a2l
  5966. flat_ams_mapping.append(_wire_slot)
  5967. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  5968. else:
  5969. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  5970. ams_id = tray_id // 4
  5971. slot_id = tray_id % 4
  5972. flat_ams_mapping.append(tray_id)
  5973. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  5974. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  5975. # printers — the mapping is authoritative about whether this print
  5976. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  5977. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  5978. # H2S falls through here now (#1386): it is single-nozzle and was
  5979. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  5980. # without an AMS attached.
  5981. #
  5982. # Two symmetric corrections:
  5983. #
  5984. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  5985. # use_ams=True even if it arrived False. A print sent to a Virtual
  5986. # Printer is sliced against the VP, which advertises no AMS, so the
  5987. # slicer sends use_ams=false and that gets stamped on the queue item
  5988. # — but at dispatch the scheduler colour-matches a real printer and
  5989. # resolves a real AMS slot. Without this, the stale False reaches the
  5990. # printer, which ignores the mapped slot and aborts at layer 0 on the
  5991. # empty external spool ("not enough filament"). Diagnosed by
  5992. # @Sawtaytoes (#2595, PR #2596).
  5993. #
  5994. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  5995. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  5996. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  5997. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  5998. # status-load race that persisted [-1] (#2589) — and treating it as
  5999. # external silently started the print against an empty feed. A genuine
  6000. # external selection is >=254; unresolved is -1; a loaded tray is
  6001. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  6002. # (or is recomputed upstream) instead of silently going external, and
  6003. # never gets force-enabled by (a) either.
  6004. if ams_mapping and not is_dual_nozzle:
  6005. has_real_tray = any(t is not None and 0 <= int(t) <= 253 for t in ams_mapping)
  6006. all_external = all(t is None or int(t) >= 254 for t in ams_mapping)
  6007. # (Not when the scheduler worked out from the plate's own
  6008. # filament list that it prints only from the spool holder: a
  6009. # real tray here is then one another plate of the file uses.)
  6010. if has_real_tray and not use_ams and not plate_uses_only_external:
  6011. use_ams = True
  6012. logger.info(
  6013. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  6014. self.serial_number,
  6015. )
  6016. elif use_ams and all_external:
  6017. use_ams = False
  6018. logger.info(
  6019. "[%s] All filament slots use external spool — setting use_ams=False",
  6020. self.serial_number,
  6021. )
  6022. # (c) A single-nozzle printer that reported no AMS at all can only
  6023. # print from the spool holder, whatever the mapping says. With
  6024. # nothing set on the holder the matcher resolves no mapping, so
  6025. # neither (a) nor (b) ran and the print went out as use_ams=True,
  6026. # which the firmware refuses with 07FF_8012 "Failed to get AMS
  6027. # mapping table" (#3356). An empty raw_data["ams"] is the
  6028. # printer's own report of no AMS; a missing key means no AMS
  6029. # push has been handled yet (a reconnect), which changes nothing.
  6030. if use_ams and not is_dual_nozzle and self.state.raw_data.get("ams") == []:
  6031. use_ams = False
  6032. logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
  6033. # Unique per-submission identity fields. Hardcoded "0" values caused
  6034. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  6035. # continuations of the same job: the printer reuses gcode_start_time
  6036. # from the prior print with task_id=0, so observers latch onto a stale
  6037. # timestamp and report compounding durations on repeat replays (#1011).
  6038. # BambuStudio mints fresh IDs per submission; matching that behavior
  6039. # makes the printer emit a clean state-transition for each job.
  6040. # md5 is left empty — firmware historically accepts "" as "skip
  6041. # validation" (unlike Studio, we don't have the file's real md5 here
  6042. # without re-reading the upload, and sending a synthetic wrong digest
  6043. # risks activation of md5 verification on some firmwares).
  6044. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  6045. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  6046. # overflows and every submission ends up with the same task_id from
  6047. # the printer's perspective — the printer then treats a fresh dispatch
  6048. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  6049. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  6050. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  6051. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  6052. # Remember it so on_print_start can persist a restart-stable id on
  6053. # the archive even before the printer echoes subtask_id back (#1485).
  6054. self.last_dispatch_subtask_id = submission_id
  6055. self.last_start_refusal = None
  6056. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  6057. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  6058. # only if it wasn't done recently). The paired bool field is true
  6059. # only for the explicit "on" state — for "auto" the bool is false and
  6060. # the int carries the intent, exactly as BambuStudio's SelectMachine
  6061. # sends it. Unknown values fall back to auto.
  6062. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  6063. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  6064. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  6065. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  6066. command = {
  6067. "print": {
  6068. "sequence_id": "20000",
  6069. "command": "project_file",
  6070. "param": f"Metadata/plate_{plate_id}.gcode",
  6071. "url": f"ftp://{filename}",
  6072. "file": filename,
  6073. "md5": "",
  6074. "bed_type": "auto",
  6075. "timelapse": timelapse,
  6076. # bed_leveling stays a JSON bool (true only for "on") and
  6077. # auto_bed_leveling carries the tri-state int — the exact
  6078. # two-field shape BambuStudio sends. The int must stay a plain
  6079. # number, never quoted (#1478 boolean-family concern applies to
  6080. # the *_cali bools, not these companion ints).
  6081. "bed_leveling": bed_levelling == "on",
  6082. "auto_bed_leveling": bed_level_int,
  6083. "flow_cali": flow_cali == "on",
  6084. "vibration_cali": vibration_cali,
  6085. "layer_inspect": layer_inspect,
  6086. "use_ams": use_ams,
  6087. # No "cfg": it is the printer's device-config bitmask
  6088. # (auto-refill, detect-on-insert, chamber light, ...), not a
  6089. # per-job field — BambuStudio's PrintParams has no such
  6090. # member. We used to send "0"; firmware ignores it, but it
  6091. # comes straight back in the project_file ack (#3040).
  6092. # extrude_cali_flag gates flow-dynamics calibration:
  6093. # 0 = never, 1 = force every print, 2 = auto (run only if the
  6094. # filament wasn't calibrated recently). #1721 saw stage 8
  6095. # ("Calibrating dynamic flow") still queued when we send 2 —
  6096. # that is exactly the auto contract (the printer queues the
  6097. # stage and skips it at runtime if recent), not a bug, so 2 is
  6098. # the right wire value for "auto". off/on remain 0/1.
  6099. "extrude_cali_flag": flow_cali_int,
  6100. "extrude_cali_manual_mode": 0,
  6101. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  6102. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  6103. # again the auto contract, not a failure to suppress.
  6104. # BambuStudio exposes the toggle only for dual-nozzle
  6105. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  6106. # firmware never runs a calibration the head doesn't support.
  6107. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  6108. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  6109. "profile_id": "0",
  6110. "project_id": submission_id,
  6111. "subtask_id": submission_id,
  6112. "task_id": submission_id,
  6113. }
  6114. }
  6115. # P2S-specific parameter adjustments
  6116. # P2S printer doesn't support vibration calibration like X1/P1 series
  6117. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  6118. command["print"]["vibration_cali"] = False
  6119. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  6120. # Add AMS mapping if provided
  6121. if ams_mapping is not None:
  6122. command["print"]["ams_mapping"] = flat_ams_mapping
  6123. command["print"]["ams_mapping2"] = ams_mapping2
  6124. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  6125. # `nozzle_mapping` carries per-filament physical nozzle position
  6126. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  6127. # item; parse here so the wire ships an array, matching
  6128. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  6129. # defensively — single-nozzle firmwares would ignore the field
  6130. # but we err on the side of not emitting unrecognised fields. A
  6131. # parse failure is logged but never blocks the dispatch — the
  6132. # firmware will fall back to its auto-pick path, which is the
  6133. # pre-fix behaviour.
  6134. if is_dual_nozzle and nozzle_mapping:
  6135. try:
  6136. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  6137. except json.JSONDecodeError:
  6138. logger.warning(
  6139. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  6140. "project_file (firmware will auto-pick): %r",
  6141. self.serial_number,
  6142. nozzle_mapping,
  6143. )
  6144. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  6145. # never saw the job, so it can never override a real capture. The
  6146. # queue stores extruder indices per filament slot; the physical
  6147. # rack position they resolve to is only knowable here, because the
  6148. # mounted hotend can change between queueing and dispatch.
  6149. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  6150. try:
  6151. slot_extruders = json.loads(nozzle_slot_extruders)
  6152. except (json.JSONDecodeError, TypeError):
  6153. # TypeError covers a caller handing us the list itself
  6154. # rather than its JSON — the field is opaque by contract,
  6155. # and a print must not die over the difference.
  6156. slot_extruders = None
  6157. logger.warning(
  6158. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  6159. "omitting nozzle_mapping (firmware will auto-pick): %r",
  6160. self.serial_number,
  6161. nozzle_slot_extruders,
  6162. )
  6163. if isinstance(slot_extruders, list):
  6164. rack_nozzle_id = (
  6165. self.state.nozzle_rack_tar_id
  6166. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  6167. else self.state.nozzle_rack_src_id
  6168. )
  6169. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  6170. if resolved is None:
  6171. logger.info(
  6172. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  6173. "omitting nozzle_mapping so the firmware picks",
  6174. self.serial_number,
  6175. slot_extruders,
  6176. self.state.nozzle_rack_tar_id,
  6177. self.state.nozzle_rack_src_id,
  6178. )
  6179. else:
  6180. logger.info(
  6181. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  6182. self.serial_number,
  6183. slot_extruders,
  6184. rack_nozzle_id,
  6185. resolved,
  6186. )
  6187. command["print"]["nozzle_mapping"] = resolved
  6188. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  6189. # Remember this dispatch so its echo on the topic is recognised as
  6190. # ours rather than logged as a slicer's.
  6191. self._own_project_file_key = self._project_file_key(command["print"])
  6192. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6193. # Record what we dispatched so /cover can pick the right plate
  6194. # thumbnail even when the printer's gcode_file echo is just the
  6195. # 3MF filename without a plate path (#1166). Match the same
  6196. # subtask_name shape we send so the comparison in the cover route
  6197. # works against state.subtask_name reflected back via MQTT.
  6198. self.state.dispatched_plate_id = plate_id
  6199. self.state.dispatched_subtask = command["print"]["subtask_name"]
  6200. return True
  6201. else:
  6202. # Log why we couldn't send the command
  6203. if not self._client:
  6204. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  6205. elif not self.state.connected:
  6206. logger.error(
  6207. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  6208. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  6209. )
  6210. return False
  6211. def stop_print(self) -> bool:
  6212. """Stop the current print job."""
  6213. if self._client and self.state.connected:
  6214. command = {"print": {"command": "stop", "sequence_id": "0"}}
  6215. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6216. logger.info("[%s] Sent stop print command", self.serial_number)
  6217. return True
  6218. return False
  6219. def set_xcam_option(
  6220. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  6221. ) -> bool:
  6222. """Set an xcam (AI detection) option on the printer.
  6223. Args:
  6224. module_name: The xcam module to control (e.g., "spaghetti_detector",
  6225. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  6226. enabled: Whether to enable or disable the feature
  6227. print_halt: Whether to halt print on detection (only applies to some detectors)
  6228. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  6229. Returns:
  6230. True if command was sent, False if not connected
  6231. """
  6232. if not self._client or not self.state.connected:
  6233. return False
  6234. # auto_recovery_step_loss uses a different command format (print.print_option)
  6235. if module_name == "auto_recovery_step_loss":
  6236. return self._set_print_option("auto_recovery", enabled)
  6237. self._sequence_id += 1
  6238. # Build the xcam control command (exact OrcaSlicer format)
  6239. # Key findings from OrcaSlicer source:
  6240. # - Uses "xcam" wrapper (not "print")
  6241. # - print_halt is ALWAYS true (legacy protocol requirement)
  6242. # - Both "control" and "enable" are set to the same value
  6243. # - halt_print_sensitivity controls actual halt behavior
  6244. command = {
  6245. "xcam": {
  6246. "command": "xcam_control_set",
  6247. "sequence_id": str(self._sequence_id),
  6248. "module_name": module_name,
  6249. "control": enabled,
  6250. "enable": enabled, # old protocol compatibility
  6251. "print_halt": True, # ALWAYS true per OrcaSlicer
  6252. }
  6253. }
  6254. # Only add sensitivity if not "never_halt"
  6255. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  6256. # The module_name field determines which detector's sensitivity is being set
  6257. if sensitivity and sensitivity != "never_halt":
  6258. command["xcam"]["halt_print_sensitivity"] = sensitivity
  6259. command_json = json.dumps(command)
  6260. self._client.publish(self.topic_publish, command_json, qos=1)
  6261. logger.debug(
  6262. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  6263. )
  6264. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  6265. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  6266. # This prevents stale MQTT data from immediately overwriting our change
  6267. self._xcam_hold_start[module_name] = time.time()
  6268. # Update local state immediately for responsive UI
  6269. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  6270. # When spaghetti_detector sensitivity is changed, pileup also changes
  6271. if module_name == "spaghetti_detector":
  6272. self.state.print_options.spaghetti_detector = enabled
  6273. self.state.print_options.print_halt = print_halt
  6274. if sensitivity and sensitivity != "never_halt":
  6275. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  6276. self.state.print_options.halt_print_sensitivity = sensitivity
  6277. self.state.print_options.pileup_sensitivity = sensitivity
  6278. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  6279. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  6280. elif module_name == "first_layer_inspector":
  6281. self.state.print_options.first_layer_inspector = enabled
  6282. elif module_name == "printing_monitor":
  6283. self.state.print_options.printing_monitor = enabled
  6284. elif module_name == "buildplate_marker_detector":
  6285. self.state.print_options.buildplate_marker_detector = enabled
  6286. elif module_name == "allow_skip_parts":
  6287. self.state.print_options.allow_skip_parts = enabled
  6288. elif module_name == "pileup_detector":
  6289. self.state.print_options.pileup_detector = enabled
  6290. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  6291. elif module_name == "clump_detector":
  6292. self.state.print_options.nozzle_clumping_detector = enabled
  6293. if sensitivity and sensitivity != "never_halt":
  6294. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  6295. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  6296. elif module_name == "airprint_detector":
  6297. self.state.print_options.airprint_detector = enabled
  6298. if sensitivity and sensitivity != "never_halt":
  6299. self.state.print_options.airprint_sensitivity = sensitivity
  6300. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  6301. elif module_name == "auto_recovery_step_loss":
  6302. self.state.print_options.auto_recovery_step_loss = enabled
  6303. return True
  6304. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  6305. """Set a print option using the print.print_option command.
  6306. This is different from xcam_control_set and is used for options like:
  6307. - auto_recovery
  6308. - air_print_detect
  6309. - filament_tangle_detect
  6310. - nozzle_blob_detect
  6311. - sound_enable
  6312. Args:
  6313. option_name: The option to control (e.g., "auto_recovery")
  6314. enabled: Whether to enable or disable the option
  6315. Returns:
  6316. True if command was sent, False if not connected
  6317. """
  6318. if not self._client or not self.state.connected:
  6319. return False
  6320. self._sequence_id += 1
  6321. command = {
  6322. "print": {
  6323. "command": "print_option",
  6324. "sequence_id": str(self._sequence_id),
  6325. option_name: enabled,
  6326. }
  6327. }
  6328. command_json = json.dumps(command)
  6329. self._client.publish(self.topic_publish, command_json, qos=1)
  6330. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  6331. # Set hold timer
  6332. hold_key = f"print_option_{option_name}"
  6333. self._xcam_hold_start[hold_key] = time.time()
  6334. # Update local state immediately
  6335. if option_name == "auto_recovery":
  6336. self.state.print_options.auto_recovery_step_loss = enabled
  6337. elif option_name == "auto_switch_filament":
  6338. self.state.ams_filament_backup = enabled
  6339. return True
  6340. def set_ams_filament_backup(self, enabled: bool) -> bool:
  6341. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  6342. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  6343. shape from H2D capture 2026-06-20.
  6344. """
  6345. return self._set_print_option("auto_switch_filament", enabled)
  6346. def start_calibration(
  6347. self,
  6348. bed_leveling: bool = False,
  6349. vibration: bool = False,
  6350. motor_noise: bool = False,
  6351. nozzle_offset: bool = False,
  6352. high_temp_heatbed: bool = False,
  6353. ) -> bool:
  6354. """Start printer calibration with selected options.
  6355. Args:
  6356. bed_leveling: Run bed leveling calibration
  6357. vibration: Run vibration compensation calibration
  6358. motor_noise: Run motor noise cancellation calibration
  6359. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  6360. high_temp_heatbed: Run high-temperature heatbed calibration
  6361. Returns:
  6362. True if command was sent, False if not connected
  6363. """
  6364. if not self._client or not self.state.connected:
  6365. return False
  6366. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  6367. # Bit 0: xcam_cali (not exposed in UI)
  6368. # Bit 1: bed_leveling
  6369. # Bit 2: vibration
  6370. # Bit 3: motor_noise
  6371. # Bit 4: nozzle_cali
  6372. # Bit 5: bed_cali (high-temp heatbed)
  6373. # Bit 6: clumppos_cali (not exposed in UI)
  6374. option = 0
  6375. if bed_leveling:
  6376. option |= 1 << 1
  6377. if vibration:
  6378. option |= 1 << 2
  6379. if motor_noise:
  6380. option |= 1 << 3
  6381. if nozzle_offset:
  6382. option |= 1 << 4
  6383. if high_temp_heatbed:
  6384. option |= 1 << 5
  6385. if option == 0:
  6386. logger.warning("[%s] No calibration options selected", self.serial_number)
  6387. return False
  6388. self._sequence_id += 1
  6389. command = {
  6390. "print": {
  6391. "command": "calibration",
  6392. "sequence_id": str(self._sequence_id),
  6393. "option": option,
  6394. }
  6395. }
  6396. command_json = json.dumps(command)
  6397. self._client.publish(self.topic_publish, command_json, qos=1)
  6398. logger.info(
  6399. f"[{self.serial_number}] Starting calibration: "
  6400. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  6401. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  6402. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  6403. )
  6404. return True
  6405. def disconnect(self, timeout: float = 0):
  6406. """Disconnect from the printer.
  6407. Waits up to *timeout* for paho to report the disconnect, then lets the
  6408. client go without joining its network thread — the callers are route
  6409. handlers (printer edited, deleted, disconnected by hand) running on the
  6410. asyncio thread, and that join has no bound (#3068)."""
  6411. if self._client:
  6412. old_client = self._client
  6413. self._disconnection_event = threading.Event()
  6414. old_client.disconnect()
  6415. # The callback that sets this fires on paho's thread, so it has to
  6416. # be given its window before retire_paho_client detaches it.
  6417. self._disconnection_event.wait(timeout=timeout)
  6418. self._client = None
  6419. retire_paho_client(old_client, self.serial_number)
  6420. self.state.connected = False
  6421. # Deliberately no on_state_change here. paho's disconnect callback
  6422. # used to land during the join, but `_on_disconnect` suppresses
  6423. # itself for a clean disconnect of a printer that reported within
  6424. # the last 10s -- which is every healthy printer -- so a
  6425. # hand-disconnected printer never broadcast one. Announcing it now
  6426. # would fire the connected→disconnected edge in
  6427. # `on_printer_status_change` and notify the user their printer went
  6428. # offline a minute after they disconnected it on purpose (#1752).
  6429. # The callers drop the client from the manager anyway, so the next
  6430. # status read already shows it gone.
  6431. def enable_logging(self, enabled: bool = True):
  6432. """Enable or disable MQTT message logging."""
  6433. self._logging_enabled = enabled
  6434. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6435. def get_logs(self) -> list[MQTTLogEntry]:
  6436. """Get all logged MQTT messages."""
  6437. return list(self._message_log)
  6438. def clear_logs(self):
  6439. """Clear the message log."""
  6440. self._message_log.clear()
  6441. @property
  6442. def logging_enabled(self) -> bool:
  6443. """Check if logging is enabled."""
  6444. return self._logging_enabled
  6445. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6446. """Register a handler invoked for every incoming MQTT message.
  6447. Used by the VP MQTT bridge to republish the printer's report pushes to
  6448. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6449. on paho's network thread and must not block; exceptions are caught.
  6450. """
  6451. if handler not in self._raw_message_handlers:
  6452. self._raw_message_handlers.append(handler)
  6453. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6454. """Unregister a previously-registered raw-message handler."""
  6455. try:
  6456. self._raw_message_handlers.remove(handler)
  6457. except ValueError:
  6458. pass
  6459. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6460. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6461. Used by the VP MQTT bridge to forward slicer-originated commands without
  6462. giving it one of our own sequence ids. Returns False if the
  6463. underlying paho client isn't ready.
  6464. """
  6465. if self._client is None:
  6466. return False
  6467. try:
  6468. info = self._client.publish(topic, payload, qos=qos)
  6469. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6470. except Exception:
  6471. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6472. return False
  6473. def send_drying_command(
  6474. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6475. ):
  6476. """Send AMS drying start/stop command.
  6477. Args:
  6478. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6479. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6480. duration: Drying duration in hours
  6481. mode: 1=start, 0=stop
  6482. filament: Filament type string (e.g. "PLA", "PETG")
  6483. rotate_tray: Whether to rotate the spool during drying for even heat
  6484. """
  6485. if not self._client:
  6486. return False
  6487. self._sequence_id += 1
  6488. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6489. # not actually support drying, but keep the translation consistent). The
  6490. # _drying_targets dict below stays keyed by the normalised id so the
  6491. # on_drying_complete callback matches the telemetry.
  6492. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6493. command = {
  6494. "print": {
  6495. "sequence_id": str(self._sequence_id),
  6496. "command": "ams_filament_drying",
  6497. "ams_id": wire_ams_id,
  6498. "temp": temp,
  6499. "cooling_temp": 20 if mode == 1 else 0,
  6500. "duration": duration,
  6501. "humidity": 0,
  6502. "mode": mode,
  6503. "rotate_tray": rotate_tray,
  6504. "filament": filament,
  6505. "close_power_conflict": False,
  6506. }
  6507. }
  6508. # Log the full wire JSON at INFO so support bundles capture exactly
  6509. # what we sent — needed to diagnose silent rejections (#1447) where
  6510. # the printer ACKs the command but never starts/stops drying.
  6511. # Paired with the ams_filament_drying response-payload INFO log so
  6512. # both halves of the conversation land in the bundle by default.
  6513. wire_json = json.dumps(command)
  6514. self._client.publish(self.topic_publish, wire_json, qos=1)
  6515. logger.info(
  6516. "[%s] Sent ams_filament_drying: %s",
  6517. self.serial_number,
  6518. wire_json,
  6519. )
  6520. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6521. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6522. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6523. # say how much of the requested time the firmware actually ran (#2770).
  6524. if mode == 1:
  6525. self._drying_targets[ams_id] = {
  6526. "filament": filament or "",
  6527. "temp": int(temp),
  6528. "duration_hours": int(duration),
  6529. }
  6530. self._drying_stops_sent.discard(ams_id)
  6531. # A start sent while a cycle is still counting down replaces it
  6532. # without dry_time passing through 0; begin a fresh record so the
  6533. # new target and length are the ones reported (#2863).
  6534. self._dry_cycles.pop(ams_id, None)
  6535. else:
  6536. self._drying_targets.pop(ams_id, None)
  6537. # Remember that this cycle's end is ours, so the cycle-end log
  6538. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6539. # stop always ends the cycle far short of its duration, which is
  6540. # otherwise indistinguishable from the firmware abandoning it.
  6541. self._drying_stops_sent.add(ams_id)
  6542. return True
  6543. @staticmethod
  6544. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6545. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6546. The printer reports ``nozzle_diameter`` **only on the response
  6547. envelope** — the per-filament entries carry just setting_id,
  6548. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6549. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6550. single-nozzle printers regardless of the installed nozzle (#1748),
  6551. which broke the K-Profiles display and, worse, the cali_idx cascade
  6552. in the inventory/Spoolman assign paths that matches on
  6553. nozzle_diameter. Fall back to the envelope value instead, and only
  6554. to "0.4" when the envelope has none either.
  6555. ``or`` rather than a dict default on purpose: it also covers an entry
  6556. that carries the key with an empty value, and stops ``str()`` turning
  6557. a missing envelope value into the literal "None".
  6558. """
  6559. profiles: list[KProfile] = []
  6560. for i, f in enumerate(filaments):
  6561. if not isinstance(f, dict):
  6562. continue
  6563. try:
  6564. profiles.append(
  6565. KProfile(
  6566. # cali_idx is the actual slot/calibration index from the printer
  6567. slot_id=f.get("cali_idx", i),
  6568. extruder_id=int(f.get("extruder_id", 0)),
  6569. nozzle_id=str(f.get("nozzle_id", "")),
  6570. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6571. filament_id=str(f.get("filament_id", "")),
  6572. name=str(f.get("name", "")),
  6573. k_value=str(f.get("k_value", "0.000000")),
  6574. n_coef=str(f.get("n_coef", "0.000000")),
  6575. ams_id=int(f.get("ams_id", 0)),
  6576. tray_id=int(f.get("tray_id", -1)),
  6577. setting_id=f.get("setting_id"),
  6578. )
  6579. )
  6580. except (ValueError, TypeError) as e:
  6581. # Skip malformed entries; the remaining profiles stay usable.
  6582. # Unsolicited broadcasts arrive constantly, so only a response
  6583. # someone is actually waiting on is worth a warning.
  6584. if log_errors:
  6585. logger.warning("Failed to parse K-profile: %s", e)
  6586. else:
  6587. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6588. return profiles
  6589. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6590. """File one calibration-table response under its nozzle diameter.
  6591. ``response_nozzle`` names the table the printer just sent, so that
  6592. bucket is replaced wholesale and every other one is left alone. When
  6593. the envelope carries no diameter, fall back to the diameters the parsed
  6594. profiles claim for themselves — and if there are none of those either,
  6595. keep what we have rather than dropping a table we cannot attribute.
  6596. ``state.kprofiles`` stays a flat list because that is what its readers
  6597. expect; the three assign paths already filter it by ``nozzle_diameter``
  6598. and were quietly finding nothing whenever the last response happened to
  6599. be for a different nozzle.
  6600. """
  6601. buckets: dict[str, list] = {}
  6602. if response_nozzle:
  6603. buckets[str(response_nozzle)] = list(profiles)
  6604. else:
  6605. for profile in profiles:
  6606. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6607. if not buckets:
  6608. return
  6609. self._kprofiles_by_nozzle.update(buckets)
  6610. self.state.kprofiles = [
  6611. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6612. ]
  6613. def _handle_kprofile_response(self, data: dict):
  6614. """Handle K-profile response from printer."""
  6615. response_nozzle = data.get("nozzle_diameter")
  6616. response_seq_id = str(data.get("sequence_id", ""))
  6617. filaments = data.get("filaments", [])
  6618. # Snapshot the map: the asyncio thread adds and removes entries while
  6619. # this MQTT callback thread walks it.
  6620. pending = dict(self._pending_kprofile_requests)
  6621. request = pending.get(response_seq_id)
  6622. if request is None and pending:
  6623. # Firmware that doesn't echo our sequence_id still has to be
  6624. # served, so fall back to the pre-#1748 rule of matching on the
  6625. # nozzle size. Only requests still waiting are eligible, and the
  6626. # sequence_id lookup above has already claimed any response that
  6627. # identifies itself, so this can no longer hand request A's
  6628. # answer to request B when both are in flight.
  6629. request = next(
  6630. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6631. None,
  6632. )
  6633. if pending:
  6634. logger.info(
  6635. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6636. self.serial_number,
  6637. response_nozzle,
  6638. response_seq_id or "?",
  6639. len(filaments),
  6640. request is not None,
  6641. )
  6642. if request is None and pending:
  6643. # A request is outstanding and this isn't its answer. The printer
  6644. # broadcasts extrusion_cali_get unsolicited, so letting this
  6645. # through would replace state.kprofiles with another nozzle's
  6646. # profiles while the caller is still waiting.
  6647. logger.debug(
  6648. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6649. self.serial_number,
  6650. response_nozzle,
  6651. response_seq_id or "?",
  6652. )
  6653. return
  6654. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6655. self._store_kprofiles(profiles, response_nozzle)
  6656. if request is None:
  6657. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6658. # nobody to wake. Worth a line — this is the printer answering
  6659. # somebody else (BambuStudio queries the same report topic), and
  6660. # until it was bucketed by nozzle it was also the quietest way for
  6661. # the AMS card's K values to change underneath us.
  6662. logger.debug(
  6663. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6664. self.serial_number,
  6665. response_nozzle or "?",
  6666. len(profiles),
  6667. )
  6668. return
  6669. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6670. request["profiles"] = profiles
  6671. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6672. # in a different thread than the event loop.
  6673. event = request["event"]
  6674. if self._loop and self._loop.is_running():
  6675. self._loop.call_soon_threadsafe(event.set)
  6676. else:
  6677. # Fallback for when loop is not available
  6678. event.set()
  6679. async def get_kprofiles(
  6680. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6681. ) -> list[KProfile]:
  6682. """Request K-profiles from the printer with retry logic.
  6683. Bambu printers sometimes ignore the first K-profile request, so we
  6684. implement retry logic to ensure reliable retrieval.
  6685. Args:
  6686. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6687. timeout: Timeout in seconds to wait for each response attempt
  6688. max_retries: Maximum number of retry attempts
  6689. Returns:
  6690. List of KProfile objects; empty when the printer has none for
  6691. the nozzle.
  6692. Raises:
  6693. KProfileReadError: not connected, or no answer to any attempt.
  6694. Returning an empty list made that a printer without profiles
  6695. (#3404).
  6696. """
  6697. if not self._client or not self.state.connected:
  6698. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6699. raise KProfileReadError("Printer not connected")
  6700. # Capture current event loop for thread-safe callback
  6701. try:
  6702. self._loop = asyncio.get_running_loop()
  6703. except RuntimeError:
  6704. logger.warning("[%s] No running event loop", self.serial_number)
  6705. raise KProfileReadError("No running event loop") from None
  6706. for attempt in range(max_retries):
  6707. # Register this attempt under its own sequence_id so a concurrent
  6708. # request for a different nozzle size can't consume its response
  6709. # (#1748) — the pending map is keyed by exactly the id we send.
  6710. self._sequence_id += 1
  6711. seq_id = str(self._sequence_id)
  6712. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6713. self._pending_kprofile_requests[seq_id] = request
  6714. # Send the command with nozzle_diameter filter
  6715. command = {
  6716. "print": {
  6717. "command": "extrusion_cali_get",
  6718. "filament_id": "",
  6719. "nozzle_diameter": nozzle_diameter,
  6720. "sequence_id": seq_id,
  6721. }
  6722. }
  6723. logger.info(
  6724. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6725. )
  6726. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6727. # Wait for the response (the handler matches it back to this entry)
  6728. try:
  6729. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6730. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6731. profiles = request["profiles"] or []
  6732. logger.info(
  6733. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6734. )
  6735. return profiles
  6736. except TimeoutError:
  6737. logger.warning(
  6738. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  6739. )
  6740. if attempt < max_retries - 1:
  6741. # Brief delay before retry
  6742. await asyncio.sleep(0.5)
  6743. finally:
  6744. self._pending_kprofile_requests.pop(seq_id, None)
  6745. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  6746. raise KProfileReadError("The printer did not answer the K-profile request")
  6747. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  6748. """Publish a K-profile write and arm its ack slot.
  6749. Registration happens before the publish because the printer answers in
  6750. well under a second — measured at 70-150ms — which is comfortably
  6751. before an async caller gets back to awaiting.
  6752. """
  6753. self._pending_cali_acks[seq_id] = None
  6754. try:
  6755. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6756. except Exception:
  6757. self._pending_cali_acks.pop(seq_id, None)
  6758. raise
  6759. return True
  6760. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  6761. """Wait for the printer's verdict on a K-profile write.
  6762. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  6763. explicitly said ``result: "fail"`` — a timeout returns True with a
  6764. detail string, because "no answer" is not evidence of rejection and
  6765. older firmware may not answer at all. Callers that need certainty read
  6766. the calibration table back.
  6767. Polled rather than event-driven on purpose: the ack is filled in by the
  6768. MQTT callback thread, and polling a dict costs one lookup every 50ms
  6769. for at most a few hundred milliseconds, against the cross-thread
  6770. event plumbing it would otherwise take.
  6771. """
  6772. deadline = time.monotonic() + timeout
  6773. try:
  6774. while time.monotonic() < deadline:
  6775. ack = self._pending_cali_acks.get(seq_id)
  6776. if ack is not None:
  6777. result = str(ack.get("result", "")).lower()
  6778. reason = str(ack.get("reason", "") or "")
  6779. if result == "fail":
  6780. return (False, reason or "printer reported failure")
  6781. return (True, reason)
  6782. await asyncio.sleep(0.05)
  6783. finally:
  6784. self._pending_cali_acks.pop(seq_id, None)
  6785. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  6786. return (True, CALI_ACK_UNCONFIRMED)
  6787. def set_kprofile(
  6788. self,
  6789. filament_id: str,
  6790. name: str,
  6791. k_value: str,
  6792. nozzle_diameter: str = "0.4",
  6793. nozzle_id: str = "HS00-0.4",
  6794. extruder_id: int = 0,
  6795. setting_id: str | None = None,
  6796. slot_id: int = 0,
  6797. cali_idx: int | None = None,
  6798. ) -> str | None:
  6799. """Set/update a K-profile on the printer.
  6800. Args:
  6801. filament_id: Bambu filament identifier
  6802. name: Profile name
  6803. k_value: Pressure advance value (e.g., "0.020000")
  6804. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6805. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  6806. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6807. setting_id: Existing setting ID for updates, None for new
  6808. slot_id: Calibration index (cali_idx) for the profile
  6809. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  6810. Returns:
  6811. The sequence_id the command was sent under, so the caller can
  6812. await the printer's verdict via await_cali_ack. None if the
  6813. command could not be sent.
  6814. """
  6815. if not self._client or not self.state.connected:
  6816. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  6817. return None
  6818. self._sequence_id += 1
  6819. seq_id = str(self._sequence_id)
  6820. # Build the filament entry - printer uses cali_idx for profile identification
  6821. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  6822. # For edits, use the provided cali_idx or slot_id
  6823. if cali_idx is not None:
  6824. effective_cali_idx = cali_idx
  6825. else:
  6826. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6827. # Generate a setting_id for new profiles (required by printer)
  6828. # Format: "PF" + 17 random digits
  6829. import random
  6830. if not setting_id and slot_id == 0:
  6831. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6832. filament_entry = {
  6833. "ams_id": 0,
  6834. "cali_idx": effective_cali_idx,
  6835. "extruder_id": extruder_id,
  6836. "filament_id": filament_id,
  6837. "k_value": k_value,
  6838. "n_coef": "0.000000",
  6839. "name": name,
  6840. "nozzle_diameter": nozzle_diameter,
  6841. "nozzle_id": nozzle_id,
  6842. "setting_id": setting_id if setting_id else "",
  6843. # 0, not -1. Single-nozzle firmware validates this field and
  6844. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  6845. # applying the write anyway, so the rejection looked like noise.
  6846. # Measured on an X1C: flipping only this value turns the ack into
  6847. # `success` (#2718). BambuStudio always sends a real tray_id and
  6848. # defaults it to 0 for a manually entered profile.
  6849. "tray_id": 0,
  6850. }
  6851. command = {
  6852. "print": {
  6853. "command": "extrusion_cali_set",
  6854. "filaments": [filament_entry],
  6855. "nozzle_diameter": nozzle_diameter,
  6856. "sequence_id": seq_id,
  6857. }
  6858. }
  6859. command_json = json.dumps(command)
  6860. logger.info(
  6861. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  6862. )
  6863. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  6864. self._publish_cali_write(command, seq_id)
  6865. return seq_id
  6866. def set_kprofiles_batch(
  6867. self,
  6868. profiles: list[dict],
  6869. nozzle_diameter: str = "0.4",
  6870. ) -> str | None:
  6871. """Set multiple K-profiles in a single command (for dual-nozzle).
  6872. Args:
  6873. profiles: List of profile dicts, each with:
  6874. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  6875. nozzle_diameter: Common nozzle diameter for all profiles
  6876. Returns:
  6877. The sequence_id the command was sent under (see set_kprofile),
  6878. or None if it could not be sent.
  6879. """
  6880. if not self._client or not self.state.connected:
  6881. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  6882. return None
  6883. import random
  6884. self._sequence_id += 1
  6885. seq_id = str(self._sequence_id)
  6886. filament_entries = []
  6887. for p in profiles:
  6888. slot_id = p.get("slot_id", 0)
  6889. cali_idx = p.get("cali_idx")
  6890. if cali_idx is not None:
  6891. effective_cali_idx = cali_idx
  6892. else:
  6893. effective_cali_idx = -1 if slot_id == 0 else slot_id
  6894. setting_id = p.get("setting_id")
  6895. if not setting_id and slot_id == 0:
  6896. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  6897. filament_entries.append(
  6898. {
  6899. "ams_id": 0,
  6900. "cali_idx": effective_cali_idx,
  6901. "extruder_id": p.get("extruder_id", 0),
  6902. "filament_id": p.get("filament_id", ""),
  6903. "k_value": p.get("k_value", "0.020000"),
  6904. "n_coef": "0.000000",
  6905. "name": p.get("name", ""),
  6906. "nozzle_diameter": nozzle_diameter,
  6907. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  6908. "setting_id": setting_id if setting_id else "",
  6909. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  6910. # single-nozzle firmware even though the write lands (#2718).
  6911. "tray_id": 0,
  6912. }
  6913. )
  6914. command = {
  6915. "print": {
  6916. "command": "extrusion_cali_set",
  6917. "filaments": filament_entries,
  6918. "nozzle_diameter": nozzle_diameter,
  6919. "sequence_id": seq_id,
  6920. }
  6921. }
  6922. command_json = json.dumps(command)
  6923. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  6924. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  6925. self._publish_cali_write(command, seq_id)
  6926. return seq_id
  6927. def delete_kprofile(
  6928. self,
  6929. cali_idx: int,
  6930. filament_id: str,
  6931. nozzle_id: str,
  6932. nozzle_diameter: str = "0.4",
  6933. extruder_id: int = 0,
  6934. setting_id: str | None = None,
  6935. ) -> str | None:
  6936. """Delete a K-profile from the printer.
  6937. Args:
  6938. cali_idx: The calibration index (slot_id) of the profile to delete
  6939. filament_id: Bambu filament identifier
  6940. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  6941. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  6942. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  6943. setting_id: Unique setting identifier (for X1C series)
  6944. Returns:
  6945. The sequence_id the command was sent under (see set_kprofile),
  6946. or None if it could not be sent.
  6947. """
  6948. if not self._client or not self.state.connected:
  6949. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  6950. return None
  6951. self._sequence_id += 1
  6952. seq_id = str(self._sequence_id)
  6953. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  6954. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  6955. # Prefer runtime detection from device.extruder.info; fall back to
  6956. # model name. H2S is single-nozzle but shares serial prefix "094" with
  6957. # H2D, so a prefix-only check misclassified it (#1386).
  6958. from backend.app.utils.printer_models import is_dual_nozzle_model
  6959. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6960. if is_dual_nozzle:
  6961. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  6962. command = {
  6963. "print": {
  6964. "command": "extrusion_cali_del",
  6965. "sequence_id": seq_id,
  6966. "extruder_id": extruder_id,
  6967. "nozzle_id": nozzle_id,
  6968. "filament_id": filament_id,
  6969. "cali_idx": cali_idx,
  6970. "nozzle_diameter": nozzle_diameter,
  6971. }
  6972. }
  6973. else:
  6974. # X1C/P1/A1 format: include all fields like the set command
  6975. # The delete command structure should match what set uses
  6976. command = {
  6977. "print": {
  6978. "command": "extrusion_cali_del",
  6979. "sequence_id": seq_id,
  6980. "filament_id": filament_id,
  6981. "cali_idx": cali_idx,
  6982. "setting_id": setting_id if setting_id else "",
  6983. "nozzle_diameter": nozzle_diameter,
  6984. "nozzle_id": nozzle_id,
  6985. "extruder_id": extruder_id,
  6986. }
  6987. }
  6988. command_json = json.dumps(command)
  6989. logger.info(
  6990. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  6991. )
  6992. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  6993. # QoS 1 for reliable delivery (at least once)
  6994. self._publish_cali_write(command, seq_id)
  6995. return seq_id
  6996. # =========================================================================
  6997. # Printer Control Commands
  6998. # =========================================================================
  6999. def pause_print(self) -> bool:
  7000. """Pause the current print job."""
  7001. if not self._client or not self.state.connected:
  7002. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  7003. return False
  7004. command = {"print": {"command": "pause", "sequence_id": "0"}}
  7005. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7006. logger.info("[%s] Sent pause print command", self.serial_number)
  7007. return True
  7008. def resume_print(self) -> bool:
  7009. """Resume a paused print job."""
  7010. if not self._client or not self.state.connected:
  7011. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  7012. return False
  7013. command = {"print": {"command": "resume", "sequence_id": "0"}}
  7014. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7015. logger.info("[%s] Sent resume print command", self.serial_number)
  7016. return True
  7017. def clear_hms_errors(self) -> bool:
  7018. """Clear HMS/print errors on the printer and locally."""
  7019. if not self._client or not self.state.connected:
  7020. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  7021. return False
  7022. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  7023. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7024. self.state.hms_errors = []
  7025. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  7026. return True
  7027. def _handle_skip_objects_answer(self, print_data: dict) -> None:
  7028. """The printer's answer to skip_objects: a refusal is logged and the
  7029. objects are no longer shown as skipped."""
  7030. obj_list = self._skip_commands.pop(str(print_data.get("sequence_id", "")), None)
  7031. result = str(print_data.get("result", "") or "").lower()
  7032. if obj_list is None or result in ("", "success"):
  7033. return
  7034. logger.error(
  7035. "[%s] Printer refused skipping objects %s: result=%s reason=%s",
  7036. self.serial_number,
  7037. obj_list,
  7038. print_data.get("result"),
  7039. print_data.get("reason", ""),
  7040. )
  7041. for oid in obj_list:
  7042. self._unconfirmed_skips.pop(oid, None)
  7043. self.state.skipped_objects = [oid for oid in self.state.skipped_objects if oid not in obj_list]
  7044. def _check_unconfirmed_skips(self) -> None:
  7045. """Log, once, a skip the printer's s_obj list never showed."""
  7046. if not self._unconfirmed_skips:
  7047. return
  7048. if self.state.state not in ("RUNNING", "PAUSE"):
  7049. # The print ended; its skips are moot.
  7050. self._unconfirmed_skips.clear()
  7051. self._skip_commands.clear()
  7052. return
  7053. now = time.monotonic()
  7054. # A copy: skip_objects adds to the dict from the event loop while this
  7055. # runs on the MQTT thread.
  7056. pending = list(self._unconfirmed_skips.items())
  7057. expired = [oid for oid, sent_at in pending if now - sent_at > SKIP_CONFIRM_TIMEOUT_S]
  7058. if not expired:
  7059. return
  7060. logger.error(
  7061. "[%s] Printer did not confirm skipping objects %s within %.0fs; they may still be printed",
  7062. self.serial_number,
  7063. sorted(expired),
  7064. SKIP_CONFIRM_TIMEOUT_S,
  7065. )
  7066. for oid in expired:
  7067. self._unconfirmed_skips.pop(oid, None)
  7068. def skip_objects(self, object_ids: list[int]) -> bool:
  7069. """Skip specific objects during a print.
  7070. This command tells the printer to skip printing the specified objects.
  7071. The object IDs come from the slice_info.config file in the 3MF.
  7072. Args:
  7073. object_ids: List of identify_id values from slice_info.config
  7074. Returns:
  7075. True if command was sent, False otherwise
  7076. """
  7077. if not self._client or not self.state.connected:
  7078. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  7079. return False
  7080. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  7081. logger.warning(
  7082. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  7083. )
  7084. return False
  7085. if not object_ids:
  7086. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  7087. return False
  7088. # Validate all IDs are integers
  7089. try:
  7090. obj_list = [int(oid) for oid in object_ids]
  7091. except (ValueError, TypeError) as e:
  7092. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  7093. return False
  7094. self._sequence_id += 1
  7095. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  7096. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7097. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  7098. sent_at = time.monotonic()
  7099. for oid in obj_list:
  7100. self._unconfirmed_skips.setdefault(oid, sent_at)
  7101. self._skip_commands[str(self._sequence_id)] = obj_list
  7102. # Track skipped objects in state
  7103. for oid in obj_list:
  7104. if oid not in self.state.skipped_objects:
  7105. self.state.skipped_objects.append(oid)
  7106. return True
  7107. def send_gcode(self, gcode: str) -> bool:
  7108. """Send G-code command(s) to the printer.
  7109. Multiple commands can be separated by newlines.
  7110. Args:
  7111. gcode: G-code command(s) to send
  7112. Returns:
  7113. True if command was sent, False otherwise
  7114. """
  7115. if not self._client or not self.state.connected:
  7116. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  7117. return False
  7118. self._sequence_id += 1
  7119. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  7120. # Use QoS 1 for reliable delivery (at least once)
  7121. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7122. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  7123. return True
  7124. def set_bed_temperature(self, target: int) -> bool:
  7125. """Set the bed target temperature.
  7126. Args:
  7127. target: Target temperature in Celsius (0 to turn off)
  7128. Returns:
  7129. True if command was sent, False otherwise
  7130. """
  7131. return self.send_gcode(f"M140 S{target}")
  7132. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  7133. """Set the nozzle target temperature.
  7134. Args:
  7135. target: Target temperature in Celsius (0 to turn off)
  7136. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  7137. Returns:
  7138. True if command was sent, False otherwise
  7139. """
  7140. # Use M104 for non-blocking
  7141. # Always use T parameter for H2D compatibility
  7142. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  7143. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  7144. # Track it locally so we can display it correctly
  7145. if result and nozzle == 1:
  7146. self.state.temperatures["nozzle_target"] = float(target)
  7147. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  7148. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  7149. return result
  7150. def set_chamber_temperature(self, target: int) -> bool:
  7151. """Set the chamber target temperature.
  7152. Args:
  7153. target: Target temperature in Celsius (0 to turn off heating)
  7154. Returns:
  7155. True if command was sent, False otherwise
  7156. """
  7157. # M141 sets chamber temperature
  7158. result = self.send_gcode(f"M141 S{target}")
  7159. # Track chamber target locally (MQTT reports encoded values that need filtering)
  7160. if result:
  7161. self.state.temperatures["chamber_target"] = float(target)
  7162. self.state.temperatures["_chamber_target_set_time"] = time.time()
  7163. # Update heating state immediately based on new target
  7164. current_temp = self.state.temperatures.get("chamber", 0)
  7165. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  7166. logger.info(
  7167. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  7168. )
  7169. return result
  7170. def set_print_speed(self, mode: int) -> bool:
  7171. """Set the print speed mode.
  7172. Args:
  7173. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  7174. Returns:
  7175. True if command was sent, False otherwise
  7176. """
  7177. if not self._client or not self.state.connected:
  7178. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  7179. return False
  7180. if mode not in (1, 2, 3, 4):
  7181. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  7182. return False
  7183. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  7184. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7185. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  7186. return True
  7187. def set_fan_speed(self, fan: int, speed: int) -> bool:
  7188. """Set fan speed.
  7189. Args:
  7190. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=second auxiliary).
  7191. Index 10 is the second auxiliary part cooling fan: left on the P2S
  7192. (an accessory kit), right on the X2D, where 2 is the left (#3373)
  7193. (airduct part id 10); Bambu's official machine profiles drive it with
  7194. "M106 P10" in start/layer-change gcode.
  7195. speed: Speed 0-255 (0=off, 255=full)
  7196. Returns:
  7197. True if command was sent, False otherwise
  7198. """
  7199. if fan not in (1, 2, 3, 10):
  7200. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  7201. return False
  7202. speed = max(0, min(255, speed)) # Clamp to 0-255
  7203. return self.send_gcode(f"M106 P{fan} S{speed}")
  7204. def set_airduct_mode(self, mode: str) -> bool:
  7205. """Set air conditioning mode (cooling or heating).
  7206. Args:
  7207. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  7208. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  7209. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  7210. closes top exhaust flap
  7211. Returns:
  7212. True if command was sent, False otherwise
  7213. """
  7214. if not self._client or not self.state.connected:
  7215. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  7216. return False
  7217. self._sequence_id += 1
  7218. mode_id = 0 if mode == "cooling" else 1
  7219. command = {
  7220. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  7221. }
  7222. # Use QoS 1 for reliable delivery
  7223. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7224. logger.info(
  7225. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  7226. )
  7227. return True
  7228. def set_chamber_light(self, on: bool) -> bool:
  7229. """Turn chamber light on or off.
  7230. Args:
  7231. on: True to turn on, False to turn off
  7232. Returns:
  7233. True if command was sent, False otherwise
  7234. """
  7235. if not self._client or not self.state.connected:
  7236. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  7237. return False
  7238. mode = "on" if on else "off"
  7239. # Control both chamber lights (some printers like H2D have two)
  7240. for led_node in ["chamber_light", "chamber_light2"]:
  7241. self._sequence_id += 1
  7242. command = {
  7243. "system": {
  7244. "command": "ledctrl",
  7245. "led_node": led_node,
  7246. "led_mode": mode,
  7247. "led_on_time": 500,
  7248. "led_off_time": 500,
  7249. "loop_times": 0,
  7250. "interval_time": 0,
  7251. "sequence_id": str(self._sequence_id),
  7252. }
  7253. }
  7254. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7255. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  7256. return True
  7257. def select_extruder(self, extruder: int) -> bool:
  7258. """Select the active extruder for dual-nozzle printers (H2D).
  7259. Args:
  7260. extruder: Extruder index (0=right, 1=left for H2D)
  7261. Returns:
  7262. True if command was sent, False otherwise
  7263. """
  7264. if extruder not in (0, 1):
  7265. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  7266. return False
  7267. if not self._client or not self.state.connected:
  7268. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  7269. return False
  7270. # H2D extruder switching via select_extruder command
  7271. # Command format captured from OrcaSlicer:
  7272. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  7273. # extruder_index: 0 = RIGHT, 1 = LEFT
  7274. self._sequence_id += 1
  7275. command = {
  7276. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  7277. }
  7278. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7279. logger.info(
  7280. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  7281. )
  7282. return True
  7283. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  7284. """Load filament from a specific AMS tray.
  7285. Args:
  7286. tray_id: Global tray ID — 0..15 for AMS slots, 24..27 for the A2L
  7287. AMS-Lite, 128..135 for an AMS-HT (its unit id), 254 for external spool
  7288. (single-external printers and Ext-L on dual-nozzle H2D),
  7289. 255 for Ext-R on dual-nozzle H2D.
  7290. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  7291. Sent only when given, matching BambuStudio: ``extruder_id`` is
  7292. an optional field on ``ams_change_filament``
  7293. (``DeviceManager::command_ams_change_filament``) and Studio
  7294. omits it unless a Filament Track Switch is installed. Without a
  7295. switch the firmware derives the hotend from the AMS's own
  7296. extruder binding and an explicit value is redundant; *with* one
  7297. every AMS reports 0xE and is bound to a switch inlet instead, so
  7298. the firmware has nothing to derive from and the load silently
  7299. does nothing until we name the hotend.
  7300. Returns:
  7301. True if command was sent, False otherwise
  7302. """
  7303. if not self._client or not self.state.connected:
  7304. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  7305. return False
  7306. # Build the ams_change_filament command. Encoding differs by target type:
  7307. # - AMS slots (0..15, A2L 24..27, AMS-HT 128..135): see
  7308. # change_filament_wire_ids; curr/tar_temp = -1.
  7309. # - External spool (tray_id=254): legacy capture from a single-extruder
  7310. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  7311. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  7312. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  7313. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  7314. self._sequence_id += 1
  7315. wire_target = tray_id
  7316. if tray_id == 255:
  7317. ams_id = 255
  7318. slot_id = 0 # extruder index for the right nozzle
  7319. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  7320. if right_temp < 180:
  7321. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  7322. curr_temp = right_temp
  7323. tar_temp = right_temp
  7324. elif tray_id == 254:
  7325. ams_id = 255
  7326. slot_id = 254
  7327. curr_temp = -1
  7328. tar_temp = -1
  7329. else:
  7330. # A regular AMS, the A2L AMS-Lite (physical unit 16) or an AMS-HT
  7331. # (128-135), as BambuStudio addresses each.
  7332. ams_id, slot_id, wire_target = change_filament_wire_ids(tray_id)
  7333. curr_temp = -1
  7334. tar_temp = -1
  7335. command = {
  7336. "print": {
  7337. "command": "ams_change_filament",
  7338. "sequence_id": str(self._sequence_id),
  7339. "ams_id": ams_id,
  7340. "slot_id": slot_id,
  7341. "target": wire_target,
  7342. "curr_temp": curr_temp,
  7343. "tar_temp": tar_temp,
  7344. }
  7345. }
  7346. if extruder_id is not None:
  7347. command["print"]["extruder_id"] = int(extruder_id)
  7348. command_json = json.dumps(command)
  7349. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  7350. self._client.publish(self.topic_publish, command_json, qos=1)
  7351. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  7352. # Track this load request for H2D dual-nozzle disambiguation
  7353. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  7354. self.state.pending_tray_target = tray_id
  7355. self.state.pending_tray_target_at = time.monotonic()
  7356. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  7357. return True
  7358. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  7359. """Unload filament, optionally naming the slot to unload.
  7360. Args:
  7361. tray_id: Global tray ID of the slot being unloaded. When given, the
  7362. command is addressed to that slot's AMS and is only sent if an
  7363. extruder is actually fed from it — BambuStudio does the same
  7364. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  7365. nothing when none matches). When omitted, the pre-existing
  7366. behaviour is kept: unload whatever ``tray_now`` names.
  7367. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  7368. machine with both hotends loaded it names only one of them and an
  7369. unaddressed unload picks that one regardless of which slot the operator
  7370. clicked. Passing the slot is what makes the two hotends distinguishable.
  7371. Returns:
  7372. True if command was sent, False otherwise
  7373. """
  7374. if not self._client or not self.state.connected:
  7375. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  7376. return False
  7377. # Get the currently loaded tray info
  7378. tray_now = self.state.tray_now
  7379. source_tray = tray_now if tray_id is None else tray_id
  7380. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  7381. # Determine source ams_id for the unload command
  7382. if source_tray == 255 or source_tray == 254:
  7383. ams_id = 255 # No filament or external spool
  7384. else:
  7385. # Source AMS: the A2L AMS-Lite as physical 16, an AMS-HT as its unit id.
  7386. ams_id = change_filament_wire_ids(source_tray)[0]
  7387. # Refuse an addressed unload of a slot no hotend is holding — but only on
  7388. # a printer that has more than one hotend, which is the only case the
  7389. # check exists for. With one hotend there is nothing to disambiguate:
  7390. # tray_now already names the loaded slot exactly, and running the check
  7391. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  7392. # very likely does, but single-nozzle machines do report the block —
  7393. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  7394. # an X1C on the maintainer's own network sends `device.extruder` — and
  7395. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  7396. # would 409 every unload on every X1C, P1S and A1.
  7397. #
  7398. # Gated on the runtime flag rather than on len(extruder_slots), which is
  7399. # rebuilt from each payload's array and would flip the check off for any
  7400. # frame that carried a short one; and deliberately not on
  7401. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  7402. # one single-nozzle machine as dual (#1386) — the false positive there is
  7403. # exactly the case this gate exists to keep out.
  7404. #
  7405. # The external spool is excluded for a different reason: 254/255 are not
  7406. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  7407. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  7408. local_slot = change_filament_wire_ids(tray_id)[1]
  7409. holder = next(
  7410. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  7411. None,
  7412. )
  7413. if holder is None:
  7414. logger.info(
  7415. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  7416. self.serial_number,
  7417. ams_id,
  7418. local_slot,
  7419. )
  7420. return False
  7421. logger.info(
  7422. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7423. )
  7424. # Command format from BambuStudio traffic capture:
  7425. # - No extruder_id field
  7426. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7427. # - slot_id=255 and target=255 for unload
  7428. # Get current nozzle temperature for the unload command
  7429. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7430. if nozzle_temp < 180:
  7431. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7432. self._sequence_id += 1
  7433. command = {
  7434. "print": {
  7435. "command": "ams_change_filament",
  7436. "sequence_id": str(self._sequence_id),
  7437. "ams_id": ams_id,
  7438. "slot_id": 255, # 255 = unload marker
  7439. "target": 255, # 255 = unload destination
  7440. "curr_temp": nozzle_temp,
  7441. "tar_temp": nozzle_temp,
  7442. }
  7443. }
  7444. command_json = json.dumps(command)
  7445. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7446. self._client.publish(self.topic_publish, command_json, qos=1)
  7447. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7448. # Clear tracked load request since we're unloading
  7449. self.state.pending_tray_target = None
  7450. self.state.pending_tray_target_at = None
  7451. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7452. return True
  7453. def ams_control(self, action: str) -> bool:
  7454. """Control AMS operations.
  7455. Args:
  7456. action: "resume", "reset", or "pause"
  7457. Returns:
  7458. True if command was sent, False otherwise
  7459. """
  7460. if not self._client or not self.state.connected:
  7461. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7462. return False
  7463. if action not in ("resume", "reset", "pause"):
  7464. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7465. return False
  7466. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7467. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7468. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7469. return True
  7470. async def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7471. """Trigger RFID re-read for a specific AMS tray.
  7472. Sends ``ams_get_rfid`` and waits for the printer's answer. Firmware
  7473. that refuses it (#3206: X1Plus on base 01.08.02.00 answers ``FAIL`` /
  7474. ``ERROR STATE``) gets the legacy ``M620 R<global tray>`` gcode instead,
  7475. which is what Bambu Studio sends to printers without the new protocol.
  7476. The fallback only follows an explicit refusal, so firmware that takes
  7477. ``ams_get_rfid`` never sees it.
  7478. Success means the printer accepted the request, not that the tag was
  7479. read: the slot updating in the next push is the only proof of that.
  7480. Args:
  7481. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7482. tray_id: Tray ID within the AMS (0-3)
  7483. Returns:
  7484. Tuple of (success, message)
  7485. """
  7486. if not self._client or not self.state.connected:
  7487. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7488. return False, "Printer not connected"
  7489. # Check if filament is currently loaded (tray_now != 255)
  7490. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7491. tray_now = self.state.tray_now
  7492. if tray_now != 255:
  7493. # Decode which tray is loaded for the message
  7494. if tray_now == 254:
  7495. loaded_tray = "external spool"
  7496. elif tray_now >= 0 and tray_now < 128:
  7497. loaded_ams = tray_now // 4
  7498. loaded_slot = tray_now % 4
  7499. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7500. else:
  7501. loaded_tray = f"tray {tray_now}"
  7502. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7503. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7504. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7505. wire_ams_id, wire_slot_id = ams_id, tray_id
  7506. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7507. wire_ams_id, wire_slot_id, _ = _a2l
  7508. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7509. refused = await self._send_rfid_command(
  7510. {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id}
  7511. )
  7512. if refused is None:
  7513. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7514. # M620 R only for what Bambu Studio sends it to: a model older than the
  7515. # newer protocol, on one of the four regular AMS units (the only ones
  7516. # with a legacy global tray index). Never during a job either: a
  7517. # gcode_line would be executed inside the running print.
  7518. from backend.app.utils.printer_models import uses_legacy_rfid_refresh
  7519. if (
  7520. not 0 <= wire_ams_id <= 3
  7521. or not uses_legacy_rfid_refresh(self.model)
  7522. or self.state.state in _ACTIVE_PRINT_STATES
  7523. ):
  7524. return False, f"Printer refused the RFID refresh: {refused}"
  7525. logger.info(
  7526. "[%s] ams_get_rfid refused (%s), falling back to M620 R%s",
  7527. self.serial_number,
  7528. refused,
  7529. wire_ams_id * 4 + wire_slot_id,
  7530. )
  7531. legacy_refused = await self._send_rfid_command(
  7532. {"command": "gcode_line", "param": f"M620 R{wire_ams_id * 4 + wire_slot_id}\n"}
  7533. )
  7534. if legacy_refused is None:
  7535. return True, f"Refreshing AMS {ams_id} tray {tray_id} (legacy command)"
  7536. return False, f"Printer refused the RFID refresh: {legacy_refused}"
  7537. # The answer to ams_get_rfid was measured at 11ms in #3206's capture.
  7538. _rfid_ack_timeout: float = 3.0
  7539. async def _send_rfid_command(self, print_command: dict) -> str | None:
  7540. """Publish one RFID refresh command and wait for the printer's answer.
  7541. Returns the printer's reason when it answered ``FAIL``, else None.
  7542. No answer within ``_rfid_ack_timeout`` counts as accepted, because
  7543. silence is not evidence of refusal and older firmware may not answer
  7544. at all.
  7545. """
  7546. timeout = self._rfid_ack_timeout
  7547. self._sequence_id += 1
  7548. seq_id = str(self._sequence_id)
  7549. command = {"print": {**print_command, "sequence_id": seq_id}}
  7550. self._pending_rfid_acks[seq_id] = None
  7551. try:
  7552. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7553. deadline = time.monotonic() + timeout
  7554. while time.monotonic() < deadline:
  7555. ack = self._pending_rfid_acks.get(seq_id)
  7556. if ack is not None:
  7557. if str(ack.get("result", "")).lower() == "fail":
  7558. return str(ack.get("reason", "") or "") or "printer reported failure"
  7559. return None
  7560. await asyncio.sleep(0.05)
  7561. finally:
  7562. self._pending_rfid_acks.pop(seq_id, None)
  7563. logger.info(
  7564. "[%s] No answer to %s seq=%s within %.1fs", self.serial_number, print_command["command"], seq_id, timeout
  7565. )
  7566. return None
  7567. def ams_set_filament_setting(
  7568. self,
  7569. ams_id: int,
  7570. tray_id: int,
  7571. tray_info_idx: str,
  7572. tray_type: str,
  7573. tray_sub_brands: str,
  7574. tray_color: str,
  7575. nozzle_temp_min: int,
  7576. nozzle_temp_max: int,
  7577. setting_id: str = "",
  7578. ) -> bool:
  7579. """Set AMS tray filament settings (type, color, temperature).
  7580. Note: K value is set separately via extrusion_cali_sel command.
  7581. Args:
  7582. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7583. tray_id: Tray ID within the AMS (0-3)
  7584. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7585. tray_type: Filament type (e.g., "PLA", "PETG")
  7586. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  7587. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  7588. nozzle_temp_min: Minimum nozzle temperature
  7589. nozzle_temp_max: Maximum nozzle temperature
  7590. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  7591. Returns:
  7592. True if command was sent, False otherwise
  7593. """
  7594. if not self._client or not self.state.connected:
  7595. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  7596. return False
  7597. # Calculate mqtt IDs based on AMS type.
  7598. # External-spool convention verified against a BambuStudio→X1C packet capture
  7599. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  7600. # *global* tray index in `tray_id`, not a local position within the virtual
  7601. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  7602. # is what the original code was matching — but the request and response
  7603. # use different semantics for that field. Sending `tray_id: 0` is what
  7604. # the P1S in #1279 rejected with `result: "fail"`.
  7605. if ams_id == 255:
  7606. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7607. if len(vt_tray) > 1:
  7608. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7609. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7610. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7611. # captured Studio→H2D exchange confirms the correct value.
  7612. mqtt_ams_id = 254 + tray_id
  7613. mqtt_tray_id = 0
  7614. else:
  7615. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7616. mqtt_ams_id = 255
  7617. mqtt_tray_id = 254
  7618. slot_id = 0
  7619. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7620. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7621. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7622. mqtt_ams_id, slot_id, _ = _a2l
  7623. mqtt_tray_id = slot_id
  7624. elif ams_id <= 3:
  7625. mqtt_ams_id = ams_id
  7626. mqtt_tray_id = tray_id
  7627. slot_id = tray_id
  7628. else:
  7629. # AMS-HT: single tray per unit
  7630. mqtt_ams_id = ams_id
  7631. mqtt_tray_id = tray_id
  7632. slot_id = 0
  7633. command = {
  7634. "print": {
  7635. "command": "ams_filament_setting",
  7636. "ams_id": mqtt_ams_id,
  7637. "tray_id": mqtt_tray_id,
  7638. "slot_id": slot_id,
  7639. "tray_info_idx": tray_info_idx,
  7640. "tray_type": tray_type,
  7641. "tray_sub_brands": tray_sub_brands,
  7642. # UPPERCASE, always: lowercase hex is silently read as zeros by
  7643. # P1S firmware and acknowledged as a success (#2987).
  7644. "tray_color": wire_tray_color(tray_color),
  7645. "nozzle_temp_min": nozzle_temp_min,
  7646. "nozzle_temp_max": nozzle_temp_max,
  7647. "sequence_id": "0",
  7648. }
  7649. }
  7650. # Include setting_id if provided (helps slicer show correct profile)
  7651. if setting_id:
  7652. command["print"]["setting_id"] = setting_id
  7653. command_json = json.dumps(command)
  7654. logger.info(
  7655. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  7656. )
  7657. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  7658. self._client.publish(self.topic_publish, command_json, qos=1)
  7659. self._last_ams_cmd_time = time.monotonic()
  7660. return True
  7661. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  7662. """Reset an AMS slot to empty/unconfigured state.
  7663. Args:
  7664. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7665. tray_id: Tray ID within the AMS (0-3)
  7666. Returns:
  7667. True if command was sent, False otherwise
  7668. """
  7669. if not self._client or not self.state.connected:
  7670. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  7671. return False
  7672. # Calculate mqtt IDs based on AMS type — same convention as
  7673. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  7674. if ams_id == 255:
  7675. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7676. if len(vt_tray) > 1:
  7677. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7678. mqtt_ams_id = 254 + tray_id
  7679. mqtt_tray_id = 0
  7680. else:
  7681. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7682. mqtt_ams_id = 255
  7683. mqtt_tray_id = 254
  7684. slot_id = 0
  7685. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7686. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  7687. mqtt_ams_id, slot_id, _ = _a2l
  7688. mqtt_tray_id = slot_id
  7689. elif ams_id <= 3:
  7690. mqtt_ams_id = ams_id
  7691. mqtt_tray_id = tray_id
  7692. slot_id = tray_id
  7693. else:
  7694. # AMS-HT: single tray per unit
  7695. mqtt_ams_id = ams_id
  7696. mqtt_tray_id = tray_id
  7697. slot_id = 0
  7698. command = {
  7699. "print": {
  7700. "command": "ams_filament_setting",
  7701. "ams_id": mqtt_ams_id,
  7702. "tray_id": mqtt_tray_id,
  7703. "slot_id": slot_id,
  7704. "tray_info_idx": "",
  7705. "tray_type": "",
  7706. "tray_sub_brands": "",
  7707. "tray_color": "00000000",
  7708. "nozzle_temp_min": 0,
  7709. "nozzle_temp_max": 0,
  7710. "sequence_id": "0",
  7711. }
  7712. }
  7713. command_json = json.dumps(command)
  7714. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  7715. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  7716. self._client.publish(self.topic_publish, command_json, qos=1)
  7717. self._last_ams_cmd_time = time.monotonic()
  7718. return True
  7719. def extrusion_cali_sel(
  7720. self,
  7721. ams_id: int,
  7722. tray_id: int,
  7723. cali_idx: int,
  7724. filament_id: str,
  7725. nozzle_diameter: str = "0.4",
  7726. ) -> bool:
  7727. """Set calibration profile (K value) for an AMS slot.
  7728. This command selects a K profile from the printer's calibration list.
  7729. Use cali_idx=-1 to use the default K value (0.020).
  7730. Note: Do NOT send setting_id in this command — BambuStudio never includes
  7731. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  7732. Args:
  7733. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7734. tray_id: Tray ID within the AMS (0-3)
  7735. cali_idx: Calibration profile index (-1 for default)
  7736. filament_id: Filament preset ID (same as tray_info_idx)
  7737. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7738. Returns:
  7739. True if command was sent, False otherwise
  7740. """
  7741. if not self._client or not self.state.connected:
  7742. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  7743. return False
  7744. # Calculate mqtt IDs based on AMS type.
  7745. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  7746. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  7747. if ams_id == 255:
  7748. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  7749. # ams_filament_setting which uses LOCAL tray_id=0).
  7750. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7751. if len(vt_tray) > 1:
  7752. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7753. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  7754. mqtt_ams_id = 254 + tray_id
  7755. mqtt_tray_id = 254 + tray_id
  7756. else:
  7757. # Single external slot (X1C, P1S, A1): global tray_id=254
  7758. mqtt_ams_id = 254
  7759. mqtt_tray_id = 254
  7760. slot_id = 0
  7761. elif ams_id <= 3:
  7762. mqtt_ams_id = ams_id
  7763. mqtt_tray_id = ams_id * 4 + tray_id
  7764. slot_id = tray_id
  7765. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7766. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  7767. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  7768. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  7769. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  7770. elif ams_id >= 128 and ams_id <= 135:
  7771. mqtt_ams_id = ams_id
  7772. mqtt_tray_id = tray_id
  7773. slot_id = 0
  7774. else:
  7775. mqtt_ams_id = ams_id
  7776. mqtt_tray_id = tray_id
  7777. slot_id = 0
  7778. command = {
  7779. "print": {
  7780. "command": "extrusion_cali_sel",
  7781. "cali_idx": cali_idx,
  7782. "filament_id": filament_id,
  7783. "nozzle_diameter": nozzle_diameter,
  7784. "ams_id": mqtt_ams_id,
  7785. "tray_id": mqtt_tray_id,
  7786. "slot_id": slot_id,
  7787. "sequence_id": "0",
  7788. }
  7789. }
  7790. command_json = json.dumps(command)
  7791. logger.info(
  7792. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  7793. )
  7794. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  7795. self._client.publish(self.topic_publish, command_json, qos=1)
  7796. return True
  7797. def extrusion_cali_set(
  7798. self,
  7799. tray_id: int,
  7800. k_value: float,
  7801. nozzle_diameter: str = "0.4",
  7802. nozzle_temp: int = 220,
  7803. filament_id: str = "",
  7804. setting_id: str = "",
  7805. name: str = "",
  7806. cali_idx: int = -1,
  7807. ) -> bool:
  7808. """Directly set K value (pressure advance) for a tray.
  7809. Uses the filaments array format required by current firmware.
  7810. Args:
  7811. tray_id: Global tray ID (ams_id * 4 + slot)
  7812. k_value: Pressure advance K value (e.g., 0.020)
  7813. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  7814. nozzle_temp: Nozzle temperature for calibration reference
  7815. filament_id: Filament preset ID (e.g., "GFA02")
  7816. setting_id: Setting ID (e.g., "GFSA02_07")
  7817. name: Profile display name
  7818. cali_idx: Calibration index (-1 for new)
  7819. Returns:
  7820. True if command was sent, False otherwise
  7821. """
  7822. if not self._client or not self.state.connected:
  7823. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  7824. return False
  7825. # Was reusing the previous command's id — harmless while nothing
  7826. # correlated on it, but the printer echoes sequence_id back and the
  7827. # K-profile write path now matches acks by it (#2718).
  7828. self._sequence_id += 1
  7829. nozzle_id = f"HS00-{nozzle_diameter}"
  7830. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  7831. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  7832. # stays 0 (hardcoded, as for every other unit here).
  7833. wire_tray_id = tray_id
  7834. if 0 <= tray_id <= 253 and (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  7835. wire_tray_id = _a2l[2]
  7836. filament_entry = {
  7837. "ams_id": 0,
  7838. "cali_idx": cali_idx,
  7839. "extruder_id": 0,
  7840. "filament_id": filament_id,
  7841. "k_value": f"{k_value:.6f}",
  7842. "n_coef": "1.400000",
  7843. "name": name,
  7844. "nozzle_diameter": nozzle_diameter,
  7845. "nozzle_id": nozzle_id,
  7846. "setting_id": setting_id,
  7847. "tray_id": wire_tray_id,
  7848. }
  7849. command = {
  7850. "print": {
  7851. "command": "extrusion_cali_set",
  7852. "filaments": [filament_entry],
  7853. "nozzle_diameter": nozzle_diameter,
  7854. "sequence_id": str(self._sequence_id),
  7855. }
  7856. }
  7857. command_json = json.dumps(command)
  7858. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  7859. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  7860. self._client.publish(self.topic_publish, command_json, qos=1)
  7861. return True
  7862. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  7863. """Dispatch the user's choice from the HMS-error modal as a printer command.
  7864. Args:
  7865. print_error: Canonical hex identifier for the fault — 8 chars for the
  7866. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  7867. (HMSError.full_code). Carried through unchanged from the route.
  7868. Converted to its DECIMAL string form for the `ignore` /
  7869. `idle_ignore` commands' `err` field, which is what the firmware
  7870. actually compares against the active fault. The pre-#1869
  7871. hex-string `err` was silently rejected because the firmware was
  7872. being asked to match `"05008051"` against int 0x05008051
  7873. (= 83918929 decimal) — see BambuStudio's
  7874. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  7875. `std::to_string(int m_error_code)`.
  7876. action: One of HMSAction's string values.
  7877. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  7878. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  7879. shapes; empty string is the no-job-id sentinel.
  7880. Returns False when the MQTT client is offline or when `action` is unknown
  7881. so the route surfaces it as a 4xx rather than a silent no-op.
  7882. """
  7883. if not self._client or not self.state.connected:
  7884. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  7885. return False
  7886. # Always re-push the full state after a command so the modal's underlying
  7887. # status query reflects the new error list (or absence) on the next tick.
  7888. def publish(payload: dict):
  7889. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  7890. self._client.publish(
  7891. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  7892. )
  7893. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  7894. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  7895. # every command_hms_* call). Our route hands us the hex string —
  7896. # convert. Falls back to the raw input if it's not parseable so the
  7897. # firmware can reject it and the route can surface 502 instead of us
  7898. # raising ValueError mid-dispatch.
  7899. try:
  7900. err_decimal = str(int(print_error, 16))
  7901. except ValueError:
  7902. err_decimal = print_error
  7903. def hms_resume():
  7904. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  7905. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  7906. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  7907. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  7908. # shape historically because it works, and changing it without a
  7909. # field test risks regressing a path that the user has confirmed.
  7910. publish(
  7911. {
  7912. "print": {
  7913. "command": "resume",
  7914. "param": "",
  7915. "sequence_id": "0",
  7916. }
  7917. }
  7918. )
  7919. def hms_stop():
  7920. # Same as hms_resume — plain shape, confirmed working by the user
  7921. # for "Stop Printing".
  7922. publish(
  7923. {
  7924. "print": {
  7925. "command": "stop",
  7926. "param": "",
  7927. "sequence_id": "0",
  7928. }
  7929. }
  7930. )
  7931. def hms_ignore_command():
  7932. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  7933. # what the "Ignore this and Resume" button actually publishes.
  7934. # Distinct from `idle_ignore`: this command has the firmware
  7935. # suppress the next re-check of the named fault AND resume the
  7936. # paused print in a single operation. The previous Bambuddy code
  7937. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  7938. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  7939. # the problem, re-check normally" so the firmware re-detected the
  7940. # wrong plate and re-paused with the same code (#1869).
  7941. #
  7942. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  7943. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  7944. # variant of "don't remind next time" lives on `idle_ignore`'s
  7945. # type=1, not as a separate ignore shape.
  7946. publish(
  7947. {
  7948. "print": {
  7949. "command": "ignore",
  7950. "err": err_decimal,
  7951. "param": "reserve",
  7952. "job_id": job_id or "",
  7953. "sequence_id": "0",
  7954. }
  7955. }
  7956. )
  7957. def hms_idle_ignore(persistent: bool = False):
  7958. # `idle_ignore` is BambuStudio's "dismiss this warning without
  7959. # resuming" command for non-pause warnings — what
  7960. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  7961. # type=0 dismisses once, type=1 suppresses the same warning
  7962. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  7963. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  7964. # NOT via the resume-bearing `ignore` command.
  7965. publish(
  7966. {
  7967. "print": {
  7968. "command": "idle_ignore",
  7969. "err": err_decimal,
  7970. "type": 1 if persistent else 0,
  7971. "sequence_id": "0",
  7972. }
  7973. }
  7974. )
  7975. def ams_control(param: str):
  7976. publish(
  7977. {
  7978. "print": {
  7979. "command": "ams_control",
  7980. "param": param,
  7981. "sequence_id": "0",
  7982. }
  7983. }
  7984. )
  7985. def clean_print_error():
  7986. # Matches the existing `clear_hms_errors` shape — Bambu does not
  7987. # expect `print_error` in the body; the command clears whatever
  7988. # error dialog is currently active on the printer.
  7989. publish(
  7990. {
  7991. "print": {
  7992. "command": "clean_print_error",
  7993. "sequence_id": "0",
  7994. }
  7995. }
  7996. )
  7997. def uiop_close():
  7998. # `err` is the 8-char hex short code (already a string from the
  7999. # frontend), uppercased for consistency with how BambuStudio sends it.
  8000. publish(
  8001. {
  8002. "system": {
  8003. "command": "uiop",
  8004. "name": "print_error",
  8005. "action": "close",
  8006. "source": 1,
  8007. "type": "dialog",
  8008. "err": print_error.upper(),
  8009. "sequence_id": "0",
  8010. }
  8011. }
  8012. )
  8013. match action:
  8014. case (
  8015. HMSAction.RESUME_PRINTING
  8016. | HMSAction.RESUME_PRINTING_DEFECTS
  8017. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  8018. | HMSAction.PROBLEM_SOLVED_RESUME
  8019. | HMSAction.FILAMENT_LOAD_RESUME
  8020. | HMSAction.PROCEED
  8021. ):
  8022. hms_resume()
  8023. case HMSAction.STOP_PRINTING:
  8024. hms_stop()
  8025. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  8026. # All three buttons map to BambuStudio's `command_hms_ignore`
  8027. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  8028. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  8029. # responsibility — the wire shape is identical.
  8030. hms_ignore_command()
  8031. case HMSAction.NO_REMINDER_NEXT_TIME:
  8032. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  8033. # `command_hms_idle_ignore` with type=0
  8034. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  8035. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  8036. # dismisses the dialog.
  8037. hms_idle_ignore(persistent=False)
  8038. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  8039. ams_control("done")
  8040. case (
  8041. HMSAction.RETRY_FILAMENT_EXTRUDED
  8042. | HMSAction.CONTINUE
  8043. | HMSAction.RETRY_PROBLEM_SOLVED
  8044. | HMSAction.DBL_CHECK_RETRY
  8045. ):
  8046. ams_control("resume")
  8047. case HMSAction.ABORT:
  8048. ams_control("abort")
  8049. case HMSAction.OK_BUTTON:
  8050. clean_print_error()
  8051. case HMSAction.DBL_CHECK_OK:
  8052. clean_print_error()
  8053. uiop_close()
  8054. case HMSAction.DBL_CHECK_RESUME:
  8055. # Plain resume — not HMS-aware, no err/job_id.
  8056. publish(
  8057. {
  8058. "print": {
  8059. "command": "resume",
  8060. "param": "",
  8061. "sequence_id": "0",
  8062. }
  8063. }
  8064. )
  8065. case HMSAction.REFRESH_NOZZLE:
  8066. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  8067. case HMSAction.TURN_OFF_FIRE_ALARM:
  8068. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  8069. case HMSAction.STOP_DRYING:
  8070. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  8071. case HMSAction.DISABLE_PURIFICATION:
  8072. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  8073. case (
  8074. HMSAction.CHECK_ASSISTANT
  8075. | HMSAction.JUMP_TO_LIVEVIEW
  8076. | HMSAction.OK_JUMP_RACK
  8077. | HMSAction.REMOVE_CLOSE_BTN
  8078. | HMSAction.LOAD_VIRTUAL_TRAY
  8079. | HMSAction.CANCLE
  8080. | HMSAction.DBL_CHECK_CANCEL
  8081. ):
  8082. # UI-only actions — the printer's own screen handles these; the
  8083. # modal still surfaces them so the user has parity with Studio.
  8084. pass
  8085. case _:
  8086. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  8087. return False
  8088. return True