bambu_mqtt.py 196 KB

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