bambu_mqtt.py 244 KB

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