bambu_mqtt.py 221 KB

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