bambu_mqtt.py 206 KB

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