bambu_mqtt.py 295 KB

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