bambu_mqtt.py 239 KB

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