bambu_mqtt.py 197 KB

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