bambu_mqtt.py 281 KB

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