bambu_mqtt.py 187 KB

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