bambu_mqtt.py 205 KB

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