bambu_mqtt.py 248 KB

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