bambu_mqtt.py 390 KB

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