bambu_mqtt.py 323 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508
  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. logger = logging.getLogger(__name__)
  22. # AMS module name prefixes used in get_version responses.
  23. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  24. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  25. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  26. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  27. _AMS_MODULE_PREFIXES = ("ams/", "n3f/", "n3s/")
  28. # gcode_state values that mean the printer is not idle and must not be handed a
  29. # new start-print (#2598). The firmware rejects a project_file while busy with
  30. # 0500_4004 "Device is busy and cannot start a new task", and on some models
  31. # (A1 mini reported) that error cancels the RUNNING job. IDLE / FINISH / FAILED
  32. # are valid start targets and are deliberately excluded. Mirrors
  33. # printer_manager.ACTIVE_PRINT_STATES and print_scheduler._ACTIVE_PRINT_STATES.
  34. _ACTIVE_PRINT_STATES = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  35. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  36. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  37. OrcaSlicer reads bit 18 of the hex string via
  38. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  39. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  40. that doesn't yield a clean integer so downstream consumers preserve today's
  41. behaviour rather than treating "absent" as "OFF".
  42. """
  43. if not isinstance(cfg_raw, str) or not cfg_raw:
  44. return None
  45. try:
  46. return bool((int(cfg_raw, 16) >> 18) & 1)
  47. except ValueError:
  48. return None
  49. # ── A2L "AMS Lite" unit-id normalisation (issue capture 2026-07-20) ──────────
  50. # The A2L reports its 4-slot AMS Lite as physical unit **id 16**, but the
  51. # firmware is internally inconsistent about it:
  52. # - its tray bitmasks (tray_exist_bits etc.) sit at **bit base 24**, i.e. the
  53. # position for id 6 (6*4), NOT id 16 (which would be bit 64);
  54. # - it reports `tray_now` as a **local** 0-3 slot, not a global id;
  55. # - `ams_mapping2` and per-unit commands use the **physical** id 16.
  56. # So we normalise 16 -> 6 at the MQTT ingest boundary. Global tray ids then land
  57. # at 24-27, which every `ams_id*4+slot` consumer handles unchanged, collides with
  58. # nothing (regular AMS 0-15, AMS-HT 128-135, external 254/255) and passes the
  59. # `ams_id <= 7` DB constraint. We translate 6 -> 16 (and the local slot) back to
  60. # the physical form ONLY on the outbound wire. See memory a2l-am-unit-16.
  61. A2L_LITE_PHYSICAL_AMS_ID = 16
  62. A2L_LITE_NORMALIZED_AMS_ID = 6
  63. A2L_LITE_GLOBAL_BASE = A2L_LITE_NORMALIZED_AMS_ID * 4 # 24
  64. def normalize_am_unit_id(ams_id: int) -> int:
  65. """Map the A2L AMS-Lite's physical unit id (16) to its normalised id (6).
  66. Self-scoping: only id 16 is remapped, and no other Bambu device reports an
  67. AMS unit at id 16 (regular AMS 0-3, AMS-HT 128-135). All other ids pass
  68. through untouched.
  69. """
  70. return A2L_LITE_NORMALIZED_AMS_ID if ams_id == A2L_LITE_PHYSICAL_AMS_ID else ams_id
  71. def a2l_lite_wire_ids(ams_id: int, tray_id: int) -> tuple[int, int, int] | None:
  72. """Translate a normalised A2L slot back to the physical wire form.
  73. Returns ``(wire_ams_id, wire_slot_id, wire_global_tray)`` for the AMS-Lite
  74. (normalised id 6), else ``None`` for every other unit.
  75. CONFIRMED from the firmware's own `ams_mapping2` ({ams_id:16, slot_id:0-3}):
  76. the wire uses the physical unit id 16 with a **local** 0-3 slot. NOT yet
  77. confirmed by capture: the physical **global** tray value some commands put on
  78. the wire (load `target`, extrusion_cali `tray_id`) — we extrapolate it as
  79. 16*4+slot = 64-67 to stay consistent with the physical unit id. This is the
  80. single unverified encoding; a BambuStudio->A2L capture of a load or cali
  81. command would settle it, and it lives only here.
  82. """
  83. if ams_id != A2L_LITE_NORMALIZED_AMS_ID:
  84. return None
  85. local_slot = tray_id % 4
  86. return (
  87. A2L_LITE_PHYSICAL_AMS_ID,
  88. local_slot,
  89. A2L_LITE_PHYSICAL_AMS_ID * 4 + local_slot,
  90. )
  91. def apply_tray_exist_bits(
  92. units: list,
  93. tray_exist_bits_str: str | int | None,
  94. *,
  95. power_on_flag: bool = True,
  96. log_label: str | None = None,
  97. annotate_exists: bool = False,
  98. ) -> int:
  99. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  100. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  101. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  102. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  103. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  104. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  105. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  106. instead of guessing from payload shape (#1322, #147).
  107. Two callers share this helper to keep their views consistent:
  108. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  109. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  110. facing push_status (#1726 — without this the VP would forward stale
  111. per-tray fields for empty slots, and BambuStudio's Sync would render
  112. phantom loaded slots).
  113. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  114. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  115. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  116. so spool removal is detected without requiring a manual reconnect.
  117. AMS-HT units (``id`` 128-135) are single-tray dry boxes whose presence bit
  118. is packed as ONE consecutive bit starting at 16 (``16 + (ams_id - 128)``),
  119. NOT ``ams_id * 4`` (which would overflow to bit 512+). This is the firmware's
  120. authoritative empty signal for the HT — the only working clear path, since
  121. the HT keeps echoing stale ``tray_type`` and its ``state`` is firmware-variant
  122. (#2670). Verified against OrcaSlicer ``DevFilaSystem.cpp``
  123. (``is_exists = tray_exist_bits >> (16 + (ams_id-128))``) and a live H2D
  124. capture (HT-A → bit 16). The A2L-Lite (normalised to id 6 upstream) lands at
  125. bits 24-27 via the regular ``ams_id * 4`` formula, matching OrcaSlicer's
  126. ``AMS_LITE_MIXED`` offset, so it needs no special case here.
  127. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  128. way). Ints are tolerated for defensive symmetry but typically not seen
  129. on the wire. ``None`` / empty / unparseable → no-op.
  130. ``annotate_exists`` writes a per-tray ``exists`` bool (from the bitmask) on
  131. every processed slot. This is firmware's authoritative "spool physically
  132. present" signal — the same one BambuStudio uses to draw a ``?`` for a
  133. non-RFID spool in an otherwise-unidentified slot. Bambuddy's AMS card keys
  134. empty-vs-unknown off it so a non-Bambu spool shows ``?`` instead of "Empty"
  135. (#2527). Only the internal (printer-card) caller sets this; the VP bridge
  136. leaves it False so the ``exists`` key never reaches the slicer wire format.
  137. Mutates ``units`` in place. Returns the number of slots cleared.
  138. """
  139. if not tray_exist_bits_str:
  140. return 0
  141. try:
  142. if isinstance(tray_exist_bits_str, int):
  143. tray_exist_bits = tray_exist_bits_str
  144. else:
  145. tray_exist_bits = int(tray_exist_bits_str, 16)
  146. except (ValueError, TypeError):
  147. return 0
  148. if tray_exist_bits == 0 and not power_on_flag:
  149. return 0
  150. if not isinstance(units, list):
  151. return 0
  152. cleared = 0
  153. for ams_unit in units:
  154. if not isinstance(ams_unit, dict):
  155. continue
  156. ams_id_raw = ams_unit.get("id")
  157. if ams_id_raw is None:
  158. continue
  159. try:
  160. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  161. except (ValueError, TypeError):
  162. continue
  163. if not isinstance(ams_id, int):
  164. continue
  165. # AMS-HT (n3s, id 128-135): single tray, presence bit at 16+(ams_id-128).
  166. # Regular AMS (and the A2L-Lite normalised to id 6): ams_id*4 + tray_id.
  167. # Anything outside those ranges has no known bit layout — don't guess it.
  168. is_ht = 128 <= ams_id <= 135
  169. if not is_ht and not (0 <= ams_id <= 15):
  170. continue
  171. for tray in ams_unit.get("tray", []):
  172. if not isinstance(tray, dict):
  173. continue
  174. tray_id_raw = tray.get("id")
  175. if tray_id_raw is None:
  176. continue
  177. try:
  178. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  179. except (ValueError, TypeError):
  180. continue
  181. if not isinstance(tray_id, int):
  182. continue
  183. global_bit = (16 + (ams_id - 128)) if is_ht else (ams_id * 4 + tray_id)
  184. slot_exists = (tray_exist_bits >> global_bit) & 1
  185. if annotate_exists:
  186. tray["exists"] = bool(slot_exists)
  187. if slot_exists:
  188. continue
  189. tray["state"] = 9
  190. if tray.get("tray_type"):
  191. if log_label:
  192. logger.debug(
  193. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  194. f"(tray_exist_bits bit {global_bit} = 0)"
  195. )
  196. tray["tray_type"] = ""
  197. tray["tray_sub_brands"] = ""
  198. tray["tray_color"] = ""
  199. tray["tray_id_name"] = ""
  200. tray["tag_uid"] = "0000000000000000"
  201. tray["tray_uuid"] = "00000000000000000000000000000000"
  202. tray["tray_info_idx"] = ""
  203. tray["remain"] = 0
  204. cleared += 1
  205. return cleared
  206. @dataclass
  207. class MQTTLogEntry:
  208. """Log entry for MQTT message debugging."""
  209. timestamp: str
  210. topic: str
  211. direction: str # "in" or "out"
  212. payload: dict
  213. @dataclass
  214. class HMSError:
  215. """Health Management System error from printer."""
  216. code: str
  217. attr: int # Attribute value for constructing wiki URL
  218. module: int
  219. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  220. message: str = ""
  221. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  222. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  223. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  224. # HMSError without explicitly passing actions can't silently land None on the schema
  225. # boundary and raise ValidationError at routes/printers.py response time.
  226. actions: list[str] = field(default_factory=list)
  227. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  228. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  229. job_id: str | None = None
  230. # Canonical hex identifier for the firmware's `err` matching: 16 chars for the
  231. # 64-bit `hms[]` array path (`f"{attr:08X}{code:08X}"`), 8 chars for the
  232. # 32-bit `print_error` path. The frontend echoes this back to
  233. # execute_hms_action; the truncated 8-char short code that `_parse_status`
  234. # used to send caused the firmware to silently reject HMS commands on H2C
  235. # (#1830) and on `hms[]`-sourced faults generally.
  236. full_code: str = ""
  237. # HMS short codes the firmware emits during normal user-cancel sequences.
  238. # These aren't faults — they're status echoes that confirm the cancel happened.
  239. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  240. # so they don't drive the printer card's "X problem" badge, the red pip, or
  241. # any other consumer that treats hms_errors as the active-fault list.
  242. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  243. {
  244. "0300_400C", # "The task was canceled."
  245. "0500_400E", # "Printing was cancelled."
  246. }
  247. )
  248. @dataclass
  249. class KProfile:
  250. """Pressure advance (K) calibration profile from printer."""
  251. slot_id: int
  252. extruder_id: int
  253. nozzle_id: str
  254. nozzle_diameter: str
  255. filament_id: str
  256. name: str
  257. k_value: str
  258. n_coef: str = "0.000000"
  259. ams_id: int = 0
  260. tray_id: int = -1
  261. setting_id: str | None = None
  262. @dataclass
  263. class NozzleInfo:
  264. """Nozzle hardware configuration."""
  265. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  266. nozzle_diameter: str = "" # e.g., "0.4"
  267. @dataclass
  268. class FilaSwitchState:
  269. """Filament Track Switch (FTS) accessory state.
  270. The FTS is an external accessory that mediates filament routing between an
  271. AMS and the printer's extruders. When installed, the AMS no longer has a
  272. fixed extruder assignment — any slot can be routed to any extruder via the
  273. track switch. Detected from print.device.fila_switch in MQTT.
  274. """
  275. installed: bool = False
  276. # in[track] = currently loaded slot for that track (-1 = empty). The slot
  277. # value is reported as observed in MQTT (treated as a global tray ID).
  278. in_slots: list[int] = field(default_factory=list)
  279. # out[track] = extruder this track terminates at (0 = right/main, 1 = left)
  280. out_extruders: list[int] = field(default_factory=list)
  281. stat: int = 0 # status flags (0 = idle)
  282. info: int = 0 # info flags
  283. @dataclass
  284. class PrintOptions:
  285. """AI detection and print options from xcam data."""
  286. # Core AI detectors
  287. spaghetti_detector: bool = False
  288. print_halt: bool = False
  289. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  290. first_layer_inspector: bool = False
  291. printing_monitor: bool = False # AI print quality monitoring
  292. buildplate_marker_detector: bool = False
  293. allow_skip_parts: bool = False
  294. # Additional AI detectors - decoded from cfg bitmask
  295. nozzle_clumping_detector: bool = True
  296. nozzle_clumping_sensitivity: str = "medium"
  297. pileup_detector: bool = True
  298. pileup_sensitivity: str = "medium"
  299. airprint_detector: bool = True
  300. airprint_sensitivity: str = "medium"
  301. auto_recovery_step_loss: bool = True # Uses print.print_option command
  302. filament_tangle_detect: bool = False
  303. @dataclass
  304. class PrinterState:
  305. connected: bool = False
  306. state: str = "unknown"
  307. current_print: str | None = None
  308. subtask_name: str | None = None
  309. progress: float = 0.0
  310. remaining_time: int = 0
  311. layer_num: int = 0
  312. total_layers: int = 0
  313. temperatures: dict = field(default_factory=dict)
  314. raw_data: dict = field(default_factory=dict)
  315. gcode_file: str | None = None
  316. subtask_id: str | None = None
  317. hms_errors: list = field(default_factory=list) # List of HMSError
  318. kprofiles: list = field(default_factory=list) # List of KProfile
  319. sdcard: bool = False # SD card inserted
  320. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  321. timelapse: bool = False # Timelapse recording active
  322. ipcam: bool = False # Live view / camera streaming enabled
  323. wifi_signal: int | None = None # WiFi signal strength in dBm
  324. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  325. door_open: bool = False # Enclosure door open (home_flag bit 23; models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  326. # Nozzle hardware info (for dual nozzle printers, index 0 = left, 1 = right)
  327. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  328. # AI detection and print options
  329. print_options: PrintOptions = field(default_factory=PrintOptions)
  330. # Calibration stage tracking (from stg_cur and stg fields)
  331. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  332. stg: list = field(default_factory=list) # List of stages to execute
  333. # Air conditioning mode (0=cooling, 1=heating)
  334. airduct_mode: int = 0
  335. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  336. speed_level: int = 2
  337. # Chamber light on/off
  338. chamber_light: bool = False
  339. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  340. active_extruder: int = 0
  341. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  342. tray_now: int = 255
  343. # Firmware's target/previous tray as reported in print.ams (RAW, not globalised):
  344. # tray_tar = the slot the paused/loading print now expects
  345. # tray_pre = the slot that was loaded before (e.g. the one that ran out)
  346. # For a single regular AMS these equal the global tray ID; for multi-AMS they
  347. # are local slot IDs (0-3) that must be resolved against the mapping field, and
  348. # for AMS-HT they are already global (128-135). 255 = none/idle, 254 = external.
  349. # Surfaced during a runout PAUSE so the UI can name the expected slot (#2587).
  350. tray_tar: int = 255
  351. tray_pre: int = 255
  352. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  353. last_loaded_tray: int = -1
  354. # Pending load target - used to track what tray we're loading for H2D disambiguation
  355. pending_tray_target: int | None = None
  356. # AMS status for filament change tracking (from print.ams.ams_status field)
  357. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  358. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  359. ams_status: int = 0
  360. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  361. ams_status_sub: int = 0 # ams_status & 0xFF
  362. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  363. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  364. mc_print_sub_stage: int = 0
  365. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  366. ams_mapping: list = field(default_factory=list)
  367. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  368. ams_extruder_map: dict = field(default_factory=dict)
  369. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  370. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  371. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  372. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  373. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  374. # regex used to derive the plate number from the path always falls back to
  375. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  376. # Bambuddy dispatches the print itself we know the plate authoritatively;
  377. # we record it here and prefer it over the gcode_file regex. The subtask
  378. # field guards against staleness: if the printer is currently running a
  379. # different subtask (e.g. a Studio-direct dispatch), these values are
  380. # ignored. Cleared on disconnect.
  381. dispatched_plate_id: int | None = None
  382. dispatched_subtask: str | None = None
  383. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  384. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  385. h2d_extruder_snow: dict = field(default_factory=dict)
  386. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  387. nozzle_rack: list = field(default_factory=list)
  388. # Timestamp of last AMS data update (for RFID refresh detection)
  389. last_ams_update: float = 0.0
  390. # Printable objects for skip object functionality: {identify_id: object_name}
  391. printable_objects: dict = field(default_factory=dict)
  392. # Objects that have been skipped during the current print
  393. skipped_objects: list = field(default_factory=list)
  394. # Fan speeds (0-100 percentage, None if not available for this model)
  395. cooling_fan_speed: int | None = None # Part cooling fan
  396. big_fan1_speed: int | None = None # Auxiliary fan
  397. big_fan2_speed: int | None = None # Chamber/exhaust fan
  398. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  399. # Left auxiliary part cooling fan (optional accessory on P2S/X2D). Reported ONLY
  400. # via device.airduct.parts (decoded part id 10 = FAN_REMOTE_COOLING_1 in Bambu
  401. # Studio's AIR_FUN enum) — the firmware does NOT mirror it into any flat
  402. # big_fanX_speed field, which is why it was previously dropped. 0-100 percent.
  403. left_aux_fan_speed: int | None = None
  404. # Chamber exhaust fan (P2S/X2D External Exhaust Fan kit). Presence is derived
  405. # from the airduct parts list containing decoded id 3; a base P2S omits it.
  406. exhaust_fan_present: bool = False
  407. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  408. # Used by usage tracker to split filament weight on mid-print tray switch
  409. tray_change_log: list = field(default_factory=list)
  410. # Firmware version info (from info.module[name="ota"].sw_ver)
  411. firmware_version: str | None = None
  412. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  413. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  414. developer_mode: bool | None = None
  415. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  416. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  417. # which uses the old protocol path; field not yet found). Consumers must treat
  418. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  419. ams_filament_backup: bool | None = None
  420. # Stage name mapping from BambuStudio DeviceManager.cpp
  421. STAGE_NAMES = {
  422. 0: "Printing",
  423. 1: "Auto bed leveling",
  424. 2: "Heatbed preheating",
  425. 3: "Vibration compensation",
  426. 4: "Changing filament",
  427. 5: "M400 pause",
  428. 6: "Paused (filament ran out)",
  429. 7: "Heating nozzle",
  430. 8: "Calibrating dynamic flow",
  431. 9: "Scanning bed surface",
  432. 10: "Inspecting first layer",
  433. 11: "Identifying build plate type",
  434. 12: "Calibrating Micro Lidar",
  435. 13: "Homing toolhead",
  436. 14: "Cleaning nozzle tip",
  437. 15: "Checking extruder temperature",
  438. 16: "Paused by the user",
  439. 17: "Pause (front cover fall off)",
  440. 18: "Calibrating the micro lidar",
  441. 19: "Calibrating flow ratio",
  442. 20: "Pause (nozzle temperature malfunction)",
  443. 21: "Pause (heatbed temperature malfunction)",
  444. 22: "Filament unloading",
  445. 23: "Pause (step loss)",
  446. 24: "Filament loading",
  447. 25: "Motor noise cancellation",
  448. 26: "Pause (AMS offline)",
  449. 27: "Pause (low speed of the heatbreak fan)",
  450. 28: "Pause (chamber temperature control problem)",
  451. 29: "Cooling chamber",
  452. 30: "Pause (Gcode inserted by user)",
  453. 31: "Motor noise showoff",
  454. 32: "Pause (nozzle clumping)",
  455. 33: "Pause (cutter error)",
  456. 34: "Pause (first layer error)",
  457. 35: "Pause (nozzle clog)",
  458. 36: "Measuring motion precision",
  459. 37: "Enhancing motion precision",
  460. 38: "Measure motion accuracy",
  461. 39: "Nozzle offset calibration",
  462. 40: "High temperature auto bed leveling",
  463. 41: "Auto Check: Quick Release Lever",
  464. 42: "Auto Check: Door and Upper Cover",
  465. 43: "Laser Calibration",
  466. 44: "Auto Check: Platform",
  467. 45: "Confirming BirdsEye Camera location",
  468. 46: "Calibrating BirdsEye Camera",
  469. 47: "Auto bed leveling - phase 1",
  470. 48: "Auto bed leveling - phase 2",
  471. 49: "Heating chamber",
  472. 50: "Cooling heatbed",
  473. 51: "Printing calibration lines",
  474. 52: "Auto Check: Material",
  475. 53: "Live View Camera Calibration",
  476. 54: "Waiting for heatbed temperature",
  477. 55: "Auto Check: Material Position",
  478. 56: "Cutting Module Offset Calibration",
  479. 57: "Measuring Surface",
  480. 58: "Thermal Preconditioning",
  481. 59: "Homing Blade Holder",
  482. 60: "Calibrating Camera Offset",
  483. 61: "Calibrating Blade Holder Position",
  484. 62: "Hotend Pick and Place Test",
  485. 63: "Waiting for Chamber temperature",
  486. 64: "Preparing Hotend",
  487. 65: "Calibrating nozzle clumping detection",
  488. 66: "Purifying the chamber air",
  489. 74: "Preparing", # Seen on H2D during print preparation
  490. 77: "Preparing AMS",
  491. }
  492. def get_stage_name(stage: int) -> str:
  493. """Get human-readable stage name from stage number."""
  494. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  495. class BambuMQTTClient:
  496. """MQTT client for Bambu Lab printer communication."""
  497. MQTT_PORT = 8883
  498. # Class-level cache: serial_number -> False when request topic is known unsupported.
  499. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  500. _request_topic_cache: dict[str, bool] = {}
  501. # Counter for generating unique MQTT client IDs across instances.
  502. _client_instance_counter: int = 0
  503. # #2582: how long to wait for the AMS telemetry to echo back an assignment
  504. # before declaring it un-confirmed. The printer re-broadcasts tray state
  505. # every few seconds (and register_assignment_verification nudges a fresh
  506. # pushall), so this only has to survive a couple of idle push intervals.
  507. ASSIGNMENT_VERIFY_TIMEOUT: float = 30.0
  508. def __init__(
  509. self,
  510. ip_address: str,
  511. serial_number: str,
  512. access_code: str,
  513. model: str | None = None,
  514. on_state_change: Callable[[PrinterState], None] | None = None,
  515. on_print_start: Callable[[dict], None] | None = None,
  516. on_print_complete: Callable[[dict], None] | None = None,
  517. on_ams_change: Callable[[list], None] | None = None,
  518. on_layer_change: Callable[[int], None] | None = None,
  519. on_bed_temp_update: Callable[[float], None] | None = None,
  520. on_drying_complete: Callable[[int], None] | None = None,
  521. on_print_running_observed: Callable[[dict], None] | None = None,
  522. on_finish_photo_moment: Callable[[dict], None] | None = None,
  523. on_assignment_verified: Callable[[int, int, bool, dict], None] | None = None,
  524. ):
  525. self.ip_address = ip_address
  526. self.serial_number = serial_number
  527. self.access_code = access_code
  528. self.model = model
  529. # Last value logged by _debug_on_change(), keyed by log site. See there.
  530. self._debug_last: dict[str, object] = {}
  531. self.on_state_change = on_state_change
  532. self.on_print_start = on_print_start
  533. self.on_print_complete = on_print_complete
  534. self.on_ams_change = on_ams_change
  535. self.on_layer_change = on_layer_change
  536. self.on_bed_temp_update = on_bed_temp_update
  537. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  538. # the drying cycle just finished (auto- or manually-triggered).
  539. # Receives the AMS id of the unit that finished drying.
  540. self.on_drying_complete = on_drying_complete
  541. # #1485 follow-up: fired the first time we see RUNNING state in a
  542. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  543. # print, the #1304 first-push guard skipped the start event). Lets
  544. # main.py capture a fresh timelapse baseline at restart-recovery
  545. # time so the completion-time snapshot-diff still works. Receives
  546. # the same shape as on_print_start (filename / subtask_name /
  547. # remaining_time / raw_data / ams_mapping).
  548. self.on_print_running_observed = on_print_running_observed
  549. # #1721: fired the moment the printer enters the end-of-print
  550. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  551. # we've hit the last layer / remaining_time<=0). This is the
  552. # framing #1397 was after — toolhead parked, bed not yet
  553. # dropped — but reached via a clean state signal instead of
  554. # the per-layer M622 J1 macros which caused per-layer nozzle
  555. # parks on slicer profiles with Timelapse Type = Smooth.
  556. # A FINISH-state fallback below fires this same callback if
  557. # stage 22 never arrives (cancel mid-print, external-spool-
  558. # only prints, HMS halt before unload, firmware variants).
  559. self.on_finish_photo_moment = on_finish_photo_moment
  560. # #2582: fired after a spool assignment (ams_filament_setting +
  561. # extrusion_cali_sel) once the tray's telemetry either confirms the
  562. # push landed or a timeout elapses without it. Receives
  563. # (ams_id, tray_id, verified: bool, detail: dict). Lets the frontend
  564. # tell the user "loaded" vs "assignment didn't take" instead of the
  565. # historic fire-and-forget silence that made the AMS/Studio hand-off
  566. # feel random. See _check_assignment_verifications.
  567. self.on_assignment_verified = on_assignment_verified
  568. # Pending read-back verifications, keyed by (ams_id, tray_id). Each
  569. # value is the desired end-state we just pushed plus a monotonic
  570. # deadline. Populated by register_assignment_verification, drained by
  571. # _check_assignment_verifications on every AMS push.
  572. self._pending_assignments: dict[tuple[int, int], dict] = {}
  573. # Per-AMS previous dry_time, used to detect the falling edge above.
  574. # Seeded lazily as we observe each AMS unit.
  575. self._previous_dry_times: dict[int, int] = {}
  576. # Per-AMS active-cycle target params (filament + temp) we sent on the
  577. # last start. Bambu does not echo these back in the per-tick AMS push
  578. # — only the dry_time countdown — so we cache what we sent to drive
  579. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  580. self._drying_targets: dict[int, dict[str, object]] = {}
  581. self.state = PrinterState()
  582. self._client: mqtt.Client | None = None
  583. self._loop: asyncio.AbstractEventLoop | None = None
  584. self._previous_gcode_state: str | None = None
  585. self._previous_gcode_file: str | None = None
  586. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  587. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  588. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  589. # #1721: one-shot guard so the end-of-print stage-22 detector
  590. # and the FINISH-state fallback don't both fire on the same
  591. # print. Reset to False on every print start.
  592. self._finish_photo_captured: bool = False
  593. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  594. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  595. # The subtask_id minted for the most recent start_print() command. The
  596. # printer echoes it back in status, but often not within the first few
  597. # seconds — so on_print_start uses this as the id source when the
  598. # printer hasn't reported it yet, letting queue/scheduled archives
  599. # persist a restart-stable id from the moment they dispatch (#1485).
  600. self.last_dispatch_subtask_id: str | None = None
  601. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  602. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  603. self._logging_enabled: bool = False
  604. self._last_message_time: float = 0.0 # Track when we last received a message
  605. # Count of report-topic messages received since the last (re)connect.
  606. # Lets check_staleness() distinguish "printer never sent a status
  607. # report" (typically a wrong / mis-cased serial) from a normal quiet
  608. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  609. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  610. self._report_messages_since_connect: int = 0
  611. self._zero_report_hint_logged: bool = False
  612. # Set by mark_power_off() to the gcode_state held just before we
  613. # optimistically forced the printer to "unknown" (#2629). Restored on
  614. # the next inbound message, because message traffic proves the power
  615. # was never actually cut. None whenever no power-off is presumed.
  616. self._state_before_power_off: str | None = None
  617. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  618. # printer's pushes verbatim to slicers connected to a virtual printer).
  619. # Handlers receive (topic, payload_bytes) before JSON parsing.
  620. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  621. self._disconnection_event: threading.Event | None = None
  622. self._previous_ams_hash: str | None = None # Track AMS changes
  623. # Track external-spool (vt_tray) identity changes separately: the AMS
  624. # hash above covers only AMS units, so an external-spool-only filament
  625. # swap would never re-trigger inventory reconciliation (#2575).
  626. self._previous_vt_tray_hash: str | None = None
  627. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  628. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  629. self._ams_version_cache: dict[int, dict[str, str]] = {}
  630. # Track which (ams_id, field) warnings have already been emitted this connection
  631. # so that missing-serial / missing-firmware warnings fire only once per connection.
  632. self._ams_version_warned: set[tuple[int | str, str]] = set()
  633. # K-profile command tracking
  634. self._sequence_id: int = 0
  635. self._pending_kprofile_response: asyncio.Event | None = None
  636. self._kprofile_response_data: list | None = None
  637. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  638. # Key: module_name, Value: timestamp when command was sent
  639. self._xcam_hold_start: dict[str, float] = {}
  640. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  641. # Track last requested tray ID for H2D dual-nozzle printers
  642. # H2D only reports slot number (0-3) in tray_now, not global tray ID
  643. # We use our tracked value to resolve the correct global ID
  644. self._last_load_tray_id: int | None = None
  645. # Captured ams_mapping from print commands on the request topic
  646. # Intercepts slicer/Bambuddy print commands to get the slot-to-tray mapping
  647. self._captured_ams_mapping: list[int] | None = None
  648. # True once we've seen (and normalised 16->6) an A2L AMS-Lite unit in the
  649. # AMS telemetry. Used to globalise the Lite's local `tray_now` to 24+slot.
  650. # See normalize_am_unit_id / a2l_lite_wire_ids and memory a2l-am-unit-16.
  651. self._has_a2l_am_unit: bool = False
  652. # Request topic subscription tracking
  653. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  654. # topic by killing the TCP connection. We detect this and gracefully degrade.
  655. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  656. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  657. self._request_topic_sub_mid: int | None = None
  658. self._request_topic_sub_time: float = 0.0
  659. self._request_topic_confirmed: bool = False
  660. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  661. # we probe by sending an ams_filament_setting and checking the response.
  662. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  663. self._dev_mode_probed: bool = False
  664. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  665. self._dev_mode_probe_seq: str | None = None
  666. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  667. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  668. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  669. # Set when check_staleness() force-closes the socket to trigger reconnect.
  670. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  671. self._stale_reconnecting: bool = False
  672. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  673. # when the frontend polls status faster than paho can reconnect.
  674. self._last_stale_reconnect: float = 0.0
  675. # Zombie session detection via ams_filament_setting response tracking (#887).
  676. # The dev-mode probe only runs on first connect; this catches zombie sessions
  677. # that develop later (telemetry flows but publishes silently fail).
  678. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  679. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  680. @property
  681. def topic_subscribe(self) -> str:
  682. return f"device/{self.serial_number}/report"
  683. @property
  684. def topic_publish(self) -> str:
  685. return f"device/{self.serial_number}/request"
  686. @property
  687. def report_messages_since_connect(self) -> int:
  688. """Count of report-topic messages received since the latest (re)connect.
  689. Exposed for the connection diagnostic so it can distinguish "MQTT
  690. broker accepted us but the printer never published" (typically a
  691. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  692. bridge that happens to be idle right now. Zero immediately after a
  693. fresh connect is normal; zero after a full status push cycle is the
  694. wrong-serial failure mode.
  695. """
  696. return self._report_messages_since_connect
  697. # Maximum time (seconds) without a message before considering connection stale
  698. STALE_TIMEOUT = 60.0
  699. def is_stale(self) -> bool:
  700. """Check if the connection is stale (no messages for too long)."""
  701. if self._last_message_time == 0:
  702. return False # Never received a message yet
  703. time_since_last = time.time() - self._last_message_time
  704. return time_since_last > self.STALE_TIMEOUT
  705. def mark_power_off(self) -> bool:
  706. """Presume the printer lost power (smart plug switched off).
  707. Optimistic: it skips the MQTT stale timeout so the UI updates at once.
  708. The presumption is undone by ``_on_message`` if the printer keeps
  709. talking — inbound traffic proves the power was never cut (#2629).
  710. Returns True when the state was actually changed.
  711. """
  712. if not self.state.connected:
  713. return False
  714. previous = self.state.state
  715. # Blank the state BEFORE recording what to restore. This runs on the
  716. # event loop while _on_message runs on the paho thread, and the restore
  717. # is a two-step (read saved state, compare against "unknown"). Writing
  718. # "unknown" first means an interleaved message either sees no saved
  719. # state yet (and skips, leaving the next message to restore) or sees a
  720. # consistent pair — never a saved state paired with a live state it
  721. # then discards, which would strand the printer on "unknown".
  722. self.state.connected = False
  723. self.state.state = "unknown"
  724. # Only the first mark wins: a second call before any message arrives
  725. # must not overwrite the real state with the "unknown" it just wrote.
  726. # Nothing to restore if the state was already blank.
  727. if self._state_before_power_off is None and previous not in ("", "unknown"):
  728. self._state_before_power_off = previous
  729. return True
  730. def _restore_state_after_false_power_off(self) -> bool:
  731. """Undo a presumed power-off once the printer proves it is alive.
  732. ``connected`` self-heals on the next message, but ``state`` does not:
  733. it is only rewritten when a payload carries ``gcode_state``, and the
  734. steady-state ``push_status`` frames are partial. Without this the
  735. forced "unknown" sticks until a full pushall (a manual Force Refresh),
  736. and the queue scheduler treats the printer as not idle the whole time
  737. (#2629). Returns True when a state was restored.
  738. """
  739. previous = self._state_before_power_off
  740. self._state_before_power_off = None
  741. if previous is None or self.state.state != "unknown":
  742. return False
  743. logger.info(
  744. "[%s] Printer still responding after presumed power-off — restoring state %s",
  745. self.serial_number,
  746. previous,
  747. )
  748. self.state.state = previous
  749. return True
  750. # Minimum seconds between stale reconnect attempts. Frontend polls
  751. # status every few seconds — without a cooldown, each poll would
  752. # force-close the socket before paho has time to reconnect.
  753. STALE_RECONNECT_COOLDOWN = 30.0
  754. def check_staleness(self) -> bool:
  755. """Check staleness and update connected state if stale. Returns True if connected."""
  756. if self.state.connected and self.is_stale():
  757. # Don't force-close again if we already did recently — give paho
  758. # time to reconnect and the printer time to send its first message.
  759. now = time.time()
  760. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  761. return self.state.connected
  762. logger.warning(
  763. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  764. )
  765. # A connection that keeps going stale without ever receiving a
  766. # status report is almost always a wrong or mis-cased serial
  767. # number — the broker accepts the connection and the subscription
  768. # regardless, but the printer publishes to device/<real-serial>/
  769. # report, which is case-sensitive. Surface that once so the user
  770. # has something actionable instead of an endless reconnect loop.
  771. if self._report_messages_since_connect == 0 and not self._zero_report_hint_logged:
  772. self._zero_report_hint_logged = True
  773. logger.warning(
  774. "[%s] Connected and subscribed, but the printer has sent zero "
  775. "status reports. The most common cause is a wrong or mis-cased "
  776. "serial number — the device/<serial>/report MQTT topic is "
  777. "case-sensitive. Verify the serial number configured in Bambuddy "
  778. "exactly matches the printer.",
  779. self.serial_number,
  780. )
  781. self._last_stale_reconnect = now
  782. self.state.connected = False
  783. if self.on_state_change:
  784. self.on_state_change(self.state)
  785. # Route based on caller thread — see force_reconnect_stale_session.
  786. # check_staleness is normally called from FastAPI handlers (async,
  787. # gets the hard-reset path) but the dispatcher exists for safety.
  788. self._stale_reconnecting = True
  789. self._reset_client_for_reconnect()
  790. return self.state.connected
  791. def force_reconnect_stale_session(self, reason: str) -> None:
  792. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  793. # arriving but our publishes don't reach the printer.
  794. #
  795. # Two routing paths:
  796. #
  797. # Async-context callers (queue dispatch deadline)
  798. # → full client teardown + fresh client_id. Wipes paho's client-side
  799. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  800. # `project_file` from the broken session would otherwise replay on
  801. # reconnect, mixing stale commands into the next dispatch and
  802. # triggering 0500_4003 SD R/W on the printer.
  803. #
  804. # Paho-network-thread callers (line ~2604/~2623 — dev-mode probe and
  805. # ams_filament_setting zombie detection inside `_update_state`)
  806. # → socket-close fallback. Calling `loop_stop()` from inside the
  807. # network thread would self-join and deadlock; the safe pattern is
  808. # to close the socket and let paho's own loop detect the broken
  809. # connection and auto-reconnect (same instance, same client_id —
  810. # queue replay is theoretically possible here but those paths have
  811. # always done socket-close and #1136 was specifically triggered
  812. # from the dispatch path).
  813. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  814. self._stale_reconnecting = True
  815. self.state.connected = False
  816. if self.on_state_change:
  817. self.on_state_change(self.state)
  818. self._reset_client_for_reconnect()
  819. def _reset_client_for_reconnect(self) -> None:
  820. """Route between hard-reset and socket-close based on caller thread.
  821. Hard-reset (preferred) requires we're not running on paho's network
  822. thread, since `loop_stop()` on the same thread deadlocks. Detect via
  823. ``asyncio.get_running_loop()`` — paho's callback thread has no loop;
  824. every legitimate hard-reset caller (FastAPI handlers, background
  825. async tasks) does."""
  826. try:
  827. loop = asyncio.get_running_loop()
  828. except RuntimeError:
  829. loop = None
  830. if loop is not None:
  831. self._loop = loop
  832. self._hard_reset_client()
  833. else:
  834. self._socket_close_for_reconnect()
  835. def _hard_reset_client(self) -> None:
  836. """Tear down the paho client entirely and rebuild it with a fresh
  837. client_id, so the broker drops the old session and paho's local
  838. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  839. Caller is responsible for setting ``_stale_reconnecting`` and
  840. broadcasting the disconnected state."""
  841. old_client = self._client
  842. self._client = None
  843. if old_client is not None:
  844. try:
  845. old_client.disconnect() # MQTT DISCONNECT — broker drops session
  846. except Exception:
  847. pass
  848. try:
  849. old_client.loop_stop() # blocks briefly until the network thread exits
  850. except Exception:
  851. pass
  852. # Skip reconnect if no asyncio loop is available (test environment or
  853. # pre-init). The next initial connect() call from PrinterManager will
  854. # set up the client fresh.
  855. if self._loop is None:
  856. return
  857. try:
  858. self.connect(loop=self._loop)
  859. except Exception as e:
  860. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  861. def _socket_close_for_reconnect(self) -> None:
  862. """Close the underlying socket so paho's loop thread detects the
  863. broken connection and triggers auto-reconnect on the SAME client
  864. instance. Safe to call from paho's own network thread (the loop
  865. polls the socket on every iteration and handles a closed socket
  866. gracefully). Used as a fallback when hard-reset isn't safe; queue
  867. replay remains theoretically possible here but #1136 specifically
  868. traced through the dispatch-deadline path which now hard-resets."""
  869. if self._client:
  870. try:
  871. sock = self._client.socket()
  872. if sock:
  873. sock.close()
  874. except Exception:
  875. pass
  876. def _on_connect(self, client, userdata, flags, rc, properties=None):
  877. if rc == 0:
  878. self.state.connected = True
  879. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  880. # A dropped-and-restored MQTT session means the presumed power-off was
  881. # real (or at least that the printer restarted): there is nothing
  882. # legitimate left to restore, and the printer will send a full status
  883. # push shortly. Dropping the saved state keeps a stale one from being
  884. # broadcast ahead of the first real report (#2629, #1679).
  885. self._state_before_power_off = None
  886. # Reset per-connection warning state so warnings fire once per (re)connection
  887. self._ams_version_warned = set()
  888. # Preserve cached developer_mode across auto-reconnects to avoid
  889. # re-probing on every reconnect. The probe (ams_filament_setting to
  890. # ext slot) can destabilize some firmware MQTT brokers, causing a
  891. # reconnect → probe → disconnect feedback loop (#887). Only probe
  892. # once when developer_mode is truly unknown (first connect).
  893. # Reset probe tracking so stale timeout state doesn't carry over.
  894. self._dev_mode_probed = False
  895. self._dev_mode_needs_probe = False
  896. self._dev_mode_probe_seq = None
  897. self._dev_mode_probe_time = 0.0
  898. self._dev_mode_probe_failures = 0
  899. self._connect_time = time.monotonic()
  900. self._report_messages_since_connect = 0
  901. self._last_ams_cmd_time = 0.0
  902. self._ams_cmd_unanswered = 0
  903. # Drop any assignment verifications that were mid-flight before the
  904. # reconnect — their deadlines are stale and the tray state we would
  905. # compare against is about to be re-pushed from scratch (#2582).
  906. # Dropping is silent (no failure event) on purpose.
  907. self._pending_assignments.clear()
  908. client.subscribe(self.topic_subscribe)
  909. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  910. if self._request_topic_supported:
  911. result, mid = client.subscribe(self.topic_publish)
  912. if result == mqtt.MQTT_ERR_SUCCESS:
  913. self._request_topic_sub_mid = mid
  914. self._request_topic_sub_time = time.time()
  915. self._request_topic_confirmed = False
  916. else:
  917. logger.warning(
  918. "[%s] Failed to send request topic subscription",
  919. self.serial_number,
  920. )
  921. self._request_topic_supported = False
  922. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  923. # Request full status update (includes nozzle info in push_status response)
  924. self._request_push_all()
  925. # Request firmware version info
  926. self._request_version()
  927. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  928. # The correct nozzle data comes from push_status.
  929. # Prime K-profile request (Bambu printers often ignore first request)
  930. self._prime_kprofile_request()
  931. # Immediately broadcast connection state change
  932. if self.on_state_change:
  933. self.on_state_change(self.state)
  934. else:
  935. self.state.connected = False
  936. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  937. """Handle SUBACK responses to detect request topic subscription rejection."""
  938. if mid == self._request_topic_sub_mid:
  939. for rc in reason_code_list:
  940. if rc.is_failure:
  941. logger.warning(
  942. "[%s] Request topic subscription rejected (code=%d: %s). "
  943. "ams_mapping capture from slicer-initiated prints unavailable.",
  944. self.serial_number,
  945. rc.value,
  946. rc.getName(),
  947. )
  948. self._request_topic_supported = False
  949. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  950. else:
  951. logger.info(
  952. "[%s] Request topic subscription accepted. "
  953. "ams_mapping capture enabled for slicer-initiated prints.",
  954. self.serial_number,
  955. )
  956. self._request_topic_confirmed = True
  957. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  958. self._request_topic_sub_mid = None
  959. self._request_topic_sub_time = 0.0
  960. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  961. # Always unblock disconnect() callers, regardless of whether we suppress
  962. # the state broadcast below. disconnect() sets _disconnection_event and
  963. # waits on it — every callback path must fire it.
  964. if self._disconnection_event:
  965. self._disconnection_event.set()
  966. # If we intentionally closed the socket for stale reconnect, don't broadcast
  967. # another state change — check_staleness() already set connected=False and
  968. # notified the UI. Just log and let paho auto-reconnect.
  969. if self._stale_reconnecting:
  970. logger.info(
  971. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  972. self.serial_number,
  973. rc,
  974. )
  975. return
  976. # Ignore spurious disconnect callbacks if we've received a message recently
  977. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  978. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  979. # — only suppress when rc indicates a clean/normal disconnect.
  980. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  981. time_since_last_message = time.time() - self._last_message_time
  982. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  983. logger.debug(
  984. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  985. )
  986. return
  987. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  988. # Detect if request topic subscription caused the disconnect.
  989. # If we just subscribed and got disconnected before any SUBACK confirmation,
  990. # the broker likely killed the connection due to the unauthorized subscription.
  991. if (
  992. self._request_topic_sub_time > 0
  993. and not self._request_topic_confirmed
  994. and time.time() - self._request_topic_sub_time < 10.0
  995. ):
  996. logger.warning(
  997. "[%s] Disconnected shortly after request topic subscription. Disabling request topic for this printer.",
  998. self.serial_number,
  999. )
  1000. self._request_topic_supported = False
  1001. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  1002. self._request_topic_sub_mid = None
  1003. self._request_topic_sub_time = 0.0
  1004. self.state.connected = False
  1005. if self.on_state_change:
  1006. self.on_state_change(self.state)
  1007. def _on_message(self, client, userdata, msg):
  1008. for handler in self._raw_message_handlers:
  1009. try:
  1010. handler(msg.topic, msg.payload)
  1011. except Exception:
  1012. logger.exception(
  1013. "[%s] raw-message handler crashed for topic=%s",
  1014. self.serial_number,
  1015. msg.topic,
  1016. )
  1017. try:
  1018. try:
  1019. raw = msg.payload.decode()
  1020. except UnicodeDecodeError:
  1021. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  1022. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  1023. raw = msg.payload.decode(errors="replace")
  1024. logger.warning(
  1025. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  1026. self.serial_number,
  1027. msg.topic,
  1028. len(msg.payload),
  1029. )
  1030. payload = json.loads(raw)
  1031. # Track last message time - receiving a message proves we're connected
  1032. self._last_message_time = time.time()
  1033. self.state.connected = True
  1034. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  1035. if msg.topic == self.topic_publish:
  1036. self._handle_request_message(payload)
  1037. return
  1038. # Count status reports per connection so check_staleness() can tell
  1039. # "printer never sent a report" apart from a mid-session quiet gap.
  1040. if msg.topic == self.topic_subscribe:
  1041. self._report_messages_since_connect += 1
  1042. # Only report-topic traffic proves the *printer* is alive — the
  1043. # request topic also carries slicer/Bambuddy commands.
  1044. if self._state_before_power_off is not None:
  1045. if self._restore_state_after_false_power_off() and self.on_state_change:
  1046. self.on_state_change(self.state)
  1047. # Log message if logging is enabled
  1048. if self._logging_enabled:
  1049. self._message_log.append(
  1050. MQTTLogEntry(
  1051. timestamp=datetime.now(timezone.utc).isoformat(),
  1052. topic=msg.topic,
  1053. direction="in",
  1054. payload=payload,
  1055. )
  1056. )
  1057. self._process_message(payload)
  1058. except json.JSONDecodeError:
  1059. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  1060. def _handle_request_message(self, data: dict) -> None:
  1061. """Intercept print commands on the request topic to capture ams_mapping."""
  1062. print_data = data.get("print", {})
  1063. if not isinstance(print_data, dict):
  1064. return
  1065. command = print_data.get("command", "")
  1066. if command == "project_file":
  1067. if "ams_mapping" in print_data:
  1068. self._captured_ams_mapping = print_data["ams_mapping"]
  1069. logger.info(
  1070. "[%s] Captured ams_mapping from print command: %s",
  1071. self.serial_number,
  1072. self._captured_ams_mapping,
  1073. )
  1074. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  1075. # slicer-launched project_file passes through the request topic,
  1076. # log the full payload so we can diff Studio's field set against
  1077. # ours. We pin our own sequence_id to "20000" (line ~3195), so
  1078. # any other value means the command came from Studio/Orca, not
  1079. # from us.
  1080. if print_data.get("sequence_id") != "20000":
  1081. logger.info(
  1082. "[%s] External project_file payload: %s",
  1083. self.serial_number,
  1084. json.dumps(print_data),
  1085. )
  1086. def _debug_on_change(self, key: str, value: object, msg: str, *args: object) -> None:
  1087. """``logger.debug``, but only when ``value`` differs from the last call for ``key``.
  1088. The state dumps in the push_status handler fire whenever their field is
  1089. *present* in the frame — and a full push_status carries every field, so
  1090. they fire on every frame regardless of whether anything changed. Several
  1091. even say "updated" or "changes" in their own comment while doing nothing
  1092. of the sort.
  1093. On one printer that is ~1.5 lines/s and nobody noticed. On the 19-printer
  1094. farm in #2555 it is ~100 lines/s, which fills the 5 MB log inside five
  1095. minutes: the reporter enabled debug logging as asked and the support
  1096. bundle came back holding under five minutes of history, almost none of it
  1097. about the queue problem we were chasing. 27,727 of its 29,830 lines were
  1098. these dumps.
  1099. Deduplicating on the value keeps every transition — which is the only part
  1100. anyone reads these lines for — and drops the steady-state repetition.
  1101. ``value`` must capture everything interpolated into ``msg``, or a change
  1102. will be swallowed; pass a tuple when the message renders several fields.
  1103. """
  1104. if not logger.isEnabledFor(logging.DEBUG):
  1105. # Debug logging is toggled at RUNTIME (POST /support/debug-logging),
  1106. # and these clients outlive the toggle. Letting INFO-level frames warm
  1107. # the cache would be self-defeating: the operator turns debug on
  1108. # precisely to see the printer's current state, and a cache already
  1109. # holding every steady-state value would suppress that baseline until
  1110. # something happened to change. On an idle printer the bundle would
  1111. # come back with none of these lines at all.
  1112. #
  1113. # So while debug is off we record nothing and drop whatever we had.
  1114. # Every enable then starts cold and dumps a full baseline on the next
  1115. # frame, exactly as it did before this method existed.
  1116. self._debug_last.clear()
  1117. return
  1118. if self._debug_last.get(key) == value:
  1119. return
  1120. self._debug_last[key] = value
  1121. logger.debug(msg, *args)
  1122. def _process_message(self, payload: dict):
  1123. """Process incoming MQTT message from printer."""
  1124. # Handle top-level AMS data (comes outside of "print" key)
  1125. # Wrap in try/except to prevent breaking the MQTT connection
  1126. if "ams" in payload:
  1127. try:
  1128. self._handle_ams_data(payload["ams"])
  1129. except Exception as e:
  1130. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  1131. # Handle xcam data (camera settings and AI detection) at top level
  1132. if "xcam" in payload:
  1133. xcam_data = payload["xcam"]
  1134. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  1135. self._parse_xcam_data(xcam_data)
  1136. # Fire state change callback for top-level xcam (not nested in "print")
  1137. if "print" not in payload and self.on_state_change:
  1138. self.on_state_change(self.state)
  1139. # Handle system responses (accessories info, etc.)
  1140. if "system" in payload:
  1141. system_data = payload["system"]
  1142. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  1143. self._handle_system_response(system_data)
  1144. # Handle info responses (firmware version info from get_version command)
  1145. if "info" in payload:
  1146. info_data = payload["info"]
  1147. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  1148. self._handle_version_info(info_data)
  1149. # Parse WiFi signal at top level (some printers send it here)
  1150. if "wifi_signal" in payload:
  1151. wifi_signal = payload["wifi_signal"]
  1152. if isinstance(wifi_signal, (int, float)):
  1153. self.state.wifi_signal = int(wifi_signal)
  1154. elif isinstance(wifi_signal, str):
  1155. try:
  1156. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  1157. except ValueError:
  1158. pass # Ignore unparseable wifi_signal strings; field is non-critical
  1159. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  1160. from backend.app.utils.printer_models import has_ethernet
  1161. if has_ethernet(self.model):
  1162. self.state.wired_network = self.state.wifi_signal == -90
  1163. # Parse developer LAN mode from top-level "fun" field
  1164. # Some firmware versions send "fun" at the top level, others inside "print"
  1165. if "fun" in payload:
  1166. try:
  1167. fun_val = payload["fun"]
  1168. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  1169. self.state.developer_mode = (fun_int & 0x20000000) == 0
  1170. except (ValueError, TypeError):
  1171. pass
  1172. if "print" in payload:
  1173. print_data = payload["print"]
  1174. # Check if xcam is nested inside print data
  1175. if "xcam" in print_data:
  1176. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  1177. self._parse_xcam_data(print_data["xcam"])
  1178. # Log when we see gcode_state changes
  1179. if "gcode_state" in print_data:
  1180. logger.debug(
  1181. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  1182. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  1183. )
  1184. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  1185. # new-protocol printers. Verified against OrcaSlicer's
  1186. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  1187. # and live H2D ON/OFF capture 2026-06-20.
  1188. #
  1189. # Hold-timer guard: when the user just toggled via the badge, the
  1190. # next 1-2 push_status frames may still carry the printer's OLD cfg
  1191. # for ~3 s before the firmware reflects the change. Without this
  1192. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  1193. new_backup = parse_ams_filament_backup_from_cfg(print_data.get("cfg"))
  1194. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  1195. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  1196. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  1197. logger.debug(
  1198. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  1199. self.serial_number,
  1200. time.time() - hold_start,
  1201. )
  1202. else:
  1203. logger.info(
  1204. "[%s] AMS Filament Backup: %s",
  1205. self.serial_number,
  1206. "ON" if new_backup else "OFF",
  1207. )
  1208. self.state.ams_filament_backup = new_backup
  1209. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  1210. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  1211. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  1212. if not self._is_dual_nozzle and "device" in print_data:
  1213. dev = print_data.get("device")
  1214. if isinstance(dev, dict):
  1215. ext_info = dev.get("extruder", {}).get("info", [])
  1216. if isinstance(ext_info, list) and len(ext_info) >= 2:
  1217. self._is_dual_nozzle = True
  1218. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  1219. # Handle AMS data that comes inside print key
  1220. if "ams" in print_data:
  1221. try:
  1222. self._handle_ams_data(print_data["ams"])
  1223. except Exception as e:
  1224. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  1225. # Handle vir_slot (H2-series external spool data) — list of external trays
  1226. # Process vir_slot FIRST so it takes priority over vt_tray
  1227. if "vir_slot" in print_data:
  1228. vir_slot = print_data["vir_slot"]
  1229. if isinstance(vir_slot, list) and vir_slot:
  1230. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  1231. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  1232. # Remap id=255→254 for single-slot printers so active detection works.
  1233. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  1234. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  1235. vir_slot[0]["id"] = "254"
  1236. self.state.raw_data["vt_tray"] = vir_slot
  1237. # Handle vt_tray (virtual tray / external spool) data
  1238. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  1239. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  1240. # which would overwrite the correct multi-slot vir_slot data)
  1241. if "vt_tray" in print_data and "vir_slot" not in print_data:
  1242. vt_tray = print_data["vt_tray"]
  1243. existing = self.state.raw_data.get("vt_tray")
  1244. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  1245. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  1246. pass # Keep the vir_slot data
  1247. else:
  1248. if isinstance(vt_tray, dict):
  1249. vt_tray = [vt_tray]
  1250. self.state.raw_data["vt_tray"] = vt_tray
  1251. # The regular AMS change-hash (in _handle_ams_data) only sees AMS
  1252. # units, and _handle_ams_data runs before this block — so a change
  1253. # to the external spool alone (e.g. swapping generic TPU for generic
  1254. # ABS on the printer) never re-triggers on_ams_change, leaving a
  1255. # stale inventory assignment on the ams_id=255 slot (#2575). Detect
  1256. # external-spool identity changes here and fire the same callback.
  1257. self._maybe_trigger_external_spool_change()
  1258. # Parse ams_status directly from print data (NOT from print.ams)
  1259. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1260. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  1261. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  1262. if "ams_status" in print_data:
  1263. raw_ams_status = print_data["ams_status"]
  1264. if isinstance(raw_ams_status, str):
  1265. try:
  1266. self.state.ams_status = int(raw_ams_status)
  1267. except ValueError:
  1268. self.state.ams_status = 0
  1269. else:
  1270. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  1271. # Compute main and sub status
  1272. self.state.ams_status_sub = self.state.ams_status & 0xFF
  1273. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  1274. # Log when ams_status changes (for filament change tracking debug)
  1275. self._debug_on_change(
  1276. "ams_status:print",
  1277. self.state.ams_status,
  1278. "[%s] ams_status: %s (main=%s, sub=%s)",
  1279. self.serial_number,
  1280. self.state.ams_status,
  1281. self.state.ams_status_main,
  1282. self.state.ams_status_sub,
  1283. )
  1284. # Check for command responses
  1285. if "command" in print_data:
  1286. cmd = print_data.get("command")
  1287. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  1288. if cmd in ("extrusion_cali_sel", "extrusion_cali_set", "extrusion_cali_del", "ams_filament_setting"):
  1289. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  1290. # AMS drying responses are rare (user-initiated only) and the
  1291. # full payload — including `result` and any `reason` code —
  1292. # is the only way to diagnose silent rejections like #1447.
  1293. # INFO level so the body lands in support bundles by default.
  1294. elif cmd == "ams_filament_drying":
  1295. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  1296. # Check for developer mode probe response
  1297. if (
  1298. cmd == "ams_filament_setting"
  1299. and self._dev_mode_probe_seq is not None
  1300. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  1301. ):
  1302. self._handle_dev_mode_probe_response(print_data)
  1303. # Track user-initiated ams_filament_setting responses (#887
  1304. # zombie detection). Reset both the timer AND the unanswered
  1305. # counter on ANY response — the response proves the channel is
  1306. # alive, so the counter must not stay armed even when the
  1307. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  1308. # tick. The original `and self._last_ams_cmd_time > 0` guard
  1309. # caused #1164: one sluggish response (>10s) would set the
  1310. # counter to 1 and zero the timer; the late response arrived
  1311. # but was ignored by this branch (timer is 0); the counter
  1312. # stayed at 1 indefinitely; the very next slow response —
  1313. # possibly hours later, on a totally unrelated command — would
  1314. # take it to 2 and force-reconnect, surfacing as "filament
  1315. # config doesn't reach the printer ~6 changes in".
  1316. elif cmd == "ams_filament_setting":
  1317. self._last_ams_cmd_time = 0.0
  1318. self._ams_cmd_unanswered = 0
  1319. is_kprofile_response = "command" in print_data and print_data.get("command") == "extrusion_cali_get"
  1320. if is_kprofile_response:
  1321. self._handle_kprofile_response(print_data)
  1322. # An extrusion_cali_get response echoes the *requested* nozzle
  1323. # diameter (get_kprofiles probes 0.2/0.4/0.6/0.8 in turn), not the
  1324. # installed hardware. Feeding it to _update_state clobbered the real
  1325. # nozzle size (#2663) — typically leaving 0.8, the last size probed,
  1326. # which then failed the #1899 dispatch guard. The response carries no
  1327. # status telemetry, so skip it; the true nozzle comes from pushall.
  1328. # (Same reasoning as get_accessories in _handle_system_response.)
  1329. if not is_kprofile_response:
  1330. self._update_state(print_data)
  1331. def _handle_system_response(self, data: dict):
  1332. """Handle system responses including accessories info.
  1333. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  1334. The correct nozzle data comes from push_status, so we don't update
  1335. nozzle type/diameter from get_accessories. We just log the response
  1336. for debugging purposes.
  1337. """
  1338. command = data.get("command")
  1339. if command == "get_accessories":
  1340. # Log response for debugging - but DON'T use it to update nozzle data
  1341. # because it returns stale values (e.g., 'stainless_steel' when the
  1342. # actual nozzle is 'HH01' hardened steel high-flow)
  1343. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  1344. def _handle_version_info(self, data: dict):
  1345. """Handle version info response from get_version command.
  1346. Parses firmware version from the 'ota' module in the module list.
  1347. Also extracts AMS unit firmware versions from AMS modules and stores
  1348. them on the corresponding AMS unit in raw_data so the status route can
  1349. expose them to the frontend.
  1350. AMS module naming conventions (numeric suffix is the AMS unit ID):
  1351. - ``ams/<id>`` – original AMS
  1352. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  1353. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  1354. Message format:
  1355. {
  1356. "command": "get_version",
  1357. "module": [
  1358. {"name": "ota", "sw_ver": "01.08.05.00"},
  1359. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  1360. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  1361. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  1362. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  1363. ...
  1364. ]
  1365. }
  1366. """
  1367. modules = data.get("module", [])
  1368. if not isinstance(modules, list):
  1369. return
  1370. state_changed = False
  1371. for module in modules:
  1372. if not isinstance(module, dict):
  1373. continue
  1374. if module.get("name") == "ota":
  1375. version = module.get("sw_ver")
  1376. if version:
  1377. old_version = self.state.firmware_version
  1378. self.state.firmware_version = version
  1379. if old_version != version:
  1380. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  1381. state_changed = True
  1382. break
  1383. # Extract AMS unit firmware versions from AMS modules.
  1384. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  1385. # Always cache regardless of whether AMS data has arrived yet — get_version
  1386. # often arrives before the first push_status, so caching must be unconditional.
  1387. ams_raw = self.state.raw_data.get("ams")
  1388. for module in modules:
  1389. if not isinstance(module, dict):
  1390. continue
  1391. name = module.get("name", "")
  1392. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  1393. continue
  1394. try:
  1395. ams_id = int(name.split("/", 1)[1])
  1396. except (ValueError, IndexError):
  1397. continue
  1398. sw_ver = module.get("sw_ver", "")
  1399. sn = module.get("sn", "")
  1400. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  1401. module_type = name.split("/", 1)[0]
  1402. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  1403. if sw_ver or sn or module_type:
  1404. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  1405. state_changed = True
  1406. # Also directly update any AMS unit already present in raw_data
  1407. if ams_raw and isinstance(ams_raw, list):
  1408. for ams_unit in ams_raw:
  1409. if not isinstance(ams_unit, dict):
  1410. continue
  1411. try:
  1412. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  1413. except (ValueError, TypeError):
  1414. unit_id = None
  1415. if unit_id == ams_id:
  1416. if sw_ver:
  1417. ams_unit["sw_ver"] = sw_ver
  1418. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  1419. # Only set sn from version info if not already present in AMS data
  1420. if sn and not ams_unit.get("sn"):
  1421. ams_unit["sn"] = sn
  1422. if module_type:
  1423. ams_unit["module_type"] = module_type
  1424. break
  1425. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  1426. # included in the broadcast (not just the printer firmware version).
  1427. if state_changed and self.on_state_change:
  1428. self.on_state_change(self.state)
  1429. # Warn if any AMS unit is still missing serial number or firmware version
  1430. # after processing the version info response. Warn only once per connection
  1431. # to avoid repeated noise on older firmware that doesn't report these fields.
  1432. if ams_raw and isinstance(ams_raw, list):
  1433. for ams_unit in ams_raw:
  1434. if not isinstance(ams_unit, dict):
  1435. continue
  1436. ams_id = ams_unit.get("id", "?")
  1437. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  1438. key = (ams_id, "sn")
  1439. if key not in self._ams_version_warned:
  1440. self._ams_version_warned.add(key)
  1441. logger.warning(
  1442. "[%s] AMS unit %s: serial number not available in version info",
  1443. self.serial_number,
  1444. ams_id,
  1445. )
  1446. if not ams_unit.get("sw_ver"):
  1447. key = (ams_id, "sw_ver")
  1448. if key not in self._ams_version_warned:
  1449. self._ams_version_warned.add(key)
  1450. logger.warning(
  1451. "[%s] AMS unit %s: firmware version not available in version info",
  1452. self.serial_number,
  1453. ams_id,
  1454. )
  1455. def _apply_ams_version_cache(self, ams_list: list) -> None:
  1456. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  1457. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  1458. strings in MQTT payloads. This helper normalizes IDs and fills missing
  1459. sw_ver/sn fields without overwriting values already present.
  1460. """
  1461. if not ams_list or not isinstance(ams_list, list):
  1462. return
  1463. cache = self._ams_version_cache
  1464. if not cache:
  1465. return
  1466. for unit in ams_list:
  1467. if not isinstance(unit, dict):
  1468. continue
  1469. raw_id = unit.get("id")
  1470. try:
  1471. unit_id = int(raw_id) if raw_id is not None else None
  1472. except (ValueError, TypeError):
  1473. unit_id = None
  1474. if unit_id is None:
  1475. continue
  1476. cached = cache.get(unit_id)
  1477. if not cached:
  1478. continue
  1479. sw_ver = cached.get("sw_ver") or ""
  1480. sn = cached.get("sn") or ""
  1481. if sw_ver and not unit.get("sw_ver"):
  1482. unit["sw_ver"] = sw_ver
  1483. # Only set sn if not already present in AMS data
  1484. if sn and not unit.get("sn") and not unit.get("serial_number"):
  1485. unit["sn"] = sn
  1486. module_type = cached.get("module_type") or ""
  1487. if module_type and not unit.get("module_type"):
  1488. unit["module_type"] = module_type
  1489. def _parse_xcam_data(self, xcam_data):
  1490. """Parse xcam data for camera settings and AI detection options."""
  1491. if not isinstance(xcam_data, dict):
  1492. return
  1493. current_time = time.time()
  1494. # Helper to check if we should accept incoming value for a module
  1495. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  1496. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  1497. """Check if we should accept an incoming xcam value.
  1498. OrcaSlicer pattern: After sending a command, ignore incoming data
  1499. for 3 seconds. After that, accept whatever the printer sends.
  1500. """
  1501. if module_name not in self._xcam_hold_start:
  1502. return True # No hold timer, accept incoming
  1503. hold_start = self._xcam_hold_start[module_name]
  1504. elapsed = current_time - hold_start
  1505. if elapsed > self._xcam_hold_time:
  1506. # Hold timer expired - accept incoming and clear hold
  1507. del self._xcam_hold_start[module_name]
  1508. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  1509. return True
  1510. # Within hold period - ignore incoming data
  1511. logger.debug(
  1512. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  1513. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  1514. )
  1515. return False
  1516. # Log all xcam fields for debugging
  1517. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  1518. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  1519. # fields (spaghetti_detector, etc.) are often stale/cached.
  1520. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  1521. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  1522. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  1523. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  1524. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  1525. # Sensitivity values: 0=low, 1=medium, 2=high
  1526. if "cfg" in xcam_data:
  1527. cfg = xcam_data["cfg"]
  1528. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  1529. def decode_detector(start_bit):
  1530. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  1531. sens_bits = (cfg >> start_bit) & 0x3
  1532. enabled = bool((cfg >> (start_bit + 2)) & 1)
  1533. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  1534. return enabled, sensitivity
  1535. # Spaghetti detector (bits 5-7)
  1536. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  1537. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  1538. old_value = self.state.print_options.spaghetti_detector
  1539. if cfg_spaghetti != old_value:
  1540. logger.debug(
  1541. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  1542. )
  1543. self.state.print_options.spaghetti_detector = cfg_spaghetti
  1544. # Check hold timer for sensitivity before accepting
  1545. if "halt_print_sensitivity" not in self._xcam_hold_start:
  1546. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  1547. logger.debug(
  1548. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  1549. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  1550. )
  1551. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  1552. else:
  1553. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  1554. elapsed = current_time - hold_start
  1555. if elapsed <= self._xcam_hold_time:
  1556. logger.debug(
  1557. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  1558. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  1559. )
  1560. else:
  1561. # Hold expired - accept from cfg
  1562. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  1563. logger.debug(
  1564. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  1565. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  1566. )
  1567. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  1568. del self._xcam_hold_start["halt_print_sensitivity"]
  1569. # Pileup detector (bits 8-10)
  1570. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  1571. if should_accept_value("pileup_detector", cfg_pileup):
  1572. if cfg_pileup != self.state.print_options.pileup_detector:
  1573. logger.debug(
  1574. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  1575. )
  1576. self.state.print_options.pileup_detector = cfg_pileup
  1577. # Pileup sensitivity with hold timer
  1578. if "pileup_sensitivity" not in self._xcam_hold_start:
  1579. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  1580. logger.debug(
  1581. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  1582. )
  1583. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  1584. else:
  1585. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  1586. elapsed = current_time - hold_start
  1587. if elapsed > self._xcam_hold_time:
  1588. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  1589. logger.debug(
  1590. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  1591. )
  1592. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  1593. del self._xcam_hold_start["pileup_sensitivity"]
  1594. # Clump/nozzle clumping detector (bits 11-13)
  1595. cfg_clump, cfg_clump_sens = decode_detector(11)
  1596. if should_accept_value("clump_detector", cfg_clump):
  1597. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  1598. logger.debug(
  1599. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  1600. )
  1601. self.state.print_options.nozzle_clumping_detector = cfg_clump
  1602. # Clump sensitivity with hold timer
  1603. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  1604. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  1605. logger.debug(
  1606. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  1607. )
  1608. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  1609. else:
  1610. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  1611. elapsed = current_time - hold_start
  1612. if elapsed > self._xcam_hold_time:
  1613. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  1614. logger.debug(
  1615. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  1616. )
  1617. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  1618. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  1619. # Airprint detector (bits 14-16)
  1620. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  1621. if should_accept_value("airprint_detector", cfg_airprint):
  1622. if cfg_airprint != self.state.print_options.airprint_detector:
  1623. logger.debug(
  1624. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  1625. )
  1626. self.state.print_options.airprint_detector = cfg_airprint
  1627. # Airprint sensitivity with hold timer
  1628. if "airprint_sensitivity" not in self._xcam_hold_start:
  1629. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  1630. logger.debug(
  1631. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  1632. )
  1633. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  1634. else:
  1635. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  1636. elapsed = current_time - hold_start
  1637. if elapsed > self._xcam_hold_time:
  1638. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  1639. logger.debug(
  1640. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  1641. )
  1642. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  1643. del self._xcam_hold_start["airprint_sensitivity"]
  1644. # Camera settings
  1645. if "ipcam_record" in xcam_data:
  1646. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  1647. if "timelapse" in xcam_data:
  1648. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  1649. # Track if timelapse was ever active during this print
  1650. if self.state.timelapse and self._was_running:
  1651. self._timelapse_during_print = True
  1652. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  1653. if "print_halt" in xcam_data:
  1654. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  1655. # Skip halt_print_sensitivity field - it's always stale ("medium")
  1656. # We read the actual sensitivity from cfg bits 5-6 above
  1657. if "first_layer_inspector" in xcam_data:
  1658. new_value = bool(xcam_data.get("first_layer_inspector"))
  1659. if should_accept_value("first_layer_inspector", new_value):
  1660. self.state.print_options.first_layer_inspector = new_value
  1661. if "printing_monitor" in xcam_data:
  1662. new_value = bool(xcam_data.get("printing_monitor"))
  1663. if should_accept_value("printing_monitor", new_value):
  1664. self.state.print_options.printing_monitor = new_value
  1665. if "buildplate_marker_detector" in xcam_data:
  1666. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  1667. if should_accept_value("buildplate_marker_detector", new_value):
  1668. self.state.print_options.buildplate_marker_detector = new_value
  1669. if "allow_skip_parts" in xcam_data:
  1670. new_value = bool(xcam_data.get("allow_skip_parts"))
  1671. if should_accept_value("allow_skip_parts", new_value):
  1672. self.state.print_options.allow_skip_parts = new_value
  1673. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  1674. # individual boolean fields (which are not sent by the printer)
  1675. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  1676. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  1677. if "auto_recovery_step_loss" in xcam_data:
  1678. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  1679. if "filament_tangle_detect" in xcam_data:
  1680. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  1681. @staticmethod
  1682. def _resolve_local_slot_from_mapping(local_slot: int, mapping_raw: list | None) -> int | None:
  1683. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  1684. The MQTT mapping field is an array of snow-encoded values:
  1685. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  1686. Finds entries where the local slot matches, then computes the global tray ID.
  1687. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  1688. """
  1689. if not isinstance(mapping_raw, list) or not mapping_raw:
  1690. return None
  1691. candidates: set[int] = set()
  1692. for value in mapping_raw:
  1693. if not isinstance(value, int) or value >= 65535:
  1694. continue
  1695. ams_hw_id = value >> 8
  1696. slot = value & 0xFF
  1697. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  1698. candidates.add(ams_hw_id * 4 + local_slot)
  1699. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  1700. candidates.add(ams_hw_id)
  1701. if len(candidates) == 1:
  1702. return candidates.pop()
  1703. return None
  1704. def _maybe_trigger_external_spool_change(self):
  1705. """Fire on_ams_change when the external spool (vt_tray) identity changes.
  1706. The AMS change-hash in _handle_ams_data is built only from AMS units, so
  1707. an external-spool-only filament swap would otherwise never re-run the
  1708. inventory reconciliation that unlinks a stale ams_id=255 assignment
  1709. (#2575). The reconciliation reads vt_tray from live status itself, so we
  1710. just need to re-fire the callback with the current merged AMS data.
  1711. """
  1712. import hashlib
  1713. vt_tray = self.state.raw_data.get("vt_tray")
  1714. if not isinstance(vt_tray, list):
  1715. return
  1716. # Identity fields only — deliberately exclude `remain` so a print's
  1717. # steadily-dropping fill percentage doesn't fire on every MQTT push.
  1718. fp_parts = [
  1719. f"{vt.get('id')}:{vt.get('tray_type')}:{vt.get('tray_color')}:"
  1720. f"{vt.get('tag_uid')}:{vt.get('tray_uuid')}:{vt.get('tray_info_idx')}"
  1721. for vt in vt_tray
  1722. if isinstance(vt, dict)
  1723. ]
  1724. vt_hash = hashlib.md5(":".join(fp_parts).encode(), usedforsecurity=False).hexdigest()
  1725. if vt_hash == self._previous_vt_tray_hash:
  1726. return
  1727. self._previous_vt_tray_hash = vt_hash
  1728. if self.on_ams_change:
  1729. logger.debug(
  1730. "[%s] External spool (vt_tray) changed, triggering sync callback",
  1731. self.serial_number,
  1732. )
  1733. self.on_ams_change(self.state.raw_data.get("ams") or [])
  1734. def _normalize_a2l_am_units(self, ams_list) -> None:
  1735. """A2L AMS-Lite normalisation (#a2l-am-unit-16): rewrite the physical unit
  1736. id 16 -> 6 in place, as early as possible, so every downstream reader —
  1737. the merge, apply_tray_exist_bits (bit base 24), the API, usage tracking,
  1738. the DB constraint — sees the normalised id and needs no special-casing.
  1739. ``tray_now`` (local) and the outbound wire are handled separately. Only id
  1740. 16 is ever touched, so every other printer/AMS type is untouched. Runs on
  1741. both the dict-wrapped and bare-list AMS shapes.
  1742. """
  1743. if not isinstance(ams_list, list):
  1744. return
  1745. for unit in ams_list:
  1746. if not isinstance(unit, dict):
  1747. continue
  1748. try:
  1749. uid = int(unit.get("id"))
  1750. except (TypeError, ValueError):
  1751. continue
  1752. if uid == A2L_LITE_PHYSICAL_AMS_ID:
  1753. unit["id"] = A2L_LITE_NORMALIZED_AMS_ID
  1754. if not self._has_a2l_am_unit:
  1755. logger.info(
  1756. "[%s] A2L AMS-Lite detected (unit id 16) — normalising to id %d",
  1757. self.serial_number,
  1758. A2L_LITE_NORMALIZED_AMS_ID,
  1759. )
  1760. self._has_a2l_am_unit = True
  1761. def _handle_ams_data(self, ams_data):
  1762. """Handle AMS data changes for Spoolman integration.
  1763. This is called when we receive top-level AMS data in MQTT messages.
  1764. It detects changes and triggers the callback for Spoolman sync.
  1765. """
  1766. import hashlib
  1767. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  1768. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  1769. ams_list = None
  1770. if isinstance(ams_data, dict):
  1771. if "ams" in ams_data:
  1772. ams_list = ams_data["ams"]
  1773. self._normalize_a2l_am_units(ams_list)
  1774. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  1775. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  1776. if non_list_fields:
  1777. self._debug_on_change(
  1778. "ams_dict_fields",
  1779. non_list_fields,
  1780. "[%s] AMS dict fields: %s",
  1781. self.serial_number,
  1782. non_list_fields,
  1783. )
  1784. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  1785. # when checking if we're in filament change mode for tray_now disambiguation
  1786. if "ams_status" in ams_data:
  1787. raw_ams_status = ams_data["ams_status"]
  1788. if isinstance(raw_ams_status, str):
  1789. try:
  1790. self.state.ams_status = int(raw_ams_status)
  1791. except ValueError:
  1792. self.state.ams_status = 0
  1793. else:
  1794. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  1795. # Compute main and sub status
  1796. self.state.ams_status_sub = self.state.ams_status & 0xFF
  1797. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  1798. self._debug_on_change(
  1799. "ams_status:ams",
  1800. self.state.ams_status,
  1801. "[%s] ams_status: %s (main=%s, sub=%s)",
  1802. self.serial_number,
  1803. self.state.ams_status,
  1804. self.state.ams_status_main,
  1805. self.state.ams_status_sub,
  1806. )
  1807. # Parse tray_tar / tray_pre (RAW). These identify the slot the firmware
  1808. # now expects (tray_tar) and the slot loaded before (tray_pre) — the key
  1809. # signal for a runout PAUSE where AMS Filament Backup has advanced to the
  1810. # next compatible slot (#2587). Stored raw here; globalised at the API
  1811. # boundary because that resolution needs the AMS layout. On H2D/multi-AMS
  1812. # these are local slot numbers (0-3), not global IDs.
  1813. for _tk, _attr in (("tray_tar", "tray_tar"), ("tray_pre", "tray_pre")):
  1814. if _tk in ams_data:
  1815. _raw = ams_data[_tk]
  1816. if isinstance(_raw, str):
  1817. try:
  1818. _val = int(_raw)
  1819. except ValueError:
  1820. _val = 255
  1821. else:
  1822. _val = _raw if _raw is not None else 255
  1823. prev = getattr(self.state, _attr)
  1824. setattr(self.state, _attr, _val)
  1825. # Log changes only while paused — the moment the operator cares —
  1826. # so a healthy print's normal tar churn doesn't spam the log.
  1827. if _val != prev and _val not in (255, -1) and self.state.state == "PAUSE":
  1828. logger.info(
  1829. "[%s] AMS %s changed to %s while paused (expected/previous slot signal, #2587)",
  1830. self.serial_number,
  1831. _tk,
  1832. _val,
  1833. )
  1834. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  1835. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  1836. if "tray_now" in ams_data:
  1837. raw_tray_now = ams_data["tray_now"]
  1838. # Convert string to int if needed
  1839. if isinstance(raw_tray_now, str):
  1840. try:
  1841. parsed_tray_now = int(raw_tray_now)
  1842. except ValueError:
  1843. parsed_tray_now = 255
  1844. else:
  1845. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  1846. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  1847. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  1848. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  1849. # — disambiguated below using MQTT mapping field
  1850. ams_map = self.state.ams_extruder_map
  1851. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  1852. # First, check if we have a pending target that matches this slot
  1853. pending_target = self.state.pending_tray_target
  1854. if pending_target is not None:
  1855. pending_slot = pending_target % 4
  1856. if pending_slot == parsed_tray_now:
  1857. # Slot matches our pending target - use the full global ID
  1858. logger.debug(
  1859. f"[{self.serial_number}] H2D tray_now disambiguation: "
  1860. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  1861. )
  1862. self.state.tray_now = pending_target
  1863. # Clear pending target now that load is confirmed
  1864. self.state.pending_tray_target = None
  1865. else:
  1866. # Slot doesn't match our pending target - something changed, use slot as-is
  1867. logger.warning(
  1868. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  1869. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  1870. )
  1871. self.state.tray_now = parsed_tray_now
  1872. # Clear pending target since it's stale
  1873. self.state.pending_tray_target = None
  1874. else:
  1875. # No pending target - use h2d_extruder_snow for accurate disambiguation
  1876. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  1877. active_ext = self.state.active_extruder # 0=right, 1=left
  1878. # Best source: use snow value from device.extruder.info if available
  1879. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  1880. if snow_tray is not None and snow_tray != 255:
  1881. # snow_tray is already normalized to global ID
  1882. # Verify the slot matches what we see in tray_now
  1883. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  1884. snow_slot = snow_tray % 4 if snow_tray < 128 else (0 if snow_tray <= 135 else -1)
  1885. if snow_slot == parsed_tray_now:
  1886. if self.state.tray_now != snow_tray:
  1887. logger.debug(
  1888. f"[{self.serial_number}] H2D tray_now from snow: "
  1889. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  1890. )
  1891. self.state.tray_now = snow_tray
  1892. else:
  1893. # Slot mismatch - snow field may not have updated yet, trust snow
  1894. logger.debug(
  1895. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  1896. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  1897. )
  1898. self.state.tray_now = snow_tray
  1899. else:
  1900. # Fallback: snow not available, use ams_extruder_map (less reliable)
  1901. # Find ALL AMS units on the active extruder
  1902. ams_on_extruder = []
  1903. for ams_id_str, ext_id in ams_map.items():
  1904. if ext_id == active_ext:
  1905. try:
  1906. ams_on_extruder.append(int(ams_id_str))
  1907. except ValueError:
  1908. pass # Skip AMS IDs that aren't valid integers
  1909. if len(ams_on_extruder) == 1:
  1910. # Single AMS on this extruder - unambiguous
  1911. active_ams_id = ams_on_extruder[0]
  1912. if 128 <= active_ams_id <= 135:
  1913. # AMS-HT: single slot per unit, global ID = unit ID
  1914. global_tray_id = active_ams_id
  1915. else:
  1916. global_tray_id = active_ams_id * 4 + parsed_tray_now
  1917. logger.debug(
  1918. f"[{self.serial_number}] H2D tray_now fallback: "
  1919. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  1920. )
  1921. self.state.tray_now = global_tray_id
  1922. elif len(ams_on_extruder) > 1:
  1923. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  1924. current_tray = self.state.tray_now
  1925. # Determine which AMS unit and slot the current tray belongs to
  1926. if 0 <= current_tray <= 15:
  1927. current_ams = current_tray // 4
  1928. current_slot = current_tray % 4
  1929. elif 128 <= current_tray <= 135:
  1930. current_ams = current_tray # AMS-HT: ID = tray ID
  1931. current_slot = 0
  1932. else:
  1933. current_ams = -1
  1934. current_slot = -1
  1935. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  1936. # Current is valid and matches slot - keep it
  1937. logger.debug(
  1938. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  1939. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  1940. )
  1941. else:
  1942. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  1943. if parsed_tray_now > 0:
  1944. candidates = [a for a in ams_on_extruder if a <= 3]
  1945. else:
  1946. candidates = ams_on_extruder
  1947. if len(candidates) == 1:
  1948. cand = candidates[0]
  1949. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  1950. logger.debug(
  1951. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  1952. f"narrowed to AMS {cand} -> global ID {resolved}"
  1953. )
  1954. self.state.tray_now = resolved
  1955. else:
  1956. # Genuinely ambiguous - use slot as-is (will be wrong for non-first AMS)
  1957. logger.warning(
  1958. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on extruder {active_ext}, "
  1959. f"no snow field, using slot {parsed_tray_now} (may be incorrect)"
  1960. )
  1961. self.state.tray_now = parsed_tray_now
  1962. else:
  1963. # No AMS on this extruder - use slot as-is
  1964. logger.warning(
  1965. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  1966. f"using slot {parsed_tray_now}"
  1967. )
  1968. self.state.tray_now = parsed_tray_now
  1969. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  1970. # Single-nozzle printer with tray_now in 0-3 range.
  1971. # #1822: H2S firmware reports tray_now as the AMS's idle
  1972. # slot (typically 0) when the active feed is actually the
  1973. # external spool. X1C / P1S / A1 correctly report 254 in
  1974. # that case; H2S does not. When the slicer-captured
  1975. # ams_mapping is all-external (every entry == -1), the
  1976. # print can only be feeding from the external spool, so
  1977. # promote tray_now to 254. Mixed (e.g. [5, -1]) and
  1978. # AMS-only mappings are NOT overridden — there's no
  1979. # evidence the firmware misreports in those cases. Prints
  1980. # started without a captured mapping (printer-screen start,
  1981. # or before Bambuddy connected) fall through unchanged.
  1982. captured = self._captured_ams_mapping
  1983. if captured and all(s == -1 for s in captured):
  1984. if self.state.tray_now != 254:
  1985. logger.debug(
  1986. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  1987. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  1988. )
  1989. self.state.tray_now = 254
  1990. else:
  1991. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  1992. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  1993. # (snow-encoded) to resolve the correct AMS unit.
  1994. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  1995. try:
  1996. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  1997. except (ValueError, TypeError):
  1998. ams_exist = 0
  1999. num_ams = bin(ams_exist).count("1")
  2000. if self._has_a2l_am_unit and num_ams <= 1:
  2001. # A2L AMS-Lite (normalised unit 6): the firmware reports
  2002. # tray_now as a LOCAL 0-3 slot, so globalise to 24+slot —
  2003. # otherwise usage tracking keys the wrong spool (it would
  2004. # deduct from AMS 0's slot). Confirmed by capture:
  2005. # tray_now="2" while printing physical slot 3.
  2006. self.state.tray_now = A2L_LITE_GLOBAL_BASE + parsed_tray_now
  2007. elif num_ams > 1:
  2008. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  2009. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  2010. if self._has_a2l_am_unit:
  2011. # A2L Lite + a regular AMS attached together is out of
  2012. # scope: the flat mapping ids are unknown for that combo
  2013. # and could collide with AMS 0. Fall through to the
  2014. # mapping-based resolve, but warn — a capture is needed.
  2015. logger.warning(
  2016. "[%s] A2L AMS-Lite alongside another AMS unit is unsupported — "
  2017. "tray_now resolution may be wrong (needs a mixed-setup capture)",
  2018. self.serial_number,
  2019. )
  2020. mapping_raw = self.state.raw_data.get("mapping")
  2021. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  2022. if resolved is not None:
  2023. if resolved != parsed_tray_now:
  2024. logger.debug(
  2025. f"[{self.serial_number}] Multi-AMS tray_now: "
  2026. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  2027. )
  2028. self.state.tray_now = resolved
  2029. else:
  2030. # No mapping available (not printing, or ambiguous) — use as-is.
  2031. # This matches the old behavior and is correct for AMS 0.
  2032. self.state.tray_now = parsed_tray_now
  2033. else:
  2034. # Single AMS — local slot 0-3 equals global ID
  2035. self.state.tray_now = parsed_tray_now
  2036. else:
  2037. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  2038. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  2039. # During filament change, the printer sends 255 first (unload), then the slot.
  2040. # We only clear pending_tray_target explicitly in ams_unload_filament().
  2041. # Trust the printer's reported value.
  2042. self.state.tray_now = parsed_tray_now
  2043. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  2044. # Valid physical trays: 0-15 (regular AMS), 24-27 (A2L AMS-Lite,
  2045. # normalised unit 6), 128-135 (AMS-HT), 254 (external spool)
  2046. tn = self.state.tray_now
  2047. if (
  2048. (0 <= tn <= 15)
  2049. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  2050. or (128 <= tn <= 135)
  2051. or tn == 254
  2052. ):
  2053. # Log tray change for mid-print usage splitting. Gate on the
  2054. # print-lifecycle flags (`_was_running` set on first RUNNING /
  2055. # new print, `_completion_triggered` set when on_print_complete
  2056. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  2057. # firmware briefly transitions out of RUNNING during AMS
  2058. # auto-fallback (#957), so a literal-string gate misses the
  2059. # switch and the usage tracker double-credits at completion.
  2060. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  2061. self.state.tray_change_log.append((tn, self.state.layer_num))
  2062. logger.info(
  2063. "[%s] Tray change during print: tray=%d at layer=%d",
  2064. self.serial_number,
  2065. tn,
  2066. self.state.layer_num,
  2067. )
  2068. self.state.last_loaded_tray = self.state.tray_now
  2069. self._debug_on_change(
  2070. "tray_now",
  2071. self.state.tray_now,
  2072. "[%s] tray_now updated: %s",
  2073. self.serial_number,
  2074. self.state.tray_now,
  2075. )
  2076. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  2077. # state when checking filament change mode for H2D disambiguation
  2078. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  2079. # We've already processed the status fields above, so just return if no ams list
  2080. if ams_list is None:
  2081. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  2082. return
  2083. elif isinstance(ams_data, list):
  2084. ams_list = ams_data
  2085. self._normalize_a2l_am_units(ams_list)
  2086. else:
  2087. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  2088. return
  2089. # Merge AMS data instead of replacing, to handle partial updates
  2090. # During prints, the printer may only send updates for active AMS units
  2091. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  2092. existing_ams = self.state.raw_data.get("ams", [])
  2093. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  2094. # Update existing units with new data, add new units
  2095. for ams_unit in ams_list:
  2096. ams_id = ams_unit.get("id")
  2097. if ams_id is not None:
  2098. existing_unit = existing_by_id.get(ams_id)
  2099. if existing_unit and "tray" in ams_unit:
  2100. # Deep merge trays to preserve fields from previous updates
  2101. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  2102. merged_trays = []
  2103. for new_tray in ams_unit.get("tray", []):
  2104. tray_id = new_tray.get("id")
  2105. if tray_id is not None and tray_id in existing_trays:
  2106. # Merge: start with existing, update with new non-empty values
  2107. merged_tray = existing_trays[tray_id].copy()
  2108. # Detect slot-clearing updates (spool removal):
  2109. # When tray_type is explicitly empty, clear everything
  2110. # including RFID data (tag_uid/tray_uuid).
  2111. slot_clearing = new_tray.get("tray_type") == ""
  2112. # Some printers (e.g. H2D) only send {id, state} in
  2113. # incremental updates when a tray is not fully loaded.
  2114. # state=11 means loaded; other values (9=empty,
  2115. # 10=spool present but filament not in feeder) indicate
  2116. # the slot should be cleared. Without this, old
  2117. # tray_type/tray_color persist indefinitely (#784).
  2118. #
  2119. # BUT this is regular-AMS semantics. An AMS-HT (single-
  2120. # tray high-temp dry box, id >= 128) reports its loaded
  2121. # tray as state=9, not 11 — it doesn't feed filament into
  2122. # a shared buffer the way a 4-slot AMS does. Applying the
  2123. # `state != 11 → empty` rule to an HT unit wiped a present
  2124. # spool on every power-on, when the printer sends a partial
  2125. # {id, state=9} for the HT tray (#2594). Skip the state
  2126. # heuristic for HT units — a genuine HT spool removal still
  2127. # clears via the explicit tray_type=="" case above and the
  2128. # tray_exist_bits cleanup below.
  2129. try:
  2130. _is_ht_unit = int(ams_id) >= 128
  2131. except (TypeError, ValueError):
  2132. _is_ht_unit = False
  2133. tray_state = new_tray.get("state")
  2134. if (
  2135. tray_state is not None
  2136. and tray_state != 11
  2137. and not _is_ht_unit
  2138. and "tray_type" not in new_tray
  2139. and merged_tray.get("tray_type")
  2140. ):
  2141. logger.info(
  2142. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  2143. self.serial_number,
  2144. ams_id,
  2145. tray_id,
  2146. tray_state,
  2147. )
  2148. slot_clearing = True
  2149. # The incremental update only has {id, state} — inject
  2150. # empty values for all content fields so the merge loop
  2151. # below clears the stale data from merged_tray.
  2152. new_tray.update(
  2153. {
  2154. "tray_type": "",
  2155. "tray_sub_brands": "",
  2156. "tray_color": "",
  2157. "tray_id_name": "",
  2158. "tray_info_idx": "",
  2159. "tag_uid": "0000000000000000",
  2160. "tray_uuid": "00000000000000000000000000000000",
  2161. "remain": 0,
  2162. "k": None,
  2163. "cali_idx": None,
  2164. }
  2165. )
  2166. for key, value in new_tray.items():
  2167. # Fields that should always be updated (even with empty/zero values):
  2168. # - remain, k, id, cali_idx: status indicators where 0 is valid
  2169. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  2170. # tray_id_name: slot content indicators that must be cleared
  2171. # when a spool is removed (fixes #147 - old AMS empty slot)
  2172. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  2173. # They are only cleared during spool removal (slot_clearing=True).
  2174. # Periodic AMS updates often include empty RFID fields which
  2175. # would overwrite valid data from the initial pushall.
  2176. always_update_fields = (
  2177. "remain",
  2178. "k",
  2179. "id",
  2180. "cali_idx",
  2181. "tray_type",
  2182. "tray_sub_brands",
  2183. "tray_info_idx",
  2184. "tray_color",
  2185. "tray_id_name",
  2186. )
  2187. if (
  2188. key in always_update_fields
  2189. or slot_clearing
  2190. or value
  2191. not in (
  2192. None,
  2193. "",
  2194. "0000000000000000",
  2195. "00000000000000000000000000000000",
  2196. )
  2197. ):
  2198. merged_tray[key] = value
  2199. merged_trays.append(merged_tray)
  2200. else:
  2201. merged_trays.append(new_tray)
  2202. # Update ams_unit with merged trays. Spread existing_unit
  2203. # FIRST so top-level fields the partial update omits —
  2204. # dry_time, info (which drives dry_status / dry_sub_status),
  2205. # humidity, temp — are preserved instead of dropped. The
  2206. # printer sends tray-bearing partials that carry no drying
  2207. # fields; without this, dry_time reads as absent → 0 and the
  2208. # falling-edge detector below fires a false "drying complete"
  2209. # (#1462). Mirrors the no-tray branch's merge semantics.
  2210. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  2211. elif existing_unit:
  2212. # Partial update without tray data: merge new fields into existing
  2213. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  2214. ams_unit = {**existing_unit, **ams_unit}
  2215. existing_by_id[ams_id] = ams_unit
  2216. # Convert back to list, sorted by ID for consistent ordering
  2217. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  2218. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  2219. # Shared with the VP bridge cache so the slicer-facing view stays in
  2220. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  2221. # for the full rationale and the printer-shutdown guard.
  2222. if isinstance(ams_data, dict):
  2223. apply_tray_exist_bits(
  2224. merged_ams,
  2225. ams_data.get("tray_exist_bits"),
  2226. power_on_flag=ams_data.get("power_on_flag", True),
  2227. log_label=self.serial_number,
  2228. annotate_exists=True,
  2229. )
  2230. self.state.raw_data["ams"] = merged_ams
  2231. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  2232. self._apply_ams_version_cache(merged_ams)
  2233. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  2234. self.state.last_ams_update = time.time()
  2235. self._debug_on_change(
  2236. "merged_ams",
  2237. (len(ams_list), len(merged_ams)),
  2238. "[%s] Merged AMS data: %s new units, %s total",
  2239. self.serial_number,
  2240. len(ams_list),
  2241. len(merged_ams),
  2242. )
  2243. # Extract ams_extruder_map from each AMS unit's info field
  2244. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  2245. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  2246. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  2247. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  2248. # extruder_id: 0=right/main, 1=left/deputy, 0xE=uninitialized (skip)
  2249. #
  2250. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  2251. # the full map. Merge into existing map to preserve entries from prior updates.
  2252. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  2253. for ams_unit in merged_ams:
  2254. ams_id = ams_unit.get("id")
  2255. info = ams_unit.get("info")
  2256. if ams_id is not None and info is not None:
  2257. try:
  2258. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  2259. info_val = int(str(info), 16)
  2260. # Extract 4 bits starting at bit 8 for extruder assignment
  2261. extruder_id = (info_val >> 8) & 0xF
  2262. if extruder_id == 0xE:
  2263. # 0xE = uninitialized AMS, skip
  2264. continue
  2265. ams_extruder_map[str(ams_id)] = extruder_id
  2266. self._debug_on_change(
  2267. f"ams_info:{ams_id}",
  2268. (info, extruder_id),
  2269. "[%s] AMS %s info=0x%s -> extruder %s",
  2270. self.serial_number,
  2271. ams_id,
  2272. info,
  2273. extruder_id,
  2274. )
  2275. except (ValueError, TypeError):
  2276. pass # Skip AMS units with unparseable info bitmask values
  2277. if ams_extruder_map:
  2278. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  2279. self.state.ams_extruder_map = ams_extruder_map
  2280. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  2281. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  2282. # BambuStudio DevFilaSystem.cpp parses info bits:
  2283. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  2284. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  2285. for ams_unit in merged_ams:
  2286. info = ams_unit.get("info")
  2287. if info is not None:
  2288. try:
  2289. info_val = int(str(info), 16)
  2290. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  2291. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  2292. except (ValueError, TypeError):
  2293. pass # Skip unparseable info values
  2294. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  2295. if "dry_sf_reason" in ams_unit:
  2296. sf_reason = ams_unit["dry_sf_reason"]
  2297. if isinstance(sf_reason, list):
  2298. ams_unit["dry_sf_reason"] = [
  2299. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  2300. ]
  2301. else:
  2302. ams_unit["dry_sf_reason"] = []
  2303. # Persist updated drying fields back to raw_data
  2304. self.state.raw_data["ams"] = merged_ams
  2305. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  2306. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  2307. # — fire the callback so smart-plug auto-off-after-drying can run,
  2308. # and drop our cached target-cycle params so the badge stops claiming
  2309. # an active cycle. Works identically for queue-triggered, ambient,
  2310. # and manual drying because we observe the firmware-reported state.
  2311. for ams_unit in merged_ams:
  2312. try:
  2313. ams_id = int(ams_unit.get("id", -1))
  2314. except (TypeError, ValueError):
  2315. continue
  2316. if ams_id < 0:
  2317. continue
  2318. # Only evaluate the edge when this update carries an explicit
  2319. # dry_time. An absent / unparseable value is NOT zero — treating
  2320. # it as 0 lets a tray-only partial fake a drying-complete edge
  2321. # (#1462). Skip without touching the remembered value so the
  2322. # next update that DOES carry dry_time sees the true previous.
  2323. raw_dry_time = ams_unit.get("dry_time")
  2324. if raw_dry_time is None:
  2325. continue
  2326. try:
  2327. current = int(raw_dry_time)
  2328. except (TypeError, ValueError):
  2329. continue
  2330. previous = self._previous_dry_times.get(ams_id, 0)
  2331. self._previous_dry_times[ams_id] = current
  2332. if previous > 0 and current == 0:
  2333. logger.info(
  2334. "[%s] AMS %d drying complete (dry_time %d → 0)",
  2335. self.serial_number,
  2336. ams_id,
  2337. previous,
  2338. )
  2339. self._drying_targets.pop(ams_id, None)
  2340. if self.on_drying_complete:
  2341. self.on_drying_complete(ams_id)
  2342. # Create a hash of relevant AMS data to detect changes.
  2343. # Hash the MERGED state, not the raw incoming ams_list: a removal signalled
  2344. # only by tray_exist_bits (firmware still echoing the old tray_type in the
  2345. # payload, unchanged remain) clears merged_ams via apply_tray_exist_bits
  2346. # above but leaves the raw payload's tracked fields untouched — so a
  2347. # raw-based hash never flips and on_ams_change never fires, leaving the
  2348. # spool_assignment row bound to an emptied slot (#2670). merged_ams also
  2349. # always spans every unit, so a partial single-unit update can't produce a
  2350. # spuriously different hash from a full pushall.
  2351. ams_hash_data = []
  2352. for ams_unit in merged_ams:
  2353. for tray in ams_unit.get("tray", []):
  2354. # Include fields that matter for filament tracking
  2355. ams_hash_data.append(
  2356. f"{ams_unit.get('id')}:{tray.get('id')}:"
  2357. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  2358. )
  2359. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  2360. # Only trigger callback if AMS data actually changed
  2361. if ams_hash != self._previous_ams_hash:
  2362. self._previous_ams_hash = ams_hash
  2363. if self.on_ams_change:
  2364. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  2365. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  2366. # may lack fields like 'remain' that the merged state preserves
  2367. self.on_ams_change(merged_ams)
  2368. # #2582: read-back check runs on EVERY AMS push, not just hash changes.
  2369. # The change hash keys on tray_type/tag_uid/remain — NOT tray_info_idx
  2370. # or cali_idx — so an assignment that only swaps the filament id on an
  2371. # already-loaded slot would not flip the hash, and gating the check on
  2372. # it would miss exactly the confirmation we are after.
  2373. if self._pending_assignments:
  2374. self._check_assignment_verifications()
  2375. def register_assignment_verification(
  2376. self,
  2377. ams_id: int,
  2378. tray_id: int,
  2379. tray_info_idx: str,
  2380. tray_color: str,
  2381. cali_idx: int | None,
  2382. ) -> None:
  2383. """Record an assignment we just pushed so subsequent AMS telemetry can
  2384. confirm the tray actually accepted it (#2582).
  2385. Called right after ``ams_set_filament_setting`` + ``extrusion_cali_sel``.
  2386. ``tray_info_idx`` is the primary signal — the slicer/printer echoes the
  2387. accepted filament id back in the per-tray push, so a match means the
  2388. setting landed. ``cali_idx`` (when >= 0) is verified as a secondary
  2389. signal so we can specifically flag "filament loaded but K-profile not
  2390. applied", which is the exact symptom the reporter chased via flow-cal.
  2391. A blank ``tray_info_idx`` means we had nothing resolvable to send, so
  2392. there is nothing to verify and no record is stored.
  2393. """
  2394. want_idx = (tray_info_idx or "").strip().upper()
  2395. if not want_idx:
  2396. return
  2397. self._pending_assignments[(ams_id, tray_id)] = {
  2398. "tray_info_idx": want_idx,
  2399. "tray_color": (tray_color or "").strip().upper(),
  2400. "cali_idx": cali_idx,
  2401. "deadline": time.monotonic() + self.ASSIGNMENT_VERIFY_TIMEOUT,
  2402. "last_seen_idx": None,
  2403. }
  2404. def _find_verify_tray(self, ams_id: int, tray_id: int) -> dict | None:
  2405. """Locate the live tray dict for a pending verification.
  2406. External spools (ams_id 255) live in ``vt_tray`` under global ids
  2407. 254/255; regular and HT AMS trays live under ``ams[].tray[]``. HT units
  2408. report a single tray whose id may not equal the logical tray_id, so fall
  2409. back to the sole tray when an id match fails.
  2410. """
  2411. raw = self.state.raw_data or {}
  2412. if ams_id == 255:
  2413. want_ext = 254 + tray_id
  2414. for vt in raw.get("vt_tray", []) or []:
  2415. if isinstance(vt, dict) and str(vt.get("id")) == str(want_ext):
  2416. return vt
  2417. return None
  2418. for unit in raw.get("ams", []) or []:
  2419. if str(unit.get("id")) != str(ams_id):
  2420. continue
  2421. trays = unit.get("tray", []) or []
  2422. for tray in trays:
  2423. if str(tray.get("id")) == str(tray_id):
  2424. return tray
  2425. if ams_id >= 128 and len(trays) == 1:
  2426. return trays[0]
  2427. return None
  2428. return None
  2429. def _check_assignment_verifications(self) -> None:
  2430. """Compare each pending assignment against live tray telemetry and fire
  2431. ``on_assignment_verified`` on a match or once the deadline passes.
  2432. Runs on every AMS push. Non-matching-but-still-within-window entries are
  2433. left in place for the next push. The timeout branch only fires when a
  2434. later push arrives after the deadline; if the printer goes silent we
  2435. simply never confirm, which is preferable to inventing a failure.
  2436. """
  2437. now = time.monotonic()
  2438. for key, want in list(self._pending_assignments.items()):
  2439. ams_id, tray_id = key
  2440. tray = self._find_verify_tray(ams_id, tray_id)
  2441. actual_idx = str((tray or {}).get("tray_info_idx") or "").strip().upper()
  2442. if tray is not None and actual_idx:
  2443. want["last_seen_idx"] = actual_idx
  2444. if actual_idx and actual_idx == want["tray_info_idx"]:
  2445. self._pending_assignments.pop(key, None)
  2446. kprofile_applied = True
  2447. want_cali = want.get("cali_idx")
  2448. if want_cali is not None and want_cali >= 0:
  2449. actual_cali = tray.get("cali_idx")
  2450. kprofile_applied = actual_cali == want_cali
  2451. self._fire_assignment_verified(
  2452. ams_id,
  2453. tray_id,
  2454. True,
  2455. {
  2456. "tray_info_idx": actual_idx,
  2457. "kprofile_applied": kprofile_applied,
  2458. },
  2459. )
  2460. elif now >= want["deadline"]:
  2461. self._pending_assignments.pop(key, None)
  2462. self._fire_assignment_verified(
  2463. ams_id,
  2464. tray_id,
  2465. False,
  2466. {
  2467. "expected_tray_info_idx": want["tray_info_idx"],
  2468. "actual_tray_info_idx": want.get("last_seen_idx"),
  2469. # True when we saw the tray at least once (so the push
  2470. # channel is alive and the printer really stored a
  2471. # different/blank id) vs never observing it at all.
  2472. "saw_tray": want.get("last_seen_idx") is not None,
  2473. },
  2474. )
  2475. def _fire_assignment_verified(self, ams_id: int, tray_id: int, verified: bool, detail: dict) -> None:
  2476. if verified:
  2477. logger.info(
  2478. "[%s] Assignment verified: AMS%d-T%d now reports %s (kprofile_applied=%s)",
  2479. self.serial_number,
  2480. ams_id,
  2481. tray_id,
  2482. detail.get("tray_info_idx"),
  2483. detail.get("kprofile_applied"),
  2484. )
  2485. else:
  2486. logger.warning(
  2487. "[%s] Assignment NOT confirmed: AMS%d-T%d expected %s, tray shows %s (saw_tray=%s)",
  2488. self.serial_number,
  2489. ams_id,
  2490. tray_id,
  2491. detail.get("expected_tray_info_idx"),
  2492. detail.get("actual_tray_info_idx"),
  2493. detail.get("saw_tray"),
  2494. )
  2495. if self.on_assignment_verified:
  2496. try:
  2497. self.on_assignment_verified(ams_id, tray_id, verified, detail)
  2498. except Exception:
  2499. logger.exception("[%s] on_assignment_verified callback failed", self.serial_number)
  2500. def _update_state(self, data: dict):
  2501. """Update printer state from message data."""
  2502. _previous_state = self.state.state
  2503. # Update state fields
  2504. if "gcode_state" in data:
  2505. self.state.state = data["gcode_state"]
  2506. if "gcode_file" in data:
  2507. self.state.gcode_file = data["gcode_file"]
  2508. self.state.current_print = data["gcode_file"]
  2509. if "subtask_name" in data:
  2510. self.state.subtask_name = data["subtask_name"]
  2511. # Prefer subtask_name as current_print if available
  2512. if data["subtask_name"]:
  2513. self.state.current_print = data["subtask_name"]
  2514. if "subtask_id" in data:
  2515. self.state.subtask_id = data["subtask_id"]
  2516. if "mc_percent" in data:
  2517. # Save last non-zero progress for usage tracking (firmware resets to 0 on cancel)
  2518. if self.state.progress > 0:
  2519. self._last_valid_progress = self.state.progress
  2520. self.state.progress = float(data["mc_percent"])
  2521. if "mc_remaining_time" in data:
  2522. self.state.remaining_time = int(data["mc_remaining_time"])
  2523. if "mc_print_sub_stage" in data:
  2524. new_sub_stage = int(data["mc_print_sub_stage"])
  2525. if new_sub_stage != self.state.mc_print_sub_stage:
  2526. logger.debug(
  2527. f"[{self.serial_number}] mc_print_sub_stage changed: "
  2528. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  2529. )
  2530. self.state.mc_print_sub_stage = new_sub_stage
  2531. if "layer_num" in data:
  2532. new_layer = int(data["layer_num"])
  2533. old_layer = self.state.layer_num
  2534. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  2535. if old_layer > 0:
  2536. self._last_valid_layer_num = old_layer
  2537. self.state.layer_num = new_layer
  2538. # Trigger layer change callback if layer increased
  2539. if new_layer > old_layer and self.on_layer_change:
  2540. self.on_layer_change(new_layer)
  2541. # #1867 last-layer finish-photo trigger. A1 Mini (and other
  2542. # firmware variants) skips `stg_cur=22`, so the fallback fires
  2543. # at gcode_state=FINISH — which runs AFTER user End G-code
  2544. # (e.g. SwapMod plate-swap) and captures the wrong plate.
  2545. # Firing on the layer_num→total_layer_num edge captures the
  2546. # last object layer before any end G-code executes.
  2547. total = self.state.total_layers or 0
  2548. if (
  2549. total > 0
  2550. and new_layer >= total
  2551. and old_layer < total
  2552. and self._was_running
  2553. and not self._finish_photo_captured
  2554. and self.on_finish_photo_moment
  2555. ):
  2556. self._finish_photo_captured = True
  2557. logger.info(
  2558. f"[{self.serial_number}] FINISH PHOTO MOMENT (last-layer) — "
  2559. f"layer={new_layer}/{total}, "
  2560. f"timelapse_active={self._timelapse_during_print}"
  2561. )
  2562. self.on_finish_photo_moment(
  2563. {
  2564. "trigger": "last_layer",
  2565. "filename": self._previous_gcode_file or self.state.gcode_file,
  2566. "subtask_name": self.state.subtask_name,
  2567. "timelapse_was_active": self._timelapse_during_print,
  2568. }
  2569. )
  2570. if "total_layer_num" in data:
  2571. # Some firmware (P1S observed) resets `total_layer_num` to 0 at
  2572. # print end — same shape as the `layer_num` reset guarded above.
  2573. # Preserve the last known good value so the usage-tracker split
  2574. # path (#1771) has a denominator that survives the reset frame.
  2575. # Explicit reset to 0 happens on print start (`_handle_print_start`).
  2576. new_total = int(data["total_layer_num"])
  2577. if new_total > 0:
  2578. self.state.total_layers = new_total
  2579. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  2580. # Convert to 0-100 percentage for display
  2581. def parse_fan_speed(value: str | int | None) -> int | None:
  2582. if value is None:
  2583. return None
  2584. try:
  2585. speed = int(value)
  2586. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  2587. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  2588. if speed <= 15:
  2589. return round(speed * 100 / 15)
  2590. # If already a percentage (0-255 scale from some printers), convert
  2591. elif speed <= 255:
  2592. return round(speed * 100 / 255)
  2593. return speed
  2594. except (ValueError, TypeError):
  2595. return None
  2596. # Log fan fields once for debugging
  2597. if not hasattr(self, "_fan_fields_logged"):
  2598. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  2599. if fan_fields:
  2600. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  2601. self._fan_fields_logged = True
  2602. if "cooling_fan_speed" in data:
  2603. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  2604. if "big_fan1_speed" in data:
  2605. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  2606. if "big_fan2_speed" in data:
  2607. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  2608. if "heatbreak_fan_speed" in data:
  2609. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  2610. # Calibration stage tracking
  2611. if "stg_cur" in data:
  2612. new_stg = data["stg_cur"]
  2613. prev_stg = self.state.stg_cur
  2614. # Always log ANY stg_cur change for debugging filament operations
  2615. if new_stg != prev_stg:
  2616. logger.debug(
  2617. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  2618. )
  2619. self.state.stg_cur = new_stg
  2620. # #1721 end-of-print finish photo trigger.
  2621. # Stage 22 = "Filament unloading" fires at end-of-print AND
  2622. # during mid-print color swaps. The end-of-print gate
  2623. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  2624. # — those signals only line up at the real end. Edge-only
  2625. # (prev != 22) so the trigger fires once per stage entry.
  2626. if (
  2627. new_stg == 22
  2628. and prev_stg != 22
  2629. and self._was_running
  2630. and not self._finish_photo_captured
  2631. and self.on_finish_photo_moment
  2632. ):
  2633. progress = self.state.progress or 0.0
  2634. layer_num = self.state.layer_num or 0
  2635. total_layers = self.state.total_layers or 0
  2636. remaining = self.state.remaining_time or 0
  2637. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  2638. if is_end_of_print:
  2639. self._finish_photo_captured = True
  2640. logger.info(
  2641. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  2642. f"progress={progress}, layer={layer_num}/{total_layers}, "
  2643. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  2644. )
  2645. self.on_finish_photo_moment(
  2646. {
  2647. "trigger": "stage_22",
  2648. "filename": self._previous_gcode_file or self.state.gcode_file,
  2649. "subtask_name": self.state.subtask_name,
  2650. "timelapse_was_active": self._timelapse_during_print,
  2651. }
  2652. )
  2653. if "stg" in data:
  2654. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  2655. # Temperature data
  2656. temps = {}
  2657. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  2658. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  2659. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  2660. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  2661. # Log ALL keys in print data for H2D temperature discovery
  2662. all_keys = sorted(data.keys())
  2663. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  2664. self._temp_fields_logged = True
  2665. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  2666. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  2667. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  2668. self._vir_slot_logged = True
  2669. # Log nozzle hardware info fields (once)
  2670. nozzle_fields = {
  2671. k: v
  2672. for k, v in data.items()
  2673. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  2674. }
  2675. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  2676. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  2677. self._nozzle_fields_logged = True
  2678. # Parse active extruder from device.extruder.state bit 8
  2679. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  2680. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  2681. if "device" in data and isinstance(data.get("device"), dict):
  2682. device = data["device"]
  2683. # One-shot identification probe: surface whatever the firmware uses to
  2684. # name itself so an unknown model in a support bundle becomes self-
  2685. # diagnosing. INFO level so it shows up without debug logging. Falls
  2686. # back to dumping device.keys() if none of the known fields are present
  2687. # (so a future Bambu rename like `model_name` is still observable).
  2688. if not getattr(self, "_device_id_logged", False):
  2689. id_fields = {
  2690. k: device.get(k)
  2691. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  2692. if k in device
  2693. }
  2694. if id_fields:
  2695. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  2696. else:
  2697. logger.info(
  2698. "[%s] Device identification: no known id fields; device.keys=%s",
  2699. self.serial_number,
  2700. sorted(device.keys()),
  2701. )
  2702. self._device_id_logged = True
  2703. if "extruder" in device and "state" in device["extruder"]:
  2704. state_val = device["extruder"]["state"]
  2705. # Extract bit 8 for extruder position
  2706. new_extruder = (state_val >> 8) & 0x1
  2707. if new_extruder != self.state.active_extruder:
  2708. logger.debug(
  2709. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  2710. )
  2711. self.state.active_extruder = new_extruder
  2712. # Log device.extruder structure for active extruder
  2713. if "device" in data and isinstance(data.get("device"), dict):
  2714. device = data["device"]
  2715. if "extruder" in device:
  2716. ext_data = device["extruder"]
  2717. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  2718. if "state" in ext_data:
  2719. state_val = ext_data["state"]
  2720. # Extract bits 12-14 (3 bits) for switch state
  2721. switch_state = (state_val >> 12) & 0x7
  2722. self._debug_on_change(
  2723. "extruder_state",
  2724. state_val,
  2725. "[%s] device.extruder.state=%s (switch_state bits 12-14: %s)",
  2726. self.serial_number,
  2727. state_val,
  2728. switch_state,
  2729. )
  2730. # Log 'cur' field if present (might indicate current/active extruder)
  2731. if "cur" in ext_data:
  2732. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  2733. # Filament Track Switch (FTS) detection — #1162. Presence of
  2734. # device.fila_switch in MQTT means the FTS accessory is installed.
  2735. if "device" in data and isinstance(data.get("device"), dict):
  2736. fs_data = data["device"].get("fila_switch")
  2737. if isinstance(fs_data, dict):
  2738. in_raw = fs_data.get("in")
  2739. out_raw = fs_data.get("out")
  2740. self.state.fila_switch = FilaSwitchState(
  2741. installed=True,
  2742. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2743. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2744. stat=int(fs_data.get("stat", 0) or 0),
  2745. info=int(fs_data.get("info", 0) or 0),
  2746. )
  2747. if "bed_temper" in data:
  2748. temps["bed"] = float(data["bed_temper"])
  2749. if "bed_target_temper" in data:
  2750. temps["bed_target"] = float(data["bed_target_temper"])
  2751. # Check if this is H2D (has device.extruder.info with 2 extruders)
  2752. has_h2d_extruder_info = (
  2753. "device" in data
  2754. and isinstance(data.get("device"), dict)
  2755. and "extruder" in data["device"]
  2756. and isinstance(data["device"]["extruder"].get("info"), list)
  2757. and len(data["device"]["extruder"]["info"]) >= 2
  2758. )
  2759. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  2760. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  2761. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  2762. if "nozzle_temper" in data:
  2763. if has_h2d_extruder_info:
  2764. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  2765. else:
  2766. temps["nozzle"] = float(data["nozzle_temper"])
  2767. if "nozzle_target_temper" in data:
  2768. if has_h2d_extruder_info:
  2769. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  2770. else:
  2771. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  2772. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  2773. if not has_h2d_extruder_info:
  2774. # Try multiple possible field names used by different firmware versions
  2775. if "nozzle_temper_2" in data:
  2776. val = float(data["nozzle_temper_2"])
  2777. if -50 < val < 500: # Valid temp range
  2778. temps["nozzle_2"] = val
  2779. else:
  2780. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  2781. elif "right_nozzle_temper" in data:
  2782. val = float(data["right_nozzle_temper"])
  2783. if -50 < val < 500: # Valid temp range
  2784. temps["nozzle_2"] = val
  2785. else:
  2786. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  2787. if "nozzle_target_temper_2" in data:
  2788. val = float(data["nozzle_target_temper_2"])
  2789. if 0 <= val < 500: # Valid temp range
  2790. temps["nozzle_2_target"] = val
  2791. else:
  2792. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  2793. elif "right_nozzle_target_temper" in data:
  2794. val = float(data["right_nozzle_target_temper"])
  2795. if 0 <= val < 500: # Valid temp range
  2796. temps["nozzle_2_target"] = val
  2797. else:
  2798. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  2799. # Also check for left nozzle as primary (some H2 models)
  2800. if "left_nozzle_temper" in data and "nozzle" not in temps:
  2801. temps["nozzle"] = float(data["left_nozzle_temper"])
  2802. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  2803. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  2804. if "chamber_temper" in data:
  2805. chamber_val = float(data["chamber_temper"])
  2806. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  2807. # Check if we recently set the target locally (within 5 seconds)
  2808. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2809. respect_local = (time.time() - local_set_time) < 5.0
  2810. # H2D protocol: chamber_temper encoding indicates heater state
  2811. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  2812. # - When < 500: direct Celsius current temp only - heater is OFF
  2813. if -50 < chamber_val < 100:
  2814. # Direct value = heater is OFF
  2815. temps["chamber"] = chamber_val
  2816. if not respect_local:
  2817. temps["chamber_target"] = 0.0 # Heater off means target = 0
  2818. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  2819. else:
  2820. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  2821. # Try to decode if it looks like an encoded value
  2822. if chamber_val > 500:
  2823. mqtt_target = int(chamber_val) // 65536
  2824. current = int(chamber_val) % 65536
  2825. logger.debug(
  2826. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  2827. )
  2828. if -50 < current < 100:
  2829. temps["chamber"] = float(current)
  2830. # Store decoded target for later use, but DON'T set chamber_heating here!
  2831. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  2832. # which is the authoritative source the slicer uses.
  2833. if not respect_local:
  2834. if 0 <= mqtt_target <= 60:
  2835. # Store as "decoded" target - may be overridden by explicit target fields
  2836. temps["_chamber_decoded_target"] = float(mqtt_target)
  2837. # Chamber target temperature (set by print file or display)
  2838. if "mc_target_cham" in data:
  2839. mc_target = float(data["mc_target_cham"])
  2840. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  2841. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  2842. if 0 <= mc_target <= 60:
  2843. temps["chamber_target"] = mc_target
  2844. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  2845. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  2846. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  2847. try:
  2848. if "info" in data and isinstance(data["info"], dict):
  2849. info_temp = data["info"].get("temp")
  2850. if info_temp is not None and "chamber" not in temps:
  2851. # Check for encoded value (target * 65536 + current)
  2852. if info_temp > 500:
  2853. # Decode: extract current temperature and target
  2854. target = info_temp // 65536
  2855. current = info_temp % 65536
  2856. temps["chamber"] = float(current)
  2857. # Store decoded target as fallback (may be overridden by ctc.info.target)
  2858. if "_chamber_decoded_target" not in temps:
  2859. temps["_chamber_decoded_target"] = float(target)
  2860. logger.debug(
  2861. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  2862. )
  2863. elif -50 < info_temp < 100:
  2864. # Valid direct temperature - heater is OFF
  2865. temps["chamber"] = float(info_temp)
  2866. temps["chamber_target"] = 0.0 # Direct value means heater off
  2867. self._debug_on_change(
  2868. "info_temp_direct",
  2869. info_temp,
  2870. "[%s] info.temp direct: %s°C (heater OFF)",
  2871. self.serial_number,
  2872. info_temp,
  2873. )
  2874. # H2D series: Dual extruder temps are in device.extruder.info array
  2875. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  2876. if "device" in data and isinstance(data["device"], dict):
  2877. device = data["device"]
  2878. # Parse dual extruder temperatures
  2879. extruder_data = device.get("extruder", {})
  2880. extruder_info = extruder_data.get("info", [])
  2881. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  2882. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  2883. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  2884. # has_h2d_extruder_info requires len(extruder_info) >= 2
  2885. if has_h2d_extruder_info:
  2886. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  2887. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  2888. if "temp" in extruder_info[0]:
  2889. temp_val = extruder_info[0]["temp"]
  2890. if temp_val > 500:
  2891. # Encoded format: temp = target * 65536 + current
  2892. target = temp_val // 65536
  2893. current = temp_val % 65536
  2894. if -50 < current < 500:
  2895. temps["nozzle_2"] = float(current)
  2896. if 0 < target < 500:
  2897. temps["nozzle_2_target"] = float(target)
  2898. temps["nozzle_2_heating"] = target > 0 and current < target
  2899. elif -50 < temp_val < 500:
  2900. # Direct Celsius value = heater is OFF
  2901. temps["nozzle_2"] = float(temp_val)
  2902. temps["nozzle_2_target"] = 0.0
  2903. temps["nozzle_2_heating"] = False
  2904. # Left nozzle (extruder 1) - only for dual nozzle printers
  2905. # H2D protocol: temp field encoding depends on value
  2906. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  2907. # - When < 500: direct Celsius current temp only - heater is OFF
  2908. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  2909. ext1 = extruder_info[1]
  2910. temp_val = ext1["temp"]
  2911. # Check if we recently set the target locally (within 5 seconds)
  2912. # If so, don't let MQTT data overwrite it
  2913. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  2914. respect_local_target = (time.time() - local_set_time) < 5.0
  2915. if temp_val > 500:
  2916. # Encoded format: temp = target * 65536 + current
  2917. target = temp_val // 65536
  2918. current = temp_val % 65536
  2919. if 0 < target < 500 and not respect_local_target:
  2920. temps["nozzle_target"] = float(target)
  2921. if -50 < current < 500:
  2922. temps["nozzle"] = float(current)
  2923. # Heating = encoded AND we're using the MQTT target (not local override)
  2924. # If local target is being respected, use local target to determine heating
  2925. if respect_local_target:
  2926. local_target = self.state.temperatures.get("nozzle_target", 0)
  2927. temps["nozzle_heating"] = local_target > 0 and current < local_target
  2928. else:
  2929. temps["nozzle_heating"] = target > 0 and current < target
  2930. elif -50 < temp_val < 500:
  2931. # Direct Celsius = heater is OFF (or at target with heater off)
  2932. temps["nozzle"] = float(temp_val)
  2933. if not respect_local_target:
  2934. temps["nozzle_target"] = 0.0
  2935. temps["nozzle_heating"] = False # Direct = not heating
  2936. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  2937. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  2938. if has_h2d_extruder_info:
  2939. for ext_info in extruder_info:
  2940. ext_id = ext_info.get("id")
  2941. snow = ext_info.get("snow")
  2942. if ext_id is not None and snow is not None and ext_id <= 1:
  2943. # Normalize H2D snow value to global tray ID
  2944. ams_id = snow >> 8
  2945. slot = snow & 0xFF
  2946. if 0 <= ams_id <= 3:
  2947. # Regular AMS slot
  2948. global_tray = ams_id * 4 + (slot & 0x03)
  2949. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2950. if old_val != global_tray:
  2951. logger.debug(
  2952. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2953. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  2954. )
  2955. self.state.h2d_extruder_snow[ext_id] = global_tray
  2956. elif ams_id == 254 or ams_id == 255:
  2957. # External spool or unloaded
  2958. normalized = 254 if slot != 255 else 255
  2959. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2960. if old_val != normalized:
  2961. logger.debug(
  2962. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2963. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  2964. )
  2965. self.state.h2d_extruder_snow[ext_id] = normalized
  2966. elif 128 <= ams_id <= 135:
  2967. # External spool with hub mapping
  2968. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2969. if old_val != ams_id:
  2970. logger.debug(
  2971. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2972. f"raw={snow} -> external hub {ams_id}"
  2973. )
  2974. self.state.h2d_extruder_snow[ext_id] = ams_id
  2975. # Parse bed heating state from device.bed.info.temp encoding
  2976. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  2977. bed_data = device.get("bed", {})
  2978. bed_info = bed_data.get("info", {})
  2979. if "temp" in bed_info:
  2980. temp_val = bed_info["temp"]
  2981. if temp_val > 500:
  2982. target = temp_val // 65536
  2983. current = temp_val % 65536
  2984. temps["bed_heating"] = target > 0 and current < target
  2985. else:
  2986. temps["bed_heating"] = False
  2987. # Parse chamber temp from device.ctc.info.temp if not already set
  2988. ctc_data = device.get("ctc", {})
  2989. ctc_info = ctc_data.get("info", {})
  2990. # Parse airduct mode (0=cooling, 1=heating)
  2991. airduct_data = device.get("airduct", {})
  2992. if "modeCur" in airduct_data:
  2993. new_mode = airduct_data["modeCur"]
  2994. if new_mode != self.state.airduct_mode:
  2995. logger.debug(
  2996. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  2997. )
  2998. self.state.airduct_mode = new_mode
  2999. # Parse individual airduct fan parts (new-protocol models: P2S/X2D/H2*).
  3000. # Raw part ids are bit-packed — decoded id = raw_id >> 4 (bits 4-11),
  3001. # mirroring Bambu Studio DevFan::ParseV3_0. Decoded ids follow the
  3002. # AIR_FUN enum: 1=part cooling, 2=right aux, 3=chamber/exhaust,
  3003. # 10=left aux (FAN_REMOTE_COOLING_1). The airduct `parts` list only
  3004. # contains the fans that physically exist, so it doubles as a
  3005. # presence signal for the two P2S/X2D add-on kits:
  3006. # - id 10 (left auxiliary part cooling fan) — reported ONLY here,
  3007. # never mirrored into a flat big_fanX_speed field.
  3008. # - id 3 (chamber exhaust fan) — its speed is mirrored into
  3009. # big_fan2_speed, but the part is only listed when the External
  3010. # Exhaust Fan kit (get_version module "eef") is installed.
  3011. # `state` is already a 0-100 percentage.
  3012. parts = airduct_data.get("parts")
  3013. if isinstance(parts, list):
  3014. left_aux_speed = None
  3015. exhaust_present = False
  3016. for part in parts:
  3017. if not isinstance(part, dict):
  3018. continue
  3019. try:
  3020. part_id = int(part["id"]) >> 4
  3021. part_state = int(part["state"])
  3022. except (KeyError, ValueError, TypeError):
  3023. continue
  3024. if part_id == 10:
  3025. left_aux_speed = max(0, min(100, part_state))
  3026. elif part_id == 3:
  3027. exhaust_present = True
  3028. if left_aux_speed != self.state.left_aux_fan_speed:
  3029. logger.debug(
  3030. f"[{self.serial_number}] left_aux_fan_speed changed: "
  3031. f"{self.state.left_aux_fan_speed} -> {left_aux_speed}"
  3032. )
  3033. # A full parts list without id 10 means the left aux fan is not
  3034. # installed — report None so the UI can hide the widget.
  3035. self.state.left_aux_fan_speed = left_aux_speed
  3036. # id 3 present == chamber exhaust fan installed (base P2S omits it).
  3037. self.state.exhaust_fan_present = exhaust_present
  3038. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  3039. # Check if we recently set the target locally (within 5 seconds)
  3040. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  3041. respect_local_target = (time.time() - local_set_time) < 5.0
  3042. # Log ctc_info contents for debugging
  3043. if ctc_info:
  3044. self._debug_on_change(
  3045. "ctc_info_keys",
  3046. tuple(ctc_info.keys()),
  3047. "[%s] ctc_info keys: %s",
  3048. self.serial_number,
  3049. list(ctc_info.keys()),
  3050. )
  3051. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  3052. # (what the slicer shows). This OVERRIDES any previously decoded target.
  3053. explicit_target = None
  3054. if "target" in ctc_info:
  3055. target_val = ctc_info["target"]
  3056. logger.debug(
  3057. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  3058. )
  3059. # Filter out invalid values (valid chamber target is 0-60°C)
  3060. if 0 <= target_val <= 60 and not respect_local_target:
  3061. explicit_target = float(target_val)
  3062. temps["chamber_target"] = explicit_target # Override any previous value
  3063. logger.debug(
  3064. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  3065. )
  3066. # Parse chamber temp from ctc.info.temp - may be encoded
  3067. if "temp" in ctc_info and "chamber" not in temps:
  3068. temp_val = ctc_info["temp"]
  3069. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  3070. if temp_val > 500:
  3071. # Encoded value: decode target and current
  3072. decoded_target = temp_val // 65536
  3073. current = temp_val % 65536
  3074. temps["chamber"] = float(current)
  3075. logger.debug(
  3076. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  3077. )
  3078. # Determine which target to use for heating state:
  3079. # Priority: local target > explicit target > decoded target
  3080. if respect_local_target:
  3081. local_target = self.state.temperatures.get("chamber_target", 0)
  3082. temps["chamber_heating"] = local_target > 0 and current < local_target
  3083. elif explicit_target is not None:
  3084. # Use explicit ctc.info.target - this is what slicer sees
  3085. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  3086. else:
  3087. # Fallback to decoded target only if no explicit target available
  3088. if not respect_local_target and "chamber_target" not in temps:
  3089. temps["chamber_target"] = float(decoded_target)
  3090. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  3091. else:
  3092. # Direct value (not encoded) - heater is OFF
  3093. temps["chamber"] = float(temp_val)
  3094. temps["chamber_heating"] = False
  3095. except Exception as e:
  3096. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  3097. if temps:
  3098. # Handle chamber_target: prefer explicit over decoded
  3099. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  3100. # No explicit target available, use decoded target from chamber_temper
  3101. temps["chamber_target"] = temps["_chamber_decoded_target"]
  3102. # Remove internal temp key before merging
  3103. temps.pop("_chamber_decoded_target", None)
  3104. # Merge new temps into existing, preserving valid values when new ones are filtered out
  3105. for key, value in temps.items():
  3106. self.state.temperatures[key] = value
  3107. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  3108. if "bed" in temps and self.on_bed_temp_update:
  3109. self.on_bed_temp_update(temps["bed"])
  3110. # Calculate chamber_heating after all targets are known
  3111. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  3112. if "chamber" in temps and "chamber_heating" not in temps:
  3113. current = self.state.temperatures.get("chamber", 0)
  3114. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  3115. respect_local = (time.time() - local_set_time) < 5.0
  3116. if respect_local:
  3117. # Use locally-set target
  3118. target = self.state.temperatures.get("chamber_target", 0)
  3119. else:
  3120. # Use explicit/decoded target from MQTT
  3121. target = self.state.temperatures.get("chamber_target", 0)
  3122. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  3123. self._debug_on_change(
  3124. "chamber_heating",
  3125. (target, current, self.state.temperatures["chamber_heating"], respect_local),
  3126. "[%s] Chamber heating calculated: target=%s, current=%s, heating=%s, respect_local=%s",
  3127. self.serial_number,
  3128. target,
  3129. current,
  3130. self.state.temperatures["chamber_heating"],
  3131. respect_local,
  3132. )
  3133. # Debug: log chamber value if it was updated
  3134. if "chamber" in temps:
  3135. self._debug_on_change(
  3136. "chamber_temp",
  3137. (
  3138. self.state.temperatures.get("chamber"),
  3139. self.state.temperatures.get("chamber_target"),
  3140. self.state.temperatures.get("chamber_heating"),
  3141. ),
  3142. "[%s] Chamber temp updated to: %s, target: %s, heating: %s",
  3143. self.serial_number,
  3144. self.state.temperatures.get("chamber"),
  3145. self.state.temperatures.get("chamber_target"),
  3146. self.state.temperatures.get("chamber_heating"),
  3147. )
  3148. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  3149. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  3150. if "nozzle" in temps and "nozzle_heating" not in temps:
  3151. current = self.state.temperatures.get("nozzle", 0)
  3152. target = self.state.temperatures.get("nozzle_target", 0)
  3153. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  3154. # Parse HMS (Health Management System) errors
  3155. if "hms" in data:
  3156. hms_list = data["hms"]
  3157. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  3158. self.state.hms_errors = []
  3159. if isinstance(hms_list, list):
  3160. for hms in hms_list:
  3161. if isinstance(hms, dict):
  3162. # HMS format: {"attr": attribute_code, "code": error_code}
  3163. # attr contains module/severity info, code contains error number
  3164. # Both are needed to construct the wiki URL
  3165. attr = hms.get("attr", 0)
  3166. code = hms.get("code", 0)
  3167. if isinstance(attr, str):
  3168. attr = int(attr.replace("0x", ""), 16) if attr else 0
  3169. if isinstance(code, str):
  3170. code = int(code.replace("0x", ""), 16) if code else 0
  3171. # Severity is in attr byte 1 (bits 8-15)
  3172. severity = (attr >> 8) & 0xF
  3173. # Module is in attr byte 3 (bits 24-31)
  3174. module = (attr >> 24) & 0xFF
  3175. # Skip non-error status codes — all real HMS errors
  3176. # have code >= 0x4000. Lower values are status/phase
  3177. # indicators that some firmware sends during normal printing.
  3178. if code < 0x4000:
  3179. continue
  3180. # Skip user-action echoes — the printer firmware emits these
  3181. # as part of normal user-cancel sequences. They're not faults
  3182. # and shouldn't count toward "X problem" badges or surface as
  3183. # red pips on the printer card. Backend's notification path
  3184. # already suppresses 0500_400E for the same reason.
  3185. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  3186. if short_code in _HMS_USER_ACTION_CODES:
  3187. continue
  3188. # Catalog has both 8-char keys (base class) and 16-char keys
  3189. # (specific variants). The full 16-char identifier preserves
  3190. # the 32 bits of `attr_low` + `code_high` that the short_code
  3191. # discards — that's the firmware's matching key, so try it
  3192. # first and fall back to the short form.
  3193. full_code = f"{attr:08X}{code:08X}"
  3194. actions = get_actions_for_error_code(self.serial_number[:3], full_code)
  3195. if not actions:
  3196. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  3197. self.state.hms_errors.append(
  3198. HMSError(
  3199. code=f"0x{code:x}" if code else "0x0",
  3200. attr=attr,
  3201. module=module,
  3202. severity=severity if severity > 0 else 2,
  3203. actions=actions,
  3204. job_id=self.state.subtask_id,
  3205. full_code=full_code,
  3206. )
  3207. )
  3208. # Parse print_error - this is a different error format than HMS
  3209. # print_error is a 32-bit integer where:
  3210. # - High 16 bits contain module info (e.g., 0x0500)
  3211. # - Low 16 bits contain error code (e.g., 0x8061)
  3212. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  3213. if "print_error" in data:
  3214. print_error = data["print_error"]
  3215. if print_error and print_error != 0:
  3216. # Extract components: MMMMEEEE -> MMMM_EEEE
  3217. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  3218. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  3219. # Values below 0x4000 are status/phase indicators, not real errors.
  3220. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  3221. # Some firmware sends low values like 0x0002 during normal printing.
  3222. if error < 0x4000:
  3223. pass # Skip — not a real error
  3224. else:
  3225. # Store in a format that matches the community error database
  3226. # attr stores the full 32-bit value for reconstruction
  3227. # code stores the short format string for lookup
  3228. short_code = f"{module:04X}_{error:04X}"
  3229. logger.debug(
  3230. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  3231. )
  3232. # Same user-action filter as the hms[] branch above — print_error
  3233. # carries the same cancel echoes (e.g. 0500_400E) and they must
  3234. # not surface as faults on the printer card.
  3235. if short_code in _HMS_USER_ACTION_CODES:
  3236. pass # cancel echo — silently drop
  3237. else:
  3238. # Only add if not already in HMS errors (avoid duplicates)
  3239. existing_short_codes = set()
  3240. for e in self.state.hms_errors:
  3241. # Extract short code from existing errors
  3242. e_module = (e.attr >> 16) & 0xFFFF
  3243. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  3244. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  3245. if short_code not in existing_short_codes:
  3246. # Bambu's HMS catalog keys by 3-letter device code (the SN
  3247. # prefix) and a 16-char short error code without the
  3248. # underscore separator we store internally.
  3249. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  3250. # Bambu pushes the current job as `subtask_id` on the
  3251. # state stream; the HMS-action commands echo it back as
  3252. # `job_id`. The error payload itself doesn't carry the
  3253. # id, so snapshot it from the live state at parse time
  3254. # and freeze it on the HMSError so subsequent
  3255. # job changes don't invalidate the action.
  3256. job_id = self.state.subtask_id
  3257. logger.debug(
  3258. "[%s, %s] HMS available actions: %s (job_id=%s)",
  3259. self.serial_number[:3],
  3260. short_code.replace("_", ""),
  3261. actions,
  3262. job_id,
  3263. )
  3264. self.state.hms_errors.append(
  3265. HMSError(
  3266. code=f"0x{error:x}",
  3267. attr=print_error, # Store full value for display
  3268. module=module >> 8, # High byte of module (e.g., 0x05)
  3269. severity=3, # Warning level for print_error
  3270. actions=actions,
  3271. job_id=job_id,
  3272. # print_error is already 32-bit — `f"{print_error:08X}"`
  3273. # is the firmware's matching key with no truncation.
  3274. full_code=f"{print_error:08X}",
  3275. )
  3276. )
  3277. # Parse home_flag first so SD-card detection below can prefer it.
  3278. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  3279. # bit 23 = door-open (X1 family only).
  3280. home_flag = None
  3281. if "home_flag" in data:
  3282. home_flag = data["home_flag"]
  3283. if home_flag < 0:
  3284. home_flag = home_flag & 0xFFFFFFFF
  3285. # SD card presence: the only remaining consumer is the firmware-update
  3286. # precondition check (firmware_update.py). Use the top-level `sdcard`
  3287. # field when present with a permissive truthy check covering the
  3288. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  3289. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  3290. # when a card is inserted, which caused the badge to flap before the
  3291. # badge was removed entirely.
  3292. if "sdcard" in data:
  3293. raw_sdcard = data["sdcard"]
  3294. if isinstance(raw_sdcard, str):
  3295. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  3296. else:
  3297. self.state.sdcard = bool(raw_sdcard)
  3298. if home_flag is not None:
  3299. store_to_sdcard = bool((home_flag >> 11) & 1)
  3300. if store_to_sdcard != self.state.store_to_sdcard:
  3301. logger.debug(
  3302. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  3303. )
  3304. self.state.store_to_sdcard = store_to_sdcard
  3305. # Door open detection — source depends on printer family:
  3306. # X1 series (X1, X1C, X1E): home_flag bit 23
  3307. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  3308. # Both share the same bitmask (0x00800000) but live in different fields.
  3309. model_upper = (self.model or "").upper().strip()
  3310. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  3311. if is_x1_family and home_flag is not None:
  3312. door_open = (home_flag & 0x00800000) != 0
  3313. if door_open != self.state.door_open:
  3314. logger.debug(
  3315. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  3316. self.serial_number,
  3317. self.state.door_open,
  3318. door_open,
  3319. home_flag,
  3320. )
  3321. self.state.door_open = door_open
  3322. elif not is_x1_family and "stat" in data:
  3323. try:
  3324. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  3325. door_open = (stat_value & 0x00800000) != 0
  3326. if door_open != self.state.door_open:
  3327. logger.debug(
  3328. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  3329. self.serial_number,
  3330. self.state.door_open,
  3331. door_open,
  3332. stat_value,
  3333. )
  3334. self.state.door_open = door_open
  3335. except (ValueError, TypeError):
  3336. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  3337. # Parse timelapse status (recording active during print)
  3338. if "timelapse" in data:
  3339. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  3340. self.state.timelapse = data["timelapse"] is True
  3341. # Track if timelapse was ever active during this print
  3342. if self.state.timelapse and self._was_running:
  3343. self._timelapse_during_print = True
  3344. # Parse ipcam/live view status
  3345. if "ipcam" in data:
  3346. ipcam_data = data["ipcam"]
  3347. self._debug_on_change("ipcam", ipcam_data, "[%s] ipcam field: %s", self.serial_number, ipcam_data)
  3348. if isinstance(ipcam_data, dict):
  3349. # Check ipcam_record field for live view status
  3350. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  3351. # Check timelapse field (H2D sends it here, not in xcam)
  3352. if "timelapse" in ipcam_data:
  3353. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  3354. if timelapse_enabled != self.state.timelapse:
  3355. logger.debug(
  3356. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  3357. )
  3358. self.state.timelapse = timelapse_enabled
  3359. # Track if timelapse was ever active during this print
  3360. if self.state.timelapse and self._was_running:
  3361. self._timelapse_during_print = True
  3362. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  3363. else:
  3364. self.state.ipcam = ipcam_data is True
  3365. # Parse WiFi signal strength (dBm)
  3366. if "wifi_signal" in data:
  3367. wifi_signal = data["wifi_signal"]
  3368. self._debug_on_change(
  3369. "wifi_signal", wifi_signal, "[%s] wifi_signal received: %s", self.serial_number, wifi_signal
  3370. )
  3371. if isinstance(wifi_signal, (int, float)):
  3372. self.state.wifi_signal = int(wifi_signal)
  3373. elif isinstance(wifi_signal, str):
  3374. # Handle string format like "-52dBm"
  3375. try:
  3376. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  3377. except ValueError:
  3378. pass # Ignore unparseable wifi_signal strings; field is non-critical
  3379. # Detect ethernet connection: printers on ethernet with WiFi disabled
  3380. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  3381. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  3382. from backend.app.utils.printer_models import has_ethernet
  3383. if has_ethernet(self.model):
  3384. self.state.wired_network = self.state.wifi_signal == -90
  3385. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  3386. if "spd_lvl" in data:
  3387. new_speed = data["spd_lvl"]
  3388. if new_speed != self.state.speed_level:
  3389. logger.debug(
  3390. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  3391. )
  3392. self.state.speed_level = new_speed
  3393. # Parse skipped objects from printer status (s_obj field)
  3394. # This allows us to restore skipped objects state after reconnection
  3395. if "s_obj" in data:
  3396. s_obj = data["s_obj"]
  3397. if isinstance(s_obj, list):
  3398. # Update skipped objects from printer's list
  3399. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  3400. if new_skipped != self.state.skipped_objects:
  3401. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  3402. self.state.skipped_objects = new_skipped
  3403. # Parse chamber light status from lights_report
  3404. if "lights_report" in data:
  3405. lights = data["lights_report"]
  3406. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  3407. if isinstance(lights, list):
  3408. for light in lights:
  3409. if isinstance(light, dict) and light.get("node") == "chamber_light":
  3410. new_light_state = light.get("mode") == "on"
  3411. if new_light_state != self.state.chamber_light:
  3412. logger.debug(
  3413. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  3414. )
  3415. self.state.chamber_light = new_light_state
  3416. break
  3417. # Parse nozzle hardware info (single nozzle printers)
  3418. if "nozzle_type" in data:
  3419. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  3420. if "nozzle_diameter" in data:
  3421. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  3422. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  3423. # Left nozzle
  3424. if "left_nozzle_type" in data:
  3425. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  3426. if "left_nozzle_diameter" in data:
  3427. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  3428. # Right nozzle
  3429. if "right_nozzle_type" in data:
  3430. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  3431. if "right_nozzle_diameter" in data:
  3432. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  3433. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  3434. if "nozzle_type_2" in data:
  3435. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  3436. if "nozzle_diameter_2" in data:
  3437. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  3438. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  3439. if "device" in data and isinstance(data["device"], dict):
  3440. device = data["device"]
  3441. nozzle_data = device.get("nozzle", {})
  3442. nozzle_info = nozzle_data.get("info", [])
  3443. if isinstance(nozzle_info, list):
  3444. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  3445. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  3446. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  3447. # for hover cards on both the L/R indicator and the nozzle rack card.
  3448. if nozzle_info:
  3449. self.state.nozzle_rack = sorted(
  3450. [
  3451. {
  3452. "id": n.get("id", i),
  3453. "type": str(n.get("type", "")),
  3454. "diameter": str(n.get("diameter", "")),
  3455. "wear": n.get("wear"),
  3456. "stat": n.get("stat"),
  3457. # H2C uses "tm", H2D uses "max_temp"
  3458. "max_temp": n.get("max_temp") or n.get("tm", 0),
  3459. # H2C uses "sn", H2D uses "serial_number"
  3460. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  3461. # H2C uses "color_m", H2D uses "filament_colour"
  3462. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  3463. # H2C uses "fila_id", H2D uses "filament_id"
  3464. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  3465. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  3466. }
  3467. for i, n in enumerate(nozzle_info)
  3468. ],
  3469. key=lambda x: x["id"],
  3470. )
  3471. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  3472. self._nozzle_rack_logged = True
  3473. logger.debug(
  3474. "[%s] Nozzle info: %d entries, IDs: %s",
  3475. self.serial_number,
  3476. len(nozzle_info),
  3477. [n.get("id") for n in nozzle_info],
  3478. )
  3479. for nozzle in nozzle_info:
  3480. idx = nozzle.get("id", 0)
  3481. if idx < len(self.state.nozzles):
  3482. if "type" in nozzle and nozzle["type"]:
  3483. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  3484. if "diameter" in nozzle:
  3485. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  3486. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  3487. # (these fields aren't sent in every MQTT push, only when changed)
  3488. ams_data = self.state.raw_data.get("ams")
  3489. vt_tray_data = self.state.raw_data.get("vt_tray")
  3490. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  3491. mapping_data = self.state.raw_data.get("mapping")
  3492. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  3493. # as a dict but consumers expect a list. Without this, the dev mode probe
  3494. # below can release the GIL (via publish), letting the event-loop thread
  3495. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  3496. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  3497. data["vt_tray"] = [data["vt_tray"]]
  3498. self.state.raw_data = data
  3499. # Restore preserved fields BEFORE any work that may release the GIL
  3500. # (e.g. _probe_developer_mode publishes an MQTT message).
  3501. if ams_data is not None:
  3502. self.state.raw_data["ams"] = ams_data
  3503. if vt_tray_data is not None:
  3504. self.state.raw_data["vt_tray"] = vt_tray_data
  3505. if ams_extruder_map_data is not None:
  3506. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  3507. if mapping_data is not None and "mapping" not in data:
  3508. self.state.raw_data["mapping"] = mapping_data
  3509. # Parse developer LAN mode from "fun" field
  3510. if "fun" in data:
  3511. try:
  3512. fun_val = data["fun"]
  3513. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  3514. self.state.developer_mode = (fun_int & 0x20000000) == 0
  3515. except (ValueError, TypeError):
  3516. pass
  3517. elif self.state.developer_mode is None and not self._dev_mode_probed:
  3518. # No "fun" field — A1/P1 series never send it, so we need to probe.
  3519. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  3520. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  3521. # after connect to let the MQTT session stabilize — probing too early
  3522. # can destabilize some firmware MQTT brokers (#887).
  3523. if not self._dev_mode_needs_probe and len(data) > 30:
  3524. # First full status without "fun" — mark that probe is needed
  3525. self._dev_mode_needs_probe = True
  3526. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  3527. self._probe_developer_mode()
  3528. elif self._dev_mode_needs_probe:
  3529. logger.debug(
  3530. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  3531. self.serial_number,
  3532. time.monotonic() - self._connect_time,
  3533. )
  3534. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  3535. # Probe was sent but no response yet — check for timeout.
  3536. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  3537. # may deliver status pushes but silently drop commands (#887).
  3538. elapsed = time.monotonic() - self._dev_mode_probe_time
  3539. if elapsed > 10.0:
  3540. self._dev_mode_probe_failures += 1
  3541. logger.warning(
  3542. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  3543. self.serial_number,
  3544. elapsed,
  3545. self._dev_mode_probe_failures,
  3546. )
  3547. self._dev_mode_probe_seq = None
  3548. if self._dev_mode_probe_failures >= 2:
  3549. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  3550. else:
  3551. # Allow retry on next full status message
  3552. self._dev_mode_probed = False
  3553. # Zombie session detection: if an ams_filament_setting command has been
  3554. # pending for >10s with no response, the publish path is likely dead (#887).
  3555. if self._last_ams_cmd_time > 0:
  3556. elapsed = time.monotonic() - self._last_ams_cmd_time
  3557. if elapsed > 10.0:
  3558. self._ams_cmd_unanswered += 1
  3559. logger.warning(
  3560. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  3561. self.serial_number,
  3562. elapsed,
  3563. self._ams_cmd_unanswered,
  3564. )
  3565. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  3566. if self._ams_cmd_unanswered >= 2:
  3567. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  3568. self._ams_cmd_unanswered = 0
  3569. # Log mapping data when received (for usage tracking debugging)
  3570. if "mapping" in data:
  3571. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  3572. # Log state transitions for debugging
  3573. if "gcode_state" in data:
  3574. logger.debug(
  3575. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  3576. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  3577. )
  3578. # Detect print start (state changes TO RUNNING with a file)
  3579. current_file = self.state.gcode_file or self.state.current_print
  3580. is_new_print = (
  3581. self.state.state == "RUNNING"
  3582. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  3583. and self._previous_gcode_state != "RUNNING"
  3584. and current_file
  3585. and not self._was_running # Prevent duplicates when resuming from PAUSE
  3586. )
  3587. # Also detect if file changed while running (new print started)
  3588. is_file_change = (
  3589. self.state.state == "RUNNING"
  3590. and current_file
  3591. and current_file != self._previous_gcode_file
  3592. and self._previous_gcode_file is not None
  3593. )
  3594. # Track RUNNING state for more robust completion detection
  3595. running_first_observed = False
  3596. if self.state.state == "RUNNING" and current_file:
  3597. if not self._was_running:
  3598. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  3599. # Check if timelapse was enabled in the same message (xcam parsed before this)
  3600. if self.state.timelapse:
  3601. self._timelapse_during_print = True
  3602. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  3603. # Mark this as the first RUNNING observation of the session.
  3604. # If is_new_print also fires below, on_print_start handles
  3605. # baseline capture and we suppress on_print_running_observed
  3606. # to avoid double-capture. If is_new_print does NOT fire
  3607. # (Bambuddy started mid-print — the #1304 guard suppressed
  3608. # it), main.py needs this hook to catch the restart-recovery
  3609. # case (#1485 follow-up).
  3610. running_first_observed = True
  3611. self._was_running = True
  3612. self._completion_triggered = False
  3613. if is_new_print or is_file_change:
  3614. # Clear any old HMS errors when a new print starts
  3615. self.state.hms_errors = []
  3616. # Reset layer tracking for new print (needed for layer-based timelapse)
  3617. self.state.layer_num = 0
  3618. # Reset total_layers so the previous print's value can't bleed into
  3619. # this print's usage-tracker split before the new push_status arrives
  3620. # with the slicer's total (#1771 follow-on to the preservation guard
  3621. # above at line ~2135 — the guard now ignores firmware-reset 0s, so
  3622. # the explicit reset has to happen here instead).
  3623. self.state.total_layers = 0
  3624. # Reset completion tracking for new print
  3625. self._was_running = True
  3626. self._completion_triggered = False
  3627. # #1721: rearm the end-of-print finish-photo trigger for the new print
  3628. self._finish_photo_captured = False
  3629. # Reset last valid progress/layer for usage tracking
  3630. self._last_valid_progress = 0.0
  3631. self._last_valid_layer_num = 0
  3632. # Clear and seed tray change log for mid-print usage splitting
  3633. self.state.tray_change_log.clear()
  3634. tn = self.state.tray_now
  3635. if (
  3636. (0 <= tn <= 15)
  3637. or (A2L_LITE_GLOBAL_BASE <= tn <= A2L_LITE_GLOBAL_BASE + 3)
  3638. or (128 <= tn <= 135)
  3639. or tn == 254
  3640. ):
  3641. self.state.tray_change_log.append((tn, 0))
  3642. # Initialize timelapse tracking based on current state
  3643. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  3644. # so self.state.timelapse may already be set from this message.
  3645. # We preserve that value instead of blindly resetting to False.
  3646. if self.state.timelapse:
  3647. self._timelapse_during_print = True
  3648. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  3649. else:
  3650. self._timelapse_during_print = False
  3651. if (is_new_print or is_file_change) and self.on_print_start:
  3652. logger.info(
  3653. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  3654. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  3655. )
  3656. self.on_print_start(
  3657. {
  3658. "filename": current_file,
  3659. "subtask_name": self.state.subtask_name,
  3660. "remaining_time": self.state.remaining_time * 60
  3661. if self.state.remaining_time > 0
  3662. else None, # Convert minutes to seconds
  3663. "raw_data": data,
  3664. "ams_mapping": self._captured_ams_mapping,
  3665. }
  3666. )
  3667. elif running_first_observed and self.on_print_running_observed:
  3668. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  3669. # print, so the #1304 first-push guard suppressed on_print_start,
  3670. # but we still need main.py to capture a fresh timelapse baseline
  3671. # before the printer uploads the in-flight MP4. Same payload
  3672. # shape as on_print_start so the consumer can reuse fields.
  3673. logger.info(
  3674. f"[{self.serial_number}] RUNNING observed without PRINT START "
  3675. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  3676. )
  3677. self.on_print_running_observed(
  3678. {
  3679. "filename": current_file,
  3680. "subtask_name": self.state.subtask_name,
  3681. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  3682. "raw_data": data,
  3683. "ams_mapping": self._captured_ams_mapping,
  3684. }
  3685. )
  3686. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  3687. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  3688. # This handles cases where server restarts during a print
  3689. should_trigger_completion = (
  3690. self.state.state in ("FINISH", "FAILED")
  3691. and not self._completion_triggered
  3692. and self.on_print_complete
  3693. and (
  3694. self._previous_gcode_state == "RUNNING" # Normal transition
  3695. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  3696. # Pre-print failure (#1111): printer rejected the job during setup
  3697. # — wrong nozzle size, AMS error, etc. The print never reaches
  3698. # RUNNING, so without this branch neither the RUNNING check nor
  3699. # _was_running match and the queue item stays stuck at "printing".
  3700. # Restricted to FAILED from pre-print states so a stale FAILED on
  3701. # first connection (prev=None) still can't accidentally fire.
  3702. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  3703. )
  3704. )
  3705. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  3706. if (
  3707. self.state.state == "IDLE"
  3708. and self._previous_gcode_state == "RUNNING"
  3709. and not self._completion_triggered
  3710. and self.on_print_complete
  3711. ):
  3712. should_trigger_completion = True
  3713. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  3714. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  3715. if (
  3716. not should_trigger_completion
  3717. and self.state.state in ("FINISH", "FAILED")
  3718. and self._previous_gcode_state != self.state.state
  3719. ):
  3720. logger.info(
  3721. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  3722. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  3723. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  3724. )
  3725. # Mark as triggered so state is clean for the next print cycle
  3726. self._completion_triggered = True
  3727. if should_trigger_completion:
  3728. if self.state.state == "FINISH":
  3729. status = "completed"
  3730. elif self.state.state == "FAILED":
  3731. status = "failed"
  3732. else:
  3733. status = "aborted"
  3734. logger.info(
  3735. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  3736. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  3737. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  3738. f"timelapse_during_print: {self._timelapse_during_print}"
  3739. )
  3740. timelapse_was_active = self._timelapse_during_print
  3741. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  3742. # external-spool-only, HMS halt, or firmware variant that skips
  3743. # the unload phase) fire the finish-photo moment now. Bed has
  3744. # already dropped, framing is worse, but we still capture.
  3745. # Only on successful completion — aborted/failed prints don't
  3746. # produce a meaningful finish photo.
  3747. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  3748. self._finish_photo_captured = True
  3749. logger.info(
  3750. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  3751. f"stage-22 never fired; capturing at FINISH-state transition"
  3752. )
  3753. self.on_finish_photo_moment(
  3754. {
  3755. "trigger": "finish_state",
  3756. "filename": self._previous_gcode_file or current_file,
  3757. "subtask_name": self.state.subtask_name,
  3758. "timelapse_was_active": timelapse_was_active,
  3759. }
  3760. )
  3761. self._completion_triggered = True
  3762. self._was_running = False
  3763. self._timelapse_during_print = False # Reset for next print
  3764. # Include HMS errors for failure reason detection
  3765. hms_errors_data = (
  3766. [
  3767. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  3768. for e in self.state.hms_errors
  3769. ]
  3770. if self.state.hms_errors
  3771. else []
  3772. )
  3773. self.on_print_complete(
  3774. {
  3775. "status": status,
  3776. "filename": self._previous_gcode_file or current_file,
  3777. "subtask_name": self.state.subtask_name,
  3778. "raw_data": data,
  3779. "timelapse_was_active": timelapse_was_active,
  3780. "hms_errors": hms_errors_data,
  3781. "ams_mapping": self._captured_ams_mapping,
  3782. # Last valid progress/layer before firmware reset (for partial usage tracking)
  3783. "last_progress": self._last_valid_progress,
  3784. "last_layer_num": self._last_valid_layer_num,
  3785. }
  3786. )
  3787. self._captured_ams_mapping = None
  3788. self._previous_gcode_state = self.state.state
  3789. if current_file:
  3790. self._previous_gcode_file = current_file
  3791. if self.on_state_change:
  3792. self.on_state_change(self.state)
  3793. def _request_push_all(self):
  3794. """Request full status update from printer."""
  3795. if self._client:
  3796. message = {"pushing": {"command": "pushall"}}
  3797. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3798. def _probe_developer_mode(self):
  3799. """Probe developer mode by sending an ams_filament_setting for the external slot.
  3800. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  3801. For these, we detect developer mode by sending a harmless command and
  3802. checking whether the printer accepts or rejects it:
  3803. - result="success" → developer mode ON (commands accepted)
  3804. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  3805. The probe re-sends the current external slot configuration so it's a no-op
  3806. when the command succeeds. If there's no external slot data yet, we send a
  3807. reset (empty filament) which is also safe.
  3808. """
  3809. if not self._client or not self.state.connected:
  3810. return
  3811. self._dev_mode_probed = True
  3812. self._dev_mode_probe_time = time.monotonic()
  3813. self._sequence_id += 1
  3814. seq = str(self._sequence_id)
  3815. self._dev_mode_probe_seq = seq
  3816. # Build probe command: re-send current external slot config (no-op on success)
  3817. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  3818. current = vt_tray[0] if vt_tray else {}
  3819. command = {
  3820. "print": {
  3821. "command": "ams_filament_setting",
  3822. "ams_id": 255,
  3823. "tray_id": 0,
  3824. "slot_id": 0,
  3825. "tray_info_idx": current.get("tray_info_idx", ""),
  3826. "tray_type": current.get("tray_type", ""),
  3827. "tray_sub_brands": current.get("tray_sub_brands", ""),
  3828. "tray_color": current.get("tray_color", "00000000"),
  3829. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  3830. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  3831. "sequence_id": seq,
  3832. }
  3833. }
  3834. setting_id = current.get("setting_id")
  3835. if setting_id:
  3836. command["print"]["setting_id"] = setting_id
  3837. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  3838. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3839. def _handle_dev_mode_probe_response(self, data: dict):
  3840. """Handle response to the developer mode probe command.
  3841. Sets developer_mode based on whether the printer accepted or rejected the command.
  3842. """
  3843. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  3844. self._dev_mode_probe_failures = 0 # Reset on any response
  3845. result = data.get("result", "")
  3846. reason = data.get("reason", "")
  3847. if result == "failed" and "verify failed" in reason:
  3848. self.state.developer_mode = False
  3849. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  3850. else:
  3851. # Success or any other response — commands are accepted
  3852. self.state.developer_mode = True
  3853. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  3854. if self.on_state_change:
  3855. self.on_state_change(self.state)
  3856. def _request_version(self):
  3857. """Request firmware version info from printer."""
  3858. if self._client:
  3859. self._sequence_id += 1
  3860. message = {
  3861. "info": {
  3862. "sequence_id": str(self._sequence_id),
  3863. "command": "get_version",
  3864. }
  3865. }
  3866. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  3867. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3868. def request_status_update(self) -> bool:
  3869. """Request a full status update from the printer (public API).
  3870. Sends both pushall and get_accessories commands to refresh all data
  3871. including nozzle hardware info.
  3872. Returns:
  3873. True if the request was sent, False if not connected.
  3874. """
  3875. if not self._client or not self.state.connected:
  3876. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  3877. return False
  3878. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  3879. self._request_push_all()
  3880. # Note: get_accessories returns stale nozzle data on H2D.
  3881. # The correct nozzle data comes from push_status response.
  3882. return True
  3883. def _request_accessories(self):
  3884. """Request accessories info (nozzle type, etc.) from printer."""
  3885. if self._client:
  3886. self._sequence_id += 1
  3887. message = {
  3888. "system": {
  3889. "sequence_id": str(self._sequence_id),
  3890. "command": "get_accessories",
  3891. "accessory_type": "none",
  3892. }
  3893. }
  3894. logger.debug("[%s] Requesting accessories info", self.serial_number)
  3895. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3896. def _prime_kprofile_request(self):
  3897. """Send a priming K-profile request on connect.
  3898. Bambu printers often ignore the first K-profile request after connection,
  3899. so we send a dummy request on connect to 'prime' the system.
  3900. """
  3901. if self._client:
  3902. self._sequence_id += 1
  3903. command = {
  3904. "print": {
  3905. "command": "extrusion_cali_get",
  3906. "filament_id": "",
  3907. "nozzle_diameter": "0.4",
  3908. "sequence_id": str(self._sequence_id),
  3909. }
  3910. }
  3911. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  3912. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3913. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  3914. """Connect to the printer MQTT broker.
  3915. Args:
  3916. loop: The asyncio event loop to use for thread-safe callbacks.
  3917. If not provided, will try to get the running loop.
  3918. """
  3919. self._loop = loop
  3920. BambuMQTTClient._client_instance_counter += 1
  3921. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  3922. self._client = mqtt.Client(
  3923. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  3924. client_id=client_id,
  3925. protocol=mqtt.MQTTv311,
  3926. )
  3927. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  3928. # tracking (#1164). The default ceiling of 20 wedges sessions after
  3929. # ~16-20 cumulative commands; lifting it well above any realistic
  3930. # session count keeps QoS=1 working without changing wire-protocol
  3931. # behaviour across printer models.
  3932. self._client.max_inflight_messages_set(1000)
  3933. self._client.username_pw_set("bblp", self.access_code)
  3934. self._client.on_connect = self._on_connect
  3935. self._client.on_disconnect = self._on_disconnect
  3936. self._client.on_subscribe = self._on_subscribe
  3937. self._client.on_message = self._on_message
  3938. # TLS setup - Bambu uses self-signed certs
  3939. ssl_context = ssl.create_default_context()
  3940. ssl_context.check_hostname = False
  3941. ssl_context.verify_mode = ssl.CERT_NONE
  3942. # Same reasoning as ImplicitFTP_TLS in bambu_ftp.py: create_default_context()
  3943. # inherits its protocol floor from the OpenSSL build instead of declaring one.
  3944. # Every Bambu broker measured (X1C, H2D on :8883) speaks TLS 1.2 and refuses
  3945. # 1.0/1.1/1.3, so this floor is a no-op on the wire and closes the gap on
  3946. # bare-metal installs whose build allows TLS 1.0.
  3947. ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  3948. self._client.tls_set_context(ssl_context)
  3949. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  3950. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  3951. # Keepalive: paho sends PINGREQs at this interval, broker considers
  3952. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  3953. # real network loss (45s), not so aggressive that transient hiccups
  3954. # trigger false disconnects. Stale detection (60s no messages) handles
  3955. # the P1S/P1P firmware bug where the broker stops publishing but the
  3956. # TCP connection stays alive.
  3957. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  3958. self._client.loop_start()
  3959. def start_print(
  3960. self,
  3961. filename: str,
  3962. plate_id: int = 1,
  3963. ams_mapping: list[int] | None = None,
  3964. bed_levelling: str = "auto",
  3965. flow_cali: str = "auto",
  3966. vibration_cali: bool = True,
  3967. layer_inspect: bool = False,
  3968. timelapse: bool = False,
  3969. use_ams: bool = True,
  3970. nozzle_offset_cali: str = "auto",
  3971. nozzle_mapping: str | None = None,
  3972. ):
  3973. """Start a print job on the printer.
  3974. The file should already be uploaded to the printer's root directory via FTP.
  3975. Args:
  3976. filename: Name of the uploaded file
  3977. plate_id: Plate number to print (default 1)
  3978. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  3979. Global tray ID = (ams_id * 4) + slot_id, external = 254
  3980. timelapse: Record timelapse video
  3981. bed_levelling: Bed levelling — tri-state "off"/"on"/"auto" (auto skips
  3982. if the bed was levelled recently, matching BambuStudio).
  3983. flow_cali: Flow/pressure advance calibration — "off"/"on"/"auto".
  3984. vibration_cali: Vibration compensation calibration
  3985. layer_inspect: First layer AI inspection
  3986. use_ams: Use AMS for automatic filament changes
  3987. nozzle_offset_cali: Nozzle offset calibration — "off"/"on"/"auto"
  3988. (dual-nozzle printers only — silently ignored on single-nozzle).
  3989. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  3990. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  3991. AND the printer is dual-nozzle, parsed and injected as the
  3992. `nozzle_mapping` array on the dispatched project_file so the
  3993. firmware honours the user's slicer pick instead of falling
  3994. back to "last matching nozzle" auto-pick. Silently ignored
  3995. on single-nozzle printers.
  3996. Returns True when the start command was published, False otherwise
  3997. (not connected, or the printer is already busy — see the run-state
  3998. guard below).
  3999. """
  4000. # Never dispatch project_file to a printer that is not idle (#2598).
  4001. # This is the single publish choke point for every dispatch path — the
  4002. # queue scheduler, a manual start, a webhook, and a Virtual-Printer
  4003. # forwarded job all funnel through here — so one guard covers them all.
  4004. # The firmware rejects a start while busy with 0500_4004 ("Device is
  4005. # busy and cannot start a new task"), and on an A1 mini that error
  4006. # cancels the RUNNING job (#2598). IDLE / FINISH / FAILED are valid
  4007. # start targets; only the active-print states are refused. (A
  4008. # transport-level QoS-1 replay on reconnect would bypass this guard,
  4009. # but the dispatch/watchdog reconnect path hard-resets the client with a
  4010. # fresh client_id, so paho has no inflight project_file to replay there.)
  4011. if self.state.state in _ACTIVE_PRINT_STATES:
  4012. logger.warning(
  4013. "[%s] start_print refused: printer busy (gcode_state=%s) — not publishing project_file for %s",
  4014. self.serial_number,
  4015. self.state.state,
  4016. filename,
  4017. )
  4018. return False
  4019. if self._client and self.state.connected:
  4020. # Bambu print command format — matches Bambu Studio's format.
  4021. # The calibration/leveling fields (timelapse, bed_leveling,
  4022. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  4023. # every model. An earlier revision integer-encoded them for the H2
  4024. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  4025. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  4026. # sends plain booleans, and the integer encoding made the H2S
  4027. # silently skip flow-dynamics calibration (#1478). use_ams is the
  4028. # one field that genuinely must stay boolean: H2D Pro firmware
  4029. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  4030. # what actually caused the wrong-extruder routing behind #1386.
  4031. # Dual-nozzle routing for external spool (254 = deputy/left,
  4032. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  4033. # H2 firmware family but is single-nozzle, despite sharing serial
  4034. # prefix "094" with H2D. Prefer runtime detection from
  4035. # device.extruder.info (set in _handle_push_status); fall back to
  4036. # model name for the brief window after connect before push data
  4037. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  4038. # as the primary signal.
  4039. from backend.app.utils.printer_models import is_dual_nozzle_model
  4040. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  4041. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  4042. ams_mapping2 = []
  4043. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  4044. # ams_mapping and relies on ams_mapping2 for external spool details.
  4045. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  4046. # with 0700_8012 "Failed to get AMS mapping table".
  4047. flat_ams_mapping = []
  4048. if ams_mapping is not None:
  4049. for tray_id in ams_mapping:
  4050. # Ensure tray_id is an integer (may be string from JSON)
  4051. tray_id = int(tray_id) if tray_id is not None else -1
  4052. if tray_id == -1:
  4053. # Unmapped filament slot
  4054. flat_ams_mapping.append(-1)
  4055. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  4056. elif tray_id >= 254:
  4057. # External/virtual spool. BambuStudio convention:
  4058. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  4059. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  4060. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  4061. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  4062. # for external spool, but BambuStudio always sends ams_id=255
  4063. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  4064. # firmware to target AMS tray 0 instead of external spool, leading
  4065. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  4066. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  4067. flat_ams_mapping.append(-1)
  4068. ext_ams_id = tray_id if is_dual_nozzle else 255
  4069. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  4070. elif tray_id >= 128:
  4071. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  4072. flat_ams_mapping.append(tray_id)
  4073. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  4074. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  4075. # A2L AMS-Lite (normalised global 24-27): flat mapping is the
  4076. # LOCAL slot 0-3 and ams_mapping2 carries {ams_id:16, slot_id:0-3}
  4077. # — both CONFIRMED against the firmware's own mapping
  4078. # (flat [1], ams_mapping2 {ams_id:16, slot_id:1}).
  4079. _wire_ams, _wire_slot, _ = _a2l
  4080. flat_ams_mapping.append(_wire_slot)
  4081. ams_mapping2.append({"ams_id": _wire_ams, "slot_id": _wire_slot})
  4082. else:
  4083. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  4084. ams_id = tray_id // 4
  4085. slot_id = tray_id % 4
  4086. flat_ams_mapping.append(tray_id)
  4087. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  4088. # Reconcile use_ams against the resolved ams_mapping for single-nozzle
  4089. # printers — the mapping is authoritative about whether this print
  4090. # actually feeds from the AMS. Skip for dual-nozzle printers, where
  4091. # use_ams encodes nozzle routing rather than an AMS on/off flag.
  4092. # H2S falls through here now (#1386): it is single-nozzle and was
  4093. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  4094. # without an AMS attached.
  4095. #
  4096. # Two symmetric corrections:
  4097. #
  4098. # (a) A mapping that resolves a *real* AMS tray (0-253) forces
  4099. # use_ams=True even if it arrived False. A print sent to a Virtual
  4100. # Printer is sliced against the VP, which advertises no AMS, so the
  4101. # slicer sends use_ams=false and that gets stamped on the queue item
  4102. # — but at dispatch the scheduler colour-matches a real printer and
  4103. # resolves a real AMS slot. Without this, the stale False reaches the
  4104. # printer, which ignores the mapped slot and aborts at layer 0 on the
  4105. # empty external spool ("not enough filament"). Diagnosed by
  4106. # @Sawtaytoes (#2595, PR #2596).
  4107. #
  4108. # (b) Only an *explicit* external/virtual spool (254/255) may downgrade
  4109. # to use_ams=False. P1S/P1P with no AMS rejects use_ams=True with
  4110. # "Failed to get AMS mapping table". An unresolved slot (-1) does
  4111. # NEITHER: it means the mapping was never resolved — e.g. a frontend
  4112. # status-load race that persisted [-1] (#2589) — and treating it as
  4113. # external silently started the print against an empty feed. A genuine
  4114. # external selection is >=254; unresolved is -1; a loaded tray is
  4115. # 0-253. Keeping them distinct means an unresolved mapping fails loudly
  4116. # (or is recomputed upstream) instead of silently going external, and
  4117. # never gets force-enabled by (a) either.
  4118. if ams_mapping and not is_dual_nozzle:
  4119. has_real_tray = any(t is not None and 0 <= int(t) <= 253 for t in ams_mapping)
  4120. all_external = all(t is None or int(t) >= 254 for t in ams_mapping)
  4121. if has_real_tray and not use_ams:
  4122. use_ams = True
  4123. logger.info(
  4124. "[%s] AMS mapping resolved a real slot — setting use_ams=True (#2595)",
  4125. self.serial_number,
  4126. )
  4127. elif use_ams and all_external:
  4128. use_ams = False
  4129. logger.info(
  4130. "[%s] All filament slots use external spool — setting use_ams=False",
  4131. self.serial_number,
  4132. )
  4133. # Unique per-submission identity fields. Hardcoded "0" values caused
  4134. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  4135. # continuations of the same job: the printer reuses gcode_start_time
  4136. # from the prior print with task_id=0, so observers latch onto a stale
  4137. # timestamp and report compounding durations on repeat replays (#1011).
  4138. # BambuStudio mints fresh IDs per submission; matching that behavior
  4139. # makes the printer emit a clean state-transition for each job.
  4140. # md5 is left empty — firmware historically accepts "" as "skip
  4141. # validation" (unlike Studio, we don't have the file's real md5 here
  4142. # without re-reading the upload, and sending a synthetic wrong digest
  4143. # risks activation of md5 verification on some firmwares).
  4144. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  4145. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  4146. # overflows and every submission ends up with the same task_id from
  4147. # the printer's perspective — the printer then treats a fresh dispatch
  4148. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  4149. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  4150. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  4151. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  4152. # Remember it so on_print_start can persist a restart-stable id on
  4153. # the archive even before the printer echoes subtask_id back (#1485).
  4154. self.last_dispatch_subtask_id = submission_id
  4155. # Tri-state calibration options → BambuStudio's getValueInt encoding:
  4156. # off=0 (never), on=1 (force every print), auto=2 (printer runs it
  4157. # only if it wasn't done recently). The paired bool field is true
  4158. # only for the explicit "on" state — for "auto" the bool is false and
  4159. # the int carries the intent, exactly as BambuStudio's SelectMachine
  4160. # sends it. Unknown values fall back to auto.
  4161. _tristate_wire = {"off": 0, "on": 1, "auto": 2}
  4162. bed_level_int = _tristate_wire.get(bed_levelling, 2)
  4163. flow_cali_int = _tristate_wire.get(flow_cali, 2)
  4164. nozzle_cali_int = _tristate_wire.get(nozzle_offset_cali, 2)
  4165. command = {
  4166. "print": {
  4167. "sequence_id": "20000",
  4168. "command": "project_file",
  4169. "param": f"Metadata/plate_{plate_id}.gcode",
  4170. "url": f"ftp://{filename}",
  4171. "file": filename,
  4172. "md5": "",
  4173. "bed_type": "auto",
  4174. "timelapse": timelapse,
  4175. # bed_leveling stays a JSON bool (true only for "on") and
  4176. # auto_bed_leveling carries the tri-state int — the exact
  4177. # two-field shape BambuStudio sends. The int must stay a plain
  4178. # number, never quoted (#1478 boolean-family concern applies to
  4179. # the *_cali bools, not these companion ints).
  4180. "bed_leveling": bed_levelling == "on",
  4181. "auto_bed_leveling": bed_level_int,
  4182. "flow_cali": flow_cali == "on",
  4183. "vibration_cali": vibration_cali,
  4184. "layer_inspect": layer_inspect,
  4185. "use_ams": use_ams,
  4186. "cfg": "0",
  4187. # extrude_cali_flag gates flow-dynamics calibration:
  4188. # 0 = never, 1 = force every print, 2 = auto (run only if the
  4189. # filament wasn't calibrated recently). #1721 saw stage 8
  4190. # ("Calibrating dynamic flow") still queued when we send 2 —
  4191. # that is exactly the auto contract (the printer queues the
  4192. # stage and skips it at runtime if recent), not a bug, so 2 is
  4193. # the right wire value for "auto". off/on remain 0/1.
  4194. "extrude_cali_flag": flow_cali_int,
  4195. "extrude_cali_manual_mode": 0,
  4196. # 0 = never, 1 = force, 2 = auto (skip if recent). #1721 saw
  4197. # stage 39 ("Nozzle offset calibration") still queued on 2 —
  4198. # again the auto contract, not a failure to suppress.
  4199. # BambuStudio exposes the toggle only for dual-nozzle
  4200. # (H2D/H2D Pro/H2C/X2D); single-nozzle prints resolve to 0 so
  4201. # firmware never runs a calibration the head doesn't support.
  4202. "nozzle_offset_cali": nozzle_cali_int if is_dual_nozzle else 0,
  4203. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  4204. "profile_id": "0",
  4205. "project_id": submission_id,
  4206. "subtask_id": submission_id,
  4207. "task_id": submission_id,
  4208. }
  4209. }
  4210. # P2S-specific parameter adjustments
  4211. # P2S printer doesn't support vibration calibration like X1/P1 series
  4212. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  4213. command["print"]["vibration_cali"] = False
  4214. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  4215. # Add AMS mapping if provided
  4216. if ams_mapping is not None:
  4217. command["print"]["ams_mapping"] = flat_ams_mapping
  4218. command["print"]["ams_mapping2"] = ams_mapping2
  4219. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  4220. # `nozzle_mapping` carries per-filament physical nozzle position
  4221. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  4222. # item; parse here so the wire ships an array, matching
  4223. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  4224. # defensively — single-nozzle firmwares would ignore the field
  4225. # but we err on the side of not emitting unrecognised fields. A
  4226. # parse failure is logged but never blocks the dispatch — the
  4227. # firmware will fall back to its auto-pick path, which is the
  4228. # pre-fix behaviour.
  4229. if is_dual_nozzle and nozzle_mapping:
  4230. try:
  4231. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  4232. except json.JSONDecodeError:
  4233. logger.warning(
  4234. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  4235. "project_file (firmware will auto-pick): %r",
  4236. self.serial_number,
  4237. nozzle_mapping,
  4238. )
  4239. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  4240. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4241. # Record what we dispatched so /cover can pick the right plate
  4242. # thumbnail even when the printer's gcode_file echo is just the
  4243. # 3MF filename without a plate path (#1166). Match the same
  4244. # subtask_name shape we send so the comparison in the cover route
  4245. # works against state.subtask_name reflected back via MQTT.
  4246. self.state.dispatched_plate_id = plate_id
  4247. self.state.dispatched_subtask = command["print"]["subtask_name"]
  4248. return True
  4249. else:
  4250. # Log why we couldn't send the command
  4251. if not self._client:
  4252. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  4253. elif not self.state.connected:
  4254. logger.error(
  4255. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  4256. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  4257. )
  4258. return False
  4259. def stop_print(self) -> bool:
  4260. """Stop the current print job."""
  4261. if self._client and self.state.connected:
  4262. command = {"print": {"command": "stop", "sequence_id": "0"}}
  4263. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4264. logger.info("[%s] Sent stop print command", self.serial_number)
  4265. return True
  4266. return False
  4267. def set_xcam_option(
  4268. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  4269. ) -> bool:
  4270. """Set an xcam (AI detection) option on the printer.
  4271. Args:
  4272. module_name: The xcam module to control (e.g., "spaghetti_detector",
  4273. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  4274. enabled: Whether to enable or disable the feature
  4275. print_halt: Whether to halt print on detection (only applies to some detectors)
  4276. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  4277. Returns:
  4278. True if command was sent, False if not connected
  4279. """
  4280. if not self._client or not self.state.connected:
  4281. return False
  4282. # auto_recovery_step_loss uses a different command format (print.print_option)
  4283. if module_name == "auto_recovery_step_loss":
  4284. return self._set_print_option("auto_recovery", enabled)
  4285. self._sequence_id += 1
  4286. # Build the xcam control command (exact OrcaSlicer format)
  4287. # Key findings from OrcaSlicer source:
  4288. # - Uses "xcam" wrapper (not "print")
  4289. # - print_halt is ALWAYS true (legacy protocol requirement)
  4290. # - Both "control" and "enable" are set to the same value
  4291. # - halt_print_sensitivity controls actual halt behavior
  4292. command = {
  4293. "xcam": {
  4294. "command": "xcam_control_set",
  4295. "sequence_id": str(self._sequence_id),
  4296. "module_name": module_name,
  4297. "control": enabled,
  4298. "enable": enabled, # old protocol compatibility
  4299. "print_halt": True, # ALWAYS true per OrcaSlicer
  4300. }
  4301. }
  4302. # Only add sensitivity if not "never_halt"
  4303. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  4304. # The module_name field determines which detector's sensitivity is being set
  4305. if sensitivity and sensitivity != "never_halt":
  4306. command["xcam"]["halt_print_sensitivity"] = sensitivity
  4307. command_json = json.dumps(command)
  4308. self._client.publish(self.topic_publish, command_json, qos=1)
  4309. logger.debug(
  4310. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  4311. )
  4312. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  4313. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  4314. # This prevents stale MQTT data from immediately overwriting our change
  4315. self._xcam_hold_start[module_name] = time.time()
  4316. # Update local state immediately for responsive UI
  4317. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  4318. # When spaghetti_detector sensitivity is changed, pileup also changes
  4319. if module_name == "spaghetti_detector":
  4320. self.state.print_options.spaghetti_detector = enabled
  4321. self.state.print_options.print_halt = print_halt
  4322. if sensitivity and sensitivity != "never_halt":
  4323. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  4324. self.state.print_options.halt_print_sensitivity = sensitivity
  4325. self.state.print_options.pileup_sensitivity = sensitivity
  4326. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  4327. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  4328. elif module_name == "first_layer_inspector":
  4329. self.state.print_options.first_layer_inspector = enabled
  4330. elif module_name == "printing_monitor":
  4331. self.state.print_options.printing_monitor = enabled
  4332. elif module_name == "buildplate_marker_detector":
  4333. self.state.print_options.buildplate_marker_detector = enabled
  4334. elif module_name == "allow_skip_parts":
  4335. self.state.print_options.allow_skip_parts = enabled
  4336. elif module_name == "pileup_detector":
  4337. self.state.print_options.pileup_detector = enabled
  4338. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  4339. elif module_name == "clump_detector":
  4340. self.state.print_options.nozzle_clumping_detector = enabled
  4341. if sensitivity and sensitivity != "never_halt":
  4342. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  4343. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  4344. elif module_name == "airprint_detector":
  4345. self.state.print_options.airprint_detector = enabled
  4346. if sensitivity and sensitivity != "never_halt":
  4347. self.state.print_options.airprint_sensitivity = sensitivity
  4348. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  4349. elif module_name == "auto_recovery_step_loss":
  4350. self.state.print_options.auto_recovery_step_loss = enabled
  4351. return True
  4352. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  4353. """Set a print option using the print.print_option command.
  4354. This is different from xcam_control_set and is used for options like:
  4355. - auto_recovery
  4356. - air_print_detect
  4357. - filament_tangle_detect
  4358. - nozzle_blob_detect
  4359. - sound_enable
  4360. Args:
  4361. option_name: The option to control (e.g., "auto_recovery")
  4362. enabled: Whether to enable or disable the option
  4363. Returns:
  4364. True if command was sent, False if not connected
  4365. """
  4366. if not self._client or not self.state.connected:
  4367. return False
  4368. self._sequence_id += 1
  4369. command = {
  4370. "print": {
  4371. "command": "print_option",
  4372. "sequence_id": str(self._sequence_id),
  4373. option_name: enabled,
  4374. }
  4375. }
  4376. command_json = json.dumps(command)
  4377. self._client.publish(self.topic_publish, command_json, qos=1)
  4378. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  4379. # Set hold timer
  4380. hold_key = f"print_option_{option_name}"
  4381. self._xcam_hold_start[hold_key] = time.time()
  4382. # Update local state immediately
  4383. if option_name == "auto_recovery":
  4384. self.state.print_options.auto_recovery_step_loss = enabled
  4385. elif option_name == "auto_switch_filament":
  4386. self.state.ams_filament_backup = enabled
  4387. return True
  4388. def set_ams_filament_backup(self, enabled: bool) -> bool:
  4389. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  4390. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  4391. shape from H2D capture 2026-06-20.
  4392. """
  4393. return self._set_print_option("auto_switch_filament", enabled)
  4394. def start_calibration(
  4395. self,
  4396. bed_leveling: bool = False,
  4397. vibration: bool = False,
  4398. motor_noise: bool = False,
  4399. nozzle_offset: bool = False,
  4400. high_temp_heatbed: bool = False,
  4401. ) -> bool:
  4402. """Start printer calibration with selected options.
  4403. Args:
  4404. bed_leveling: Run bed leveling calibration
  4405. vibration: Run vibration compensation calibration
  4406. motor_noise: Run motor noise cancellation calibration
  4407. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  4408. high_temp_heatbed: Run high-temperature heatbed calibration
  4409. Returns:
  4410. True if command was sent, False if not connected
  4411. """
  4412. if not self._client or not self.state.connected:
  4413. return False
  4414. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  4415. # Bit 0: xcam_cali (not exposed in UI)
  4416. # Bit 1: bed_leveling
  4417. # Bit 2: vibration
  4418. # Bit 3: motor_noise
  4419. # Bit 4: nozzle_cali
  4420. # Bit 5: bed_cali (high-temp heatbed)
  4421. # Bit 6: clumppos_cali (not exposed in UI)
  4422. option = 0
  4423. if bed_leveling:
  4424. option |= 1 << 1
  4425. if vibration:
  4426. option |= 1 << 2
  4427. if motor_noise:
  4428. option |= 1 << 3
  4429. if nozzle_offset:
  4430. option |= 1 << 4
  4431. if high_temp_heatbed:
  4432. option |= 1 << 5
  4433. if option == 0:
  4434. logger.warning("[%s] No calibration options selected", self.serial_number)
  4435. return False
  4436. self._sequence_id += 1
  4437. command = {
  4438. "print": {
  4439. "command": "calibration",
  4440. "sequence_id": str(self._sequence_id),
  4441. "option": option,
  4442. }
  4443. }
  4444. command_json = json.dumps(command)
  4445. self._client.publish(self.topic_publish, command_json, qos=1)
  4446. logger.info(
  4447. f"[{self.serial_number}] Starting calibration: "
  4448. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  4449. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  4450. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  4451. )
  4452. return True
  4453. def disconnect(self, timeout: float = 0):
  4454. """Disconnect from the printer."""
  4455. if self._client:
  4456. self._disconnection_event = threading.Event()
  4457. self._client.disconnect()
  4458. self._disconnection_event.wait(timeout=timeout)
  4459. self._client.loop_stop()
  4460. self._client = None
  4461. self.state.connected = False
  4462. def send_command(self, command: dict):
  4463. """Send a command to the printer."""
  4464. if self._client and self.state.connected:
  4465. # Log outgoing message if logging is enabled
  4466. if self._logging_enabled:
  4467. self._message_log.append(
  4468. MQTTLogEntry(
  4469. timestamp=datetime.now(timezone.utc).isoformat(),
  4470. topic=self.topic_publish,
  4471. direction="out",
  4472. payload=command,
  4473. )
  4474. )
  4475. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4476. def enable_logging(self, enabled: bool = True):
  4477. """Enable or disable MQTT message logging."""
  4478. self._logging_enabled = enabled
  4479. # Don't clear logs when stopping - user can manually clear with clear_logs()
  4480. def get_logs(self) -> list[MQTTLogEntry]:
  4481. """Get all logged MQTT messages."""
  4482. return list(self._message_log)
  4483. def clear_logs(self):
  4484. """Clear the message log."""
  4485. self._message_log.clear()
  4486. @property
  4487. def logging_enabled(self) -> bool:
  4488. """Check if logging is enabled."""
  4489. return self._logging_enabled
  4490. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  4491. """Register a handler invoked for every incoming MQTT message.
  4492. Used by the VP MQTT bridge to republish the printer's report pushes to
  4493. slicers connected to a virtual printer in non-proxy mode. Handlers run
  4494. on paho's network thread and must not block; exceptions are caught.
  4495. """
  4496. if handler not in self._raw_message_handlers:
  4497. self._raw_message_handlers.append(handler)
  4498. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  4499. """Unregister a previously-registered raw-message handler."""
  4500. try:
  4501. self._raw_message_handlers.remove(handler)
  4502. except ValueError:
  4503. pass
  4504. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  4505. """Publish a pre-formed payload directly to the printer's MQTT broker.
  4506. Used by the VP MQTT bridge to forward slicer-originated commands without
  4507. going through send_command's sequence-id mangling. Returns False if the
  4508. underlying paho client isn't ready.
  4509. """
  4510. if self._client is None:
  4511. return False
  4512. try:
  4513. info = self._client.publish(topic, payload, qos=qos)
  4514. return info.rc == mqtt.MQTT_ERR_SUCCESS
  4515. except Exception:
  4516. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  4517. return False
  4518. def send_drying_command(
  4519. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  4520. ):
  4521. """Send AMS drying start/stop command.
  4522. Args:
  4523. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  4524. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  4525. duration: Drying duration in hours
  4526. mode: 1=start, 0=stop
  4527. filament: Filament type string (e.g. "PLA", "PETG")
  4528. rotate_tray: Whether to rotate the spool during drying for even heat
  4529. """
  4530. if not self._client:
  4531. return False
  4532. self._sequence_id += 1
  4533. # A2L AMS-Lite: normalised id 6 -> physical 16 on the wire (the Lite does
  4534. # not actually support drying, but keep the translation consistent). The
  4535. # _drying_targets dict below stays keyed by the normalised id so the
  4536. # on_drying_complete callback matches the telemetry.
  4537. wire_ams_id = a2l_lite_wire_ids(ams_id, 0)[0] if ams_id == A2L_LITE_NORMALIZED_AMS_ID else ams_id
  4538. command = {
  4539. "print": {
  4540. "sequence_id": str(self._sequence_id),
  4541. "command": "ams_filament_drying",
  4542. "ams_id": wire_ams_id,
  4543. "temp": temp,
  4544. "cooling_temp": 20 if mode == 1 else 0,
  4545. "duration": duration,
  4546. "humidity": 0,
  4547. "mode": mode,
  4548. "rotate_tray": rotate_tray,
  4549. "filament": filament,
  4550. "close_power_conflict": False,
  4551. }
  4552. }
  4553. # Log the full wire JSON at INFO so support bundles capture exactly
  4554. # what we sent — needed to diagnose silent rejections (#1447) where
  4555. # the printer ACKs the command but never starts/stops drying.
  4556. # Paired with the ams_filament_drying response-payload INFO log so
  4557. # both halves of the conversation land in the bundle by default.
  4558. wire_json = json.dumps(command)
  4559. self._client.publish(self.topic_publish, wire_json, qos=1)
  4560. logger.info(
  4561. "[%s] Sent ams_filament_drying: %s",
  4562. self.serial_number,
  4563. wire_json,
  4564. )
  4565. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  4566. # while drying. Bambu only echoes dry_time on subsequent pushes.
  4567. if mode == 1:
  4568. self._drying_targets[ams_id] = {
  4569. "filament": filament or "",
  4570. "temp": int(temp),
  4571. }
  4572. else:
  4573. self._drying_targets.pop(ams_id, None)
  4574. return True
  4575. def _handle_kprofile_response(self, data: dict):
  4576. """Handle K-profile response from printer."""
  4577. response_nozzle = data.get("nozzle_diameter")
  4578. response_seq_id = data.get("sequence_id", "?")
  4579. filaments = data.get("filaments", [])
  4580. expected_nozzle = getattr(self, "_expected_kprofile_nozzle", None)
  4581. has_pending_request = self._pending_kprofile_response is not None
  4582. # Log all incoming responses when we have a pending request (for debugging)
  4583. if has_pending_request:
  4584. logger.info(
  4585. f"[{self.serial_number}] K-profile response: nozzle={response_nozzle}, "
  4586. f"seq_id={response_seq_id}, {len(filaments)} profiles, expected={expected_nozzle}"
  4587. )
  4588. # If we have a pending request, only accept responses with matching nozzle_diameter
  4589. # The printer broadcasts 0.4mm profiles constantly - we need to wait for the actual response
  4590. if has_pending_request and expected_nozzle and response_nozzle != expected_nozzle:
  4591. # Ignore this broadcast, keep waiting for matching response
  4592. logger.debug(
  4593. f"[{self.serial_number}] Ignoring broadcast: got nozzle={response_nozzle}, waiting for {expected_nozzle}"
  4594. )
  4595. return
  4596. # If no pending request, this is just a broadcast - update state silently and return early
  4597. if not has_pending_request:
  4598. # Still parse profiles to keep state updated, but don't log
  4599. profiles = []
  4600. for f in filaments:
  4601. if isinstance(f, dict):
  4602. try:
  4603. cali_idx = f.get("cali_idx", 0)
  4604. profiles.append(
  4605. KProfile(
  4606. slot_id=cali_idx,
  4607. extruder_id=int(f.get("extruder_id", 0)),
  4608. nozzle_id=str(f.get("nozzle_id", "")),
  4609. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  4610. filament_id=str(f.get("filament_id", "")),
  4611. name=str(f.get("name", "")),
  4612. k_value=str(f.get("k_value", "0.000000")),
  4613. n_coef=str(f.get("n_coef", "0.000000")),
  4614. ams_id=int(f.get("ams_id", 0)),
  4615. tray_id=int(f.get("tray_id", -1)),
  4616. setting_id=f.get("setting_id"),
  4617. )
  4618. )
  4619. except (ValueError, TypeError):
  4620. pass # Skip malformed K-profile entries; remaining profiles still usable
  4621. self.state.kprofiles = profiles
  4622. return
  4623. profiles = []
  4624. for i, f in enumerate(filaments):
  4625. if isinstance(f, dict):
  4626. try:
  4627. # cali_idx is the actual slot/calibration index from the printer
  4628. cali_idx = f.get("cali_idx", i)
  4629. profiles.append(
  4630. KProfile(
  4631. slot_id=cali_idx,
  4632. extruder_id=int(f.get("extruder_id", 0)),
  4633. nozzle_id=str(f.get("nozzle_id", "")),
  4634. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  4635. filament_id=str(f.get("filament_id", "")),
  4636. name=str(f.get("name", "")),
  4637. k_value=str(f.get("k_value", "0.000000")),
  4638. n_coef=str(f.get("n_coef", "0.000000")),
  4639. ams_id=int(f.get("ams_id", 0)),
  4640. tray_id=int(f.get("tray_id", -1)),
  4641. setting_id=f.get("setting_id"),
  4642. )
  4643. )
  4644. except (ValueError, TypeError) as e:
  4645. logger.warning("Failed to parse K-profile: %s", e)
  4646. self.state.kprofiles = profiles
  4647. self._kprofile_response_data = profiles
  4648. # Signal that we received the response (only if we were waiting for one)
  4649. # Use thread-safe method since MQTT callbacks run in a different thread
  4650. # Capture in local var to avoid TOCTOU race: asyncio thread can clear
  4651. # self._pending_kprofile_response between the check and the .set() call
  4652. event = self._pending_kprofile_response
  4653. if event:
  4654. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  4655. if self._loop and self._loop.is_running():
  4656. self._loop.call_soon_threadsafe(event.set)
  4657. else:
  4658. # Fallback for when loop is not available
  4659. event.set()
  4660. async def get_kprofiles(
  4661. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  4662. ) -> list[KProfile]:
  4663. """Request K-profiles from the printer with retry logic.
  4664. Bambu printers sometimes ignore the first K-profile request, so we
  4665. implement retry logic to ensure reliable retrieval.
  4666. Args:
  4667. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  4668. timeout: Timeout in seconds to wait for each response attempt
  4669. max_retries: Maximum number of retry attempts
  4670. Returns:
  4671. List of KProfile objects
  4672. """
  4673. if not self._client or not self.state.connected:
  4674. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  4675. return []
  4676. # Capture current event loop for thread-safe callback
  4677. try:
  4678. self._loop = asyncio.get_running_loop()
  4679. except RuntimeError:
  4680. logger.warning("[%s] No running event loop", self.serial_number)
  4681. return []
  4682. for attempt in range(max_retries):
  4683. # Set up response event for this attempt
  4684. self._sequence_id += 1
  4685. self._pending_kprofile_response = asyncio.Event()
  4686. self._kprofile_response_data = None
  4687. self._expected_kprofile_nozzle = nozzle_diameter # Track which nozzle response we expect
  4688. # Send the command with nozzle_diameter filter
  4689. command = {
  4690. "print": {
  4691. "command": "extrusion_cali_get",
  4692. "filament_id": "",
  4693. "nozzle_diameter": nozzle_diameter,
  4694. "sequence_id": str(self._sequence_id),
  4695. }
  4696. }
  4697. logger.info(
  4698. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries})"
  4699. )
  4700. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  4701. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4702. # Wait for response (response handler already filters by nozzle_diameter)
  4703. try:
  4704. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  4705. profiles = self._kprofile_response_data or []
  4706. logger.info(
  4707. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  4708. )
  4709. return profiles
  4710. except TimeoutError:
  4711. logger.warning(
  4712. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  4713. )
  4714. if attempt < max_retries - 1:
  4715. # Brief delay before retry
  4716. await asyncio.sleep(0.5)
  4717. finally:
  4718. self._pending_kprofile_response = None
  4719. self._expected_kprofile_nozzle = None
  4720. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  4721. return []
  4722. def set_kprofile(
  4723. self,
  4724. filament_id: str,
  4725. name: str,
  4726. k_value: str,
  4727. nozzle_diameter: str = "0.4",
  4728. nozzle_id: str = "HS00-0.4",
  4729. extruder_id: int = 0,
  4730. setting_id: str | None = None,
  4731. slot_id: int = 0,
  4732. cali_idx: int | None = None,
  4733. ) -> bool:
  4734. """Set/update a K-profile on the printer.
  4735. Args:
  4736. filament_id: Bambu filament identifier
  4737. name: Profile name
  4738. k_value: Pressure advance value (e.g., "0.020000")
  4739. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  4740. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  4741. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  4742. setting_id: Existing setting ID for updates, None for new
  4743. slot_id: Calibration index (cali_idx) for the profile
  4744. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  4745. Returns:
  4746. True if command was sent, False otherwise
  4747. """
  4748. if not self._client or not self.state.connected:
  4749. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  4750. return False
  4751. self._sequence_id += 1
  4752. # Build the filament entry - printer uses cali_idx for profile identification
  4753. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  4754. # For edits, use the provided cali_idx or slot_id
  4755. if cali_idx is not None:
  4756. effective_cali_idx = cali_idx
  4757. else:
  4758. effective_cali_idx = -1 if slot_id == 0 else slot_id
  4759. # Generate a setting_id for new profiles (required by printer)
  4760. # Format: "PF" + 17 random digits
  4761. import random
  4762. if not setting_id and slot_id == 0:
  4763. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  4764. filament_entry = {
  4765. "ams_id": 0,
  4766. "cali_idx": effective_cali_idx,
  4767. "extruder_id": extruder_id,
  4768. "filament_id": filament_id,
  4769. "k_value": k_value,
  4770. "n_coef": "0.000000",
  4771. "name": name,
  4772. "nozzle_diameter": nozzle_diameter,
  4773. "nozzle_id": nozzle_id,
  4774. "setting_id": setting_id if setting_id else "",
  4775. "tray_id": -1,
  4776. }
  4777. command = {
  4778. "print": {
  4779. "command": "extrusion_cali_set",
  4780. "filaments": [filament_entry],
  4781. "nozzle_diameter": nozzle_diameter,
  4782. "sequence_id": str(self._sequence_id),
  4783. }
  4784. }
  4785. command_json = json.dumps(command)
  4786. logger.info(
  4787. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  4788. )
  4789. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  4790. self._client.publish(self.topic_publish, command_json, qos=1)
  4791. return True
  4792. def set_kprofiles_batch(
  4793. self,
  4794. profiles: list[dict],
  4795. nozzle_diameter: str = "0.4",
  4796. ) -> bool:
  4797. """Set multiple K-profiles in a single command (for dual-nozzle).
  4798. Args:
  4799. profiles: List of profile dicts, each with:
  4800. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  4801. nozzle_diameter: Common nozzle diameter for all profiles
  4802. Returns:
  4803. True if command was sent, False otherwise
  4804. """
  4805. if not self._client or not self.state.connected:
  4806. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  4807. return False
  4808. import random
  4809. self._sequence_id += 1
  4810. filament_entries = []
  4811. for p in profiles:
  4812. slot_id = p.get("slot_id", 0)
  4813. cali_idx = p.get("cali_idx")
  4814. if cali_idx is not None:
  4815. effective_cali_idx = cali_idx
  4816. else:
  4817. effective_cali_idx = -1 if slot_id == 0 else slot_id
  4818. setting_id = p.get("setting_id")
  4819. if not setting_id and slot_id == 0:
  4820. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  4821. filament_entries.append(
  4822. {
  4823. "ams_id": 0,
  4824. "cali_idx": effective_cali_idx,
  4825. "extruder_id": p.get("extruder_id", 0),
  4826. "filament_id": p.get("filament_id", ""),
  4827. "k_value": p.get("k_value", "0.020000"),
  4828. "n_coef": "0.000000",
  4829. "name": p.get("name", ""),
  4830. "nozzle_diameter": nozzle_diameter,
  4831. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  4832. "setting_id": setting_id if setting_id else "",
  4833. "tray_id": -1,
  4834. }
  4835. )
  4836. command = {
  4837. "print": {
  4838. "command": "extrusion_cali_set",
  4839. "filaments": filament_entries,
  4840. "nozzle_diameter": nozzle_diameter,
  4841. "sequence_id": str(self._sequence_id),
  4842. }
  4843. }
  4844. command_json = json.dumps(command)
  4845. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  4846. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  4847. self._client.publish(self.topic_publish, command_json, qos=1)
  4848. return True
  4849. def delete_kprofile(
  4850. self,
  4851. cali_idx: int,
  4852. filament_id: str,
  4853. nozzle_id: str,
  4854. nozzle_diameter: str = "0.4",
  4855. extruder_id: int = 0,
  4856. setting_id: str | None = None,
  4857. ) -> bool:
  4858. """Delete a K-profile from the printer.
  4859. Args:
  4860. cali_idx: The calibration index (slot_id) of the profile to delete
  4861. filament_id: Bambu filament identifier
  4862. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  4863. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  4864. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  4865. setting_id: Unique setting identifier (for X1C series)
  4866. Returns:
  4867. True if command was sent, False otherwise
  4868. """
  4869. if not self._client or not self.state.connected:
  4870. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  4871. return False
  4872. self._sequence_id += 1
  4873. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  4874. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  4875. # Prefer runtime detection from device.extruder.info; fall back to
  4876. # model name. H2S is single-nozzle but shares serial prefix "094" with
  4877. # H2D, so a prefix-only check misclassified it (#1386).
  4878. from backend.app.utils.printer_models import is_dual_nozzle_model
  4879. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  4880. if is_dual_nozzle:
  4881. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  4882. command = {
  4883. "print": {
  4884. "command": "extrusion_cali_del",
  4885. "sequence_id": str(self._sequence_id),
  4886. "extruder_id": extruder_id,
  4887. "nozzle_id": nozzle_id,
  4888. "filament_id": filament_id,
  4889. "cali_idx": cali_idx,
  4890. "nozzle_diameter": nozzle_diameter,
  4891. }
  4892. }
  4893. else:
  4894. # X1C/P1/A1 format: include all fields like the set command
  4895. # The delete command structure should match what set uses
  4896. command = {
  4897. "print": {
  4898. "command": "extrusion_cali_del",
  4899. "sequence_id": str(self._sequence_id),
  4900. "filament_id": filament_id,
  4901. "cali_idx": cali_idx,
  4902. "setting_id": setting_id if setting_id else "",
  4903. "nozzle_diameter": nozzle_diameter,
  4904. "nozzle_id": nozzle_id,
  4905. "extruder_id": extruder_id,
  4906. }
  4907. }
  4908. command_json = json.dumps(command)
  4909. logger.info(
  4910. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  4911. )
  4912. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  4913. # Use QoS 1 for reliable delivery (at least once)
  4914. self._client.publish(self.topic_publish, command_json, qos=1)
  4915. return True
  4916. # =========================================================================
  4917. # Printer Control Commands
  4918. # =========================================================================
  4919. def pause_print(self) -> bool:
  4920. """Pause the current print job."""
  4921. if not self._client or not self.state.connected:
  4922. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  4923. return False
  4924. command = {"print": {"command": "pause", "sequence_id": "0"}}
  4925. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4926. logger.info("[%s] Sent pause print command", self.serial_number)
  4927. return True
  4928. def resume_print(self) -> bool:
  4929. """Resume a paused print job."""
  4930. if not self._client or not self.state.connected:
  4931. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  4932. return False
  4933. command = {"print": {"command": "resume", "sequence_id": "0"}}
  4934. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4935. logger.info("[%s] Sent resume print command", self.serial_number)
  4936. return True
  4937. def clear_hms_errors(self) -> bool:
  4938. """Clear HMS/print errors on the printer and locally."""
  4939. if not self._client or not self.state.connected:
  4940. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  4941. return False
  4942. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  4943. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4944. self.state.hms_errors = []
  4945. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  4946. return True
  4947. def skip_objects(self, object_ids: list[int]) -> bool:
  4948. """Skip specific objects during a print.
  4949. This command tells the printer to skip printing the specified objects.
  4950. The object IDs come from the slice_info.config file in the 3MF.
  4951. Args:
  4952. object_ids: List of identify_id values from slice_info.config
  4953. Returns:
  4954. True if command was sent, False otherwise
  4955. """
  4956. if not self._client or not self.state.connected:
  4957. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  4958. return False
  4959. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  4960. logger.warning(
  4961. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  4962. )
  4963. return False
  4964. if not object_ids:
  4965. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  4966. return False
  4967. # Validate all IDs are integers
  4968. try:
  4969. obj_list = [int(oid) for oid in object_ids]
  4970. except (ValueError, TypeError) as e:
  4971. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  4972. return False
  4973. self._sequence_id += 1
  4974. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  4975. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4976. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  4977. # Track skipped objects in state
  4978. for oid in obj_list:
  4979. if oid not in self.state.skipped_objects:
  4980. self.state.skipped_objects.append(oid)
  4981. return True
  4982. def send_gcode(self, gcode: str) -> bool:
  4983. """Send G-code command(s) to the printer.
  4984. Multiple commands can be separated by newlines.
  4985. Args:
  4986. gcode: G-code command(s) to send
  4987. Returns:
  4988. True if command was sent, False otherwise
  4989. """
  4990. if not self._client or not self.state.connected:
  4991. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  4992. return False
  4993. self._sequence_id += 1
  4994. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  4995. # Use QoS 1 for reliable delivery (at least once)
  4996. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4997. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  4998. return True
  4999. def set_bed_temperature(self, target: int) -> bool:
  5000. """Set the bed target temperature.
  5001. Args:
  5002. target: Target temperature in Celsius (0 to turn off)
  5003. Returns:
  5004. True if command was sent, False otherwise
  5005. """
  5006. return self.send_gcode(f"M140 S{target}")
  5007. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  5008. """Set the nozzle target temperature.
  5009. Args:
  5010. target: Target temperature in Celsius (0 to turn off)
  5011. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  5012. Returns:
  5013. True if command was sent, False otherwise
  5014. """
  5015. # Use M104 for non-blocking
  5016. # Always use T parameter for H2D compatibility
  5017. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  5018. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  5019. # Track it locally so we can display it correctly
  5020. if result and nozzle == 1:
  5021. self.state.temperatures["nozzle_target"] = float(target)
  5022. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  5023. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  5024. return result
  5025. def set_chamber_temperature(self, target: int) -> bool:
  5026. """Set the chamber target temperature.
  5027. Args:
  5028. target: Target temperature in Celsius (0 to turn off heating)
  5029. Returns:
  5030. True if command was sent, False otherwise
  5031. """
  5032. # M141 sets chamber temperature
  5033. result = self.send_gcode(f"M141 S{target}")
  5034. # Track chamber target locally (MQTT reports encoded values that need filtering)
  5035. if result:
  5036. self.state.temperatures["chamber_target"] = float(target)
  5037. self.state.temperatures["_chamber_target_set_time"] = time.time()
  5038. # Update heating state immediately based on new target
  5039. current_temp = self.state.temperatures.get("chamber", 0)
  5040. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  5041. logger.info(
  5042. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  5043. )
  5044. return result
  5045. def set_print_speed(self, mode: int) -> bool:
  5046. """Set the print speed mode.
  5047. Args:
  5048. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  5049. Returns:
  5050. True if command was sent, False otherwise
  5051. """
  5052. if not self._client or not self.state.connected:
  5053. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  5054. return False
  5055. if mode not in (1, 2, 3, 4):
  5056. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  5057. return False
  5058. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  5059. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5060. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  5061. return True
  5062. def set_fan_speed(self, fan: int, speed: int) -> bool:
  5063. """Set fan speed.
  5064. Args:
  5065. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber, 10=left auxiliary).
  5066. Index 10 is the optional left auxiliary part cooling fan on P2S/X2D
  5067. (airduct part id 10); Bambu's official machine profiles drive it with
  5068. "M106 P10" in start/layer-change gcode.
  5069. speed: Speed 0-255 (0=off, 255=full)
  5070. Returns:
  5071. True if command was sent, False otherwise
  5072. """
  5073. if fan not in (1, 2, 3, 10):
  5074. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  5075. return False
  5076. speed = max(0, min(255, speed)) # Clamp to 0-255
  5077. return self.send_gcode(f"M106 P{fan} S{speed}")
  5078. def set_part_fan(self, speed: int) -> bool:
  5079. """Set part cooling fan speed (0-255)."""
  5080. return self.set_fan_speed(1, speed)
  5081. def set_aux_fan(self, speed: int) -> bool:
  5082. """Set auxiliary fan speed (0-255)."""
  5083. return self.set_fan_speed(2, speed)
  5084. def set_chamber_fan(self, speed: int) -> bool:
  5085. """Set chamber fan speed (0-255)."""
  5086. return self.set_fan_speed(3, speed)
  5087. def set_left_aux_fan(self, speed: int) -> bool:
  5088. """Set left auxiliary part cooling fan speed (0-255). P2S/X2D accessory."""
  5089. return self.set_fan_speed(10, speed)
  5090. def set_airduct_mode(self, mode: str) -> bool:
  5091. """Set air conditioning mode (cooling or heating).
  5092. Args:
  5093. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  5094. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  5095. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  5096. closes top exhaust flap
  5097. Returns:
  5098. True if command was sent, False otherwise
  5099. """
  5100. if not self._client or not self.state.connected:
  5101. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  5102. return False
  5103. self._sequence_id += 1
  5104. mode_id = 0 if mode == "cooling" else 1
  5105. command = {
  5106. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  5107. }
  5108. # Use QoS 1 for reliable delivery
  5109. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5110. logger.info(
  5111. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  5112. )
  5113. return True
  5114. def set_chamber_light(self, on: bool) -> bool:
  5115. """Turn chamber light on or off.
  5116. Args:
  5117. on: True to turn on, False to turn off
  5118. Returns:
  5119. True if command was sent, False otherwise
  5120. """
  5121. if not self._client or not self.state.connected:
  5122. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  5123. return False
  5124. mode = "on" if on else "off"
  5125. # Control both chamber lights (some printers like H2D have two)
  5126. for led_node in ["chamber_light", "chamber_light2"]:
  5127. self._sequence_id += 1
  5128. command = {
  5129. "system": {
  5130. "command": "ledctrl",
  5131. "led_node": led_node,
  5132. "led_mode": mode,
  5133. "led_on_time": 500,
  5134. "led_off_time": 500,
  5135. "loop_times": 0,
  5136. "interval_time": 0,
  5137. "sequence_id": str(self._sequence_id),
  5138. }
  5139. }
  5140. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5141. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  5142. return True
  5143. def select_extruder(self, extruder: int) -> bool:
  5144. """Select the active extruder for dual-nozzle printers (H2D).
  5145. Args:
  5146. extruder: Extruder index (0=right, 1=left for H2D)
  5147. Returns:
  5148. True if command was sent, False otherwise
  5149. """
  5150. if extruder not in (0, 1):
  5151. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  5152. return False
  5153. if not self._client or not self.state.connected:
  5154. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  5155. return False
  5156. # H2D extruder switching via select_extruder command
  5157. # Command format captured from OrcaSlicer:
  5158. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  5159. # extruder_index: 0 = RIGHT, 1 = LEFT
  5160. self._sequence_id += 1
  5161. command = {
  5162. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  5163. }
  5164. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5165. logger.info(
  5166. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  5167. )
  5168. return True
  5169. def home_axes(self, axes: str = "XYZ") -> bool:
  5170. """Run the printer's full auto-home sequence.
  5171. The ``axes`` argument is ignored: a bare ``G28`` is always sent so
  5172. Bambu firmware runs its safe multi-step routine (park toolhead →
  5173. home XY → home Z). Partial-axis variants like ``G28 Z`` skip the
  5174. toolhead-park step and can crash the bed into the toolhead on H2C
  5175. / H2D / H2S / X1 where Z-home moves the bed UP — see #1052.
  5176. """
  5177. return self.send_gcode("G28")
  5178. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  5179. """Move an axis by a relative distance.
  5180. Args:
  5181. axis: Axis to move ("X", "Y", or "Z")
  5182. distance: Distance to move in mm (positive or negative)
  5183. speed: Movement speed in mm/min
  5184. Returns:
  5185. True if command was sent, False otherwise
  5186. """
  5187. axis = axis.upper()
  5188. if axis not in ("X", "Y", "Z"):
  5189. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  5190. return False
  5191. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  5192. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  5193. return self.send_gcode(gcode)
  5194. def disable_motors(self) -> bool:
  5195. """Disable all stepper motors.
  5196. Warning: This will cause the printer to lose its position.
  5197. A homing operation will be required before printing.
  5198. Returns:
  5199. True if command was sent, False otherwise
  5200. """
  5201. return self.send_gcode("M18")
  5202. def enable_motors(self) -> bool:
  5203. """Enable all stepper motors.
  5204. Returns:
  5205. True if command was sent, False otherwise
  5206. """
  5207. return self.send_gcode("M17")
  5208. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  5209. """Load filament from a specific AMS tray.
  5210. Args:
  5211. tray_id: Global tray ID — 0..15 for AMS slots, 254 for external spool
  5212. (single-external printers and Ext-L on dual-nozzle H2D),
  5213. 255 for Ext-R on dual-nozzle H2D.
  5214. extruder_id: Unused - kept for API compatibility
  5215. Returns:
  5216. True if command was sent, False otherwise
  5217. """
  5218. if not self._client or not self.state.connected:
  5219. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  5220. return False
  5221. # Build the ams_change_filament command. Encoding differs by target type:
  5222. # - AMS slots (0..15): slot_id is the local slot, curr/tar_temp = -1.
  5223. # - External spool (tray_id=254): legacy capture from a single-extruder
  5224. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  5225. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  5226. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  5227. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  5228. self._sequence_id += 1
  5229. wire_target = tray_id
  5230. if tray_id == 255:
  5231. ams_id = 255
  5232. slot_id = 0 # extruder index for the right nozzle
  5233. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  5234. if right_temp < 180:
  5235. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  5236. curr_temp = right_temp
  5237. tar_temp = right_temp
  5238. elif tray_id == 254:
  5239. ams_id = 255
  5240. slot_id = 254
  5241. curr_temp = -1
  5242. tar_temp = -1
  5243. elif (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  5244. # A2L AMS-Lite: physical unit 16 + local slot confirmed; the wire
  5245. # `target` (physical global 64-67) is extrapolated (no A2L load
  5246. # capture yet). See a2l_lite_wire_ids.
  5247. ams_id, slot_id, wire_target = _a2l
  5248. curr_temp = -1
  5249. tar_temp = -1
  5250. else:
  5251. ams_id = tray_id // 4
  5252. slot_id = tray_id % 4
  5253. curr_temp = -1
  5254. tar_temp = -1
  5255. command = {
  5256. "print": {
  5257. "command": "ams_change_filament",
  5258. "sequence_id": str(self._sequence_id),
  5259. "ams_id": ams_id,
  5260. "slot_id": slot_id,
  5261. "target": wire_target,
  5262. "curr_temp": curr_temp,
  5263. "tar_temp": tar_temp,
  5264. }
  5265. }
  5266. command_json = json.dumps(command)
  5267. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  5268. self._client.publish(self.topic_publish, command_json, qos=1)
  5269. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  5270. # Track this load request for H2D dual-nozzle disambiguation
  5271. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  5272. self._last_load_tray_id = tray_id
  5273. self.state.pending_tray_target = tray_id
  5274. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  5275. return True
  5276. def ams_unload_filament(self) -> bool:
  5277. """Unload the currently loaded filament.
  5278. Returns:
  5279. True if command was sent, False otherwise
  5280. """
  5281. if not self._client or not self.state.connected:
  5282. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  5283. return False
  5284. # Get the currently loaded tray info
  5285. tray_now = self.state.tray_now
  5286. logger.info("[%s] Unload requested, tray_now=%s", self.serial_number, tray_now)
  5287. # Determine source ams_id for the unload command
  5288. if tray_now == 255 or tray_now == 254:
  5289. ams_id = 255 # No filament or external spool
  5290. elif (_a2l := a2l_lite_wire_ids(tray_now // 4, tray_now)) is not None:
  5291. ams_id = _a2l[0] # A2L AMS-Lite: normalised 6 -> physical 16
  5292. else:
  5293. ams_id = tray_now // 4 # Source AMS
  5294. # Command format from BambuStudio traffic capture:
  5295. # - No extruder_id field
  5296. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  5297. # - slot_id=255 and target=255 for unload
  5298. # Get current nozzle temperature for the unload command
  5299. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  5300. if nozzle_temp < 180:
  5301. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  5302. self._sequence_id += 1
  5303. command = {
  5304. "print": {
  5305. "command": "ams_change_filament",
  5306. "sequence_id": str(self._sequence_id),
  5307. "ams_id": ams_id,
  5308. "slot_id": 255, # 255 = unload marker
  5309. "target": 255, # 255 = unload destination
  5310. "curr_temp": nozzle_temp,
  5311. "tar_temp": nozzle_temp,
  5312. }
  5313. }
  5314. command_json = json.dumps(command)
  5315. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  5316. self._client.publish(self.topic_publish, command_json, qos=1)
  5317. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  5318. # Clear tracked load request since we're unloading
  5319. self._last_load_tray_id = None
  5320. self.state.pending_tray_target = None
  5321. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  5322. return True
  5323. def ams_control(self, action: str) -> bool:
  5324. """Control AMS operations.
  5325. Args:
  5326. action: "resume", "reset", or "pause"
  5327. Returns:
  5328. True if command was sent, False otherwise
  5329. """
  5330. if not self._client or not self.state.connected:
  5331. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  5332. return False
  5333. if action not in ("resume", "reset", "pause"):
  5334. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  5335. return False
  5336. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  5337. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5338. logger.info("[%s] AMS control: %s", self.serial_number, action)
  5339. return True
  5340. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  5341. """Trigger RFID re-read for a specific AMS tray.
  5342. Args:
  5343. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  5344. tray_id: Tray ID within the AMS (0-3)
  5345. Returns:
  5346. Tuple of (success, message)
  5347. """
  5348. if not self._client or not self.state.connected:
  5349. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  5350. return False, "Printer not connected"
  5351. # Check if filament is currently loaded (tray_now != 255)
  5352. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  5353. tray_now = self.state.tray_now
  5354. if tray_now != 255:
  5355. # Decode which tray is loaded for the message
  5356. if tray_now == 254:
  5357. loaded_tray = "external spool"
  5358. elif tray_now >= 0 and tray_now < 128:
  5359. loaded_ams = tray_now // 4
  5360. loaded_slot = tray_now % 4
  5361. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  5362. else:
  5363. loaded_tray = f"tray {tray_now}"
  5364. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  5365. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  5366. # A2L AMS-Lite: physical unit 16 + local slot (matches ams_mapping2).
  5367. wire_ams_id, wire_slot_id = ams_id, tray_id
  5368. if (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  5369. wire_ams_id, wire_slot_id, _ = _a2l
  5370. # Use ams_get_rfid command to trigger RFID re-read
  5371. # This command is used by Bambu Studio to re-read the RFID tag
  5372. command = {
  5373. "print": {"command": "ams_get_rfid", "ams_id": wire_ams_id, "slot_id": wire_slot_id, "sequence_id": "0"}
  5374. }
  5375. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5376. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  5377. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  5378. def ams_set_filament_setting(
  5379. self,
  5380. ams_id: int,
  5381. tray_id: int,
  5382. tray_info_idx: str,
  5383. tray_type: str,
  5384. tray_sub_brands: str,
  5385. tray_color: str,
  5386. nozzle_temp_min: int,
  5387. nozzle_temp_max: int,
  5388. setting_id: str = "",
  5389. ) -> bool:
  5390. """Set AMS tray filament settings (type, color, temperature).
  5391. Note: K value is set separately via extrusion_cali_sel command.
  5392. Args:
  5393. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  5394. tray_id: Tray ID within the AMS (0-3)
  5395. tray_info_idx: Filament ID short format (e.g., "GFL05")
  5396. tray_type: Filament type (e.g., "PLA", "PETG")
  5397. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  5398. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  5399. nozzle_temp_min: Minimum nozzle temperature
  5400. nozzle_temp_max: Maximum nozzle temperature
  5401. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  5402. Returns:
  5403. True if command was sent, False otherwise
  5404. """
  5405. if not self._client or not self.state.connected:
  5406. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  5407. return False
  5408. # Calculate mqtt IDs based on AMS type.
  5409. # External-spool convention verified against a BambuStudio→X1C packet capture
  5410. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  5411. # *global* tray index in `tray_id`, not a local position within the virtual
  5412. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  5413. # is what the original code was matching — but the request and response
  5414. # use different semantics for that field. Sending `tray_id: 0` is what
  5415. # the P1S in #1279 rejected with `result: "fail"`.
  5416. if ams_id == 255:
  5417. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5418. if len(vt_tray) > 1:
  5419. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  5420. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  5421. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  5422. # captured Studio→H2D exchange confirms the correct value.
  5423. mqtt_ams_id = 254 + tray_id
  5424. mqtt_tray_id = 0
  5425. else:
  5426. # Single external slot (X1C, P1S, A1): global tray_id=254.
  5427. mqtt_ams_id = 255
  5428. mqtt_tray_id = 254
  5429. slot_id = 0
  5430. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  5431. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches the
  5432. # firmware's own ams_mapping2 {ams_id:16, slot_id:0-3}).
  5433. mqtt_ams_id, slot_id, _ = _a2l
  5434. mqtt_tray_id = slot_id
  5435. elif ams_id <= 3:
  5436. mqtt_ams_id = ams_id
  5437. mqtt_tray_id = tray_id
  5438. slot_id = tray_id
  5439. else:
  5440. # AMS-HT: single tray per unit
  5441. mqtt_ams_id = ams_id
  5442. mqtt_tray_id = tray_id
  5443. slot_id = 0
  5444. command = {
  5445. "print": {
  5446. "command": "ams_filament_setting",
  5447. "ams_id": mqtt_ams_id,
  5448. "tray_id": mqtt_tray_id,
  5449. "slot_id": slot_id,
  5450. "tray_info_idx": tray_info_idx,
  5451. "tray_type": tray_type,
  5452. "tray_sub_brands": tray_sub_brands,
  5453. "tray_color": tray_color,
  5454. "nozzle_temp_min": nozzle_temp_min,
  5455. "nozzle_temp_max": nozzle_temp_max,
  5456. "sequence_id": "0",
  5457. }
  5458. }
  5459. # Include setting_id if provided (helps slicer show correct profile)
  5460. if setting_id:
  5461. command["print"]["setting_id"] = setting_id
  5462. command_json = json.dumps(command)
  5463. logger.info(
  5464. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  5465. )
  5466. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  5467. self._client.publish(self.topic_publish, command_json, qos=1)
  5468. self._last_ams_cmd_time = time.monotonic()
  5469. return True
  5470. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  5471. """Reset an AMS slot to empty/unconfigured state.
  5472. Args:
  5473. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  5474. tray_id: Tray ID within the AMS (0-3)
  5475. Returns:
  5476. True if command was sent, False otherwise
  5477. """
  5478. if not self._client or not self.state.connected:
  5479. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  5480. return False
  5481. # Calculate mqtt IDs based on AMS type — same convention as
  5482. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  5483. if ams_id == 255:
  5484. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5485. if len(vt_tray) > 1:
  5486. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  5487. mqtt_ams_id = 254 + tray_id
  5488. mqtt_tray_id = 0
  5489. else:
  5490. # Single external slot (X1C, P1S, A1): global tray_id=254.
  5491. mqtt_ams_id = 255
  5492. mqtt_tray_id = 254
  5493. slot_id = 0
  5494. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  5495. # A2L AMS-Lite: physical unit 16, local 0-3 slot (matches ams_mapping2).
  5496. mqtt_ams_id, slot_id, _ = _a2l
  5497. mqtt_tray_id = slot_id
  5498. elif ams_id <= 3:
  5499. mqtt_ams_id = ams_id
  5500. mqtt_tray_id = tray_id
  5501. slot_id = tray_id
  5502. else:
  5503. # AMS-HT: single tray per unit
  5504. mqtt_ams_id = ams_id
  5505. mqtt_tray_id = tray_id
  5506. slot_id = 0
  5507. command = {
  5508. "print": {
  5509. "command": "ams_filament_setting",
  5510. "ams_id": mqtt_ams_id,
  5511. "tray_id": mqtt_tray_id,
  5512. "slot_id": slot_id,
  5513. "tray_info_idx": "",
  5514. "tray_type": "",
  5515. "tray_sub_brands": "",
  5516. "tray_color": "00000000",
  5517. "nozzle_temp_min": 0,
  5518. "nozzle_temp_max": 0,
  5519. "sequence_id": "0",
  5520. }
  5521. }
  5522. command_json = json.dumps(command)
  5523. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  5524. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  5525. self._client.publish(self.topic_publish, command_json, qos=1)
  5526. self._last_ams_cmd_time = time.monotonic()
  5527. return True
  5528. def extrusion_cali_sel(
  5529. self,
  5530. ams_id: int,
  5531. tray_id: int,
  5532. cali_idx: int,
  5533. filament_id: str,
  5534. nozzle_diameter: str = "0.4",
  5535. ) -> bool:
  5536. """Set calibration profile (K value) for an AMS slot.
  5537. This command selects a K profile from the printer's calibration list.
  5538. Use cali_idx=-1 to use the default K value (0.020).
  5539. Note: Do NOT send setting_id in this command — BambuStudio never includes
  5540. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  5541. Args:
  5542. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  5543. tray_id: Tray ID within the AMS (0-3)
  5544. cali_idx: Calibration profile index (-1 for default)
  5545. filament_id: Filament preset ID (same as tray_info_idx)
  5546. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  5547. Returns:
  5548. True if command was sent, False otherwise
  5549. """
  5550. if not self._client or not self.state.connected:
  5551. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  5552. return False
  5553. # Calculate mqtt IDs based on AMS type.
  5554. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  5555. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  5556. if ams_id == 255:
  5557. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  5558. # ams_filament_setting which uses LOCAL tray_id=0).
  5559. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  5560. if len(vt_tray) > 1:
  5561. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  5562. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  5563. mqtt_ams_id = 254 + tray_id
  5564. mqtt_tray_id = 254 + tray_id
  5565. else:
  5566. # Single external slot (X1C, P1S, A1): global tray_id=254
  5567. mqtt_ams_id = 254
  5568. mqtt_tray_id = 254
  5569. slot_id = 0
  5570. elif ams_id <= 3:
  5571. mqtt_ams_id = ams_id
  5572. mqtt_tray_id = ams_id * 4 + tray_id
  5573. slot_id = tray_id
  5574. elif (_a2l := a2l_lite_wire_ids(ams_id, tray_id)) is not None:
  5575. # A2L AMS-Lite: physical unit 16 + local slot are confirmed; the GLOBAL
  5576. # tray_id this command wants (physical 16*4+slot) is extrapolated (no
  5577. # A2L cali_sel capture yet) — see a2l_lite_wire_ids.
  5578. mqtt_ams_id, slot_id, mqtt_tray_id = _a2l
  5579. elif ams_id >= 128 and ams_id <= 135:
  5580. mqtt_ams_id = ams_id
  5581. mqtt_tray_id = tray_id
  5582. slot_id = 0
  5583. else:
  5584. mqtt_ams_id = ams_id
  5585. mqtt_tray_id = tray_id
  5586. slot_id = 0
  5587. command = {
  5588. "print": {
  5589. "command": "extrusion_cali_sel",
  5590. "cali_idx": cali_idx,
  5591. "filament_id": filament_id,
  5592. "nozzle_diameter": nozzle_diameter,
  5593. "ams_id": mqtt_ams_id,
  5594. "tray_id": mqtt_tray_id,
  5595. "slot_id": slot_id,
  5596. "sequence_id": "0",
  5597. }
  5598. }
  5599. command_json = json.dumps(command)
  5600. logger.info(
  5601. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  5602. )
  5603. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  5604. self._client.publish(self.topic_publish, command_json, qos=1)
  5605. return True
  5606. def extrusion_cali_set(
  5607. self,
  5608. tray_id: int,
  5609. k_value: float,
  5610. nozzle_diameter: str = "0.4",
  5611. nozzle_temp: int = 220,
  5612. filament_id: str = "",
  5613. setting_id: str = "",
  5614. name: str = "",
  5615. cali_idx: int = -1,
  5616. ) -> bool:
  5617. """Directly set K value (pressure advance) for a tray.
  5618. Uses the filaments array format required by current firmware.
  5619. Args:
  5620. tray_id: Global tray ID (ams_id * 4 + slot)
  5621. k_value: Pressure advance K value (e.g., 0.020)
  5622. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  5623. nozzle_temp: Nozzle temperature for calibration reference
  5624. filament_id: Filament preset ID (e.g., "GFA02")
  5625. setting_id: Setting ID (e.g., "GFSA02_07")
  5626. name: Profile display name
  5627. cali_idx: Calibration index (-1 for new)
  5628. Returns:
  5629. True if command was sent, False otherwise
  5630. """
  5631. if not self._client or not self.state.connected:
  5632. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  5633. return False
  5634. nozzle_id = f"HS00-{nozzle_diameter}"
  5635. # A2L AMS-Lite: a normalised global tray (24-27) must go out as the
  5636. # physical global (extrapolated 64-67; see a2l_lite_wire_ids). ams_id
  5637. # stays 0 (hardcoded, as for every other unit here).
  5638. wire_tray_id = tray_id
  5639. if 0 <= tray_id <= 253 and (_a2l := a2l_lite_wire_ids(tray_id // 4, tray_id)) is not None:
  5640. wire_tray_id = _a2l[2]
  5641. filament_entry = {
  5642. "ams_id": 0,
  5643. "cali_idx": cali_idx,
  5644. "extruder_id": 0,
  5645. "filament_id": filament_id,
  5646. "k_value": f"{k_value:.6f}",
  5647. "n_coef": "1.400000",
  5648. "name": name,
  5649. "nozzle_diameter": nozzle_diameter,
  5650. "nozzle_id": nozzle_id,
  5651. "setting_id": setting_id,
  5652. "tray_id": wire_tray_id,
  5653. }
  5654. command = {
  5655. "print": {
  5656. "command": "extrusion_cali_set",
  5657. "filaments": [filament_entry],
  5658. "nozzle_diameter": nozzle_diameter,
  5659. "sequence_id": str(self._sequence_id),
  5660. }
  5661. }
  5662. command_json = json.dumps(command)
  5663. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  5664. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  5665. self._client.publish(self.topic_publish, command_json, qos=1)
  5666. return True
  5667. def set_timelapse(self, enable: bool) -> bool:
  5668. """Enable or disable timelapse recording.
  5669. Args:
  5670. enable: True to enable, False to disable
  5671. Returns:
  5672. True if command was sent, False otherwise
  5673. """
  5674. if not self._client or not self.state.connected:
  5675. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  5676. return False
  5677. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  5678. # First send the timelapse setting
  5679. timelapse_cmd = {
  5680. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  5681. }
  5682. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  5683. # Request status update
  5684. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5685. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  5686. return True
  5687. def set_liveview(self, enable: bool) -> bool:
  5688. """Enable or disable live view / camera streaming.
  5689. Args:
  5690. enable: True to enable, False to disable
  5691. Returns:
  5692. True if command was sent, False otherwise
  5693. """
  5694. if not self._client or not self.state.connected:
  5695. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  5696. return False
  5697. command = {
  5698. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  5699. }
  5700. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  5701. # Request status update
  5702. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  5703. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  5704. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  5705. return True
  5706. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  5707. """Dispatch the user's choice from the HMS-error modal as a printer command.
  5708. Args:
  5709. print_error: Canonical hex identifier for the fault — 8 chars for the
  5710. 32-bit `print_error` path, 16 chars for the 64-bit `hms[]` path
  5711. (HMSError.full_code). Carried through unchanged from the route.
  5712. Converted to its DECIMAL string form for the `ignore` /
  5713. `idle_ignore` commands' `err` field, which is what the firmware
  5714. actually compares against the active fault. The pre-#1869
  5715. hex-string `err` was silently rejected because the firmware was
  5716. being asked to match `"05008051"` against int 0x05008051
  5717. (= 83918929 decimal) — see BambuStudio's
  5718. DeviceManager.cpp:1450-1462 (`command_hms_ignore`) which passes
  5719. `std::to_string(int m_error_code)`.
  5720. action: One of HMSAction's string values.
  5721. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  5722. Required by BambuStudio's `command_hms_ignore` / `command_hms_stop`
  5723. shapes; empty string is the no-job-id sentinel.
  5724. Returns False when the MQTT client is offline or when `action` is unknown
  5725. so the route surfaces it as a 4xx rather than a silent no-op.
  5726. """
  5727. if not self._client or not self.state.connected:
  5728. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  5729. return False
  5730. # Always re-push the full state after a command so the modal's underlying
  5731. # status query reflects the new error list (or absence) on the next tick.
  5732. def publish(payload: dict):
  5733. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  5734. self._client.publish(
  5735. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  5736. )
  5737. # BambuStudio's `err` field is the DECIMAL string of the error code's int
  5738. # value (DeviceErrorDialog.cpp passes `std::to_string(m_error_code)` to
  5739. # every command_hms_* call). Our route hands us the hex string —
  5740. # convert. Falls back to the raw input if it's not parseable so the
  5741. # firmware can reject it and the route can surface 502 instead of us
  5742. # raising ValueError mid-dispatch.
  5743. try:
  5744. err_decimal = str(int(print_error, 16))
  5745. except ValueError:
  5746. err_decimal = print_error
  5747. def hms_resume():
  5748. # Plain resume — verified against the user's H2D/H2S to leave PAUSE
  5749. # cleanly when "Problem Solved and Resume" is clicked. BambuStudio
  5750. # sends `{command: "resume", err: "<decimal>", param: "reserve",
  5751. # job_id: ...}` from `command_hms_resume`; we kept the simpler
  5752. # shape historically because it works, and changing it without a
  5753. # field test risks regressing a path that the user has confirmed.
  5754. publish(
  5755. {
  5756. "print": {
  5757. "command": "resume",
  5758. "param": "",
  5759. "sequence_id": "0",
  5760. }
  5761. }
  5762. )
  5763. def hms_stop():
  5764. # Same as hms_resume — plain shape, confirmed working by the user
  5765. # for "Stop Printing".
  5766. publish(
  5767. {
  5768. "print": {
  5769. "command": "stop",
  5770. "param": "",
  5771. "sequence_id": "0",
  5772. }
  5773. }
  5774. )
  5775. def hms_ignore_command():
  5776. # BambuStudio's `command_hms_ignore` (DeviceManager.cpp:1450) —
  5777. # what the "Ignore this and Resume" button actually publishes.
  5778. # Distinct from `idle_ignore`: this command has the firmware
  5779. # suppress the next re-check of the named fault AND resume the
  5780. # paused print in a single operation. The previous Bambuddy code
  5781. # redirected IGNORE_RESUME to a plain `resume`, which is why the
  5782. # wrong-plate HMS came back 1-2 s later: `resume` means "I fixed
  5783. # the problem, re-check normally" so the firmware re-detected the
  5784. # wrong plate and re-paused with the same code (#1869).
  5785. #
  5786. # BambuStudio also routes IGNORE_NO_REMINDER_NEXT_TIME (a.k.a.
  5787. # DONT_REMIND_NEXT_TIME) to this same command — the persistent
  5788. # variant of "don't remind next time" lives on `idle_ignore`'s
  5789. # type=1, not as a separate ignore shape.
  5790. publish(
  5791. {
  5792. "print": {
  5793. "command": "ignore",
  5794. "err": err_decimal,
  5795. "param": "reserve",
  5796. "job_id": job_id or "",
  5797. "sequence_id": "0",
  5798. }
  5799. }
  5800. )
  5801. def hms_idle_ignore(persistent: bool = False):
  5802. # `idle_ignore` is BambuStudio's "dismiss this warning without
  5803. # resuming" command for non-pause warnings — what
  5804. # `command_hms_idle_ignore` (DeviceManager.cpp:1424) sends.
  5805. # type=0 dismisses once, type=1 suppresses the same warning
  5806. # permanently. Used by NO_REMINDER_NEXT_TIME, which BambuStudio
  5807. # explicitly dispatches via `command_hms_idle_ignore(..., 0)` —
  5808. # NOT via the resume-bearing `ignore` command.
  5809. publish(
  5810. {
  5811. "print": {
  5812. "command": "idle_ignore",
  5813. "err": err_decimal,
  5814. "type": 1 if persistent else 0,
  5815. "sequence_id": "0",
  5816. }
  5817. }
  5818. )
  5819. def ams_control(param: str):
  5820. publish(
  5821. {
  5822. "print": {
  5823. "command": "ams_control",
  5824. "param": param,
  5825. "sequence_id": "0",
  5826. }
  5827. }
  5828. )
  5829. def clean_print_error():
  5830. # Matches the existing `clear_hms_errors` shape — Bambu does not
  5831. # expect `print_error` in the body; the command clears whatever
  5832. # error dialog is currently active on the printer.
  5833. publish(
  5834. {
  5835. "print": {
  5836. "command": "clean_print_error",
  5837. "sequence_id": "0",
  5838. }
  5839. }
  5840. )
  5841. def uiop_close():
  5842. # `err` is the 8-char hex short code (already a string from the
  5843. # frontend), uppercased for consistency with how BambuStudio sends it.
  5844. publish(
  5845. {
  5846. "system": {
  5847. "command": "uiop",
  5848. "name": "print_error",
  5849. "action": "close",
  5850. "source": 1,
  5851. "type": "dialog",
  5852. "err": print_error.upper(),
  5853. "sequence_id": "0",
  5854. }
  5855. }
  5856. )
  5857. match action:
  5858. case (
  5859. HMSAction.RESUME_PRINTING
  5860. | HMSAction.RESUME_PRINTING_DEFECTS
  5861. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  5862. | HMSAction.PROBLEM_SOLVED_RESUME
  5863. | HMSAction.FILAMENT_LOAD_RESUME
  5864. | HMSAction.PROCEED
  5865. ):
  5866. hms_resume()
  5867. case HMSAction.STOP_PRINTING:
  5868. hms_stop()
  5869. case HMSAction.IGNORE_RESUME | HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  5870. # All three buttons map to BambuStudio's `command_hms_ignore`
  5871. # (DeviceErrorDialog.cpp:596-602). The "no reminder next time"
  5872. # half of IGNORE_NO_REMINDER_NEXT_TIME is the firmware's
  5873. # responsibility — the wire shape is identical.
  5874. hms_ignore_command()
  5875. case HMSAction.NO_REMINDER_NEXT_TIME:
  5876. # BambuStudio's NO_REMINDER_NEXT_TIME branch dispatches
  5877. # `command_hms_idle_ignore` with type=0
  5878. # (DeviceErrorDialog.cpp:588-590). Distinct from the
  5879. # IGNORE_* buttons above: idle_ignore does NOT resume, only
  5880. # dismisses the dialog.
  5881. hms_idle_ignore(persistent=False)
  5882. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  5883. ams_control("done")
  5884. case (
  5885. HMSAction.RETRY_FILAMENT_EXTRUDED
  5886. | HMSAction.CONTINUE
  5887. | HMSAction.RETRY_PROBLEM_SOLVED
  5888. | HMSAction.DBL_CHECK_RETRY
  5889. ):
  5890. ams_control("resume")
  5891. case HMSAction.ABORT:
  5892. ams_control("abort")
  5893. case HMSAction.OK_BUTTON:
  5894. clean_print_error()
  5895. case HMSAction.DBL_CHECK_OK:
  5896. clean_print_error()
  5897. uiop_close()
  5898. case HMSAction.DBL_CHECK_RESUME:
  5899. # Plain resume — not HMS-aware, no err/job_id.
  5900. publish(
  5901. {
  5902. "print": {
  5903. "command": "resume",
  5904. "param": "",
  5905. "sequence_id": "0",
  5906. }
  5907. }
  5908. )
  5909. case HMSAction.REFRESH_NOZZLE:
  5910. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  5911. case HMSAction.TURN_OFF_FIRE_ALARM:
  5912. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  5913. case HMSAction.STOP_DRYING:
  5914. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  5915. case HMSAction.DISABLE_PURIFICATION:
  5916. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  5917. case (
  5918. HMSAction.CHECK_ASSISTANT
  5919. | HMSAction.JUMP_TO_LIVEVIEW
  5920. | HMSAction.OK_JUMP_RACK
  5921. | HMSAction.REMOVE_CLOSE_BTN
  5922. | HMSAction.LOAD_VIRTUAL_TRAY
  5923. | HMSAction.CANCLE
  5924. | HMSAction.DBL_CHECK_CANCEL
  5925. ):
  5926. # UI-only actions — the printer's own screen handles these; the
  5927. # modal still surfaces them so the user has parity with Studio.
  5928. pass
  5929. case _:
  5930. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  5931. return False
  5932. return True