bambu_mqtt.py 182 KB

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