bambu_mqtt.py 237 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879
  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
  1431. if tn != self.state.last_loaded_tray and self.state.state in ("RUNNING", "PAUSE"):
  1432. self.state.tray_change_log.append((tn, self.state.layer_num))
  1433. logger.info(
  1434. "[%s] Tray change during print: tray=%d at layer=%d",
  1435. self.serial_number,
  1436. tn,
  1437. self.state.layer_num,
  1438. )
  1439. self.state.last_loaded_tray = self.state.tray_now
  1440. logger.debug("[%s] tray_now updated: %s", self.serial_number, self.state.tray_now)
  1441. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  1442. # state when checking filament change mode for H2D disambiguation
  1443. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  1444. # We've already processed the status fields above, so just return if no ams list
  1445. if ams_list is None:
  1446. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  1447. return
  1448. elif isinstance(ams_data, list):
  1449. ams_list = ams_data
  1450. else:
  1451. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  1452. return
  1453. # Merge AMS data instead of replacing, to handle partial updates
  1454. # During prints, the printer may only send updates for active AMS units
  1455. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  1456. existing_ams = self.state.raw_data.get("ams", [])
  1457. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  1458. # Update existing units with new data, add new units
  1459. for ams_unit in ams_list:
  1460. ams_id = ams_unit.get("id")
  1461. if ams_id is not None:
  1462. existing_unit = existing_by_id.get(ams_id)
  1463. if existing_unit and "tray" in ams_unit:
  1464. # Deep merge trays to preserve fields from previous updates
  1465. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  1466. merged_trays = []
  1467. for new_tray in ams_unit.get("tray", []):
  1468. tray_id = new_tray.get("id")
  1469. if tray_id is not None and tray_id in existing_trays:
  1470. # Merge: start with existing, update with new non-empty values
  1471. merged_tray = existing_trays[tray_id].copy()
  1472. # Detect slot-clearing updates (spool removal):
  1473. # When tray_type is explicitly empty, clear everything
  1474. # including RFID data (tag_uid/tray_uuid).
  1475. slot_clearing = new_tray.get("tray_type") == ""
  1476. # Some printers (e.g. H2D) only send {id, state} in
  1477. # incremental updates when a tray is not fully loaded.
  1478. # state=11 means loaded; other values (9=empty,
  1479. # 10=spool present but filament not in feeder) indicate
  1480. # the slot should be cleared. Without this, old
  1481. # tray_type/tray_color persist indefinitely (#784).
  1482. tray_state = new_tray.get("state")
  1483. if (
  1484. tray_state is not None
  1485. and tray_state != 11
  1486. and "tray_type" not in new_tray
  1487. and merged_tray.get("tray_type")
  1488. ):
  1489. logger.info(
  1490. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  1491. self.serial_number,
  1492. ams_id,
  1493. tray_id,
  1494. tray_state,
  1495. )
  1496. slot_clearing = True
  1497. # The incremental update only has {id, state} — inject
  1498. # empty values for all content fields so the merge loop
  1499. # below clears the stale data from merged_tray.
  1500. new_tray.update(
  1501. {
  1502. "tray_type": "",
  1503. "tray_sub_brands": "",
  1504. "tray_color": "",
  1505. "tray_id_name": "",
  1506. "tray_info_idx": "",
  1507. "tag_uid": "0000000000000000",
  1508. "tray_uuid": "00000000000000000000000000000000",
  1509. "remain": 0,
  1510. "k": None,
  1511. "cali_idx": None,
  1512. }
  1513. )
  1514. for key, value in new_tray.items():
  1515. # Fields that should always be updated (even with empty/zero values):
  1516. # - remain, k, id, cali_idx: status indicators where 0 is valid
  1517. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  1518. # tray_id_name: slot content indicators that must be cleared
  1519. # when a spool is removed (fixes #147 - old AMS empty slot)
  1520. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  1521. # They are only cleared during spool removal (slot_clearing=True).
  1522. # Periodic AMS updates often include empty RFID fields which
  1523. # would overwrite valid data from the initial pushall.
  1524. always_update_fields = (
  1525. "remain",
  1526. "k",
  1527. "id",
  1528. "cali_idx",
  1529. "tray_type",
  1530. "tray_sub_brands",
  1531. "tray_info_idx",
  1532. "tray_color",
  1533. "tray_id_name",
  1534. )
  1535. if (
  1536. key in always_update_fields
  1537. or slot_clearing
  1538. or value
  1539. not in (
  1540. None,
  1541. "",
  1542. "0000000000000000",
  1543. "00000000000000000000000000000000",
  1544. )
  1545. ):
  1546. merged_tray[key] = value
  1547. merged_trays.append(merged_tray)
  1548. else:
  1549. merged_trays.append(new_tray)
  1550. # Update ams_unit with merged trays
  1551. ams_unit = {**ams_unit, "tray": merged_trays}
  1552. elif existing_unit:
  1553. # Partial update without tray data: merge new fields into existing
  1554. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  1555. ams_unit = {**existing_unit, **ams_unit}
  1556. existing_by_id[ams_id] = ams_unit
  1557. # Convert back to list, sorted by ID for consistent ordering
  1558. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  1559. # Check tray_exist_bits to clear empty slots (Issue #147)
  1560. # New AMS models don't send empty tray data - they just update tray_exist_bits
  1561. # Each bit in tray_exist_bits represents a slot: bit=0 means empty, bit=1 means has spool
  1562. # Skip when power_on_flag=False: printer shutdown sends all-zero bits which would
  1563. # wipe all slot data and cause auto-unlink to remove spool assignments (#765)
  1564. tray_exist_bits_str = ams_data.get("tray_exist_bits") if isinstance(ams_data, dict) else None
  1565. power_on = ams_data.get("power_on_flag", True) if isinstance(ams_data, dict) else True
  1566. if tray_exist_bits_str and power_on:
  1567. try:
  1568. tray_exist_bits = int(tray_exist_bits_str, 16)
  1569. for ams_unit in merged_ams:
  1570. ams_id_raw = ams_unit.get("id")
  1571. if ams_id_raw is None:
  1572. continue
  1573. # Convert to int (may be string from JSON)
  1574. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  1575. if ams_id >= 128: # Skip HT AMS (id >= 128)
  1576. continue
  1577. # Bits for this AMS unit: bits (ams_id*4) to (ams_id*4 + 3)
  1578. for tray in ams_unit.get("tray", []):
  1579. tray_id_raw = tray.get("id")
  1580. if tray_id_raw is None:
  1581. continue
  1582. # Convert to int (may be string from JSON)
  1583. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  1584. global_bit = ams_id * 4 + tray_id
  1585. slot_exists = (tray_exist_bits >> global_bit) & 1
  1586. if not slot_exists and tray.get("tray_type"):
  1587. # Slot is marked empty but has data - clear it
  1588. logger.debug(
  1589. f"[{self.serial_number}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  1590. f"(tray_exist_bits bit {global_bit} = 0)"
  1591. )
  1592. tray["tray_type"] = ""
  1593. tray["tray_sub_brands"] = ""
  1594. tray["tray_color"] = ""
  1595. tray["tray_id_name"] = ""
  1596. tray["tag_uid"] = "0000000000000000"
  1597. tray["tray_uuid"] = "00000000000000000000000000000000"
  1598. tray["tray_info_idx"] = ""
  1599. tray["remain"] = 0
  1600. except (ValueError, TypeError) as e:
  1601. logger.debug("[%s] Could not parse tray_exist_bits: %s", self.serial_number, e)
  1602. self.state.raw_data["ams"] = merged_ams
  1603. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  1604. self._apply_ams_version_cache(merged_ams)
  1605. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  1606. self.state.last_ams_update = time.time()
  1607. logger.debug("[%s] Merged AMS data: %s new units, %s total", self.serial_number, len(ams_list), len(merged_ams))
  1608. # Extract ams_extruder_map from each AMS unit's info field
  1609. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  1610. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  1611. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  1612. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  1613. # extruder_id: 0=right/main, 1=left/deputy, 0xE=uninitialized (skip)
  1614. #
  1615. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  1616. # the full map. Merge into existing map to preserve entries from prior updates.
  1617. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  1618. for ams_unit in merged_ams:
  1619. ams_id = ams_unit.get("id")
  1620. info = ams_unit.get("info")
  1621. if ams_id is not None and info is not None:
  1622. try:
  1623. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  1624. info_val = int(str(info), 16)
  1625. # Extract 4 bits starting at bit 8 for extruder assignment
  1626. extruder_id = (info_val >> 8) & 0xF
  1627. if extruder_id == 0xE:
  1628. # 0xE = uninitialized AMS, skip
  1629. continue
  1630. ams_extruder_map[str(ams_id)] = extruder_id
  1631. logger.debug(f"[{self.serial_number}] AMS {ams_id} info=0x{info} -> extruder {extruder_id}")
  1632. except (ValueError, TypeError):
  1633. pass # Skip AMS units with unparseable info bitmask values
  1634. if ams_extruder_map:
  1635. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  1636. self.state.ams_extruder_map = ams_extruder_map
  1637. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  1638. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  1639. # BambuStudio DevFilaSystem.cpp parses info bits:
  1640. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  1641. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  1642. for ams_unit in merged_ams:
  1643. info = ams_unit.get("info")
  1644. if info is not None:
  1645. try:
  1646. info_val = int(str(info), 16)
  1647. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  1648. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  1649. except (ValueError, TypeError):
  1650. pass # Skip unparseable info values
  1651. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  1652. if "dry_sf_reason" in ams_unit:
  1653. sf_reason = ams_unit["dry_sf_reason"]
  1654. if isinstance(sf_reason, list):
  1655. ams_unit["dry_sf_reason"] = [
  1656. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  1657. ]
  1658. else:
  1659. ams_unit["dry_sf_reason"] = []
  1660. # Persist updated drying fields back to raw_data
  1661. self.state.raw_data["ams"] = merged_ams
  1662. # Create a hash of relevant AMS data to detect changes
  1663. ams_hash_data = []
  1664. for ams_unit in ams_list:
  1665. for tray in ams_unit.get("tray", []):
  1666. # Include fields that matter for filament tracking
  1667. ams_hash_data.append(
  1668. f"{ams_unit.get('id')}:{tray.get('id')}:"
  1669. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  1670. )
  1671. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  1672. # Only trigger callback if AMS data actually changed
  1673. if ams_hash != self._previous_ams_hash:
  1674. self._previous_ams_hash = ams_hash
  1675. if self.on_ams_change:
  1676. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  1677. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  1678. # may lack fields like 'remain' that the merged state preserves
  1679. self.on_ams_change(merged_ams)
  1680. def _update_state(self, data: dict):
  1681. """Update printer state from message data."""
  1682. _previous_state = self.state.state
  1683. # Update state fields
  1684. if "gcode_state" in data:
  1685. self.state.state = data["gcode_state"]
  1686. if "gcode_file" in data:
  1687. self.state.gcode_file = data["gcode_file"]
  1688. self.state.current_print = data["gcode_file"]
  1689. if "subtask_name" in data:
  1690. self.state.subtask_name = data["subtask_name"]
  1691. # Prefer subtask_name as current_print if available
  1692. if data["subtask_name"]:
  1693. self.state.current_print = data["subtask_name"]
  1694. if "subtask_id" in data:
  1695. self.state.subtask_id = data["subtask_id"]
  1696. if "mc_percent" in data:
  1697. # Save last non-zero progress for usage tracking (firmware resets to 0 on cancel)
  1698. if self.state.progress > 0:
  1699. self._last_valid_progress = self.state.progress
  1700. self.state.progress = float(data["mc_percent"])
  1701. if "mc_remaining_time" in data:
  1702. self.state.remaining_time = int(data["mc_remaining_time"])
  1703. if "mc_print_sub_stage" in data:
  1704. new_sub_stage = int(data["mc_print_sub_stage"])
  1705. if new_sub_stage != self.state.mc_print_sub_stage:
  1706. logger.debug(
  1707. f"[{self.serial_number}] mc_print_sub_stage changed: "
  1708. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  1709. )
  1710. self.state.mc_print_sub_stage = new_sub_stage
  1711. if "layer_num" in data:
  1712. new_layer = int(data["layer_num"])
  1713. old_layer = self.state.layer_num
  1714. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  1715. if old_layer > 0:
  1716. self._last_valid_layer_num = old_layer
  1717. self.state.layer_num = new_layer
  1718. # Trigger layer change callback if layer increased
  1719. if new_layer > old_layer and self.on_layer_change:
  1720. self.on_layer_change(new_layer)
  1721. if "total_layer_num" in data:
  1722. self.state.total_layers = int(data["total_layer_num"])
  1723. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  1724. # Convert to 0-100 percentage for display
  1725. def parse_fan_speed(value: str | int | None) -> int | None:
  1726. if value is None:
  1727. return None
  1728. try:
  1729. speed = int(value)
  1730. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  1731. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  1732. if speed <= 15:
  1733. return round(speed * 100 / 15)
  1734. # If already a percentage (0-255 scale from some printers), convert
  1735. elif speed <= 255:
  1736. return round(speed * 100 / 255)
  1737. return speed
  1738. except (ValueError, TypeError):
  1739. return None
  1740. # Log fan fields once for debugging
  1741. if not hasattr(self, "_fan_fields_logged"):
  1742. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  1743. if fan_fields:
  1744. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  1745. self._fan_fields_logged = True
  1746. if "cooling_fan_speed" in data:
  1747. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  1748. if "big_fan1_speed" in data:
  1749. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  1750. if "big_fan2_speed" in data:
  1751. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  1752. if "heatbreak_fan_speed" in data:
  1753. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  1754. # Calibration stage tracking
  1755. if "stg_cur" in data:
  1756. new_stg = data["stg_cur"]
  1757. # Always log ANY stg_cur change for debugging filament operations
  1758. if new_stg != self.state.stg_cur:
  1759. logger.debug(
  1760. f"[{self.serial_number}] stg_cur changed: {self.state.stg_cur} -> {new_stg} ({get_stage_name(new_stg)})"
  1761. )
  1762. self.state.stg_cur = new_stg
  1763. if "stg" in data:
  1764. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  1765. # Temperature data
  1766. temps = {}
  1767. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  1768. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  1769. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  1770. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  1771. # Log ALL keys in print data for H2D temperature discovery
  1772. all_keys = sorted(data.keys())
  1773. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  1774. self._temp_fields_logged = True
  1775. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  1776. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  1777. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  1778. self._vir_slot_logged = True
  1779. # Log nozzle hardware info fields (once)
  1780. nozzle_fields = {
  1781. k: v
  1782. for k, v in data.items()
  1783. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  1784. }
  1785. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  1786. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  1787. self._nozzle_fields_logged = True
  1788. # Parse active extruder from device.extruder.state bit 8
  1789. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  1790. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  1791. if "device" in data and isinstance(data.get("device"), dict):
  1792. device = data["device"]
  1793. if "extruder" in device and "state" in device["extruder"]:
  1794. state_val = device["extruder"]["state"]
  1795. # Extract bit 8 for extruder position
  1796. new_extruder = (state_val >> 8) & 0x1
  1797. if new_extruder != self.state.active_extruder:
  1798. logger.debug(
  1799. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  1800. )
  1801. self.state.active_extruder = new_extruder
  1802. # Log device.extruder structure for active extruder
  1803. if "device" in data and isinstance(data.get("device"), dict):
  1804. device = data["device"]
  1805. if "extruder" in device:
  1806. ext_data = device["extruder"]
  1807. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  1808. if "state" in ext_data:
  1809. state_val = ext_data["state"]
  1810. # Extract bits 12-14 (3 bits) for switch state
  1811. switch_state = (state_val >> 12) & 0x7
  1812. logger.debug(
  1813. f"[{self.serial_number}] device.extruder.state={state_val} (switch_state bits 12-14: {switch_state})"
  1814. )
  1815. # Log 'cur' field if present (might indicate current/active extruder)
  1816. if "cur" in ext_data:
  1817. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  1818. # Filament Track Switch (FTS) detection — #1162. Presence of
  1819. # device.fila_switch in MQTT means the FTS accessory is installed.
  1820. if "device" in data and isinstance(data.get("device"), dict):
  1821. fs_data = data["device"].get("fila_switch")
  1822. if isinstance(fs_data, dict):
  1823. in_raw = fs_data.get("in")
  1824. out_raw = fs_data.get("out")
  1825. self.state.fila_switch = FilaSwitchState(
  1826. installed=True,
  1827. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  1828. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  1829. stat=int(fs_data.get("stat", 0) or 0),
  1830. info=int(fs_data.get("info", 0) or 0),
  1831. )
  1832. if "bed_temper" in data:
  1833. temps["bed"] = float(data["bed_temper"])
  1834. if "bed_target_temper" in data:
  1835. temps["bed_target"] = float(data["bed_target_temper"])
  1836. # Check if this is H2D (has device.extruder.info with 2 extruders)
  1837. has_h2d_extruder_info = (
  1838. "device" in data
  1839. and isinstance(data.get("device"), dict)
  1840. and "extruder" in data["device"]
  1841. and isinstance(data["device"]["extruder"].get("info"), list)
  1842. and len(data["device"]["extruder"]["info"]) >= 2
  1843. )
  1844. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  1845. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  1846. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  1847. if "nozzle_temper" in data:
  1848. if has_h2d_extruder_info:
  1849. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  1850. else:
  1851. temps["nozzle"] = float(data["nozzle_temper"])
  1852. if "nozzle_target_temper" in data:
  1853. if has_h2d_extruder_info:
  1854. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  1855. else:
  1856. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  1857. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  1858. if not has_h2d_extruder_info:
  1859. # Try multiple possible field names used by different firmware versions
  1860. if "nozzle_temper_2" in data:
  1861. val = float(data["nozzle_temper_2"])
  1862. if -50 < val < 500: # Valid temp range
  1863. temps["nozzle_2"] = val
  1864. else:
  1865. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  1866. elif "right_nozzle_temper" in data:
  1867. val = float(data["right_nozzle_temper"])
  1868. if -50 < val < 500: # Valid temp range
  1869. temps["nozzle_2"] = val
  1870. else:
  1871. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  1872. if "nozzle_target_temper_2" in data:
  1873. val = float(data["nozzle_target_temper_2"])
  1874. if 0 <= val < 500: # Valid temp range
  1875. temps["nozzle_2_target"] = val
  1876. else:
  1877. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  1878. elif "right_nozzle_target_temper" in data:
  1879. val = float(data["right_nozzle_target_temper"])
  1880. if 0 <= val < 500: # Valid temp range
  1881. temps["nozzle_2_target"] = val
  1882. else:
  1883. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  1884. # Also check for left nozzle as primary (some H2 models)
  1885. if "left_nozzle_temper" in data and "nozzle" not in temps:
  1886. temps["nozzle"] = float(data["left_nozzle_temper"])
  1887. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  1888. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  1889. if "chamber_temper" in data:
  1890. chamber_val = float(data["chamber_temper"])
  1891. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  1892. # Check if we recently set the target locally (within 5 seconds)
  1893. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  1894. respect_local = (time.time() - local_set_time) < 5.0
  1895. # H2D protocol: chamber_temper encoding indicates heater state
  1896. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  1897. # - When < 500: direct Celsius current temp only - heater is OFF
  1898. if -50 < chamber_val < 100:
  1899. # Direct value = heater is OFF
  1900. temps["chamber"] = chamber_val
  1901. if not respect_local:
  1902. temps["chamber_target"] = 0.0 # Heater off means target = 0
  1903. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  1904. else:
  1905. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  1906. # Try to decode if it looks like an encoded value
  1907. if chamber_val > 500:
  1908. mqtt_target = int(chamber_val) // 65536
  1909. current = int(chamber_val) % 65536
  1910. logger.debug(
  1911. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  1912. )
  1913. if -50 < current < 100:
  1914. temps["chamber"] = float(current)
  1915. # Store decoded target for later use, but DON'T set chamber_heating here!
  1916. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  1917. # which is the authoritative source the slicer uses.
  1918. if not respect_local:
  1919. if 0 <= mqtt_target <= 60:
  1920. # Store as "decoded" target - may be overridden by explicit target fields
  1921. temps["_chamber_decoded_target"] = float(mqtt_target)
  1922. # Chamber target temperature (set by print file or display)
  1923. if "mc_target_cham" in data:
  1924. mc_target = float(data["mc_target_cham"])
  1925. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  1926. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  1927. if 0 <= mc_target <= 60:
  1928. temps["chamber_target"] = mc_target
  1929. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  1930. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  1931. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  1932. try:
  1933. if "info" in data and isinstance(data["info"], dict):
  1934. info_temp = data["info"].get("temp")
  1935. if info_temp is not None and "chamber" not in temps:
  1936. # Check for encoded value (target * 65536 + current)
  1937. if info_temp > 500:
  1938. # Decode: extract current temperature and target
  1939. target = info_temp // 65536
  1940. current = info_temp % 65536
  1941. temps["chamber"] = float(current)
  1942. # Store decoded target as fallback (may be overridden by ctc.info.target)
  1943. if "_chamber_decoded_target" not in temps:
  1944. temps["_chamber_decoded_target"] = float(target)
  1945. logger.debug(
  1946. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  1947. )
  1948. elif -50 < info_temp < 100:
  1949. # Valid direct temperature - heater is OFF
  1950. temps["chamber"] = float(info_temp)
  1951. temps["chamber_target"] = 0.0 # Direct value means heater off
  1952. logger.debug("[%s] info.temp direct: %s°C (heater OFF)", self.serial_number, info_temp)
  1953. # H2D series: Dual extruder temps are in device.extruder.info array
  1954. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  1955. if "device" in data and isinstance(data["device"], dict):
  1956. device = data["device"]
  1957. # Parse dual extruder temperatures
  1958. extruder_data = device.get("extruder", {})
  1959. extruder_info = extruder_data.get("info", [])
  1960. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  1961. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  1962. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  1963. # has_h2d_extruder_info requires len(extruder_info) >= 2
  1964. if has_h2d_extruder_info:
  1965. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  1966. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  1967. if "temp" in extruder_info[0]:
  1968. temp_val = extruder_info[0]["temp"]
  1969. if temp_val > 500:
  1970. # Encoded format: temp = target * 65536 + current
  1971. target = temp_val // 65536
  1972. current = temp_val % 65536
  1973. if -50 < current < 500:
  1974. temps["nozzle_2"] = float(current)
  1975. if 0 < target < 500:
  1976. temps["nozzle_2_target"] = float(target)
  1977. temps["nozzle_2_heating"] = target > 0 and current < target
  1978. elif -50 < temp_val < 500:
  1979. # Direct Celsius value = heater is OFF
  1980. temps["nozzle_2"] = float(temp_val)
  1981. temps["nozzle_2_target"] = 0.0
  1982. temps["nozzle_2_heating"] = False
  1983. # Left nozzle (extruder 1) - only for dual nozzle printers
  1984. # H2D protocol: temp field encoding depends on value
  1985. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  1986. # - When < 500: direct Celsius current temp only - heater is OFF
  1987. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  1988. ext1 = extruder_info[1]
  1989. temp_val = ext1["temp"]
  1990. # Check if we recently set the target locally (within 5 seconds)
  1991. # If so, don't let MQTT data overwrite it
  1992. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  1993. respect_local_target = (time.time() - local_set_time) < 5.0
  1994. if temp_val > 500:
  1995. # Encoded format: temp = target * 65536 + current
  1996. target = temp_val // 65536
  1997. current = temp_val % 65536
  1998. if 0 < target < 500 and not respect_local_target:
  1999. temps["nozzle_target"] = float(target)
  2000. if -50 < current < 500:
  2001. temps["nozzle"] = float(current)
  2002. # Heating = encoded AND we're using the MQTT target (not local override)
  2003. # If local target is being respected, use local target to determine heating
  2004. if respect_local_target:
  2005. local_target = self.state.temperatures.get("nozzle_target", 0)
  2006. temps["nozzle_heating"] = local_target > 0 and current < local_target
  2007. else:
  2008. temps["nozzle_heating"] = target > 0 and current < target
  2009. elif -50 < temp_val < 500:
  2010. # Direct Celsius = heater is OFF (or at target with heater off)
  2011. temps["nozzle"] = float(temp_val)
  2012. if not respect_local_target:
  2013. temps["nozzle_target"] = 0.0
  2014. temps["nozzle_heating"] = False # Direct = not heating
  2015. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  2016. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  2017. if has_h2d_extruder_info:
  2018. for ext_info in extruder_info:
  2019. ext_id = ext_info.get("id")
  2020. snow = ext_info.get("snow")
  2021. if ext_id is not None and snow is not None and ext_id <= 1:
  2022. # Normalize H2D snow value to global tray ID
  2023. ams_id = snow >> 8
  2024. slot = snow & 0xFF
  2025. if 0 <= ams_id <= 3:
  2026. # Regular AMS slot
  2027. global_tray = ams_id * 4 + (slot & 0x03)
  2028. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2029. if old_val != global_tray:
  2030. logger.debug(
  2031. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2032. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  2033. )
  2034. self.state.h2d_extruder_snow[ext_id] = global_tray
  2035. elif ams_id == 254 or ams_id == 255:
  2036. # External spool or unloaded
  2037. normalized = 254 if slot != 255 else 255
  2038. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2039. if old_val != normalized:
  2040. logger.debug(
  2041. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2042. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  2043. )
  2044. self.state.h2d_extruder_snow[ext_id] = normalized
  2045. elif 128 <= ams_id <= 135:
  2046. # External spool with hub mapping
  2047. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2048. if old_val != ams_id:
  2049. logger.debug(
  2050. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2051. f"raw={snow} -> external hub {ams_id}"
  2052. )
  2053. self.state.h2d_extruder_snow[ext_id] = ams_id
  2054. # Parse bed heating state from device.bed.info.temp encoding
  2055. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  2056. bed_data = device.get("bed", {})
  2057. bed_info = bed_data.get("info", {})
  2058. if "temp" in bed_info:
  2059. temp_val = bed_info["temp"]
  2060. if temp_val > 500:
  2061. target = temp_val // 65536
  2062. current = temp_val % 65536
  2063. temps["bed_heating"] = target > 0 and current < target
  2064. else:
  2065. temps["bed_heating"] = False
  2066. # Parse chamber temp from device.ctc.info.temp if not already set
  2067. ctc_data = device.get("ctc", {})
  2068. ctc_info = ctc_data.get("info", {})
  2069. # Parse airduct mode (0=cooling, 1=heating)
  2070. airduct_data = device.get("airduct", {})
  2071. if "modeCur" in airduct_data:
  2072. new_mode = airduct_data["modeCur"]
  2073. if new_mode != self.state.airduct_mode:
  2074. logger.debug(
  2075. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  2076. )
  2077. self.state.airduct_mode = new_mode
  2078. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  2079. # Check if we recently set the target locally (within 5 seconds)
  2080. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2081. respect_local_target = (time.time() - local_set_time) < 5.0
  2082. # Log ctc_info contents for debugging
  2083. if ctc_info:
  2084. logger.debug("[%s] ctc_info keys: %s", self.serial_number, list(ctc_info.keys()))
  2085. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  2086. # (what the slicer shows). This OVERRIDES any previously decoded target.
  2087. explicit_target = None
  2088. if "target" in ctc_info:
  2089. target_val = ctc_info["target"]
  2090. logger.debug(
  2091. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  2092. )
  2093. # Filter out invalid values (valid chamber target is 0-60°C)
  2094. if 0 <= target_val <= 60 and not respect_local_target:
  2095. explicit_target = float(target_val)
  2096. temps["chamber_target"] = explicit_target # Override any previous value
  2097. logger.debug(
  2098. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  2099. )
  2100. # Parse chamber temp from ctc.info.temp - may be encoded
  2101. if "temp" in ctc_info and "chamber" not in temps:
  2102. temp_val = ctc_info["temp"]
  2103. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  2104. if temp_val > 500:
  2105. # Encoded value: decode target and current
  2106. decoded_target = temp_val // 65536
  2107. current = temp_val % 65536
  2108. temps["chamber"] = float(current)
  2109. logger.debug(
  2110. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  2111. )
  2112. # Determine which target to use for heating state:
  2113. # Priority: local target > explicit target > decoded target
  2114. if respect_local_target:
  2115. local_target = self.state.temperatures.get("chamber_target", 0)
  2116. temps["chamber_heating"] = local_target > 0 and current < local_target
  2117. elif explicit_target is not None:
  2118. # Use explicit ctc.info.target - this is what slicer sees
  2119. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  2120. else:
  2121. # Fallback to decoded target only if no explicit target available
  2122. if not respect_local_target and "chamber_target" not in temps:
  2123. temps["chamber_target"] = float(decoded_target)
  2124. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  2125. else:
  2126. # Direct value (not encoded) - heater is OFF
  2127. temps["chamber"] = float(temp_val)
  2128. temps["chamber_heating"] = False
  2129. except Exception as e:
  2130. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  2131. if temps:
  2132. # Handle chamber_target: prefer explicit over decoded
  2133. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  2134. # No explicit target available, use decoded target from chamber_temper
  2135. temps["chamber_target"] = temps["_chamber_decoded_target"]
  2136. # Remove internal temp key before merging
  2137. temps.pop("_chamber_decoded_target", None)
  2138. # Merge new temps into existing, preserving valid values when new ones are filtered out
  2139. for key, value in temps.items():
  2140. self.state.temperatures[key] = value
  2141. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  2142. if "bed" in temps and self.on_bed_temp_update:
  2143. self.on_bed_temp_update(temps["bed"])
  2144. # Calculate chamber_heating after all targets are known
  2145. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  2146. if "chamber" in temps and "chamber_heating" not in temps:
  2147. current = self.state.temperatures.get("chamber", 0)
  2148. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2149. respect_local = (time.time() - local_set_time) < 5.0
  2150. if respect_local:
  2151. # Use locally-set target
  2152. target = self.state.temperatures.get("chamber_target", 0)
  2153. else:
  2154. # Use explicit/decoded target from MQTT
  2155. target = self.state.temperatures.get("chamber_target", 0)
  2156. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  2157. logger.debug(
  2158. f"[{self.serial_number}] Chamber heating calculated: target={target}, current={current}, heating={self.state.temperatures['chamber_heating']}, respect_local={respect_local}"
  2159. )
  2160. # Debug: log chamber value if it was updated
  2161. if "chamber" in temps:
  2162. logger.debug(
  2163. 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')}"
  2164. )
  2165. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  2166. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  2167. if "nozzle" in temps and "nozzle_heating" not in temps:
  2168. current = self.state.temperatures.get("nozzle", 0)
  2169. target = self.state.temperatures.get("nozzle_target", 0)
  2170. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  2171. # Parse HMS (Health Management System) errors
  2172. if "hms" in data:
  2173. hms_list = data["hms"]
  2174. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  2175. self.state.hms_errors = []
  2176. if isinstance(hms_list, list):
  2177. for hms in hms_list:
  2178. if isinstance(hms, dict):
  2179. # HMS format: {"attr": attribute_code, "code": error_code}
  2180. # attr contains module/severity info, code contains error number
  2181. # Both are needed to construct the wiki URL
  2182. attr = hms.get("attr", 0)
  2183. code = hms.get("code", 0)
  2184. if isinstance(attr, str):
  2185. attr = int(attr.replace("0x", ""), 16) if attr else 0
  2186. if isinstance(code, str):
  2187. code = int(code.replace("0x", ""), 16) if code else 0
  2188. # Severity is in attr byte 1 (bits 8-15)
  2189. severity = (attr >> 8) & 0xF
  2190. # Module is in attr byte 3 (bits 24-31)
  2191. module = (attr >> 24) & 0xFF
  2192. # Skip non-error status codes — all real HMS errors
  2193. # have code >= 0x4000. Lower values are status/phase
  2194. # indicators that some firmware sends during normal printing.
  2195. if code < 0x4000:
  2196. continue
  2197. # Skip user-action echoes — the printer firmware emits these
  2198. # as part of normal user-cancel sequences. They're not faults
  2199. # and shouldn't count toward "X problem" badges or surface as
  2200. # red pips on the printer card. Backend's notification path
  2201. # already suppresses 0500_400E for the same reason.
  2202. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  2203. if short_code in _HMS_USER_ACTION_CODES:
  2204. continue
  2205. self.state.hms_errors.append(
  2206. HMSError(
  2207. code=f"0x{code:x}" if code else "0x0",
  2208. attr=attr,
  2209. module=module,
  2210. severity=severity if severity > 0 else 2,
  2211. )
  2212. )
  2213. # Parse print_error - this is a different error format than HMS
  2214. # print_error is a 32-bit integer where:
  2215. # - High 16 bits contain module info (e.g., 0x0500)
  2216. # - Low 16 bits contain error code (e.g., 0x8061)
  2217. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  2218. if "print_error" in data:
  2219. print_error = data["print_error"]
  2220. if print_error and print_error != 0:
  2221. # Extract components: MMMMEEEE -> MMMM_EEEE
  2222. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  2223. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  2224. # Values below 0x4000 are status/phase indicators, not real errors.
  2225. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  2226. # Some firmware sends low values like 0x0002 during normal printing.
  2227. if error < 0x4000:
  2228. pass # Skip — not a real error
  2229. else:
  2230. # Store in a format that matches the community error database
  2231. # attr stores the full 32-bit value for reconstruction
  2232. # code stores the short format string for lookup
  2233. short_code = f"{module:04X}_{error:04X}"
  2234. logger.debug(
  2235. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  2236. )
  2237. # Same user-action filter as the hms[] branch above — print_error
  2238. # carries the same cancel echoes (e.g. 0500_400E) and they must
  2239. # not surface as faults on the printer card.
  2240. if short_code in _HMS_USER_ACTION_CODES:
  2241. pass # cancel echo — silently drop
  2242. else:
  2243. # Only add if not already in HMS errors (avoid duplicates)
  2244. existing_short_codes = set()
  2245. for e in self.state.hms_errors:
  2246. # Extract short code from existing errors
  2247. e_module = (e.attr >> 16) & 0xFFFF
  2248. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  2249. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  2250. if short_code not in existing_short_codes:
  2251. self.state.hms_errors.append(
  2252. HMSError(
  2253. code=f"0x{error:x}",
  2254. attr=print_error, # Store full value for display
  2255. module=module >> 8, # High byte of module (e.g., 0x05)
  2256. severity=3, # Warning level for print_error
  2257. )
  2258. )
  2259. # Parse home_flag first so SD-card detection below can prefer it.
  2260. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  2261. # bit 23 = door-open (X1 family only).
  2262. home_flag = None
  2263. if "home_flag" in data:
  2264. home_flag = data["home_flag"]
  2265. if home_flag < 0:
  2266. home_flag = home_flag & 0xFFFFFFFF
  2267. # SD card presence: the only remaining consumer is the firmware-update
  2268. # precondition check (firmware_update.py). Use the top-level `sdcard`
  2269. # field when present with a permissive truthy check covering the
  2270. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  2271. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  2272. # when a card is inserted, which caused the badge to flap before the
  2273. # badge was removed entirely.
  2274. if "sdcard" in data:
  2275. raw_sdcard = data["sdcard"]
  2276. if isinstance(raw_sdcard, str):
  2277. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  2278. else:
  2279. self.state.sdcard = bool(raw_sdcard)
  2280. if home_flag is not None:
  2281. store_to_sdcard = bool((home_flag >> 11) & 1)
  2282. if store_to_sdcard != self.state.store_to_sdcard:
  2283. logger.debug(
  2284. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  2285. )
  2286. self.state.store_to_sdcard = store_to_sdcard
  2287. # Door open detection — source depends on printer family:
  2288. # X1 series (X1, X1C, X1E): home_flag bit 23
  2289. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  2290. # Both share the same bitmask (0x00800000) but live in different fields.
  2291. model_upper = (self.model or "").upper().strip()
  2292. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  2293. if is_x1_family and home_flag is not None:
  2294. door_open = (home_flag & 0x00800000) != 0
  2295. if door_open != self.state.door_open:
  2296. logger.debug(
  2297. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  2298. self.serial_number,
  2299. self.state.door_open,
  2300. door_open,
  2301. home_flag,
  2302. )
  2303. self.state.door_open = door_open
  2304. elif not is_x1_family and "stat" in data:
  2305. try:
  2306. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  2307. door_open = (stat_value & 0x00800000) != 0
  2308. if door_open != self.state.door_open:
  2309. logger.debug(
  2310. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  2311. self.serial_number,
  2312. self.state.door_open,
  2313. door_open,
  2314. stat_value,
  2315. )
  2316. self.state.door_open = door_open
  2317. except (ValueError, TypeError):
  2318. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  2319. # Parse timelapse status (recording active during print)
  2320. if "timelapse" in data:
  2321. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  2322. self.state.timelapse = data["timelapse"] is True
  2323. # Track if timelapse was ever active during this print
  2324. if self.state.timelapse and self._was_running:
  2325. self._timelapse_during_print = True
  2326. # Parse ipcam/live view status
  2327. if "ipcam" in data:
  2328. ipcam_data = data["ipcam"]
  2329. logger.debug("[%s] ipcam field: %s", self.serial_number, ipcam_data)
  2330. if isinstance(ipcam_data, dict):
  2331. # Check ipcam_record field for live view status
  2332. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  2333. # Check timelapse field (H2D sends it here, not in xcam)
  2334. if "timelapse" in ipcam_data:
  2335. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  2336. if timelapse_enabled != self.state.timelapse:
  2337. logger.debug(
  2338. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  2339. )
  2340. self.state.timelapse = timelapse_enabled
  2341. # Track if timelapse was ever active during this print
  2342. if self.state.timelapse and self._was_running:
  2343. self._timelapse_during_print = True
  2344. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  2345. else:
  2346. self.state.ipcam = ipcam_data is True
  2347. # Parse WiFi signal strength (dBm)
  2348. if "wifi_signal" in data:
  2349. wifi_signal = data["wifi_signal"]
  2350. logger.debug("[%s] wifi_signal received: %s", self.serial_number, wifi_signal)
  2351. if isinstance(wifi_signal, (int, float)):
  2352. self.state.wifi_signal = int(wifi_signal)
  2353. elif isinstance(wifi_signal, str):
  2354. # Handle string format like "-52dBm"
  2355. try:
  2356. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2357. except ValueError:
  2358. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2359. # Detect ethernet connection: printers on ethernet with WiFi disabled
  2360. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  2361. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  2362. from backend.app.utils.printer_models import has_ethernet
  2363. if has_ethernet(self.model):
  2364. self.state.wired_network = self.state.wifi_signal == -90
  2365. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  2366. if "spd_lvl" in data:
  2367. new_speed = data["spd_lvl"]
  2368. if new_speed != self.state.speed_level:
  2369. logger.debug(
  2370. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  2371. )
  2372. self.state.speed_level = new_speed
  2373. # Parse skipped objects from printer status (s_obj field)
  2374. # This allows us to restore skipped objects state after reconnection
  2375. if "s_obj" in data:
  2376. s_obj = data["s_obj"]
  2377. if isinstance(s_obj, list):
  2378. # Update skipped objects from printer's list
  2379. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  2380. if new_skipped != self.state.skipped_objects:
  2381. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  2382. self.state.skipped_objects = new_skipped
  2383. # Parse chamber light status from lights_report
  2384. if "lights_report" in data:
  2385. lights = data["lights_report"]
  2386. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  2387. if isinstance(lights, list):
  2388. for light in lights:
  2389. if isinstance(light, dict) and light.get("node") == "chamber_light":
  2390. new_light_state = light.get("mode") == "on"
  2391. if new_light_state != self.state.chamber_light:
  2392. logger.debug(
  2393. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  2394. )
  2395. self.state.chamber_light = new_light_state
  2396. break
  2397. # Parse nozzle hardware info (single nozzle printers)
  2398. if "nozzle_type" in data:
  2399. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  2400. if "nozzle_diameter" in data:
  2401. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  2402. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  2403. # Left nozzle
  2404. if "left_nozzle_type" in data:
  2405. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  2406. if "left_nozzle_diameter" in data:
  2407. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  2408. # Right nozzle
  2409. if "right_nozzle_type" in data:
  2410. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  2411. if "right_nozzle_diameter" in data:
  2412. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  2413. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  2414. if "nozzle_type_2" in data:
  2415. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  2416. if "nozzle_diameter_2" in data:
  2417. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  2418. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  2419. if "device" in data and isinstance(data["device"], dict):
  2420. device = data["device"]
  2421. nozzle_data = device.get("nozzle", {})
  2422. nozzle_info = nozzle_data.get("info", [])
  2423. if isinstance(nozzle_info, list):
  2424. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  2425. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  2426. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  2427. # for hover cards on both the L/R indicator and the nozzle rack card.
  2428. if nozzle_info:
  2429. self.state.nozzle_rack = sorted(
  2430. [
  2431. {
  2432. "id": n.get("id", i),
  2433. "type": str(n.get("type", "")),
  2434. "diameter": str(n.get("diameter", "")),
  2435. "wear": n.get("wear"),
  2436. "stat": n.get("stat"),
  2437. # H2C uses "tm", H2D uses "max_temp"
  2438. "max_temp": n.get("max_temp") or n.get("tm", 0),
  2439. # H2C uses "sn", H2D uses "serial_number"
  2440. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  2441. # H2C uses "color_m", H2D uses "filament_colour"
  2442. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  2443. # H2C uses "fila_id", H2D uses "filament_id"
  2444. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  2445. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  2446. }
  2447. for i, n in enumerate(nozzle_info)
  2448. ],
  2449. key=lambda x: x["id"],
  2450. )
  2451. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  2452. self._nozzle_rack_logged = True
  2453. logger.debug(
  2454. "[%s] Nozzle info: %d entries, IDs: %s",
  2455. self.serial_number,
  2456. len(nozzle_info),
  2457. [n.get("id") for n in nozzle_info],
  2458. )
  2459. for nozzle in nozzle_info:
  2460. idx = nozzle.get("id", 0)
  2461. if idx < len(self.state.nozzles):
  2462. if "type" in nozzle and nozzle["type"]:
  2463. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  2464. if "diameter" in nozzle:
  2465. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  2466. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  2467. # (these fields aren't sent in every MQTT push, only when changed)
  2468. ams_data = self.state.raw_data.get("ams")
  2469. vt_tray_data = self.state.raw_data.get("vt_tray")
  2470. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  2471. mapping_data = self.state.raw_data.get("mapping")
  2472. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  2473. # as a dict but consumers expect a list. Without this, the dev mode probe
  2474. # below can release the GIL (via publish), letting the event-loop thread
  2475. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  2476. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  2477. data["vt_tray"] = [data["vt_tray"]]
  2478. self.state.raw_data = data
  2479. # Restore preserved fields BEFORE any work that may release the GIL
  2480. # (e.g. _probe_developer_mode publishes an MQTT message).
  2481. if ams_data is not None:
  2482. self.state.raw_data["ams"] = ams_data
  2483. if vt_tray_data is not None:
  2484. self.state.raw_data["vt_tray"] = vt_tray_data
  2485. if ams_extruder_map_data is not None:
  2486. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  2487. if mapping_data is not None and "mapping" not in data:
  2488. self.state.raw_data["mapping"] = mapping_data
  2489. # Parse developer LAN mode from "fun" field
  2490. if "fun" in data:
  2491. try:
  2492. fun_val = data["fun"]
  2493. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2494. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2495. except (ValueError, TypeError):
  2496. pass
  2497. elif self.state.developer_mode is None and not self._dev_mode_probed:
  2498. # No "fun" field — A1/P1 series never send it, so we need to probe.
  2499. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  2500. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  2501. # after connect to let the MQTT session stabilize — probing too early
  2502. # can destabilize some firmware MQTT brokers (#887).
  2503. if not self._dev_mode_needs_probe and len(data) > 30:
  2504. # First full status without "fun" — mark that probe is needed
  2505. self._dev_mode_needs_probe = True
  2506. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  2507. self._probe_developer_mode()
  2508. elif self._dev_mode_needs_probe:
  2509. logger.debug(
  2510. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  2511. self.serial_number,
  2512. time.monotonic() - self._connect_time,
  2513. )
  2514. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  2515. # Probe was sent but no response yet — check for timeout.
  2516. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  2517. # may deliver status pushes but silently drop commands (#887).
  2518. elapsed = time.monotonic() - self._dev_mode_probe_time
  2519. if elapsed > 10.0:
  2520. self._dev_mode_probe_failures += 1
  2521. logger.warning(
  2522. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  2523. self.serial_number,
  2524. elapsed,
  2525. self._dev_mode_probe_failures,
  2526. )
  2527. self._dev_mode_probe_seq = None
  2528. if self._dev_mode_probe_failures >= 2:
  2529. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  2530. else:
  2531. # Allow retry on next full status message
  2532. self._dev_mode_probed = False
  2533. # Zombie session detection: if an ams_filament_setting command has been
  2534. # pending for >10s with no response, the publish path is likely dead (#887).
  2535. if self._last_ams_cmd_time > 0:
  2536. elapsed = time.monotonic() - self._last_ams_cmd_time
  2537. if elapsed > 10.0:
  2538. self._ams_cmd_unanswered += 1
  2539. logger.warning(
  2540. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  2541. self.serial_number,
  2542. elapsed,
  2543. self._ams_cmd_unanswered,
  2544. )
  2545. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  2546. if self._ams_cmd_unanswered >= 2:
  2547. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  2548. self._ams_cmd_unanswered = 0
  2549. # Log mapping data when received (for usage tracking debugging)
  2550. if "mapping" in data:
  2551. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  2552. # Log state transitions for debugging
  2553. if "gcode_state" in data:
  2554. logger.debug(
  2555. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  2556. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  2557. )
  2558. # Detect print start (state changes TO RUNNING with a file)
  2559. current_file = self.state.gcode_file or self.state.current_print
  2560. is_new_print = (
  2561. self.state.state == "RUNNING"
  2562. and self._previous_gcode_state != "RUNNING"
  2563. and current_file
  2564. and not self._was_running # Prevent duplicates when resuming from PAUSE
  2565. )
  2566. # Also detect if file changed while running (new print started)
  2567. is_file_change = (
  2568. self.state.state == "RUNNING"
  2569. and current_file
  2570. and current_file != self._previous_gcode_file
  2571. and self._previous_gcode_file is not None
  2572. )
  2573. # Track RUNNING state for more robust completion detection
  2574. if self.state.state == "RUNNING" and current_file:
  2575. if not self._was_running:
  2576. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  2577. # Check if timelapse was enabled in the same message (xcam parsed before this)
  2578. if self.state.timelapse:
  2579. self._timelapse_during_print = True
  2580. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  2581. self._was_running = True
  2582. self._completion_triggered = False
  2583. if is_new_print or is_file_change:
  2584. # Clear any old HMS errors when a new print starts
  2585. self.state.hms_errors = []
  2586. # Reset layer tracking for new print (needed for layer-based timelapse)
  2587. self.state.layer_num = 0
  2588. # Reset completion tracking for new print
  2589. self._was_running = True
  2590. self._completion_triggered = False
  2591. # Reset last valid progress/layer for usage tracking
  2592. self._last_valid_progress = 0.0
  2593. self._last_valid_layer_num = 0
  2594. # Clear and seed tray change log for mid-print usage splitting
  2595. self.state.tray_change_log.clear()
  2596. tn = self.state.tray_now
  2597. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  2598. self.state.tray_change_log.append((tn, 0))
  2599. # Initialize timelapse tracking based on current state
  2600. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  2601. # so self.state.timelapse may already be set from this message.
  2602. # We preserve that value instead of blindly resetting to False.
  2603. if self.state.timelapse:
  2604. self._timelapse_during_print = True
  2605. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  2606. else:
  2607. self._timelapse_during_print = False
  2608. if (is_new_print or is_file_change) and self.on_print_start:
  2609. logger.info(
  2610. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  2611. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  2612. )
  2613. self.on_print_start(
  2614. {
  2615. "filename": current_file,
  2616. "subtask_name": self.state.subtask_name,
  2617. "remaining_time": self.state.remaining_time * 60
  2618. if self.state.remaining_time > 0
  2619. else None, # Convert minutes to seconds
  2620. "raw_data": data,
  2621. "ams_mapping": self._captured_ams_mapping,
  2622. }
  2623. )
  2624. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  2625. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  2626. # This handles cases where server restarts during a print
  2627. should_trigger_completion = (
  2628. self.state.state in ("FINISH", "FAILED")
  2629. and not self._completion_triggered
  2630. and self.on_print_complete
  2631. and (
  2632. self._previous_gcode_state == "RUNNING" # Normal transition
  2633. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  2634. # Pre-print failure (#1111): printer rejected the job during setup
  2635. # — wrong nozzle size, AMS error, etc. The print never reaches
  2636. # RUNNING, so without this branch neither the RUNNING check nor
  2637. # _was_running match and the queue item stays stuck at "printing".
  2638. # Restricted to FAILED from pre-print states so a stale FAILED on
  2639. # first connection (prev=None) still can't accidentally fire.
  2640. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  2641. )
  2642. )
  2643. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  2644. if (
  2645. self.state.state == "IDLE"
  2646. and self._previous_gcode_state == "RUNNING"
  2647. and not self._completion_triggered
  2648. and self.on_print_complete
  2649. ):
  2650. should_trigger_completion = True
  2651. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  2652. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  2653. if (
  2654. not should_trigger_completion
  2655. and self.state.state in ("FINISH", "FAILED")
  2656. and self._previous_gcode_state != self.state.state
  2657. ):
  2658. logger.info(
  2659. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  2660. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  2661. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  2662. )
  2663. # Mark as triggered so state is clean for the next print cycle
  2664. self._completion_triggered = True
  2665. if should_trigger_completion:
  2666. if self.state.state == "FINISH":
  2667. status = "completed"
  2668. elif self.state.state == "FAILED":
  2669. status = "failed"
  2670. else:
  2671. status = "aborted"
  2672. logger.info(
  2673. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  2674. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  2675. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  2676. f"timelapse_during_print: {self._timelapse_during_print}"
  2677. )
  2678. timelapse_was_active = self._timelapse_during_print
  2679. self._completion_triggered = True
  2680. self._was_running = False
  2681. self._timelapse_during_print = False # Reset for next print
  2682. # Include HMS errors for failure reason detection
  2683. hms_errors_data = (
  2684. [
  2685. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  2686. for e in self.state.hms_errors
  2687. ]
  2688. if self.state.hms_errors
  2689. else []
  2690. )
  2691. self.on_print_complete(
  2692. {
  2693. "status": status,
  2694. "filename": self._previous_gcode_file or current_file,
  2695. "subtask_name": self.state.subtask_name,
  2696. "raw_data": data,
  2697. "timelapse_was_active": timelapse_was_active,
  2698. "hms_errors": hms_errors_data,
  2699. "ams_mapping": self._captured_ams_mapping,
  2700. # Last valid progress/layer before firmware reset (for partial usage tracking)
  2701. "last_progress": self._last_valid_progress,
  2702. "last_layer_num": self._last_valid_layer_num,
  2703. }
  2704. )
  2705. self._captured_ams_mapping = None
  2706. self._previous_gcode_state = self.state.state
  2707. if current_file:
  2708. self._previous_gcode_file = current_file
  2709. if self.on_state_change:
  2710. self.on_state_change(self.state)
  2711. def _request_push_all(self):
  2712. """Request full status update from printer."""
  2713. if self._client:
  2714. message = {"pushing": {"command": "pushall"}}
  2715. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  2716. def _probe_developer_mode(self):
  2717. """Probe developer mode by sending an ams_filament_setting for the external slot.
  2718. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  2719. For these, we detect developer mode by sending a harmless command and
  2720. checking whether the printer accepts or rejects it:
  2721. - result="success" → developer mode ON (commands accepted)
  2722. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  2723. The probe re-sends the current external slot configuration so it's a no-op
  2724. when the command succeeds. If there's no external slot data yet, we send a
  2725. reset (empty filament) which is also safe.
  2726. """
  2727. if not self._client or not self.state.connected:
  2728. return
  2729. self._dev_mode_probed = True
  2730. self._dev_mode_probe_time = time.monotonic()
  2731. self._sequence_id += 1
  2732. seq = str(self._sequence_id)
  2733. self._dev_mode_probe_seq = seq
  2734. # Build probe command: re-send current external slot config (no-op on success)
  2735. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  2736. current = vt_tray[0] if vt_tray else {}
  2737. command = {
  2738. "print": {
  2739. "command": "ams_filament_setting",
  2740. "ams_id": 255,
  2741. "tray_id": 0,
  2742. "slot_id": 0,
  2743. "tray_info_idx": current.get("tray_info_idx", ""),
  2744. "tray_type": current.get("tray_type", ""),
  2745. "tray_sub_brands": current.get("tray_sub_brands", ""),
  2746. "tray_color": current.get("tray_color", "00000000"),
  2747. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  2748. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  2749. "sequence_id": seq,
  2750. }
  2751. }
  2752. setting_id = current.get("setting_id")
  2753. if setting_id:
  2754. command["print"]["setting_id"] = setting_id
  2755. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  2756. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2757. def _handle_dev_mode_probe_response(self, data: dict):
  2758. """Handle response to the developer mode probe command.
  2759. Sets developer_mode based on whether the printer accepted or rejected the command.
  2760. """
  2761. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  2762. self._dev_mode_probe_failures = 0 # Reset on any response
  2763. result = data.get("result", "")
  2764. reason = data.get("reason", "")
  2765. if result == "failed" and "verify failed" in reason:
  2766. self.state.developer_mode = False
  2767. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  2768. else:
  2769. # Success or any other response — commands are accepted
  2770. self.state.developer_mode = True
  2771. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  2772. if self.on_state_change:
  2773. self.on_state_change(self.state)
  2774. def _request_version(self):
  2775. """Request firmware version info from printer."""
  2776. if self._client:
  2777. self._sequence_id += 1
  2778. message = {
  2779. "info": {
  2780. "sequence_id": str(self._sequence_id),
  2781. "command": "get_version",
  2782. }
  2783. }
  2784. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  2785. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  2786. def request_status_update(self) -> bool:
  2787. """Request a full status update from the printer (public API).
  2788. Sends both pushall and get_accessories commands to refresh all data
  2789. including nozzle hardware info.
  2790. Returns:
  2791. True if the request was sent, False if not connected.
  2792. """
  2793. if not self._client or not self.state.connected:
  2794. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  2795. return False
  2796. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  2797. self._request_push_all()
  2798. # Note: get_accessories returns stale nozzle data on H2D.
  2799. # The correct nozzle data comes from push_status response.
  2800. return True
  2801. def _request_accessories(self):
  2802. """Request accessories info (nozzle type, etc.) from printer."""
  2803. if self._client:
  2804. self._sequence_id += 1
  2805. message = {
  2806. "system": {
  2807. "sequence_id": str(self._sequence_id),
  2808. "command": "get_accessories",
  2809. "accessory_type": "none",
  2810. }
  2811. }
  2812. logger.debug("[%s] Requesting accessories info", self.serial_number)
  2813. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  2814. def _prime_kprofile_request(self):
  2815. """Send a priming K-profile request on connect.
  2816. Bambu printers often ignore the first K-profile request after connection,
  2817. so we send a dummy request on connect to 'prime' the system.
  2818. """
  2819. if self._client:
  2820. self._sequence_id += 1
  2821. command = {
  2822. "print": {
  2823. "command": "extrusion_cali_get",
  2824. "filament_id": "",
  2825. "nozzle_diameter": "0.4",
  2826. "sequence_id": str(self._sequence_id),
  2827. }
  2828. }
  2829. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  2830. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2831. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  2832. """Connect to the printer MQTT broker.
  2833. Args:
  2834. loop: The asyncio event loop to use for thread-safe callbacks.
  2835. If not provided, will try to get the running loop.
  2836. """
  2837. self._loop = loop
  2838. BambuMQTTClient._client_instance_counter += 1
  2839. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  2840. self._client = mqtt.Client(
  2841. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  2842. client_id=client_id,
  2843. protocol=mqtt.MQTTv311,
  2844. )
  2845. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  2846. # tracking (#1164). The default ceiling of 20 wedges sessions after
  2847. # ~16-20 cumulative commands; lifting it well above any realistic
  2848. # session count keeps QoS=1 working without changing wire-protocol
  2849. # behaviour across printer models.
  2850. self._client.max_inflight_messages_set(1000)
  2851. self._client.username_pw_set("bblp", self.access_code)
  2852. self._client.on_connect = self._on_connect
  2853. self._client.on_disconnect = self._on_disconnect
  2854. self._client.on_subscribe = self._on_subscribe
  2855. self._client.on_message = self._on_message
  2856. # TLS setup - Bambu uses self-signed certs
  2857. ssl_context = ssl.create_default_context()
  2858. ssl_context.check_hostname = False
  2859. ssl_context.verify_mode = ssl.CERT_NONE
  2860. self._client.tls_set_context(ssl_context)
  2861. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  2862. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  2863. # Keepalive: paho sends PINGREQs at this interval, broker considers
  2864. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  2865. # real network loss (45s), not so aggressive that transient hiccups
  2866. # trigger false disconnects. Stale detection (60s no messages) handles
  2867. # the P1S/P1P firmware bug where the broker stops publishing but the
  2868. # TCP connection stays alive.
  2869. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  2870. self._client.loop_start()
  2871. def start_print(
  2872. self,
  2873. filename: str,
  2874. plate_id: int = 1,
  2875. ams_mapping: list[int] | None = None,
  2876. bed_levelling: bool = True,
  2877. flow_cali: bool = False,
  2878. vibration_cali: bool = True,
  2879. layer_inspect: bool = False,
  2880. timelapse: bool = False,
  2881. use_ams: bool = True,
  2882. ):
  2883. """Start a print job on the printer.
  2884. The file should already be uploaded to the printer's root directory via FTP.
  2885. Args:
  2886. filename: Name of the uploaded file
  2887. plate_id: Plate number to print (default 1)
  2888. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  2889. Global tray ID = (ams_id * 4) + slot_id, external = 254
  2890. timelapse: Record timelapse video
  2891. bed_levelling: Auto bed levelling before print
  2892. flow_cali: Flow/pressure advance calibration
  2893. vibration_cali: Vibration compensation calibration
  2894. layer_inspect: First layer AI inspection
  2895. use_ams: Use AMS for automatic filament changes
  2896. """
  2897. if self._client and self.state.connected:
  2898. # Bambu print command format - matches Bambu Studio's format
  2899. # H2D series requires integer values (0/1) for calibration/leveling fields
  2900. # but use_ams MUST remain boolean — H2D Pro firmware interprets integer
  2901. # values as nozzle index (1 = deputy nozzle), causing wrong extruder routing
  2902. # Other printers (X1C, P1S, A1, etc.) require actual booleans for all fields
  2903. is_h2d = self.model and self.model.upper().strip() in ("H2D", "H2D PRO", "H2DPRO", "H2C", "H2S", "X2D")
  2904. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  2905. ams_mapping2 = []
  2906. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  2907. # ams_mapping and relies on ams_mapping2 for external spool details.
  2908. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  2909. # with 0700_8012 "Failed to get AMS mapping table".
  2910. flat_ams_mapping = []
  2911. if ams_mapping is not None:
  2912. for tray_id in ams_mapping:
  2913. # Ensure tray_id is an integer (may be string from JSON)
  2914. tray_id = int(tray_id) if tray_id is not None else -1
  2915. if tray_id == -1:
  2916. # Unmapped filament slot
  2917. flat_ams_mapping.append(-1)
  2918. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  2919. elif tray_id >= 254:
  2920. # External/virtual spool. BambuStudio convention:
  2921. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  2922. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  2923. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  2924. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  2925. # for external spool, but BambuStudio always sends ams_id=255
  2926. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  2927. # firmware to target AMS tray 0 instead of external spool, leading
  2928. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  2929. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  2930. flat_ams_mapping.append(-1)
  2931. ext_ams_id = tray_id if is_h2d else 255
  2932. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  2933. elif tray_id >= 128:
  2934. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  2935. flat_ams_mapping.append(tray_id)
  2936. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  2937. else:
  2938. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  2939. ams_id = tray_id // 4
  2940. slot_id = tray_id % 4
  2941. flat_ams_mapping.append(tray_id)
  2942. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  2943. # If all mapped slots are external spool (no real AMS trays), force use_ams=False.
  2944. # P1S/P1P with no AMS rejects use_ams=True with "Failed to get AMS mapping table".
  2945. # Skip for H2D series — use_ams controls nozzle routing on those printers.
  2946. if ams_mapping and use_ams and not is_h2d:
  2947. if all(t is None or int(t) < 0 or int(t) >= 254 for t in ams_mapping):
  2948. use_ams = False
  2949. logger.info(
  2950. "[%s] All filament slots use external spool — setting use_ams=False",
  2951. self.serial_number,
  2952. )
  2953. # Unique per-submission identity fields. Hardcoded "0" values caused
  2954. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  2955. # continuations of the same job: the printer reuses gcode_start_time
  2956. # from the prior print with task_id=0, so observers latch onto a stale
  2957. # timestamp and report compounding durations on repeat replays (#1011).
  2958. # BambuStudio mints fresh IDs per submission; matching that behavior
  2959. # makes the printer emit a clean state-transition for each job.
  2960. # md5 is left empty — firmware historically accepts "" as "skip
  2961. # validation" (unlike Studio, we don't have the file's real md5 here
  2962. # without re-reading the upload, and sending a synthetic wrong digest
  2963. # risks activation of md5 verification on some firmwares).
  2964. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  2965. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  2966. # overflows and every submission ends up with the same task_id from
  2967. # the printer's perspective — the printer then treats a fresh dispatch
  2968. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  2969. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  2970. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  2971. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  2972. command = {
  2973. "print": {
  2974. "sequence_id": "20000",
  2975. "command": "project_file",
  2976. "param": f"Metadata/plate_{plate_id}.gcode",
  2977. "url": f"ftp://{filename}",
  2978. "file": filename,
  2979. "md5": "",
  2980. "bed_type": "auto",
  2981. "timelapse": (1 if timelapse else 0) if is_h2d else timelapse,
  2982. "bed_leveling": (1 if bed_levelling else 0) if is_h2d else bed_levelling,
  2983. "auto_bed_leveling": 1 if bed_levelling else 0,
  2984. "flow_cali": (1 if flow_cali else 0) if is_h2d else flow_cali,
  2985. "vibration_cali": (1 if vibration_cali else 0) if is_h2d else vibration_cali,
  2986. "layer_inspect": (1 if layer_inspect else 0) if is_h2d else layer_inspect,
  2987. "use_ams": use_ams,
  2988. "cfg": "0",
  2989. "extrude_cali_flag": 0,
  2990. "extrude_cali_manual_mode": 0,
  2991. "nozzle_offset_cali": 2,
  2992. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  2993. "profile_id": "0",
  2994. "project_id": submission_id,
  2995. "subtask_id": submission_id,
  2996. "task_id": submission_id,
  2997. }
  2998. }
  2999. if is_h2d:
  3000. logger.debug(
  3001. "[%s] H2D series detected: using integer format for calibration fields (use_ams stays boolean)",
  3002. self.serial_number,
  3003. )
  3004. # P2S-specific parameter adjustments
  3005. # P2S printer doesn't support vibration calibration like X1/P1 series
  3006. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  3007. command["print"]["vibration_cali"] = False
  3008. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  3009. # Add AMS mapping if provided
  3010. if ams_mapping is not None:
  3011. command["print"]["ams_mapping"] = flat_ams_mapping
  3012. command["print"]["ams_mapping2"] = ams_mapping2
  3013. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  3014. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3015. # Record what we dispatched so /cover can pick the right plate
  3016. # thumbnail even when the printer's gcode_file echo is just the
  3017. # 3MF filename without a plate path (#1166). Match the same
  3018. # subtask_name shape we send so the comparison in the cover route
  3019. # works against state.subtask_name reflected back via MQTT.
  3020. self.state.dispatched_plate_id = plate_id
  3021. self.state.dispatched_subtask = command["print"]["subtask_name"]
  3022. return True
  3023. else:
  3024. # Log why we couldn't send the command
  3025. if not self._client:
  3026. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  3027. elif not self.state.connected:
  3028. logger.error(
  3029. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  3030. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  3031. )
  3032. return False
  3033. def stop_print(self) -> bool:
  3034. """Stop the current print job."""
  3035. if self._client and self.state.connected:
  3036. command = {"print": {"command": "stop", "sequence_id": "0"}}
  3037. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3038. logger.info("[%s] Sent stop print command", self.serial_number)
  3039. return True
  3040. return False
  3041. def set_xcam_option(
  3042. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  3043. ) -> bool:
  3044. """Set an xcam (AI detection) option on the printer.
  3045. Args:
  3046. module_name: The xcam module to control (e.g., "spaghetti_detector",
  3047. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  3048. enabled: Whether to enable or disable the feature
  3049. print_halt: Whether to halt print on detection (only applies to some detectors)
  3050. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  3051. Returns:
  3052. True if command was sent, False if not connected
  3053. """
  3054. if not self._client or not self.state.connected:
  3055. return False
  3056. # auto_recovery_step_loss uses a different command format (print.print_option)
  3057. if module_name == "auto_recovery_step_loss":
  3058. return self._set_print_option("auto_recovery", enabled)
  3059. self._sequence_id += 1
  3060. # Build the xcam control command (exact OrcaSlicer format)
  3061. # Key findings from OrcaSlicer source:
  3062. # - Uses "xcam" wrapper (not "print")
  3063. # - print_halt is ALWAYS true (legacy protocol requirement)
  3064. # - Both "control" and "enable" are set to the same value
  3065. # - halt_print_sensitivity controls actual halt behavior
  3066. command = {
  3067. "xcam": {
  3068. "command": "xcam_control_set",
  3069. "sequence_id": str(self._sequence_id),
  3070. "module_name": module_name,
  3071. "control": enabled,
  3072. "enable": enabled, # old protocol compatibility
  3073. "print_halt": True, # ALWAYS true per OrcaSlicer
  3074. }
  3075. }
  3076. # Only add sensitivity if not "never_halt"
  3077. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  3078. # The module_name field determines which detector's sensitivity is being set
  3079. if sensitivity and sensitivity != "never_halt":
  3080. command["xcam"]["halt_print_sensitivity"] = sensitivity
  3081. command_json = json.dumps(command)
  3082. self._client.publish(self.topic_publish, command_json, qos=1)
  3083. logger.debug(
  3084. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  3085. )
  3086. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  3087. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  3088. # This prevents stale MQTT data from immediately overwriting our change
  3089. self._xcam_hold_start[module_name] = time.time()
  3090. # Update local state immediately for responsive UI
  3091. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  3092. # When spaghetti_detector sensitivity is changed, pileup also changes
  3093. if module_name == "spaghetti_detector":
  3094. self.state.print_options.spaghetti_detector = enabled
  3095. self.state.print_options.print_halt = print_halt
  3096. if sensitivity and sensitivity != "never_halt":
  3097. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  3098. self.state.print_options.halt_print_sensitivity = sensitivity
  3099. self.state.print_options.pileup_sensitivity = sensitivity
  3100. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  3101. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  3102. elif module_name == "first_layer_inspector":
  3103. self.state.print_options.first_layer_inspector = enabled
  3104. elif module_name == "printing_monitor":
  3105. self.state.print_options.printing_monitor = enabled
  3106. elif module_name == "buildplate_marker_detector":
  3107. self.state.print_options.buildplate_marker_detector = enabled
  3108. elif module_name == "allow_skip_parts":
  3109. self.state.print_options.allow_skip_parts = enabled
  3110. elif module_name == "pileup_detector":
  3111. self.state.print_options.pileup_detector = enabled
  3112. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  3113. elif module_name == "clump_detector":
  3114. self.state.print_options.nozzle_clumping_detector = enabled
  3115. if sensitivity and sensitivity != "never_halt":
  3116. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  3117. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  3118. elif module_name == "airprint_detector":
  3119. self.state.print_options.airprint_detector = enabled
  3120. if sensitivity and sensitivity != "never_halt":
  3121. self.state.print_options.airprint_sensitivity = sensitivity
  3122. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  3123. elif module_name == "auto_recovery_step_loss":
  3124. self.state.print_options.auto_recovery_step_loss = enabled
  3125. return True
  3126. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  3127. """Set a print option using the print.print_option command.
  3128. This is different from xcam_control_set and is used for options like:
  3129. - auto_recovery
  3130. - air_print_detect
  3131. - filament_tangle_detect
  3132. - nozzle_blob_detect
  3133. - sound_enable
  3134. Args:
  3135. option_name: The option to control (e.g., "auto_recovery")
  3136. enabled: Whether to enable or disable the option
  3137. Returns:
  3138. True if command was sent, False if not connected
  3139. """
  3140. if not self._client or not self.state.connected:
  3141. return False
  3142. self._sequence_id += 1
  3143. command = {
  3144. "print": {
  3145. "command": "print_option",
  3146. "sequence_id": str(self._sequence_id),
  3147. option_name: enabled,
  3148. }
  3149. }
  3150. command_json = json.dumps(command)
  3151. self._client.publish(self.topic_publish, command_json, qos=1)
  3152. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  3153. # Set hold timer
  3154. hold_key = f"print_option_{option_name}"
  3155. self._xcam_hold_start[hold_key] = time.time()
  3156. # Update local state immediately
  3157. if option_name == "auto_recovery":
  3158. self.state.print_options.auto_recovery_step_loss = enabled
  3159. return True
  3160. def start_calibration(
  3161. self,
  3162. bed_leveling: bool = False,
  3163. vibration: bool = False,
  3164. motor_noise: bool = False,
  3165. nozzle_offset: bool = False,
  3166. high_temp_heatbed: bool = False,
  3167. ) -> bool:
  3168. """Start printer calibration with selected options.
  3169. Args:
  3170. bed_leveling: Run bed leveling calibration
  3171. vibration: Run vibration compensation calibration
  3172. motor_noise: Run motor noise cancellation calibration
  3173. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  3174. high_temp_heatbed: Run high-temperature heatbed calibration
  3175. Returns:
  3176. True if command was sent, False if not connected
  3177. """
  3178. if not self._client or not self.state.connected:
  3179. return False
  3180. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  3181. # Bit 0: xcam_cali (not exposed in UI)
  3182. # Bit 1: bed_leveling
  3183. # Bit 2: vibration
  3184. # Bit 3: motor_noise
  3185. # Bit 4: nozzle_cali
  3186. # Bit 5: bed_cali (high-temp heatbed)
  3187. # Bit 6: clumppos_cali (not exposed in UI)
  3188. option = 0
  3189. if bed_leveling:
  3190. option |= 1 << 1
  3191. if vibration:
  3192. option |= 1 << 2
  3193. if motor_noise:
  3194. option |= 1 << 3
  3195. if nozzle_offset:
  3196. option |= 1 << 4
  3197. if high_temp_heatbed:
  3198. option |= 1 << 5
  3199. if option == 0:
  3200. logger.warning("[%s] No calibration options selected", self.serial_number)
  3201. return False
  3202. self._sequence_id += 1
  3203. command = {
  3204. "print": {
  3205. "command": "calibration",
  3206. "sequence_id": str(self._sequence_id),
  3207. "option": option,
  3208. }
  3209. }
  3210. command_json = json.dumps(command)
  3211. self._client.publish(self.topic_publish, command_json, qos=1)
  3212. logger.info(
  3213. f"[{self.serial_number}] Starting calibration: "
  3214. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  3215. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  3216. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  3217. )
  3218. return True
  3219. def disconnect(self, timeout: float = 0):
  3220. """Disconnect from the printer."""
  3221. if self._client:
  3222. self._disconnection_event = threading.Event()
  3223. self._client.disconnect()
  3224. self._disconnection_event.wait(timeout=timeout)
  3225. self._client.loop_stop()
  3226. self._client = None
  3227. self.state.connected = False
  3228. def send_command(self, command: dict):
  3229. """Send a command to the printer."""
  3230. if self._client and self.state.connected:
  3231. # Log outgoing message if logging is enabled
  3232. if self._logging_enabled:
  3233. self._message_log.append(
  3234. MQTTLogEntry(
  3235. timestamp=datetime.now(timezone.utc).isoformat(),
  3236. topic=self.topic_publish,
  3237. direction="out",
  3238. payload=command,
  3239. )
  3240. )
  3241. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3242. def enable_logging(self, enabled: bool = True):
  3243. """Enable or disable MQTT message logging."""
  3244. self._logging_enabled = enabled
  3245. # Don't clear logs when stopping - user can manually clear with clear_logs()
  3246. def get_logs(self) -> list[MQTTLogEntry]:
  3247. """Get all logged MQTT messages."""
  3248. return list(self._message_log)
  3249. def clear_logs(self):
  3250. """Clear the message log."""
  3251. self._message_log.clear()
  3252. @property
  3253. def logging_enabled(self) -> bool:
  3254. """Check if logging is enabled."""
  3255. return self._logging_enabled
  3256. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  3257. """Register a handler invoked for every incoming MQTT message.
  3258. Used by the VP MQTT bridge to republish the printer's report pushes to
  3259. slicers connected to a virtual printer in non-proxy mode. Handlers run
  3260. on paho's network thread and must not block; exceptions are caught.
  3261. """
  3262. if handler not in self._raw_message_handlers:
  3263. self._raw_message_handlers.append(handler)
  3264. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  3265. """Unregister a previously-registered raw-message handler."""
  3266. try:
  3267. self._raw_message_handlers.remove(handler)
  3268. except ValueError:
  3269. pass
  3270. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  3271. """Publish a pre-formed payload directly to the printer's MQTT broker.
  3272. Used by the VP MQTT bridge to forward slicer-originated commands without
  3273. going through send_command's sequence-id mangling. Returns False if the
  3274. underlying paho client isn't ready.
  3275. """
  3276. if self._client is None:
  3277. return False
  3278. try:
  3279. info = self._client.publish(topic, payload, qos=qos)
  3280. return info.rc == mqtt.MQTT_ERR_SUCCESS
  3281. except Exception:
  3282. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  3283. return False
  3284. def send_drying_command(
  3285. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  3286. ):
  3287. """Send AMS drying start/stop command.
  3288. Args:
  3289. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  3290. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  3291. duration: Drying duration in hours
  3292. mode: 1=start, 0=stop
  3293. filament: Filament type string (e.g. "PLA", "PETG")
  3294. rotate_tray: Whether to rotate the spool during drying for even heat
  3295. """
  3296. if not self._client:
  3297. return False
  3298. self._sequence_id += 1
  3299. command = {
  3300. "print": {
  3301. "sequence_id": str(self._sequence_id),
  3302. "command": "ams_filament_drying",
  3303. "ams_id": ams_id,
  3304. "temp": temp,
  3305. "cooling_temp": 20 if mode == 1 else 0,
  3306. "duration": duration,
  3307. "humidity": 0,
  3308. "mode": mode,
  3309. "rotate_tray": rotate_tray,
  3310. "filament": filament,
  3311. "close_power_conflict": False,
  3312. }
  3313. }
  3314. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3315. logger.info(
  3316. "[%s] Sent drying command: ams_id=%d, temp=%d, duration=%d, mode=%d",
  3317. self.serial_number,
  3318. ams_id,
  3319. temp,
  3320. duration,
  3321. mode,
  3322. )
  3323. return True
  3324. def _handle_kprofile_response(self, data: dict):
  3325. """Handle K-profile response from printer."""
  3326. response_nozzle = data.get("nozzle_diameter")
  3327. response_seq_id = data.get("sequence_id", "?")
  3328. filaments = data.get("filaments", [])
  3329. expected_nozzle = getattr(self, "_expected_kprofile_nozzle", None)
  3330. has_pending_request = self._pending_kprofile_response is not None
  3331. # Log all incoming responses when we have a pending request (for debugging)
  3332. if has_pending_request:
  3333. logger.info(
  3334. f"[{self.serial_number}] K-profile response: nozzle={response_nozzle}, "
  3335. f"seq_id={response_seq_id}, {len(filaments)} profiles, expected={expected_nozzle}"
  3336. )
  3337. # If we have a pending request, only accept responses with matching nozzle_diameter
  3338. # The printer broadcasts 0.4mm profiles constantly - we need to wait for the actual response
  3339. if has_pending_request and expected_nozzle and response_nozzle != expected_nozzle:
  3340. # Ignore this broadcast, keep waiting for matching response
  3341. logger.debug(
  3342. f"[{self.serial_number}] Ignoring broadcast: got nozzle={response_nozzle}, waiting for {expected_nozzle}"
  3343. )
  3344. return
  3345. # If no pending request, this is just a broadcast - update state silently and return early
  3346. if not has_pending_request:
  3347. # Still parse profiles to keep state updated, but don't log
  3348. profiles = []
  3349. for f in filaments:
  3350. if isinstance(f, dict):
  3351. try:
  3352. cali_idx = f.get("cali_idx", 0)
  3353. profiles.append(
  3354. KProfile(
  3355. slot_id=cali_idx,
  3356. extruder_id=int(f.get("extruder_id", 0)),
  3357. nozzle_id=str(f.get("nozzle_id", "")),
  3358. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  3359. filament_id=str(f.get("filament_id", "")),
  3360. name=str(f.get("name", "")),
  3361. k_value=str(f.get("k_value", "0.000000")),
  3362. n_coef=str(f.get("n_coef", "0.000000")),
  3363. ams_id=int(f.get("ams_id", 0)),
  3364. tray_id=int(f.get("tray_id", -1)),
  3365. setting_id=f.get("setting_id"),
  3366. )
  3367. )
  3368. except (ValueError, TypeError):
  3369. pass # Skip malformed K-profile entries; remaining profiles still usable
  3370. self.state.kprofiles = profiles
  3371. return
  3372. profiles = []
  3373. for i, f in enumerate(filaments):
  3374. if isinstance(f, dict):
  3375. try:
  3376. # cali_idx is the actual slot/calibration index from the printer
  3377. cali_idx = f.get("cali_idx", i)
  3378. profiles.append(
  3379. KProfile(
  3380. slot_id=cali_idx,
  3381. extruder_id=int(f.get("extruder_id", 0)),
  3382. nozzle_id=str(f.get("nozzle_id", "")),
  3383. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  3384. filament_id=str(f.get("filament_id", "")),
  3385. name=str(f.get("name", "")),
  3386. k_value=str(f.get("k_value", "0.000000")),
  3387. n_coef=str(f.get("n_coef", "0.000000")),
  3388. ams_id=int(f.get("ams_id", 0)),
  3389. tray_id=int(f.get("tray_id", -1)),
  3390. setting_id=f.get("setting_id"),
  3391. )
  3392. )
  3393. except (ValueError, TypeError) as e:
  3394. logger.warning("Failed to parse K-profile: %s", e)
  3395. self.state.kprofiles = profiles
  3396. self._kprofile_response_data = profiles
  3397. # Signal that we received the response (only if we were waiting for one)
  3398. # Use thread-safe method since MQTT callbacks run in a different thread
  3399. # Capture in local var to avoid TOCTOU race: asyncio thread can clear
  3400. # self._pending_kprofile_response between the check and the .set() call
  3401. event = self._pending_kprofile_response
  3402. if event:
  3403. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  3404. if self._loop and self._loop.is_running():
  3405. self._loop.call_soon_threadsafe(event.set)
  3406. else:
  3407. # Fallback for when loop is not available
  3408. event.set()
  3409. async def get_kprofiles(
  3410. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  3411. ) -> list[KProfile]:
  3412. """Request K-profiles from the printer with retry logic.
  3413. Bambu printers sometimes ignore the first K-profile request, so we
  3414. implement retry logic to ensure reliable retrieval.
  3415. Args:
  3416. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  3417. timeout: Timeout in seconds to wait for each response attempt
  3418. max_retries: Maximum number of retry attempts
  3419. Returns:
  3420. List of KProfile objects
  3421. """
  3422. if not self._client or not self.state.connected:
  3423. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  3424. return []
  3425. # Capture current event loop for thread-safe callback
  3426. try:
  3427. self._loop = asyncio.get_running_loop()
  3428. except RuntimeError:
  3429. logger.warning("[%s] No running event loop", self.serial_number)
  3430. return []
  3431. for attempt in range(max_retries):
  3432. # Set up response event for this attempt
  3433. self._sequence_id += 1
  3434. self._pending_kprofile_response = asyncio.Event()
  3435. self._kprofile_response_data = None
  3436. self._expected_kprofile_nozzle = nozzle_diameter # Track which nozzle response we expect
  3437. # Send the command with nozzle_diameter filter
  3438. command = {
  3439. "print": {
  3440. "command": "extrusion_cali_get",
  3441. "filament_id": "",
  3442. "nozzle_diameter": nozzle_diameter,
  3443. "sequence_id": str(self._sequence_id),
  3444. }
  3445. }
  3446. logger.info(
  3447. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries})"
  3448. )
  3449. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  3450. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3451. # Wait for response (response handler already filters by nozzle_diameter)
  3452. try:
  3453. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  3454. profiles = self._kprofile_response_data or []
  3455. logger.info(
  3456. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  3457. )
  3458. return profiles
  3459. except TimeoutError:
  3460. logger.warning(
  3461. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  3462. )
  3463. if attempt < max_retries - 1:
  3464. # Brief delay before retry
  3465. await asyncio.sleep(0.5)
  3466. finally:
  3467. self._pending_kprofile_response = None
  3468. self._expected_kprofile_nozzle = None
  3469. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  3470. return []
  3471. def set_kprofile(
  3472. self,
  3473. filament_id: str,
  3474. name: str,
  3475. k_value: str,
  3476. nozzle_diameter: str = "0.4",
  3477. nozzle_id: str = "HS00-0.4",
  3478. extruder_id: int = 0,
  3479. setting_id: str | None = None,
  3480. slot_id: int = 0,
  3481. cali_idx: int | None = None,
  3482. ) -> bool:
  3483. """Set/update a K-profile on the printer.
  3484. Args:
  3485. filament_id: Bambu filament identifier
  3486. name: Profile name
  3487. k_value: Pressure advance value (e.g., "0.020000")
  3488. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  3489. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  3490. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  3491. setting_id: Existing setting ID for updates, None for new
  3492. slot_id: Calibration index (cali_idx) for the profile
  3493. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  3494. Returns:
  3495. True if command was sent, False otherwise
  3496. """
  3497. if not self._client or not self.state.connected:
  3498. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  3499. return False
  3500. self._sequence_id += 1
  3501. # Build the filament entry - printer uses cali_idx for profile identification
  3502. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  3503. # For edits, use the provided cali_idx or slot_id
  3504. if cali_idx is not None:
  3505. effective_cali_idx = cali_idx
  3506. else:
  3507. effective_cali_idx = -1 if slot_id == 0 else slot_id
  3508. # Generate a setting_id for new profiles (required by printer)
  3509. # Format: "PF" + 17 random digits
  3510. import random
  3511. if not setting_id and slot_id == 0:
  3512. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  3513. filament_entry = {
  3514. "ams_id": 0,
  3515. "cali_idx": effective_cali_idx,
  3516. "extruder_id": extruder_id,
  3517. "filament_id": filament_id,
  3518. "k_value": k_value,
  3519. "n_coef": "0.000000",
  3520. "name": name,
  3521. "nozzle_diameter": nozzle_diameter,
  3522. "nozzle_id": nozzle_id,
  3523. "setting_id": setting_id if setting_id else "",
  3524. "tray_id": -1,
  3525. }
  3526. command = {
  3527. "print": {
  3528. "command": "extrusion_cali_set",
  3529. "filaments": [filament_entry],
  3530. "nozzle_diameter": nozzle_diameter,
  3531. "sequence_id": str(self._sequence_id),
  3532. }
  3533. }
  3534. command_json = json.dumps(command)
  3535. logger.info(
  3536. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  3537. )
  3538. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  3539. self._client.publish(self.topic_publish, command_json, qos=1)
  3540. return True
  3541. def set_kprofiles_batch(
  3542. self,
  3543. profiles: list[dict],
  3544. nozzle_diameter: str = "0.4",
  3545. ) -> bool:
  3546. """Set multiple K-profiles in a single command (for dual-nozzle).
  3547. Args:
  3548. profiles: List of profile dicts, each with:
  3549. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  3550. nozzle_diameter: Common nozzle diameter for all profiles
  3551. Returns:
  3552. True if command was sent, False otherwise
  3553. """
  3554. if not self._client or not self.state.connected:
  3555. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  3556. return False
  3557. import random
  3558. self._sequence_id += 1
  3559. filament_entries = []
  3560. for p in profiles:
  3561. slot_id = p.get("slot_id", 0)
  3562. cali_idx = p.get("cali_idx")
  3563. if cali_idx is not None:
  3564. effective_cali_idx = cali_idx
  3565. else:
  3566. effective_cali_idx = -1 if slot_id == 0 else slot_id
  3567. setting_id = p.get("setting_id")
  3568. if not setting_id and slot_id == 0:
  3569. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  3570. filament_entries.append(
  3571. {
  3572. "ams_id": 0,
  3573. "cali_idx": effective_cali_idx,
  3574. "extruder_id": p.get("extruder_id", 0),
  3575. "filament_id": p.get("filament_id", ""),
  3576. "k_value": p.get("k_value", "0.020000"),
  3577. "n_coef": "0.000000",
  3578. "name": p.get("name", ""),
  3579. "nozzle_diameter": nozzle_diameter,
  3580. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  3581. "setting_id": setting_id if setting_id else "",
  3582. "tray_id": -1,
  3583. }
  3584. )
  3585. command = {
  3586. "print": {
  3587. "command": "extrusion_cali_set",
  3588. "filaments": filament_entries,
  3589. "nozzle_diameter": nozzle_diameter,
  3590. "sequence_id": str(self._sequence_id),
  3591. }
  3592. }
  3593. command_json = json.dumps(command)
  3594. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  3595. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  3596. self._client.publish(self.topic_publish, command_json, qos=1)
  3597. return True
  3598. def delete_kprofile(
  3599. self,
  3600. cali_idx: int,
  3601. filament_id: str,
  3602. nozzle_id: str,
  3603. nozzle_diameter: str = "0.4",
  3604. extruder_id: int = 0,
  3605. setting_id: str | None = None,
  3606. ) -> bool:
  3607. """Delete a K-profile from the printer.
  3608. Args:
  3609. cali_idx: The calibration index (slot_id) of the profile to delete
  3610. filament_id: Bambu filament identifier
  3611. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  3612. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  3613. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  3614. setting_id: Unique setting identifier (for X1C series)
  3615. Returns:
  3616. True if command was sent, False otherwise
  3617. """
  3618. if not self._client or not self.state.connected:
  3619. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  3620. return False
  3621. self._sequence_id += 1
  3622. # Detect printer type by serial number prefix
  3623. # Dual-nozzle families:
  3624. # H2 series: legacy "094"; post-2026 H2C batches ship with "31B8B" (#1105)
  3625. # X2D series: "20P9"
  3626. is_dual_nozzle = self.serial_number.startswith(("094", "20P9", "31B8B"))
  3627. if is_dual_nozzle:
  3628. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  3629. command = {
  3630. "print": {
  3631. "command": "extrusion_cali_del",
  3632. "sequence_id": str(self._sequence_id),
  3633. "extruder_id": extruder_id,
  3634. "nozzle_id": nozzle_id,
  3635. "filament_id": filament_id,
  3636. "cali_idx": cali_idx,
  3637. "nozzle_diameter": nozzle_diameter,
  3638. }
  3639. }
  3640. else:
  3641. # X1C/P1/A1 format: include all fields like the set command
  3642. # The delete command structure should match what set uses
  3643. command = {
  3644. "print": {
  3645. "command": "extrusion_cali_del",
  3646. "sequence_id": str(self._sequence_id),
  3647. "filament_id": filament_id,
  3648. "cali_idx": cali_idx,
  3649. "setting_id": setting_id if setting_id else "",
  3650. "nozzle_diameter": nozzle_diameter,
  3651. "nozzle_id": nozzle_id,
  3652. "extruder_id": extruder_id,
  3653. }
  3654. }
  3655. command_json = json.dumps(command)
  3656. logger.info(
  3657. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  3658. )
  3659. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  3660. # Use QoS 1 for reliable delivery (at least once)
  3661. self._client.publish(self.topic_publish, command_json, qos=1)
  3662. return True
  3663. # =========================================================================
  3664. # Printer Control Commands
  3665. # =========================================================================
  3666. def pause_print(self) -> bool:
  3667. """Pause the current print job."""
  3668. if not self._client or not self.state.connected:
  3669. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  3670. return False
  3671. command = {"print": {"command": "pause", "sequence_id": "0"}}
  3672. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3673. logger.info("[%s] Sent pause print command", self.serial_number)
  3674. return True
  3675. def resume_print(self) -> bool:
  3676. """Resume a paused print job."""
  3677. if not self._client or not self.state.connected:
  3678. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  3679. return False
  3680. command = {"print": {"command": "resume", "sequence_id": "0"}}
  3681. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3682. logger.info("[%s] Sent resume print command", self.serial_number)
  3683. return True
  3684. def clear_hms_errors(self) -> bool:
  3685. """Clear HMS/print errors on the printer and locally."""
  3686. if not self._client or not self.state.connected:
  3687. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  3688. return False
  3689. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  3690. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3691. self.state.hms_errors = []
  3692. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  3693. return True
  3694. def skip_objects(self, object_ids: list[int]) -> bool:
  3695. """Skip specific objects during a print.
  3696. This command tells the printer to skip printing the specified objects.
  3697. The object IDs come from the slice_info.config file in the 3MF.
  3698. Args:
  3699. object_ids: List of identify_id values from slice_info.config
  3700. Returns:
  3701. True if command was sent, False otherwise
  3702. """
  3703. if not self._client or not self.state.connected:
  3704. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  3705. return False
  3706. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  3707. logger.warning(
  3708. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  3709. )
  3710. return False
  3711. if not object_ids:
  3712. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  3713. return False
  3714. # Validate all IDs are integers
  3715. try:
  3716. obj_list = [int(oid) for oid in object_ids]
  3717. except (ValueError, TypeError) as e:
  3718. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  3719. return False
  3720. self._sequence_id += 1
  3721. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  3722. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3723. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  3724. # Track skipped objects in state
  3725. for oid in obj_list:
  3726. if oid not in self.state.skipped_objects:
  3727. self.state.skipped_objects.append(oid)
  3728. return True
  3729. def send_gcode(self, gcode: str) -> bool:
  3730. """Send G-code command(s) to the printer.
  3731. Multiple commands can be separated by newlines.
  3732. Args:
  3733. gcode: G-code command(s) to send
  3734. Returns:
  3735. True if command was sent, False otherwise
  3736. """
  3737. if not self._client or not self.state.connected:
  3738. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  3739. return False
  3740. self._sequence_id += 1
  3741. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  3742. # Use QoS 1 for reliable delivery (at least once)
  3743. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3744. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  3745. return True
  3746. def set_bed_temperature(self, target: int) -> bool:
  3747. """Set the bed target temperature.
  3748. Args:
  3749. target: Target temperature in Celsius (0 to turn off)
  3750. Returns:
  3751. True if command was sent, False otherwise
  3752. """
  3753. return self.send_gcode(f"M140 S{target}")
  3754. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  3755. """Set the nozzle target temperature.
  3756. Args:
  3757. target: Target temperature in Celsius (0 to turn off)
  3758. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  3759. Returns:
  3760. True if command was sent, False otherwise
  3761. """
  3762. # Use M104 for non-blocking
  3763. # Always use T parameter for H2D compatibility
  3764. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  3765. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  3766. # Track it locally so we can display it correctly
  3767. if result and nozzle == 1:
  3768. self.state.temperatures["nozzle_target"] = float(target)
  3769. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  3770. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  3771. return result
  3772. def set_chamber_temperature(self, target: int) -> bool:
  3773. """Set the chamber target temperature.
  3774. Args:
  3775. target: Target temperature in Celsius (0 to turn off heating)
  3776. Returns:
  3777. True if command was sent, False otherwise
  3778. """
  3779. # M141 sets chamber temperature
  3780. result = self.send_gcode(f"M141 S{target}")
  3781. # Track chamber target locally (MQTT reports encoded values that need filtering)
  3782. if result:
  3783. self.state.temperatures["chamber_target"] = float(target)
  3784. self.state.temperatures["_chamber_target_set_time"] = time.time()
  3785. # Update heating state immediately based on new target
  3786. current_temp = self.state.temperatures.get("chamber", 0)
  3787. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  3788. logger.info(
  3789. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  3790. )
  3791. return result
  3792. def set_print_speed(self, mode: int) -> bool:
  3793. """Set the print speed mode.
  3794. Args:
  3795. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  3796. Returns:
  3797. True if command was sent, False otherwise
  3798. """
  3799. if not self._client or not self.state.connected:
  3800. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  3801. return False
  3802. if mode not in (1, 2, 3, 4):
  3803. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  3804. return False
  3805. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  3806. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3807. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  3808. return True
  3809. def set_fan_speed(self, fan: int, speed: int) -> bool:
  3810. """Set fan speed.
  3811. Args:
  3812. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber)
  3813. speed: Speed 0-255 (0=off, 255=full)
  3814. Returns:
  3815. True if command was sent, False otherwise
  3816. """
  3817. if fan not in (1, 2, 3):
  3818. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  3819. return False
  3820. speed = max(0, min(255, speed)) # Clamp to 0-255
  3821. return self.send_gcode(f"M106 P{fan} S{speed}")
  3822. def set_part_fan(self, speed: int) -> bool:
  3823. """Set part cooling fan speed (0-255)."""
  3824. return self.set_fan_speed(1, speed)
  3825. def set_aux_fan(self, speed: int) -> bool:
  3826. """Set auxiliary fan speed (0-255)."""
  3827. return self.set_fan_speed(2, speed)
  3828. def set_chamber_fan(self, speed: int) -> bool:
  3829. """Set chamber fan speed (0-255)."""
  3830. return self.set_fan_speed(3, speed)
  3831. def set_airduct_mode(self, mode: str) -> bool:
  3832. """Set air conditioning mode (cooling or heating).
  3833. Args:
  3834. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  3835. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  3836. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  3837. closes top exhaust flap
  3838. Returns:
  3839. True if command was sent, False otherwise
  3840. """
  3841. if not self._client or not self.state.connected:
  3842. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  3843. return False
  3844. self._sequence_id += 1
  3845. mode_id = 0 if mode == "cooling" else 1
  3846. command = {
  3847. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  3848. }
  3849. # Use QoS 1 for reliable delivery
  3850. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3851. logger.info(
  3852. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  3853. )
  3854. return True
  3855. def set_chamber_light(self, on: bool) -> bool:
  3856. """Turn chamber light on or off.
  3857. Args:
  3858. on: True to turn on, False to turn off
  3859. Returns:
  3860. True if command was sent, False otherwise
  3861. """
  3862. if not self._client or not self.state.connected:
  3863. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  3864. return False
  3865. mode = "on" if on else "off"
  3866. # Control both chamber lights (some printers like H2D have two)
  3867. for led_node in ["chamber_light", "chamber_light2"]:
  3868. self._sequence_id += 1
  3869. command = {
  3870. "system": {
  3871. "command": "ledctrl",
  3872. "led_node": led_node,
  3873. "led_mode": mode,
  3874. "led_on_time": 500,
  3875. "led_off_time": 500,
  3876. "loop_times": 0,
  3877. "interval_time": 0,
  3878. "sequence_id": str(self._sequence_id),
  3879. }
  3880. }
  3881. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3882. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  3883. return True
  3884. def select_extruder(self, extruder: int) -> bool:
  3885. """Select the active extruder for dual-nozzle printers (H2D).
  3886. Args:
  3887. extruder: Extruder index (0=right, 1=left for H2D)
  3888. Returns:
  3889. True if command was sent, False otherwise
  3890. """
  3891. if extruder not in (0, 1):
  3892. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  3893. return False
  3894. if not self._client or not self.state.connected:
  3895. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  3896. return False
  3897. # H2D extruder switching via select_extruder command
  3898. # Command format captured from OrcaSlicer:
  3899. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  3900. # extruder_index: 0 = RIGHT, 1 = LEFT
  3901. self._sequence_id += 1
  3902. command = {
  3903. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  3904. }
  3905. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3906. logger.info(
  3907. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  3908. )
  3909. return True
  3910. def home_axes(self, axes: str = "XYZ") -> bool:
  3911. """Run the printer's full auto-home sequence.
  3912. The ``axes`` argument is ignored: a bare ``G28`` is always sent so
  3913. Bambu firmware runs its safe multi-step routine (park toolhead →
  3914. home XY → home Z). Partial-axis variants like ``G28 Z`` skip the
  3915. toolhead-park step and can crash the bed into the toolhead on H2C
  3916. / H2D / H2S / X1 where Z-home moves the bed UP — see #1052.
  3917. """
  3918. return self.send_gcode("G28")
  3919. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  3920. """Move an axis by a relative distance.
  3921. Args:
  3922. axis: Axis to move ("X", "Y", or "Z")
  3923. distance: Distance to move in mm (positive or negative)
  3924. speed: Movement speed in mm/min
  3925. Returns:
  3926. True if command was sent, False otherwise
  3927. """
  3928. axis = axis.upper()
  3929. if axis not in ("X", "Y", "Z"):
  3930. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  3931. return False
  3932. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  3933. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  3934. return self.send_gcode(gcode)
  3935. def disable_motors(self) -> bool:
  3936. """Disable all stepper motors.
  3937. Warning: This will cause the printer to lose its position.
  3938. A homing operation will be required before printing.
  3939. Returns:
  3940. True if command was sent, False otherwise
  3941. """
  3942. return self.send_gcode("M18")
  3943. def enable_motors(self) -> bool:
  3944. """Enable all stepper motors.
  3945. Returns:
  3946. True if command was sent, False otherwise
  3947. """
  3948. return self.send_gcode("M17")
  3949. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  3950. """Load filament from a specific AMS tray.
  3951. Args:
  3952. tray_id: Global tray ID — 0..15 for AMS slots, 254 for external spool
  3953. (single-external printers and Ext-L on dual-nozzle H2D),
  3954. 255 for Ext-R on dual-nozzle H2D.
  3955. extruder_id: Unused - kept for API compatibility
  3956. Returns:
  3957. True if command was sent, False otherwise
  3958. """
  3959. if not self._client or not self.state.connected:
  3960. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  3961. return False
  3962. # Build the ams_change_filament command. Encoding differs by target type:
  3963. # - AMS slots (0..15): slot_id is the local slot, curr/tar_temp = -1.
  3964. # - External spool (tray_id=254): legacy capture from a single-extruder
  3965. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  3966. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  3967. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  3968. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  3969. self._sequence_id += 1
  3970. if tray_id == 255:
  3971. ams_id = 255
  3972. slot_id = 0 # extruder index for the right nozzle
  3973. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  3974. if right_temp < 180:
  3975. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  3976. curr_temp = right_temp
  3977. tar_temp = right_temp
  3978. elif tray_id == 254:
  3979. ams_id = 255
  3980. slot_id = 254
  3981. curr_temp = -1
  3982. tar_temp = -1
  3983. else:
  3984. ams_id = tray_id // 4
  3985. slot_id = tray_id % 4
  3986. curr_temp = -1
  3987. tar_temp = -1
  3988. command = {
  3989. "print": {
  3990. "command": "ams_change_filament",
  3991. "sequence_id": str(self._sequence_id),
  3992. "ams_id": ams_id,
  3993. "slot_id": slot_id,
  3994. "target": tray_id,
  3995. "curr_temp": curr_temp,
  3996. "tar_temp": tar_temp,
  3997. }
  3998. }
  3999. command_json = json.dumps(command)
  4000. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  4001. self._client.publish(self.topic_publish, command_json, qos=1)
  4002. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  4003. # Track this load request for H2D dual-nozzle disambiguation
  4004. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  4005. self._last_load_tray_id = tray_id
  4006. self.state.pending_tray_target = tray_id
  4007. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  4008. return True
  4009. def ams_unload_filament(self) -> bool:
  4010. """Unload the currently loaded filament.
  4011. Returns:
  4012. True if command was sent, False otherwise
  4013. """
  4014. if not self._client or not self.state.connected:
  4015. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  4016. return False
  4017. # Get the currently loaded tray info
  4018. tray_now = self.state.tray_now
  4019. logger.info("[%s] Unload requested, tray_now=%s", self.serial_number, tray_now)
  4020. # Determine source ams_id for the unload command
  4021. if tray_now == 255 or tray_now == 254:
  4022. ams_id = 255 # No filament or external spool
  4023. else:
  4024. ams_id = tray_now // 4 # Source AMS
  4025. # Command format from BambuStudio traffic capture:
  4026. # - No extruder_id field
  4027. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  4028. # - slot_id=255 and target=255 for unload
  4029. # Get current nozzle temperature for the unload command
  4030. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  4031. if nozzle_temp < 180:
  4032. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  4033. self._sequence_id += 1
  4034. command = {
  4035. "print": {
  4036. "command": "ams_change_filament",
  4037. "sequence_id": str(self._sequence_id),
  4038. "ams_id": ams_id,
  4039. "slot_id": 255, # 255 = unload marker
  4040. "target": 255, # 255 = unload destination
  4041. "curr_temp": nozzle_temp,
  4042. "tar_temp": nozzle_temp,
  4043. }
  4044. }
  4045. command_json = json.dumps(command)
  4046. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  4047. self._client.publish(self.topic_publish, command_json, qos=1)
  4048. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  4049. # Clear tracked load request since we're unloading
  4050. self._last_load_tray_id = None
  4051. self.state.pending_tray_target = None
  4052. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  4053. return True
  4054. def ams_control(self, action: str) -> bool:
  4055. """Control AMS operations.
  4056. Args:
  4057. action: "resume", "reset", or "pause"
  4058. Returns:
  4059. True if command was sent, False otherwise
  4060. """
  4061. if not self._client or not self.state.connected:
  4062. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  4063. return False
  4064. if action not in ("resume", "reset", "pause"):
  4065. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  4066. return False
  4067. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  4068. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4069. logger.info("[%s] AMS control: %s", self.serial_number, action)
  4070. return True
  4071. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  4072. """Trigger RFID re-read for a specific AMS tray.
  4073. Args:
  4074. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  4075. tray_id: Tray ID within the AMS (0-3)
  4076. Returns:
  4077. Tuple of (success, message)
  4078. """
  4079. if not self._client or not self.state.connected:
  4080. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  4081. return False, "Printer not connected"
  4082. # Check if filament is currently loaded (tray_now != 255)
  4083. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  4084. tray_now = self.state.tray_now
  4085. if tray_now != 255:
  4086. # Decode which tray is loaded for the message
  4087. if tray_now == 254:
  4088. loaded_tray = "external spool"
  4089. elif tray_now >= 0 and tray_now < 128:
  4090. loaded_ams = tray_now // 4
  4091. loaded_slot = tray_now % 4
  4092. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  4093. else:
  4094. loaded_tray = f"tray {tray_now}"
  4095. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  4096. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  4097. # Use ams_get_rfid command to trigger RFID re-read
  4098. # This command is used by Bambu Studio to re-read the RFID tag
  4099. command = {"print": {"command": "ams_get_rfid", "ams_id": ams_id, "slot_id": tray_id, "sequence_id": "0"}}
  4100. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4101. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  4102. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  4103. def ams_set_filament_setting(
  4104. self,
  4105. ams_id: int,
  4106. tray_id: int,
  4107. tray_info_idx: str,
  4108. tray_type: str,
  4109. tray_sub_brands: str,
  4110. tray_color: str,
  4111. nozzle_temp_min: int,
  4112. nozzle_temp_max: int,
  4113. setting_id: str = "",
  4114. ) -> bool:
  4115. """Set AMS tray filament settings (type, color, temperature).
  4116. Note: K value is set separately via extrusion_cali_sel command.
  4117. Args:
  4118. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4119. tray_id: Tray ID within the AMS (0-3)
  4120. tray_info_idx: Filament ID short format (e.g., "GFL05")
  4121. tray_type: Filament type (e.g., "PLA", "PETG")
  4122. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  4123. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  4124. nozzle_temp_min: Minimum nozzle temperature
  4125. nozzle_temp_max: Maximum nozzle temperature
  4126. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  4127. Returns:
  4128. True if command was sent, False otherwise
  4129. """
  4130. if not self._client or not self.state.connected:
  4131. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  4132. return False
  4133. # Calculate mqtt IDs based on AMS type
  4134. if ams_id == 255:
  4135. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4136. if len(vt_tray) > 1:
  4137. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4138. # (254=ext-L / slot 0, 255=ext-R / slot 1)
  4139. mqtt_ams_id = 254 + tray_id
  4140. else:
  4141. # Single external slot (X1C, P1S, A1): always ams_id=255
  4142. mqtt_ams_id = 255
  4143. mqtt_tray_id = 0
  4144. slot_id = 0
  4145. elif ams_id <= 3:
  4146. mqtt_ams_id = ams_id
  4147. mqtt_tray_id = tray_id
  4148. slot_id = tray_id
  4149. else:
  4150. # AMS-HT: single tray per unit
  4151. mqtt_ams_id = ams_id
  4152. mqtt_tray_id = tray_id
  4153. slot_id = 0
  4154. command = {
  4155. "print": {
  4156. "command": "ams_filament_setting",
  4157. "ams_id": mqtt_ams_id,
  4158. "tray_id": mqtt_tray_id,
  4159. "slot_id": slot_id,
  4160. "tray_info_idx": tray_info_idx,
  4161. "tray_type": tray_type,
  4162. "tray_sub_brands": tray_sub_brands,
  4163. "tray_color": tray_color,
  4164. "nozzle_temp_min": nozzle_temp_min,
  4165. "nozzle_temp_max": nozzle_temp_max,
  4166. "sequence_id": "0",
  4167. }
  4168. }
  4169. # Include setting_id if provided (helps slicer show correct profile)
  4170. if setting_id:
  4171. command["print"]["setting_id"] = setting_id
  4172. command_json = json.dumps(command)
  4173. logger.info(
  4174. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  4175. )
  4176. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  4177. self._client.publish(self.topic_publish, command_json, qos=1)
  4178. self._last_ams_cmd_time = time.monotonic()
  4179. return True
  4180. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  4181. """Reset an AMS slot to empty/unconfigured state.
  4182. Args:
  4183. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4184. tray_id: Tray ID within the AMS (0-3)
  4185. Returns:
  4186. True if command was sent, False otherwise
  4187. """
  4188. if not self._client or not self.state.connected:
  4189. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  4190. return False
  4191. # Calculate mqtt IDs based on AMS type
  4192. if ams_id == 255:
  4193. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4194. if len(vt_tray) > 1:
  4195. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4196. mqtt_ams_id = 254 + tray_id
  4197. else:
  4198. # Single external slot (X1C, P1S, A1): always ams_id=255
  4199. mqtt_ams_id = 255
  4200. mqtt_tray_id = 0
  4201. slot_id = 0
  4202. elif ams_id <= 3:
  4203. mqtt_ams_id = ams_id
  4204. mqtt_tray_id = tray_id
  4205. slot_id = tray_id
  4206. else:
  4207. # AMS-HT: single tray per unit
  4208. mqtt_ams_id = ams_id
  4209. mqtt_tray_id = tray_id
  4210. slot_id = 0
  4211. command = {
  4212. "print": {
  4213. "command": "ams_filament_setting",
  4214. "ams_id": mqtt_ams_id,
  4215. "tray_id": mqtt_tray_id,
  4216. "slot_id": slot_id,
  4217. "tray_info_idx": "",
  4218. "tray_type": "",
  4219. "tray_sub_brands": "",
  4220. "tray_color": "00000000",
  4221. "nozzle_temp_min": 0,
  4222. "nozzle_temp_max": 0,
  4223. "sequence_id": "0",
  4224. }
  4225. }
  4226. command_json = json.dumps(command)
  4227. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  4228. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  4229. self._client.publish(self.topic_publish, command_json, qos=1)
  4230. self._last_ams_cmd_time = time.monotonic()
  4231. return True
  4232. def extrusion_cali_sel(
  4233. self,
  4234. ams_id: int,
  4235. tray_id: int,
  4236. cali_idx: int,
  4237. filament_id: str,
  4238. nozzle_diameter: str = "0.4",
  4239. ) -> bool:
  4240. """Set calibration profile (K value) for an AMS slot.
  4241. This command selects a K profile from the printer's calibration list.
  4242. Use cali_idx=-1 to use the default K value (0.020).
  4243. Note: Do NOT send setting_id in this command — BambuStudio never includes
  4244. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  4245. Args:
  4246. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4247. tray_id: Tray ID within the AMS (0-3)
  4248. cali_idx: Calibration profile index (-1 for default)
  4249. filament_id: Filament preset ID (same as tray_info_idx)
  4250. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  4251. Returns:
  4252. True if command was sent, False otherwise
  4253. """
  4254. if not self._client or not self.state.connected:
  4255. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  4256. return False
  4257. # Calculate mqtt IDs based on AMS type.
  4258. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  4259. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  4260. if ams_id == 255:
  4261. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  4262. # ams_filament_setting which uses LOCAL tray_id=0).
  4263. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4264. if len(vt_tray) > 1:
  4265. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4266. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  4267. mqtt_ams_id = 254 + tray_id
  4268. mqtt_tray_id = 254 + tray_id
  4269. else:
  4270. # Single external slot (X1C, P1S, A1): global tray_id=254
  4271. mqtt_ams_id = 254
  4272. mqtt_tray_id = 254
  4273. slot_id = 0
  4274. elif ams_id <= 3:
  4275. mqtt_ams_id = ams_id
  4276. mqtt_tray_id = ams_id * 4 + tray_id
  4277. slot_id = tray_id
  4278. elif ams_id >= 128 and ams_id <= 135:
  4279. mqtt_ams_id = ams_id
  4280. mqtt_tray_id = tray_id
  4281. slot_id = 0
  4282. else:
  4283. mqtt_ams_id = ams_id
  4284. mqtt_tray_id = tray_id
  4285. slot_id = 0
  4286. command = {
  4287. "print": {
  4288. "command": "extrusion_cali_sel",
  4289. "cali_idx": cali_idx,
  4290. "filament_id": filament_id,
  4291. "nozzle_diameter": nozzle_diameter,
  4292. "ams_id": mqtt_ams_id,
  4293. "tray_id": mqtt_tray_id,
  4294. "slot_id": slot_id,
  4295. "sequence_id": "0",
  4296. }
  4297. }
  4298. command_json = json.dumps(command)
  4299. logger.info(
  4300. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  4301. )
  4302. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  4303. self._client.publish(self.topic_publish, command_json, qos=1)
  4304. return True
  4305. def extrusion_cali_set(
  4306. self,
  4307. tray_id: int,
  4308. k_value: float,
  4309. nozzle_diameter: str = "0.4",
  4310. nozzle_temp: int = 220,
  4311. filament_id: str = "",
  4312. setting_id: str = "",
  4313. name: str = "",
  4314. cali_idx: int = -1,
  4315. ) -> bool:
  4316. """Directly set K value (pressure advance) for a tray.
  4317. Uses the filaments array format required by current firmware.
  4318. Args:
  4319. tray_id: Global tray ID (ams_id * 4 + slot)
  4320. k_value: Pressure advance K value (e.g., 0.020)
  4321. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  4322. nozzle_temp: Nozzle temperature for calibration reference
  4323. filament_id: Filament preset ID (e.g., "GFA02")
  4324. setting_id: Setting ID (e.g., "GFSA02_07")
  4325. name: Profile display name
  4326. cali_idx: Calibration index (-1 for new)
  4327. Returns:
  4328. True if command was sent, False otherwise
  4329. """
  4330. if not self._client or not self.state.connected:
  4331. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  4332. return False
  4333. nozzle_id = f"HS00-{nozzle_diameter}"
  4334. filament_entry = {
  4335. "ams_id": 0,
  4336. "cali_idx": cali_idx,
  4337. "extruder_id": 0,
  4338. "filament_id": filament_id,
  4339. "k_value": f"{k_value:.6f}",
  4340. "n_coef": "1.400000",
  4341. "name": name,
  4342. "nozzle_diameter": nozzle_diameter,
  4343. "nozzle_id": nozzle_id,
  4344. "setting_id": setting_id,
  4345. "tray_id": tray_id,
  4346. }
  4347. command = {
  4348. "print": {
  4349. "command": "extrusion_cali_set",
  4350. "filaments": [filament_entry],
  4351. "nozzle_diameter": nozzle_diameter,
  4352. "sequence_id": str(self._sequence_id),
  4353. }
  4354. }
  4355. command_json = json.dumps(command)
  4356. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  4357. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  4358. self._client.publish(self.topic_publish, command_json, qos=1)
  4359. return True
  4360. def set_timelapse(self, enable: bool) -> bool:
  4361. """Enable or disable timelapse recording.
  4362. Args:
  4363. enable: True to enable, False to disable
  4364. Returns:
  4365. True if command was sent, False otherwise
  4366. """
  4367. if not self._client or not self.state.connected:
  4368. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  4369. return False
  4370. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  4371. # First send the timelapse setting
  4372. timelapse_cmd = {
  4373. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  4374. }
  4375. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  4376. # Request status update
  4377. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4378. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  4379. return True
  4380. def set_liveview(self, enable: bool) -> bool:
  4381. """Enable or disable live view / camera streaming.
  4382. Args:
  4383. enable: True to enable, False to disable
  4384. Returns:
  4385. True if command was sent, False otherwise
  4386. """
  4387. if not self._client or not self.state.connected:
  4388. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  4389. return False
  4390. command = {
  4391. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  4392. }
  4393. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4394. # Request status update
  4395. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  4396. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  4397. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  4398. return True