bambu_mqtt.py 466 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220
  1. """Bambu Lab MQTT communication service.
  2. IMPORTANT: Always use qos=1 for all MQTT publish calls!
  3. The printer ignores qos=0 messages when busy broadcasting status updates.
  4. Using qos=1 ensures the printer acknowledges and processes our commands immediately.
  5. This was discovered when K-profile requests with qos=0 took 20-30 seconds,
  6. but with qos=1 they respond instantly.
  7. """
  8. import asyncio
  9. import json
  10. import logging
  11. import os
  12. import ssl
  13. import threading
  14. import time
  15. from collections import deque
  16. from collections.abc import Callable
  17. from dataclasses import dataclass, field
  18. from datetime import datetime, timezone
  19. import paho.mqtt.client as mqtt
  20. from backend.app.services.hms_actions import HMSAction, get_actions_for_error_code
  21. from backend.app.services.hms_errors import alert_level_from_print_error, describe_fault
  22. from backend.app.utils.ams_drying import ACTIVE_DRY_STATUSES, DRY_COUNTDOWN_STALL_SECONDS
  23. from backend.app.utils.ams_humidity import ams_humidity_percent
  24. from backend.app.utils.paho_teardown import discard_queued_publishes, retire_paho_client
  25. from backend.app.utils.tray_ids import (
  26. AMS3H_UNIT_ID,
  27. RACK_SLOT_COUNT,
  28. AmsType,
  29. TrayLayout,
  30. ams_type_from_info,
  31. decode_wire_slot,
  32. external_tray_id,
  33. global_tray_id,
  34. is_ams_ht_id,
  35. is_external_tray,
  36. is_rack_ams,
  37. legacy_tray_index,
  38. mapped_trays_with_slot,
  39. tray_flag_bit,
  40. unit_ams_type,
  41. unit_label,
  42. )
  43. logger = logging.getLogger(__name__)
  44. # How long a manual load's tray target stays a hint for an H2D's tray_now: long
  45. # enough for a real load to report, short enough that a refused one cannot
  46. # relabel a later print's load of the same slot number (FW-C7).
  47. PENDING_TRAY_TARGET_TTL = 120.0
  48. # AMS module name prefixes used in get_version responses.
  49. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  50. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  51. # "ams_f1/<id>" – AMS Lite (A1, A1 Mini; the A2L reports id 16, stored as 6)
  52. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  53. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  54. # "n10a" – AMS 3H (H3C), no suffix: read as "n10a/<its unit id>"
  55. _AMS_MODULE_PREFIXES = ("ams/", "ams_f1/", "n3f/", "n3s/", "n10a/")
  56. # gcode_state values that mean the printer is not idle and must not be handed a
  57. # new start-print (#2598). The firmware rejects a project_file while busy with
  58. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  59. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  60. # are valid start targets and are deliberately excluded. Mirrors
  61. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  62. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  63. # A drying cycle that runs to term ends with its countdown all but exhausted, so
  64. # the last dry_time we saw before the drop to 0 tells us whether the firmware
  65. # ended the cycle on schedule or aborted it. More than this many minutes still on
  66. # the clock means it was cut short, and the firmware's own reason codes are worth
  67. # capturing at INFO — #2770 aborted a 12-hour cycle 20 minutes in (700 minutes
  68. # left), and the log said only "drying complete", so the report carried no
  69. # evidence of why. The margin absorbs a stale last observation between AMS
  70. # pushes; it is not a judgement about how short "short" is.
  71. _EARLY_DRY_END_MINUTES = 5
  72. # CONNACK reason codes that mean the printer actively refused our credentials,
  73. # as opposed to being unreachable or busy. Bambu speaks MQTT 3.1.1, whose
  74. # single-byte CONNACK return codes paho maps onto the v5 reason-code space:
  75. # return code 4 ("bad user name or password") -> 134, and 5 ("not authorized")
  76. # -> 135. Both mean the same thing in practice for a Bambu printer: the access
  77. # code (or, on some firmware, the serial used as the username) is wrong.
  78. _CONNACK_AUTH_REJECTED = frozenset({134, 135})
  79. # Short, stable slugs recorded on the client and surfaced to the connection
  80. # diagnostic as a `params.reason` variant. Deliberately not free text — the
  81. # frontend picks a localized message key off these.
  82. CONNECT_ERROR_AUTH_REJECTED = "auth_rejected"
  83. CONNECT_ERROR_REFUSED = "refused"
  84. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  85. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  86. OrcaSlicer reads bit 18 of the hex string via
  87. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  88. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  89. that doesn't yield a clean integer so downstream consumers preserve today's
  90. behaviour rather than treating "absent" as "OFF".
  91. """
  92. if not isinstance(cfg_raw, str) or not cfg_raw:
  93. return None
  94. try:
  95. return bool((int(cfg_raw, 16) >> 18) & 1)
  96. except ValueError:
  97. return None
  98. def parse_ams_filament_backup_from_home_flag(home_flag: object) -> bool | None:
  99. """Extract AMS Filament Backup state from a push_status ``print.home_flag`` value.
  100. Bambu Studio reads bit 10 for every family (DeviceManager.cpp
  101. ``parse_home_flag``: ``SetAutoRefillEnabled((flag >> 10) & 0x1)``). It's
  102. the only source on the P1S, P1P, A1 and A1 Mini, which never send ``cfg``
  103. (#3259). On every printer that sends both, the two bits agree in all
  104. captured snapshots, ON and OFF alike. Returns ``None`` for anything that
  105. isn't an integer.
  106. """
  107. if isinstance(home_flag, bool) or not isinstance(home_flag, int):
  108. return None
  109. # Negative values are the 32-bit flag read as signed; bit 10 is the same.
  110. return bool((home_flag >> 10) & 1)
  111. def is_printer_status_frame(print_data: dict) -> bool:
  112. """True when a ``print`` payload is the printer reporting its own state.
  113. Bambu firmware echoes a command's fields back in its acknowledgement, so a
  114. `project_file` ack carries whatever Bambuddy put on the wire — including
  115. the `cfg` bitmask and the per-job `timelapse` flag. Ingesting those as
  116. telemetry means reading our own request back as the printer's state
  117. (#3040). Only `push_status` (and the odd firmware that omits `command`
  118. entirely on a status frame) describes the printer.
  119. """
  120. command = print_data.get("command")
  121. return command is None or command == "push_status"
  122. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  123. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  124. # firmware is internally inconsistent about it:
  125. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  126. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  127. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  128. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  129. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  130. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  131. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  132. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  133. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  134. A2L_LITE_PHYSICAL_AMS_ID = 16
  135. A2L_LITE_NORMALIZED_AMS_ID = 6
  136. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  137. def _ams_unit_order(unit: dict) -> tuple[int, str]:
  138. """Sort key for AMS units by id (#3499).
  139. Firmware sends unit ids as strings ("0"), while the A2L AMS Lite's id is
  140. normalised to the int 6, so an A2L with an AMS 2 Pro and an AMS Lite held
  141. both: comparing them raised, and the AMS card stayed empty. Numeric order,
  142. with anything unreadable last.
  143. """
  144. raw = unit.get("id", 0)
  145. try:
  146. return (int(raw), "")
  147. except (TypeError, ValueError):
  148. return (1 << 30, str(raw))
  149. def normalize_am_unit_id(ams_id: int) -> int:
  150. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  151. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  152. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  153. through untouched.
  154. """
  155. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  156. def wire_tray_color(tray_color: str | None) -> str:
  157. """Normalise a colour to the form AMS firmware actually parses: UPPERCASE hex.
  158. P1S firmware 01.10.00.00 parses every lowercase hex letter in ``tray_color``
  159. as a zero, and does it silently: the command response echoes the value you
  160. sent and reports ``result: "success"``, so only the next AMS push shows what
  161. was really stored. Measured on the reporter's machine (#2987), where the
  162. spool's own ``rgba`` is stored lowercase and went out verbatim:
  163. sent 09ff00ff -> AMS reports 09000000
  164. sent ff5100ff -> AMS reports 00510000
  165. sent 090000FF -> AMS reports 090000FF
  166. A mangled colour is not merely cosmetic. The auto-unlink sweep compares the
  167. tray against the spool it is assigned to, so the tray Bambuddy just wrote no
  168. longer matches the spool that asked for it and the assignment is deleted
  169. seconds after being made -- and re-assigning through the slot modal writes
  170. the mangled colour back, because the modal seeds itself from the tray.
  171. Applied here, at the one place the command is built, rather than in each of
  172. the four callers: a caller that forgets is exactly how this arrived.
  173. A leading ``#`` is stripped -- the wire format carries bare hex -- and a
  174. blank stays blank, which is how a slot is cleared.
  175. """
  176. return (tray_color or "").strip().lstrip("#").upper()
  177. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  178. """Translate a normalised A2L slot back to the physical wire form.
  179. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  180. (normalised id 6), else ``None`` for every other unit.
  181. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  182. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  183. confirmed by capture: the physical **global** tray value the extrusion_cali
  184. commands put in `tray_id` — we extrapolate it as 16*4+slot = 64-67 to stay
  185. consistent with the physical unit id. BambuStudio's source sends 24+slot
  186. there instead (``GetTrayIndexMap``); a BambuStudio->A2L capture of a cali
  187. command would settle it, and it lives only here. Load's `target` is not this
  188. value: see ``change_filament_wire_ids``.
  189. """
  190. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  191. return None
  192. local_slot = tray_id % 4
  193. return (
  194. A2L_LITE_PHYSICAL_AMS_ID,
  195. local_slot,
  196. legacy_tray_index(A2L_LITE_PHYSICAL_AMS_ID, local_slot),
  197. )
  198. def change_filament_wire_ids(tray_id: int, layout: TrayLayout | None = None) -> tuple[int, int, int]:
  199. """``(ams_id, slot_id, target)`` of ``ams_change_filament`` for an AMS tray.
  200. As BambuStudio's ``command_ams_change_filament`` builds them: a regular AMS
  201. is addressed by unit and local slot with the global tray as target; a unit
  202. id of 16 or more (the A2L AMS-Lite's physical 16, an AMS-HT's 128-135) has
  203. the unit id itself as target. An AMS-HT holds one tray, so its global tray
  204. id is its unit id and its slot is 0.
  205. """
  206. if is_ams_ht_id(tray_id):
  207. return tray_id, 0, tray_id
  208. ams_id, slot_id = (layout or TrayLayout()).slot_key(tray_id)
  209. if (a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  210. return a2l[0], a2l[1], a2l[0]
  211. return ams_id, slot_id, tray_id
  212. # The H3C's AMS 3H is one unit (32, AMS type 6) with nine slots, numbered 28 + k
  213. # (utils.tray_ids). Its tray_now / tray_tar / tray_pre are the raw slot 0-8;
  214. # print.mapping and the snow fields encode a slot as (32 << 8) | k. Commands
  215. # address it as {ams_id: 32, slot_id: k}.
  216. AMS3H_MODULE_NAME = "n10a" # its get_version module (no "/<unit>" suffix)
  217. def _mqtt_int(value: object) -> int | None:
  218. """An MQTT id / number field as an int (they arrive as int or numeric str), else None."""
  219. if isinstance(value, bool) or not isinstance(value, (int, str)):
  220. return None
  221. try:
  222. return int(value)
  223. except ValueError:
  224. return None
  225. # AMS 3H drying (Bambu Studio 02.09, AMSDryControl.cpp): the unit reports
  226. # `zone_info[]` and only a zone with exactly two slots can dry; the others are
  227. # ambient readings. A drying start carries the filament's softening temperature
  228. # as `cooling_temp` (the preset's filament_dev_drying_softening_temperature).
  229. AMS3H_DRY_COOLING_TEMP = {"PLA": 65, "PETG": 75, "ABS": 95, "ASA": 95, "TPU": 70, "PA": 150, "PC": 120}
  230. AMS3H_DRY_COOLING_TEMP_DEFAULT = 50
  231. def ams3h_drying_zone(zone_info: object) -> dict | None:
  232. """The zone of an AMS 3H's `zone_info` that can dry: the first holding exactly two slots."""
  233. if not isinstance(zone_info, list):
  234. return None
  235. for zone in zone_info:
  236. if isinstance(zone, dict) and isinstance(zone.get("zone_slots"), list) and len(zone["zone_slots"]) == 2:
  237. return zone
  238. return None
  239. def ams3h_drying_cooling_temp(filament: str) -> int:
  240. """`cooling_temp` for an AMS 3H drying start: the filament's softening temperature."""
  241. base = (filament or "").upper().split("-")[0].split(" ")[0]
  242. return AMS3H_DRY_COOLING_TEMP.get(base, AMS3H_DRY_COOLING_TEMP_DEFAULT)
  243. def _ams3h_unit_drying_fields(unit: dict) -> dict:
  244. """An AMS 3H's drying state, which lives on its drying zone, lifted onto the unit."""
  245. zone = ams3h_drying_zone(unit.get("zone_info"))
  246. if zone is None:
  247. return {}
  248. fields: dict = {"dry_zone_id": zone.get("zone_id", 0), "dry_zone_slots": list(zone.get("zone_slots") or [])}
  249. for key in ("dry_time", "dry_setting", "dry_sf_reason"):
  250. if key in zone:
  251. fields[key] = zone[key]
  252. if "info" not in unit and "info" in zone:
  253. fields["info"] = zone["info"]
  254. if "humidity_raw" in zone:
  255. fields["dry_zone_humidity_raw"] = zone["humidity_raw"]
  256. if "temp" in zone:
  257. fields["dry_zone_temp"] = zone["temp"]
  258. return fields
  259. def _ams3h_unit_env_fields(unit: dict) -> dict:
  260. """An AMS 3H's humidity and temperature (the unit has none) from its first non-drying zone, as Studio shows it."""
  261. zones = unit.get("zone_info")
  262. if not isinstance(zones, list):
  263. return {}
  264. dry_zone = ams3h_drying_zone(zones)
  265. ambient = next((z for z in zones if isinstance(z, dict) and z is not dry_zone), None)
  266. if ambient is None:
  267. return {}
  268. return {key: ambient[key] for key in ("humidity_raw", "temp") if key in ambient and key not in unit}
  269. def apply_rack_ams_zone_fields(ams_list: object, known_types: dict[int, AmsType] | None = None) -> None:
  270. """Lift a rack AMS's per-zone readings and drying state onto the unit, in place (type from `info`, else ``known_types``)."""
  271. if not isinstance(ams_list, list):
  272. return
  273. for unit in ams_list:
  274. if not isinstance(unit, dict) or not isinstance(unit.get("zone_info"), list):
  275. continue
  276. uid = _mqtt_int(unit.get("id"))
  277. if uid is None:
  278. continue
  279. kind = ams_type_from_info(unit.get("info"))
  280. if kind is None:
  281. kind = (known_types or {}).get(uid, unit_ams_type(uid))
  282. if not is_rack_ams(kind):
  283. continue
  284. unit.update({**_ams3h_unit_env_fields(unit), **_ams3h_unit_drying_fields(unit)})
  285. def resolve_external_spools_in_mapping(
  286. ams_mapping: object, ams_mapping2: object, is_dual_nozzle: bool, layout: TrayLayout | None = None
  287. ) -> object:
  288. """Put the external spool back into a captured flat ``ams_mapping`` (#3166).
  289. The firmware rejects 254/255 in the flat list, so BambuStudio and our own
  290. dispatch both write an external spool there as -1 -- the same value as a
  291. slot that isn't fed at all -- and carry the real target only in
  292. ``ams_mapping2`` as ``{ams_id: 254|255, slot_id: 0}``. Capturing the flat
  293. list alone turns "printed from the external spool" into "unmapped", and
  294. usage then lands on whatever tray the fallback guesses.
  295. Each -1 whose ``ams_mapping2`` entry names an external spool becomes the
  296. global tray the rest of Bambuddy uses: the ams_id itself on dual-nozzle
  297. printers (254 = left/deputy, 255 = right/main), 254 on single-nozzle
  298. printers, which have one external spool that the wire always calls 255.
  299. ``{255, 255}`` is the unmapped marker and stays -1.
  300. An A2L AMS-Lite tray is the local slot 0-3 in the flat list and
  301. ``{ams_id: 16, slot_id: n}`` in ``ams_mapping2``; it becomes its normalised
  302. global tray 24+n. Kept local, it read as a regular AMS tray, so usage was
  303. charged to the wrong spool. A rack AMS slot (``{ams_id: 32, slot_id: k}``)
  304. becomes its global tray 28+k, and on a rack printer each external input
  305. 247-255 keeps its own id. Every other entry is left exactly as captured.
  306. Without a usable ``ams_mapping2`` the input is returned unchanged.
  307. """
  308. if not isinstance(ams_mapping, list) or not isinstance(ams_mapping2, list):
  309. return ams_mapping
  310. if len(ams_mapping2) != len(ams_mapping):
  311. return ams_mapping
  312. resolved = list(ams_mapping)
  313. layout = layout or TrayLayout()
  314. for i, (flat, detail) in enumerate(zip(ams_mapping, ams_mapping2, strict=True)):
  315. if not isinstance(detail, dict):
  316. continue
  317. ams_id = detail.get("ams_id")
  318. slot_id = detail.get("slot_id")
  319. if ams_id == A2L_LITE_PHYSICAL_AMS_ID and slot_id in (0, 1, 2, 3):
  320. resolved[i] = A2L_LITE_GLOBAL_BASE + slot_id
  321. continue
  322. if (
  323. isinstance(ams_id, int)
  324. and isinstance(slot_id, int)
  325. and not is_external_tray(ams_id, layout.rack)
  326. and is_rack_ams(layout.ams_type(ams_id))
  327. and 0 <= slot_id < RACK_SLOT_COUNT
  328. ):
  329. resolved[i] = layout.global_tray_id(ams_id, slot_id)
  330. continue
  331. if flat != -1 or not is_external_tray(ams_id, layout.rack) or slot_id == 255:
  332. continue
  333. resolved[i] = ams_id if is_dual_nozzle or layout.rack else 254
  334. return resolved
  335. def unit_reported_absent(ams_id, ams_list: list, ams_exist_bits) -> bool:
  336. """Whether a push that doesn't list AMS unit ``ams_id`` says it is unplugged.
  337. ``ams_exist_bits`` (hex) has bit n set for AMS unit n, measured on an X1C
  338. (unit 1 -> "2", none -> "0") and an H2C (units 0, 1, 2 and HT 128 -> "17").
  339. So an AMS unit 0-3 whose bit is clear is gone. An empty unit list with no
  340. bits set means no unit at all, which is what the X1C sends with its AMS
  341. unplugged. Anything else is kept, as the merge always did: a partial push
  342. lists only some units, and the bits of an AMS HT or AMS Lite next to other
  343. units are not measured well enough to read.
  344. """
  345. if ams_exist_bits is None:
  346. return False
  347. try:
  348. bits = int(ams_exist_bits, 16) if isinstance(ams_exist_bits, str) else int(ams_exist_bits)
  349. unit = int(ams_id)
  350. except (TypeError, ValueError):
  351. return False
  352. if bits == 0 and not ams_list:
  353. return True
  354. return 0 <= unit <= 3 and not bits >> unit & 1
  355. def apply_tray_exist_bits(
  356. units: list,
  357. tray_exist_bits_str: str | int | None,
  358. *,
  359. power_on_flag: bool = True,
  360. log_label: str | None = None,
  361. annotate_exists: bool = False,
  362. ) -> int:
  363. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  364. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  365. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  366. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  367. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  368. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  369. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  370. instead of guessing from payload shape (#1322, #147).
  371. Two callers share this helper to keep their views consistent:
  372. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  373. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  374. facing push_status (#1726 — without this the VP would forward stale
  375. per-tray fields for empty slots, and BambuStudio's Sync would render
  376. phantom loaded slots).
  377. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  378. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  379. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  380. so spool removal is detected without requiring a manual reconnect.
  381. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  382. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  383. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  384. authoritative empty signal for the HT — the only working clear path, since
  385. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  386. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  387. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  388. capture (HT-A → bit 16). The A2L-Lite lands at bits 24-27 via the regular
  389. ``ams_id * 4`` formula, matching OrcaSlicer's ``AMS_LITE_MIXED`` offset; the
  390. unit id is folded through ``normalize_am_unit_id`` first so callers holding
  391. the raw physical id 16 get the same bit base as callers holding the
  392. normalised 6 (#2697).
  393. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  394. way). Ints are tolerated for defensive symmetry but typically not seen
  395. on the wire. ``None`` / empty / unparseable → no-op.
  396. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  397. every processed slot. This is firmware's authoritative "spool physically
  398. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  399. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  400. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  401. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  402. leaves it False so the ``exists`` key never reaches the slicer wire format.
  403. Mutates ``units`` in place. Returns the number of slots cleared.
  404. """
  405. if not tray_exist_bits_str:
  406. return 0
  407. try:
  408. if isinstance(tray_exist_bits_str, int):
  409. tray_exist_bits = tray_exist_bits_str
  410. else:
  411. tray_exist_bits = int(tray_exist_bits_str, 16)
  412. except (ValueError, TypeError):
  413. return 0
  414. if tray_exist_bits == 0 and not power_on_flag:
  415. return 0
  416. if not isinstance(units, list):
  417. return 0
  418. cleared = 0
  419. for ams_unit in units:
  420. if not isinstance(ams_unit, dict):
  421. continue
  422. ams_id_raw = ams_unit.get("id")
  423. if ams_id_raw is None:
  424. continue
  425. try:
  426. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  427. except (ValueError, TypeError):
  428. continue
  429. if not isinstance(ams_id, int):
  430. continue
  431. # The A2L AMS-Lite reaches this helper under either id: `_handle_ams_data`
  432. # normalises 16 -> 6 before calling, but the VP bridge parses the raw
  433. # printer payload itself (`mqtt_bridge._on_printer_raw`) and still holds
  434. # the physical 16. Both mean bit base 24, so fold them together here
  435. # rather than relying on every caller to normalise first — reading 16 as
  436. # 16*4 = bit 64 finds nothing set and wipes every A2L slot (#2697).
  437. ams_id = normalize_am_unit_id(ams_id)
  438. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  439. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  440. # A rack AMS (unit 32): its global tray id 28 + slot.
  441. # Anything outside those has no known bit layout — don't guess it.
  442. kind = unit_ams_type(ams_id, ams_unit.get("info"))
  443. if tray_flag_bit(ams_id, 0, kind) is None:
  444. continue
  445. for tray in ams_unit.get("tray", []):
  446. if not isinstance(tray, dict):
  447. continue
  448. tray_id_raw = tray.get("id")
  449. if tray_id_raw is None:
  450. continue
  451. try:
  452. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  453. except (ValueError, TypeError):
  454. continue
  455. if not isinstance(tray_id, int):
  456. continue
  457. global_bit = tray_flag_bit(ams_id, tray_id, kind)
  458. if global_bit is None or global_bit < 0:
  459. continue
  460. slot_exists = (tray_exist_bits >> global_bit) & 1
  461. if annotate_exists:
  462. tray["exists"] = bool(slot_exists)
  463. if slot_exists:
  464. continue
  465. tray["state"] = 9
  466. if tray.get("tray_type"):
  467. if log_label:
  468. logger.debug(
  469. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  470. f"(tray_exist_bits bit {global_bit} = 0)"
  471. )
  472. tray["tray_type"] = ""
  473. tray["tray_sub_brands"] = ""
  474. tray["tray_color"] = ""
  475. tray["tray_id_name"] = ""
  476. tray["tag_uid"] = "0000000000000000"
  477. tray["tray_uuid"] = "00000000000000000000000000000000"
  478. tray["tray_info_idx"] = ""
  479. tray["remain"] = 0
  480. cleared += 1
  481. return cleared
  482. # --- H2C nozzle-rack dispatch mapping (#2800) -------------------------------
  483. #
  484. # Physical nozzle IDs the H2C reports for its six rack slots, verified on
  485. # hardware. They sit well clear of the fixed hotend's own physical ID, so a
  486. # rack position is never mistakable for the nozzle on the other carriage.
  487. #
  488. # Extruder indices are a different namespace that happens to overlap these
  489. # low numbers -- index 1 means the rack, physical ID 1 means the fixed hotend.
  490. # Nothing below may pass a value from one namespace to the other untranslated;
  491. # doing exactly that is what #2800 was.
  492. _RACK_NOZZLE_IDS = frozenset(range(16, 22))
  493. # BambuStudio dispatches a fixed-length nozzle_mapping on rack models: one
  494. # physical nozzle ID per filament slot, -1 for slots the plate does not print.
  495. #
  496. # Briefly changed to the plate's own slot count on the strength of a single
  497. # 3-entry capture, then changed back: Studio's dispatch of a real 3-filament
  498. # project print on the maintainer's H2C is 32 entries ([16, 1, 18, -1 x29],
  499. # captured 2026-08-13 17:20, and that print completed). The 3-entry capture was
  500. # a calibration job, so the length varies with whatever Studio is doing rather
  501. # than with the filament count -- which makes it the wrong thing to derive.
  502. _RACK_WIRE_SLOTS = 32
  503. # The two carriages, as extruder indices in the form the queue stores (already
  504. # translated through the file's physical_extruder_map).
  505. #
  506. # Measured on the maintainer's H2C 2026-08-14, from three sources that agree:
  507. #
  508. # - telemetry: ``ams_extruder_map {'0': 1, '1': 0, '2': 0}`` -- AMS 0 feeds
  509. # extruder 1, AMS 1 and 2 feed extruder 0;
  510. # - BambuStudio's own dispatch of a plate using all three units sent AMS 0's
  511. # filament to physical nozzle 1 and AMS 1's to rack positions 16 and 18,
  512. # and that print completed. So extruder 1 is the fixed hotend and extruder
  513. # 0 is the rack;
  514. # - our own constants were internally inconsistent about it: physical nozzle
  515. # id N sits on extruder N (see the L/R split in PrintersPage), and
  516. # ``_FIXED_NOZZLE_ID`` is 1, which cannot be reconciled with a fixed
  517. # extruder index of 0.
  518. #
  519. # These were the other way round until then, which is what dispatched a plate
  520. # to the carriage that had not been levelled and printed its first layer in
  521. # mid-air. That value came from #2800, where dispatching [17, -1, -1, 1] printed
  522. # in mid-air and [1, -1, -1, 17] printed correctly -- but that A/B measured
  523. # which *wire* worked, and the extruder indices were only inferred from it by
  524. # pairing with a slot_extruders list the then-buggy 3MF reader had produced. The
  525. # wire result stands; the inference from it did not.
  526. _FIXED_EXTRUDER_ID = 1
  527. _RACK_EXTRUDER_ID = 0
  528. # The fixed hotend's physical ID, which is *not* its extruder index. The same
  529. # hardware A/B ruled the index out: [0, -1, -1, 17] was rejected by the printer
  530. # outright, which would not start the job at all. Native BambuStudio captures
  531. # of a mixed plate agree -- [1, 17, ...], and [17, 1, ...] once the filament
  532. # slot order is swapped, so the fixed side is 1 whichever slot it lands in.
  533. _FIXED_NOZZLE_ID = 1
  534. def resolve_rack_nozzle_mapping(
  535. slot_extruders: list[int],
  536. rack_nozzle_id: int | None,
  537. ) -> list[int] | None:
  538. """Expand a per-slot extruder mapping into an H2C physical nozzle_mapping.
  539. ``slot_extruders`` is the compact form stored on the queue item: MQTT
  540. extruder index per filament slot (index 0 = slot 1), -1 for a slot the
  541. plate does not print. ``rack_nozzle_id`` is the rack position the printer
  542. reports as live.
  543. Returns a ``_RACK_WIRE_SLOTS``-long list of physical nozzle IDs, or None
  544. when the mapping cannot be resolved with confidence -- in which case the
  545. caller omits the field entirely and the firmware falls back to its own
  546. nozzle pick, exactly as it did before this translation existed. Omitting
  547. is deliberately the failure mode: a *wrong* physical ID makes the printer
  548. level with one nozzle and print with another several millimetres off the
  549. bed, which is far worse than letting the firmware choose.
  550. Returns None specifically when:
  551. - a slot needs the rack but the printer has not reported a live rack
  552. position (mid-swap, or a stale connection);
  553. - no slot needs the rack at all. BambuStudio omits nozzle_mapping entirely
  554. for a plate sliced for the fixed hotend only (#2800 capture), so this
  555. matches it rather than naming a nozzle it does not have to name;
  556. - a slot names a carriage that is neither of the two an H2C has, which
  557. means the file was mapped for a machine this translation does not model;
  558. - the plate needs more slots than the wire format carries;
  559. - the input is not a list of whole numbers.
  560. Total by construction: it raises nothing, because the only caller is
  561. building an MQTT print command with no exception handler above it and the
  562. queue item has already been committed as `printing` by then. An
  563. unparseable input has to degrade to "let the firmware pick", not to a job
  564. wedged in a state no print will ever leave.
  565. """
  566. if not isinstance(slot_extruders, list) or not slot_extruders:
  567. return None
  568. if len(slot_extruders) > _RACK_WIRE_SLOTS:
  569. return None
  570. if not isinstance(rack_nozzle_id, int) or isinstance(rack_nozzle_id, bool):
  571. return None
  572. if rack_nozzle_id not in _RACK_NOZZLE_IDS:
  573. return None
  574. # Normalise first so the checks below, and the values that reach the wire,
  575. # are known ints. bool is an int subclass and would otherwise serialise as
  576. # a JSON `true`; None means "slot not printed" and is folded into -1.
  577. normalised: list[int] = []
  578. for extruder in slot_extruders:
  579. if extruder is None:
  580. normalised.append(-1)
  581. elif isinstance(extruder, int) and not isinstance(extruder, bool):
  582. normalised.append(extruder)
  583. else:
  584. return None
  585. if _RACK_EXTRUDER_ID not in normalised:
  586. return None
  587. wire = [-1] * _RACK_WIRE_SLOTS
  588. for index, extruder in enumerate(normalised):
  589. if extruder < 0:
  590. continue
  591. if extruder == _RACK_EXTRUDER_ID:
  592. wire[index] = rack_nozzle_id
  593. elif extruder == _FIXED_EXTRUDER_ID:
  594. wire[index] = _FIXED_NOZZLE_ID
  595. else:
  596. # An H2C has these two carriages and no others. A third index is a
  597. # file mapped for something else, and forwarding it raw would name
  598. # a physical nozzle by an index that does not identify one.
  599. return None
  600. return wire
  601. # A rack position as the operator counts it (and as the printer card and
  602. # BambuStudio both label it) is 1-based; the physical nozzle id is 15 higher.
  603. # Measured 2026-08-14: a plate dispatched with the operator picking R1 and R2
  604. # sent 16 and 17, and the same plate picking R1 and R3 sent 16 and 18.
  605. _RACK_POSITION_BASE = 15
  606. RACK_POSITIONS = tuple(range(1, len(_RACK_NOZZLE_IDS) + 1))
  607. def rack_position_to_nozzle_id(position: int) -> int | None:
  608. """Physical nozzle id for a 1-based rack position, or None if out of range."""
  609. if not isinstance(position, int) or isinstance(position, bool):
  610. return None
  611. if position not in RACK_POSITIONS:
  612. return None
  613. return _RACK_POSITION_BASE + position
  614. def _rack_slot_is_eligible(slot: dict, diameter: str, volume_type: str) -> bool:
  615. """Whether a live rack slot can print a group wanting this nozzle.
  616. Mirrors the filter BambuStudio applies in its own picker: the position has
  617. to hold a nozzle at all, and that nozzle has to match the slice's diameter
  618. and flow type. A mismatch here is not cosmetic -- it is the printer being
  619. asked to lay down a 0.4 extrusion through a 0.2 orifice.
  620. """
  621. if not isinstance(slot, dict):
  622. return False
  623. slot_diameter = str(slot.get("diameter") or "").strip()
  624. slot_type = str(slot.get("type") or "").strip()
  625. if not slot_diameter and not slot_type:
  626. return False # empty position
  627. # "0.40" and "0.4" are the same nozzle spelled two ways -- the 3MF pads,
  628. # the printer does not.
  629. try:
  630. if round(float(slot_diameter), 2) != round(float(diameter), 2):
  631. return False
  632. except (TypeError, ValueError):
  633. return False
  634. # Flow type: the printer reports a code ("HS", "HH01"), the slice reports a
  635. # name ("Standard", "High Flow"). Compared only when both are stated, so a
  636. # printer that omits the code is not thereby ruled ineligible.
  637. wanted = volume_type.strip().lower()
  638. if wanted and slot_type:
  639. is_high_flow = slot_type.upper().startswith("HH")
  640. if wanted.startswith("high flow") != is_high_flow:
  641. return False
  642. return True
  643. # The nozzle currently picked up onto the rack carriage. Physical id 1 is the
  644. # fixed hotend (``_FIXED_NOZZLE_ID``), so the other carriage entry is 0.
  645. _RACK_CARRIAGE_NOZZLE_ID = 0
  646. def _rack_by_position(rack_slots: list[dict]) -> dict[int, dict]:
  647. """Live rack contents keyed by 1-based position, mounted nozzle included.
  648. The firmware omits a rack id entirely while that nozzle is picked up onto
  649. the carriage (#943) -- it does not send an empty placeholder. Taking the
  650. omission at face value would rule the nozzle ineligible for the very print
  651. that wants it, and it is the single most likely position to be picked,
  652. because it is the one the last print left mounted.
  653. The absent id is recoverable only when exactly one is missing: rack ids are
  654. fixed at 16..21, so a single gap alongside a loaded carriage is that
  655. carriage's nozzle. Two or more gaps are genuinely ambiguous -- an operator
  656. with four nozzles in six positions looks the same -- so those stay absent
  657. and the caller treats them as empty.
  658. Measured 2026-08-14 09:02 on the maintainer's H2C: ``IDs: [16, 1, 21, 19,
  659. 18, 0, 20]`` -- both carriages present, rack id 17 the lone gap.
  660. """
  661. by_position: dict[int, dict] = {}
  662. carriage: dict | None = None
  663. for slot in rack_slots or []:
  664. if not isinstance(slot, dict) or not isinstance(slot.get("id"), int):
  665. continue
  666. if slot["id"] == _RACK_CARRIAGE_NOZZLE_ID:
  667. carriage = slot
  668. continue
  669. position = slot["id"] - _RACK_POSITION_BASE
  670. if position in RACK_POSITIONS:
  671. by_position[position] = slot
  672. missing = [position for position in RACK_POSITIONS if position not in by_position]
  673. if len(missing) == 1 and carriage is not None and (carriage.get("diameter") or carriage.get("type")):
  674. by_position[missing[0]] = carriage
  675. return by_position
  676. def resolve_rack_plan_mapping(
  677. slot_groups: list[int],
  678. groups: dict[int, dict],
  679. choice: dict[int, int],
  680. rack_slots: list[dict],
  681. ) -> tuple[list[int] | None, str | None]:
  682. """Build a physical ``nozzle_mapping`` from a rack plan and a position pick.
  683. This is the multi-hotend counterpart to :func:`resolve_rack_nozzle_mapping`.
  684. That one can only name the single live rack position, so a plate wanting a
  685. different hotend per group is unresolvable to it. Here each group carries
  686. its own position, which is the operator's choice (#1784) -- the 3MF states
  687. it nowhere, proven by dispatching one plate twice with different picks and
  688. diffing the two files down to float noise.
  689. ``choice`` may be partial or empty; groups it does not name are assigned
  690. from the live rack, preferring a position already loaded with the group's
  691. own filament colour and otherwise taking the lowest eligible one.
  692. Returns ``(wire, None)`` on success, or ``(None, reason)`` where *reason*
  693. is a sentence naming what could not be satisfied. The caller decides what
  694. to do with a failure, and the two cases differ: a stale *explicit* pick
  695. should stop the print, while a failed auto-assignment should degrade to
  696. letting the firmware choose, exactly as before this existed.
  697. """
  698. if not isinstance(slot_groups, list) or not slot_groups:
  699. return None, "the plate lists no filament slots"
  700. if len(slot_groups) > _RACK_WIRE_SLOTS:
  701. return None, f"the plate needs {len(slot_groups)} filament slots and the printer takes {_RACK_WIRE_SLOTS}"
  702. by_position = _rack_by_position(rack_slots)
  703. # Assign every rack-bound group a position before building the wire, so a
  704. # group can never be handed one an earlier group already took. Explicit
  705. # picks are placed first: an auto-assignment must yield to them rather than
  706. # claim a position the operator asked for.
  707. assigned: dict[int, int] = {}
  708. rack_group_ids = sorted(gid for gid, g in groups.items() if g.get("on_rack"))
  709. for group_id in rack_group_ids:
  710. position = choice.get(group_id)
  711. if position is None:
  712. continue
  713. group = groups[group_id]
  714. if rack_position_to_nozzle_id(position) is None:
  715. return None, f"rack position {position} does not exist"
  716. if position in assigned.values():
  717. return None, f"rack position {position} is picked for more than one filament group"
  718. slot = by_position.get(position)
  719. if slot is None:
  720. return None, f"the printer reports nothing at rack position {position}"
  721. if not _rack_slot_is_eligible(slot, group.get("nozzle_diameter", ""), group.get("volume_type", "")):
  722. return None, (
  723. f"rack position {position} holds a "
  724. f"{slot.get('diameter') or 'missing'} {slot.get('type') or ''} nozzle, "
  725. f"and the plate needs {group.get('nozzle_diameter')} {group.get('volume_type')}".replace(" ", " ")
  726. )
  727. assigned[group_id] = position
  728. for group_id in rack_group_ids:
  729. if group_id in assigned:
  730. continue
  731. group = groups[group_id]
  732. eligible = [
  733. position
  734. for position in RACK_POSITIONS
  735. if position not in assigned.values()
  736. and position in by_position
  737. and _rack_slot_is_eligible(
  738. by_position[position], group.get("nozzle_diameter", ""), group.get("volume_type", "")
  739. )
  740. ]
  741. if not eligible:
  742. return None, (
  743. f"no free rack position holds a {group.get('nozzle_diameter')} "
  744. f"{group.get('volume_type')} nozzle for filament group {group_id}"
  745. )
  746. # Prefer a position already carrying this group's colour: picking it
  747. # means the operator does not have to move filament to make the print
  748. # match what they asked for.
  749. wanted_colour = str(group.get("filament_color") or "").strip().lstrip("#").upper()[:6]
  750. assigned[group_id] = next(
  751. (
  752. position
  753. for position in eligible
  754. if wanted_colour
  755. and str(by_position[position].get("filament_color") or "").strip().lstrip("#").upper()[:6]
  756. == wanted_colour
  757. ),
  758. eligible[0],
  759. )
  760. wire = [-1] * _RACK_WIRE_SLOTS
  761. for index, group_id in enumerate(slot_groups):
  762. if not isinstance(group_id, int) or isinstance(group_id, bool) or group_id < 0:
  763. continue # slot this plate does not print
  764. group = groups.get(group_id)
  765. if group is None:
  766. return None, f"filament slot {index + 1} names group {group_id}, which the plate does not describe"
  767. if not group.get("on_rack"):
  768. wire[index] = _FIXED_NOZZLE_ID
  769. continue
  770. nozzle_id = rack_position_to_nozzle_id(assigned[group_id])
  771. if nozzle_id is None: # pragma: no cover - assigned only ever holds valid positions
  772. return None, f"filament group {group_id} resolved to no rack position"
  773. wire[index] = nozzle_id
  774. if all(value == -1 for value in wire):
  775. return None, "the plate assigns no filament to a nozzle"
  776. return wire, None
  777. @dataclass(frozen=True)
  778. class DryingCycleEnd:
  779. """What Bambuddy saw of one AMS drying cycle, reported when it ends (#2863).
  780. ``peak_minutes`` is the highest ``dry_time`` observed during the cycle and
  781. ``remaining_minutes`` the last one before the drop to 0. ``start_seen`` says
  782. whether the countdown was watched from its first minute; when it was not
  783. (Bambuddy started mid-cycle) the peak is only a lower bound on the length.
  784. ``target_temp`` / ``target_hours`` are known only for cycles Bambuddy itself
  785. started, because the printer never echoes them.
  786. """
  787. ams_id: int
  788. remaining_minutes: int
  789. peak_minutes: int
  790. start_seen: bool
  791. target_temp: int | None = None
  792. target_hours: int | None = None
  793. @dataclass
  794. class MQTTLogEntry:
  795. """Log entry for MQTT message debugging."""
  796. timestamp: str
  797. topic: str
  798. direction: str # "in" or "out"
  799. payload: dict
  800. @dataclass
  801. class HMSError:
  802. """Health Management System error from printer."""
  803. code: str
  804. attr: int # Attribute value for constructing wiki URL
  805. module: int
  806. # Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  807. # 3 notification, 0 invalid. From `code >> 16` for `hms[]` faults, and from
  808. # the error's first hex digit for `print_error` (#2728).
  809. severity: int
  810. # The bundled catalogue's sentence for this fault, resolved once here so
  811. # every surface that reports it — the status response, the WebSocket
  812. # broadcast, the completion payload, notifications — says the same thing.
  813. # None when Bambu publishes no text for the code; see `describe_fault`.
  814. # Replaces a `message` field that was never set or read anywhere.
  815. description: str | None = None
  816. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  817. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  818. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  819. # HMSError without explicitly passing actions can't silently land None on the schema
  820. # boundary and raise ValidationError at routes/printers.py response time.
  821. actions: list[str] = field(default_factory=list)
  822. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  823. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  824. job_id: str | None = None
  825. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  826. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  827. # 32-bit `print_error` path. The frontend echoes this back to
  828. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  829. # used to send caused the firmware to silently reject HMS commands on H2C
  830. # (#1830) and on `hms[]`-sourced faults generally.
  831. full_code: str = ""
  832. def completion_payload(self) -> dict:
  833. """This error as a print-complete payload carries it, for the failure reason."""
  834. return {
  835. "code": self.code,
  836. "attr": self.attr,
  837. "module": self.module,
  838. "severity": self.severity,
  839. # Lets the queue's failure reason label an `hms[]` fault
  840. # with its full code rather than a lossy short one (#2728).
  841. "full_code": self.full_code,
  842. # Carried so the queue's failure reason quotes the same
  843. # sentence the status response and the broadcast do,
  844. # rather than resolving the code a fourth time (#2926).
  845. "description": self.description,
  846. }
  847. def _is_print_error_entry(error: HMSError) -> bool:
  848. """Whether this entry came from the 32-bit `print_error` field, whose
  849. full code has 8 hex digits; an `hms[]` entry's has 16."""
  850. return len(error.full_code) == 8
  851. def _hms_short_code(error: HMSError) -> str:
  852. """The MMMM_EEEE short code of an entry from either source."""
  853. module = (error.attr >> 16) & 0xFFFF
  854. # The low half only: an hms[] code carries its alert level above it
  855. # (0x18061 for 0500_8061), and read whole it never matched, listing the
  856. # fault twice (M-U9).
  857. number = (int(error.code.replace("0x", ""), 16) & 0xFFFF) if error.code else 0
  858. return f"{module:04X}_{number:04X}"
  859. def _hms_short_codes(errors: list) -> set[str]:
  860. return {_hms_short_code(e) for e in errors}
  861. # HMS short codes the firmware emits during normal user-cancel sequences.
  862. # These aren't faults — they're status echoes that confirm the cancel happened.
  863. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  864. # so they don't drive the printer card's "X problem" badge, the red pip, or
  865. # any other consumer that treats hms_errors as the active-fault list.
  866. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  867. {
  868. "0300_400C", # "The task was canceled."
  869. "0500_400E", # "Printing was cancelled."
  870. }
  871. )
  872. # "MQTT command verification failed" — the printer's authorization/authentication
  873. # protection (firmware >= 01.08.03.00beta / 01.08.05.00) rejecting a control
  874. # command it could not verify. Queries (get_version, extrusion_cali_get,
  875. # pushall) still answer, so the connection looks perfectly healthy while
  876. # project_file, gcode_line and ams_change_filament are all silently dropped —
  877. # which is exactly how it presents: uploads succeed, the printer echoes our
  878. # subtask_id, then sits at IDLE forever (#2732).
  879. #
  880. # The 16-char form is load-bearing. This code's meaning lives in attr's low half
  881. # (0500) and code's high half (0001); the MMMM_EEEE short code collapses it to
  882. # "0500_0007", which matches nothing in any catalog.
  883. HMS_MQTT_VERIFY_FAILED: str = "0500050000010007"
  884. @dataclass
  885. class KProfile:
  886. """Pressure advance (K) calibration profile from printer."""
  887. slot_id: int
  888. extruder_id: int
  889. nozzle_id: str
  890. nozzle_diameter: str
  891. filament_id: str
  892. name: str
  893. k_value: str
  894. n_coef: str = "0.000000"
  895. ams_id: int = 0
  896. tray_id: int = -1
  897. setting_id: str | None = None
  898. @dataclass
  899. class NozzleInfo:
  900. """Nozzle hardware configuration."""
  901. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  902. nozzle_diameter: str = "" # e.g., "0.4"
  903. # What await_cali_ack reports when the printer did not answer a K-profile write
  904. # in time. Not a refusal: firmware that predates the ack never answers.
  905. CALI_ACK_UNCONFIRMED = "no acknowledgement from printer"
  906. class KProfileReadError(Exception):
  907. """The printer's K-profile table could not be read: not connected, or no
  908. answer to any attempt. Not an empty table, which is a printer without
  909. profiles for that nozzle (#3404)."""
  910. # Time the printer has to list a skipped object in s_obj before the skip is
  911. # logged as not confirmed.
  912. SKIP_CONFIRM_TIMEOUT_S = 60.0
  913. # Answers to K-profile commands: they echo the command's own fields (the nozzle
  914. # diameter among them), never the printer's status.
  915. _KPROFILE_COMMAND_ANSWERS = frozenset(
  916. {"extrusion_cali_get", "extrusion_cali_set", "extrusion_cali_del", "extrusion_cali_sel"}
  917. )
  918. @dataclass
  919. class FilaSwitchState:
  920. """Filament Track Switch (FTS) accessory state.
  921. The FTS is an external accessory that mediates filament routing between an
  922. AMS and the printer's extruders. When installed, the AMS no longer has a
  923. fixed extruder assignment — any slot can be routed to any extruder via the
  924. track switch. Detected from print.device.fila_switch in MQTT.
  925. The switch has two inlets (In-A, In-B) and two outlets (Out-A, Out-B), and
  926. can pair any inlet with any outlet. Which AMS sits on which *inlet* is the
  927. stable, operator-visible relationship — it is set on the printer's "Manual
  928. AMS Setup" screen and read back from AMS ``info`` bits 24-27, not from here.
  929. Field semantics below are taken from BambuStudio's own parser
  930. (``DevFilaSwitch::ParseFilaSwitchInfo``), not inferred.
  931. """
  932. installed: bool = False
  933. # Raw ``in`` array, as it arrives. **Index 0 is In-B and index 1 is In-A** —
  934. # the arrays are ordered B-then-A, which is the opposite of how they read.
  935. # Each value is snow-encoded: bits 8-15 = AMS id, bits 0-7 = slot. -1 = the
  936. # inlet is empty. Use `inlet_slot()` rather than indexing this directly.
  937. in_slots: list[int] = field(default_factory=list)
  938. # Raw ``out`` array, same B-then-A order. out[i] = the extruder that *outlet*
  939. # terminates at (0 = right/main, 1 = left/deputy), or 0xE when unset. Note
  940. # this is the outlet's static wiring, NOT the live inlet→outlet route: which
  941. # inlet is currently paired with which outlet is not reported at all.
  942. out_extruders: list[int] = field(default_factory=list)
  943. stat: int = 0 # CaliStatus: 0 = idle, 1 = calibration stepping
  944. info: int = 0 # bit 0 = inlet has filament
  945. def inlet_slot(self, inlet: str) -> tuple[int, int] | None:
  946. """Decode ``in`` for inlet ``"A"`` or ``"B"`` into ``(ams_id, slot)``.
  947. Returns None when the inlet is empty, unreported, or ``inlet`` is not
  948. one of A/B.
  949. """
  950. index = {"A": 1, "B": 0}.get(inlet.upper())
  951. if index is None or index >= len(self.in_slots):
  952. return None
  953. raw = self.in_slots[index]
  954. if raw < 0:
  955. return None
  956. return (raw >> 8) & 0xFF, raw & 0xFF
  957. # ``snow``/``spre``/``star`` all use this sentinel for "nothing here". Studio
  958. # only special-cases it on single-extruder machines, but 0xFFFF decodes to AMS
  959. # 255 slot 255 and slot 255 is not a real slot on any machine, so treating it
  960. # as empty everywhere is strictly safer than reading it as the external spool.
  961. _EXTRUDER_SLOT_EMPTY = 0xFFFF
  962. @dataclass
  963. class ExtruderSlot:
  964. """Which AMS slot an extruder is currently fed from.
  965. Parsed from ``print.device.extruder.info[i]`` — ``snow`` is snow-encoded
  966. exactly like ``fila_switch.in`` (bits 8-15 = AMS id, bits 0-7 = slot), and
  967. bit 1 of ``info`` says whether the extruder actually holds filament. Field
  968. semantics from BambuStudio's ``DevExtruderSystem::ParseExtruderInfo``.
  969. ``state.tray_now`` cannot answer this: it is a single value for the whole
  970. printer, so on a dual-nozzle machine with both hotends loaded it names only
  971. one of them. Unloading a specific slot needs to know which extruder is
  972. holding it, which is what this is for.
  973. """
  974. ams_id: int | None = None
  975. slot_id: int | None = None
  976. has_filament: bool = False
  977. def holds(self, ams_id: int, slot_id: int) -> bool:
  978. """True when this extruder is fed from exactly ``(ams_id, slot_id)``."""
  979. return self.ams_id == ams_id and self.slot_id == slot_id
  980. @dataclass
  981. class PrintOptions:
  982. """AI detection and print options from xcam data."""
  983. # Core AI detectors
  984. spaghetti_detector: bool = False
  985. print_halt: bool = False
  986. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  987. first_layer_inspector: bool = False
  988. printing_monitor: bool = False # AI print quality monitoring
  989. buildplate_marker_detector: bool = False
  990. allow_skip_parts: bool = False
  991. # Additional AI detectors - decoded from cfg bitmask
  992. nozzle_clumping_detector: bool = True
  993. nozzle_clumping_sensitivity: str = "medium"
  994. pileup_detector: bool = True
  995. pileup_sensitivity: str = "medium"
  996. airprint_detector: bool = True
  997. airprint_sensitivity: str = "medium"
  998. auto_recovery_step_loss: bool = True # Uses print.print_option command
  999. filament_tangle_detect: bool = False
  1000. @dataclass
  1001. class PrinterState:
  1002. connected: bool = False
  1003. state: str = "unknown"
  1004. current_print: str | None = None
  1005. subtask_name: str | None = None
  1006. progress: float = 0.0
  1007. remaining_time: int = 0
  1008. layer_num: int = 0
  1009. total_layers: int = 0
  1010. temperatures: dict = field(default_factory=dict)
  1011. raw_data: dict = field(default_factory=dict)
  1012. gcode_file: str | None = None
  1013. subtask_id: str | None = None
  1014. hms_errors: list = field(default_factory=list) # List of HMSError
  1015. kprofiles: list = field(default_factory=list) # List of KProfile
  1016. sdcard: bool = False # SD card inserted
  1017. # Whether the printer has ever actually told us about `sdcard`. Without this
  1018. # the default False is indistinguishable from a real "no card", and any
  1019. # consumer that treats False as evidence would act on silence — which is how
  1020. # a storage gate turns into a regression for every printer whose firmware
  1021. # simply doesn't publish the field (#2780).
  1022. sdcard_reported: bool = False
  1023. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  1024. # Scheme+path of a `project_file` dispatch seen on the request topic, from
  1025. # whoever sent it (the slicer or us). Bambu states where the sliced file
  1026. # went: `ftp://<name>` is external storage, which FTPS serves, while
  1027. # `brtc://emmc/<name>` is the printer's internal storage, which it does not.
  1028. #
  1029. # Two fields, because the two readers need different guarantees.
  1030. # ``current_project_url`` belongs to the print now running and is cleared
  1031. # when that print ends, so a print Bambuddy saw no dispatch for reads as
  1032. # "unknown" rather than inheriting the previous job's answer. That matters:
  1033. # 18% of the print starts in #2780's bundle had no dispatch on the request
  1034. # topic at all (touchscreen reprints, restart recovery), and a stale
  1035. # internal-storage URL would make those skip an FTPS sweep that could have
  1036. # found the file — losing an archive that works today.
  1037. #
  1038. # ``last_project_url`` is sticky and exists for reporting only: the
  1039. # connection diagnostic is usually run *after* the print that prompted it,
  1040. # by which point the per-print value is rightly gone.
  1041. #
  1042. # None means we never saw a dispatch — say nothing, don't guess.
  1043. current_project_url: str | None = None
  1044. last_project_url: str | None = None
  1045. timelapse: bool = False # Timelapse recording active
  1046. ipcam: bool = False # Live view / camera streaming enabled
  1047. wifi_signal: int | None = None # WiFi signal strength in dBm
  1048. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  1049. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  1050. # Nozzle hardware info. Indexed by EXTRUDER id: [0] is the RIGHT hotend and
  1051. # [1] the left, measured 2026-08-27 on an H2D fitted with 0.4 left / 0.6
  1052. # right. (The legacy parser below writes left -> [0], but it only ever runs
  1053. # for single-nozzle printers -- every dual-nozzle model reports
  1054. # device.nozzle.info instead.) Read it through services.slot_nozzle rather
  1055. # than indexing it directly.
  1056. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  1057. # AI detection and print options
  1058. print_options: PrintOptions = field(default_factory=PrintOptions)
  1059. # Calibration stage tracking (from stg_cur and stg fields)
  1060. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  1061. stg: list = field(default_factory=list) # List of stages to execute
  1062. # Air conditioning mode (0=cooling, 1=heating)
  1063. airduct_mode: int = 0
  1064. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1065. speed_level: int = 2
  1066. # Chamber light on/off
  1067. chamber_light: bool = False
  1068. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  1069. active_extruder: int = 0
  1070. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  1071. tray_now: int = 255
  1072. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  1073. # tray_tar = the slot the paused/loading print now expects
  1074. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  1075. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  1076. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  1077. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  1078. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  1079. tray_tar: int = 255
  1080. tray_pre: int = 255
  1081. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  1082. last_loaded_tray: int = -1
  1083. # Pending load target - used to track what tray we're loading for H2D disambiguation
  1084. pending_tray_target: int | None = None
  1085. # When it was set (time.monotonic): see PENDING_TRAY_TARGET_TTL.
  1086. pending_tray_target_at: float | None = None
  1087. # AMS status for filament change tracking (from print.ams.ams_status field)
  1088. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1089. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  1090. ams_status: int = 0
  1091. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  1092. ams_status_sub: int = 0 # ams_status & 0xFF
  1093. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  1094. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  1095. mc_print_sub_stage: int = 0
  1096. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  1097. ams_mapping: list = field(default_factory=list)
  1098. # The running print's AMS mapping (global tray per filament, -1 = none),
  1099. # as captured from its print command. None when no print has one.
  1100. print_ams_mapping: list | None = None
  1101. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  1102. ams_extruder_map: dict = field(default_factory=dict)
  1103. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  1104. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  1105. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  1106. # Per-AMS FTS inlet binding: {ams_id: "A" | "B"}. Which of the switch's two
  1107. # filament inlets an AMS is plumbed into, as set on the printer's "Manual AMS
  1108. # Setup" screen. Only populated when an FTS is installed — without one an AMS
  1109. # is bound to an extruder instead and this stays empty. See FilaSwitchState.
  1110. ams_switch_inlet: dict = field(default_factory=dict)
  1111. # Which AMS slot each extruder is fed from: {extruder_id: ExtruderSlot}.
  1112. # Only populated by printers that report ``device.extruder.info`` (H2/X2
  1113. # series). Empty elsewhere, which every reader has to tolerate — see
  1114. # ExtruderSlot for why tray_now cannot stand in for it.
  1115. extruder_slots: dict = field(default_factory=dict)
  1116. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  1117. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  1118. # regex used to derive the plate number from the path always falls back to
  1119. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  1120. # Bambuddy dispatches the print itself we know the plate authoritatively;
  1121. # we record it here and prefer it over the gcode_file regex. The subtask
  1122. # field guards against staleness: if the printer is currently running a
  1123. # different subtask (e.g. a Studio-direct dispatch), these values are
  1124. # ignored. Cleared on disconnect.
  1125. dispatched_plate_id: int | None = None
  1126. dispatched_subtask: str | None = None
  1127. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  1128. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  1129. h2d_extruder_snow: dict = field(default_factory=dict)
  1130. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  1131. nozzle_rack: list = field(default_factory=list)
  1132. # H2C rack position currently mounted / being moved to, from
  1133. # device.nozzle.src_id / tar_id. These are PHYSICAL nozzle IDs (16-21 for
  1134. # the six rack slots), not extruder indices, and they are what the
  1135. # dispatch `nozzle_mapping` array has to carry (#2800). Only the printer
  1136. # can tell us which hotend is in the carriage right now, so this is read
  1137. # live rather than derived from the queued job.
  1138. nozzle_rack_src_id: int | None = None
  1139. nozzle_rack_tar_id: int | None = None
  1140. # Timestamp of last AMS data update (for RFID refresh detection)
  1141. last_ams_update: float = 0.0
  1142. # Printable objects for skip object functionality: {identify_id: object_name}
  1143. printable_objects: dict = field(default_factory=dict)
  1144. # Objects that have been skipped during the current print
  1145. skipped_objects: list = field(default_factory=list)
  1146. # Pauses the slicer put into the running print, from its archived 3MF
  1147. # (#2984): threemf_tools.PausePoint, in print order. Empty when unknown.
  1148. pause_points: list = field(default_factory=list)
  1149. # Layers of those pauses a heads-up notification already went out for.
  1150. pause_warned_layers: set = field(default_factory=set)
  1151. # Fan speeds (0-100 percentage, None if not available for this model)
  1152. cooling_fan_speed: int | None = None # Part cooling fan
  1153. big_fan1_speed: int | None = None # Auxiliary fan
  1154. big_fan2_speed: int | None = None # Chamber/exhaust fan
  1155. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  1156. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  1157. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  1158. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  1159. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  1160. left_aux_fan_speed: int | None = None
  1161. # Chamber exhaust fan, derived from the airduct parts list containing decoded
  1162. # id 3. On the P2S this is the External Exhaust Fan kit and a base machine
  1163. # omits it, which is the case this flag exists to detect.
  1164. #
  1165. # NOTE: the flag is not P2S/X2D-specific despite the name. The H2 series
  1166. # (H2C/H2D/H2S) also reports part 3, so this goes True there too. That is
  1167. # harmless because only the P2S/X2D badge consults it — those models keep
  1168. # their unconditional "Chamber Fan" badge — but do not read this as
  1169. # "an exhaust kit is fitted" without also checking the model.
  1170. exhaust_fan_present: bool = False
  1171. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  1172. # Used by usage tracker to split filament weight on mid-print tray switch
  1173. tray_change_log: list = field(default_factory=list)
  1174. # Spools assigned to a tray during the current print, and the spool each
  1175. # assigned tray held at its start (services.spool_swaps, #3325).
  1176. spool_change_log: list = field(default_factory=list)
  1177. # Firmware version info (from info.module[name="ota"].sw_ver)
  1178. firmware_version: str | None = None
  1179. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  1180. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  1181. developer_mode: bool | None = None
  1182. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  1183. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  1184. # which uses the old protocol path; field not yet found). Consumers must treat
  1185. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  1186. ams_filament_backup: bool | None = None
  1187. # Stage name mapping from BambuStudio DeviceManager.cpp
  1188. STAGE_NAMES = {
  1189. 0: "Printing",
  1190. 1: "Auto bed leveling",
  1191. 2: "Heatbed preheating",
  1192. 3: "Vibration compensation",
  1193. 4: "Changing filament",
  1194. 5: "M400 pause",
  1195. 6: "Paused (filament ran out)",
  1196. 7: "Heating nozzle",
  1197. 8: "Calibrating dynamic flow",
  1198. 9: "Scanning bed surface",
  1199. 10: "Inspecting first layer",
  1200. 11: "Identifying build plate type",
  1201. 12: "Calibrating Micro Lidar",
  1202. 13: "Homing toolhead",
  1203. 14: "Cleaning nozzle tip",
  1204. 15: "Checking extruder temperature",
  1205. 16: "Paused by the user",
  1206. 17: "Pause (front cover fall off)",
  1207. 18: "Calibrating the micro lidar",
  1208. 19: "Calibrating flow ratio",
  1209. 20: "Pause (nozzle temperature malfunction)",
  1210. 21: "Pause (heatbed temperature malfunction)",
  1211. 22: "Filament unloading",
  1212. 23: "Pause (step loss)",
  1213. 24: "Filament loading",
  1214. 25: "Motor noise cancellation",
  1215. 26: "Pause (AMS offline)",
  1216. 27: "Pause (low speed of the heatbreak fan)",
  1217. 28: "Pause (chamber temperature control problem)",
  1218. 29: "Cooling chamber",
  1219. 30: "Pause (Gcode inserted by user)",
  1220. 31: "Motor noise showoff",
  1221. 32: "Pause (nozzle clumping)",
  1222. 33: "Pause (cutter error)",
  1223. 34: "Pause (first layer error)",
  1224. 35: "Pause (nozzle clog)",
  1225. 36: "Measuring motion precision",
  1226. 37: "Enhancing motion precision",
  1227. 38: "Measure motion accuracy",
  1228. 39: "Nozzle offset calibration",
  1229. 40: "High temperature auto bed leveling",
  1230. 41: "Auto Check: Quick Release Lever",
  1231. 42: "Auto Check: Door and Upper Cover",
  1232. 43: "Laser Calibration",
  1233. 44: "Auto Check: Platform",
  1234. 45: "Confirming BirdsEye Camera location",
  1235. 46: "Calibrating BirdsEye Camera",
  1236. 47: "Auto bed leveling - phase 1",
  1237. 48: "Auto bed leveling - phase 2",
  1238. 49: "Heating chamber",
  1239. 50: "Cooling heatbed",
  1240. 51: "Printing calibration lines",
  1241. 52: "Auto Check: Material",
  1242. 53: "Live View Camera Calibration",
  1243. 54: "Waiting for heatbed temperature",
  1244. 55: "Auto Check: Material Position",
  1245. 56: "Cutting Module Offset Calibration",
  1246. 57: "Measuring Surface",
  1247. 58: "Thermal Preconditioning",
  1248. 59: "Homing Blade Holder",
  1249. 60: "Calibrating Camera Offset",
  1250. 61: "Calibrating Blade Holder Position",
  1251. 62: "Hotend Pick and Place Test",
  1252. 63: "Waiting for Chamber temperature",
  1253. 64: "Preparing Hotend",
  1254. 65: "Calibrating nozzle clumping detection",
  1255. 66: "Purifying the chamber air",
  1256. 74: "Preparing", # Seen on H2D during print preparation
  1257. 77: "Preparing AMS",
  1258. }
  1259. def get_stage_name(stage: int) -> str:
  1260. """Get human-readable stage name from stage number."""
  1261. try:
  1262. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  1263. except TypeError:
  1264. # `stage` is an int by convention only -- it comes straight out of the
  1265. # printer's JSON, and an unhashable value there would otherwise raise
  1266. # from inside the f-string that builds the stage-change log line, which
  1267. # is evaluated on every transition whatever the log level is set to.
  1268. # Labelling a value must not be able to abort the state update.
  1269. return f"Unknown stage ({stage})"
  1270. # #2547 end-of-print telemetry probe.
  1271. #
  1272. # The finish photo needs a "printing is done, toolhead parked, filament unload
  1273. # not started yet" moment. ``stg_cur=22`` was meant to be that moment (#1721)
  1274. # but fires on no model in the field: across 247 support bundles there is not a
  1275. # single ``FINISH PHOTO MOMENT (stage-22)``, including the 2026-06-13..07-08
  1276. # window where it was the only pre-FINISH trigger in the code (104 captures on
  1277. # A1, A1 Mini, H2C, H2D, P1S, P2S, X1C, X2D — all of them the FINISH fallback).
  1278. #
  1279. # We can't design a replacement from bundles we already have, because out of
  1280. # this window Bambuddy only ever parses ``stg_cur`` and ``mc_print_sub_stage``;
  1281. # every other stage/action field is dropped unread. The obvious candidates
  1282. # (``print_real_action``, ``mc_action``, ``mc_stage``) are also absent from
  1283. # A1/A1 Mini/P1S payloads, so none of them can be the universal answer on its
  1284. # own. Dumping the raw values for the window between the last object layer and
  1285. # ``gcode_state=FINISH`` lets one debug bundle per model settle what — if
  1286. # anything — marks that moment.
  1287. #
  1288. # Every field here is machine telemetry (stage codes, counters, bitfields).
  1289. # Nothing identifying, and nothing that could carry an access code.
  1290. _END_OF_PRINT_PROBE_FIELDS = (
  1291. "gcode_state",
  1292. "state",
  1293. "print_error",
  1294. "stg_cur",
  1295. "stg",
  1296. "stg_cd",
  1297. "mc_print_stage",
  1298. "mc_print_sub_stage",
  1299. "mc_action",
  1300. "mc_stage",
  1301. "print_real_action",
  1302. "print_gcode_action",
  1303. "spd_lvl",
  1304. "mc_percent",
  1305. "mc_remaining_time",
  1306. "layer_num",
  1307. "total_layer_num",
  1308. "home_flag",
  1309. "prepare_per",
  1310. )
  1311. # Frame budget for one print's probe. A long final layer can hold the window
  1312. # open for minutes at ~1 frame/second; this stops a single print from filling
  1313. # the log the user then has to upload.
  1314. _END_OF_PRINT_PROBE_MAX_FRAMES = 400
  1315. # States that close the window. FINISH is the interesting one — the probe's
  1316. # whole job is to show what happened in the run-up to it.
  1317. _END_OF_PRINT_PROBE_CLOSING_STATES = frozenset({"FINISH", "FAILED", "IDLE", "PREPARE"})
  1318. class BambuMQTTClient:
  1319. """MQTT client for Bambu Lab printer communication."""
  1320. MQTT_PORT = 8883
  1321. # Class-level cache: serial_number -> False when request topic is known unsupported.
  1322. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  1323. _request_topic_cache: dict[str, bool] = {}
  1324. # serial_number -> consecutive disconnects seen shortly after subscribing to
  1325. # the request topic. A SUBACK failure is the broker answering the question;
  1326. # a disconnect is only circumstantial, and any drop inside the window looks
  1327. # identical -- a network blip, the printer rebooting, the container being
  1328. # stopped mid-probe. Latching on the first one costs ams_mapping capture for
  1329. # the rest of the process on a printer that supports it perfectly well
  1330. # (#2953). Require the drop to repeat before believing it; a printer that
  1331. # really does refuse the topic answers the same way every time and pays one
  1332. # extra reconnect for it.
  1333. _request_topic_probe_failures: dict[str, int] = {}
  1334. _REQUEST_TOPIC_PROBE_LIMIT: int = 2
  1335. # Counter for generating unique MQTT client IDs across instances.
  1336. _client_instance_counter: int = 0
  1337. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  1338. # before declaring it un-confirmed. The printer re-broadcasts tray state
  1339. # every few seconds (and register_assignment_verification nudges a fresh
  1340. # pushall), so this only has to survive a couple of idle push intervals.
  1341. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  1342. def __init__(
  1343. self,
  1344. ip_address: str,
  1345. serial_number: str,
  1346. access_code: str,
  1347. model: str | None = None,
  1348. on_state_change: Callable[[PrinterState], None] | None = None,
  1349. on_print_start: Callable[[dict], None] | None = None,
  1350. on_print_complete: Callable[[dict], None] | None = None,
  1351. on_ams_change: Callable[[list], None] | None = None,
  1352. on_layer_change: Callable[[int], None] | None = None,
  1353. on_print_progress: Callable[[int], None] | None = None,
  1354. on_bed_temp_update: Callable[[float], None] | None = None,
  1355. on_drying_complete: Callable[[int], None] | None = None,
  1356. on_drying_cycle_end: Callable[[DryingCycleEnd], None] | None = None,
  1357. on_print_running_observed: Callable[[dict], None] | None = None,
  1358. on_finish_photo_moment: Callable[[dict], None] | None = None,
  1359. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  1360. on_tray_change: Callable[[int, int], None] | None = None,
  1361. on_fts_inlet_change: Callable[[int, str], None] | None = None,
  1362. ):
  1363. self.ip_address = ip_address
  1364. self.serial_number = serial_number
  1365. self.access_code = access_code
  1366. self.model = model
  1367. # Last value logged by _debug_on_change(), keyed by log site. See there.
  1368. self._debug_last: dict[str, object] = {}
  1369. self.on_state_change = on_state_change
  1370. self.on_print_start = on_print_start
  1371. self.on_print_complete = on_print_complete
  1372. self.on_ams_change = on_ams_change
  1373. # Fired when an AMS is moved to the switch's other inlet, which changes
  1374. # the nozzle it feeds and so invalidates its slots' K-profile bindings.
  1375. self.on_fts_inlet_change = on_fts_inlet_change
  1376. self.on_layer_change = on_layer_change
  1377. # #2547: fired when `mc_percent` advances during a running print.
  1378. # `on_layer_change` stops firing the instant the final layer starts, so
  1379. # it is blind to the last few percent of a print — which is exactly the
  1380. # window the finish-photo frame bank needs to keep refreshing through.
  1381. # Progress is the one field that keeps ticking there and then freezes
  1382. # before the end G-code runs, so banking on it stays inside the print.
  1383. self.on_print_progress = on_print_progress
  1384. self.on_bed_temp_update = on_bed_temp_update
  1385. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  1386. # the drying cycle just finished (auto- or manually-triggered).
  1387. # Receives the AMS id of the unit that finished drying.
  1388. self.on_drying_complete = on_drying_complete
  1389. # #2863: fired on the same edge with what was seen of the cycle, so the
  1390. # spools in that AMS can be stamped as dried.
  1391. self.on_drying_cycle_end = on_drying_cycle_end
  1392. # #1485 follow-up: fired the first time we see RUNNING state in a
  1393. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  1394. # print, the #1304 first-push guard skipped the start event). Lets
  1395. # main.py capture a fresh timelapse baseline at restart-recovery
  1396. # time so the completion-time snapshot-diff still works. Receives
  1397. # the same shape as on_print_start (filename / subtask_name /
  1398. # remaining_time / raw_data / ams_mapping).
  1399. self.on_print_running_observed = on_print_running_observed
  1400. # Fired for every entry appended to ``state.tray_change_log`` so main.py
  1401. # can mirror it into ``active_print_sessions``. The in-memory log dies
  1402. # with the process, and a long print outliving a restart would
  1403. # otherwise lose the segment boundaries the usage tracker splits on.
  1404. # Receives (global_tray_id, layer_num).
  1405. self.on_tray_change = on_tray_change
  1406. # #1721: fired the moment the printer enters the end-of-print
  1407. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  1408. # we've hit the last layer / remaining_time<=0). This is the
  1409. # framing #1397 was after — toolhead parked, bed not yet
  1410. # dropped — but reached via a clean state signal instead of
  1411. # the per-layer M622 J1 macros which caused per-layer nozzle
  1412. # parks on slicer profiles with Timelapse Type = Smooth.
  1413. # A FINISH-state fallback below fires this same callback if
  1414. # stage 22 never arrives (cancel mid-print, external-spool-
  1415. # only prints, HMS halt before unload, firmware variants).
  1416. self.on_finish_photo_moment = on_finish_photo_moment
  1417. # #2582: fired after a spool assignment (ams_filament_setting +
  1418. # extrusion_cali_sel) once the tray's telemetry either confirms the
  1419. # push landed or a timeout elapses without it. Receives
  1420. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  1421. # tell the user "loaded" vs "assignment didn't take" instead of the
  1422. # historic fire-and-forget silence that made the AMS/Studio hand-off
  1423. # feel random. See _check_assignment_verifications.
  1424. self.on_assignment_verified = on_assignment_verified
  1425. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  1426. # value is the desired end-state we just pushed plus a monotonic
  1427. # deadline. Populated by register_assignment_verification, drained by
  1428. # _check_assignment_verifications on every AMS push.
  1429. self._pending_assignments: dict[tuple[int, int], dict] = {}
  1430. # Per-AMS previous dry_time, used to detect the falling edge above.
  1431. # Seeded lazily as we observe each AMS unit.
  1432. self._previous_dry_times: dict[int, int] = {}
  1433. # Per-AMS monotonic stamp of the last time dry_time CHANGED value.
  1434. # A live cycle's countdown ticks once a minute; a command the firmware
  1435. # accepted but never actually started (observed on an H2D mid-print
  1436. # with two AMS-HT cycles already running: the third unit's timer sat
  1437. # frozen at its full duration) never ticks. dry_time > 0 with no tick
  1438. # for DRY_COUNTDOWN_STALL_SECONDS and no active dry_status phase is
  1439. # reported as dry_countdown_stalled so the UI can stop claiming an
  1440. # active cycle that is not running.
  1441. self._dry_time_changed_at: dict[int, float] = {}
  1442. # Per-AMS active-cycle target params (filament + temp) we sent on the
  1443. # last start. Bambu does not echo these back in the per-tick AMS push
  1444. # — only the dry_time countdown — so we cache what we sent to drive
  1445. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  1446. self._drying_targets: dict[int, dict[str, object]] = {}
  1447. # AMS ids we have sent a stop for and not yet seen end. A stop always
  1448. # ends a cycle far short of its duration, which on the telemetry alone
  1449. # is indistinguishable from the firmware abandoning it — so the cycle-end
  1450. # log would otherwise blame the printer for our own decision (#2770).
  1451. self._drying_stops_sent: set[int] = set()
  1452. # Per-AMS record of the cycle in progress: the highest dry_time seen,
  1453. # whether its first minute was observed, and the target we sent for it.
  1454. # The target is copied here when the countdown starts because a stop
  1455. # drops _drying_targets before the cycle ends (#2863).
  1456. self._dry_cycles: dict[int, dict[str, object]] = {}
  1457. # Stage numbers this printer has reported that STAGE_NAMES has no entry
  1458. # for, so each is reported once rather than on every transition into it.
  1459. self._unnamed_stages_seen: set[int] = set()
  1460. self.state = PrinterState()
  1461. self._client: mqtt.Client | None = None
  1462. self._loop: asyncio.AbstractEventLoop | None = None
  1463. self._previous_gcode_state: str | None = None
  1464. self._previous_gcode_file: str | None = None
  1465. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  1466. # #3485: the first state after startup was PAUSE with a print loaded,
  1467. # e.g. a printer in power-loss recovery when Bambuddy came back. Its
  1468. # PAUSE -> RUNNING is that print resuming, not a new one.
  1469. self._paused_at_startup: bool = False
  1470. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  1471. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  1472. # #1721: one-shot guard so the end-of-print stage-22 detector
  1473. # and the FINISH-state fallback don't both fire on the same
  1474. # print. Reset to False on every print start.
  1475. self._finish_photo_captured: bool = False
  1476. # #2702: one-shot re-request of the layer total. Armed at print start
  1477. # when the starting frame carried no `total_layer_num`, spent on the
  1478. # first layer advance that still has no denominator. Bambu firmware
  1479. # only re-sends *changed* fields, so a total we never received (or
  1480. # dropped) is only recoverable via a full pushall.
  1481. self._total_layers_refresh_armed: bool = False
  1482. # #2547 end-of-print telemetry probe state. `_armed` is cleared once the
  1483. # window has run for a print so a late FINISH re-send can't reopen it.
  1484. self._eop_probe_armed: bool = True
  1485. self._eop_probe_open: bool = False
  1486. self._eop_probe_frames: int = 0
  1487. self._eop_probe_last: dict = {}
  1488. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  1489. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  1490. # #3317: the layer the previous print ended on. Right after a print
  1491. # starts, the printer can send one frame that still carries it (H2S:
  1492. # `layer_num` 357 with `mc_percent` 0, then 0 a second later). Taken at
  1493. # face value, the 0 that follows saved 357 as this print's last layer,
  1494. # and a print failing at layer 0 was charged as finished. Frames with
  1495. # this value are ignored until the new print reports another layer.
  1496. self._stale_layer_num: int = 0
  1497. # The subtask_id minted for the most recent start_print() command. The
  1498. # printer echoes it back in status, but often not within the first few
  1499. # seconds — so on_print_start uses this as the id source when the
  1500. # printer hasn't reported it yet, letting queue/scheduled archives
  1501. # persist a restart-stable id from the moment they dispatch (#1485).
  1502. self.last_dispatch_subtask_id: str | None = None
  1503. # The printer's answer to the last print start it refused, as (result,
  1504. # reason); cleared when the next start is sent. The start watchdog
  1505. # reads it to stop waiting for a print that will not come.
  1506. self.last_start_refusal: tuple[str, str | None] | None = None
  1507. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  1508. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  1509. self._logging_enabled: bool = False
  1510. self._last_message_time: float = 0.0 # Track when we last received a message
  1511. # Count of report-topic messages received since the last (re)connect.
  1512. # Lets check_staleness() distinguish "printer never sent a status
  1513. # report" (typically a wrong / mis-cased serial) from a normal quiet
  1514. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  1515. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  1516. self._report_messages_since_connect: int = 0
  1517. self._zero_report_hint_logged: bool = False
  1518. # Set by mark_power_off() to the gcode_state held just before we
  1519. # optimistically forced the printer to "unknown" (#2629). Restored on
  1520. # the next inbound message, because message traffic proves the power
  1521. # was never actually cut. None whenever no power-off is presumed.
  1522. self._state_before_power_off: str | None = None
  1523. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  1524. # printer's pushes verbatim to slicers connected to a virtual printer).
  1525. # Handlers receive (topic, payload_bytes) before JSON parsing.
  1526. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  1527. self._disconnection_event: threading.Event | None = None
  1528. self._previous_ams_hash: str | None = None # Track AMS changes
  1529. # Track external-spool (vt_tray) identity changes separately: the AMS
  1530. # hash above covers only AMS units, so an external-spool-only filament
  1531. # swap would never re-trigger inventory reconciliation (#2575).
  1532. self._previous_vt_tray_hash: str | None = None
  1533. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  1534. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  1535. self._ams_version_cache: dict[int, dict[str, str]] = {}
  1536. # Track which (ams_id, field) warnings have already been emitted this connection
  1537. # so that missing-serial / missing-firmware warnings fire only once per connection.
  1538. self._ams_version_warned: set[tuple[int | str, str]] = set()
  1539. # K-profile command tracking. One entry per in-flight extrusion_cali_get,
  1540. # keyed by the sequence_id we sent, so two concurrent requests for
  1541. # different nozzle sizes can't steal each other's response (#1748).
  1542. # Value: {"nozzle": str, "event": asyncio.Event, "profiles": list | None}.
  1543. self._sequence_id: int = 0
  1544. self._pending_kprofile_requests: dict[str, dict] = {}
  1545. # The printer's calibration table, one bucket per nozzle diameter.
  1546. #
  1547. # An extrusion_cali_get response is the complete table for *one* nozzle
  1548. # size, and the printer answers whoever asks — including BambuStudio,
  1549. # whose queries land on the same report topic we subscribe to. Assigning
  1550. # each response straight to state.kprofiles therefore let any single
  1551. # answer stand for the whole printer: a GitHub backup probing
  1552. # 0.2/0.4/0.6/0.8 in turn finished on 0.8, which holds no profiles on a
  1553. # 0.4+0.6 machine, and left the list empty until something refilled it.
  1554. # Measured on the maintainer's H2 on 2026-08-25, and visible on the AMS
  1555. # card because H2-series trays carry no `k` of their own — the slot's
  1556. # K value is resolved from cali_idx against exactly this list.
  1557. #
  1558. # Keyed by diameter so a response only ever replaces the bucket it
  1559. # actually describes; state.kprofiles is then the union across buckets.
  1560. # An empty answer for a nozzle the printer doesn't have empties that
  1561. # bucket alone.
  1562. self._kprofiles_by_nozzle: dict[str, list] = {}
  1563. # Acks for K-profile *writes* (extrusion_cali_set / extrusion_cali_del),
  1564. # keyed by the sequence_id we sent. The printer echoes it back, measured
  1565. # on both an X1C and an H2D (#2718). Filled by the MQTT thread, drained
  1566. # by await_cali_ack.
  1567. self._pending_cali_acks: dict[str, dict | None] = {}
  1568. # Objects sent in skip_objects that the printer's s_obj list has not
  1569. # shown yet: object id -> when it was sent. And the ids of each
  1570. # command by its sequence_id, for its answer.
  1571. self._unconfirmed_skips: dict[int, float] = {}
  1572. self._skip_commands: dict[str, list[int]] = {}
  1573. # Acks for RFID re-reads (ams_get_rfid, and the M620 R gcode_line
  1574. # fallback), keyed the same way. Drained by ams_refresh_tray (#3206).
  1575. self._pending_rfid_acks: dict[str, dict | None] = {}
  1576. # Identifies the one project_file *we* dispatched, so its echo on the
  1577. # topic can be told apart from a slicer's. One-shot: consumed by the
  1578. # first frame that matches. See _project_file_key.
  1579. self._own_project_file_key: str | None = None
  1580. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  1581. # Key: module_name, Value: timestamp when command was sent
  1582. self._xcam_hold_start: dict[str, float] = {}
  1583. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  1584. # True once the printer has sent `cfg`; from then on AMS Filament Backup
  1585. # is read from cfg only, never from home_flag (#3259).
  1586. self._backup_cfg_seen: bool = False
  1587. # True once a full status report arrived without `cfg`; from then on
  1588. # home_flag bit 10 is read from every status frame (#3259).
  1589. self._backup_home_flag_trusted: bool = False
  1590. # Whether the frame being handled carried the nozzles' snow: only then
  1591. # may snow overrule the slot the same frame reports as tray_now.
  1592. self._snow_in_frame = False
  1593. # The captured ams_mapping lives on the state (print_ams_mapping), so
  1594. # the status the card reads carries it; see _captured_ams_mapping.
  1595. # The destination of the dispatch it was captured from.
  1596. self._captured_mapping_url: str | None = None
  1597. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  1598. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  1599. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  1600. self._has_a2l_am_unit: bool = False
  1601. # Rack AMS units already logged as detected (once per unit).
  1602. self._rack_ams_logged: set[int] = set()
  1603. self._tray_layout_key: tuple | None = None
  1604. self._tray_layout = TrayLayout()
  1605. # Why the last connection attempt was refused by the printer, or None
  1606. # when we have never seen a CONNACK failure since the last success.
  1607. # Without this a rejected access code was completely invisible: paho
  1608. # reports the follow-up disconnect as the generic "Unspecified error"
  1609. # and `_on_connect`'s failure branch used to log nothing at all, so a
  1610. # printer stuck in a reconnect loop looked identical whether it was
  1611. # powered off, on the wrong IP, or refusing our credentials (#2698).
  1612. # One of the CONNECT_ERROR_* slugs; the paired name is the paho reason
  1613. # string, kept for the log line only.
  1614. self.last_connect_error: str | None = None
  1615. self.last_connect_error_name: str | None = None
  1616. # Request topic subscription tracking
  1617. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  1618. # topic by killing the TCP connection. We detect this and gracefully degrade.
  1619. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  1620. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  1621. self._request_topic_sub_mid: int | None = None
  1622. self._request_topic_sub_time: float = 0.0
  1623. self._request_topic_confirmed: bool = False
  1624. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  1625. # we probe by sending an ams_filament_setting and checking the response.
  1626. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  1627. self._dev_mode_probed: bool = False
  1628. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  1629. self._dev_mode_probe_seq: str | None = None
  1630. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  1631. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  1632. # True while developer_mode=False came from HMS_MQTT_VERIFY_FAILED rather
  1633. # than from the probe or the "fun" bit. The HMS is a latch, not a level:
  1634. # the printer reports it until the fault clears, so when a later hms[]
  1635. # arrives without it (user enabled Developer Mode and restarted the
  1636. # printer) we drop back to "unknown" and let the probe re-run instead of
  1637. # leaving a permanently-wrong False behind (#2732).
  1638. self._dev_mode_from_hms: bool = False
  1639. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  1640. # Set when check_staleness() force-closes the socket to trigger reconnect.
  1641. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  1642. self._stale_reconnecting: bool = False
  1643. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  1644. # when the frontend polls status faster than paho can reconnect.
  1645. self._last_stale_reconnect: float = 0.0
  1646. # Zombie session detection via ams_filament_setting response tracking (#887).
  1647. # The dev-mode probe only runs on first connect; this catches zombie sessions
  1648. # that develop later (telemetry flows but publishes silently fail).
  1649. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  1650. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  1651. @property
  1652. def topic_subscribe(self) -> str:
  1653. return f"device/{self.serial_number}/report"
  1654. @property
  1655. def topic_publish(self) -> str:
  1656. return f"device/{self.serial_number}/request"
  1657. @property
  1658. def report_messages_since_connect(self) -> int:
  1659. """Count of report-topic messages received since the latest (re)connect.
  1660. Exposed for the connection diagnostic so it can distinguish "MQTT
  1661. broker accepted us but the printer never published" (typically a
  1662. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  1663. bridge that happens to be idle right now. Zero immediately after a
  1664. fresh connect is normal; zero after a full status push cycle is the
  1665. wrong-serial failure mode.
  1666. """
  1667. return self._report_messages_since_connect
  1668. # Maximum time (seconds) without a message before considering connection stale
  1669. STALE_TIMEOUT = 60.0
  1670. def is_stale(self) -> bool:
  1671. """Check if the connection is stale (no messages for too long)."""
  1672. if self._last_message_time == 0:
  1673. return False # Never received a message yet
  1674. time_since_last = time.time() - self._last_message_time
  1675. return time_since_last > self.STALE_TIMEOUT
  1676. def mark_power_off(self) -> bool:
  1677. """Presume the printer lost power (smart plug switched off).
  1678. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  1679. The presumption is undone by ``_on_message`` if the printer keeps
  1680. talking — inbound traffic proves the power was never cut (#2629).
  1681. Returns True when the state was actually changed.
  1682. """
  1683. if not self.state.connected:
  1684. return False
  1685. previous = self.state.state
  1686. # Blank the state BEFORE recording what to restore. This runs on the
  1687. # event loop while _on_message runs on the paho thread, and the restore
  1688. # is a two-step (read saved state, compare against "unknown"). Writing
  1689. # "unknown" first means an interleaved message either sees no saved
  1690. # state yet (and skips, leaving the next message to restore) or sees a
  1691. # consistent pair — never a saved state paired with a live state it
  1692. # then discards, which would strand the printer on "unknown".
  1693. self.state.connected = False
  1694. self.state.state = "unknown"
  1695. # Only the first mark wins: a second call before any message arrives
  1696. # must not overwrite the real state with the "unknown" it just wrote.
  1697. # Nothing to restore if the state was already blank.
  1698. if self._state_before_power_off is None and previous not in ("", "unknown"):
  1699. self._state_before_power_off = previous
  1700. return True
  1701. def _restore_state_after_false_power_off(self) -> bool:
  1702. """Undo a presumed power-off once the printer proves it is alive.
  1703. ``connected`` self-heals on the next message, but ``state`` does not:
  1704. it is only rewritten when a payload carries ``gcode_state``, and the
  1705. steady-state ``push_status`` frames are partial. Without this the
  1706. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  1707. and the queue scheduler treats the printer as not idle the whole time
  1708. (#2629). Returns True when a state was restored.
  1709. """
  1710. previous = self._state_before_power_off
  1711. self._state_before_power_off = None
  1712. if previous is None or self.state.state != "unknown":
  1713. return False
  1714. logger.info(
  1715. "[%s] Printer still responding after presumed power-off — restoring state %s",
  1716. self.serial_number,
  1717. previous,
  1718. )
  1719. self.state.state = previous
  1720. return True
  1721. # Minimum seconds between stale reconnect attempts. Frontend polls
  1722. # status every few seconds — without a cooldown, each poll would
  1723. # force-close the socket before paho has time to reconnect.
  1724. STALE_RECONNECT_COOLDOWN = 30.0
  1725. def check_staleness(self) -> bool:
  1726. """Check staleness and update connected state if stale. Returns True if connected."""
  1727. if self.state.connected and self.is_stale():
  1728. # Don't force-close again if we already did recently — give paho
  1729. # time to reconnect and the printer time to send its first message.
  1730. now = time.time()
  1731. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  1732. return self.state.connected
  1733. logger.warning(
  1734. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  1735. )
  1736. # A connection that keeps going stale without ever receiving a
  1737. # status report is almost always a wrong or mis-cased serial
  1738. # number — the broker accepts the connection and the subscription
  1739. # regardless, but the printer publishes to device/<real-serial>/
  1740. # report, which is case-sensitive. Surface that once so the user
  1741. # has something actionable instead of an endless reconnect loop.
  1742. # Only meaningful once the *current* session has had time to receive
  1743. # something. _report_messages_since_connect is reset by _on_connect,
  1744. # so a reconnect that lands microseconds before this check leaves it
  1745. # at 0 for reasons that have nothing to do with the serial — which is
  1746. # how a healthy P1S ended up being told to go check its serial number
  1747. # 1 ms after reconnecting (#2732). Requiring STALE_TIMEOUT of silence
  1748. # on this session means the hint only fires when the printer really
  1749. # has published nothing to the topic we subscribed to.
  1750. # _connect_time of 0 means we have no timestamp to judge by (never went
  1751. # through _on_connect); fall back to the old unconditional behaviour
  1752. # rather than silently swallowing the hint.
  1753. session_too_young = self._connect_time > 0 and (time.monotonic() - self._connect_time) < self.STALE_TIMEOUT
  1754. if self._report_messages_since_connect == 0 and not session_too_young and not self._zero_report_hint_logged:
  1755. self._zero_report_hint_logged = True
  1756. logger.warning(
  1757. "[%s] Connected and subscribed, but the printer has sent zero "
  1758. "status reports. The most common cause is a wrong or mis-cased "
  1759. "serial number — the device/<serial>/report MQTT topic is "
  1760. "case-sensitive. Verify the serial number configured in Bambuddy "
  1761. "exactly matches the printer.",
  1762. self.serial_number,
  1763. )
  1764. self._last_stale_reconnect = now
  1765. self.state.connected = False
  1766. if self.on_state_change:
  1767. self.on_state_change(self.state)
  1768. # Route based on caller thread — see force_reconnect_stale_session.
  1769. # check_staleness is normally called from FastAPI handlers (async,
  1770. # gets the hard-reset path) but the dispatcher exists for safety.
  1771. self._stale_reconnecting = True
  1772. self._reset_client_for_reconnect()
  1773. return self.state.connected
  1774. def force_reconnect_stale_session(self, reason: str) -> None:
  1775. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  1776. # arriving but our publishes don't reach the printer.
  1777. #
  1778. # Two routing paths:
  1779. #
  1780. # Async-context callers (queue dispatch deadline)
  1781. # → full client teardown + fresh client_id. Wipes paho's client-side
  1782. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  1783. # `project_file` from the broken session would otherwise replay on
  1784. # reconnect, mixing stale commands into the next dispatch and
  1785. # triggering 0500_4003 SD R/W on the printer.
  1786. #
  1787. # Paho-network-thread callers (dev-mode probe and ams_filament_setting
  1788. # zombie detection, both inside `_update_state`)
  1789. # → socket-close fallback. There is no running loop on that thread to
  1790. # hand the rebuilt client, so close the socket and let paho's own
  1791. # loop detect the broken connection and auto-reconnect (same
  1792. # instance, same client_id). paho would re-send its old outbox on
  1793. # that reconnect; _on_connect empties it first (#3454).
  1794. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  1795. self._stale_reconnecting = True
  1796. self.state.connected = False
  1797. if self.on_state_change:
  1798. self.on_state_change(self.state)
  1799. self._reset_client_for_reconnect()
  1800. def _reset_client_for_reconnect(self) -> None:
  1801. """Route between hard-reset and socket-close based on caller thread.
  1802. Hard-reset (preferred) rebuilds the client, and the rebuild needs a
  1803. running loop to hand to ``connect()``. ``asyncio.get_running_loop()``
  1804. answers that and identifies the caller in one go — paho's callback
  1805. thread has no loop; every legitimate hard-reset caller (FastAPI
  1806. handlers, background async tasks) does."""
  1807. try:
  1808. loop = asyncio.get_running_loop()
  1809. except RuntimeError:
  1810. loop = None
  1811. if loop is not None:
  1812. self._loop = loop
  1813. self._hard_reset_client()
  1814. else:
  1815. self._socket_close_for_reconnect()
  1816. def _hard_reset_client(self) -> None:
  1817. """Tear down the paho client entirely and rebuild it with a fresh
  1818. client_id, so the broker drops the old session and paho's local
  1819. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  1820. Caller is responsible for setting ``_stale_reconnecting`` and
  1821. broadcasting the disconnected state.
  1822. Returns as fast as it can build a client: the old one's teardown is
  1823. handed off rather than waited on, because waiting on it is what
  1824. stopped the event loop in #3068. See ``retire_paho_client``."""
  1825. old_client = self._client
  1826. self._client = None
  1827. if old_client is not None:
  1828. retire_paho_client(old_client, self.serial_number)
  1829. # Skip reconnect if no asyncio loop is available (test environment or
  1830. # pre-init). The next initial connect() call from PrinterManager will
  1831. # set up the client fresh.
  1832. if self._loop is None:
  1833. return
  1834. try:
  1835. self.connect(loop=self._loop)
  1836. except Exception as e:
  1837. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  1838. def _socket_close_for_reconnect(self) -> None:
  1839. """Close the underlying socket so paho's loop thread detects the
  1840. broken connection and triggers auto-reconnect on the SAME client
  1841. instance. Safe to call from paho's own network thread (the loop
  1842. polls the socket on every iteration and handles a closed socket
  1843. gracefully). Used as a fallback when hard-reset isn't safe. The old
  1844. outbox is not re-sent: _on_connect empties it first (#3454)."""
  1845. if self._client:
  1846. try:
  1847. sock = self._client.socket()
  1848. if sock:
  1849. sock.close()
  1850. except Exception:
  1851. pass
  1852. def _drop_previous_connection_commands(self, client) -> None:
  1853. """Forget every command queued on an earlier connection (#3454).
  1854. Called first in on_connect, which paho runs before it re-sends its
  1855. old outbox. Makes every printer command at most once per connection;
  1856. a command lost in the seconds before a drop is clicked again."""
  1857. dropped = discard_queued_publishes(client)
  1858. if dropped is None:
  1859. logger.warning(
  1860. "[%s] Cannot clear paho's outbox on reconnect (paho internals changed); "
  1861. "commands from the previous connection may be sent again",
  1862. self.serial_number,
  1863. )
  1864. elif dropped:
  1865. logger.info(
  1866. "[%s] Dropped %d command(s) queued on the previous MQTT connection",
  1867. self.serial_number,
  1868. dropped,
  1869. )
  1870. def _on_connect(self, client, userdata, flags, rc, properties=None):
  1871. if rc == 0:
  1872. # First, before anything here publishes on the new connection.
  1873. self._drop_previous_connection_commands(client)
  1874. self.state.connected = True
  1875. self.last_connect_error = None
  1876. self.last_connect_error_name = None
  1877. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  1878. # A dropped-and-restored MQTT session means the presumed power-off was
  1879. # real (or at least that the printer restarted): there is nothing
  1880. # legitimate left to restore, and the printer will send a full status
  1881. # push shortly. Dropping the saved state keeps a stale one from being
  1882. # broadcast ahead of the first real report (#2629, #1679).
  1883. self._state_before_power_off = None
  1884. # Reset per-connection warning state so warnings fire once per (re)connection
  1885. self._ams_version_warned = set()
  1886. # Preserve cached developer_mode across auto-reconnects to avoid
  1887. # re-probing on every reconnect. The probe (ams_filament_setting to
  1888. # ext slot) can destabilize some firmware MQTT brokers, causing a
  1889. # reconnect → probe → disconnect feedback loop (#887). Only probe
  1890. # once when developer_mode is truly unknown (first connect).
  1891. # Reset probe tracking so stale timeout state doesn't carry over.
  1892. self._dev_mode_probed = False
  1893. self._dev_mode_needs_probe = False
  1894. self._dev_mode_probe_seq = None
  1895. self._dev_mode_probe_time = 0.0
  1896. self._dev_mode_probe_failures = 0
  1897. self._connect_time = time.monotonic()
  1898. self._report_messages_since_connect = 0
  1899. self._last_ams_cmd_time = 0.0
  1900. self._ams_cmd_unanswered = 0
  1901. # Drop any assignment verifications that were mid-flight before the
  1902. # reconnect — their deadlines are stale and the tray state we would
  1903. # compare against is about to be re-pushed from scratch (#2582).
  1904. # Dropping is silent (no failure event) on purpose.
  1905. self._pending_assignments.clear()
  1906. client.subscribe(self.topic_subscribe)
  1907. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  1908. if self._request_topic_supported:
  1909. result, mid = client.subscribe(self.topic_publish)
  1910. if result == mqtt.MQTT_ERR_SUCCESS:
  1911. self._request_topic_sub_mid = mid
  1912. self._request_topic_sub_time = time.time()
  1913. self._request_topic_confirmed = False
  1914. else:
  1915. logger.warning(
  1916. "[%s] Failed to send request topic subscription",
  1917. self.serial_number,
  1918. )
  1919. self._request_topic_supported = False
  1920. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1921. # Request full status update (includes nozzle info in push_status response)
  1922. self._request_push_all()
  1923. # Request firmware version info
  1924. self._request_version()
  1925. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  1926. # The correct nozzle data comes from push_status.
  1927. # Prime K-profile request (Bambu printers often ignore first request)
  1928. self._prime_kprofile_request()
  1929. # Immediately broadcast connection state change
  1930. if self.on_state_change:
  1931. self.on_state_change(self.state)
  1932. else:
  1933. self.state.connected = False
  1934. self._record_connect_refusal(rc)
  1935. def _record_connect_refusal(self, rc) -> None:
  1936. """Log and remember why the printer refused the MQTT connection.
  1937. The failure branch of ``_on_connect`` used to be a bare
  1938. ``connected = False``, which threw away the only signal that says
  1939. *why* a printer never comes online. The user-visible result was a
  1940. 30-second reconnect loop logging nothing but paho's generic
  1941. ``MQTT disconnected: rc=Unspecified error`` — indistinguishable from a
  1942. powered-off printer, so "my printer won't print" reports could not be
  1943. triaged without a round trip (#2698).
  1944. Never logs the access code itself; the code is the likely culprit but
  1945. printing it would put a credential in every support bundle.
  1946. """
  1947. code = getattr(rc, "value", rc)
  1948. name = rc.getName() if hasattr(rc, "getName") else str(rc)
  1949. self.last_connect_error_name = name
  1950. if isinstance(code, int) and code in _CONNACK_AUTH_REJECTED:
  1951. self.last_connect_error = CONNECT_ERROR_AUTH_REJECTED
  1952. logger.warning(
  1953. "[%s] MQTT connection refused by the printer: %s (code %s). The access code "
  1954. "or serial number is wrong — the access code changes every time LAN Only or "
  1955. "Developer Mode is toggled, so re-read it from the printer's screen.",
  1956. self.serial_number,
  1957. name,
  1958. code,
  1959. )
  1960. else:
  1961. self.last_connect_error = CONNECT_ERROR_REFUSED
  1962. logger.warning(
  1963. "[%s] MQTT connection refused by the printer: %s (code %s).",
  1964. self.serial_number,
  1965. name,
  1966. code,
  1967. )
  1968. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  1969. """Handle SUBACK responses to detect request topic subscription rejection."""
  1970. if mid == self._request_topic_sub_mid:
  1971. for rc in reason_code_list:
  1972. if rc.is_failure:
  1973. logger.warning(
  1974. "[%s] Request topic subscription rejected (code=%d: %s). "
  1975. "ams_mapping capture from slicer-initiated prints unavailable.",
  1976. self.serial_number,
  1977. rc.value,
  1978. rc.getName(),
  1979. )
  1980. self._request_topic_supported = False
  1981. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1982. else:
  1983. logger.info(
  1984. "[%s] Request topic subscription accepted. "
  1985. "ams_mapping capture enabled for slicer-initiated prints.",
  1986. self.serial_number,
  1987. )
  1988. self._request_topic_confirmed = True
  1989. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  1990. BambuMQTTClient._request_topic_probe_failures.pop(self.serial_number, None)
  1991. self._request_topic_sub_mid = None
  1992. self._request_topic_sub_time = 0.0
  1993. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  1994. # Always unblock disconnect() callers, regardless of whether we suppress
  1995. # the state broadcast below. disconnect() sets _disconnection_event and
  1996. # waits on it — every callback path must fire it.
  1997. if self._disconnection_event:
  1998. self._disconnection_event.set()
  1999. # If we intentionally closed the socket for stale reconnect, don't broadcast
  2000. # another state change — check_staleness() already set connected=False and
  2001. # notified the UI. Just log and let paho auto-reconnect.
  2002. if self._stale_reconnecting:
  2003. logger.info(
  2004. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  2005. self.serial_number,
  2006. rc,
  2007. )
  2008. return
  2009. # Ignore spurious disconnect callbacks if we've received a message recently
  2010. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  2011. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  2012. # — only suppress when rc indicates a clean/normal disconnect.
  2013. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  2014. time_since_last_message = time.time() - self._last_message_time
  2015. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  2016. logger.debug(
  2017. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  2018. )
  2019. return
  2020. # Carry the last CONNACK refusal into the disconnect line. paho reports
  2021. # the drop that follows a refused CONNACK as "Unspecified error", so on
  2022. # its own this line says nothing useful about a printer that is looping
  2023. # on bad credentials — and this is the line that fills a support bundle
  2024. # (#2698).
  2025. if self.last_connect_error:
  2026. logger.warning(
  2027. "[%s] MQTT disconnected: rc=%s, flags=%s (last connection attempt was refused: %s)",
  2028. self.serial_number,
  2029. rc,
  2030. disconnect_flags,
  2031. self.last_connect_error_name,
  2032. )
  2033. else:
  2034. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  2035. # Detect if request topic subscription caused the disconnect.
  2036. # If we just subscribed and got disconnected before any SUBACK confirmation,
  2037. # the broker likely killed the connection due to the unauthorized subscription.
  2038. if (
  2039. self._request_topic_sub_time > 0
  2040. and not self._request_topic_confirmed
  2041. and time.time() - self._request_topic_sub_time < 10.0
  2042. # A disconnect we asked for says nothing about the subscription.
  2043. and self._disconnection_event is None
  2044. ):
  2045. failures = BambuMQTTClient._request_topic_probe_failures.get(self.serial_number, 0) + 1
  2046. BambuMQTTClient._request_topic_probe_failures[self.serial_number] = failures
  2047. if failures >= BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT:
  2048. logger.warning(
  2049. "[%s] Disconnected shortly after request topic subscription %d times. "
  2050. "Disabling request topic for this printer — ams_mapping capture from "
  2051. "slicer-initiated prints is unavailable, and their filament will be "
  2052. "attributed from the printer's own tray reporting instead.",
  2053. self.serial_number,
  2054. failures,
  2055. )
  2056. self._request_topic_supported = False
  2057. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  2058. else:
  2059. logger.info(
  2060. "[%s] Disconnected shortly after request topic subscription (%d/%d). "
  2061. "Retrying it on the next connection before giving up.",
  2062. self.serial_number,
  2063. failures,
  2064. BambuMQTTClient._REQUEST_TOPIC_PROBE_LIMIT,
  2065. )
  2066. self._request_topic_sub_mid = None
  2067. self._request_topic_sub_time = 0.0
  2068. self.state.connected = False
  2069. if self.on_state_change:
  2070. self.on_state_change(self.state)
  2071. def _log_message(self, topic: str, direction: str, raw: str) -> None:
  2072. """Record a message for the MQTT Debug log, as it arrived.
  2073. Parsed again from the raw text rather than shared with the handlers:
  2074. processing keeps the payload's "print" dict as the new raw_data and
  2075. writes Bambuddy's merged AMS list and other state into it, so a shared
  2076. dict showed Bambuddy's state instead of what the printer sent (#3356).
  2077. """
  2078. self._message_log.append(
  2079. MQTTLogEntry(
  2080. timestamp=datetime.now(timezone.utc).isoformat(),
  2081. topic=topic,
  2082. direction=direction,
  2083. payload=json.loads(raw),
  2084. )
  2085. )
  2086. def _on_message(self, client, userdata, msg):
  2087. for handler in self._raw_message_handlers:
  2088. try:
  2089. handler(msg.topic, msg.payload)
  2090. except Exception:
  2091. logger.exception(
  2092. "[%s] raw-message handler crashed for topic=%s",
  2093. self.serial_number,
  2094. msg.topic,
  2095. )
  2096. try:
  2097. try:
  2098. raw = msg.payload.decode()
  2099. except UnicodeDecodeError:
  2100. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  2101. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  2102. raw = msg.payload.decode(errors="replace")
  2103. logger.warning(
  2104. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  2105. self.serial_number,
  2106. msg.topic,
  2107. len(msg.payload),
  2108. )
  2109. payload = json.loads(raw)
  2110. # Track last message time - receiving a message proves we're connected
  2111. self._last_message_time = time.time()
  2112. self.state.connected = True
  2113. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  2114. if msg.topic == self.topic_publish:
  2115. # Record it before returning. This topic carries every command
  2116. # travelling *to* the printer, including the ones Bambu Studio
  2117. # sends, and it used to be the one thing an MQTT capture could
  2118. # never show -- which is why "what does Studio put in the drying
  2119. # command?" had no answer from a user's log (#2774). Filed as
  2120. # "out" so the direction filter groups it with our own commands
  2121. # rather than with printer telemetry; anything we send
  2122. # lands twice, once on publish and once on the
  2123. # broker's echo, and the pair is itself evidence the command
  2124. # reached the broker.
  2125. if self._logging_enabled:
  2126. self._log_message(msg.topic, "out", raw)
  2127. self._handle_request_message(payload)
  2128. return
  2129. # Count status reports per connection so check_staleness() can tell
  2130. # "printer never sent a report" apart from a mid-session quiet gap.
  2131. if msg.topic == self.topic_subscribe:
  2132. self._report_messages_since_connect += 1
  2133. # Only report-topic traffic proves the *printer* is alive — the
  2134. # request topic also carries slicer/Bambuddy commands.
  2135. if self._state_before_power_off is not None:
  2136. if self._restore_state_after_false_power_off() and self.on_state_change:
  2137. self.on_state_change(self.state)
  2138. # Log message if logging is enabled
  2139. if self._logging_enabled:
  2140. self._log_message(msg.topic, "in", raw)
  2141. self._process_message(payload)
  2142. except json.JSONDecodeError:
  2143. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  2144. @property
  2145. def _captured_ams_mapping(self):
  2146. """The ams_mapping captured from the current print's command.
  2147. Kept on the state so the status shows it (the slot pills, #1762): the
  2148. printer's own push almost never carries one.
  2149. """
  2150. return self.state.print_ams_mapping
  2151. @_captured_ams_mapping.setter
  2152. def _captured_ams_mapping(self, mapping) -> None:
  2153. self.state.print_ams_mapping = mapping
  2154. def _handle_request_message(self, data: dict) -> None:
  2155. """Intercept print commands on the request topic to capture ams_mapping."""
  2156. print_data = data.get("print", {})
  2157. if not isinstance(print_data, dict):
  2158. return
  2159. command = print_data.get("command", "")
  2160. if command == "project_file":
  2161. # Where the dispatcher put the sliced file. Captured for every
  2162. # project_file, ours included: we publish to this same topic and
  2163. # subscribe to it, so whoever dispatched last wins, which is exactly
  2164. # the print the archive lookup is about to go looking for (#2780).
  2165. url = print_data.get("url")
  2166. if isinstance(url, str) and url:
  2167. self.state.current_project_url = url
  2168. self.state.last_project_url = url
  2169. if "ams_mapping" in print_data:
  2170. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2171. self._captured_mapping_url = url if isinstance(url, str) else None
  2172. logger.info(
  2173. "[%s] Captured ams_mapping from print command: %s",
  2174. self.serial_number,
  2175. self._captured_ams_mapping,
  2176. )
  2177. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  2178. # slicer-launched project_file passes through the request topic,
  2179. # log the full payload so we can diff Studio's field set against
  2180. # ours.
  2181. #
  2182. # This used to read `sequence_id != "20000"`, on the belief that
  2183. # 20000 was ours alone. It is not: 20000 is the slicer convention
  2184. # Bambuddy adopted -- bind_server documents the slicer sending it
  2185. # during detect, and measured on the wire OrcaSlicer dispatched
  2186. # 20000 then 20001 while BambuStudio was on 20009/20010, both
  2187. # counting up from the same base. So the test swallowed whichever
  2188. # slicer dispatch happened to land on 20000, which on a fresh
  2189. # slicer start is the first one. Match our own dispatch instead.
  2190. if self._project_file_key(print_data) == self._own_project_file_key:
  2191. self._own_project_file_key = None
  2192. else:
  2193. logger.info(
  2194. "[%s] External project_file payload: %s",
  2195. self.serial_number,
  2196. json.dumps(print_data),
  2197. )
  2198. def _capture_report_project_file(self, print_data: dict) -> None:
  2199. """Read a print's destination off a ``project_file`` *response* (#1820).
  2200. ``_handle_request_message`` only ever sees the request topic, so a print
  2201. started from the printer's own touchscreen -- which publishes nothing --
  2202. left ``current_project_url`` at None, and the storage verdict fell
  2203. through to the ``sdcard`` fallback for the one case it was written for.
  2204. On an H2S that flag is True (its "card" is the internal eMMC), so the
  2205. verdict came back reachable and the ~110-connection sweep ran in full.
  2206. The printer does announce it: an unsolicited ``project_file`` response
  2207. on the report topic, ~2 s before ``gcode_state`` reaches PREPARE,
  2208. carrying ``file:///userdata/model/history/<name>.gcode.3mf``.
  2209. This also covers an install nobody had in view: some brokers refuse the
  2210. request-topic subscription, and on those no print of any kind has ever
  2211. populated the field.
  2212. Both kinds of ``project_file`` on this topic are read -- the printer's
  2213. echo of a dispatch and a screen start -- because both name the
  2214. destination in ``url``, which is the only thing the verdict wants. What
  2215. this must NOT do is reuse ``_handle_request_message``'s "External
  2216. project_file payload" diagnostic: our own dispatch is echoed on *both*
  2217. topics, the request-topic echo arrives first and clears
  2218. ``_own_project_file_key``, so by the time this frame lands the key is
  2219. already None and every Bambuddy-started print would log itself as
  2220. someone else's.
  2221. """
  2222. # Same shape as _handle_request_message: the frame is whatever the
  2223. # printer put on the wire, and this is the first thing to touch it.
  2224. if not isinstance(print_data, dict) or print_data.get("command") != "project_file":
  2225. return
  2226. # A refused dispatch names a file that was never written. Acting on it
  2227. # would pin an archive on a destination nothing ever went to. Logged:
  2228. # nothing else says the printer refused a print it was sent.
  2229. result = str(print_data.get("result") or "")
  2230. if result.upper() != "SUCCESS":
  2231. logger.info(
  2232. "[%s] Printer refused a print start (project_file): result=%s reason=%s url=%s",
  2233. self.serial_number,
  2234. result,
  2235. print_data.get("reason"),
  2236. print_data.get("url"),
  2237. )
  2238. self.last_start_refusal = (result, print_data.get("reason"))
  2239. return
  2240. url = print_data.get("url")
  2241. if not isinstance(url, str) or not url:
  2242. return
  2243. if self.state.current_project_url != url:
  2244. logger.info(
  2245. "[%s] Print destination from the report topic: %s",
  2246. self.serial_number,
  2247. url,
  2248. )
  2249. self.state.current_project_url = url
  2250. self.state.last_project_url = url
  2251. # On a screen start this frame is the only place the mapping appears --
  2252. # no slicer ever sent one. Fill a gap only: when the request topic
  2253. # already captured this print's mapping that copy is the slicer's own,
  2254. # and the echo can arrive without the field at all. A mapping captured
  2255. # for another destination is from a dispatch that never ran (refused,
  2256. # or cancelled before it started, so no completion cleared it).
  2257. stale = self._captured_ams_mapping is not None and self._captured_mapping_url != url
  2258. if (self._captured_ams_mapping is None or stale) and isinstance(print_data.get("ams_mapping"), list):
  2259. self._captured_ams_mapping = self._resolve_captured_mapping(print_data)
  2260. self._captured_mapping_url = url
  2261. logger.info(
  2262. "[%s] Captured ams_mapping from print response: %s",
  2263. self.serial_number,
  2264. self._captured_ams_mapping,
  2265. )
  2266. def _resolve_captured_mapping(self, print_data: dict) -> object:
  2267. """The ``ams_mapping`` of a project_file, with external spools resolved
  2268. from its ``ams_mapping2`` (#3166)."""
  2269. from backend.app.utils.printer_models import is_dual_nozzle_model
  2270. return resolve_external_spools_in_mapping(
  2271. print_data.get("ams_mapping"),
  2272. print_data.get("ams_mapping2"),
  2273. self._is_dual_nozzle or is_dual_nozzle_model(self.model),
  2274. self.tray_layout,
  2275. )
  2276. @staticmethod
  2277. def _project_file_key(print_data: dict) -> str:
  2278. """Identity of a project_file dispatch, for telling ours from a slicer's.
  2279. Sequence id alone cannot do it -- every slicer counts up from the same
  2280. 20000 -- so this also carries the file and its destination, which differ
  2281. between any two real dispatches.
  2282. """
  2283. return "|".join(str(print_data.get(field, "")) for field in ("sequence_id", "file", "url", "subtask_name"))
  2284. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  2285. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  2286. The state dumps in the push_status handler fire whenever their field is
  2287. *present* in the frame — and a full push_status carries every field, so
  2288. they fire on every frame regardless of whether anything changed. Several
  2289. even say "updated" or "changes" in their own comment while doing nothing
  2290. of the sort.
  2291. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  2292. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  2293. minutes: the reporter enabled debug logging as asked and the support
  2294. bundle came back holding under five minutes of history, almost none of it
  2295. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  2296. these dumps.
  2297. Deduplicating on the value keeps every transition — which is the only part
  2298. anyone reads these lines for — and drops the steady-state repetition.
  2299. ``value`` must capture everything interpolated into ``msg``, or a change
  2300. will be swallowed; pass a tuple when the message renders several fields.
  2301. """
  2302. if not logger.isEnabledFor(logging.DEBUG):
  2303. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  2304. # and these clients outlive the toggle. Letting INFO-level frames warm
  2305. # the cache would be self-defeating: the operator turns debug on
  2306. # precisely to see the printer's current state, and a cache already
  2307. # holding every steady-state value would suppress that baseline until
  2308. # something happened to change. On an idle printer the bundle would
  2309. # come back with none of these lines at all.
  2310. #
  2311. # So while debug is off we record nothing and drop whatever we had.
  2312. # Every enable then starts cold and dumps a full baseline on the next
  2313. # frame, exactly as it did before this method existed.
  2314. self._debug_last.clear()
  2315. return
  2316. if self._debug_last.get(key) == value:
  2317. return
  2318. self._debug_last[key] = value
  2319. logger.debug(msg, *args)
  2320. def _process_message(self, payload: dict):
  2321. """Process incoming MQTT message from printer."""
  2322. # Handle top-level AMS data (comes outside of "print" key)
  2323. # Wrap in try/except to prevent breaking the MQTT connection
  2324. if "ams" in payload:
  2325. try:
  2326. self._snow_in_frame = False # a bare AMS frame carries no extruder data
  2327. self._handle_ams_data(payload["ams"])
  2328. except Exception as e:
  2329. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  2330. # Handle xcam data (camera settings and AI detection) at top level
  2331. if "xcam" in payload:
  2332. xcam_data = payload["xcam"]
  2333. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  2334. self._parse_xcam_data(xcam_data)
  2335. # Fire state change callback for top-level xcam (not nested in "print")
  2336. if "print" not in payload and self.on_state_change:
  2337. self.on_state_change(self.state)
  2338. # Handle system responses (accessories info, etc.)
  2339. if "system" in payload:
  2340. system_data = payload["system"]
  2341. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  2342. self._handle_system_response(system_data)
  2343. # Handle info responses (firmware version info from get_version command)
  2344. if "info" in payload:
  2345. info_data = payload["info"]
  2346. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  2347. self._handle_version_info(info_data)
  2348. # Parse WiFi signal at top level (some printers send it here)
  2349. if "wifi_signal" in payload:
  2350. wifi_signal = payload["wifi_signal"]
  2351. if isinstance(wifi_signal, (int, float)):
  2352. self.state.wifi_signal = int(wifi_signal)
  2353. elif isinstance(wifi_signal, str):
  2354. try:
  2355. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2356. except ValueError:
  2357. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2358. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  2359. from backend.app.utils.printer_models import has_ethernet
  2360. if has_ethernet(self.model):
  2361. self.state.wired_network = self.state.wifi_signal == -90
  2362. # Parse developer LAN mode from top-level "fun" field
  2363. # Some firmware versions send "fun" at the top level, others inside "print"
  2364. if "fun" in payload:
  2365. try:
  2366. fun_val = payload["fun"]
  2367. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2368. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2369. except (ValueError, TypeError):
  2370. pass
  2371. if "print" in payload:
  2372. print_data = payload["print"]
  2373. # Before anything reads the state: this is where a touchscreen-
  2374. # started print announces where its file lives, and the print-start
  2375. # handler asks ~2 s later (#1820).
  2376. self._capture_report_project_file(print_data)
  2377. # Check if xcam is nested inside print data
  2378. if "xcam" in print_data:
  2379. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  2380. self._parse_xcam_data(print_data["xcam"])
  2381. # Log when we see gcode_state changes
  2382. if "gcode_state" in print_data:
  2383. logger.debug(
  2384. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  2385. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  2386. )
  2387. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  2388. # new-protocol printers. Verified against OrcaSlicer's
  2389. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  2390. # and live H2D ON/OFF capture 2026-06-20.
  2391. #
  2392. # Families without cfg (P1S, P1P, A1, A1 Mini) carry it in home_flag
  2393. # bit 10 (#3259). Trusted once a full status report (the same
  2394. # >30-key test as the developer-mode probe) arrived without cfg;
  2395. # from then on every status frame that carries home_flag is read,
  2396. # so a toggle in the slicer shows up without a Force Refresh (P1S
  2397. # capture: each toggle came in a 4-6 key update frame). Before
  2398. # that nothing is read from small frames, so a cfg printer can't
  2399. # be misread from a frame that arrives ahead of its first cfg.
  2400. # Printers that send cfg keep reading it alone.
  2401. #
  2402. # Hold-timer guard: when the user just toggled via the badge, the
  2403. # next 1-2 push_status frames may still carry the printer's OLD cfg
  2404. # for ~3 s before the firmware reflects the change. Without this
  2405. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  2406. # Only from a status frame: a project_file ack echoes our own
  2407. # `"cfg": "0"` back, which read as "printer says backup is OFF" and
  2408. # stuck on every family that doesn't repeat `cfg` in its periodic
  2409. # frames — P1S, A1, A1 Mini, A2L (#3040).
  2410. new_backup = None
  2411. if is_printer_status_frame(print_data):
  2412. if "cfg" in print_data:
  2413. self._backup_cfg_seen = True
  2414. new_backup = parse_ams_filament_backup_from_cfg(print_data["cfg"])
  2415. elif not self._backup_cfg_seen:
  2416. if len(print_data) > 30:
  2417. self._backup_home_flag_trusted = True
  2418. if self._backup_home_flag_trusted:
  2419. new_backup = parse_ams_filament_backup_from_home_flag(print_data.get("home_flag"))
  2420. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  2421. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  2422. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  2423. logger.debug(
  2424. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  2425. self.serial_number,
  2426. time.time() - hold_start,
  2427. )
  2428. else:
  2429. logger.info(
  2430. "[%s] AMS Filament Backup: %s",
  2431. self.serial_number,
  2432. "ON" if new_backup else "OFF",
  2433. )
  2434. self.state.ams_filament_backup = new_backup
  2435. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  2436. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  2437. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  2438. if not self._is_dual_nozzle and "device" in print_data:
  2439. dev = print_data.get("device")
  2440. if isinstance(dev, dict):
  2441. ext_info = dev.get("extruder", {}).get("info", [])
  2442. if isinstance(ext_info, list) and len(ext_info) >= 2:
  2443. self._is_dual_nozzle = True
  2444. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  2445. # Must run before _handle_ams_data: the per-AMS inlet binding is read
  2446. # out of the AMS info bits, but only means anything once we know a
  2447. # switch is installed. Parsing them the other way round would lose
  2448. # the binding on every frame where the two arrive together.
  2449. self._parse_fila_switch(print_data)
  2450. # Before _handle_ams_data too: an H2D's tray_now is a bare slot that
  2451. # this frame's extruder data places (which nozzle, which AMS).
  2452. self._snow_in_frame = self._parse_extruder_position(print_data)
  2453. self._parse_extruder_slots(print_data)
  2454. # Handle AMS data that comes inside print key
  2455. if "ams" in print_data:
  2456. try:
  2457. self._handle_ams_data(print_data["ams"])
  2458. except Exception as e:
  2459. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  2460. # Handle vir_slot (H2-series external spool data) — list of external trays
  2461. # Process vir_slot FIRST so it takes priority over vt_tray
  2462. if "vir_slot" in print_data:
  2463. vir_slot = print_data["vir_slot"]
  2464. if isinstance(vir_slot, list) and vir_slot:
  2465. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  2466. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  2467. # Remap id=255→254 for single-slot printers so active detection works.
  2468. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  2469. # A nozzle-rack printer (H3C) reports one input per hotend,
  2470. # 247-255, kept as reported.
  2471. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  2472. vir_slot[0]["id"] = "254"
  2473. self.state.raw_data["vt_tray"] = vir_slot
  2474. # Handle vt_tray (virtual tray / external spool) data
  2475. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  2476. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  2477. # which would overwrite the correct multi-slot vir_slot data)
  2478. if "vt_tray" in print_data and "vir_slot" not in print_data:
  2479. vt_tray = print_data["vt_tray"]
  2480. existing = self.state.raw_data.get("vt_tray")
  2481. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  2482. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  2483. pass # Keep the vir_slot data
  2484. else:
  2485. if isinstance(vt_tray, dict):
  2486. vt_tray = [vt_tray]
  2487. self.state.raw_data["vt_tray"] = vt_tray
  2488. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  2489. # units, and _handle_ams_data runs before this block — so a change
  2490. # to the external spool alone (e.g. swapping generic TPU for generic
  2491. # ABS on the printer) never re-triggers on_ams_change, leaving a
  2492. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  2493. # external-spool identity changes here and fire the same callback.
  2494. self._maybe_trigger_external_spool_change()
  2495. # Parse ams_status directly from print data (NOT from print.ams)
  2496. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  2497. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  2498. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  2499. if "ams_status" in print_data:
  2500. raw_ams_status = print_data["ams_status"]
  2501. if isinstance(raw_ams_status, str):
  2502. try:
  2503. self.state.ams_status = int(raw_ams_status)
  2504. except ValueError:
  2505. self.state.ams_status = 0
  2506. else:
  2507. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  2508. # Compute main and sub status
  2509. self.state.ams_status_sub = self.state.ams_status & 0xFF
  2510. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  2511. # Log when ams_status changes (for filament change tracking debug)
  2512. self._debug_on_change(
  2513. "ams_status:print",
  2514. self.state.ams_status,
  2515. "[%s] ams_status: %s (main=%s, sub=%s)",
  2516. self.serial_number,
  2517. self.state.ams_status,
  2518. self.state.ams_status_main,
  2519. self.state.ams_status_sub,
  2520. )
  2521. # Check for command responses
  2522. if "command" in print_data:
  2523. cmd = print_data.get("command")
  2524. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  2525. if cmd in ("extrusion_cali_set", "extrusion_cali_del"):
  2526. # INFO, not debug: this is the printer's verdict on a write
  2527. # the user just made, and it was invisible in support
  2528. # bundles for as long as it sat at DEBUG (#2718). Same
  2529. # reasoning as ams_filament_drying below.
  2530. logger.info(
  2531. "[%s] %s response: result=%s reason=%s seq=%s",
  2532. self.serial_number,
  2533. cmd,
  2534. print_data.get("result"),
  2535. print_data.get("reason", ""),
  2536. print_data.get("sequence_id"),
  2537. )
  2538. logger.debug("[%s] %s full response: %s", self.serial_number, cmd, print_data)
  2539. ack_seq = str(print_data.get("sequence_id", ""))
  2540. if ack_seq in self._pending_cali_acks:
  2541. self._pending_cali_acks[ack_seq] = print_data
  2542. elif cmd == "skip_objects":
  2543. self._handle_skip_objects_answer(print_data)
  2544. elif cmd in ("extrusion_cali_sel", "ams_filament_setting"):
  2545. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  2546. # A refused ams_filament_setting is the printer's verdict on
  2547. # a write the user just made, and at DEBUG it never reached
  2548. # a support bundle: #2756 reported six manual Configure Slot
  2549. # attempts on an X1C, each returning HTTP 200 with the
  2550. # read-back still showing the previous profile, and no
  2551. # record of what the printer said about any of them. Same
  2552. # promotion as extrusion_cali_set (#2718) and
  2553. # ams_filament_drying (#1447) — but only on a non-success,
  2554. # because unlike those two this command is not rare: every
  2555. # spool assignment and every K-profile re-apply sends one,
  2556. # so promoting each ack would bury the interesting line.
  2557. #
  2558. # The developer-mode probe is excluded. It sends this exact
  2559. # command to the external slot precisely to see it refused
  2560. # on P1 firmware, so its failure is a normal reading rather
  2561. # than a fault. Its response is still matched below (this
  2562. # runs before _handle_dev_mode_probe_response clears the
  2563. # seq), and user-initiated commands can't be mistaken for
  2564. # it — they publish a hardcoded sequence_id of "0".
  2565. result = print_data.get("result")
  2566. is_dev_mode_probe = (
  2567. self._dev_mode_probe_seq is not None
  2568. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2569. )
  2570. # extrusion_cali_sel too (FW-C3): every RFID re-read
  2571. # re-applies the spool's K-profile and logs "Applied PA
  2572. # profile", so its refusal must reach the bundle beside it.
  2573. # The printer's word, not a verdict: the extrusion_cali_*
  2574. # acks are known to say "fail" for writes that applied.
  2575. if not is_dev_mode_probe and isinstance(result, str) and result.lower() != "success":
  2576. logger.info(
  2577. "[%s] %s refused: result=%s reason=%s ams_id=%s tray_id=%s",
  2578. self.serial_number,
  2579. cmd,
  2580. result,
  2581. print_data.get("reason", ""),
  2582. print_data.get("ams_id"),
  2583. print_data.get("tray_id"),
  2584. )
  2585. # AMS drying responses are rare (user-initiated only) and the
  2586. # full payload — including `result` and any `reason` code —
  2587. # is the only way to diagnose silent rejections like #1447.
  2588. # INFO level so the body lands in support bundles by default.
  2589. elif cmd == "ams_filament_drying":
  2590. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  2591. # RFID re-reads are user-initiated and rare, and a refusal was
  2592. # invisible until #3206 (X1Plus answering FAIL / ERROR STATE).
  2593. # gcode_line acks are only of interest when they answer our
  2594. # M620 R fallback, so those are matched by sequence_id alone.
  2595. ack_seq = str(print_data.get("sequence_id", ""))
  2596. if (
  2597. cmd in ("ams_get_rfid", "gcode_line")
  2598. and ack_seq in self._pending_rfid_acks
  2599. and "result" in print_data
  2600. ):
  2601. logger.info(
  2602. "[%s] %s response: result=%s reason=%s seq=%s",
  2603. self.serial_number,
  2604. cmd,
  2605. print_data.get("result"),
  2606. print_data.get("reason", ""),
  2607. ack_seq,
  2608. )
  2609. self._pending_rfid_acks[ack_seq] = print_data
  2610. # Check for developer mode probe response
  2611. if (
  2612. cmd == "ams_filament_setting"
  2613. and self._dev_mode_probe_seq is not None
  2614. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  2615. ):
  2616. self._handle_dev_mode_probe_response(print_data)
  2617. # Track user-initiated ams_filament_setting responses (#887
  2618. # zombie detection). Reset both the timer AND the unanswered
  2619. # counter on ANY response — the response proves the channel is
  2620. # alive, so the counter must not stay armed even when the
  2621. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  2622. # tick. The original `and self._last_ams_cmd_time > 0` guard
  2623. # caused #1164: one sluggish response (>10s) would set the
  2624. # counter to 1 and zero the timer; the late response arrived
  2625. # but was ignored by this branch (timer is 0); the counter
  2626. # stayed at 1 indefinitely; the very next slow response —
  2627. # possibly hours later, on a totally unrelated command — would
  2628. # take it to 2 and force-reconnect, surfacing as "filament
  2629. # config doesn't reach the printer ~6 changes in".
  2630. elif cmd == "ams_filament_setting":
  2631. self._last_ams_cmd_time = 0.0
  2632. self._ams_cmd_unanswered = 0
  2633. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  2634. if is_kprofile_response:
  2635. self._handle_kprofile_response(print_data)
  2636. # An extrusion_cali_get response echoes the *requested* nozzle
  2637. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  2638. # installed hardware. Feeding it to _update_state clobbered the real
  2639. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  2640. # which then failed the #1899 dispatch guard. The response carries no
  2641. # status telemetry, so skip it; the true nozzle comes from pushall.
  2642. # (Same reasoning as get_accessories in _handle_system_response.)
  2643. # The answers to K-profile writes and selections echo the diameter
  2644. # the command named in the same way, so none of them is status.
  2645. if print_data.get("command") not in _KPROFILE_COMMAND_ANSWERS:
  2646. self._update_state(print_data)
  2647. def _handle_system_response(self, data: dict):
  2648. """Handle system responses including accessories info.
  2649. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  2650. The correct nozzle data comes from push_status, so we don't update
  2651. nozzle type/diameter from get_accessories. We just log the response
  2652. for debugging purposes.
  2653. """
  2654. command = data.get("command")
  2655. if command == "get_accessories":
  2656. # Log response for debugging - but DON'T use it to update nozzle data
  2657. # because it returns stale values (e.g., 'stainless_steel' when the
  2658. # actual nozzle is 'HH01' hardened steel high-flow)
  2659. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  2660. def _handle_version_info(self, data: dict):
  2661. """Handle version info response from get_version command.
  2662. Parses firmware version from the 'ota' module in the module list.
  2663. Also extracts AMS unit firmware versions from AMS modules and stores
  2664. them on the corresponding AMS unit in raw_data so the status route can
  2665. expose them to the frontend.
  2666. AMS module naming conventions (numeric suffix is the AMS unit ID):
  2667. - ``ams/<id>`` – original AMS
  2668. - ``ams_f1/<id>`` – AMS Lite (#3348)
  2669. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  2670. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  2671. Message format:
  2672. {
  2673. "command": "get_version",
  2674. "module": [
  2675. {"name": "ota", "sw_ver": "01.08.05.00"},
  2676. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  2677. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  2678. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  2679. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  2680. ...
  2681. ]
  2682. }
  2683. """
  2684. modules = data.get("module", [])
  2685. if not isinstance(modules, list):
  2686. return
  2687. state_changed = False
  2688. for module in modules:
  2689. if not isinstance(module, dict):
  2690. continue
  2691. if module.get("name") == "ota":
  2692. version = module.get("sw_ver")
  2693. if version:
  2694. old_version = self.state.firmware_version
  2695. self.state.firmware_version = version
  2696. if old_version != version:
  2697. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  2698. state_changed = True
  2699. break
  2700. # Extract AMS unit firmware versions from AMS modules.
  2701. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  2702. # Always cache regardless of whether AMS data has arrived yet — get_version
  2703. # often arrives before the first push_status, so caching must be unconditional.
  2704. ams_raw = self.state.raw_data.get("ams")
  2705. for module in modules:
  2706. if not isinstance(module, dict):
  2707. continue
  2708. name = module.get("name", "")
  2709. if name == AMS3H_MODULE_NAME:
  2710. name = f"{name}/{self._ams3h_unit_id()}"
  2711. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  2712. continue
  2713. try:
  2714. # The A2L's AMS Lite is unit 16 here but stored as 6, like
  2715. # everywhere else it is ingested.
  2716. ams_id = normalize_am_unit_id(int(name.split("/", 1)[1]))
  2717. except (ValueError, IndexError):
  2718. continue
  2719. sw_ver = module.get("sw_ver", "")
  2720. sn = module.get("sn", "")
  2721. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  2722. module_type = name.split("/", 1)[0]
  2723. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  2724. if sw_ver or sn or module_type:
  2725. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  2726. state_changed = True
  2727. # Also directly update any AMS unit already present in raw_data
  2728. if ams_raw and isinstance(ams_raw, list):
  2729. for ams_unit in ams_raw:
  2730. if not isinstance(ams_unit, dict):
  2731. continue
  2732. try:
  2733. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  2734. except (ValueError, TypeError):
  2735. unit_id = None
  2736. if unit_id == ams_id:
  2737. if sw_ver:
  2738. ams_unit["sw_ver"] = sw_ver
  2739. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  2740. # Only set sn from version info if not already present in AMS data
  2741. if sn and not ams_unit.get("sn"):
  2742. ams_unit["sn"] = sn
  2743. if module_type:
  2744. ams_unit["module_type"] = module_type
  2745. break
  2746. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  2747. # included in the broadcast (not just the printer firmware version).
  2748. if state_changed and self.on_state_change:
  2749. self.on_state_change(self.state)
  2750. # Warn if any AMS unit is still missing serial number or firmware version
  2751. # after processing the version info response. Warn only once per connection
  2752. # to avoid repeated noise on older firmware that doesn't report these fields.
  2753. if ams_raw and isinstance(ams_raw, list):
  2754. for ams_unit in ams_raw:
  2755. if not isinstance(ams_unit, dict):
  2756. continue
  2757. ams_id = ams_unit.get("id", "?")
  2758. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  2759. key = (ams_id, "sn")
  2760. if key not in self._ams_version_warned:
  2761. self._ams_version_warned.add(key)
  2762. logger.warning(
  2763. "[%s] AMS unit %s: serial number not available in version info",
  2764. self.serial_number,
  2765. ams_id,
  2766. )
  2767. if not ams_unit.get("sw_ver"):
  2768. key = (ams_id, "sw_ver")
  2769. if key not in self._ams_version_warned:
  2770. self._ams_version_warned.add(key)
  2771. logger.warning(
  2772. "[%s] AMS unit %s: firmware version not available in version info",
  2773. self.serial_number,
  2774. ams_id,
  2775. )
  2776. def _apply_ams_version_cache(self, ams_list: list) -> None:
  2777. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  2778. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  2779. strings in MQTT payloads. This helper normalizes IDs and fills missing
  2780. sw_ver/sn fields without overwriting values already present.
  2781. """
  2782. if not ams_list or not isinstance(ams_list, list):
  2783. return
  2784. cache = self._ams_version_cache
  2785. if not cache:
  2786. return
  2787. for unit in ams_list:
  2788. if not isinstance(unit, dict):
  2789. continue
  2790. raw_id = unit.get("id")
  2791. try:
  2792. unit_id = int(raw_id) if raw_id is not None else None
  2793. except (ValueError, TypeError):
  2794. unit_id = None
  2795. if unit_id is None:
  2796. continue
  2797. cached = cache.get(unit_id)
  2798. if not cached:
  2799. continue
  2800. sw_ver = cached.get("sw_ver") or ""
  2801. sn = cached.get("sn") or ""
  2802. if sw_ver and not unit.get("sw_ver"):
  2803. unit["sw_ver"] = sw_ver
  2804. # Only set sn if not already present in AMS data
  2805. if sn and not unit.get("sn") and not unit.get("serial_number"):
  2806. unit["sn"] = sn
  2807. module_type = cached.get("module_type") or ""
  2808. if module_type and not unit.get("module_type"):
  2809. unit["module_type"] = module_type
  2810. def _parse_xcam_data(self, xcam_data):
  2811. """Parse xcam data for camera settings and AI detection options."""
  2812. if not isinstance(xcam_data, dict):
  2813. return
  2814. current_time = time.time()
  2815. # Helper to check if we should accept incoming value for a module
  2816. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  2817. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  2818. """Check if we should accept an incoming xcam value.
  2819. OrcaSlicer pattern: After sending a command, ignore incoming data
  2820. for 3 seconds. After that, accept whatever the printer sends.
  2821. """
  2822. if module_name not in self._xcam_hold_start:
  2823. return True # No hold timer, accept incoming
  2824. hold_start = self._xcam_hold_start[module_name]
  2825. elapsed = current_time - hold_start
  2826. if elapsed > self._xcam_hold_time:
  2827. # Hold timer expired - accept incoming and clear hold
  2828. del self._xcam_hold_start[module_name]
  2829. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  2830. return True
  2831. # Within hold period - ignore incoming data
  2832. logger.debug(
  2833. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  2834. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2835. )
  2836. return False
  2837. # Log all xcam fields for debugging
  2838. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  2839. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  2840. # fields (spaghetti_detector, etc.) are often stale/cached.
  2841. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  2842. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  2843. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  2844. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  2845. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  2846. # Sensitivity values: 0=low, 1=medium, 2=high
  2847. if "cfg" in xcam_data:
  2848. cfg = xcam_data["cfg"]
  2849. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  2850. def decode_detector(start_bit):
  2851. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  2852. sens_bits = (cfg >> start_bit) & 0x3
  2853. enabled = bool((cfg >> (start_bit + 2)) & 1)
  2854. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  2855. return enabled, sensitivity
  2856. # Spaghetti detector (bits 5-7)
  2857. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  2858. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  2859. old_value = self.state.print_options.spaghetti_detector
  2860. if cfg_spaghetti != old_value:
  2861. logger.debug(
  2862. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  2863. )
  2864. self.state.print_options.spaghetti_detector = cfg_spaghetti
  2865. # Check hold timer for sensitivity before accepting
  2866. if "halt_print_sensitivity" not in self._xcam_hold_start:
  2867. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2868. logger.debug(
  2869. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  2870. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2871. )
  2872. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2873. else:
  2874. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  2875. elapsed = current_time - hold_start
  2876. if elapsed <= self._xcam_hold_time:
  2877. logger.debug(
  2878. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  2879. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  2880. )
  2881. else:
  2882. # Hold expired - accept from cfg
  2883. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  2884. logger.debug(
  2885. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  2886. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  2887. )
  2888. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  2889. del self._xcam_hold_start["halt_print_sensitivity"]
  2890. # Pileup detector (bits 8-10)
  2891. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  2892. if should_accept_value("pileup_detector", cfg_pileup):
  2893. if cfg_pileup != self.state.print_options.pileup_detector:
  2894. logger.debug(
  2895. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  2896. )
  2897. self.state.print_options.pileup_detector = cfg_pileup
  2898. # Pileup sensitivity with hold timer
  2899. if "pileup_sensitivity" not in self._xcam_hold_start:
  2900. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2901. logger.debug(
  2902. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2903. )
  2904. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2905. else:
  2906. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  2907. elapsed = current_time - hold_start
  2908. if elapsed > self._xcam_hold_time:
  2909. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  2910. logger.debug(
  2911. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  2912. )
  2913. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  2914. del self._xcam_hold_start["pileup_sensitivity"]
  2915. # Clump/nozzle clumping detector (bits 11-13)
  2916. cfg_clump, cfg_clump_sens = decode_detector(11)
  2917. if should_accept_value("clump_detector", cfg_clump):
  2918. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  2919. logger.debug(
  2920. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  2921. )
  2922. self.state.print_options.nozzle_clumping_detector = cfg_clump
  2923. # Clump sensitivity with hold timer
  2924. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  2925. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2926. logger.debug(
  2927. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2928. )
  2929. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2930. else:
  2931. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2932. elapsed = current_time - hold_start
  2933. if elapsed > self._xcam_hold_time:
  2934. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  2935. logger.debug(
  2936. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  2937. )
  2938. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  2939. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  2940. # Airprint detector (bits 14-16)
  2941. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  2942. if should_accept_value("airprint_detector", cfg_airprint):
  2943. if cfg_airprint != self.state.print_options.airprint_detector:
  2944. logger.debug(
  2945. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  2946. )
  2947. self.state.print_options.airprint_detector = cfg_airprint
  2948. # Airprint sensitivity with hold timer
  2949. if "airprint_sensitivity" not in self._xcam_hold_start:
  2950. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2951. logger.debug(
  2952. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2953. )
  2954. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2955. else:
  2956. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  2957. elapsed = current_time - hold_start
  2958. if elapsed > self._xcam_hold_time:
  2959. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  2960. logger.debug(
  2961. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  2962. )
  2963. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  2964. del self._xcam_hold_start["airprint_sensitivity"]
  2965. # Camera settings
  2966. if "ipcam_record" in xcam_data:
  2967. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  2968. if "timelapse" in xcam_data:
  2969. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  2970. # Track if timelapse was ever active during this print
  2971. if self.state.timelapse and self._was_running:
  2972. self._timelapse_during_print = True
  2973. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  2974. if "print_halt" in xcam_data:
  2975. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  2976. # Skip halt_print_sensitivity field - it's always stale ("medium")
  2977. # We read the actual sensitivity from cfg bits 5-6 above
  2978. if "first_layer_inspector" in xcam_data:
  2979. new_value = bool(xcam_data.get("first_layer_inspector"))
  2980. if should_accept_value("first_layer_inspector", new_value):
  2981. self.state.print_options.first_layer_inspector = new_value
  2982. if "printing_monitor" in xcam_data:
  2983. new_value = bool(xcam_data.get("printing_monitor"))
  2984. if should_accept_value("printing_monitor", new_value):
  2985. self.state.print_options.printing_monitor = new_value
  2986. if "buildplate_marker_detector" in xcam_data:
  2987. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  2988. if should_accept_value("buildplate_marker_detector", new_value):
  2989. self.state.print_options.buildplate_marker_detector = new_value
  2990. if "allow_skip_parts" in xcam_data:
  2991. new_value = bool(xcam_data.get("allow_skip_parts"))
  2992. if should_accept_value("allow_skip_parts", new_value):
  2993. self.state.print_options.allow_skip_parts = new_value
  2994. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  2995. # individual boolean fields (which are not sent by the printer)
  2996. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  2997. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  2998. if "auto_recovery_step_loss" in xcam_data:
  2999. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  3000. if "filament_tangle_detect" in xcam_data:
  3001. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  3002. @staticmethod
  3003. def _resolve_local_slot_from_mapping(
  3004. local_slot: int, mapping_raw: list | None, units: list[int] | None = None
  3005. ) -> int | None:
  3006. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  3007. The MQTT mapping field is an array of snow-encoded values:
  3008. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  3009. Finds entries where the local slot matches, then computes the global tray ID.
  3010. When several match and ``units`` is given (the AMS units on the active
  3011. extruder of a dual-nozzle printer), only those units' trays count.
  3012. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  3013. """
  3014. if not isinstance(mapping_raw, list) or not mapping_raw:
  3015. return None
  3016. candidates = mapped_trays_with_slot(mapping_raw, local_slot) # global tray ID -> AMS unit
  3017. if len(candidates) > 1 and units:
  3018. candidates = {tray: unit for tray, unit in candidates.items() if unit in units}
  3019. if len(candidates) == 1:
  3020. return next(iter(candidates))
  3021. return None
  3022. def _maybe_trigger_external_spool_change(self):
  3023. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  3024. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  3025. an external-spool-only filament swap would otherwise never re-run the
  3026. inventory reconciliation that unlinks a stale ams_id=255 assignment
  3027. (#2575). The reconciliation reads vt_tray from live status itself, so we
  3028. just need to re-fire the callback with the current merged AMS data.
  3029. """
  3030. import hashlib
  3031. vt_tray = self.state.raw_data.get("vt_tray")
  3032. if not isinstance(vt_tray, list):
  3033. return
  3034. # Identity fields only — deliberately exclude `remain` so a print's
  3035. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  3036. fp_parts = [
  3037. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  3038. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  3039. for vt in vt_tray
  3040. if isinstance(vt, dict)
  3041. ]
  3042. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  3043. if vt_hash == self._previous_vt_tray_hash:
  3044. return
  3045. self._previous_vt_tray_hash = vt_hash
  3046. if self.on_ams_change:
  3047. logger.debug(
  3048. "[%s] External spool (vt_tray) changed, triggering sync callback",
  3049. self.serial_number,
  3050. )
  3051. self.on_ams_change(self.state.raw_data.get("ams") or [])
  3052. def _normalize_a2l_am_units(self, ams_list) -> None:
  3053. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  3054. id 16 -> 6 in place, as early as possible, so every downstream reader —
  3055. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  3056. the DB constraint — sees the normalised id and needs no special-casing.
  3057. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  3058. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  3059. both the dict-wrapped and bare-list AMS shapes.
  3060. """
  3061. if not isinstance(ams_list, list):
  3062. return
  3063. for unit in ams_list:
  3064. if not isinstance(unit, dict):
  3065. continue
  3066. try:
  3067. uid = int(unit.get("id"))
  3068. except (TypeError, ValueError):
  3069. continue
  3070. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  3071. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  3072. if not self._has_a2l_am_unit:
  3073. logger.info(
  3074. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  3075. self.serial_number,
  3076. A2L_LITE_NORMALIZED_AMS_ID,
  3077. )
  3078. self._has_a2l_am_unit = True
  3079. @property
  3080. def tray_layout(self) -> TrayLayout:
  3081. """How this printer numbers its trays (utils.tray_ids); rebuilt only when its units change."""
  3082. raw = self.state.raw_data
  3083. units, vt_trays = raw.get("ams"), raw.get("vt_tray")
  3084. key = (
  3085. tuple((u.get("id"), u.get("info")) for u in units if isinstance(u, dict))
  3086. if isinstance(units, list)
  3087. else (),
  3088. tuple(vt.get("id") for vt in vt_trays if isinstance(vt, dict)) if isinstance(vt_trays, list) else (),
  3089. self.model,
  3090. )
  3091. if key != self._tray_layout_key:
  3092. from backend.app.utils.printer_models import has_ams3h
  3093. self._tray_layout = TrayLayout.from_state(self.state, has_ams3h(self.model))
  3094. self._tray_layout_key = key
  3095. return self._tray_layout
  3096. def _layout_with(self, ams_list: object) -> TrayLayout:
  3097. """``tray_layout`` including the units of a push not merged into the state yet."""
  3098. if not isinstance(ams_list, list) or not any(isinstance(u, dict) for u in ams_list):
  3099. return self.tray_layout
  3100. units = [u for u in ams_list if isinstance(u, dict)]
  3101. known = self.state.raw_data.get("ams")
  3102. if isinstance(known, list):
  3103. units.extend(u for u in known if isinstance(u, dict))
  3104. vt_trays = self.state.raw_data.get("vt_tray")
  3105. return TrayLayout.from_units(units, vt_trays if isinstance(vt_trays, list) else None)
  3106. def _note_rack_ams(self, layout: TrayLayout) -> None:
  3107. """Log a rack AMS the first time this connection sees it."""
  3108. for ams_id, kind in layout.rack_units:
  3109. if ams_id in self._rack_ams_logged:
  3110. continue
  3111. self._rack_ams_logged.add(ams_id)
  3112. logger.info(
  3113. "[%s] Rack AMS detected: unit %s (AMS type %s), global tray ids %s-%s",
  3114. self.serial_number,
  3115. ams_id,
  3116. int(kind),
  3117. global_tray_id(ams_id, 0, kind),
  3118. global_tray_id(ams_id, RACK_SLOT_COUNT - 1, kind),
  3119. )
  3120. def _ams3h_unit_id(self) -> int:
  3121. """The unit id of this printer's AMS 3H (32 on the H3C)."""
  3122. return next((uid for uid, kind in self.tray_layout.rack_units if kind == AmsType.ZMULTI_A), AMS3H_UNIT_ID)
  3123. def _rack_ams_type(self, ams_id: int) -> AmsType | None:
  3124. """The type of unit ``ams_id`` when it is one of this printer's rack AMS units, else None."""
  3125. for uid, kind in self.tray_layout.rack_units:
  3126. if uid == ams_id:
  3127. return kind
  3128. return None
  3129. def _parse_fila_switch(self, data: dict) -> None:
  3130. """Read the Filament Track Switch block out of a print payload — #1162.
  3131. Presence of ``device.fila_switch`` means the accessory is installed. Kept
  3132. separate from the rest of the state update because ``_handle_ams_data``
  3133. needs the answer before it parses the AMS info bits, and that runs first.
  3134. """
  3135. if not isinstance(data.get("device"), dict):
  3136. return
  3137. fs_data = data["device"].get("fila_switch")
  3138. if not isinstance(fs_data, dict):
  3139. return
  3140. in_raw = fs_data.get("in")
  3141. out_raw = fs_data.get("out")
  3142. self.state.fila_switch = FilaSwitchState(
  3143. installed=True,
  3144. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  3145. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  3146. stat=int(fs_data.get("stat", 0) or 0),
  3147. info=int(fs_data.get("info", 0) or 0),
  3148. )
  3149. def _parse_extruder_position(self, data: dict) -> bool:
  3150. """Read which nozzle is active and which tray each nozzle holds.
  3151. From ``device.extruder``: ``state`` bit 8 is the active nozzle, each
  3152. ``info`` entry's ``snow`` names its AMS and slot. Run on a frame before
  3153. its AMS block, because an H2D's tray_now is a bare slot that only the
  3154. extruder data of the same frame places. Returns True when the frame
  3155. carried the active nozzle's snow. A malformed value is skipped, never
  3156. raised: this runs ahead of everything else the frame carries.
  3157. """
  3158. device = data.get("device")
  3159. extruder = device.get("extruder") if isinstance(device, dict) else None
  3160. if not isinstance(extruder, dict):
  3161. return False
  3162. try:
  3163. state_val = int(extruder["state"]) if "state" in extruder else None
  3164. except (TypeError, ValueError):
  3165. state_val = None
  3166. if state_val is not None:
  3167. # Extract bit 8 for extruder position
  3168. new_extruder = (state_val >> 8) & 0x1
  3169. if new_extruder != self.state.active_extruder:
  3170. logger.debug(
  3171. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  3172. )
  3173. self.state.active_extruder = new_extruder
  3174. extruder_info = extruder.get("info")
  3175. if not isinstance(extruder_info, list) or len(extruder_info) < 2:
  3176. return False
  3177. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  3178. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  3179. snow_read: set[int] = set()
  3180. for ext_info in extruder_info:
  3181. if not isinstance(ext_info, dict) or "id" not in ext_info or "snow" not in ext_info:
  3182. continue
  3183. try:
  3184. ext_id = int(ext_info["id"])
  3185. snow = int(ext_info["snow"])
  3186. except (TypeError, ValueError):
  3187. continue
  3188. if ext_id <= 1:
  3189. snow_read.add(ext_id)
  3190. # Normalize H2D snow value to global tray ID (255 = unloaded)
  3191. global_tray = 255 if snow == 0xFFFF else decode_wire_slot(snow)
  3192. if global_tray is None:
  3193. continue
  3194. if self.state.h2d_extruder_snow.get(ext_id) != global_tray:
  3195. logger.debug(
  3196. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: raw={snow} -> global tray {global_tray}"
  3197. )
  3198. self.state.h2d_extruder_snow[ext_id] = global_tray
  3199. return self.state.active_extruder in snow_read
  3200. def _parse_extruder_slots(self, data: dict) -> None:
  3201. """Read which AMS slot each extruder is fed from — ``device.extruder.info``.
  3202. Absent on printers that do not report the block, in which case the
  3203. previous answer is kept rather than cleared: a partial payload carrying
  3204. only temperatures must not look like "both hotends are now empty".
  3205. """
  3206. device = data.get("device")
  3207. if not isinstance(device, dict):
  3208. return
  3209. info = device.get("extruder", {}).get("info") if isinstance(device.get("extruder"), dict) else None
  3210. if not isinstance(info, list) or not info:
  3211. return
  3212. slots: dict[int, ExtruderSlot] = {}
  3213. for entry in info:
  3214. if not isinstance(entry, dict) or "id" not in entry:
  3215. continue
  3216. try:
  3217. ext_id = int(entry["id"])
  3218. snow = int(entry.get("snow", _EXTRUDER_SLOT_EMPTY))
  3219. flags = int(entry.get("info", 0) or 0)
  3220. except (TypeError, ValueError):
  3221. continue
  3222. if snow == _EXTRUDER_SLOT_EMPTY or snow < 0:
  3223. ams_id = slot_id = None
  3224. else:
  3225. ams_id = (snow >> 8) & 0xFF
  3226. slot_id = snow & 0xFF
  3227. slots[ext_id] = ExtruderSlot(
  3228. ams_id=ams_id,
  3229. slot_id=slot_id,
  3230. has_filament=bool(flags & 0b10),
  3231. )
  3232. if slots:
  3233. self.state.extruder_slots = slots
  3234. def _handle_ams_data(self, ams_data):
  3235. """Handle AMS data changes for Spoolman integration.
  3236. This is called when we receive top-level AMS data in MQTT messages.
  3237. It detects changes and triggers the callback for Spoolman sync.
  3238. """
  3239. import hashlib
  3240. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  3241. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  3242. ams_list = None
  3243. if isinstance(ams_data, dict):
  3244. if "ams" in ams_data:
  3245. ams_list = ams_data["ams"]
  3246. self._normalize_a2l_am_units(ams_list)
  3247. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3248. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  3249. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  3250. if non_list_fields:
  3251. self._debug_on_change(
  3252. "ams_dict_fields",
  3253. non_list_fields,
  3254. "[%s] AMS dict fields: %s",
  3255. self.serial_number,
  3256. non_list_fields,
  3257. )
  3258. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  3259. # when checking if we're in filament change mode for tray_now disambiguation
  3260. if "ams_status" in ams_data:
  3261. raw_ams_status = ams_data["ams_status"]
  3262. if isinstance(raw_ams_status, str):
  3263. try:
  3264. self.state.ams_status = int(raw_ams_status)
  3265. except ValueError:
  3266. self.state.ams_status = 0
  3267. else:
  3268. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  3269. # Compute main and sub status
  3270. self.state.ams_status_sub = self.state.ams_status & 0xFF
  3271. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  3272. self._debug_on_change(
  3273. "ams_status:ams",
  3274. self.state.ams_status,
  3275. "[%s] ams_status: %s (main=%s, sub=%s)",
  3276. self.serial_number,
  3277. self.state.ams_status,
  3278. self.state.ams_status_main,
  3279. self.state.ams_status_sub,
  3280. )
  3281. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  3282. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  3283. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  3284. # next compatible slot (#2587). Stored raw here; globalised at the API
  3285. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  3286. # these are local slot numbers (0-3), not global IDs.
  3287. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  3288. if _tk in ams_data:
  3289. _raw = ams_data[_tk]
  3290. if isinstance(_raw, str):
  3291. try:
  3292. _val = int(_raw)
  3293. except ValueError:
  3294. _val = 255
  3295. else:
  3296. _val = _raw if _raw is not None else 255
  3297. prev = getattr(self.state, _attr)
  3298. setattr(self.state, _attr, _val)
  3299. # Log changes only while paused — the moment the operator cares —
  3300. # so a healthy print's normal tar churn doesn't spam the log.
  3301. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  3302. logger.info(
  3303. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  3304. self.serial_number,
  3305. _tk,
  3306. _val,
  3307. )
  3308. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  3309. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  3310. if "tray_now" in ams_data:
  3311. raw_tray_now = ams_data["tray_now"]
  3312. # Convert string to int if needed
  3313. if isinstance(raw_tray_now, str):
  3314. try:
  3315. parsed_tray_now = int(raw_tray_now)
  3316. except ValueError:
  3317. parsed_tray_now = 255
  3318. else:
  3319. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  3320. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  3321. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  3322. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  3323. # — disambiguated below using MQTT mapping field
  3324. ams_map = self.state.ams_extruder_map
  3325. # A rack AMS reports tray_now as its raw slot 0-8 (global 28 +
  3326. # slot). Its units may arrive in this same push, before the merge.
  3327. rack_layout = self._layout_with(ams_list)
  3328. self._note_rack_ams(rack_layout)
  3329. if rack_layout.rack_units and not self._is_dual_nozzle:
  3330. rack_tray = rack_layout.raw_slot_to_global(parsed_tray_now)
  3331. # 255 (nothing on the toolhead, also mid-swap) and any
  3332. # external input id are kept as reported.
  3333. self.state.tray_now = rack_tray if rack_tray is not None else parsed_tray_now
  3334. elif self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3335. # First, check if we have a pending target that matches this slot
  3336. pending_target = self.state.pending_tray_target
  3337. pending_at = self.state.pending_tray_target_at
  3338. if (
  3339. pending_target is not None
  3340. and pending_at is not None
  3341. and time.monotonic() - pending_at > PENDING_TRAY_TARGET_TTL
  3342. ):
  3343. # A load the printer refused or dropped: nothing clears
  3344. # it (tray_now stays 255), and a print loading the same
  3345. # slot number on another AMS long after was shown as
  3346. # this target (FW-C7). Fall through to the snow field.
  3347. self.state.pending_tray_target = None
  3348. self.state.pending_tray_target_at = None
  3349. pending_target = None
  3350. if pending_target is not None:
  3351. # Same slot rule as the snow branch below: an AMS-HT
  3352. # (128-135) has its one tray in slot 0.
  3353. pending_slot = 0 if is_ams_ht_id(pending_target) else pending_target % 4
  3354. if pending_slot == parsed_tray_now:
  3355. # Slot matches our pending target - use the full global ID
  3356. logger.debug(
  3357. f"[{self.serial_number}] H2D tray_now disambiguation: "
  3358. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  3359. )
  3360. self.state.tray_now = pending_target
  3361. # Clear pending target now that load is confirmed
  3362. self.state.pending_tray_target = None
  3363. else:
  3364. # Slot doesn't match our pending target - something changed, use slot as-is
  3365. logger.warning(
  3366. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  3367. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  3368. )
  3369. self.state.tray_now = parsed_tray_now
  3370. # Clear pending target since it's stale
  3371. self.state.pending_tray_target = None
  3372. else:
  3373. # No pending target - use h2d_extruder_snow for accurate disambiguation
  3374. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  3375. active_ext = self.state.active_extruder # 0=right, 1=left
  3376. # Best source: use snow value from device.extruder.info if available
  3377. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  3378. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  3379. snow_slot = (
  3380. None
  3381. if snow_tray is None
  3382. else snow_tray % 4
  3383. if snow_tray < 128
  3384. else (0 if is_ams_ht_id(snow_tray) else -1)
  3385. )
  3386. # A snow from an earlier frame may predate a swap: it
  3387. # names the tray only while it agrees with the slot.
  3388. snow_usable = (
  3389. snow_tray is not None
  3390. and snow_tray != 255
  3391. and (snow_slot == parsed_tray_now or self._snow_in_frame)
  3392. )
  3393. if snow_usable and snow_tray is not None:
  3394. # snow_tray is already normalized to global ID
  3395. if snow_slot == parsed_tray_now:
  3396. if self.state.tray_now != snow_tray:
  3397. logger.debug(
  3398. f"[{self.serial_number}] H2D tray_now from snow: "
  3399. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  3400. )
  3401. self.state.tray_now = snow_tray
  3402. else:
  3403. # Slot mismatch in one frame: the extruder's own
  3404. # report is the complete answer, trust snow
  3405. logger.debug(
  3406. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  3407. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  3408. )
  3409. self.state.tray_now = snow_tray
  3410. else:
  3411. # Fallback: snow not available, use ams_extruder_map (less reliable)
  3412. # Find ALL AMS units on the active extruder
  3413. ams_on_extruder = []
  3414. for ams_id_str, ext_id in ams_map.items():
  3415. if ext_id == active_ext:
  3416. try:
  3417. ams_on_extruder.append(int(ams_id_str))
  3418. except ValueError:
  3419. pass # Skip AMS IDs that aren't valid integers
  3420. # Several AMS (or none the map knows of) leave the
  3421. # slot ambiguous. The printer's own mapping names the
  3422. # trays the running print uses: one of them at this
  3423. # slot is the one feeding (#3242). Only while a print
  3424. # runs: an idle H2 keeps reporting the previous
  3425. # print's mapping.
  3426. mapped_tray = None
  3427. if len(ams_on_extruder) != 1 and self._was_running and not self._completion_triggered:
  3428. mapped_tray = self._resolve_local_slot_from_mapping(
  3429. parsed_tray_now, self.state.raw_data.get("mapping"), ams_on_extruder
  3430. )
  3431. if mapped_tray is not None:
  3432. if self.state.tray_now != mapped_tray:
  3433. logger.debug(
  3434. f"[{self.serial_number}] H2D tray_now: AMS {ams_on_extruder} on extruder "
  3435. f"{active_ext}, slot {parsed_tray_now} -> global ID {mapped_tray} (from mapping)"
  3436. )
  3437. self.state.tray_now = mapped_tray
  3438. elif len(ams_on_extruder) == 1:
  3439. # Single AMS on this extruder - unambiguous
  3440. active_ams_id = ams_on_extruder[0]
  3441. # AMS-HT: single slot per unit, global ID = unit ID
  3442. fallback_tray = global_tray_id(active_ams_id, parsed_tray_now)
  3443. logger.debug(
  3444. f"[{self.serial_number}] H2D tray_now fallback: "
  3445. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {fallback_tray}"
  3446. )
  3447. self.state.tray_now = fallback_tray
  3448. elif len(ams_on_extruder) > 1:
  3449. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  3450. current_tray = self.state.tray_now
  3451. # Determine which AMS unit and slot the current tray belongs to
  3452. if 0 <= current_tray <= 15 or is_ams_ht_id(current_tray):
  3453. # AMS-HT: ID = tray ID, one slot
  3454. current_ams, current_slot = rack_layout.slot_key(current_tray)
  3455. else:
  3456. current_ams = -1
  3457. current_slot = -1
  3458. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  3459. # Current is valid and matches slot - keep it
  3460. logger.debug(
  3461. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3462. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  3463. )
  3464. else:
  3465. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  3466. if parsed_tray_now > 0:
  3467. candidates = [a for a in ams_on_extruder if a <= 3]
  3468. else:
  3469. candidates = ams_on_extruder
  3470. if len(candidates) == 1:
  3471. cand = candidates[0]
  3472. resolved = global_tray_id(cand, parsed_tray_now)
  3473. logger.debug(
  3474. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  3475. f"narrowed to AMS {cand} -> global ID {resolved}"
  3476. )
  3477. self.state.tray_now = resolved
  3478. else:
  3479. # Genuinely ambiguous. This is the second between a
  3480. # filament change reaching the AMS report and the
  3481. # extruder's snow, which then names the tray. Using
  3482. # the bare slot would point at AMS 0 and put that
  3483. # tray in the usage change log (#3242), so keep the
  3484. # current tray until snow arrives.
  3485. logger.debug(
  3486. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on "
  3487. f"extruder {active_ext}, slot {parsed_tray_now} is ambiguous without snow, "
  3488. f"keeping {current_tray}"
  3489. )
  3490. else:
  3491. # No AMS on this extruder that the map knows of: the
  3492. # slot can't be placed, keep the current tray (#3242)
  3493. logger.debug(
  3494. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  3495. f"slot {parsed_tray_now} can't be placed without snow, keeping {self.state.tray_now}"
  3496. )
  3497. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  3498. # Single-nozzle printer with tray_now in 0-3 range.
  3499. # #1822: H2S firmware reports tray_now as the AMS's idle
  3500. # slot (typically 0) when the active feed is actually the
  3501. # external spool. X1C / P1S / A1 correctly report 254 in
  3502. # that case; H2S does not. When the slicer-captured
  3503. # ams_mapping is all-external (every entry is 254, or -1
  3504. # when the command carried no ams_mapping2 to resolve it
  3505. # from, #3166), the print can only be feeding from the
  3506. # external spool, so promote tray_now to 254. Mixed (e.g. [5, 254]) and
  3507. # AMS-only mappings are NOT overridden — there's no
  3508. # evidence the firmware misreports in those cases. Prints
  3509. # started without a captured mapping (printer-screen start,
  3510. # or before Bambuddy connected) fall through unchanged.
  3511. captured = self._captured_ams_mapping
  3512. if captured and all(s in (-1, 254, 255) for s in captured):
  3513. if self.state.tray_now != 254:
  3514. logger.debug(
  3515. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  3516. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  3517. )
  3518. self.state.tray_now = 254
  3519. else:
  3520. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  3521. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  3522. # (snow-encoded) to resolve the correct AMS unit.
  3523. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  3524. try:
  3525. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  3526. except (ValueError, TypeError):
  3527. ams_exist = 0
  3528. num_ams = bin(ams_exist).count("1")
  3529. if self._has_a2l_am_unit and num_ams <= 1:
  3530. # A2L AMS-Lite (normalised unit 6): the firmware reports
  3531. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  3532. # otherwise usage tracking keys the wrong spool (it would
  3533. # deduct from AMS 0's slot). Confirmed by capture:
  3534. # tray_now="2" while printing physical slot 3.
  3535. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  3536. elif num_ams > 1:
  3537. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  3538. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  3539. if self._has_a2l_am_unit:
  3540. # A2L Lite + a regular AMS attached together is out of
  3541. # scope: the flat mapping ids are unknown for that combo
  3542. # and could collide with AMS 0. Fall through to the
  3543. # mapping-based resolve, but warn — a capture is needed.
  3544. logger.warning(
  3545. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  3546. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  3547. self.serial_number,
  3548. )
  3549. mapping_raw = self.state.raw_data.get("mapping")
  3550. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  3551. if resolved is not None:
  3552. if resolved != parsed_tray_now:
  3553. logger.debug(
  3554. f"[{self.serial_number}] Multi-AMS tray_now: "
  3555. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  3556. )
  3557. self.state.tray_now = resolved
  3558. else:
  3559. # No mapping available (not printing, or ambiguous) — use as-is.
  3560. # This matches the old behavior and is correct for AMS 0.
  3561. self.state.tray_now = parsed_tray_now
  3562. else:
  3563. # Single AMS — local slot 0-3 equals global ID
  3564. self.state.tray_now = parsed_tray_now
  3565. else:
  3566. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  3567. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  3568. # During filament change, the printer sends 255 first (unload), then the slot.
  3569. # We only clear pending_tray_target explicitly in ams_unload_filament().
  3570. # Trust the printer's reported value.
  3571. self.state.tray_now = parsed_tray_now
  3572. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  3573. tn = self.state.tray_now
  3574. if rack_layout.is_loaded_tray(tn):
  3575. # Log tray change for mid-print usage splitting. Gate on the
  3576. # print-lifecycle flags (`_was_running` set on first RUNNING /
  3577. # new print, `_completion_triggered` set when on_print_complete
  3578. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  3579. # firmware briefly transitions out of RUNNING during AMS
  3580. # auto-fallback (#957), so a literal-string gate misses the
  3581. # switch and the usage tracker double-credits at completion.
  3582. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  3583. self.state.tray_change_log.append((tn, self.state.layer_num))
  3584. logger.info(
  3585. "[%s] Tray change during print: tray=%d at layer=%d",
  3586. self.serial_number,
  3587. tn,
  3588. self.state.layer_num,
  3589. )
  3590. if self.on_tray_change:
  3591. self.on_tray_change(tn, self.state.layer_num)
  3592. self.state.last_loaded_tray = self.state.tray_now
  3593. self._debug_on_change(
  3594. "tray_now",
  3595. self.state.tray_now,
  3596. "[%s] tray_now updated: %s",
  3597. self.serial_number,
  3598. self.state.tray_now,
  3599. )
  3600. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  3601. # state when checking filament change mode for H2D disambiguation
  3602. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  3603. # We've already processed the status fields above, so just return if no ams list
  3604. if ams_list is None:
  3605. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  3606. return
  3607. elif isinstance(ams_data, list):
  3608. ams_list = ams_data
  3609. self._normalize_a2l_am_units(ams_list)
  3610. apply_rack_ams_zone_fields(ams_list, dict(self.tray_layout.units))
  3611. else:
  3612. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  3613. return
  3614. # Merge AMS data instead of replacing, to handle partial updates
  3615. # During prints, the printer may only send updates for active AMS units
  3616. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  3617. existing_ams = self.state.raw_data.get("ams")
  3618. # #3499: anything but the merged unit list (once, the frame's own AMS
  3619. # object) would fail every later frame on its string keys.
  3620. if not isinstance(existing_ams, list):
  3621. existing_ams = []
  3622. existing_by_id = {
  3623. ams.get("id"): ams for ams in existing_ams if isinstance(ams, dict) and ams.get("id") is not None
  3624. }
  3625. # Update existing units with new data, add new units
  3626. for ams_unit in ams_list:
  3627. ams_id = ams_unit.get("id")
  3628. if ams_id is not None:
  3629. existing_unit = existing_by_id.get(ams_id)
  3630. if existing_unit and "tray" in ams_unit:
  3631. # Deep merge trays to preserve fields from previous updates
  3632. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  3633. merged_trays = []
  3634. for new_tray in ams_unit.get("tray", []):
  3635. tray_id = new_tray.get("id")
  3636. if tray_id is not None and tray_id in existing_trays:
  3637. # Merge: start with existing, update with new non-empty values
  3638. merged_tray = existing_trays[tray_id].copy()
  3639. # Detect slot-clearing updates (spool removal):
  3640. # When tray_type is explicitly empty, clear everything
  3641. # including RFID data (tag_uid/tray_uuid).
  3642. slot_clearing = new_tray.get("tray_type") == ""
  3643. # Some printers (e.g. H2D) only send {id, state} in
  3644. # incremental updates when a tray is not fully loaded.
  3645. # state=11 means loaded; other values (9=empty,
  3646. # 10=spool present but filament not in feeder) indicate
  3647. # the slot should be cleared. Without this, old
  3648. # tray_type/tray_color persist indefinitely (#784).
  3649. #
  3650. # BUT this is regular-AMS semantics. An AMS-HT (single-
  3651. # tray high-temp dry box, id >= 128) reports its loaded
  3652. # tray as state=9, not 11 — it doesn't feed filament into
  3653. # a shared buffer the way a 4-slot AMS does. Applying the
  3654. # `state != 11 → empty` rule to an HT unit wiped a present
  3655. # spool on every power-on, when the printer sends a partial
  3656. # {id, state=9} for the HT tray (#2594). Skip the state
  3657. # heuristic for HT units — a genuine HT spool removal still
  3658. # clears via the explicit tray_type=="" case above and the
  3659. # tray_exist_bits cleanup below.
  3660. #
  3661. # A rack AMS (the H3C's AMS 3H) reports a loaded slot
  3662. # as state=27, so it is skipped the same way.
  3663. try:
  3664. _is_ht_unit = int(ams_id) >= 128 or is_rack_ams(
  3665. unit_ams_type(int(ams_id), ams_unit.get("info") or existing_unit.get("info"))
  3666. )
  3667. except (TypeError, ValueError):
  3668. _is_ht_unit = False
  3669. tray_state = new_tray.get("state")
  3670. if (
  3671. tray_state is not None
  3672. and tray_state != 11
  3673. and not _is_ht_unit
  3674. and "tray_type" not in new_tray
  3675. and merged_tray.get("tray_type")
  3676. ):
  3677. logger.info(
  3678. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  3679. self.serial_number,
  3680. ams_id,
  3681. tray_id,
  3682. tray_state,
  3683. )
  3684. slot_clearing = True
  3685. # The incremental update only has {id, state} — inject
  3686. # empty values for all content fields so the merge loop
  3687. # below clears the stale data from merged_tray.
  3688. new_tray.update(
  3689. {
  3690. "tray_type": "",
  3691. "tray_sub_brands": "",
  3692. "tray_color": "",
  3693. "tray_id_name": "",
  3694. "tray_info_idx": "",
  3695. "tag_uid": "0000000000000000",
  3696. "tray_uuid": "00000000000000000000000000000000",
  3697. "remain": 0,
  3698. "k": None,
  3699. "cali_idx": None,
  3700. }
  3701. )
  3702. for key, value in new_tray.items():
  3703. # Fields that should always be updated (even with empty/zero values):
  3704. # - remain, k, id, cali_idx: status indicators where 0 is valid
  3705. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  3706. # tray_id_name: slot content indicators that must be cleared
  3707. # when a spool is removed (fixes #147 - old AMS empty slot)
  3708. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  3709. # They are only cleared during spool removal (slot_clearing=True).
  3710. # Periodic AMS updates often include empty RFID fields which
  3711. # would overwrite valid data from the initial pushall.
  3712. always_update_fields = (
  3713. "remain",
  3714. "k",
  3715. "id",
  3716. "cali_idx",
  3717. "tray_type",
  3718. "tray_sub_brands",
  3719. "tray_info_idx",
  3720. "tray_color",
  3721. "tray_id_name",
  3722. )
  3723. if (
  3724. key in always_update_fields
  3725. or slot_clearing
  3726. or value
  3727. not in (
  3728. None,
  3729. "",
  3730. "0000000000000000",
  3731. "00000000000000000000000000000000",
  3732. )
  3733. ):
  3734. merged_tray[key] = value
  3735. merged_trays.append(merged_tray)
  3736. else:
  3737. merged_trays.append(new_tray)
  3738. # Update ams_unit with merged trays. Spread existing_unit
  3739. # FIRST so top-level fields the partial update omits —
  3740. # dry_time, info (which drives dry_status / dry_sub_status),
  3741. # humidity, temp — are preserved instead of dropped. The
  3742. # printer sends tray-bearing partials that carry no drying
  3743. # fields; without this, dry_time reads as absent → 0 and the
  3744. # falling-edge detector below fires a false "drying complete"
  3745. # (#1462). Mirrors the no-tray branch's merge semantics.
  3746. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  3747. elif existing_unit:
  3748. # Partial update without tray data: merge new fields into existing
  3749. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  3750. ams_unit = {**existing_unit, **ams_unit}
  3751. existing_by_id[ams_id] = ams_unit
  3752. # The merge keeps a unit the push doesn't list, so an unplugged AMS used
  3753. # to stay until Bambuddy restarted (#3356). Drop one only on the
  3754. # printer's own word that it is gone.
  3755. if isinstance(ams_data, dict):
  3756. listed = {ams_unit.get("id") for ams_unit in ams_list}
  3757. for ams_id in [i for i in existing_by_id if i not in listed]:
  3758. if unit_reported_absent(ams_id, ams_list, ams_data.get("ams_exist_bits")):
  3759. logger.info("[%s] AMS %s no longer attached, removing it", self.serial_number, ams_id)
  3760. del existing_by_id[ams_id]
  3761. # Convert back to list, sorted by ID for consistent ordering
  3762. merged_ams = sorted(existing_by_id.values(), key=_ams_unit_order)
  3763. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  3764. # Shared with the VP bridge cache so the slicer-facing view stays in
  3765. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  3766. # for the full rationale and the printer-shutdown guard.
  3767. if isinstance(ams_data, dict):
  3768. apply_tray_exist_bits(
  3769. merged_ams,
  3770. ams_data.get("tray_exist_bits"),
  3771. power_on_flag=ams_data.get("power_on_flag", True),
  3772. log_label=self.serial_number,
  3773. annotate_exists=True,
  3774. )
  3775. self.state.raw_data["ams"] = merged_ams
  3776. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  3777. self._apply_ams_version_cache(merged_ams)
  3778. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  3779. self.state.last_ams_update = time.time()
  3780. self._debug_on_change(
  3781. "merged_ams",
  3782. (len(ams_list), len(merged_ams)),
  3783. "[%s] Merged AMS data: %s new units, %s total",
  3784. self.serial_number,
  3785. len(ams_list),
  3786. len(merged_ams),
  3787. )
  3788. # Extract ams_extruder_map from each AMS unit's info field
  3789. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  3790. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  3791. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  3792. # bind_switch_in = get_flag_bits(info, 24, 4) // bits 24-27: FTS inlet
  3793. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  3794. # extruder_id: 0=right/main, 1=left/deputy, 0xE=routing is not fixed
  3795. #
  3796. # 0xE does not mean "broken". On a Filament Track Switch machine it is the
  3797. # normal steady state: the AMS is bound to a switch *inlet* rather than to
  3798. # one extruder, and reaches both nozzles through it. Bits 24-27 then name
  3799. # that inlet — 0 = In-B, 1 = In-A (BambuStudio's SwitchPos enum, which is
  3800. # ordered B-then-A). Without an FTS, 0xE really is an uninitialised unit
  3801. # and bits 24-27 carry nothing, which is why the inlet read is gated on
  3802. # the switch being installed.
  3803. #
  3804. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  3805. # the full map. Merge into existing map to preserve entries from prior updates.
  3806. fts_installed = self.state.fila_switch.installed
  3807. inlet_moves: list[tuple[int, str]] = []
  3808. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  3809. ams_switch_inlet = dict(self.state.ams_switch_inlet) if self.state.ams_switch_inlet else {}
  3810. # A rack AMS feeds the one extruder of a rack printer; listed here it
  3811. # would make the slot/dispatch code assume two nozzles.
  3812. rack_ams_ids = {uid for uid, _ in TrayLayout.from_units(merged_ams).rack_units}
  3813. for ams_unit in merged_ams:
  3814. ams_id = ams_unit.get("id")
  3815. info = ams_unit.get("info")
  3816. if _mqtt_int(ams_id) in rack_ams_ids:
  3817. continue
  3818. if ams_id is not None and info is not None:
  3819. try:
  3820. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  3821. info_val = int(str(info), 16)
  3822. # Extract 4 bits starting at bit 8 for extruder assignment
  3823. extruder_id = (info_val >> 8) & 0xF
  3824. if extruder_id == 0xE:
  3825. if fts_installed:
  3826. inlet = {0: "B", 1: "A"}.get((info_val >> 24) & 0xF)
  3827. if inlet is not None:
  3828. previous = ams_switch_inlet.get(str(ams_id))
  3829. ams_switch_inlet[str(ams_id)] = inlet
  3830. self._debug_on_change(
  3831. f"ams_inlet:{ams_id}",
  3832. inlet,
  3833. "[%s] AMS %s info=0x%s -> FTS inlet %s",
  3834. self.serial_number,
  3835. ams_id,
  3836. info,
  3837. inlet,
  3838. )
  3839. if previous is not None and previous != inlet:
  3840. # Only a genuine move, never the first sighting:
  3841. # re-applying K-profiles on every reconnect would
  3842. # fight a binding the operator set deliberately.
  3843. logger.info(
  3844. "[%s] AMS %s moved to FTS inlet %s (was %s)",
  3845. self.serial_number,
  3846. ams_id,
  3847. inlet,
  3848. previous,
  3849. )
  3850. inlet_moves.append((int(ams_id), inlet))
  3851. continue
  3852. ams_extruder_map[str(ams_id)] = extruder_id
  3853. self._debug_on_change(
  3854. f"ams_info:{ams_id}",
  3855. (info, extruder_id),
  3856. "[%s] AMS %s info=0x%s -> extruder %s",
  3857. self.serial_number,
  3858. ams_id,
  3859. info,
  3860. extruder_id,
  3861. )
  3862. except (ValueError, TypeError):
  3863. pass # Skip AMS units with unparseable info bitmask values
  3864. if ams_extruder_map:
  3865. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  3866. self.state.ams_extruder_map = ams_extruder_map
  3867. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  3868. if ams_switch_inlet:
  3869. self.state.ams_switch_inlet = ams_switch_inlet
  3870. for moved_ams_id, moved_inlet in inlet_moves:
  3871. if self.on_fts_inlet_change:
  3872. self.on_fts_inlet_change(moved_ams_id, moved_inlet)
  3873. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  3874. # BambuStudio DevFilaSystem.cpp parses info bits:
  3875. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  3876. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  3877. for ams_unit in merged_ams:
  3878. info = ams_unit.get("info")
  3879. if info is not None:
  3880. try:
  3881. info_val = int(str(info), 16)
  3882. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  3883. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  3884. except (ValueError, TypeError):
  3885. pass # Skip unparseable info values
  3886. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  3887. if "dry_sf_reason" in ams_unit:
  3888. sf_reason = ams_unit["dry_sf_reason"]
  3889. if isinstance(sf_reason, list):
  3890. ams_unit["dry_sf_reason"] = [
  3891. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  3892. ]
  3893. else:
  3894. ams_unit["dry_sf_reason"] = []
  3895. # Persist updated drying fields back to raw_data
  3896. self.state.raw_data["ams"] = merged_ams
  3897. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  3898. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  3899. # — fire the callback so smart-plug auto-off-after-drying can run,
  3900. # and drop our cached target-cycle params so the badge stops claiming
  3901. # an active cycle. Works identically for queue-triggered, ambient,
  3902. # and manual drying because we observe the firmware-reported state.
  3903. for ams_unit in merged_ams:
  3904. try:
  3905. ams_id = int(ams_unit.get("id", -1))
  3906. except (TypeError, ValueError):
  3907. continue
  3908. if ams_id < 0:
  3909. continue
  3910. # The firmware phase outranks the stalled-countdown heuristic even
  3911. # on a transient-zero frame, which the completion guard below skips.
  3912. # Clear a previously raised flag before that early continue.
  3913. if ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3914. ams_unit["dry_countdown_stalled"] = False
  3915. # Only evaluate the edge when this update carries an explicit
  3916. # dry_time. An absent / unparseable value is NOT zero — treating
  3917. # it as 0 lets a tray-only partial fake a drying-complete edge
  3918. # (#1462). Skip without touching the remembered value so the
  3919. # next update that DOES carry dry_time sees the true previous.
  3920. raw_dry_time = ams_unit.get("dry_time")
  3921. if raw_dry_time is None:
  3922. continue
  3923. try:
  3924. current = int(raw_dry_time)
  3925. except (TypeError, ValueError):
  3926. continue
  3927. # A dry_time of 0 only means "finished" when the unit also reports
  3928. # an idle phase. Between the command ack and the countdown settling
  3929. # the firmware publishes a transient 0 while the AMS is still
  3930. # Checking — #2759 caught a 720 → 0 → 719 sequence one minute into a
  3931. # 12-hour cycle. Taking that at face value dropped the cached target
  3932. # (leaving the badge to guess the filament from tray 1, so a PLA
  3933. # cycle read "PETG @ 65°C") and fired on_drying_complete, which
  3934. # schedules smart-plug auto-off. dry_status comes from the same info
  3935. # hex parsed above; when it is absent we let the edge through, so a
  3936. # firmware that never reports one still ends its cycles.
  3937. if current == 0 and ams_unit.get("dry_status") in ACTIVE_DRY_STATUSES:
  3938. # Leave the remembered value alone, exactly as the absent-
  3939. # dry_time skip above does: whichever push ends the cycle for
  3940. # real must still see a non-zero previous.
  3941. logger.debug(
  3942. "[%s] AMS %d reported dry_time 0 in phase %s — cycle still live, ignoring",
  3943. self.serial_number,
  3944. ams_id,
  3945. ams_unit.get("dry_status"),
  3946. )
  3947. continue
  3948. seen_before = ams_id in self._previous_dry_times
  3949. previous = self._previous_dry_times.get(ams_id, 0)
  3950. self._previous_dry_times[ams_id] = current
  3951. if current > 0:
  3952. cycle = self._dry_cycles.get(ams_id)
  3953. if cycle is None or previous == 0:
  3954. cycle = {
  3955. "peak": current,
  3956. # A rise from an observed 0 is the cycle's first minute.
  3957. # A first sighting already counting down is not.
  3958. "start_seen": seen_before,
  3959. "target": self._drying_targets.get(ams_id),
  3960. }
  3961. self._dry_cycles[ams_id] = cycle
  3962. elif current > int(cycle["peak"]):
  3963. cycle["peak"] = current
  3964. # Stall detection: stamp value CHANGES only — a live countdown
  3965. # decrements once a minute, so repeats of the same value within
  3966. # the minute must not refresh the stamp, and a frame without a
  3967. # dry_time never reaches here (the absent-value skip above).
  3968. now_mono = time.monotonic()
  3969. if current != previous or ams_id not in self._dry_time_changed_at:
  3970. self._dry_time_changed_at[ams_id] = now_mono
  3971. ams_unit["dry_countdown_stalled"] = bool(
  3972. current > 0
  3973. and ams_unit.get("dry_status") not in ACTIVE_DRY_STATUSES
  3974. and now_mono - self._dry_time_changed_at[ams_id] > DRY_COUNTDOWN_STALL_SECONDS
  3975. )
  3976. if previous > 0 and current == 0:
  3977. self._log_drying_cycle_end(ams_id, previous, ams_unit, self._drying_targets.pop(ams_id, None))
  3978. if self.on_drying_complete:
  3979. self.on_drying_complete(ams_id)
  3980. cycle = self._dry_cycles.pop(ams_id, None) or {"peak": previous, "start_seen": False, "target": None}
  3981. if self.on_drying_cycle_end:
  3982. self.on_drying_cycle_end(self._drying_cycle_end(ams_id, previous, cycle))
  3983. # Create a hash of relevant AMS data to detect changes.
  3984. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  3985. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  3986. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  3987. # above but leaves the raw payload's tracked fields untouched — so a
  3988. # raw-based hash never flips and on_ams_change never fires, leaving the
  3989. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  3990. # always spans every unit, so a partial single-unit update can't produce a
  3991. # spuriously different hash from a full pushall.
  3992. ams_hash_data = []
  3993. for ams_unit in merged_ams:
  3994. for tray in ams_unit.get("tray", []):
  3995. # Include fields that matter for filament tracking
  3996. ams_hash_data.append(
  3997. f"{ams_unit.get('id')}:{tray.get('id')}:"
  3998. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  3999. )
  4000. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  4001. # Only trigger callback if AMS data actually changed
  4002. if ams_hash != self._previous_ams_hash:
  4003. self._previous_ams_hash = ams_hash
  4004. if self.on_ams_change:
  4005. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  4006. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  4007. # may lack fields like 'remain' that the merged state preserves
  4008. self.on_ams_change(merged_ams)
  4009. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  4010. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  4011. # or cali_idx — so an assignment that only swaps the filament id on an
  4012. # already-loaded slot would not flip the hash, and gating the check on
  4013. # it would miss exactly the confirmation we are after.
  4014. if self._pending_assignments:
  4015. self._check_assignment_verifications()
  4016. @staticmethod
  4017. def _drying_cycle_end(ams_id: int, remaining: int, cycle: dict[str, object]) -> DryingCycleEnd:
  4018. """Build the cycle-end report from the record kept while it ran."""
  4019. target = cycle.get("target")
  4020. target_temp: int | None = None
  4021. target_hours: int | None = None
  4022. if isinstance(target, dict):
  4023. try:
  4024. target_temp = int(target.get("temp") or 0) or None
  4025. target_hours = int(target.get("duration_hours") or 0) or None
  4026. except (TypeError, ValueError):
  4027. target_temp = target_hours = None
  4028. return DryingCycleEnd(
  4029. ams_id=ams_id,
  4030. remaining_minutes=remaining,
  4031. peak_minutes=max(int(cycle.get("peak") or 0), remaining),
  4032. start_seen=bool(cycle.get("start_seen")),
  4033. target_temp=target_temp,
  4034. target_hours=target_hours,
  4035. )
  4036. def _log_drying_cycle_end(
  4037. self,
  4038. ams_id: int,
  4039. remaining: int,
  4040. ams_unit: dict,
  4041. target: dict[str, object] | None,
  4042. ) -> None:
  4043. """Report a finished drying cycle, with the firmware's reason when it was
  4044. cut short (#2770).
  4045. A cycle that reaches its configured duration needs no explanation and
  4046. keeps the one-line "drying complete" it has always had. One that ends
  4047. with most of its countdown left was ended by somebody, and there are
  4048. only two candidates: a stop Bambuddy sent — the print-takes-priority
  4049. stop, or the user's Stop button — which is named as such, or the
  4050. firmware.
  4051. For the firmware case the only account of why lives in fields we already
  4052. parse but have never written down: the ``dry_status`` /
  4053. ``dry_sub_status`` phase from the info hex, the per-unit
  4054. ``dry_sf_reason`` constraint codes, and whatever HMS errors are live at
  4055. that moment. Logging them at INFO puts them in every support bundle by
  4056. default, which is what a report like #2770 needs before its cause can be
  4057. argued about at all.
  4058. The unit's ``temp`` and ``humidity_raw`` at the moment of the end are
  4059. logged for every cycle, early or not, because they are what decides
  4060. whether auto-drying re-arms. Reconstructing them for #2770 meant
  4061. cross-referencing hourly alarm lines against 30-second scheduler debug
  4062. that was switched off at the time; one line here says it outright — a
  4063. cycle ending at 63 degC with the reading still above the threshold is
  4064. the whole shape of the re-arm loop.
  4065. """
  4066. box = f"temp={ams_unit.get('temp')} humidity={ams_humidity_percent(ams_unit)}"
  4067. if ams_id in self._drying_stops_sent:
  4068. self._drying_stops_sent.discard(ams_id)
  4069. logger.info(
  4070. "[%s] AMS %d drying stopped by Bambuddy (dry_time %d → 0, %s)",
  4071. self.serial_number,
  4072. ams_id,
  4073. remaining,
  4074. box,
  4075. )
  4076. return
  4077. if remaining <= _EARLY_DRY_END_MINUTES:
  4078. logger.info(
  4079. "[%s] AMS %d drying complete (dry_time %d → 0, %s)",
  4080. self.serial_number,
  4081. ams_id,
  4082. remaining,
  4083. box,
  4084. )
  4085. return
  4086. requested_minutes: int | None = None
  4087. if target is not None:
  4088. try:
  4089. requested_minutes = int(target.get("duration_hours") or 0) * 60 or None
  4090. except (TypeError, ValueError):
  4091. requested_minutes = None
  4092. logger.info(
  4093. "[%s] AMS %d drying ended early — %d of %s minutes still on the clock. "
  4094. "Bambuddy sent no stop command, so the firmware ended this cycle: "
  4095. "dry_status=%s dry_sub_status=%s dry_sf_reason=%s hms=%s %s",
  4096. self.serial_number,
  4097. ams_id,
  4098. remaining,
  4099. requested_minutes if requested_minutes is not None else "?",
  4100. ams_unit.get("dry_status"),
  4101. ams_unit.get("dry_sub_status"),
  4102. ams_unit.get("dry_sf_reason") or [],
  4103. [e.full_code for e in self.state.hms_errors] or "none",
  4104. box,
  4105. )
  4106. def register_assignment_verification(
  4107. self,
  4108. ams_id: int,
  4109. tray_id: int,
  4110. tray_info_idx: str,
  4111. tray_color: str,
  4112. cali_idx: int | None,
  4113. ) -> None:
  4114. """Record an assignment we just pushed so subsequent AMS telemetry can
  4115. confirm the tray actually accepted it (#2582).
  4116. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  4117. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  4118. accepted filament id back in the per-tray push, so a match means the
  4119. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  4120. signal so we can specifically flag "filament loaded but K-profile not
  4121. applied", which is the exact symptom the reporter chased via flow-cal.
  4122. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  4123. there is nothing to verify and no record is stored.
  4124. """
  4125. want_idx = (tray_info_idx or "").strip().upper()
  4126. if not want_idx:
  4127. return
  4128. self._pending_assignments[(ams_id, tray_id)] = {
  4129. "tray_info_idx": want_idx,
  4130. "tray_color": (tray_color or "").strip().upper(),
  4131. "cali_idx": cali_idx,
  4132. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  4133. "last_seen_idx": None,
  4134. }
  4135. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  4136. """Locate the live tray dict for a pending verification.
  4137. External spools (ams_id 255) live in ``vt_tray`` under global ids
  4138. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  4139. report a single tray whose id may not equal the logical tray_id, so fall
  4140. back to the sole tray when an id match fails.
  4141. """
  4142. raw = self.state.raw_data or {}
  4143. if ams_id == 255:
  4144. want_ext = external_tray_id(tray_id)
  4145. for vt in raw.get("vt_tray", []) or []:
  4146. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  4147. return vt
  4148. return None
  4149. for unit in raw.get("ams", []) or []:
  4150. if str(unit.get("id")) != str(ams_id):
  4151. continue
  4152. trays = unit.get("tray", []) or []
  4153. for tray in trays:
  4154. if str(tray.get("id")) == str(tray_id):
  4155. return tray
  4156. if ams_id >= 128 and len(trays) == 1:
  4157. return trays[0]
  4158. return None
  4159. return None
  4160. def _check_assignment_verifications(self) -> None:
  4161. """Compare each pending assignment against live tray telemetry and fire
  4162. ``on_assignment_verified`` on a match or once the deadline passes.
  4163. Runs on every AMS push. Non-matching-but-still-within-window entries are
  4164. left in place for the next push. The timeout branch only fires when a
  4165. later push arrives after the deadline; if the printer goes silent we
  4166. simply never confirm, which is preferable to inventing a failure.
  4167. """
  4168. now = time.monotonic()
  4169. for key, want in list(self._pending_assignments.items()):
  4170. ams_id, tray_id = key
  4171. tray = self._find_verify_tray(ams_id, tray_id)
  4172. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  4173. if tray is not None and actual_idx:
  4174. want["last_seen_idx"] = actual_idx
  4175. if actual_idx and actual_idx == want["tray_info_idx"]:
  4176. self._pending_assignments.pop(key, None)
  4177. kprofile_applied = True
  4178. want_cali = want.get("cali_idx")
  4179. if want_cali is not None and want_cali >= 0:
  4180. actual_cali = tray.get("cali_idx")
  4181. kprofile_applied = actual_cali == want_cali
  4182. self._fire_assignment_verified(
  4183. ams_id,
  4184. tray_id,
  4185. True,
  4186. {
  4187. "tray_info_idx": actual_idx,
  4188. "kprofile_applied": kprofile_applied,
  4189. },
  4190. )
  4191. elif now >= want["deadline"]:
  4192. self._pending_assignments.pop(key, None)
  4193. self._fire_assignment_verified(
  4194. ams_id,
  4195. tray_id,
  4196. False,
  4197. {
  4198. "expected_tray_info_idx": want["tray_info_idx"],
  4199. "actual_tray_info_idx": want.get("last_seen_idx"),
  4200. # True when we saw the tray at least once (so the push
  4201. # channel is alive and the printer really stored a
  4202. # different/blank id) vs never observing it at all.
  4203. "saw_tray": want.get("last_seen_idx") is not None,
  4204. },
  4205. )
  4206. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  4207. if verified:
  4208. logger.info(
  4209. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  4210. self.serial_number,
  4211. ams_id,
  4212. tray_id,
  4213. detail.get("tray_info_idx"),
  4214. detail.get("kprofile_applied"),
  4215. )
  4216. else:
  4217. logger.warning(
  4218. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  4219. self.serial_number,
  4220. ams_id,
  4221. tray_id,
  4222. detail.get("expected_tray_info_idx"),
  4223. detail.get("actual_tray_info_idx"),
  4224. detail.get("saw_tray"),
  4225. )
  4226. if self.on_assignment_verified:
  4227. try:
  4228. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  4229. except Exception:
  4230. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  4231. @staticmethod
  4232. def _probe_number(value, fallback: float | None = None) -> float | None:
  4233. """Coerce a telemetry field to a number, or return `fallback`.
  4234. Firmware is inconsistent about whether these arrive as ints or as
  4235. numeric strings, and the probe must never raise on a surprise type.
  4236. """
  4237. try:
  4238. return float(value)
  4239. except (TypeError, ValueError):
  4240. return fallback
  4241. def _probe_end_of_print(self, data: dict) -> None:
  4242. """Log raw end-of-print telemetry for one print at DEBUG (#2547).
  4243. Opens on the first frame that looks like end-of-print (last object
  4244. layer reached, progress at 99+, or no remaining time), then logs each
  4245. frame in which any probed field changed, and closes on the transition
  4246. out of RUNNING. Armed once per print — see the module-level comment on
  4247. ``_END_OF_PRINT_PROBE_FIELDS`` for why this window is the one we can't
  4248. currently see into.
  4249. Read-only with respect to printer state: this is instrumentation, and
  4250. nothing downstream may come to depend on it.
  4251. """
  4252. if not logger.isEnabledFor(logging.DEBUG):
  4253. return
  4254. if not self._eop_probe_open and not (self._eop_probe_armed and self._was_running):
  4255. return
  4256. present = {k: data[k] for k in _END_OF_PRINT_PROBE_FIELDS if k in data}
  4257. if not present:
  4258. return
  4259. if not self._eop_probe_open:
  4260. # Open on any end-of-print signal. Read from the raw frame first so
  4261. # the frame that *carries* the signal is itself captured — state
  4262. # fields are only updated further down this same call.
  4263. frame_layer = data.get("layer_num")
  4264. if self._is_stale_layer(frame_layer):
  4265. frame_layer = None
  4266. layer = self._probe_number(frame_layer, self.state.layer_num) or 0
  4267. total = self._probe_number(data.get("total_layer_num"), self.state.total_layers) or 0
  4268. percent = self._probe_number(data.get("mc_percent"), self.state.progress) or 0
  4269. remaining = self._probe_number(data.get("mc_remaining_time"), self.state.remaining_time)
  4270. at_last_layer = total > 0 and layer >= total
  4271. # `remaining <= 0` is only meaningful once the print has actually
  4272. # progressed — it reads 0 during the pre-print calibration too.
  4273. out_of_time = remaining is not None and remaining <= 0 and percent > 0
  4274. if not (at_last_layer or percent >= 99 or out_of_time):
  4275. return
  4276. self._eop_probe_open = True
  4277. self._eop_probe_frames = 0
  4278. self._eop_probe_last = {}
  4279. logger.debug(
  4280. "[%s] EOP-PROBE open — layer=%s/%s percent=%s remaining=%s",
  4281. self.serial_number,
  4282. layer,
  4283. total,
  4284. percent,
  4285. remaining,
  4286. )
  4287. closing = str(data.get("gcode_state") or "") in _END_OF_PRINT_PROBE_CLOSING_STATES
  4288. changed = {k: v for k, v in present.items() if self._eop_probe_last.get(k, object()) != v}
  4289. self._eop_probe_last.update(present)
  4290. if self._eop_probe_frames >= _END_OF_PRINT_PROBE_MAX_FRAMES and not closing:
  4291. if self._eop_probe_frames == _END_OF_PRINT_PROBE_MAX_FRAMES:
  4292. self._eop_probe_frames += 1
  4293. logger.debug(
  4294. "[%s] EOP-PROBE frame budget (%s) reached — suppressing until FINISH",
  4295. self.serial_number,
  4296. _END_OF_PRINT_PROBE_MAX_FRAMES,
  4297. )
  4298. return
  4299. if changed or closing:
  4300. self._eop_probe_frames += 1
  4301. logger.debug(
  4302. "[%s] EOP-PROBE %s%s: %s",
  4303. self.serial_number,
  4304. self._eop_probe_frames,
  4305. " CLOSE" if closing else "",
  4306. # `changed` on a closing frame can be empty; fall back to the
  4307. # full picture so the last line is always self-contained.
  4308. changed if changed else present,
  4309. )
  4310. if closing:
  4311. self._eop_probe_open = False
  4312. self._eop_probe_armed = False
  4313. self._eop_probe_last = {}
  4314. @property
  4315. def layer_before_new_print(self) -> int:
  4316. """The layer the printer was on when a print start was detected, until
  4317. it reports another (#3317); 0 when none.
  4318. For a print that is resumed rather than new, which a restart while it
  4319. was paused makes look new, that is the layer it is still on (#2984).
  4320. """
  4321. return self._stale_layer_num
  4322. def _is_stale_layer(self, value) -> bool:
  4323. """Whether a frame's `layer_num` is the previous print's last layer (#3317)."""
  4324. if not self._stale_layer_num:
  4325. return False
  4326. try:
  4327. return int(value) == self._stale_layer_num
  4328. except (TypeError, ValueError):
  4329. return False
  4330. def _update_state(self, data: dict):
  4331. """Update printer state from message data."""
  4332. _previous_state = self.state.state
  4333. # #2547: instrumentation only — runs before any state mutation so the
  4334. # frame carrying an end-of-print signal is logged as it arrived.
  4335. try:
  4336. self._probe_end_of_print(data)
  4337. except Exception: # pragma: no cover - a probe must never break ingest
  4338. logger.debug("[%s] EOP-PROBE failed", self.serial_number, exc_info=True)
  4339. # Update state fields
  4340. if "gcode_state" in data:
  4341. self.state.state = data["gcode_state"]
  4342. if "gcode_file" in data:
  4343. self.state.gcode_file = data["gcode_file"]
  4344. self.state.current_print = data["gcode_file"]
  4345. # The answer to a print start the printer refused names the job it
  4346. # refused, not one it runs: read as status, its job id told the start
  4347. # watchdog the file had landed.
  4348. refused_start = (
  4349. data.get("command") == "project_file"
  4350. and data.get("result") is not None
  4351. and str(data["result"]).upper() != "SUCCESS"
  4352. )
  4353. if "subtask_name" in data and not refused_start:
  4354. self.state.subtask_name = data["subtask_name"]
  4355. # Prefer subtask_name as current_print if available
  4356. if data["subtask_name"]:
  4357. self.state.current_print = data["subtask_name"]
  4358. if "subtask_id" in data and not refused_start:
  4359. self.state.subtask_id = data["subtask_id"]
  4360. if "mc_percent" in data:
  4361. # Billing: retain this frame's latest positive value immediately.
  4362. # A display-side abort may be the very next frame (and may omit
  4363. # mc_percent entirely), so retaining only the previous frame can
  4364. # lose the only usable estimate for proportional charging.
  4365. previous_progress = self.state.progress
  4366. new_progress = float(data["mc_percent"])
  4367. if new_progress > 0:
  4368. self._last_valid_progress = new_progress
  4369. self.state.progress = new_progress
  4370. # #2547: strictly-increasing only. The firmware resets progress to 0
  4371. # on cancel and re-reports the same percent on most frames; neither
  4372. # is the print advancing, and both would make the frame bank grab a
  4373. # camera frame for nothing.
  4374. if self.state.progress > previous_progress and self._was_running and self.on_print_progress:
  4375. self.on_print_progress(int(self.state.progress))
  4376. if "mc_remaining_time" in data:
  4377. self.state.remaining_time = int(data["mc_remaining_time"])
  4378. if "mc_print_sub_stage" in data:
  4379. new_sub_stage = int(data["mc_print_sub_stage"])
  4380. if new_sub_stage != self.state.mc_print_sub_stage:
  4381. logger.debug(
  4382. f"[{self.serial_number}] mc_print_sub_stage changed: "
  4383. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  4384. )
  4385. self.state.mc_print_sub_stage = new_sub_stage
  4386. # Positive `total_layer_num` carried by *this* frame, or 0. Read up
  4387. # front because three places below consult it and they run in an order
  4388. # that is not the order they read most naturally in: the layer-advance
  4389. # refresh (#2702) must not fire on a frame that already answers it, the
  4390. # apply step must ignore firmware-reset 0s (#1771), and the new-print
  4391. # reset must not discard a total that belongs to the starting print.
  4392. total_from_this_frame = 0
  4393. if "total_layer_num" in data:
  4394. try:
  4395. total_from_this_frame = max(int(data["total_layer_num"] or 0), 0)
  4396. except (TypeError, ValueError):
  4397. # Must not escape. `_on_message` catches only JSONDecodeError
  4398. # and paho is left at `suppress_exceptions = False`, so an
  4399. # exception raised here is re-raised on the network thread and
  4400. # takes the printer connection down over one unusable field.
  4401. # Treat it as "not reported": the refresh below then recovers
  4402. # the real total from a pushall.
  4403. logger.debug(
  4404. "[%s] ignoring unusable total_layer_num: %r",
  4405. self.serial_number,
  4406. data["total_layer_num"],
  4407. )
  4408. if "layer_num" in data:
  4409. try:
  4410. new_layer = int(data["layer_num"])
  4411. except (TypeError, ValueError):
  4412. # Contained for the same reason as `total_layer_num` above: an
  4413. # exception raised here escapes `_update_state` and paho
  4414. # re-raises it on the network thread. Losing this frame would
  4415. # also lose the print-start and completion detection further
  4416. # down, which is worse than losing a layer number.
  4417. #
  4418. # Held at the last known layer rather than substituted with 0:
  4419. # a fabricated 0 reads as the firmware's cancel reset, which
  4420. # would move `_last_valid_layer_num` and show layer 0 in the UI
  4421. # until the next good frame.
  4422. logger.debug(
  4423. "[%s] ignoring unusable layer_num: %r",
  4424. self.serial_number,
  4425. data["layer_num"],
  4426. )
  4427. new_layer = self.state.layer_num
  4428. if self._is_stale_layer(new_layer):
  4429. logger.debug(
  4430. "[%s] ignoring layer_num %s: last layer of the previous print",
  4431. self.serial_number,
  4432. new_layer,
  4433. )
  4434. new_layer = self.state.layer_num
  4435. elif new_layer > 0:
  4436. # The new print reports a layer of its own; from here on the
  4437. # previous print's value is a layer this print can reach.
  4438. self._stale_layer_num = 0
  4439. old_layer = self.state.layer_num
  4440. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  4441. if old_layer > 0:
  4442. self._last_valid_layer_num = old_layer
  4443. self.state.layer_num = new_layer
  4444. # Trigger layer change callback if layer increased
  4445. if new_layer > old_layer and self.on_layer_change:
  4446. self.on_layer_change(new_layer)
  4447. # #2702: the print is demonstrably laying down layers but we still
  4448. # have no denominator, so the pushall requested at print start
  4449. # either went unanswered or raced the printer learning the total.
  4450. # Ask once more — by layer 1 the printer definitely knows it.
  4451. # One-shot: an unanswered pushall must not turn into a per-layer
  4452. # retry loop for the rest of the print.
  4453. if (
  4454. new_layer > old_layer
  4455. and self._total_layers_refresh_armed
  4456. and not self.state.total_layers
  4457. and not total_from_this_frame
  4458. ):
  4459. self._total_layers_refresh_armed = False
  4460. logger.debug(
  4461. "[%s] layer %s with no total_layer_num — re-requesting full status",
  4462. self.serial_number,
  4463. new_layer,
  4464. )
  4465. self._request_push_all()
  4466. # #2547: there is deliberately NO finish-photo trigger on the
  4467. # last-layer edge. `layer_num` reaching `total_layer_num` is the
  4468. # moment the printer *starts* the final layer, not the moment it
  4469. # finishes it — on the H2C capture that closed #2547 the edge
  4470. # arrived at 92% with `mc_remaining_time=2`, three minutes and a
  4471. # filament change before the print actually ended, so the photo
  4472. # showed the toolhead mid-print over the part. Worse, the trigger
  4473. # latched `_finish_photo_captured`, locking out both the stage-22
  4474. # and FINISH triggers below for the rest of the print.
  4475. #
  4476. # #1867 (End G-code ejects the plate before FINISH) is handled
  4477. # where it belongs instead: `on_finish_photo_moment` prefers the
  4478. # in-print frame bank when the dispatcher recorded that it injected
  4479. # End G-code into this print. See services/print_dispatch_context.
  4480. if total_from_this_frame:
  4481. # Firmware (P1S observed) resets `total_layer_num` to 0 at print
  4482. # end — same shape as the `layer_num` reset guarded above. Applying
  4483. # only positive values preserves the last known good denominator so
  4484. # the usage-tracker split path (#1771) survives the reset frame.
  4485. self.state.total_layers = total_from_this_frame
  4486. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  4487. # Convert to 0-100 percentage for display
  4488. def parse_fan_speed(value: str | int | None) -> int | None:
  4489. if value is None:
  4490. return None
  4491. try:
  4492. speed = int(value)
  4493. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  4494. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  4495. if speed <= 15:
  4496. return round(speed * 100 / 15)
  4497. # If already a percentage (0-255 scale from some printers), convert
  4498. elif speed <= 255:
  4499. return round(speed * 100 / 255)
  4500. return speed
  4501. except (ValueError, TypeError):
  4502. return None
  4503. # Log fan fields once for debugging
  4504. if not hasattr(self, "_fan_fields_logged"):
  4505. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  4506. if fan_fields:
  4507. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  4508. self._fan_fields_logged = True
  4509. if "cooling_fan_speed" in data:
  4510. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  4511. if "big_fan1_speed" in data:
  4512. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  4513. if "big_fan2_speed" in data:
  4514. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  4515. if "heatbreak_fan_speed" in data:
  4516. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  4517. # Calibration stage tracking
  4518. if "stg_cur" in data:
  4519. new_stg = data["stg_cur"]
  4520. prev_stg = self.state.stg_cur
  4521. # Always log ANY stg_cur change for debugging filament operations
  4522. if new_stg != prev_stg:
  4523. logger.debug(
  4524. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  4525. )
  4526. # A stage we cannot name is the one worth seeing at the default
  4527. # log level: the DEBUG line above is off in normal running, so
  4528. # an unnamed stage otherwise reaches the user as "Unknown stage
  4529. # (72)" on a card with nothing behind it to say when it
  4530. # happened or what the printer was doing. Recorded once per
  4531. # stage number per session, with the stage it came from and the
  4532. # print state, which is what naming it later needs. Guarded on
  4533. # the int type because the field is whatever the firmware sent.
  4534. if (
  4535. isinstance(new_stg, int)
  4536. and not isinstance(new_stg, bool)
  4537. # -1 is Bambuddy's own "not in a stage" sentinel and the
  4538. # initial value of the field, not something the firmware
  4539. # reports; every print would otherwise report it on the way
  4540. # out of its last real stage.
  4541. and new_stg != -1
  4542. and new_stg not in STAGE_NAMES
  4543. and new_stg not in self._unnamed_stages_seen
  4544. ):
  4545. self._unnamed_stages_seen.add(new_stg)
  4546. logger.info(
  4547. "[%s] Unnamed print stage %s on model %s, entered from %s (%s); "
  4548. "state=%s progress=%s%% layer=%s/%s",
  4549. self.serial_number,
  4550. new_stg,
  4551. self.model,
  4552. prev_stg,
  4553. get_stage_name(prev_stg),
  4554. self.state.state,
  4555. self.state.progress,
  4556. self.state.layer_num,
  4557. self.state.total_layers,
  4558. )
  4559. self.state.stg_cur = new_stg
  4560. # #1721 end-of-print finish photo trigger.
  4561. # Stage 22 = "Filament unloading" fires at end-of-print AND
  4562. # during mid-print color swaps. The end-of-print gate
  4563. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  4564. # — those signals only line up at the real end. Edge-only
  4565. # (prev != 22) so the trigger fires once per stage entry.
  4566. if (
  4567. new_stg == 22
  4568. and prev_stg != 22
  4569. and self._was_running
  4570. and not self._finish_photo_captured
  4571. and self.on_finish_photo_moment
  4572. ):
  4573. progress = self.state.progress or 0.0
  4574. layer_num = self.state.layer_num or 0
  4575. total_layers = self.state.total_layers or 0
  4576. remaining = self.state.remaining_time or 0
  4577. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  4578. if is_end_of_print:
  4579. self._finish_photo_captured = True
  4580. logger.info(
  4581. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  4582. f"progress={progress}, layer={layer_num}/{total_layers}, "
  4583. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  4584. )
  4585. self.on_finish_photo_moment(
  4586. {
  4587. "trigger": "stage_22",
  4588. "filename": self._previous_gcode_file or self.state.gcode_file,
  4589. "subtask_name": self.state.subtask_name,
  4590. "timelapse_was_active": self._timelapse_during_print,
  4591. }
  4592. )
  4593. if "stg" in data:
  4594. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  4595. # Temperature data
  4596. temps = {}
  4597. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  4598. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  4599. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  4600. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  4601. # Log ALL keys in print data for H2D temperature discovery
  4602. all_keys = sorted(data.keys())
  4603. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  4604. self._temp_fields_logged = True
  4605. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  4606. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  4607. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  4608. self._vir_slot_logged = True
  4609. # Log nozzle hardware info fields (once)
  4610. nozzle_fields = {
  4611. k: v
  4612. for k, v in data.items()
  4613. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  4614. }
  4615. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  4616. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  4617. self._nozzle_fields_logged = True
  4618. # Parse active extruder from device.extruder.state bit 8
  4619. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  4620. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  4621. if "device" in data and isinstance(data.get("device"), dict):
  4622. device = data["device"]
  4623. # One-shot identification probe: surface whatever the firmware uses to
  4624. # name itself so an unknown model in a support bundle becomes self-
  4625. # diagnosing. INFO level so it shows up without debug logging. Falls
  4626. # back to dumping device.keys() if none of the known fields are present
  4627. # (so a future Bambu rename like `model_name` is still observable).
  4628. if not getattr(self, "_device_id_logged", False):
  4629. id_fields = {
  4630. k: device.get(k)
  4631. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  4632. if k in device
  4633. }
  4634. if id_fields:
  4635. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  4636. else:
  4637. logger.info(
  4638. "[%s] Device identification: no known id fields; device.keys=%s",
  4639. self.serial_number,
  4640. sorted(device.keys()),
  4641. )
  4642. self._device_id_logged = True
  4643. self._parse_extruder_position(data)
  4644. # Log device.extruder structure for active extruder
  4645. if "device" in data and isinstance(data.get("device"), dict):
  4646. device = data["device"]
  4647. if "extruder" in device:
  4648. ext_data = device["extruder"]
  4649. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  4650. if "state" in ext_data:
  4651. state_val = ext_data["state"]
  4652. # Extract bits 12-14 (3 bits) for switch state
  4653. switch_state = (state_val >> 12) & 0x7
  4654. self._debug_on_change(
  4655. "extruder_state",
  4656. state_val,
  4657. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  4658. self.serial_number,
  4659. state_val,
  4660. switch_state,
  4661. )
  4662. # Log 'cur' field if present (might indicate current/active extruder)
  4663. if "cur" in ext_data:
  4664. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  4665. # Also parsed earlier in _process_message, because _handle_ams_data needs
  4666. # it first. Repeated here so _update_state stays a complete "absorb this
  4667. # payload" step for any other caller; re-parsing the same block is free.
  4668. self._parse_fila_switch(data)
  4669. self._parse_extruder_slots(data)
  4670. if "bed_temper" in data:
  4671. temps["bed"] = float(data["bed_temper"])
  4672. if "bed_target_temper" in data:
  4673. temps["bed_target"] = float(data["bed_target_temper"])
  4674. # Check if this is H2D (has device.extruder.info with 2 extruders)
  4675. has_h2d_extruder_info = (
  4676. "device" in data
  4677. and isinstance(data.get("device"), dict)
  4678. and "extruder" in data["device"]
  4679. and isinstance(data["device"]["extruder"].get("info"), list)
  4680. and len(data["device"]["extruder"]["info"]) >= 2
  4681. )
  4682. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  4683. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  4684. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  4685. if "nozzle_temper" in data:
  4686. if has_h2d_extruder_info:
  4687. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  4688. else:
  4689. temps["nozzle"] = float(data["nozzle_temper"])
  4690. if "nozzle_target_temper" in data:
  4691. if has_h2d_extruder_info:
  4692. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  4693. else:
  4694. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  4695. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  4696. if not has_h2d_extruder_info:
  4697. # Try multiple possible field names used by different firmware versions
  4698. if "nozzle_temper_2" in data:
  4699. val = float(data["nozzle_temper_2"])
  4700. if -50 < val < 500: # Valid temp range
  4701. temps["nozzle_2"] = val
  4702. else:
  4703. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  4704. elif "right_nozzle_temper" in data:
  4705. val = float(data["right_nozzle_temper"])
  4706. if -50 < val < 500: # Valid temp range
  4707. temps["nozzle_2"] = val
  4708. else:
  4709. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  4710. if "nozzle_target_temper_2" in data:
  4711. val = float(data["nozzle_target_temper_2"])
  4712. if 0 <= val < 500: # Valid temp range
  4713. temps["nozzle_2_target"] = val
  4714. else:
  4715. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  4716. elif "right_nozzle_target_temper" in data:
  4717. val = float(data["right_nozzle_target_temper"])
  4718. if 0 <= val < 500: # Valid temp range
  4719. temps["nozzle_2_target"] = val
  4720. else:
  4721. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  4722. # Also check for left nozzle as primary (some H2 models)
  4723. if "left_nozzle_temper" in data and "nozzle" not in temps:
  4724. temps["nozzle"] = float(data["left_nozzle_temper"])
  4725. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  4726. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  4727. if "chamber_temper" in data:
  4728. chamber_val = float(data["chamber_temper"])
  4729. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  4730. # Check if we recently set the target locally (within 5 seconds)
  4731. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4732. respect_local = (time.time() - local_set_time) < 5.0
  4733. # H2D protocol: chamber_temper encoding indicates heater state
  4734. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4735. # - When < 500: direct Celsius current temp only - heater is OFF
  4736. if -50 < chamber_val < 100:
  4737. # Direct value = heater is OFF
  4738. temps["chamber"] = chamber_val
  4739. if not respect_local:
  4740. temps["chamber_target"] = 0.0 # Heater off means target = 0
  4741. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  4742. else:
  4743. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  4744. # Try to decode if it looks like an encoded value
  4745. if chamber_val > 500:
  4746. mqtt_target = int(chamber_val) // 65536
  4747. current = int(chamber_val) % 65536
  4748. logger.debug(
  4749. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  4750. )
  4751. if -50 < current < 100:
  4752. temps["chamber"] = float(current)
  4753. # Store decoded target for later use, but DON'T set chamber_heating here!
  4754. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  4755. # which is the authoritative source the slicer uses.
  4756. if not respect_local:
  4757. if 0 <= mqtt_target <= 60:
  4758. # Store as "decoded" target - may be overridden by explicit target fields
  4759. temps["_chamber_decoded_target"] = float(mqtt_target)
  4760. # Chamber target temperature (set by print file or display)
  4761. if "mc_target_cham" in data:
  4762. mc_target = float(data["mc_target_cham"])
  4763. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  4764. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  4765. if 0 <= mc_target <= 60:
  4766. temps["chamber_target"] = mc_target
  4767. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  4768. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  4769. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  4770. try:
  4771. if "info" in data and isinstance(data["info"], dict):
  4772. info_temp = data["info"].get("temp")
  4773. if info_temp is not None and "chamber" not in temps:
  4774. # Check for encoded value (target * 65536 + current)
  4775. if info_temp > 500:
  4776. # Decode: extract current temperature and target
  4777. target = info_temp // 65536
  4778. current = info_temp % 65536
  4779. temps["chamber"] = float(current)
  4780. # Store decoded target as fallback (may be overridden by ctc.info.target)
  4781. if "_chamber_decoded_target" not in temps:
  4782. temps["_chamber_decoded_target"] = float(target)
  4783. logger.debug(
  4784. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  4785. )
  4786. elif -50 < info_temp < 100:
  4787. # Valid direct temperature - heater is OFF
  4788. temps["chamber"] = float(info_temp)
  4789. temps["chamber_target"] = 0.0 # Direct value means heater off
  4790. self._debug_on_change(
  4791. "info_temp_direct",
  4792. info_temp,
  4793. "[%s] info.temp direct: %s°C (heater OFF)",
  4794. self.serial_number,
  4795. info_temp,
  4796. )
  4797. # H2D series: Dual extruder temps are in device.extruder.info array
  4798. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  4799. if "device" in data and isinstance(data["device"], dict):
  4800. device = data["device"]
  4801. # Parse dual extruder temperatures
  4802. extruder_data = device.get("extruder", {})
  4803. extruder_info = extruder_data.get("info", [])
  4804. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  4805. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  4806. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  4807. # has_h2d_extruder_info requires len(extruder_info) >= 2
  4808. if has_h2d_extruder_info:
  4809. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  4810. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  4811. if "temp" in extruder_info[0]:
  4812. temp_val = extruder_info[0]["temp"]
  4813. if temp_val > 500:
  4814. # Encoded format: temp = target * 65536 + current
  4815. target = temp_val // 65536
  4816. current = temp_val % 65536
  4817. if -50 < current < 500:
  4818. temps["nozzle_2"] = float(current)
  4819. if 0 < target < 500:
  4820. temps["nozzle_2_target"] = float(target)
  4821. temps["nozzle_2_heating"] = target > 0 and current < target
  4822. elif -50 < temp_val < 500:
  4823. # Direct Celsius value = heater is OFF
  4824. temps["nozzle_2"] = float(temp_val)
  4825. temps["nozzle_2_target"] = 0.0
  4826. temps["nozzle_2_heating"] = False
  4827. # Left nozzle (extruder 1) - only for dual nozzle printers
  4828. # H2D protocol: temp field encoding depends on value
  4829. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  4830. # - When < 500: direct Celsius current temp only - heater is OFF
  4831. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  4832. ext1 = extruder_info[1]
  4833. temp_val = ext1["temp"]
  4834. # Check if we recently set the target locally (within 5 seconds)
  4835. # If so, don't let MQTT data overwrite it
  4836. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  4837. respect_local_target = (time.time() - local_set_time) < 5.0
  4838. if temp_val > 500:
  4839. # Encoded format: temp = target * 65536 + current
  4840. target = temp_val // 65536
  4841. current = temp_val % 65536
  4842. if 0 < target < 500 and not respect_local_target:
  4843. temps["nozzle_target"] = float(target)
  4844. if -50 < current < 500:
  4845. temps["nozzle"] = float(current)
  4846. # Heating = encoded AND we're using the MQTT target (not local override)
  4847. # If local target is being respected, use local target to determine heating
  4848. if respect_local_target:
  4849. local_target = self.state.temperatures.get("nozzle_target", 0)
  4850. temps["nozzle_heating"] = local_target > 0 and current < local_target
  4851. else:
  4852. temps["nozzle_heating"] = target > 0 and current < target
  4853. elif -50 < temp_val < 500:
  4854. # Direct Celsius = heater is OFF (or at target with heater off)
  4855. temps["nozzle"] = float(temp_val)
  4856. if not respect_local_target:
  4857. temps["nozzle_target"] = 0.0
  4858. temps["nozzle_heating"] = False # Direct = not heating
  4859. # The extruder snow is read by _parse_extruder_position, before the
  4860. # AMS block of the same frame (tray_now resolution needs it first).
  4861. # Parse bed heating state from device.bed.info.temp encoding
  4862. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  4863. bed_data = device.get("bed", {})
  4864. bed_info = bed_data.get("info", {})
  4865. if "temp" in bed_info:
  4866. temp_val = bed_info["temp"]
  4867. if temp_val > 500:
  4868. target = temp_val // 65536
  4869. current = temp_val % 65536
  4870. temps["bed_heating"] = target > 0 and current < target
  4871. else:
  4872. temps["bed_heating"] = False
  4873. # Parse chamber temp from device.ctc.info.temp if not already set
  4874. ctc_data = device.get("ctc", {})
  4875. ctc_info = ctc_data.get("info", {})
  4876. # Parse airduct mode (0=cooling, 1=heating)
  4877. airduct_data = device.get("airduct", {})
  4878. if "modeCur" in airduct_data:
  4879. new_mode = airduct_data["modeCur"]
  4880. if new_mode != self.state.airduct_mode:
  4881. logger.debug(
  4882. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  4883. )
  4884. self.state.airduct_mode = new_mode
  4885. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  4886. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  4887. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  4888. # AIR_FUN enum: 1=part cooling, 2=aux, 3=chamber/exhaust,
  4889. # 10=second aux (FAN_REMOTE_COOLING_1). Aux 2 is the right fan and
  4890. # 10 the left on the P2S, the other way round on the X2D (#3373;
  4891. # Bambu Studio's N7.json / N6.json). The airduct `parts` list only
  4892. # contains the fans that physically exist, so it doubles as a
  4893. # presence signal for the two P2S/X2D add-on kits:
  4894. # - id 10 (second auxiliary part cooling fan) — reported ONLY here,
  4895. # never mirrored into a flat big_fanX_speed field.
  4896. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  4897. # big_fan2_speed, but the part is only listed when the External
  4898. # Exhaust Fan kit (get_version module "eef") is installed.
  4899. # `state` is already a 0-100 percentage.
  4900. parts = airduct_data.get("parts")
  4901. if isinstance(parts, list):
  4902. speeds: dict[int, int] = {}
  4903. for part in parts:
  4904. if not isinstance(part, dict):
  4905. continue
  4906. try:
  4907. # Studio reads the id with get_flag_bits(id, 4, 8),
  4908. # so mask after shifting for the same reason `state`
  4909. # is masked below. Every id seen in the wild
  4910. # (16/32/48/160) decodes identically either way —
  4911. # this is consistency, not a live bug.
  4912. part_id = (int(part["id"]) >> 4) & 0xFF
  4913. # `state` is bit-packed like its sibling `range`
  4914. # (end << 16 | start), so take only the low 8 bits —
  4915. # the same decode Bambu Studio does with
  4916. # get_flag_bits(state, 0, 8). Without the mask a
  4917. # packed value would clamp to 100 instead of
  4918. # decoding to the real percentage.
  4919. part_state = int(part["state"]) & 0xFF
  4920. except (KeyError, ValueError, TypeError):
  4921. continue
  4922. # Ids seen across the support-package archive:
  4923. # 1 part cooling, 2 aux, 3 chamber/exhaust,
  4924. # 6 (H2 series, unmapped), 10 second aux.
  4925. speeds[part_id] = max(0, min(100, part_state))
  4926. # Absence in this list is what tells us a kit is NOT fitted,
  4927. # so it may only be trusted when the list is a full
  4928. # inventory rather than a diff frame. `device.airduct` is
  4929. # pushed field by field — the `modeCur` handler above exists
  4930. # for exactly that reason — and a truncated `parts` read as
  4931. # gospel would retract both accessory badges mid-print and
  4932. # start rejecting `aux2` on a printer that has the fan.
  4933. #
  4934. # Every airduct layout in the support-package archive
  4935. # (P2S base 1,2 / P2S+kit 1,2,3 / X2D 1,2,3,10 /
  4936. # H2C,H2D,H2S 1,2,3,6 — 37 of 37 bundles) contains both the
  4937. # part cooling fan and the aux fan, neither of which is
  4938. # optional on any machine that reports an airduct at all.
  4939. # A list carrying both is therefore a complete inventory; a
  4940. # list missing either is a partial frame, and we take its
  4941. # speeds without touching presence.
  4942. is_full_inventory = 1 in speeds and 2 in speeds
  4943. left_aux_speed = speeds.get(10)
  4944. if left_aux_speed is None and not is_full_inventory:
  4945. # Partial frame that didn't mention the second aux fan —
  4946. # keep whatever we already knew about it.
  4947. left_aux_speed = self.state.left_aux_fan_speed
  4948. if left_aux_speed != self.state.left_aux_fan_speed:
  4949. logger.debug(
  4950. f"[{self.serial_number}] left_aux_fan_speed changed: "
  4951. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  4952. )
  4953. # A FULL parts list without id 10 means the second aux fan is
  4954. # not installed — report None so the UI can hide the widget.
  4955. self.state.left_aux_fan_speed = left_aux_speed
  4956. # id 3 present == chamber exhaust fan installed (base P2S
  4957. # omits it). Only ever retracted on a full inventory.
  4958. if 3 in speeds:
  4959. self.state.exhaust_fan_present = True
  4960. elif is_full_inventory:
  4961. self.state.exhaust_fan_present = False
  4962. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  4963. # Check if we recently set the target locally (within 5 seconds)
  4964. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  4965. respect_local_target = (time.time() - local_set_time) < 5.0
  4966. # Log ctc_info contents for debugging
  4967. if ctc_info:
  4968. self._debug_on_change(
  4969. "ctc_info_keys",
  4970. tuple(ctc_info.keys()),
  4971. "[%s] ctc_info keys: %s",
  4972. self.serial_number,
  4973. list(ctc_info.keys()),
  4974. )
  4975. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  4976. # (what the slicer shows). This OVERRIDES any previously decoded target.
  4977. explicit_target = None
  4978. if "target" in ctc_info:
  4979. target_val = ctc_info["target"]
  4980. logger.debug(
  4981. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  4982. )
  4983. # Filter out invalid values (valid chamber target is 0-60°C)
  4984. if 0 <= target_val <= 60 and not respect_local_target:
  4985. explicit_target = float(target_val)
  4986. temps["chamber_target"] = explicit_target # Override any previous value
  4987. logger.debug(
  4988. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  4989. )
  4990. # Parse chamber temp from ctc.info.temp - may be encoded
  4991. if "temp" in ctc_info and "chamber" not in temps:
  4992. temp_val = ctc_info["temp"]
  4993. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  4994. if temp_val > 500:
  4995. # Encoded value: decode target and current
  4996. decoded_target = temp_val // 65536
  4997. current = temp_val % 65536
  4998. temps["chamber"] = float(current)
  4999. logger.debug(
  5000. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  5001. )
  5002. # Determine which target to use for heating state:
  5003. # Priority: local target > explicit target > decoded target
  5004. if respect_local_target:
  5005. local_target = self.state.temperatures.get("chamber_target", 0)
  5006. temps["chamber_heating"] = local_target > 0 and current < local_target
  5007. elif explicit_target is not None:
  5008. # Use explicit ctc.info.target - this is what slicer sees
  5009. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  5010. else:
  5011. # Fallback to decoded target only if no explicit target available
  5012. if not respect_local_target and "chamber_target" not in temps:
  5013. temps["chamber_target"] = float(decoded_target)
  5014. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  5015. else:
  5016. # Direct value (not encoded) - heater is OFF
  5017. temps["chamber"] = float(temp_val)
  5018. temps["chamber_heating"] = False
  5019. except Exception as e:
  5020. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  5021. if temps:
  5022. # Handle chamber_target: prefer explicit over decoded
  5023. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  5024. # No explicit target available, use decoded target from chamber_temper
  5025. temps["chamber_target"] = temps["_chamber_decoded_target"]
  5026. # Remove internal temp key before merging
  5027. temps.pop("_chamber_decoded_target", None)
  5028. # Merge new temps into existing, preserving valid values when new ones are filtered out
  5029. for key, value in temps.items():
  5030. self.state.temperatures[key] = value
  5031. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  5032. if "bed" in temps and self.on_bed_temp_update:
  5033. self.on_bed_temp_update(temps["bed"])
  5034. # Calculate chamber_heating after all targets are known
  5035. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  5036. if "chamber" in temps and "chamber_heating" not in temps:
  5037. current = self.state.temperatures.get("chamber", 0)
  5038. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  5039. respect_local = (time.time() - local_set_time) < 5.0
  5040. if respect_local:
  5041. # Use locally-set target
  5042. target = self.state.temperatures.get("chamber_target", 0)
  5043. else:
  5044. # Use explicit/decoded target from MQTT
  5045. target = self.state.temperatures.get("chamber_target", 0)
  5046. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  5047. self._debug_on_change(
  5048. "chamber_heating",
  5049. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  5050. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  5051. self.serial_number,
  5052. target,
  5053. current,
  5054. self.state.temperatures["chamber_heating"],
  5055. respect_local,
  5056. )
  5057. # Debug: log chamber value if it was updated
  5058. if "chamber" in temps:
  5059. self._debug_on_change(
  5060. "chamber_temp",
  5061. (
  5062. self.state.temperatures.get("chamber"),
  5063. self.state.temperatures.get("chamber_target"),
  5064. self.state.temperatures.get("chamber_heating"),
  5065. ),
  5066. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  5067. self.serial_number,
  5068. self.state.temperatures.get("chamber"),
  5069. self.state.temperatures.get("chamber_target"),
  5070. self.state.temperatures.get("chamber_heating"),
  5071. )
  5072. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  5073. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  5074. if "nozzle" in temps and "nozzle_heating" not in temps:
  5075. current = self.state.temperatures.get("nozzle", 0)
  5076. target = self.state.temperatures.get("nozzle_target", 0)
  5077. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  5078. # Parse HMS (Health Management System) errors
  5079. if "hms" in data:
  5080. hms_list = data["hms"]
  5081. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  5082. # A `print_error` fault is not in `hms[]` and its field only comes
  5083. # when it changes, so a list rebuilt from `hms[]` keeps it (#3487).
  5084. print_error_entries = [e for e in self.state.hms_errors if _is_print_error_entry(e)]
  5085. self.state.hms_errors = []
  5086. verify_failed = False
  5087. if isinstance(hms_list, list):
  5088. for hms in hms_list:
  5089. if isinstance(hms, dict):
  5090. # HMS format: {"attr": attribute_code, "code": error_code}
  5091. # attr contains module/severity info, code contains error number
  5092. # Both are needed to construct the wiki URL
  5093. attr = hms.get("attr", 0)
  5094. code = hms.get("code", 0)
  5095. if isinstance(attr, str):
  5096. attr = int(attr.replace("0x", ""), 16) if attr else 0
  5097. if isinstance(code, str):
  5098. code = int(code.replace("0x", ""), 16) if code else 0
  5099. # attr is module, module no., part, part no. (a byte each);
  5100. # code is the alert level (high 16 bits) then the error
  5101. # (low 16). The level is 1 error (task stopped), 2 warning
  5102. # (task paused), 3 notification; 0 is invalid. This is how
  5103. # Bambu Studio decodes it (DevHMSItem::parse_hms_info). It
  5104. # used to be read from attr bits 8-15, which is the part
  5105. # byte (#2728).
  5106. severity = (code >> 16) & 0xFFFF
  5107. # Module is in attr byte 3 (bits 24-31)
  5108. module = (attr >> 24) & 0xFF
  5109. # Skip non-error status codes. A real fault has a level of
  5110. # at least 1 in the high half, so its code is >= 0x10000
  5111. # and clears this; lower values are status/phase
  5112. # indicators some firmware sends during normal printing.
  5113. if code < 0x4000:
  5114. continue
  5115. # Skip user-action echoes — the printer firmware emits these
  5116. # as part of normal user-cancel sequences. They're not faults
  5117. # and shouldn't count toward "X problem" badges or surface as
  5118. # red pips on the printer card. Backend's notification path
  5119. # already suppresses 0500_400E for the same reason.
  5120. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  5121. if short_code in _HMS_USER_ACTION_CODES:
  5122. continue
  5123. # The full 16-char identifier is the firmware's matching key
  5124. # and the HMS catalogue's key for this kind of fault; the
  5125. # short code discards the part and alert-level groups. The
  5126. # action table still has some short-form entries, so that
  5127. # lookup falls back to it.
  5128. full_code = f"{attr:08X}{code:08X}"
  5129. if full_code == HMS_MQTT_VERIFY_FAILED:
  5130. verify_failed = True
  5131. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  5132. if not actions:
  5133. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5134. self.state.hms_errors.append(
  5135. HMSError(
  5136. code=f"0x{code:x}" if code else "0x0",
  5137. attr=attr,
  5138. module=module,
  5139. # No fallback: 0 is Bambu's "invalid" level, and
  5140. # promoting it would render it as a fault.
  5141. severity=severity,
  5142. actions=actions,
  5143. job_id=self.state.subtask_id,
  5144. full_code=full_code,
  5145. description=describe_fault(full_code, self.serial_number[:3]),
  5146. )
  5147. )
  5148. hms_short_codes = _hms_short_codes(self.state.hms_errors)
  5149. self.state.hms_errors.extend(e for e in print_error_entries if _hms_short_code(e) not in hms_short_codes)
  5150. self._apply_mqtt_verify_state(verify_failed)
  5151. # Parse print_error - this is a different error format than HMS
  5152. # print_error is a 32-bit integer where:
  5153. # - High 16 bits contain module info (e.g., 0x0500)
  5154. # - Low 16 bits contain error code (e.g., 0x8061)
  5155. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  5156. if "print_error" in data:
  5157. print_error = data["print_error"]
  5158. # The field holds the one current fault, and 0 once it is resolved,
  5159. # for example when the filament-load prompt is answered on the
  5160. # printer. The entry of a code that is no longer reported goes
  5161. # (#3487); the entry of the same code is kept as it is.
  5162. self.state.hms_errors = [
  5163. e for e in self.state.hms_errors if not _is_print_error_entry(e) or e.attr == print_error
  5164. ]
  5165. if print_error and print_error != 0:
  5166. # Extract components: MMMMEEEE -> MMMM_EEEE
  5167. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  5168. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  5169. # Values below 0x4000 are status/phase indicators, not real errors.
  5170. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  5171. # Some firmware sends low values like 0x0002 during normal printing.
  5172. if error < 0x4000:
  5173. pass # Skip — not a real error
  5174. else:
  5175. # Store in a format that matches the community error database
  5176. # attr stores the full 32-bit value for reconstruction
  5177. # code stores the short format string for lookup
  5178. short_code = f"{module:04X}_{error:04X}"
  5179. logger.debug(
  5180. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  5181. )
  5182. # Same user-action filter as the hms[] branch above — print_error
  5183. # carries the same cancel echoes (e.g. 0500_400E) and they must
  5184. # not surface as faults on the printer card.
  5185. if short_code in _HMS_USER_ACTION_CODES:
  5186. pass # cancel echo — silently drop
  5187. else:
  5188. # Only add if not already in HMS errors (avoid duplicates)
  5189. if short_code not in _hms_short_codes(self.state.hms_errors):
  5190. # Bambu's HMS catalog keys by 3-letter device code (the SN
  5191. # prefix) and a 16-char short error code without the
  5192. # underscore separator we store internally.
  5193. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  5194. # Bambu pushes the current job as `subtask_id` on the
  5195. # state stream; the HMS-action commands echo it back as
  5196. # `job_id`. The error payload itself doesn't carry the
  5197. # id, so snapshot it from the live state at parse time
  5198. # and freeze it on the HMSError so subsequent
  5199. # job changes don't invalidate the action.
  5200. job_id = self.state.subtask_id
  5201. logger.debug(
  5202. "[%s, %s] HMS available actions: %s (job_id=%s)",
  5203. self.serial_number[:3],
  5204. short_code.replace("_", ""),
  5205. actions,
  5206. job_id,
  5207. )
  5208. self.state.hms_errors.append(
  5209. HMSError(
  5210. code=f"0x{error:x}",
  5211. attr=print_error, # Store full value for display
  5212. module=module >> 8, # High byte of module (e.g., 0x05)
  5213. # print_error has no level field; its error
  5214. # number's first digit carries it instead.
  5215. severity=alert_level_from_print_error(error),
  5216. actions=actions,
  5217. job_id=job_id,
  5218. # print_error is already 32-bit — `f"{print_error:08X}"`
  5219. # is the firmware's matching key with no truncation.
  5220. full_code=f"{print_error:08X}",
  5221. description=describe_fault(f"{print_error:08X}", self.serial_number[:3]),
  5222. )
  5223. )
  5224. # Parse home_flag first so SD-card detection below can prefer it.
  5225. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  5226. # bit 23 = door-open (X1 family only).
  5227. home_flag = None
  5228. if "home_flag" in data:
  5229. home_flag = data["home_flag"]
  5230. if home_flag < 0:
  5231. home_flag = home_flag & 0xFFFFFFFF
  5232. # SD card presence: the only remaining consumer is the firmware-update
  5233. # precondition check (firmware_update.py). Use the top-level `sdcard`
  5234. # field when present with a permissive truthy check covering the
  5235. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  5236. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  5237. # when a card is inserted, which caused the badge to flap before the
  5238. # badge was removed entirely.
  5239. if "sdcard" in data:
  5240. raw_sdcard = data["sdcard"]
  5241. if isinstance(raw_sdcard, str):
  5242. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  5243. else:
  5244. self.state.sdcard = bool(raw_sdcard)
  5245. self.state.sdcard_reported = True
  5246. if home_flag is not None:
  5247. store_to_sdcard = bool((home_flag >> 11) & 1)
  5248. if store_to_sdcard != self.state.store_to_sdcard:
  5249. logger.debug(
  5250. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  5251. )
  5252. self.state.store_to_sdcard = store_to_sdcard
  5253. # Door open detection — source depends on printer family:
  5254. # X1 series (X1, X1C, X1E): home_flag bit 23
  5255. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  5256. # Both share the same bitmask (0x00800000) but live in different fields.
  5257. model_upper = (self.model or "").upper().strip()
  5258. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  5259. if is_x1_family and home_flag is not None:
  5260. door_open = (home_flag & 0x00800000) != 0
  5261. if door_open != self.state.door_open:
  5262. logger.debug(
  5263. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  5264. self.serial_number,
  5265. self.state.door_open,
  5266. door_open,
  5267. home_flag,
  5268. )
  5269. self.state.door_open = door_open
  5270. elif not is_x1_family and "stat" in data:
  5271. try:
  5272. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  5273. door_open = (stat_value & 0x00800000) != 0
  5274. if door_open != self.state.door_open:
  5275. logger.debug(
  5276. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  5277. self.serial_number,
  5278. self.state.door_open,
  5279. door_open,
  5280. stat_value,
  5281. )
  5282. self.state.door_open = door_open
  5283. except (ValueError, TypeError):
  5284. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  5285. # Parse timelapse status (recording active during print). Status frames
  5286. # only — the project_file ack echoes back the per-job timelapse flag we
  5287. # asked for, which is a request, not the recorder's state (#3040).
  5288. if "timelapse" in data and is_printer_status_frame(data):
  5289. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  5290. self.state.timelapse = data["timelapse"] is True
  5291. # Track if timelapse was ever active during this print
  5292. if self.state.timelapse and self._was_running:
  5293. self._timelapse_during_print = True
  5294. # Parse ipcam/live view status
  5295. if "ipcam" in data:
  5296. ipcam_data = data["ipcam"]
  5297. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  5298. if isinstance(ipcam_data, dict):
  5299. # Check ipcam_record field for live view status
  5300. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  5301. # Check timelapse field (H2D sends it here, not in xcam)
  5302. if "timelapse" in ipcam_data:
  5303. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  5304. if timelapse_enabled != self.state.timelapse:
  5305. logger.debug(
  5306. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  5307. )
  5308. self.state.timelapse = timelapse_enabled
  5309. # Track if timelapse was ever active during this print
  5310. if self.state.timelapse and self._was_running:
  5311. self._timelapse_during_print = True
  5312. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  5313. else:
  5314. self.state.ipcam = ipcam_data is True
  5315. # Parse WiFi signal strength (dBm)
  5316. if "wifi_signal" in data:
  5317. wifi_signal = data["wifi_signal"]
  5318. self._debug_on_change(
  5319. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  5320. )
  5321. if isinstance(wifi_signal, (int, float)):
  5322. self.state.wifi_signal = int(wifi_signal)
  5323. elif isinstance(wifi_signal, str):
  5324. # Handle string format like "-52dBm"
  5325. try:
  5326. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  5327. except ValueError:
  5328. pass # Ignore unparseable wifi_signal strings; field is non-critical
  5329. # Detect ethernet connection: printers on ethernet with WiFi disabled
  5330. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  5331. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  5332. from backend.app.utils.printer_models import has_ethernet
  5333. if has_ethernet(self.model):
  5334. self.state.wired_network = self.state.wifi_signal == -90
  5335. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5336. if "spd_lvl" in data:
  5337. new_speed = data["spd_lvl"]
  5338. if new_speed != self.state.speed_level:
  5339. logger.debug(
  5340. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  5341. )
  5342. self.state.speed_level = new_speed
  5343. # Parse skipped objects from printer status (s_obj field)
  5344. # This allows us to restore skipped objects state after reconnection
  5345. if "s_obj" in data:
  5346. s_obj = data["s_obj"]
  5347. if isinstance(s_obj, list):
  5348. # Update skipped objects from printer's list
  5349. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  5350. if new_skipped != self.state.skipped_objects:
  5351. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  5352. self.state.skipped_objects = new_skipped
  5353. for oid in new_skipped:
  5354. self._unconfirmed_skips.pop(oid, None)
  5355. self._check_unconfirmed_skips()
  5356. # Parse chamber light status from lights_report
  5357. if "lights_report" in data:
  5358. lights = data["lights_report"]
  5359. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  5360. if isinstance(lights, list):
  5361. for light in lights:
  5362. if isinstance(light, dict) and light.get("node") == "chamber_light":
  5363. new_light_state = light.get("mode") == "on"
  5364. if new_light_state != self.state.chamber_light:
  5365. logger.debug(
  5366. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  5367. )
  5368. self.state.chamber_light = new_light_state
  5369. break
  5370. # Parse nozzle hardware info (single nozzle printers)
  5371. if "nozzle_type" in data:
  5372. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  5373. if "nozzle_diameter" in data:
  5374. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  5375. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  5376. # Left nozzle
  5377. if "left_nozzle_type" in data:
  5378. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  5379. if "left_nozzle_diameter" in data:
  5380. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  5381. # Right nozzle
  5382. if "right_nozzle_type" in data:
  5383. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  5384. if "right_nozzle_diameter" in data:
  5385. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  5386. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  5387. if "nozzle_type_2" in data:
  5388. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  5389. if "nozzle_diameter_2" in data:
  5390. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  5391. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  5392. if "device" in data and isinstance(data["device"], dict):
  5393. device = data["device"]
  5394. nozzle_data = device.get("nozzle", {})
  5395. # H2C rack position (#2800). `tar_id` is where the carriage is
  5396. # headed, `src_id` where it came from; mid-swap they differ, so
  5397. # dispatch prefers tar_id and falls back to src_id. Both are
  5398. # sticky — the field is only pushed when it changes, so an
  5399. # absent key must leave the last known value alone rather than
  5400. # reset it to None.
  5401. if isinstance(nozzle_data, dict):
  5402. for key, attr in (("src_id", "nozzle_rack_src_id"), ("tar_id", "nozzle_rack_tar_id")):
  5403. if key not in nozzle_data:
  5404. continue
  5405. try:
  5406. parsed_id = int(nozzle_data[key])
  5407. except (TypeError, ValueError):
  5408. continue
  5409. if getattr(self.state, attr) != parsed_id:
  5410. setattr(self.state, attr, parsed_id)
  5411. # DEBUG, not INFO: these move on every tool change, so
  5412. # a long multi-material print would otherwise write
  5413. # thousands of lines. The dispatch log records both
  5414. # values once per print, which is where triage needs
  5415. # them. Same reasoning as the one-shot `nozzle_info`
  5416. # log below.
  5417. logger.debug(
  5418. "[%s] Nozzle rack %s -> %s",
  5419. self.serial_number,
  5420. key,
  5421. parsed_id,
  5422. )
  5423. nozzle_info = nozzle_data.get("info", [])
  5424. if isinstance(nozzle_info, list):
  5425. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  5426. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  5427. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  5428. # for hover cards on both the L/R indicator and the nozzle rack card.
  5429. if nozzle_info:
  5430. self.state.nozzle_rack = sorted(
  5431. [
  5432. {
  5433. "id": n.get("id", i),
  5434. "type": str(n.get("type", "")),
  5435. "diameter": str(n.get("diameter", "")),
  5436. "wear": n.get("wear"),
  5437. "stat": n.get("stat"),
  5438. # H2C uses "tm", H2D uses "max_temp"
  5439. "max_temp": n.get("max_temp") or n.get("tm", 0),
  5440. # H2C uses "sn", H2D uses "serial_number"
  5441. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  5442. # H2C uses "color_m", H2D uses "filament_colour"
  5443. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  5444. # H2C uses "fila_id", H2D uses "filament_id"
  5445. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  5446. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  5447. # H3C: home rack position 0-8 (the mounted hotend reports id 0)
  5448. "addr_id": n.get("addr_id") if isinstance(n.get("addr_id"), int) else None,
  5449. }
  5450. for i, n in enumerate(nozzle_info)
  5451. ],
  5452. key=lambda x: x["id"],
  5453. )
  5454. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  5455. self._nozzle_rack_logged = True
  5456. logger.debug(
  5457. "[%s] Nozzle info: %d entries, IDs: %s",
  5458. self.serial_number,
  5459. len(nozzle_info),
  5460. [n.get("id") for n in nozzle_info],
  5461. )
  5462. for nozzle in nozzle_info:
  5463. idx = nozzle.get("id", 0)
  5464. if idx < len(self.state.nozzles):
  5465. if "type" in nozzle and nozzle["type"]:
  5466. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  5467. if "diameter" in nozzle:
  5468. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  5469. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  5470. # (these fields aren't sent in every MQTT push, only when changed)
  5471. ams_data = self.state.raw_data.get("ams")
  5472. vt_tray_data = self.state.raw_data.get("vt_tray")
  5473. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  5474. mapping_data = self.state.raw_data.get("mapping")
  5475. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  5476. # as a dict but consumers expect a list. Without this, the dev mode probe
  5477. # below can release the GIL (via publish), letting the event-loop thread
  5478. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  5479. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  5480. data["vt_tray"] = [data["vt_tray"]]
  5481. self.state.raw_data = data
  5482. # Restore preserved fields BEFORE any work that may release the GIL
  5483. # (e.g. _probe_developer_mode publishes an MQTT message).
  5484. if ams_data is not None:
  5485. self.state.raw_data["ams"] = ams_data
  5486. elif not isinstance(self.state.raw_data.get("ams"), list):
  5487. # #3499: no unit list yet (the AMS handling failed on this frame).
  5488. # The frame's AMS object is not one; readers iterate it as units.
  5489. self.state.raw_data.pop("ams", None)
  5490. if vt_tray_data is not None:
  5491. self.state.raw_data["vt_tray"] = vt_tray_data
  5492. if ams_extruder_map_data is not None:
  5493. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  5494. if mapping_data is not None and "mapping" not in data:
  5495. self.state.raw_data["mapping"] = mapping_data
  5496. # Parse developer LAN mode from "fun" field
  5497. if "fun" in data:
  5498. try:
  5499. fun_val = data["fun"]
  5500. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  5501. self.state.developer_mode = (fun_int & 0x20000000) == 0
  5502. except (ValueError, TypeError):
  5503. pass
  5504. elif self.state.developer_mode is None and not self._dev_mode_probed:
  5505. # No "fun" field — A1/P1 series never send it, so we need to probe.
  5506. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  5507. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  5508. # after connect to let the MQTT session stabilize — probing too early
  5509. # can destabilize some firmware MQTT brokers (#887).
  5510. if not self._dev_mode_needs_probe and len(data) > 30:
  5511. # First full status without "fun" — mark that probe is needed
  5512. self._dev_mode_needs_probe = True
  5513. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  5514. self._probe_developer_mode()
  5515. elif self._dev_mode_needs_probe:
  5516. logger.debug(
  5517. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  5518. self.serial_number,
  5519. time.monotonic() - self._connect_time,
  5520. )
  5521. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  5522. # Probe was sent but no response yet — check for timeout.
  5523. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  5524. # may deliver status pushes but silently drop commands (#887).
  5525. elapsed = time.monotonic() - self._dev_mode_probe_time
  5526. if elapsed > 10.0:
  5527. self._dev_mode_probe_failures += 1
  5528. logger.warning(
  5529. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  5530. self.serial_number,
  5531. elapsed,
  5532. self._dev_mode_probe_failures,
  5533. )
  5534. self._dev_mode_probe_seq = None
  5535. if self._dev_mode_probe_failures >= 2:
  5536. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  5537. else:
  5538. # Allow retry on next full status message
  5539. self._dev_mode_probed = False
  5540. # Zombie session detection: if an ams_filament_setting command has been
  5541. # pending for >10s with no response, the publish path is likely dead (#887).
  5542. if self._last_ams_cmd_time > 0:
  5543. elapsed = time.monotonic() - self._last_ams_cmd_time
  5544. if elapsed > 10.0:
  5545. self._ams_cmd_unanswered += 1
  5546. logger.warning(
  5547. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  5548. self.serial_number,
  5549. elapsed,
  5550. self._ams_cmd_unanswered,
  5551. )
  5552. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  5553. if self._ams_cmd_unanswered >= 2:
  5554. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  5555. self._ams_cmd_unanswered = 0
  5556. # Log mapping data when received (for usage tracking debugging)
  5557. if "mapping" in data:
  5558. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  5559. # Log state transitions for debugging
  5560. if "gcode_state" in data:
  5561. logger.debug(
  5562. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  5563. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  5564. )
  5565. # Detect print start (state changes TO RUNNING with a file)
  5566. current_file = self.state.gcode_file or self.state.current_print
  5567. if self._previous_gcode_state is None and self.state.state == "PAUSE" and current_file:
  5568. self._paused_at_startup = True
  5569. is_new_print = (
  5570. self.state.state == "RUNNING"
  5571. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  5572. and self._previous_gcode_state != "RUNNING"
  5573. and current_file
  5574. and not self._was_running # Prevent duplicates when resuming from PAUSE
  5575. # #3485: a print paused when Bambuddy started resumes like one it
  5576. # found running (#1304): restart recovery below, not a new print.
  5577. and not (self._paused_at_startup and self._previous_gcode_state == "PAUSE")
  5578. )
  5579. if self.state.state != "PAUSE":
  5580. self._paused_at_startup = False
  5581. # Also detect if file changed while running (new print started)
  5582. is_file_change = (
  5583. self.state.state == "RUNNING"
  5584. and current_file
  5585. and current_file != self._previous_gcode_file
  5586. and self._previous_gcode_file is not None
  5587. )
  5588. # Track RUNNING state for more robust completion detection
  5589. running_first_observed = False
  5590. if self.state.state == "RUNNING" and current_file:
  5591. if not self._was_running:
  5592. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  5593. # Check if timelapse was enabled in the same message (xcam parsed before this)
  5594. if self.state.timelapse:
  5595. self._timelapse_during_print = True
  5596. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  5597. # Mark this as the first RUNNING observation of the session.
  5598. # If is_new_print also fires below, on_print_start handles
  5599. # baseline capture and we suppress on_print_running_observed
  5600. # to avoid double-capture. If is_new_print does NOT fire
  5601. # (Bambuddy started mid-print — the #1304 guard suppressed
  5602. # it), main.py needs this hook to catch the restart-recovery
  5603. # case (#1485 follow-up).
  5604. running_first_observed = True
  5605. self._was_running = True
  5606. self._completion_triggered = False
  5607. if is_new_print or is_file_change:
  5608. # Clear any old HMS errors when a new print starts
  5609. self.state.hms_errors = []
  5610. # The last print's pauses; this one's come from its 3MF (#2984).
  5611. self.state.pause_points = []
  5612. self.state.pause_warned_layers = set()
  5613. # Reset layer tracking for new print (needed for layer-based timelapse)
  5614. # #3317: only above 1. Every print reports layer 1 first, which
  5615. # clears a higher value; a previous print that ended on layer 1
  5616. # would make this print's own first layer look stale.
  5617. self._stale_layer_num = self.state.layer_num if self.state.layer_num > 1 else 0
  5618. self.state.layer_num = 0
  5619. # Reset total_layers so the previous print's value can't bleed into
  5620. # this print's usage-tracker split (#1771 follow-on to the
  5621. # preservation guard at the `total_layer_num` parse above — that
  5622. # guard ignores firmware-reset 0s, so the explicit reset has to
  5623. # happen here instead).
  5624. #
  5625. # #2702: reset to *this frame's* total, not to 0. The frame that
  5626. # trips the new-print detection can carry the new print's
  5627. # `total_layer_num` as well — the parse above has already applied
  5628. # it, and zeroing unconditionally threw it away. That looked
  5629. # harmless but is not recoverable: Bambu firmware sends only
  5630. # changed fields, so the printer never offers the total again, and
  5631. # the print runs to completion at `n/0` in the UI, in
  5632. # `{total_layers}` notifications, and as the usage-split
  5633. # denominator. The value only reappears on the next full pushall
  5634. # (reconnect / Force Refresh), which is why the symptom looked
  5635. # random and why a *stable* connection made it worse.
  5636. self.state.total_layers = total_from_this_frame
  5637. # If the starting frame brought no total, ask for one. Costs one
  5638. # MQTT message per print and covers the ordering where the printer
  5639. # published the total a frame or two before the state flip.
  5640. self._total_layers_refresh_armed = not total_from_this_frame
  5641. if self._total_layers_refresh_armed:
  5642. self._request_push_all()
  5643. # Reset completion tracking for new print
  5644. self._was_running = True
  5645. self._completion_triggered = False
  5646. # #1721: rearm the end-of-print finish-photo trigger for the new print
  5647. self._finish_photo_captured = False
  5648. # #2547: rearm the end-of-print telemetry probe for the new print
  5649. self._eop_probe_armed = True
  5650. self._eop_probe_open = False
  5651. self._eop_probe_frames = 0
  5652. self._eop_probe_last = {}
  5653. # Reset last valid progress/layer for usage tracking
  5654. self._last_valid_progress = 0.0
  5655. self._last_valid_layer_num = 0
  5656. # Clear and seed tray change log for mid-print usage splitting
  5657. self.state.tray_change_log.clear()
  5658. # Seeded with the assigned spools by usage_tracker.on_print_start.
  5659. self.state.spool_change_log = []
  5660. tn = self.state.tray_now
  5661. if self.tray_layout.is_loaded_tray(tn):
  5662. self.state.tray_change_log.append((tn, 0))
  5663. # Initialize timelapse tracking based on current state
  5664. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  5665. # so self.state.timelapse may already be set from this message.
  5666. # We preserve that value instead of blindly resetting to False.
  5667. if self.state.timelapse:
  5668. self._timelapse_during_print = True
  5669. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  5670. else:
  5671. self._timelapse_during_print = False
  5672. if (is_new_print or is_file_change) and self.on_print_start:
  5673. logger.info(
  5674. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  5675. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  5676. )
  5677. self.on_print_start(
  5678. {
  5679. "filename": current_file,
  5680. "subtask_name": self.state.subtask_name,
  5681. "remaining_time": self.state.remaining_time * 60
  5682. if self.state.remaining_time > 0
  5683. else None, # Convert minutes to seconds
  5684. "raw_data": data,
  5685. "ams_mapping": self._captured_ams_mapping,
  5686. }
  5687. )
  5688. elif running_first_observed and self.on_print_running_observed:
  5689. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  5690. # print, so the #1304 first-push guard suppressed on_print_start,
  5691. # but we still need main.py to capture a fresh timelapse baseline
  5692. # before the printer uploads the in-flight MP4. Same payload
  5693. # shape as on_print_start so the consumer can reuse fields.
  5694. logger.info(
  5695. f"[{self.serial_number}] RUNNING observed without PRINT START "
  5696. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  5697. )
  5698. self.on_print_running_observed(
  5699. {
  5700. "filename": current_file,
  5701. "subtask_name": self.state.subtask_name,
  5702. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  5703. "raw_data": data,
  5704. "ams_mapping": self._captured_ams_mapping,
  5705. }
  5706. )
  5707. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  5708. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  5709. # This handles cases where server restarts during a print
  5710. should_trigger_completion = (
  5711. self.state.state in ("FINISH", "FAILED")
  5712. and not self._completion_triggered
  5713. and self.on_print_complete
  5714. and (
  5715. self._previous_gcode_state == "RUNNING" # Normal transition
  5716. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  5717. # Pre-print failure (#1111): printer rejected the job during setup
  5718. # — wrong nozzle size, AMS error, etc. The print never reaches
  5719. # RUNNING, so without this branch neither the RUNNING check nor
  5720. # _was_running match and the queue item stays stuck at "printing".
  5721. # Restricted to FAILED from pre-print states so a stale FAILED on
  5722. # first connection (prev=None) still can't accidentally fire.
  5723. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  5724. )
  5725. )
  5726. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  5727. if (
  5728. self.state.state == "IDLE"
  5729. and self._previous_gcode_state == "RUNNING"
  5730. and not self._completion_triggered
  5731. and self.on_print_complete
  5732. ):
  5733. should_trigger_completion = True
  5734. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  5735. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  5736. if (
  5737. not should_trigger_completion
  5738. and self.state.state in ("FINISH", "FAILED")
  5739. and self._previous_gcode_state != self.state.state
  5740. ):
  5741. logger.info(
  5742. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  5743. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  5744. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  5745. )
  5746. # Mark as triggered so state is clean for the next print cycle
  5747. self._completion_triggered = True
  5748. if should_trigger_completion:
  5749. if self.state.state == "FINISH":
  5750. status = "completed"
  5751. elif self.state.state == "FAILED":
  5752. status = "failed"
  5753. else:
  5754. status = "aborted"
  5755. logger.info(
  5756. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  5757. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  5758. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  5759. f"timelapse_during_print: {self._timelapse_during_print}"
  5760. )
  5761. timelapse_was_active = self._timelapse_during_print
  5762. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  5763. # external-spool-only, HMS halt, or firmware variant that skips
  5764. # the unload phase) fire the finish-photo moment now. Bed has
  5765. # already dropped, framing is worse, but we still capture.
  5766. # Only on successful completion — aborted/failed prints don't
  5767. # produce a meaningful finish photo.
  5768. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  5769. self._finish_photo_captured = True
  5770. logger.info(
  5771. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  5772. f"stage-22 never fired; capturing at FINISH-state transition"
  5773. )
  5774. self.on_finish_photo_moment(
  5775. {
  5776. "trigger": "finish_state",
  5777. "filename": self._previous_gcode_file or current_file,
  5778. "subtask_name": self.state.subtask_name,
  5779. "timelapse_was_active": timelapse_was_active,
  5780. }
  5781. )
  5782. self._completion_triggered = True
  5783. self._was_running = False
  5784. self._timelapse_during_print = False # Reset for next print
  5785. # Include HMS errors for failure reason detection
  5786. hms_errors_data = [e.completion_payload() for e in self.state.hms_errors or []]
  5787. from backend.app.utils.printer_models import usage_progress
  5788. last_progress = usage_progress(
  5789. self.model, self._last_valid_progress, self._last_valid_layer_num, self.state.total_layers
  5790. )
  5791. self.on_print_complete(
  5792. {
  5793. "status": status,
  5794. "subtask_id": self.state.subtask_id,
  5795. "filename": self._previous_gcode_file or current_file,
  5796. "subtask_name": self.state.subtask_name,
  5797. "raw_data": data,
  5798. "timelapse_was_active": timelapse_was_active,
  5799. "hms_errors": hms_errors_data,
  5800. "ams_mapping": self._captured_ams_mapping,
  5801. # Last valid progress/layer before firmware reset (for partial usage tracking)
  5802. "last_progress": last_progress,
  5803. "last_layer_num": self._last_valid_layer_num,
  5804. }
  5805. )
  5806. self._captured_ams_mapping = None
  5807. # Same lifecycle as the mapping above: it described *this* print.
  5808. # Leaving it set would hand the next print an answer about where a
  5809. # different file went, and a stale "internal storage" reading costs
  5810. # an archive that the FTPS sweep would have found (#2780).
  5811. self.state.current_project_url = None
  5812. self._previous_gcode_state = self.state.state
  5813. if current_file:
  5814. self._previous_gcode_file = current_file
  5815. if self.on_state_change:
  5816. self.on_state_change(self.state)
  5817. def _request_push_all(self):
  5818. """Request full status update from printer."""
  5819. if self._client:
  5820. message = {"pushing": {"command": "pushall"}}
  5821. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5822. def _probe_developer_mode(self):
  5823. """Probe developer mode by sending an ams_filament_setting for the external slot.
  5824. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  5825. For these, we detect developer mode by sending a harmless command and
  5826. checking whether the printer accepts or rejects it:
  5827. - result="success" → developer mode ON (commands accepted)
  5828. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  5829. The probe re-sends the current external slot configuration so it's a no-op
  5830. when the command succeeds. If there's no external slot data yet, we send a
  5831. reset (empty filament) which is also safe.
  5832. """
  5833. if not self._client or not self.state.connected:
  5834. return
  5835. self._dev_mode_probed = True
  5836. self._dev_mode_probe_time = time.monotonic()
  5837. self._sequence_id += 1
  5838. seq = str(self._sequence_id)
  5839. self._dev_mode_probe_seq = seq
  5840. # Build probe command: re-send current external slot config (no-op on success)
  5841. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5842. current = vt_tray[0] if vt_tray else {}
  5843. command = {
  5844. "print": {
  5845. "command": "ams_filament_setting",
  5846. "ams_id": 255,
  5847. "tray_id": 0,
  5848. "slot_id": 0,
  5849. "tray_info_idx": current.get("tray_info_idx", ""),
  5850. "tray_type": current.get("tray_type", ""),
  5851. "tray_sub_brands": current.get("tray_sub_brands", ""),
  5852. "tray_color": current.get("tray_color", "00000000"),
  5853. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  5854. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  5855. "sequence_id": seq,
  5856. }
  5857. }
  5858. setting_id = current.get("setting_id")
  5859. if setting_id:
  5860. command["print"]["setting_id"] = setting_id
  5861. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  5862. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5863. def _apply_mqtt_verify_state(self, verify_failed: bool) -> None:
  5864. """Reconcile developer_mode with the printer's own command-verification verdict.
  5865. ``HMS_MQTT_VERIFY_FAILED`` is the only *direct* evidence we ever get that
  5866. control commands are being refused, so it outranks the probe in both
  5867. directions:
  5868. * present → developer_mode is definitively False, whatever the probe
  5869. concluded. The probe can only read the response to its own
  5870. ``ams_filament_setting``; on P1 firmware a refusal is reported here
  5871. instead, so the probe answers ENABLED while every print silently dies
  5872. (#2732).
  5873. * gone again → drop the HMS-derived False back to unknown and re-arm the
  5874. probe, so a user who enables Developer Mode and restarts the printer
  5875. isn't stuck behind a verdict nothing would ever revisit.
  5876. A False that came from the probe or the ``fun`` bit is left alone — this
  5877. only ever unwinds its own latch.
  5878. """
  5879. if verify_failed:
  5880. if not self._dev_mode_from_hms:
  5881. logger.warning(
  5882. "[%s] Printer reported HMS %s (MQTT command verification failed): it is "
  5883. "rejecting control commands, so prints, temperature changes and filament "
  5884. "loads will be ignored. Enable Developer Mode on the printer and restart it.",
  5885. self.serial_number,
  5886. HMS_MQTT_VERIFY_FAILED,
  5887. )
  5888. self._dev_mode_from_hms = True
  5889. self.state.developer_mode = False
  5890. return
  5891. if not self._dev_mode_from_hms:
  5892. return
  5893. logger.info(
  5894. "[%s] HMS %s cleared — re-probing developer mode",
  5895. self.serial_number,
  5896. HMS_MQTT_VERIFY_FAILED,
  5897. )
  5898. self._dev_mode_from_hms = False
  5899. self.state.developer_mode = None
  5900. self._dev_mode_probed = False
  5901. self._dev_mode_needs_probe = False
  5902. def _handle_dev_mode_probe_response(self, data: dict):
  5903. """Handle response to the developer mode probe command.
  5904. Sets developer_mode based on whether the printer accepted or rejected the command.
  5905. Three outcomes, not two. An explicit ``success`` proves commands are
  5906. accepted and an explicit verify-failure proves they are not, but anything
  5907. else proves nothing — P1S firmware 01.10.00.00 answers this probe with a
  5908. bare ``{"command": "ams_filament_setting", "sequence_id": "3"}`` and no
  5909. ``result`` at all, while refusing every control command and reporting
  5910. ``HMS_MQTT_VERIFY_FAILED`` instead. Reading that empty response as ENABLED
  5911. is what put ``developer_mode: pass`` in the support bundle of a printer
  5912. that had not accepted a command all day (#2732). Leaving it unknown makes
  5913. the connection diagnostic report ``skip``, which is the honest answer.
  5914. """
  5915. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  5916. self._dev_mode_probe_failures = 0 # Reset on any response
  5917. result = data.get("result", "")
  5918. reason = data.get("reason", "")
  5919. if result == "failed" and "verify failed" in reason:
  5920. self.state.developer_mode = False
  5921. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  5922. elif str(result).lower() == "success":
  5923. self.state.developer_mode = True
  5924. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  5925. else:
  5926. # An HMS verdict already recorded here is real evidence; don't let an
  5927. # inconclusive probe response wipe it back to unknown.
  5928. if not self._dev_mode_from_hms:
  5929. self.state.developer_mode = None
  5930. logger.info(
  5931. "[%s] Developer mode probe: INCONCLUSIVE (result=%r, reason=%r) — "
  5932. "the printer neither confirmed nor refused the command",
  5933. self.serial_number,
  5934. result,
  5935. reason,
  5936. )
  5937. if self.on_state_change:
  5938. self.on_state_change(self.state)
  5939. def _request_version(self):
  5940. """Request firmware version info from printer."""
  5941. if self._client:
  5942. self._sequence_id += 1
  5943. message = {
  5944. "info": {
  5945. "sequence_id": str(self._sequence_id),
  5946. "command": "get_version",
  5947. }
  5948. }
  5949. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  5950. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  5951. def request_status_update(self) -> bool:
  5952. """Request a full status update from the printer (public API).
  5953. Sends both pushall and get_accessories commands to refresh all data
  5954. including nozzle hardware info.
  5955. Returns:
  5956. True if the request was sent, False if not connected.
  5957. """
  5958. if not self._client or not self.state.connected:
  5959. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  5960. return False
  5961. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  5962. self._request_push_all()
  5963. # Note: get_accessories returns stale nozzle data on H2D.
  5964. # The correct nozzle data comes from push_status response.
  5965. return True
  5966. def _prime_kprofile_request(self):
  5967. """Send a priming K-profile request on connect.
  5968. Bambu printers often ignore the first K-profile request after connection,
  5969. so we send a dummy request on connect to 'prime' the system.
  5970. """
  5971. if self._client:
  5972. self._sequence_id += 1
  5973. command = {
  5974. "print": {
  5975. "command": "extrusion_cali_get",
  5976. "filament_id": "",
  5977. "nozzle_diameter": "0.4",
  5978. "sequence_id": str(self._sequence_id),
  5979. }
  5980. }
  5981. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  5982. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5983. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  5984. """Connect to the printer MQTT broker.
  5985. Args:
  5986. loop: The asyncio event loop to use for thread-safe callbacks.
  5987. If not provided, will try to get the running loop.
  5988. """
  5989. self._loop = loop
  5990. BambuMQTTClient._client_instance_counter += 1
  5991. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  5992. self._client = mqtt.Client(
  5993. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  5994. client_id=client_id,
  5995. protocol=mqtt.MQTTv311,
  5996. )
  5997. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  5998. # tracking (#1164). The default ceiling of 20 wedges sessions after
  5999. # ~16-20 cumulative commands; lifting it well above any realistic
  6000. # session count keeps QoS=1 working without changing wire-protocol
  6001. # behaviour across printer models.
  6002. self._client.max_inflight_messages_set(1000)
  6003. self._client.username_pw_set("bblp", self.access_code)
  6004. self._client.on_connect = self._on_connect
  6005. self._client.on_disconnect = self._on_disconnect
  6006. self._client.on_subscribe = self._on_subscribe
  6007. self._client.on_message = self._on_message
  6008. # TLS setup - Bambu uses self-signed certs
  6009. ssl_context = ssl.create_default_context()
  6010. ssl_context.check_hostname = False
  6011. ssl_context.verify_mode = ssl.CERT_NONE
  6012. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  6013. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  6014. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  6015. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  6016. # bare-metal installs whose build allows TLS 1.0.
  6017. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  6018. self._client.tls_set_context(ssl_context)
  6019. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  6020. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  6021. # Keepalive: paho sends PINGREQs at this interval, broker considers
  6022. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  6023. # real network loss (45s), not so aggressive that transient hiccups
  6024. # trigger false disconnects. Stale detection (60s no messages) handles
  6025. # the P1S/P1P firmware bug where the broker stops publishing but the
  6026. # TCP connection stays alive.
  6027. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  6028. self._client.loop_start()
  6029. def start_print(
  6030. self,
  6031. filename: str,
  6032. plate_id: int = 1,
  6033. ams_mapping: list[int] | None = None,
  6034. bed_levelling: str = "auto",
  6035. flow_cali: str = "auto",
  6036. vibration_cali: bool = True,
  6037. layer_inspect: bool = False,
  6038. timelapse: bool = False,
  6039. use_ams: bool = True,
  6040. nozzle_offset_cali: str = "auto",
  6041. nozzle_mapping: str | None = None,
  6042. nozzle_slot_extruders: str | None = None,
  6043. plate_uses_only_external: bool = False,
  6044. ):
  6045. """Start a print job on the printer.
  6046. The file should already be uploaded to the printer's root directory via FTP.
  6047. Args:
  6048. filename: Name of the uploaded file
  6049. plate_id: Plate number to print (default 1)
  6050. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  6051. Global tray ID = (ams_id * 4) + slot_id, external = 254
  6052. timelapse: Record timelapse video
  6053. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  6054. if the bed was levelled recently, matching BambuStudio).
  6055. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  6056. vibration_cali: Vibration compensation calibration
  6057. layer_inspect: First layer AI inspection
  6058. use_ams: Use AMS for automatic filament changes
  6059. plate_uses_only_external: The caller determined from the plate's
  6060. own filament list that it prints only from the spool holder;
  6061. use_ams=False then stands even if the mapping names a real
  6062. tray (one another plate of the file uses, #3087)
  6063. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  6064. (dual-nozzle printers only — silently ignored on single-nozzle).
  6065. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  6066. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  6067. AND the printer is dual-nozzle, parsed and injected as the
  6068. `nozzle_mapping` array on the dispatched project_file so the
  6069. firmware honours the user's slicer pick instead of falling
  6070. back to "last matching nozzle" auto-pick. Silently ignored
  6071. on single-nozzle printers.
  6072. nozzle_slot_extruders: Opaque JSON string of per-filament-slot
  6073. MQTT extruder indices, derived from the 3MF when no
  6074. BambuStudio capture exists (#2800). Consulted only on
  6075. nozzle-rack models (H2C) and only when `nozzle_mapping` did
  6076. not already supply one; resolved here into physical rack
  6077. positions using the live `device.nozzle` state. When it
  6078. cannot be resolved the field is omitted and the firmware
  6079. picks, as it did before this existed.
  6080. Returns True when the start command was published, False otherwise
  6081. (not connected, or the printer is already busy — see the run-state
  6082. guard below).
  6083. """
  6084. # Never dispatch project_file to a printer that is not idle (#2598).
  6085. # This is the single publish choke point for every dispatch path — the
  6086. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  6087. # forwarded job all funnel through here — so one guard covers them all.
  6088. # The firmware rejects a start while busy with 0500_4004 ("Device is
  6089. # busy and cannot start a new task"), and on an A1 mini that error
  6090. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  6091. # start targets; only the active-print states are refused. (A
  6092. # transport-level QoS-1 replay on reconnect would bypass this guard;
  6093. # _on_connect empties paho's outbox before it can re-send (#3454).)
  6094. if self.state.state in _ACTIVE_PRINT_STATES:
  6095. logger.warning(
  6096. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  6097. self.serial_number,
  6098. self.state.state,
  6099. filename,
  6100. )
  6101. return False
  6102. if self._client and self.state.connected:
  6103. # Bambu print command format — matches Bambu Studio's format.
  6104. # The calibration/leveling fields (timelapse, bed_leveling,
  6105. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  6106. # every model. An earlier revision integer-encoded them for the H2
  6107. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  6108. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  6109. # sends plain booleans, and the integer encoding made the H2S
  6110. # silently skip flow-dynamics calibration (#1478). use_ams is the
  6111. # one field that genuinely must stay boolean: H2D Pro firmware
  6112. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  6113. # what actually caused the wrong-extruder routing behind #1386.
  6114. # Dual-nozzle routing for external spool (254 = deputy/left,
  6115. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  6116. # H2 firmware family but is single-nozzle, despite sharing serial
  6117. # prefix "094" with H2D. Prefer runtime detection from
  6118. # device.extruder.info (set in _handle_push_status); fall back to
  6119. # model name for the brief window after connect before push data
  6120. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  6121. # as the primary signal.
  6122. from backend.app.utils.printer_models import is_dual_nozzle_model, is_nozzle_rack_model
  6123. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  6124. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  6125. ams_mapping2 = []
  6126. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  6127. # ams_mapping and relies on ams_mapping2 for external spool details.
  6128. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  6129. # with 0700_8012 "Failed to get AMS mapping table".
  6130. flat_ams_mapping = []
  6131. layout = self.tray_layout
  6132. if ams_mapping is not None:
  6133. for tray_id in ams_mapping:
  6134. # Ensure tray_id is an integer (may be string from JSON)
  6135. tray_id = int(tray_id) if tray_id is not None else -1
  6136. rack_slot = layout.rack_slot(tray_id) if tray_id >= 0 else None
  6137. if tray_id == -1:
  6138. # Unmapped filament slot
  6139. flat_ams_mapping.append(-1)
  6140. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  6141. elif layout.rack and layout.is_external(tray_id):
  6142. # A rack printer's per-hotend input 247-255, as Studio
  6143. # sends it: -1 flat, its own id in ams_mapping2.
  6144. flat_ams_mapping.append(-1)
  6145. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6146. elif rack_slot is not None:
  6147. # Rack AMS slot, as Studio sends it: 28 + k flat,
  6148. # {ams_id: 32, slot_id: k} in ams_mapping2.
  6149. flat_ams_mapping.append(tray_id)
  6150. ams_mapping2.append({"ams_id": rack_slot[0], "slot_id": rack_slot[1]})
  6151. elif tray_id >= 254:
  6152. # External/virtual spool. BambuStudio convention:
  6153. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  6154. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  6155. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  6156. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  6157. # for external spool, but BambuStudio always sends ams_id=255
  6158. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  6159. # firmware to target AMS tray 0 instead of external spool, leading
  6160. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  6161. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  6162. flat_ams_mapping.append(-1)
  6163. ext_ams_id = tray_id if is_dual_nozzle else 255
  6164. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  6165. elif tray_id >= 128:
  6166. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  6167. flat_ams_mapping.append(tray_id)
  6168. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  6169. elif (_a2l := a2l_lite_wire_ids(layout.slot_key(tray_id)[0], tray_id)) is not None:
  6170. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  6171. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  6172. # — both CONFIRMED against the firmware's own mapping
  6173. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  6174. _wire_ams, _wire_slot, _ = _a2l
  6175. flat_ams_mapping.append(_wire_slot)
  6176. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  6177. else:
  6178. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  6179. ams_id, slot_id = layout.slot_key(tray_id)
  6180. flat_ams_mapping.append(tray_id)
  6181. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  6182. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  6183. # printers — the mapping is authoritative about whether this print
  6184. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  6185. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  6186. # H2S falls through here now (#1386): it is single-nozzle and was
  6187. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  6188. # without an AMS attached.
  6189. #
  6190. # Two symmetric corrections:
  6191. #
  6192. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  6193. # use_ams=True even if it arrived False. A print sent to a Virtual
  6194. # Printer is sliced against the VP, which advertises no AMS, so the
  6195. # slicer sends use_ams=false and that gets stamped on the queue item
  6196. # — but at dispatch the scheduler colour-matches a real printer and
  6197. # resolves a real AMS slot. Without this, the stale False reaches the
  6198. # printer, which ignores the mapped slot and aborts at layer 0 on the
  6199. # empty external spool ("not enough filament"). Diagnosed by
  6200. # @Sawtaytoes (#2595, PR #2596).
  6201. #
  6202. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  6203. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  6204. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  6205. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  6206. # status-load race that persisted [-1] (#2589) — and treating it as
  6207. # external silently started the print against an empty feed. A genuine
  6208. # external selection is >=254; unresolved is -1; a loaded tray is
  6209. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  6210. # (or is recomputed upstream) instead of silently going external, and
  6211. # never gets force-enabled by (a) either.
  6212. if ams_mapping and not is_dual_nozzle:
  6213. has_real_tray = any(
  6214. t is not None and 0 <= int(t) <= 253 and not layout.is_external(int(t)) for t in ams_mapping
  6215. )
  6216. all_external = all(t is None or int(t) >= 254 or layout.is_external(int(t)) for t in ams_mapping)
  6217. # (Not when the scheduler worked out from the plate's own
  6218. # filament list that it prints only from the spool holder: a
  6219. # real tray here is then one another plate of the file uses.)
  6220. if has_real_tray and not use_ams and not plate_uses_only_external:
  6221. use_ams = True
  6222. logger.info(
  6223. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  6224. self.serial_number,
  6225. )
  6226. elif use_ams and all_external:
  6227. use_ams = False
  6228. logger.info(
  6229. "[%s] All filament slots use external spool — setting use_ams=False",
  6230. self.serial_number,
  6231. )
  6232. # (c) A single-nozzle printer that reported no AMS at all can only
  6233. # print from the spool holder, whatever the mapping says. With
  6234. # nothing set on the holder the matcher resolves no mapping, so
  6235. # neither (a) nor (b) ran and the print went out as use_ams=True,
  6236. # which the firmware refuses with 07FF_8012 "Failed to get AMS
  6237. # mapping table" (#3356). An empty raw_data["ams"] is the
  6238. # printer's own report of no AMS; a missing key means no AMS
  6239. # push has been handled yet (a reconnect), which changes nothing.
  6240. if use_ams and not is_dual_nozzle and self.state.raw_data.get("ams") == []:
  6241. use_ams = False
  6242. logger.info("[%s] Printer has no AMS — setting use_ams=False (#3356)", self.serial_number)
  6243. # Unique per-submission identity fields. Hardcoded "0" values caused
  6244. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  6245. # continuations of the same job: the printer reuses gcode_start_time
  6246. # from the prior print with task_id=0, so observers latch onto a stale
  6247. # timestamp and report compounding durations on repeat replays (#1011).
  6248. # BambuStudio mints fresh IDs per submission; matching that behavior
  6249. # makes the printer emit a clean state-transition for each job.
  6250. # md5 is left empty — firmware historically accepts "" as "skip
  6251. # validation" (unlike Studio, we don't have the file's real md5 here
  6252. # without re-reading the upload, and sending a synthetic wrong digest
  6253. # risks activation of md5 verification on some firmwares).
  6254. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  6255. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  6256. # overflows and every submission ends up with the same task_id from
  6257. # the printer's perspective — the printer then treats a fresh dispatch
  6258. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  6259. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  6260. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  6261. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  6262. # Remember it so on_print_start can persist a restart-stable id on
  6263. # the archive even before the printer echoes subtask_id back (#1485).
  6264. self.last_dispatch_subtask_id = submission_id
  6265. self.last_start_refusal = None
  6266. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  6267. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  6268. # only if it wasn't done recently). The paired bool field is true
  6269. # only for the explicit "on" state — for "auto" the bool is false and
  6270. # the int carries the intent, exactly as BambuStudio's SelectMachine
  6271. # sends it. Unknown values fall back to auto.
  6272. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  6273. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  6274. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  6275. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  6276. command = {
  6277. "print": {
  6278. "sequence_id": "20000",
  6279. "command": "project_file",
  6280. "param": f"Metadata/plate_{plate_id}.gcode",
  6281. "url": f"ftp://{filename}",
  6282. "file": filename,
  6283. "md5": "",
  6284. "bed_type": "auto",
  6285. "timelapse": timelapse,
  6286. # bed_leveling stays a JSON bool (true only for "on") and
  6287. # auto_bed_leveling carries the tri-state int — the exact
  6288. # two-field shape BambuStudio sends. The int must stay a plain
  6289. # number, never quoted (#1478 boolean-family concern applies to
  6290. # the *_cali bools, not these companion ints).
  6291. "bed_leveling": bed_levelling == "on",
  6292. "auto_bed_leveling": bed_level_int,
  6293. "flow_cali": flow_cali == "on",
  6294. "vibration_cali": vibration_cali,
  6295. "layer_inspect": layer_inspect,
  6296. "use_ams": use_ams,
  6297. # No "cfg": it is the printer's device-config bitmask
  6298. # (auto-refill, detect-on-insert, chamber light, ...), not a
  6299. # per-job field — BambuStudio's PrintParams has no such
  6300. # member. We used to send "0"; firmware ignores it, but it
  6301. # comes straight back in the project_file ack (#3040).
  6302. # extrude_cali_flag gates flow-dynamics calibration:
  6303. # 0 = never, 1 = force every print, 2 = auto (run only if the
  6304. # filament wasn't calibrated recently). #1721 saw stage 8
  6305. # ("Calibrating dynamic flow") still queued when we send 2 —
  6306. # that is exactly the auto contract (the printer queues the
  6307. # stage and skips it at runtime if recent), not a bug, so 2 is
  6308. # the right wire value for "auto". off/on remain 0/1.
  6309. "extrude_cali_flag": flow_cali_int,
  6310. "extrude_cali_manual_mode": 0,
  6311. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  6312. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  6313. # again the auto contract, not a failure to suppress.
  6314. # BambuStudio exposes the toggle only for dual-nozzle
  6315. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  6316. # firmware never runs a calibration the head doesn't support.
  6317. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  6318. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  6319. "profile_id": "0",
  6320. "project_id": submission_id,
  6321. "subtask_id": submission_id,
  6322. "task_id": submission_id,
  6323. }
  6324. }
  6325. # P2S-specific parameter adjustments
  6326. # P2S printer doesn't support vibration calibration like X1/P1 series
  6327. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  6328. command["print"]["vibration_cali"] = False
  6329. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  6330. # Add AMS mapping if provided
  6331. if ams_mapping is not None:
  6332. command["print"]["ams_mapping"] = flat_ams_mapping
  6333. command["print"]["ams_mapping2"] = ams_mapping2
  6334. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  6335. # `nozzle_mapping` carries per-filament physical nozzle position
  6336. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  6337. # item; parse here so the wire ships an array, matching
  6338. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  6339. # defensively — single-nozzle firmwares would ignore the field
  6340. # but we err on the side of not emitting unrecognised fields. A
  6341. # parse failure is logged but never blocks the dispatch — the
  6342. # firmware will fall back to its auto-pick path, which is the
  6343. # pre-fix behaviour.
  6344. if is_dual_nozzle and nozzle_mapping:
  6345. try:
  6346. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  6347. except json.JSONDecodeError:
  6348. logger.warning(
  6349. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  6350. "project_file (firmware will auto-pick): %r",
  6351. self.serial_number,
  6352. nozzle_mapping,
  6353. )
  6354. # Nozzle-rack fallback (#2800). Only consulted when BambuStudio
  6355. # never saw the job, so it can never override a real capture. The
  6356. # queue stores extruder indices per filament slot; the physical
  6357. # rack position they resolve to is only knowable here, because the
  6358. # mounted hotend can change between queueing and dispatch.
  6359. if is_nozzle_rack_model(self.model) and nozzle_slot_extruders and "nozzle_mapping" not in command["print"]:
  6360. try:
  6361. slot_extruders = json.loads(nozzle_slot_extruders)
  6362. except (json.JSONDecodeError, TypeError):
  6363. # TypeError covers a caller handing us the list itself
  6364. # rather than its JSON — the field is opaque by contract,
  6365. # and a print must not die over the difference.
  6366. slot_extruders = None
  6367. logger.warning(
  6368. "[%s] Invalid nozzle_slot_extruders JSON on dispatch, "
  6369. "omitting nozzle_mapping (firmware will auto-pick): %r",
  6370. self.serial_number,
  6371. nozzle_slot_extruders,
  6372. )
  6373. if isinstance(slot_extruders, list):
  6374. rack_nozzle_id = (
  6375. self.state.nozzle_rack_tar_id
  6376. if self.state.nozzle_rack_tar_id in _RACK_NOZZLE_IDS
  6377. else self.state.nozzle_rack_src_id
  6378. )
  6379. resolved = resolve_rack_nozzle_mapping(slot_extruders, rack_nozzle_id)
  6380. if resolved is None:
  6381. logger.info(
  6382. "[%s] Nozzle rack slots %s not resolvable (tar_id=%s src_id=%s); "
  6383. "omitting nozzle_mapping so the firmware picks",
  6384. self.serial_number,
  6385. slot_extruders,
  6386. self.state.nozzle_rack_tar_id,
  6387. self.state.nozzle_rack_src_id,
  6388. )
  6389. else:
  6390. logger.info(
  6391. "[%s] Nozzle rack mapping: slots=%s rack_id=%s -> %s",
  6392. self.serial_number,
  6393. slot_extruders,
  6394. rack_nozzle_id,
  6395. resolved,
  6396. )
  6397. command["print"]["nozzle_mapping"] = resolved
  6398. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  6399. # Remember this dispatch so its echo on the topic is recognised as
  6400. # ours rather than logged as a slicer's.
  6401. self._own_project_file_key = self._project_file_key(command["print"])
  6402. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6403. # Record what we dispatched so /cover can pick the right plate
  6404. # thumbnail even when the printer's gcode_file echo is just the
  6405. # 3MF filename without a plate path (#1166). Match the same
  6406. # subtask_name shape we send so the comparison in the cover route
  6407. # works against state.subtask_name reflected back via MQTT.
  6408. self.state.dispatched_plate_id = plate_id
  6409. self.state.dispatched_subtask = command["print"]["subtask_name"]
  6410. return True
  6411. else:
  6412. # Log why we couldn't send the command
  6413. if not self._client:
  6414. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  6415. elif not self.state.connected:
  6416. logger.error(
  6417. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  6418. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  6419. )
  6420. return False
  6421. def stop_print(self) -> bool:
  6422. """Stop the current print job."""
  6423. if self._client and self.state.connected:
  6424. command = {"print": {"command": "stop", "sequence_id": "0"}}
  6425. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6426. logger.info("[%s] Sent stop print command", self.serial_number)
  6427. return True
  6428. return False
  6429. def set_xcam_option(
  6430. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  6431. ) -> bool:
  6432. """Set an xcam (AI detection) option on the printer.
  6433. Args:
  6434. module_name: The xcam module to control (e.g., "spaghetti_detector",
  6435. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  6436. enabled: Whether to enable or disable the feature
  6437. print_halt: Whether to halt print on detection (only applies to some detectors)
  6438. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  6439. Returns:
  6440. True if command was sent, False if not connected
  6441. """
  6442. if not self._client or not self.state.connected:
  6443. return False
  6444. # auto_recovery_step_loss uses a different command format (print.print_option)
  6445. if module_name == "auto_recovery_step_loss":
  6446. return self._set_print_option("auto_recovery", enabled)
  6447. self._sequence_id += 1
  6448. # Build the xcam control command (exact OrcaSlicer format)
  6449. # Key findings from OrcaSlicer source:
  6450. # - Uses "xcam" wrapper (not "print")
  6451. # - print_halt is ALWAYS true (legacy protocol requirement)
  6452. # - Both "control" and "enable" are set to the same value
  6453. # - halt_print_sensitivity controls actual halt behavior
  6454. command = {
  6455. "xcam": {
  6456. "command": "xcam_control_set",
  6457. "sequence_id": str(self._sequence_id),
  6458. "module_name": module_name,
  6459. "control": enabled,
  6460. "enable": enabled, # old protocol compatibility
  6461. "print_halt": True, # ALWAYS true per OrcaSlicer
  6462. }
  6463. }
  6464. # Only add sensitivity if not "never_halt"
  6465. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  6466. # The module_name field determines which detector's sensitivity is being set
  6467. if sensitivity and sensitivity != "never_halt":
  6468. command["xcam"]["halt_print_sensitivity"] = sensitivity
  6469. command_json = json.dumps(command)
  6470. self._client.publish(self.topic_publish, command_json, qos=1)
  6471. logger.debug(
  6472. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  6473. )
  6474. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  6475. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  6476. # This prevents stale MQTT data from immediately overwriting our change
  6477. self._xcam_hold_start[module_name] = time.time()
  6478. # Update local state immediately for responsive UI
  6479. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  6480. # When spaghetti_detector sensitivity is changed, pileup also changes
  6481. if module_name == "spaghetti_detector":
  6482. self.state.print_options.spaghetti_detector = enabled
  6483. self.state.print_options.print_halt = print_halt
  6484. if sensitivity and sensitivity != "never_halt":
  6485. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  6486. self.state.print_options.halt_print_sensitivity = sensitivity
  6487. self.state.print_options.pileup_sensitivity = sensitivity
  6488. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  6489. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  6490. elif module_name == "first_layer_inspector":
  6491. self.state.print_options.first_layer_inspector = enabled
  6492. elif module_name == "printing_monitor":
  6493. self.state.print_options.printing_monitor = enabled
  6494. elif module_name == "buildplate_marker_detector":
  6495. self.state.print_options.buildplate_marker_detector = enabled
  6496. elif module_name == "allow_skip_parts":
  6497. self.state.print_options.allow_skip_parts = enabled
  6498. elif module_name == "pileup_detector":
  6499. self.state.print_options.pileup_detector = enabled
  6500. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  6501. elif module_name == "clump_detector":
  6502. self.state.print_options.nozzle_clumping_detector = enabled
  6503. if sensitivity and sensitivity != "never_halt":
  6504. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  6505. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  6506. elif module_name == "airprint_detector":
  6507. self.state.print_options.airprint_detector = enabled
  6508. if sensitivity and sensitivity != "never_halt":
  6509. self.state.print_options.airprint_sensitivity = sensitivity
  6510. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  6511. elif module_name == "auto_recovery_step_loss":
  6512. self.state.print_options.auto_recovery_step_loss = enabled
  6513. return True
  6514. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  6515. """Set a print option using the print.print_option command.
  6516. This is different from xcam_control_set and is used for options like:
  6517. - auto_recovery
  6518. - air_print_detect
  6519. - filament_tangle_detect
  6520. - nozzle_blob_detect
  6521. - sound_enable
  6522. Args:
  6523. option_name: The option to control (e.g., "auto_recovery")
  6524. enabled: Whether to enable or disable the option
  6525. Returns:
  6526. True if command was sent, False if not connected
  6527. """
  6528. if not self._client or not self.state.connected:
  6529. return False
  6530. self._sequence_id += 1
  6531. command = {
  6532. "print": {
  6533. "command": "print_option",
  6534. "sequence_id": str(self._sequence_id),
  6535. option_name: enabled,
  6536. }
  6537. }
  6538. command_json = json.dumps(command)
  6539. self._client.publish(self.topic_publish, command_json, qos=1)
  6540. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  6541. # Set hold timer
  6542. hold_key = f"print_option_{option_name}"
  6543. self._xcam_hold_start[hold_key] = time.time()
  6544. # Update local state immediately
  6545. if option_name == "auto_recovery":
  6546. self.state.print_options.auto_recovery_step_loss = enabled
  6547. elif option_name == "auto_switch_filament":
  6548. self.state.ams_filament_backup = enabled
  6549. return True
  6550. def set_ams_filament_backup(self, enabled: bool) -> bool:
  6551. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  6552. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  6553. shape from H2D capture 2026-06-20.
  6554. """
  6555. return self._set_print_option("auto_switch_filament", enabled)
  6556. def start_calibration(
  6557. self,
  6558. bed_leveling: bool = False,
  6559. vibration: bool = False,
  6560. motor_noise: bool = False,
  6561. nozzle_offset: bool = False,
  6562. high_temp_heatbed: bool = False,
  6563. ) -> bool:
  6564. """Start printer calibration with selected options.
  6565. Args:
  6566. bed_leveling: Run bed leveling calibration
  6567. vibration: Run vibration compensation calibration
  6568. motor_noise: Run motor noise cancellation calibration
  6569. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  6570. high_temp_heatbed: Run high-temperature heatbed calibration
  6571. Returns:
  6572. True if command was sent, False if not connected
  6573. """
  6574. if not self._client or not self.state.connected:
  6575. return False
  6576. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  6577. # Bit 0: xcam_cali (not exposed in UI)
  6578. # Bit 1: bed_leveling
  6579. # Bit 2: vibration
  6580. # Bit 3: motor_noise
  6581. # Bit 4: nozzle_cali
  6582. # Bit 5: bed_cali (high-temp heatbed)
  6583. # Bit 6: clumppos_cali (not exposed in UI)
  6584. option = 0
  6585. if bed_leveling:
  6586. option |= 1 << 1
  6587. if vibration:
  6588. option |= 1 << 2
  6589. if motor_noise:
  6590. option |= 1 << 3
  6591. if nozzle_offset:
  6592. option |= 1 << 4
  6593. if high_temp_heatbed:
  6594. option |= 1 << 5
  6595. if option == 0:
  6596. logger.warning("[%s] No calibration options selected", self.serial_number)
  6597. return False
  6598. self._sequence_id += 1
  6599. command = {
  6600. "print": {
  6601. "command": "calibration",
  6602. "sequence_id": str(self._sequence_id),
  6603. "option": option,
  6604. }
  6605. }
  6606. command_json = json.dumps(command)
  6607. self._client.publish(self.topic_publish, command_json, qos=1)
  6608. logger.info(
  6609. f"[{self.serial_number}] Starting calibration: "
  6610. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  6611. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  6612. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  6613. )
  6614. return True
  6615. def disconnect(self, timeout: float = 0):
  6616. """Disconnect from the printer.
  6617. Waits up to *timeout* for paho to report the disconnect, then lets the
  6618. client go without joining its network thread — the callers are route
  6619. handlers (printer edited, deleted, disconnected by hand) running on the
  6620. asyncio thread, and that join has no bound (#3068)."""
  6621. if self._client:
  6622. old_client = self._client
  6623. self._disconnection_event = threading.Event()
  6624. old_client.disconnect()
  6625. # The callback that sets this fires on paho's thread, so it has to
  6626. # be given its window before retire_paho_client detaches it.
  6627. self._disconnection_event.wait(timeout=timeout)
  6628. self._client = None
  6629. retire_paho_client(old_client, self.serial_number)
  6630. self.state.connected = False
  6631. # Deliberately no on_state_change here. paho's disconnect callback
  6632. # used to land during the join, but `_on_disconnect` suppresses
  6633. # itself for a clean disconnect of a printer that reported within
  6634. # the last 10s -- which is every healthy printer -- so a
  6635. # hand-disconnected printer never broadcast one. Announcing it now
  6636. # would fire the connected→disconnected edge in
  6637. # `on_printer_status_change` and notify the user their printer went
  6638. # offline a minute after they disconnected it on purpose (#1752).
  6639. # The callers drop the client from the manager anyway, so the next
  6640. # status read already shows it gone.
  6641. def enable_logging(self, enabled: bool = True):
  6642. """Enable or disable MQTT message logging."""
  6643. self._logging_enabled = enabled
  6644. # Don't clear logs when stopping - user can manually clear with clear_logs()
  6645. def get_logs(self) -> list[MQTTLogEntry]:
  6646. """Get all logged MQTT messages."""
  6647. return list(self._message_log)
  6648. def clear_logs(self):
  6649. """Clear the message log."""
  6650. self._message_log.clear()
  6651. @property
  6652. def logging_enabled(self) -> bool:
  6653. """Check if logging is enabled."""
  6654. return self._logging_enabled
  6655. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6656. """Register a handler invoked for every incoming MQTT message.
  6657. Used by the VP MQTT bridge to republish the printer's report pushes to
  6658. slicers connected to a virtual printer in non-proxy mode. Handlers run
  6659. on paho's network thread and must not block; exceptions are caught.
  6660. """
  6661. if handler not in self._raw_message_handlers:
  6662. self._raw_message_handlers.append(handler)
  6663. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  6664. """Unregister a previously-registered raw-message handler."""
  6665. try:
  6666. self._raw_message_handlers.remove(handler)
  6667. except ValueError:
  6668. pass
  6669. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  6670. """Publish a pre-formed payload directly to the printer's MQTT broker.
  6671. Used by the VP MQTT bridge to forward slicer-originated commands without
  6672. giving it one of our own sequence ids. Returns False if the
  6673. underlying paho client isn't ready.
  6674. """
  6675. if self._client is None:
  6676. return False
  6677. try:
  6678. info = self._client.publish(topic, payload, qos=qos)
  6679. return info.rc == mqtt.MQTT_ERR_SUCCESS
  6680. except Exception:
  6681. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  6682. return False
  6683. def _ams3h_drying_zone_id(self, ams_id: int) -> int:
  6684. """The drying zone id of AMS 3H unit ``ams_id`` from the last status, else 0."""
  6685. unit = self._ams_unit(ams_id)
  6686. return _mqtt_int((unit or {}).get("dry_zone_id")) or 0
  6687. def send_drying_command(
  6688. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  6689. ):
  6690. """Send AMS drying start/stop command.
  6691. Args:
  6692. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  6693. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  6694. duration: Drying duration in hours
  6695. mode: 1=start, 0=stop
  6696. filament: Filament type string (e.g. "PLA", "PETG")
  6697. rotate_tray: Whether to rotate the spool during drying for even heat
  6698. """
  6699. if not self._client:
  6700. return False
  6701. self._sequence_id += 1
  6702. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  6703. # not actually support drying, but keep the translation consistent). The
  6704. # _drying_targets dict below stays keyed by the normalised id so the
  6705. # on_drying_complete callback matches the telemetry.
  6706. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  6707. ams3h = self._rack_ams_type(ams_id) == AmsType.ZMULTI_A
  6708. command = {
  6709. "print": {
  6710. "sequence_id": str(self._sequence_id),
  6711. "command": "ams_filament_drying",
  6712. "ams_id": wire_ams_id,
  6713. "temp": temp,
  6714. "cooling_temp": 20 if mode == 1 else 0,
  6715. "duration": duration,
  6716. "humidity": 0,
  6717. "mode": mode,
  6718. "rotate_tray": rotate_tray,
  6719. "filament": filament,
  6720. "close_power_conflict": False,
  6721. }
  6722. }
  6723. if ams3h:
  6724. # As Studio 02.09 sends it (DevFilaSystemCtrl.cpp): a start names
  6725. # the drying zone and cooling_temp; a stop names no zone. The AMS 3H
  6726. # can't turn spools.
  6727. command["print"]["rotate_tray"] = False
  6728. if mode == 1:
  6729. command["print"]["zone_id"] = self._ams3h_drying_zone_id(ams_id)
  6730. command["print"]["cooling_temp"] = ams3h_drying_cooling_temp(filament)
  6731. # Log the full wire JSON at INFO so support bundles capture exactly
  6732. # what we sent — needed to diagnose silent rejections (#1447) where
  6733. # the printer ACKs the command but never starts/stops drying.
  6734. # Paired with the ams_filament_drying response-payload INFO log so
  6735. # both halves of the conversation land in the bundle by default.
  6736. wire_json = json.dumps(command)
  6737. self._client.publish(self.topic_publish, wire_json, qos=1)
  6738. logger.info(
  6739. "[%s] Sent ams_filament_drying: %s",
  6740. self.serial_number,
  6741. wire_json,
  6742. )
  6743. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  6744. # while drying. Bambu only echoes dry_time on subsequent pushes.
  6745. # duration_hours is not shown anywhere; it is what lets the cycle-end log
  6746. # say how much of the requested time the firmware actually ran (#2770).
  6747. if mode == 1:
  6748. self._drying_targets[ams_id] = {
  6749. "filament": filament or "",
  6750. "temp": int(temp),
  6751. "duration_hours": int(duration),
  6752. }
  6753. self._drying_stops_sent.discard(ams_id)
  6754. # A start sent while a cycle is still counting down replaces it
  6755. # without dry_time passing through 0; begin a fresh record so the
  6756. # new target and length are the ones reported (#2863).
  6757. self._dry_cycles.pop(ams_id, None)
  6758. else:
  6759. self._drying_targets.pop(ams_id, None)
  6760. # Remember that this cycle's end is ours, so the cycle-end log
  6761. # attributes it to Bambuddy instead of to the firmware (#2770). A
  6762. # stop always ends the cycle far short of its duration, which is
  6763. # otherwise indistinguishable from the firmware abandoning it.
  6764. self._drying_stops_sent.add(ams_id)
  6765. return True
  6766. @staticmethod
  6767. def _parse_kprofile_entries(filaments: list, response_nozzle: str | None, log_errors: bool) -> list[KProfile]:
  6768. """Build KProfile objects from an ``extrusion_cali_get`` filaments array.
  6769. The printer reports ``nozzle_diameter`` **only on the response
  6770. envelope** — the per-filament entries carry just setting_id,
  6771. filament_id, name, k_value, n_coef and cali_idx. Defaulting the
  6772. per-entry lookup to "0.4" therefore stamped every profile 0.4mm on
  6773. single-nozzle printers regardless of the installed nozzle (#1748),
  6774. which broke the K-Profiles display and, worse, the cali_idx cascade
  6775. in the inventory/Spoolman assign paths that matches on
  6776. nozzle_diameter. Fall back to the envelope value instead, and only
  6777. to "0.4" when the envelope has none either.
  6778. ``or`` rather than a dict default on purpose: it also covers an entry
  6779. that carries the key with an empty value, and stops ``str()`` turning
  6780. a missing envelope value into the literal "None".
  6781. """
  6782. profiles: list[KProfile] = []
  6783. for i, f in enumerate(filaments):
  6784. if not isinstance(f, dict):
  6785. continue
  6786. try:
  6787. profiles.append(
  6788. KProfile(
  6789. # cali_idx is the actual slot/calibration index from the printer
  6790. slot_id=f.get("cali_idx", i),
  6791. extruder_id=int(f.get("extruder_id", 0)),
  6792. nozzle_id=str(f.get("nozzle_id", "")),
  6793. nozzle_diameter=str(f.get("nozzle_diameter") or response_nozzle or "0.4"),
  6794. filament_id=str(f.get("filament_id", "")),
  6795. name=str(f.get("name", "")),
  6796. k_value=str(f.get("k_value", "0.000000")),
  6797. n_coef=str(f.get("n_coef", "0.000000")),
  6798. ams_id=int(f.get("ams_id", 0)),
  6799. tray_id=int(f.get("tray_id", -1)),
  6800. setting_id=f.get("setting_id"),
  6801. )
  6802. )
  6803. except (ValueError, TypeError) as e:
  6804. # Skip malformed entries; the remaining profiles stay usable.
  6805. # Unsolicited broadcasts arrive constantly, so only a response
  6806. # someone is actually waiting on is worth a warning.
  6807. if log_errors:
  6808. logger.warning("Failed to parse K-profile: %s", e)
  6809. else:
  6810. logger.debug("Failed to parse K-profile from broadcast: %s", e)
  6811. return profiles
  6812. def _store_kprofiles(self, profiles: list, response_nozzle: str | None) -> None:
  6813. """File one calibration-table response under its nozzle diameter.
  6814. ``response_nozzle`` names the table the printer just sent, so that
  6815. bucket is replaced wholesale and every other one is left alone. When
  6816. the envelope carries no diameter, fall back to the diameters the parsed
  6817. profiles claim for themselves — and if there are none of those either,
  6818. keep what we have rather than dropping a table we cannot attribute.
  6819. ``state.kprofiles`` stays a flat list because that is what its readers
  6820. expect; the three assign paths already filter it by ``nozzle_diameter``
  6821. and were quietly finding nothing whenever the last response happened to
  6822. be for a different nozzle.
  6823. """
  6824. buckets: dict[str, list] = {}
  6825. if response_nozzle:
  6826. buckets[str(response_nozzle)] = list(profiles)
  6827. else:
  6828. for profile in profiles:
  6829. buckets.setdefault(str(profile.nozzle_diameter), []).append(profile)
  6830. if not buckets:
  6831. return
  6832. self._kprofiles_by_nozzle.update(buckets)
  6833. self.state.kprofiles = [
  6834. kp for nozzle in sorted(self._kprofiles_by_nozzle) for kp in self._kprofiles_by_nozzle[nozzle]
  6835. ]
  6836. def _handle_kprofile_response(self, data: dict):
  6837. """Handle K-profile response from printer."""
  6838. response_nozzle = data.get("nozzle_diameter")
  6839. response_seq_id = str(data.get("sequence_id", ""))
  6840. filaments = data.get("filaments", [])
  6841. # Snapshot the map: the asyncio thread adds and removes entries while
  6842. # this MQTT callback thread walks it.
  6843. pending = dict(self._pending_kprofile_requests)
  6844. request = pending.get(response_seq_id)
  6845. if request is None and pending:
  6846. # Firmware that doesn't echo our sequence_id still has to be
  6847. # served, so fall back to the pre-#1748 rule of matching on the
  6848. # nozzle size. Only requests still waiting are eligible, and the
  6849. # sequence_id lookup above has already claimed any response that
  6850. # identifies itself, so this can no longer hand request A's
  6851. # answer to request B when both are in flight.
  6852. request = next(
  6853. (r for r in pending.values() if r["nozzle"] == response_nozzle and r["profiles"] is None),
  6854. None,
  6855. )
  6856. if pending:
  6857. logger.info(
  6858. "[%s] K-profile response: nozzle=%s, seq_id=%s, %d profiles, matched=%s",
  6859. self.serial_number,
  6860. response_nozzle,
  6861. response_seq_id or "?",
  6862. len(filaments),
  6863. request is not None,
  6864. )
  6865. if request is None and pending:
  6866. # A request is outstanding and this isn't its answer. The printer
  6867. # broadcasts extrusion_cali_get unsolicited, so letting this
  6868. # through would replace state.kprofiles with another nozzle's
  6869. # profiles while the caller is still waiting.
  6870. logger.debug(
  6871. "[%s] Ignoring unmatched K-profile response: nozzle=%s, seq_id=%s",
  6872. self.serial_number,
  6873. response_nozzle,
  6874. response_seq_id or "?",
  6875. )
  6876. return
  6877. profiles = self._parse_kprofile_entries(filaments, response_nozzle, log_errors=request is not None)
  6878. self._store_kprofiles(profiles, response_nozzle)
  6879. if request is None:
  6880. # Unsolicited broadcast with nothing in flight: state is refreshed,
  6881. # nobody to wake. Worth a line — this is the printer answering
  6882. # somebody else (BambuStudio queries the same report topic), and
  6883. # until it was bucketed by nozzle it was also the quietest way for
  6884. # the AMS card's K values to change underneath us.
  6885. logger.debug(
  6886. "[%s] Adopted unsolicited K-profile table: nozzle=%s, %d profiles",
  6887. self.serial_number,
  6888. response_nozzle or "?",
  6889. len(profiles),
  6890. )
  6891. return
  6892. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  6893. request["profiles"] = profiles
  6894. # Signal the waiter. Use the thread-safe path since MQTT callbacks run
  6895. # in a different thread than the event loop.
  6896. event = request["event"]
  6897. if self._loop and self._loop.is_running():
  6898. self._loop.call_soon_threadsafe(event.set)
  6899. else:
  6900. # Fallback for when loop is not available
  6901. event.set()
  6902. async def get_kprofiles(
  6903. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  6904. ) -> list[KProfile]:
  6905. """Request K-profiles from the printer with retry logic.
  6906. Bambu printers sometimes ignore the first K-profile request, so we
  6907. implement retry logic to ensure reliable retrieval.
  6908. Args:
  6909. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  6910. timeout: Timeout in seconds to wait for each response attempt
  6911. max_retries: Maximum number of retry attempts
  6912. Returns:
  6913. List of KProfile objects; empty when the printer has none for
  6914. the nozzle.
  6915. Raises:
  6916. KProfileReadError: not connected, or no answer to any attempt.
  6917. Returning an empty list made that a printer without profiles
  6918. (#3404).
  6919. """
  6920. if not self._client or not self.state.connected:
  6921. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  6922. raise KProfileReadError("Printer not connected")
  6923. # Capture current event loop for thread-safe callback
  6924. try:
  6925. self._loop = asyncio.get_running_loop()
  6926. except RuntimeError:
  6927. logger.warning("[%s] No running event loop", self.serial_number)
  6928. raise KProfileReadError("No running event loop") from None
  6929. for attempt in range(max_retries):
  6930. # Register this attempt under its own sequence_id so a concurrent
  6931. # request for a different nozzle size can't consume its response
  6932. # (#1748) — the pending map is keyed by exactly the id we send.
  6933. self._sequence_id += 1
  6934. seq_id = str(self._sequence_id)
  6935. request: dict = {"nozzle": nozzle_diameter, "event": asyncio.Event(), "profiles": None}
  6936. self._pending_kprofile_requests[seq_id] = request
  6937. # Send the command with nozzle_diameter filter
  6938. command = {
  6939. "print": {
  6940. "command": "extrusion_cali_get",
  6941. "filament_id": "",
  6942. "nozzle_diameter": nozzle_diameter,
  6943. "sequence_id": seq_id,
  6944. }
  6945. }
  6946. logger.info(
  6947. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries}, seq_id={seq_id})"
  6948. )
  6949. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  6950. # Wait for the response (the handler matches it back to this entry)
  6951. try:
  6952. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6953. await asyncio.wait_for(request["event"].wait(), timeout=timeout)
  6954. profiles = request["profiles"] or []
  6955. logger.info(
  6956. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  6957. )
  6958. return profiles
  6959. except TimeoutError:
  6960. logger.warning(
  6961. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  6962. )
  6963. if attempt < max_retries - 1:
  6964. # Brief delay before retry
  6965. await asyncio.sleep(0.5)
  6966. finally:
  6967. self._pending_kprofile_requests.pop(seq_id, None)
  6968. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  6969. raise KProfileReadError("The printer did not answer the K-profile request")
  6970. def _publish_cali_write(self, command: dict, seq_id: str) -> bool:
  6971. """Publish a K-profile write and arm its ack slot.
  6972. Registration happens before the publish because the printer answers in
  6973. well under a second — measured at 70-150ms — which is comfortably
  6974. before an async caller gets back to awaiting.
  6975. """
  6976. self._pending_cali_acks[seq_id] = None
  6977. try:
  6978. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  6979. except Exception:
  6980. self._pending_cali_acks.pop(seq_id, None)
  6981. raise
  6982. return True
  6983. async def await_cali_ack(self, seq_id: str, timeout: float = 6.0) -> tuple[bool, str]:
  6984. """Wait for the printer's verdict on a K-profile write.
  6985. Returns ``(ok, detail)``. ``ok`` is False only when the printer
  6986. explicitly said ``result: "fail"`` — a timeout returns True with a
  6987. detail string, because "no answer" is not evidence of rejection and
  6988. older firmware may not answer at all. Callers that need certainty read
  6989. the calibration table back.
  6990. Polled rather than event-driven on purpose: the ack is filled in by the
  6991. MQTT callback thread, and polling a dict costs one lookup every 50ms
  6992. for at most a few hundred milliseconds, against the cross-thread
  6993. event plumbing it would otherwise take.
  6994. """
  6995. deadline = time.monotonic() + timeout
  6996. try:
  6997. while time.monotonic() < deadline:
  6998. ack = self._pending_cali_acks.get(seq_id)
  6999. if ack is not None:
  7000. result = str(ack.get("result", "")).lower()
  7001. reason = str(ack.get("reason", "") or "")
  7002. if result == "fail":
  7003. return (False, reason or "printer reported failure")
  7004. return (True, reason)
  7005. await asyncio.sleep(0.05)
  7006. finally:
  7007. self._pending_cali_acks.pop(seq_id, None)
  7008. logger.warning("[%s] No ack for K-profile write seq=%s within %.1fs", self.serial_number, seq_id, timeout)
  7009. return (True, CALI_ACK_UNCONFIRMED)
  7010. def set_kprofile(
  7011. self,
  7012. filament_id: str,
  7013. name: str,
  7014. k_value: str,
  7015. nozzle_diameter: str = "0.4",
  7016. nozzle_id: str = "HS00-0.4",
  7017. extruder_id: int = 0,
  7018. setting_id: str | None = None,
  7019. slot_id: int = 0,
  7020. cali_idx: int | None = None,
  7021. ) -> str | None:
  7022. """Set/update a K-profile on the printer.
  7023. Args:
  7024. filament_id: Bambu filament identifier
  7025. name: Profile name
  7026. k_value: Pressure advance value (e.g., "0.020000")
  7027. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7028. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  7029. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7030. setting_id: Existing setting ID for updates, None for new
  7031. slot_id: Calibration index (cali_idx) for the profile
  7032. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  7033. Returns:
  7034. The sequence_id the command was sent under, so the caller can
  7035. await the printer's verdict via await_cali_ack. None if the
  7036. command could not be sent.
  7037. """
  7038. if not self._client or not self.state.connected:
  7039. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  7040. return None
  7041. self._sequence_id += 1
  7042. seq_id = str(self._sequence_id)
  7043. # Build the filament entry - printer uses cali_idx for profile identification
  7044. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  7045. # For edits, use the provided cali_idx or slot_id
  7046. if cali_idx is not None:
  7047. effective_cali_idx = cali_idx
  7048. else:
  7049. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7050. # Generate a setting_id for new profiles (required by printer)
  7051. # Format: "PF" + 17 random digits
  7052. import random
  7053. if not setting_id and slot_id == 0:
  7054. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7055. filament_entry = {
  7056. "ams_id": 0,
  7057. "cali_idx": effective_cali_idx,
  7058. "extruder_id": extruder_id,
  7059. "filament_id": filament_id,
  7060. "k_value": k_value,
  7061. "n_coef": "0.000000",
  7062. "name": name,
  7063. "nozzle_diameter": nozzle_diameter,
  7064. "nozzle_id": nozzle_id,
  7065. "setting_id": setting_id if setting_id else "",
  7066. # 0, not -1. Single-nozzle firmware validates this field and
  7067. # answers `result: "fail", reason: "invalid tray_id"` to -1 — while
  7068. # applying the write anyway, so the rejection looked like noise.
  7069. # Measured on an X1C: flipping only this value turns the ack into
  7070. # `success` (#2718). BambuStudio always sends a real tray_id and
  7071. # defaults it to 0 for a manually entered profile.
  7072. "tray_id": 0,
  7073. }
  7074. command = {
  7075. "print": {
  7076. "command": "extrusion_cali_set",
  7077. "filaments": [filament_entry],
  7078. "nozzle_diameter": nozzle_diameter,
  7079. "sequence_id": seq_id,
  7080. }
  7081. }
  7082. command_json = json.dumps(command)
  7083. logger.info(
  7084. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  7085. )
  7086. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  7087. self._publish_cali_write(command, seq_id)
  7088. return seq_id
  7089. def set_kprofiles_batch(
  7090. self,
  7091. profiles: list[dict],
  7092. nozzle_diameter: str = "0.4",
  7093. ) -> str | None:
  7094. """Set multiple K-profiles in a single command (for dual-nozzle).
  7095. Args:
  7096. profiles: List of profile dicts, each with:
  7097. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  7098. nozzle_diameter: Common nozzle diameter for all profiles
  7099. Returns:
  7100. The sequence_id the command was sent under (see set_kprofile),
  7101. or None if it could not be sent.
  7102. """
  7103. if not self._client or not self.state.connected:
  7104. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  7105. return None
  7106. import random
  7107. self._sequence_id += 1
  7108. seq_id = str(self._sequence_id)
  7109. filament_entries = []
  7110. for p in profiles:
  7111. slot_id = p.get("slot_id", 0)
  7112. cali_idx = p.get("cali_idx")
  7113. if cali_idx is not None:
  7114. effective_cali_idx = cali_idx
  7115. else:
  7116. effective_cali_idx = -1 if slot_id == 0 else slot_id
  7117. setting_id = p.get("setting_id")
  7118. if not setting_id and slot_id == 0:
  7119. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  7120. filament_entries.append(
  7121. {
  7122. "ams_id": 0,
  7123. "cali_idx": effective_cali_idx,
  7124. "extruder_id": p.get("extruder_id", 0),
  7125. "filament_id": p.get("filament_id", ""),
  7126. "k_value": p.get("k_value", "0.020000"),
  7127. "n_coef": "0.000000",
  7128. "name": p.get("name", ""),
  7129. "nozzle_diameter": nozzle_diameter,
  7130. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  7131. "setting_id": setting_id if setting_id else "",
  7132. # See set_kprofile: -1 is rejected as "invalid tray_id" by
  7133. # single-nozzle firmware even though the write lands (#2718).
  7134. "tray_id": 0,
  7135. }
  7136. )
  7137. command = {
  7138. "print": {
  7139. "command": "extrusion_cali_set",
  7140. "filaments": filament_entries,
  7141. "nozzle_diameter": nozzle_diameter,
  7142. "sequence_id": seq_id,
  7143. }
  7144. }
  7145. command_json = json.dumps(command)
  7146. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  7147. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  7148. self._publish_cali_write(command, seq_id)
  7149. return seq_id
  7150. def delete_kprofile(
  7151. self,
  7152. cali_idx: int,
  7153. filament_id: str,
  7154. nozzle_id: str,
  7155. nozzle_diameter: str = "0.4",
  7156. extruder_id: int = 0,
  7157. setting_id: str | None = None,
  7158. ) -> str | None:
  7159. """Delete a K-profile from the printer.
  7160. Args:
  7161. cali_idx: The calibration index (slot_id) of the profile to delete
  7162. filament_id: Bambu filament identifier
  7163. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  7164. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  7165. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  7166. setting_id: Unique setting identifier (for X1C series)
  7167. Returns:
  7168. The sequence_id the command was sent under (see set_kprofile),
  7169. or None if it could not be sent.
  7170. """
  7171. if not self._client or not self.state.connected:
  7172. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  7173. return None
  7174. self._sequence_id += 1
  7175. seq_id = str(self._sequence_id)
  7176. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  7177. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  7178. # Prefer runtime detection from device.extruder.info; fall back to
  7179. # model name. H2S is single-nozzle but shares serial prefix "094" with
  7180. # H2D, so a prefix-only check misclassified it (#1386).
  7181. from backend.app.utils.printer_models import is_dual_nozzle_model
  7182. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  7183. if is_dual_nozzle:
  7184. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  7185. command = {
  7186. "print": {
  7187. "command": "extrusion_cali_del",
  7188. "sequence_id": seq_id,
  7189. "extruder_id": extruder_id,
  7190. "nozzle_id": nozzle_id,
  7191. "filament_id": filament_id,
  7192. "cali_idx": cali_idx,
  7193. "nozzle_diameter": nozzle_diameter,
  7194. }
  7195. }
  7196. else:
  7197. # X1C/P1/A1 format: include all fields like the set command
  7198. # The delete command structure should match what set uses
  7199. command = {
  7200. "print": {
  7201. "command": "extrusion_cali_del",
  7202. "sequence_id": seq_id,
  7203. "filament_id": filament_id,
  7204. "cali_idx": cali_idx,
  7205. "setting_id": setting_id if setting_id else "",
  7206. "nozzle_diameter": nozzle_diameter,
  7207. "nozzle_id": nozzle_id,
  7208. "extruder_id": extruder_id,
  7209. }
  7210. }
  7211. command_json = json.dumps(command)
  7212. logger.info(
  7213. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  7214. )
  7215. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  7216. # QoS 1 for reliable delivery (at least once)
  7217. self._publish_cali_write(command, seq_id)
  7218. return seq_id
  7219. # =========================================================================
  7220. # Printer Control Commands
  7221. # =========================================================================
  7222. def pause_print(self) -> bool:
  7223. """Pause the current print job."""
  7224. if not self._client or not self.state.connected:
  7225. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  7226. return False
  7227. command = {"print": {"command": "pause", "sequence_id": "0"}}
  7228. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7229. logger.info("[%s] Sent pause print command", self.serial_number)
  7230. return True
  7231. def resume_print(self) -> bool:
  7232. """Resume a paused print job."""
  7233. if not self._client or not self.state.connected:
  7234. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  7235. return False
  7236. command = {"print": {"command": "resume", "sequence_id": "0"}}
  7237. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7238. logger.info("[%s] Sent resume print command", self.serial_number)
  7239. return True
  7240. def clear_hms_errors(self) -> bool:
  7241. """Clear HMS/print errors on the printer and locally."""
  7242. if not self._client or not self.state.connected:
  7243. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  7244. return False
  7245. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  7246. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7247. self.state.hms_errors = []
  7248. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  7249. return True
  7250. def _handle_skip_objects_answer(self, print_data: dict) -> None:
  7251. """The printer's answer to skip_objects: a refusal is logged and the
  7252. objects are no longer shown as skipped."""
  7253. obj_list = self._skip_commands.pop(str(print_data.get("sequence_id", "")), None)
  7254. result = str(print_data.get("result", "") or "").lower()
  7255. if obj_list is None or result in ("", "success"):
  7256. return
  7257. logger.error(
  7258. "[%s] Printer refused skipping objects %s: result=%s reason=%s",
  7259. self.serial_number,
  7260. obj_list,
  7261. print_data.get("result"),
  7262. print_data.get("reason", ""),
  7263. )
  7264. for oid in obj_list:
  7265. self._unconfirmed_skips.pop(oid, None)
  7266. self.state.skipped_objects = [oid for oid in self.state.skipped_objects if oid not in obj_list]
  7267. def _check_unconfirmed_skips(self) -> None:
  7268. """Log, once, a skip the printer's s_obj list never showed."""
  7269. if not self._unconfirmed_skips:
  7270. return
  7271. if self.state.state not in ("RUNNING", "PAUSE"):
  7272. # The print ended; its skips are moot.
  7273. self._unconfirmed_skips.clear()
  7274. self._skip_commands.clear()
  7275. return
  7276. now = time.monotonic()
  7277. # A copy: skip_objects adds to the dict from the event loop while this
  7278. # runs on the MQTT thread.
  7279. pending = list(self._unconfirmed_skips.items())
  7280. expired = [oid for oid, sent_at in pending if now - sent_at > SKIP_CONFIRM_TIMEOUT_S]
  7281. if not expired:
  7282. return
  7283. logger.error(
  7284. "[%s] Printer did not confirm skipping objects %s within %.0fs; they may still be printed",
  7285. self.serial_number,
  7286. sorted(expired),
  7287. SKIP_CONFIRM_TIMEOUT_S,
  7288. )
  7289. for oid in expired:
  7290. self._unconfirmed_skips.pop(oid, None)
  7291. def skip_objects(self, object_ids: list[int]) -> bool:
  7292. """Skip specific objects during a print.
  7293. This command tells the printer to skip printing the specified objects.
  7294. The object IDs come from the slice_info.config file in the 3MF.
  7295. Args:
  7296. object_ids: List of identify_id values from slice_info.config
  7297. Returns:
  7298. True if command was sent, False otherwise
  7299. """
  7300. if not self._client or not self.state.connected:
  7301. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  7302. return False
  7303. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  7304. logger.warning(
  7305. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  7306. )
  7307. return False
  7308. if not object_ids:
  7309. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  7310. return False
  7311. # Validate all IDs are integers
  7312. try:
  7313. obj_list = [int(oid) for oid in object_ids]
  7314. except (ValueError, TypeError) as e:
  7315. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  7316. return False
  7317. self._sequence_id += 1
  7318. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  7319. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7320. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  7321. sent_at = time.monotonic()
  7322. for oid in obj_list:
  7323. self._unconfirmed_skips.setdefault(oid, sent_at)
  7324. self._skip_commands[str(self._sequence_id)] = obj_list
  7325. # Track skipped objects in state
  7326. for oid in obj_list:
  7327. if oid not in self.state.skipped_objects:
  7328. self.state.skipped_objects.append(oid)
  7329. return True
  7330. def send_gcode(self, gcode: str) -> bool:
  7331. """Send G-code command(s) to the printer.
  7332. Multiple commands can be separated by newlines.
  7333. Args:
  7334. gcode: G-code command(s) to send
  7335. Returns:
  7336. True if command was sent, False otherwise
  7337. """
  7338. if not self._client or not self.state.connected:
  7339. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  7340. return False
  7341. self._sequence_id += 1
  7342. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  7343. # Use QoS 1 for reliable delivery (at least once)
  7344. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7345. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  7346. return True
  7347. def set_bed_temperature(self, target: int) -> bool:
  7348. """Set the bed target temperature.
  7349. Args:
  7350. target: Target temperature in Celsius (0 to turn off)
  7351. Returns:
  7352. True if command was sent, False otherwise
  7353. """
  7354. return self.send_gcode(f"M140 S{target}")
  7355. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  7356. """Set the nozzle target temperature.
  7357. Args:
  7358. target: Target temperature in Celsius (0 to turn off)
  7359. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  7360. Returns:
  7361. True if command was sent, False otherwise
  7362. """
  7363. # Use M104 for non-blocking
  7364. # Always use T parameter for H2D compatibility
  7365. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  7366. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  7367. # Track it locally so we can display it correctly
  7368. if result and nozzle == 1:
  7369. self.state.temperatures["nozzle_target"] = float(target)
  7370. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  7371. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  7372. return result
  7373. def set_chamber_temperature(self, target: int) -> bool:
  7374. """Set the chamber target temperature.
  7375. Args:
  7376. target: Target temperature in Celsius (0 to turn off heating)
  7377. Returns:
  7378. True if command was sent, False otherwise
  7379. """
  7380. # The H3C's heater only runs in the airduct's heating mode.
  7381. from backend.app.utils.printer_models import chamber_heater_needs_heating_mode
  7382. if target > 0 and self.state.airduct_mode != 1 and chamber_heater_needs_heating_mode(self.model):
  7383. logger.info(
  7384. "[%s] Chamber target %s°C: switching the airduct to heating mode first (H3C)",
  7385. self.serial_number,
  7386. target,
  7387. )
  7388. self.set_airduct_mode("heating")
  7389. # M141 sets chamber temperature
  7390. result = self.send_gcode(f"M141 S{target}")
  7391. # Track chamber target locally (MQTT reports encoded values that need filtering)
  7392. if result:
  7393. self.state.temperatures["chamber_target"] = float(target)
  7394. self.state.temperatures["_chamber_target_set_time"] = time.time()
  7395. # Update heating state immediately based on new target
  7396. current_temp = self.state.temperatures.get("chamber", 0)
  7397. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  7398. logger.info(
  7399. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  7400. )
  7401. return result
  7402. def set_print_speed(self, mode: int) -> bool:
  7403. """Set the print speed mode.
  7404. Args:
  7405. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  7406. Returns:
  7407. True if command was sent, False otherwise
  7408. """
  7409. if not self._client or not self.state.connected:
  7410. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  7411. return False
  7412. if mode not in (1, 2, 3, 4):
  7413. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  7414. return False
  7415. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  7416. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7417. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  7418. return True
  7419. def set_fan_speed(self, fan: int, speed: int) -> bool:
  7420. """Set fan speed.
  7421. Args:
  7422. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=second auxiliary).
  7423. Index 10 is the second auxiliary part cooling fan: left on the P2S
  7424. (an accessory kit), right on the X2D, where 2 is the left (#3373)
  7425. (airduct part id 10); Bambu's official machine profiles drive it with
  7426. "M106 P10" in start/layer-change gcode.
  7427. speed: Speed 0-255 (0=off, 255=full)
  7428. Returns:
  7429. True if command was sent, False otherwise
  7430. """
  7431. if fan not in (1, 2, 3, 10):
  7432. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  7433. return False
  7434. speed = max(0, min(255, speed)) # Clamp to 0-255
  7435. return self.send_gcode(f"M106 P{fan} S{speed}")
  7436. def set_airduct_mode(self, mode: str) -> bool:
  7437. """Set air conditioning mode (cooling or heating).
  7438. Args:
  7439. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  7440. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  7441. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  7442. closes top exhaust flap
  7443. Returns:
  7444. True if command was sent, False otherwise
  7445. """
  7446. if not self._client or not self.state.connected:
  7447. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  7448. return False
  7449. self._sequence_id += 1
  7450. mode_id = 0 if mode == "cooling" else 1
  7451. command = {
  7452. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  7453. }
  7454. # Use QoS 1 for reliable delivery
  7455. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7456. logger.info(
  7457. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  7458. )
  7459. return True
  7460. def set_chamber_light(self, on: bool) -> bool:
  7461. """Turn chamber light on or off.
  7462. Args:
  7463. on: True to turn on, False to turn off
  7464. Returns:
  7465. True if command was sent, False otherwise
  7466. """
  7467. if not self._client or not self.state.connected:
  7468. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  7469. return False
  7470. mode = "on" if on else "off"
  7471. # Control both chamber lights (some printers like H2D have two)
  7472. for led_node in ["chamber_light", "chamber_light2"]:
  7473. self._sequence_id += 1
  7474. command = {
  7475. "system": {
  7476. "command": "ledctrl",
  7477. "led_node": led_node,
  7478. "led_mode": mode,
  7479. "led_on_time": 500,
  7480. "led_off_time": 500,
  7481. "loop_times": 0,
  7482. "interval_time": 0,
  7483. "sequence_id": str(self._sequence_id),
  7484. }
  7485. }
  7486. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7487. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  7488. return True
  7489. def select_extruder(self, extruder: int) -> bool:
  7490. """Select the active extruder for dual-nozzle printers (H2D).
  7491. Args:
  7492. extruder: Extruder index (0=right, 1=left for H2D)
  7493. Returns:
  7494. True if command was sent, False otherwise
  7495. """
  7496. if extruder not in (0, 1):
  7497. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  7498. return False
  7499. if not self._client or not self.state.connected:
  7500. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  7501. return False
  7502. # H2D extruder switching via select_extruder command
  7503. # Command format captured from OrcaSlicer:
  7504. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  7505. # extruder_index: 0 = RIGHT, 1 = LEFT
  7506. self._sequence_id += 1
  7507. command = {
  7508. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  7509. }
  7510. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7511. logger.info(
  7512. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  7513. )
  7514. return True
  7515. def _ams_unit(self, ams_id: int) -> dict | None:
  7516. """AMS unit ``ams_id`` in the last status, or None."""
  7517. for unit in self.state.raw_data.get("ams") or []:
  7518. if isinstance(unit, dict) and _mqtt_int(unit.get("id")) == ams_id:
  7519. return unit
  7520. return None
  7521. def _rack_tray(self, tray_id: int | None) -> tuple[int, int, dict | None] | None:
  7522. """``(ams_id, slot, tray)`` of a rack AMS slot's global tray id (the AMS 3H's 28-36), else None."""
  7523. if not isinstance(tray_id, int):
  7524. return None
  7525. located = self.tray_layout.rack_slot(tray_id)
  7526. if located is None:
  7527. return None
  7528. ams_id, slot = located
  7529. unit = self._ams_unit(ams_id) or {}
  7530. tray = next(
  7531. (t for t in unit.get("tray") or [] if isinstance(t, dict) and _mqtt_int(t.get("id")) == slot),
  7532. None,
  7533. )
  7534. return ams_id, slot, tray
  7535. def rack_tray_has_filament(self, tray_id: int) -> bool:
  7536. """Whether rack AMS slot ``tray_id`` reports a filament type, which Studio requires before a Load.
  7537. The AMS 3H registers a spool only once it has pulled the filament in at the inlet.
  7538. """
  7539. rack = self._rack_tray(tray_id)
  7540. return bool(rack and rack[2] and rack[2].get("tray_type"))
  7541. @staticmethod
  7542. def _tray_mid_temp(tray: dict | None) -> int:
  7543. """Midpoint of a tray's nozzle_temp_min/max, or -1 (as Studio's ams_change_filament)."""
  7544. if tray is None:
  7545. return -1
  7546. low, high = _mqtt_int(tray.get("nozzle_temp_min")), _mqtt_int(tray.get("nozzle_temp_max"))
  7547. return (low + high) // 2 if low and high and low > 0 and high > 0 else -1
  7548. def _rack_change_filament(self, tray_id: int, load: bool) -> bool:
  7549. """Load AMS 3H slot ``tray_id`` into its own hotend, or unload that hotend.
  7550. As Studio 02.09 sends it for a direct-connected rack (PageFilament.cpp):
  7551. load targets 32 at slot k, unload 255 at slot 255 - k (the feeder to
  7552. retract). The AMS 3H can't rewind: an unload ends with a hand pull.
  7553. """
  7554. client = self._client
  7555. rack = self._rack_tray(tray_id)
  7556. if client is None or rack is None:
  7557. return False
  7558. ams_id, slot, tray = rack
  7559. on_head = self._rack_tray(self.state.tray_now)
  7560. self._sequence_id += 1
  7561. command = {
  7562. "print": {
  7563. "command": "ams_change_filament",
  7564. "sequence_id": str(self._sequence_id),
  7565. "ams_id": ams_id,
  7566. "target": ams_id if load else 255,
  7567. "slot_id": slot if load else 255 - slot,
  7568. "extruder_id": 0,
  7569. "curr_temp": self._tray_mid_temp(on_head[2] if on_head else None),
  7570. "tar_temp": self._tray_mid_temp(tray),
  7571. }
  7572. }
  7573. command_json = json.dumps(command)
  7574. logger.info(
  7575. "[%s] Publishing ams_change_filament (%s, AMS 3H slot %d): %s",
  7576. self.serial_number,
  7577. "load" if load else "unload",
  7578. slot + 1,
  7579. command_json,
  7580. )
  7581. client.publish(self.topic_publish, command_json, qos=1)
  7582. if load:
  7583. self.state.pending_tray_target = tray_id
  7584. self.state.pending_tray_target_at = time.monotonic()
  7585. else:
  7586. self.state.pending_tray_target = None
  7587. self.state.pending_tray_target_at = None
  7588. return True
  7589. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  7590. """Load filament from a specific AMS tray.
  7591. Args:
  7592. tray_id: Global tray ID — 0..15 for AMS slots, 24..27 for the A2L
  7593. AMS-Lite, 128..135 for an AMS-HT (its unit id), 254 for external spool
  7594. (single-external printers and Ext-L on dual-nozzle H2D),
  7595. 255 for Ext-R on dual-nozzle H2D.
  7596. extruder_id: Which hotend to feed (0 = right/main, 1 = left/deputy).
  7597. Sent only when given, matching BambuStudio: ``extruder_id`` is
  7598. an optional field on ``ams_change_filament``
  7599. (``DeviceManager::command_ams_change_filament``) and Studio
  7600. omits it unless a Filament Track Switch is installed. Without a
  7601. switch the firmware derives the hotend from the AMS's own
  7602. extruder binding and an explicit value is redundant; *with* one
  7603. every AMS reports 0xE and is bound to a switch inlet instead, so
  7604. the firmware has nothing to derive from and the load silently
  7605. does nothing until we name the hotend.
  7606. Returns:
  7607. True if command was sent, False otherwise
  7608. """
  7609. if not self._client or not self.state.connected:
  7610. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  7611. return False
  7612. if self.tray_layout.rack_units:
  7613. # Only an AMS 3H slot can be loaded: an external input or an AMS-B
  7614. # can't feed itself (Studio's CanAutoFeed).
  7615. rack = self._rack_tray(tray_id)
  7616. if rack is None or self.tray_layout.ams_type(rack[0]) != AmsType.ZMULTI_A:
  7617. logger.warning("[%s] Load: tray %s is not an AMS 3H slot", self.serial_number, tray_id)
  7618. return False
  7619. if not self.rack_tray_has_filament(tray_id):
  7620. logger.warning("[%s] Load: AMS 3H slot %d has no filament", self.serial_number, rack[1] + 1)
  7621. return False
  7622. return self._rack_change_filament(tray_id, load=True)
  7623. # Build the ams_change_filament command. Encoding differs by target type:
  7624. # - AMS slots (0..15, A2L 24..27, AMS-HT 128..135): see
  7625. # change_filament_wire_ids; curr/tar_temp = -1.
  7626. # - External spool (tray_id=254): legacy capture from a single-extruder
  7627. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  7628. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  7629. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  7630. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  7631. self._sequence_id += 1
  7632. wire_target = tray_id
  7633. if tray_id == 255:
  7634. ams_id = 255
  7635. slot_id = 0 # extruder index for the right nozzle
  7636. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  7637. if right_temp < 180:
  7638. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  7639. curr_temp = right_temp
  7640. tar_temp = right_temp
  7641. elif tray_id == 254:
  7642. ams_id = 255
  7643. slot_id = 254
  7644. curr_temp = -1
  7645. tar_temp = -1
  7646. else:
  7647. # A regular AMS, the A2L AMS-Lite (physical unit 16) or an AMS-HT
  7648. # (128-135), as BambuStudio addresses each.
  7649. ams_id, slot_id, wire_target = change_filament_wire_ids(tray_id, self.tray_layout)
  7650. curr_temp = -1
  7651. tar_temp = -1
  7652. command = {
  7653. "print": {
  7654. "command": "ams_change_filament",
  7655. "sequence_id": str(self._sequence_id),
  7656. "ams_id": ams_id,
  7657. "slot_id": slot_id,
  7658. "target": wire_target,
  7659. "curr_temp": curr_temp,
  7660. "tar_temp": tar_temp,
  7661. }
  7662. }
  7663. if extruder_id is not None:
  7664. command["print"]["extruder_id"] = int(extruder_id)
  7665. command_json = json.dumps(command)
  7666. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  7667. self._client.publish(self.topic_publish, command_json, qos=1)
  7668. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  7669. # Track this load request for H2D dual-nozzle disambiguation
  7670. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  7671. self.state.pending_tray_target = tray_id
  7672. self.state.pending_tray_target_at = time.monotonic()
  7673. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  7674. return True
  7675. def ams_unload_filament(self, tray_id: int | None = None) -> bool:
  7676. """Unload filament, optionally naming the slot to unload.
  7677. Args:
  7678. tray_id: Global tray ID of the slot being unloaded. When given, the
  7679. command is addressed to that slot's AMS and is only sent if an
  7680. extruder is actually fed from it — BambuStudio does the same
  7681. (``StatusPanel::on_ams_unload`` walks the extruders and sends
  7682. nothing when none matches). When omitted, the pre-existing
  7683. behaviour is kept: unload whatever ``tray_now`` names.
  7684. ``tray_now`` is a single value for the whole printer, so on a dual-nozzle
  7685. machine with both hotends loaded it names only one of them and an
  7686. unaddressed unload picks that one regardless of which slot the operator
  7687. clicked. Passing the slot is what makes the two hotends distinguishable.
  7688. Returns:
  7689. True if command was sent, False otherwise
  7690. """
  7691. if not self._client or not self.state.connected:
  7692. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  7693. return False
  7694. if self.tray_layout.rack_units:
  7695. # The hotend of the named AMS 3H slot, else of the one on the toolhead.
  7696. source = tray_id if tray_id is not None else self.state.tray_now
  7697. if self._rack_tray(source) is None:
  7698. logger.warning("[%s] Unload: no AMS 3H slot to unload (tray %s)", self.serial_number, source)
  7699. return False
  7700. return self._rack_change_filament(source, load=False)
  7701. # Get the currently loaded tray info
  7702. tray_now = self.state.tray_now
  7703. source_tray = tray_now if tray_id is None else tray_id
  7704. logger.info("[%s] Unload requested, tray_now=%s, tray_id=%s", self.serial_number, tray_now, tray_id)
  7705. # Determine source ams_id for the unload command
  7706. if source_tray == 255 or source_tray == 254:
  7707. ams_id = 255 # No filament or external spool
  7708. else:
  7709. # Source AMS: the A2L AMS-Lite as physical 16, an AMS-HT as its unit id.
  7710. ams_id = change_filament_wire_ids(source_tray, self.tray_layout)[0]
  7711. # Refuse an addressed unload of a slot no hotend is holding — but only on
  7712. # a printer that has more than one hotend, which is the only case the
  7713. # check exists for. With one hotend there is nothing to disambiguate:
  7714. # tray_now already names the loaded slot exactly, and running the check
  7715. # anyway would stake unload on `snow` meaning ams*4+slot there too. It
  7716. # very likely does, but single-nozzle machines do report the block —
  7717. # BambuStudio has a dedicated branch for `m_total_extder_count == 1` and
  7718. # an X1C on the maintainer's own network sends `device.extruder` — and
  7719. # nobody has read a single-nozzle `snow` off the wire. Guessing wrong
  7720. # would 409 every unload on every X1C, P1S and A1.
  7721. #
  7722. # Gated on the runtime flag rather than on len(extruder_slots), which is
  7723. # rebuilt from each payload's array and would flip the check off for any
  7724. # frame that carried a short one; and deliberately not on
  7725. # ``is_dual_nozzle_model``, whose model-name fallback reports at least
  7726. # one single-nozzle machine as dual (#1386) — the false positive there is
  7727. # exactly the case this gate exists to keep out.
  7728. #
  7729. # The external spool is excluded for a different reason: 254/255 are not
  7730. # ams*4+slot, so the local-slot arithmetic below cannot describe them.
  7731. if tray_id is not None and tray_id not in (254, 255) and self._is_dual_nozzle and self.state.extruder_slots:
  7732. local_slot = change_filament_wire_ids(tray_id, self.tray_layout)[1]
  7733. holder = next(
  7734. (ext for ext, slot in self.state.extruder_slots.items() if slot.holds(ams_id, local_slot)),
  7735. None,
  7736. )
  7737. if holder is None:
  7738. logger.info(
  7739. "[%s] Unload skipped: no extruder is fed from AMS %s slot %s",
  7740. self.serial_number,
  7741. ams_id,
  7742. local_slot,
  7743. )
  7744. return False
  7745. logger.info(
  7746. "[%s] Unloading AMS %s slot %s from extruder %s", self.serial_number, ams_id, local_slot, holder
  7747. )
  7748. # Command format from BambuStudio traffic capture:
  7749. # - No extruder_id field
  7750. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  7751. # - slot_id=255 and target=255 for unload
  7752. # Get current nozzle temperature for the unload command
  7753. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  7754. if nozzle_temp < 180:
  7755. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  7756. self._sequence_id += 1
  7757. command = {
  7758. "print": {
  7759. "command": "ams_change_filament",
  7760. "sequence_id": str(self._sequence_id),
  7761. "ams_id": ams_id,
  7762. "slot_id": 255, # 255 = unload marker
  7763. "target": 255, # 255 = unload destination
  7764. "curr_temp": nozzle_temp,
  7765. "tar_temp": nozzle_temp,
  7766. }
  7767. }
  7768. command_json = json.dumps(command)
  7769. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  7770. self._client.publish(self.topic_publish, command_json, qos=1)
  7771. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  7772. # Clear tracked load request since we're unloading
  7773. self.state.pending_tray_target = None
  7774. self.state.pending_tray_target_at = None
  7775. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  7776. return True
  7777. def ams_control(self, action: str) -> bool:
  7778. """Control AMS operations.
  7779. Args:
  7780. action: "resume", "reset", or "pause"
  7781. Returns:
  7782. True if command was sent, False otherwise
  7783. """
  7784. if not self._client or not self.state.connected:
  7785. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  7786. return False
  7787. if action not in ("resume", "reset", "pause"):
  7788. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  7789. return False
  7790. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  7791. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7792. logger.info("[%s] AMS control: %s", self.serial_number, action)
  7793. return True
  7794. async def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  7795. """Trigger RFID re-read for a specific AMS tray.
  7796. Sends ``ams_get_rfid`` and waits for the printer's answer. Firmware
  7797. that refuses it (#3206: X1Plus on base 01.08.02.00 answers ``FAIL`` /
  7798. ``ERROR STATE``) gets the legacy ``M620 R<global tray>`` gcode instead,
  7799. which is what Bambu Studio sends to printers without the new protocol.
  7800. The fallback only follows an explicit refusal, so firmware that takes
  7801. ``ams_get_rfid`` never sees it.
  7802. Success means the printer accepted the request, not that the tag was
  7803. read: the slot updating in the next push is the only proof of that.
  7804. Args:
  7805. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  7806. tray_id: Tray ID within the AMS (0-3)
  7807. Returns:
  7808. Tuple of (success, message)
  7809. """
  7810. if not self._client or not self.state.connected:
  7811. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  7812. return False, "Printer not connected"
  7813. # Check if filament is currently loaded (tray_now != 255)
  7814. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  7815. tray_now = self.state.tray_now
  7816. if tray_now != 255:
  7817. # Decode which tray is loaded for the message
  7818. layout = self.tray_layout
  7819. if tray_now == 254:
  7820. loaded_tray = "external spool"
  7821. elif (rack := layout.rack_slot(tray_now)) is not None:
  7822. loaded_tray = f"{unit_label(rack[0], layout.ams_type(rack[0]))} slot {rack[1] + 1}"
  7823. elif tray_now >= 0 and tray_now < 128:
  7824. loaded_ams, loaded_slot = layout.slot_key(tray_now)
  7825. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  7826. else:
  7827. loaded_tray = f"tray {tray_now}"
  7828. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  7829. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  7830. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  7831. wire_ams_id, wire_slot_id = ams_id, tray_id
  7832. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7833. wire_ams_id, wire_slot_id, _ = _a2l
  7834. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  7835. refused = await self._send_rfid_command(
  7836. {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id}
  7837. )
  7838. if refused is None:
  7839. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  7840. # M620 R only for what Bambu Studio sends it to: a model older than the
  7841. # newer protocol, on one of the four regular AMS units (the only ones
  7842. # with a legacy global tray index). Never during a job either: a
  7843. # gcode_line would be executed inside the running print.
  7844. from backend.app.utils.printer_models import uses_legacy_rfid_refresh
  7845. if (
  7846. not 0 <= wire_ams_id <= 3
  7847. or not uses_legacy_rfid_refresh(self.model)
  7848. or self.state.state in _ACTIVE_PRINT_STATES
  7849. ):
  7850. return False, f"Printer refused the RFID refresh: {refused}"
  7851. logger.info(
  7852. "[%s] ams_get_rfid refused (%s), falling back to M620 R%s",
  7853. self.serial_number,
  7854. refused,
  7855. legacy_tray_index(wire_ams_id, wire_slot_id),
  7856. )
  7857. legacy_refused = await self._send_rfid_command(
  7858. {"command": "gcode_line", "param": f"M620 R{legacy_tray_index(wire_ams_id, wire_slot_id)}\n"}
  7859. )
  7860. if legacy_refused is None:
  7861. return True, f"Refreshing AMS {ams_id} tray {tray_id} (legacy command)"
  7862. return False, f"Printer refused the RFID refresh: {legacy_refused}"
  7863. # The answer to ams_get_rfid was measured at 11ms in #3206's capture.
  7864. _rfid_ack_timeout: float = 3.0
  7865. async def _send_rfid_command(self, print_command: dict) -> str | None:
  7866. """Publish one RFID refresh command and wait for the printer's answer.
  7867. Returns the printer's reason when it answered ``FAIL``, else None.
  7868. No answer within ``_rfid_ack_timeout`` counts as accepted, because
  7869. silence is not evidence of refusal and older firmware may not answer
  7870. at all.
  7871. """
  7872. timeout = self._rfid_ack_timeout
  7873. self._sequence_id += 1
  7874. seq_id = str(self._sequence_id)
  7875. command = {"print": {**print_command, "sequence_id": seq_id}}
  7876. self._pending_rfid_acks[seq_id] = None
  7877. try:
  7878. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  7879. deadline = time.monotonic() + timeout
  7880. while time.monotonic() < deadline:
  7881. ack = self._pending_rfid_acks.get(seq_id)
  7882. if ack is not None:
  7883. if str(ack.get("result", "")).lower() == "fail":
  7884. return str(ack.get("reason", "") or "") or "printer reported failure"
  7885. return None
  7886. await asyncio.sleep(0.05)
  7887. finally:
  7888. self._pending_rfid_acks.pop(seq_id, None)
  7889. logger.info(
  7890. "[%s] No answer to %s seq=%s within %.1fs", self.serial_number, print_command["command"], seq_id, timeout
  7891. )
  7892. return None
  7893. def ams_set_filament_setting(
  7894. self,
  7895. ams_id: int,
  7896. tray_id: int,
  7897. tray_info_idx: str,
  7898. tray_type: str,
  7899. tray_sub_brands: str,
  7900. tray_color: str,
  7901. nozzle_temp_min: int,
  7902. nozzle_temp_max: int,
  7903. setting_id: str = "",
  7904. ) -> bool:
  7905. """Set AMS tray filament settings (type, color, temperature).
  7906. Note: K value is set separately via extrusion_cali_sel command.
  7907. Args:
  7908. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7909. tray_id: Tray ID within the AMS (0-3)
  7910. tray_info_idx: Filament ID short format (e.g., "GFL05")
  7911. tray_type: Filament type (e.g., "PLA", "PETG")
  7912. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  7913. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  7914. nozzle_temp_min: Minimum nozzle temperature
  7915. nozzle_temp_max: Maximum nozzle temperature
  7916. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  7917. Returns:
  7918. True if command was sent, False otherwise
  7919. """
  7920. if not self._client or not self.state.connected:
  7921. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  7922. return False
  7923. # Calculate mqtt IDs based on AMS type.
  7924. # External-spool convention verified against a BambuStudio→X1C packet capture
  7925. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  7926. # *global* tray index in `tray_id`, not a local position within the virtual
  7927. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  7928. # is what the original code was matching — but the request and response
  7929. # use different semantics for that field. Sending `tray_id: 0` is what
  7930. # the P1S in #1279 rejected with `result: "fail"`.
  7931. if ams_id == 255:
  7932. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  7933. if len(vt_tray) > 1:
  7934. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  7935. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  7936. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  7937. # captured Studio→H2D exchange confirms the correct value.
  7938. mqtt_ams_id = external_tray_id(tray_id)
  7939. mqtt_tray_id = 0
  7940. else:
  7941. # Single external slot (X1C, P1S, A1): global tray_id=254.
  7942. mqtt_ams_id = 255
  7943. mqtt_tray_id = 254
  7944. slot_id = 0
  7945. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  7946. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  7947. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  7948. mqtt_ams_id, slot_id, _ = _a2l
  7949. mqtt_tray_id = slot_id
  7950. elif self._rack_ams_type(ams_id) is not None:
  7951. # AMS 3H: unit 32 with its slot 0-8 in tray_id and slot_id (verified).
  7952. mqtt_ams_id = ams_id
  7953. mqtt_tray_id = slot_id = tray_id
  7954. elif ams_id <= 3:
  7955. mqtt_ams_id = ams_id
  7956. mqtt_tray_id = tray_id
  7957. slot_id = tray_id
  7958. else:
  7959. # AMS-HT: single tray per unit
  7960. mqtt_ams_id = ams_id
  7961. mqtt_tray_id = tray_id
  7962. slot_id = 0
  7963. command = {
  7964. "print": {
  7965. "command": "ams_filament_setting",
  7966. "ams_id": mqtt_ams_id,
  7967. "tray_id": mqtt_tray_id,
  7968. "slot_id": slot_id,
  7969. "tray_info_idx": tray_info_idx,
  7970. "tray_type": tray_type,
  7971. "tray_sub_brands": tray_sub_brands,
  7972. # UPPERCASE, always: lowercase hex is silently read as zeros by
  7973. # P1S firmware and acknowledged as a success (#2987).
  7974. "tray_color": wire_tray_color(tray_color),
  7975. "nozzle_temp_min": nozzle_temp_min,
  7976. "nozzle_temp_max": nozzle_temp_max,
  7977. "sequence_id": "0",
  7978. }
  7979. }
  7980. # Include setting_id if provided (helps slicer show correct profile)
  7981. if setting_id:
  7982. command["print"]["setting_id"] = setting_id
  7983. command_json = json.dumps(command)
  7984. logger.info(
  7985. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  7986. )
  7987. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  7988. self._client.publish(self.topic_publish, command_json, qos=1)
  7989. self._last_ams_cmd_time = time.monotonic()
  7990. return True
  7991. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  7992. """Reset an AMS slot to empty/unconfigured state.
  7993. Args:
  7994. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  7995. tray_id: Tray ID within the AMS (0-3)
  7996. Returns:
  7997. True if command was sent, False otherwise
  7998. """
  7999. if not self._client or not self.state.connected:
  8000. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  8001. return False
  8002. # Calculate mqtt IDs based on AMS type — same convention as
  8003. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  8004. if ams_id == 255:
  8005. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8006. if len(vt_tray) > 1:
  8007. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8008. mqtt_ams_id = external_tray_id(tray_id)
  8009. mqtt_tray_id = 0
  8010. else:
  8011. # Single external slot (X1C, P1S, A1): global tray_id=254.
  8012. mqtt_ams_id = 255
  8013. mqtt_tray_id = 254
  8014. slot_id = 0
  8015. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8016. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  8017. mqtt_ams_id, slot_id, _ = _a2l
  8018. mqtt_tray_id = slot_id
  8019. elif self._rack_ams_type(ams_id) is not None:
  8020. # AMS 3H: unit 32 with its slot 0-8 (see ams_set_filament_setting).
  8021. mqtt_ams_id = ams_id
  8022. mqtt_tray_id = slot_id = tray_id
  8023. elif ams_id <= 3:
  8024. mqtt_ams_id = ams_id
  8025. mqtt_tray_id = tray_id
  8026. slot_id = tray_id
  8027. else:
  8028. # AMS-HT: single tray per unit
  8029. mqtt_ams_id = ams_id
  8030. mqtt_tray_id = tray_id
  8031. slot_id = 0
  8032. command = {
  8033. "print": {
  8034. "command": "ams_filament_setting",
  8035. "ams_id": mqtt_ams_id,
  8036. "tray_id": mqtt_tray_id,
  8037. "slot_id": slot_id,
  8038. "tray_info_idx": "",
  8039. "tray_type": "",
  8040. "tray_sub_brands": "",
  8041. "tray_color": "00000000",
  8042. "nozzle_temp_min": 0,
  8043. "nozzle_temp_max": 0,
  8044. "sequence_id": "0",
  8045. }
  8046. }
  8047. command_json = json.dumps(command)
  8048. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  8049. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  8050. self._client.publish(self.topic_publish, command_json, qos=1)
  8051. self._last_ams_cmd_time = time.monotonic()
  8052. return True
  8053. def extrusion_cali_sel(
  8054. self,
  8055. ams_id: int,
  8056. tray_id: int,
  8057. cali_idx: int,
  8058. filament_id: str,
  8059. nozzle_diameter: str = "0.4",
  8060. ) -> bool:
  8061. """Set calibration profile (K value) for an AMS slot.
  8062. This command selects a K profile from the printer's calibration list.
  8063. Use cali_idx=-1 to use the default K value (0.020).
  8064. Note: Do NOT send setting_id in this command — BambuStudio never includes
  8065. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  8066. Args:
  8067. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  8068. tray_id: Tray ID within the AMS (0-3)
  8069. cali_idx: Calibration profile index (-1 for default)
  8070. filament_id: Filament preset ID (same as tray_info_idx)
  8071. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8072. Returns:
  8073. True if command was sent, False otherwise
  8074. """
  8075. if not self._client or not self.state.connected:
  8076. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  8077. return False
  8078. # Calculate mqtt IDs based on AMS type.
  8079. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  8080. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  8081. if ams_id == 255:
  8082. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  8083. # ams_filament_setting which uses LOCAL tray_id=0).
  8084. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  8085. if len(vt_tray) > 1:
  8086. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  8087. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  8088. mqtt_ams_id = external_tray_id(tray_id)
  8089. mqtt_tray_id = external_tray_id(tray_id)
  8090. else:
  8091. # Single external slot (X1C, P1S, A1): global tray_id=254
  8092. mqtt_ams_id = 254
  8093. mqtt_tray_id = 254
  8094. slot_id = 0
  8095. elif self._rack_ams_type(ams_id) is not None:
  8096. # AMS 3H: unit 32, slot k in tray_id and slot_id ({32, 8, 8} verified).
  8097. mqtt_ams_id = ams_id
  8098. mqtt_tray_id = slot_id = tray_id
  8099. elif ams_id <= 3:
  8100. mqtt_ams_id = ams_id
  8101. mqtt_tray_id = legacy_tray_index(ams_id, tray_id)
  8102. slot_id = tray_id
  8103. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  8104. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  8105. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  8106. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  8107. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  8108. elif is_ams_ht_id(ams_id):
  8109. mqtt_ams_id = ams_id
  8110. mqtt_tray_id = tray_id
  8111. slot_id = 0
  8112. else:
  8113. mqtt_ams_id = ams_id
  8114. mqtt_tray_id = tray_id
  8115. slot_id = 0
  8116. command = {
  8117. "print": {
  8118. "command": "extrusion_cali_sel",
  8119. "cali_idx": cali_idx,
  8120. "filament_id": filament_id,
  8121. "nozzle_diameter": nozzle_diameter,
  8122. "ams_id": mqtt_ams_id,
  8123. "tray_id": mqtt_tray_id,
  8124. "slot_id": slot_id,
  8125. "sequence_id": "0",
  8126. }
  8127. }
  8128. command_json = json.dumps(command)
  8129. logger.info(
  8130. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  8131. )
  8132. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  8133. self._client.publish(self.topic_publish, command_json, qos=1)
  8134. return True
  8135. def extrusion_cali_set(
  8136. self,
  8137. tray_id: int,
  8138. k_value: float,
  8139. nozzle_diameter: str = "0.4",
  8140. nozzle_temp: int = 220,
  8141. filament_id: str = "",
  8142. setting_id: str = "",
  8143. name: str = "",
  8144. cali_idx: int = -1,
  8145. ) -> bool:
  8146. """Directly set K value (pressure advance) for a tray.
  8147. Uses the filaments array format required by current firmware.
  8148. Args:
  8149. tray_id: Global tray ID (ams_id * 4 + slot)
  8150. k_value: Pressure advance K value (e.g., 0.020)
  8151. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  8152. nozzle_temp: Nozzle temperature for calibration reference
  8153. filament_id: Filament preset ID (e.g., "GFA02")
  8154. setting_id: Setting ID (e.g., "GFSA02_07")
  8155. name: Profile display name
  8156. cali_idx: Calibration index (-1 for new)
  8157. Returns:
  8158. True if command was sent, False otherwise
  8159. """
  8160. if not self._client or not self.state.connected:
  8161. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  8162. return False
  8163. # Was reusing the previous command's id — harmless while nothing
  8164. # correlated on it, but the printer echoes sequence_id back and the
  8165. # K-profile write path now matches acks by it (#2718).
  8166. self._sequence_id += 1
  8167. nozzle_id = f"HS00-{nozzle_diameter}"
  8168. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  8169. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  8170. # stays 0 (hardcoded, as for every other unit here).
  8171. wire_tray_id = tray_id
  8172. if (
  8173. 0 <= tray_id <= 253
  8174. and (_a2l := a2l_lite_wire_ids(self.tray_layout.slot_key(tray_id)[0], tray_id)) is not None
  8175. ):
  8176. wire_tray_id = _a2l[2]
  8177. filament_entry = {
  8178. "ams_id": 0,
  8179. "cali_idx": cali_idx,
  8180. "extruder_id": 0,
  8181. "filament_id": filament_id,
  8182. "k_value": f"{k_value:.6f}",
  8183. "n_coef": "1.400000",
  8184. "name": name,
  8185. "nozzle_diameter": nozzle_diameter,
  8186. "nozzle_id": nozzle_id,
  8187. "setting_id": setting_id,
  8188. "tray_id": wire_tray_id,
  8189. }
  8190. command = {
  8191. "print": {
  8192. "command": "extrusion_cali_set",
  8193. "filaments": [filament_entry],
  8194. "nozzle_diameter": nozzle_diameter,
  8195. "sequence_id": str(self._sequence_id),
  8196. }
  8197. }
  8198. command_json = json.dumps(command)
  8199. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  8200. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  8201. self._client.publish(self.topic_publish, command_json, qos=1)
  8202. return True
  8203. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  8204. """Dispatch the user's choice from the HMS-error modal as a printer command.
  8205. Args:
  8206. print_error: Canonical hex identifier for the fault — 8 chars for the
  8207. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  8208. (HMSError.full_code). Carried through unchanged from the route.
  8209. Converted to its DECIMAL string form for the `ignore` /
  8210. `idle_ignore` commands' `err` field, which is what the firmware
  8211. actually compares against the active fault. The pre-#1869
  8212. hex-string `err` was silently rejected because the firmware was
  8213. being asked to match `"05008051"` against int 0x05008051
  8214. (= 83918929 decimal) — see BambuStudio's
  8215. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  8216. `std::to_string(int m_error_code)`.
  8217. action: One of HMSAction's string values.
  8218. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  8219. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  8220. shapes; empty string is the no-job-id sentinel.
  8221. Returns False when the MQTT client is offline or when `action` is unknown
  8222. so the route surfaces it as a 4xx rather than a silent no-op.
  8223. """
  8224. if not self._client or not self.state.connected:
  8225. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  8226. return False
  8227. # Always re-push the full state after a command so the modal's underlying
  8228. # status query reflects the new error list (or absence) on the next tick.
  8229. def publish(payload: dict):
  8230. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  8231. self._client.publish(
  8232. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  8233. )
  8234. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  8235. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  8236. # every command_hms_* call). Our route hands us the hex string —
  8237. # convert. Falls back to the raw input if it's not parseable so the
  8238. # firmware can reject it and the route can surface 502 instead of us
  8239. # raising ValueError mid-dispatch.
  8240. try:
  8241. err_decimal = str(int(print_error, 16))
  8242. except ValueError:
  8243. err_decimal = print_error
  8244. def hms_resume():
  8245. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  8246. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  8247. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  8248. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  8249. # shape historically because it works, and changing it without a
  8250. # field test risks regressing a path that the user has confirmed.
  8251. publish(
  8252. {
  8253. "print": {
  8254. "command": "resume",
  8255. "param": "",
  8256. "sequence_id": "0",
  8257. }
  8258. }
  8259. )
  8260. def hms_stop():
  8261. # Same as hms_resume — plain shape, confirmed working by the user
  8262. # for "Stop Printing".
  8263. publish(
  8264. {
  8265. "print": {
  8266. "command": "stop",
  8267. "param": "",
  8268. "sequence_id": "0",
  8269. }
  8270. }
  8271. )
  8272. def hms_ignore_command():
  8273. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  8274. # what the "Ignore this and Resume" button actually publishes.
  8275. # Distinct from `idle_ignore`: this command has the firmware
  8276. # suppress the next re-check of the named fault AND resume the
  8277. # paused print in a single operation. The previous Bambuddy code
  8278. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  8279. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  8280. # the problem, re-check normally" so the firmware re-detected the
  8281. # wrong plate and re-paused with the same code (#1869).
  8282. #
  8283. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  8284. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  8285. # variant of "don't remind next time" lives on `idle_ignore`'s
  8286. # type=1, not as a separate ignore shape.
  8287. publish(
  8288. {
  8289. "print": {
  8290. "command": "ignore",
  8291. "err": err_decimal,
  8292. "param": "reserve",
  8293. "job_id": job_id or "",
  8294. "sequence_id": "0",
  8295. }
  8296. }
  8297. )
  8298. def hms_idle_ignore(persistent: bool = False):
  8299. # `idle_ignore` is BambuStudio's "dismiss this warning without
  8300. # resuming" command for non-pause warnings — what
  8301. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  8302. # type=0 dismisses once, type=1 suppresses the same warning
  8303. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  8304. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  8305. # NOT via the resume-bearing `ignore` command.
  8306. publish(
  8307. {
  8308. "print": {
  8309. "command": "idle_ignore",
  8310. "err": err_decimal,
  8311. "type": 1 if persistent else 0,
  8312. "sequence_id": "0",
  8313. }
  8314. }
  8315. )
  8316. def ams_control(param: str):
  8317. publish(
  8318. {
  8319. "print": {
  8320. "command": "ams_control",
  8321. "param": param,
  8322. "sequence_id": "0",
  8323. }
  8324. }
  8325. )
  8326. def clean_print_error():
  8327. # Matches the existing `clear_hms_errors` shape — Bambu does not
  8328. # expect `print_error` in the body; the command clears whatever
  8329. # error dialog is currently active on the printer.
  8330. publish(
  8331. {
  8332. "print": {
  8333. "command": "clean_print_error",
  8334. "sequence_id": "0",
  8335. }
  8336. }
  8337. )
  8338. def uiop_close():
  8339. # `err` is the 8-char hex short code (already a string from the
  8340. # frontend), uppercased for consistency with how BambuStudio sends it.
  8341. publish(
  8342. {
  8343. "system": {
  8344. "command": "uiop",
  8345. "name": "print_error",
  8346. "action": "close",
  8347. "source": 1,
  8348. "type": "dialog",
  8349. "err": print_error.upper(),
  8350. "sequence_id": "0",
  8351. }
  8352. }
  8353. )
  8354. match action:
  8355. case (
  8356. HMSAction.RESUME_PRINTING
  8357. | HMSAction.RESUME_PRINTING_DEFECTS
  8358. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  8359. | HMSAction.PROBLEM_SOLVED_RESUME
  8360. | HMSAction.FILAMENT_LOAD_RESUME
  8361. | HMSAction.PROCEED
  8362. ):
  8363. hms_resume()
  8364. case HMSAction.STOP_PRINTING:
  8365. hms_stop()
  8366. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  8367. # All three buttons map to BambuStudio's `command_hms_ignore`
  8368. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  8369. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  8370. # responsibility — the wire shape is identical.
  8371. hms_ignore_command()
  8372. case HMSAction.NO_REMINDER_NEXT_TIME:
  8373. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  8374. # `command_hms_idle_ignore` with type=0
  8375. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  8376. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  8377. # dismisses the dialog.
  8378. hms_idle_ignore(persistent=False)
  8379. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  8380. ams_control("done")
  8381. case (
  8382. HMSAction.RETRY_FILAMENT_EXTRUDED
  8383. | HMSAction.CONTINUE
  8384. | HMSAction.RETRY_PROBLEM_SOLVED
  8385. | HMSAction.DBL_CHECK_RETRY
  8386. ):
  8387. ams_control("resume")
  8388. case HMSAction.ABORT:
  8389. ams_control("abort")
  8390. case HMSAction.OK_BUTTON:
  8391. clean_print_error()
  8392. case HMSAction.DBL_CHECK_OK:
  8393. clean_print_error()
  8394. uiop_close()
  8395. case HMSAction.DBL_CHECK_RESUME:
  8396. # Plain resume — not HMS-aware, no err/job_id.
  8397. publish(
  8398. {
  8399. "print": {
  8400. "command": "resume",
  8401. "param": "",
  8402. "sequence_id": "0",
  8403. }
  8404. }
  8405. )
  8406. case HMSAction.REFRESH_NOZZLE:
  8407. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  8408. case HMSAction.TURN_OFF_FIRE_ALARM:
  8409. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  8410. case HMSAction.STOP_DRYING:
  8411. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  8412. case HMSAction.DISABLE_PURIFICATION:
  8413. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  8414. case (
  8415. HMSAction.CHECK_ASSISTANT
  8416. | HMSAction.JUMP_TO_LIVEVIEW
  8417. | HMSAction.OK_JUMP_RACK
  8418. | HMSAction.REMOVE_CLOSE_BTN
  8419. | HMSAction.LOAD_VIRTUAL_TRAY
  8420. | HMSAction.CANCLE
  8421. | HMSAction.DBL_CHECK_CANCEL
  8422. ):
  8423. # UI-only actions — the printer's own screen handles these; the
  8424. # modal still surfaces them so the user has parity with Studio.
  8425. pass
  8426. case _:
  8427. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  8428. return False
  8429. return True