bambu_mqtt.py 188 KB

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