bambu_mqtt.py 197 KB

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