bambu_mqtt.py 245 KB

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