bambu_mqtt.py 179 KB

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