bambu_mqtt.py 196 KB

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