bambu_mqtt.py 431 KB

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