bambu_mqtt.py 341 KB

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