bambu_mqtt.py 415 KB

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