bambu_mqtt.py 220 KB

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