bambu_mqtt.py 318 KB

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