bambu_mqtt.py 282 KB

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