bambu_mqtt.py 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230
  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. for key, value in new_tray.items():
  1234. # Fields that should always be updated (even with empty/zero values):
  1235. # - remain, k, id, cali_idx: status indicators where 0 is valid
  1236. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  1237. # tray_id_name: slot content indicators that must be cleared
  1238. # when a spool is removed (fixes #147 - old AMS empty slot)
  1239. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  1240. # They are only cleared during spool removal (slot_clearing=True).
  1241. # Periodic AMS updates often include empty RFID fields which
  1242. # would overwrite valid data from the initial pushall.
  1243. always_update_fields = (
  1244. "remain",
  1245. "k",
  1246. "id",
  1247. "cali_idx",
  1248. "tray_type",
  1249. "tray_sub_brands",
  1250. "tray_info_idx",
  1251. "tray_color",
  1252. "tray_id_name",
  1253. )
  1254. if (
  1255. key in always_update_fields
  1256. or slot_clearing
  1257. or value
  1258. not in (
  1259. None,
  1260. "",
  1261. "0000000000000000",
  1262. "00000000000000000000000000000000",
  1263. )
  1264. ):
  1265. merged_tray[key] = value
  1266. merged_trays.append(merged_tray)
  1267. else:
  1268. merged_trays.append(new_tray)
  1269. # Update ams_unit with merged trays
  1270. ams_unit = {**ams_unit, "tray": merged_trays}
  1271. elif existing_unit:
  1272. # Partial update without tray data: merge new fields into existing
  1273. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  1274. ams_unit = {**existing_unit, **ams_unit}
  1275. existing_by_id[ams_id] = ams_unit
  1276. # Convert back to list, sorted by ID for consistent ordering
  1277. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  1278. # Check tray_exist_bits to clear empty slots (Issue #147)
  1279. # New AMS models don't send empty tray data - they just update tray_exist_bits
  1280. # Each bit in tray_exist_bits represents a slot: bit=0 means empty, bit=1 means has spool
  1281. # Skip when power_on_flag=False: printer shutdown sends all-zero bits which would
  1282. # wipe all slot data and cause auto-unlink to remove spool assignments (#765)
  1283. tray_exist_bits_str = ams_data.get("tray_exist_bits") if isinstance(ams_data, dict) else None
  1284. power_on = ams_data.get("power_on_flag", True) if isinstance(ams_data, dict) else True
  1285. if tray_exist_bits_str and power_on:
  1286. try:
  1287. tray_exist_bits = int(tray_exist_bits_str, 16)
  1288. for ams_unit in merged_ams:
  1289. ams_id_raw = ams_unit.get("id")
  1290. if ams_id_raw is None:
  1291. continue
  1292. # Convert to int (may be string from JSON)
  1293. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  1294. if ams_id >= 128: # Skip HT AMS (id >= 128)
  1295. continue
  1296. # Bits for this AMS unit: bits (ams_id*4) to (ams_id*4 + 3)
  1297. for tray in ams_unit.get("tray", []):
  1298. tray_id_raw = tray.get("id")
  1299. if tray_id_raw is None:
  1300. continue
  1301. # Convert to int (may be string from JSON)
  1302. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  1303. global_bit = ams_id * 4 + tray_id
  1304. slot_exists = (tray_exist_bits >> global_bit) & 1
  1305. if not slot_exists and tray.get("tray_type"):
  1306. # Slot is marked empty but has data - clear it
  1307. logger.debug(
  1308. f"[{self.serial_number}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  1309. f"(tray_exist_bits bit {global_bit} = 0)"
  1310. )
  1311. tray["tray_type"] = ""
  1312. tray["tray_sub_brands"] = ""
  1313. tray["tray_color"] = ""
  1314. tray["tray_id_name"] = ""
  1315. tray["tag_uid"] = "0000000000000000"
  1316. tray["tray_uuid"] = "00000000000000000000000000000000"
  1317. tray["tray_info_idx"] = ""
  1318. tray["remain"] = 0
  1319. except (ValueError, TypeError) as e:
  1320. logger.debug("[%s] Could not parse tray_exist_bits: %s", self.serial_number, e)
  1321. self.state.raw_data["ams"] = merged_ams
  1322. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  1323. self._apply_ams_version_cache(merged_ams)
  1324. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  1325. self.state.last_ams_update = time.time()
  1326. logger.debug("[%s] Merged AMS data: %s new units, %s total", self.serial_number, len(ams_list), len(merged_ams))
  1327. # Extract ams_extruder_map from each AMS unit's info field
  1328. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  1329. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  1330. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  1331. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  1332. # extruder_id: 0=right/main, 1=left/deputy, 0xE=uninitialized (skip)
  1333. #
  1334. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  1335. # the full map. Merge into existing map to preserve entries from prior updates.
  1336. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  1337. for ams_unit in merged_ams:
  1338. ams_id = ams_unit.get("id")
  1339. info = ams_unit.get("info")
  1340. if ams_id is not None and info is not None:
  1341. try:
  1342. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  1343. info_val = int(str(info), 16)
  1344. # Extract 4 bits starting at bit 8 for extruder assignment
  1345. extruder_id = (info_val >> 8) & 0xF
  1346. if extruder_id == 0xE:
  1347. # 0xE = uninitialized AMS, skip
  1348. continue
  1349. ams_extruder_map[str(ams_id)] = extruder_id
  1350. logger.debug(f"[{self.serial_number}] AMS {ams_id} info=0x{info} -> extruder {extruder_id}")
  1351. except (ValueError, TypeError):
  1352. pass # Skip AMS units with unparseable info bitmask values
  1353. if ams_extruder_map:
  1354. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  1355. self.state.ams_extruder_map = ams_extruder_map
  1356. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  1357. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  1358. # BambuStudio DevFilaSystem.cpp parses info bits:
  1359. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  1360. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  1361. for ams_unit in merged_ams:
  1362. info = ams_unit.get("info")
  1363. if info is not None:
  1364. try:
  1365. info_val = int(str(info), 16)
  1366. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  1367. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  1368. except (ValueError, TypeError):
  1369. pass # Skip unparseable info values
  1370. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  1371. if "dry_sf_reason" in ams_unit:
  1372. sf_reason = ams_unit["dry_sf_reason"]
  1373. if isinstance(sf_reason, list):
  1374. ams_unit["dry_sf_reason"] = [
  1375. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  1376. ]
  1377. else:
  1378. ams_unit["dry_sf_reason"] = []
  1379. # Persist updated drying fields back to raw_data
  1380. self.state.raw_data["ams"] = merged_ams
  1381. # Create a hash of relevant AMS data to detect changes
  1382. ams_hash_data = []
  1383. for ams_unit in ams_list:
  1384. for tray in ams_unit.get("tray", []):
  1385. # Include fields that matter for filament tracking
  1386. ams_hash_data.append(
  1387. f"{ams_unit.get('id')}:{tray.get('id')}:"
  1388. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  1389. )
  1390. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  1391. # Only trigger callback if AMS data actually changed
  1392. if ams_hash != self._previous_ams_hash:
  1393. self._previous_ams_hash = ams_hash
  1394. if self.on_ams_change:
  1395. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  1396. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  1397. # may lack fields like 'remain' that the merged state preserves
  1398. self.on_ams_change(merged_ams)
  1399. def _update_state(self, data: dict):
  1400. """Update printer state from message data."""
  1401. _previous_state = self.state.state
  1402. # Update state fields
  1403. if "gcode_state" in data:
  1404. self.state.state = data["gcode_state"]
  1405. if "gcode_file" in data:
  1406. self.state.gcode_file = data["gcode_file"]
  1407. self.state.current_print = data["gcode_file"]
  1408. if "subtask_name" in data:
  1409. self.state.subtask_name = data["subtask_name"]
  1410. # Prefer subtask_name as current_print if available
  1411. if data["subtask_name"]:
  1412. self.state.current_print = data["subtask_name"]
  1413. if "subtask_id" in data:
  1414. self.state.subtask_id = data["subtask_id"]
  1415. if "mc_percent" in data:
  1416. # Save last non-zero progress for usage tracking (firmware resets to 0 on cancel)
  1417. if self.state.progress > 0:
  1418. self._last_valid_progress = self.state.progress
  1419. self.state.progress = float(data["mc_percent"])
  1420. if "mc_remaining_time" in data:
  1421. self.state.remaining_time = int(data["mc_remaining_time"])
  1422. if "mc_print_sub_stage" in data:
  1423. new_sub_stage = int(data["mc_print_sub_stage"])
  1424. if new_sub_stage != self.state.mc_print_sub_stage:
  1425. logger.debug(
  1426. f"[{self.serial_number}] mc_print_sub_stage changed: "
  1427. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  1428. )
  1429. self.state.mc_print_sub_stage = new_sub_stage
  1430. if "layer_num" in data:
  1431. new_layer = int(data["layer_num"])
  1432. old_layer = self.state.layer_num
  1433. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  1434. if old_layer > 0:
  1435. self._last_valid_layer_num = old_layer
  1436. self.state.layer_num = new_layer
  1437. # Trigger layer change callback if layer increased
  1438. if new_layer > old_layer and self.on_layer_change:
  1439. self.on_layer_change(new_layer)
  1440. if "total_layer_num" in data:
  1441. self.state.total_layers = int(data["total_layer_num"])
  1442. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  1443. # Convert to 0-100 percentage for display
  1444. def parse_fan_speed(value: str | int | None) -> int | None:
  1445. if value is None:
  1446. return None
  1447. try:
  1448. speed = int(value)
  1449. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  1450. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  1451. if speed <= 15:
  1452. return round(speed * 100 / 15)
  1453. # If already a percentage (0-255 scale from some printers), convert
  1454. elif speed <= 255:
  1455. return round(speed * 100 / 255)
  1456. return speed
  1457. except (ValueError, TypeError):
  1458. return None
  1459. # Log fan fields once for debugging
  1460. if not hasattr(self, "_fan_fields_logged"):
  1461. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  1462. if fan_fields:
  1463. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  1464. self._fan_fields_logged = True
  1465. if "cooling_fan_speed" in data:
  1466. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  1467. if "big_fan1_speed" in data:
  1468. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  1469. if "big_fan2_speed" in data:
  1470. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  1471. if "heatbreak_fan_speed" in data:
  1472. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  1473. # Calibration stage tracking
  1474. if "stg_cur" in data:
  1475. new_stg = data["stg_cur"]
  1476. # Always log ANY stg_cur change for debugging filament operations
  1477. if new_stg != self.state.stg_cur:
  1478. logger.debug(
  1479. f"[{self.serial_number}] stg_cur changed: {self.state.stg_cur} -> {new_stg} ({get_stage_name(new_stg)})"
  1480. )
  1481. self.state.stg_cur = new_stg
  1482. if "stg" in data:
  1483. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  1484. # Temperature data
  1485. temps = {}
  1486. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  1487. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  1488. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  1489. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  1490. # Log ALL keys in print data for H2D temperature discovery
  1491. all_keys = sorted(data.keys())
  1492. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  1493. self._temp_fields_logged = True
  1494. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  1495. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  1496. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  1497. self._vir_slot_logged = True
  1498. # Log nozzle hardware info fields (once)
  1499. nozzle_fields = {
  1500. k: v
  1501. for k, v in data.items()
  1502. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  1503. }
  1504. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  1505. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  1506. self._nozzle_fields_logged = True
  1507. # Parse active extruder from device.extruder.state bit 8
  1508. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  1509. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  1510. if "device" in data and isinstance(data.get("device"), dict):
  1511. device = data["device"]
  1512. if "extruder" in device and "state" in device["extruder"]:
  1513. state_val = device["extruder"]["state"]
  1514. # Extract bit 8 for extruder position
  1515. new_extruder = (state_val >> 8) & 0x1
  1516. if new_extruder != self.state.active_extruder:
  1517. logger.debug(
  1518. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  1519. )
  1520. self.state.active_extruder = new_extruder
  1521. # Log device.extruder structure for active extruder
  1522. if "device" in data and isinstance(data.get("device"), dict):
  1523. device = data["device"]
  1524. if "extruder" in device:
  1525. ext_data = device["extruder"]
  1526. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  1527. if "state" in ext_data:
  1528. state_val = ext_data["state"]
  1529. # Extract bits 12-14 (3 bits) for switch state
  1530. switch_state = (state_val >> 12) & 0x7
  1531. logger.debug(
  1532. f"[{self.serial_number}] device.extruder.state={state_val} (switch_state bits 12-14: {switch_state})"
  1533. )
  1534. # Log 'cur' field if present (might indicate current/active extruder)
  1535. if "cur" in ext_data:
  1536. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  1537. if "bed_temper" in data:
  1538. temps["bed"] = float(data["bed_temper"])
  1539. if "bed_target_temper" in data:
  1540. temps["bed_target"] = float(data["bed_target_temper"])
  1541. # Check if this is H2D (has device.extruder.info with 2 extruders)
  1542. has_h2d_extruder_info = (
  1543. "device" in data
  1544. and isinstance(data.get("device"), dict)
  1545. and "extruder" in data["device"]
  1546. and isinstance(data["device"]["extruder"].get("info"), list)
  1547. and len(data["device"]["extruder"]["info"]) >= 2
  1548. )
  1549. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  1550. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  1551. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  1552. if "nozzle_temper" in data:
  1553. if has_h2d_extruder_info:
  1554. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  1555. else:
  1556. temps["nozzle"] = float(data["nozzle_temper"])
  1557. if "nozzle_target_temper" in data:
  1558. if has_h2d_extruder_info:
  1559. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  1560. else:
  1561. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  1562. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  1563. if not has_h2d_extruder_info:
  1564. # Try multiple possible field names used by different firmware versions
  1565. if "nozzle_temper_2" in data:
  1566. val = float(data["nozzle_temper_2"])
  1567. if -50 < val < 500: # Valid temp range
  1568. temps["nozzle_2"] = val
  1569. else:
  1570. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  1571. elif "right_nozzle_temper" in data:
  1572. val = float(data["right_nozzle_temper"])
  1573. if -50 < val < 500: # Valid temp range
  1574. temps["nozzle_2"] = val
  1575. else:
  1576. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  1577. if "nozzle_target_temper_2" in data:
  1578. val = float(data["nozzle_target_temper_2"])
  1579. if 0 <= val < 500: # Valid temp range
  1580. temps["nozzle_2_target"] = val
  1581. else:
  1582. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  1583. elif "right_nozzle_target_temper" in data:
  1584. val = float(data["right_nozzle_target_temper"])
  1585. if 0 <= val < 500: # Valid temp range
  1586. temps["nozzle_2_target"] = val
  1587. else:
  1588. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  1589. # Also check for left nozzle as primary (some H2 models)
  1590. if "left_nozzle_temper" in data and "nozzle" not in temps:
  1591. temps["nozzle"] = float(data["left_nozzle_temper"])
  1592. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  1593. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  1594. if "chamber_temper" in data:
  1595. chamber_val = float(data["chamber_temper"])
  1596. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  1597. # Check if we recently set the target locally (within 5 seconds)
  1598. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  1599. respect_local = (time.time() - local_set_time) < 5.0
  1600. # H2D protocol: chamber_temper encoding indicates heater state
  1601. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  1602. # - When < 500: direct Celsius current temp only - heater is OFF
  1603. if -50 < chamber_val < 100:
  1604. # Direct value = heater is OFF
  1605. temps["chamber"] = chamber_val
  1606. if not respect_local:
  1607. temps["chamber_target"] = 0.0 # Heater off means target = 0
  1608. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  1609. else:
  1610. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  1611. # Try to decode if it looks like an encoded value
  1612. if chamber_val > 500:
  1613. mqtt_target = int(chamber_val) // 65536
  1614. current = int(chamber_val) % 65536
  1615. logger.debug(
  1616. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  1617. )
  1618. if -50 < current < 100:
  1619. temps["chamber"] = float(current)
  1620. # Store decoded target for later use, but DON'T set chamber_heating here!
  1621. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  1622. # which is the authoritative source the slicer uses.
  1623. if not respect_local:
  1624. if 0 <= mqtt_target <= 60:
  1625. # Store as "decoded" target - may be overridden by explicit target fields
  1626. temps["_chamber_decoded_target"] = float(mqtt_target)
  1627. # Chamber target temperature (set by print file or display)
  1628. if "mc_target_cham" in data:
  1629. mc_target = float(data["mc_target_cham"])
  1630. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  1631. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  1632. if 0 <= mc_target <= 60:
  1633. temps["chamber_target"] = mc_target
  1634. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  1635. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  1636. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  1637. try:
  1638. if "info" in data and isinstance(data["info"], dict):
  1639. info_temp = data["info"].get("temp")
  1640. if info_temp is not None and "chamber" not in temps:
  1641. # Check for encoded value (target * 65536 + current)
  1642. if info_temp > 500:
  1643. # Decode: extract current temperature and target
  1644. target = info_temp // 65536
  1645. current = info_temp % 65536
  1646. temps["chamber"] = float(current)
  1647. # Store decoded target as fallback (may be overridden by ctc.info.target)
  1648. if "_chamber_decoded_target" not in temps:
  1649. temps["_chamber_decoded_target"] = float(target)
  1650. logger.debug(
  1651. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  1652. )
  1653. elif -50 < info_temp < 100:
  1654. # Valid direct temperature - heater is OFF
  1655. temps["chamber"] = float(info_temp)
  1656. temps["chamber_target"] = 0.0 # Direct value means heater off
  1657. logger.debug("[%s] info.temp direct: %s°C (heater OFF)", self.serial_number, info_temp)
  1658. # H2D series: Dual extruder temps are in device.extruder.info array
  1659. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  1660. if "device" in data and isinstance(data["device"], dict):
  1661. device = data["device"]
  1662. # Parse dual extruder temperatures
  1663. extruder_data = device.get("extruder", {})
  1664. extruder_info = extruder_data.get("info", [])
  1665. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  1666. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  1667. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  1668. # has_h2d_extruder_info requires len(extruder_info) >= 2
  1669. if has_h2d_extruder_info:
  1670. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  1671. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  1672. if "temp" in extruder_info[0]:
  1673. temp_val = extruder_info[0]["temp"]
  1674. if temp_val > 500:
  1675. # Encoded format: temp = target * 65536 + current
  1676. target = temp_val // 65536
  1677. current = temp_val % 65536
  1678. if -50 < current < 500:
  1679. temps["nozzle_2"] = float(current)
  1680. if 0 < target < 500:
  1681. temps["nozzle_2_target"] = float(target)
  1682. temps["nozzle_2_heating"] = target > 0 and current < target
  1683. elif -50 < temp_val < 500:
  1684. # Direct Celsius value = heater is OFF
  1685. temps["nozzle_2"] = float(temp_val)
  1686. temps["nozzle_2_target"] = 0.0
  1687. temps["nozzle_2_heating"] = False
  1688. # Left nozzle (extruder 1) - only for dual nozzle printers
  1689. # H2D protocol: temp field encoding depends on value
  1690. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  1691. # - When < 500: direct Celsius current temp only - heater is OFF
  1692. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  1693. ext1 = extruder_info[1]
  1694. temp_val = ext1["temp"]
  1695. # Check if we recently set the target locally (within 5 seconds)
  1696. # If so, don't let MQTT data overwrite it
  1697. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  1698. respect_local_target = (time.time() - local_set_time) < 5.0
  1699. if temp_val > 500:
  1700. # Encoded format: temp = target * 65536 + current
  1701. target = temp_val // 65536
  1702. current = temp_val % 65536
  1703. if 0 < target < 500 and not respect_local_target:
  1704. temps["nozzle_target"] = float(target)
  1705. if -50 < current < 500:
  1706. temps["nozzle"] = float(current)
  1707. # Heating = encoded AND we're using the MQTT target (not local override)
  1708. # If local target is being respected, use local target to determine heating
  1709. if respect_local_target:
  1710. local_target = self.state.temperatures.get("nozzle_target", 0)
  1711. temps["nozzle_heating"] = local_target > 0 and current < local_target
  1712. else:
  1713. temps["nozzle_heating"] = target > 0 and current < target
  1714. elif -50 < temp_val < 500:
  1715. # Direct Celsius = heater is OFF (or at target with heater off)
  1716. temps["nozzle"] = float(temp_val)
  1717. if not respect_local_target:
  1718. temps["nozzle_target"] = 0.0
  1719. temps["nozzle_heating"] = False # Direct = not heating
  1720. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  1721. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  1722. if has_h2d_extruder_info:
  1723. for ext_info in extruder_info:
  1724. ext_id = ext_info.get("id")
  1725. snow = ext_info.get("snow")
  1726. if ext_id is not None and snow is not None and ext_id <= 1:
  1727. # Normalize H2D snow value to global tray ID
  1728. ams_id = snow >> 8
  1729. slot = snow & 0xFF
  1730. if 0 <= ams_id <= 3:
  1731. # Regular AMS slot
  1732. global_tray = ams_id * 4 + (slot & 0x03)
  1733. old_val = self.state.h2d_extruder_snow.get(ext_id)
  1734. if old_val != global_tray:
  1735. logger.debug(
  1736. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  1737. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  1738. )
  1739. self.state.h2d_extruder_snow[ext_id] = global_tray
  1740. elif ams_id == 254 or ams_id == 255:
  1741. # External spool or unloaded
  1742. normalized = 254 if slot != 255 else 255
  1743. old_val = self.state.h2d_extruder_snow.get(ext_id)
  1744. if old_val != normalized:
  1745. logger.debug(
  1746. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  1747. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  1748. )
  1749. self.state.h2d_extruder_snow[ext_id] = normalized
  1750. elif 128 <= ams_id <= 135:
  1751. # External spool with hub mapping
  1752. old_val = self.state.h2d_extruder_snow.get(ext_id)
  1753. if old_val != ams_id:
  1754. logger.debug(
  1755. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  1756. f"raw={snow} -> external hub {ams_id}"
  1757. )
  1758. self.state.h2d_extruder_snow[ext_id] = ams_id
  1759. # Parse bed heating state from device.bed.info.temp encoding
  1760. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  1761. bed_data = device.get("bed", {})
  1762. bed_info = bed_data.get("info", {})
  1763. if "temp" in bed_info:
  1764. temp_val = bed_info["temp"]
  1765. if temp_val > 500:
  1766. target = temp_val // 65536
  1767. current = temp_val % 65536
  1768. temps["bed_heating"] = target > 0 and current < target
  1769. else:
  1770. temps["bed_heating"] = False
  1771. # Parse chamber temp from device.ctc.info.temp if not already set
  1772. ctc_data = device.get("ctc", {})
  1773. ctc_info = ctc_data.get("info", {})
  1774. # Parse airduct mode (0=cooling, 1=heating)
  1775. airduct_data = device.get("airduct", {})
  1776. if "modeCur" in airduct_data:
  1777. new_mode = airduct_data["modeCur"]
  1778. if new_mode != self.state.airduct_mode:
  1779. logger.debug(
  1780. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  1781. )
  1782. self.state.airduct_mode = new_mode
  1783. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  1784. # Check if we recently set the target locally (within 5 seconds)
  1785. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  1786. respect_local_target = (time.time() - local_set_time) < 5.0
  1787. # Log ctc_info contents for debugging
  1788. if ctc_info:
  1789. logger.debug("[%s] ctc_info keys: %s", self.serial_number, list(ctc_info.keys()))
  1790. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  1791. # (what the slicer shows). This OVERRIDES any previously decoded target.
  1792. explicit_target = None
  1793. if "target" in ctc_info:
  1794. target_val = ctc_info["target"]
  1795. logger.debug(
  1796. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  1797. )
  1798. # Filter out invalid values (valid chamber target is 0-60°C)
  1799. if 0 <= target_val <= 60 and not respect_local_target:
  1800. explicit_target = float(target_val)
  1801. temps["chamber_target"] = explicit_target # Override any previous value
  1802. logger.debug(
  1803. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  1804. )
  1805. # Parse chamber temp from ctc.info.temp - may be encoded
  1806. if "temp" in ctc_info and "chamber" not in temps:
  1807. temp_val = ctc_info["temp"]
  1808. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  1809. if temp_val > 500:
  1810. # Encoded value: decode target and current
  1811. decoded_target = temp_val // 65536
  1812. current = temp_val % 65536
  1813. temps["chamber"] = float(current)
  1814. logger.debug(
  1815. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  1816. )
  1817. # Determine which target to use for heating state:
  1818. # Priority: local target > explicit target > decoded target
  1819. if respect_local_target:
  1820. local_target = self.state.temperatures.get("chamber_target", 0)
  1821. temps["chamber_heating"] = local_target > 0 and current < local_target
  1822. elif explicit_target is not None:
  1823. # Use explicit ctc.info.target - this is what slicer sees
  1824. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  1825. else:
  1826. # Fallback to decoded target only if no explicit target available
  1827. if not respect_local_target and "chamber_target" not in temps:
  1828. temps["chamber_target"] = float(decoded_target)
  1829. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  1830. else:
  1831. # Direct value (not encoded) - heater is OFF
  1832. temps["chamber"] = float(temp_val)
  1833. temps["chamber_heating"] = False
  1834. except Exception as e:
  1835. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  1836. if temps:
  1837. # Handle chamber_target: prefer explicit over decoded
  1838. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  1839. # No explicit target available, use decoded target from chamber_temper
  1840. temps["chamber_target"] = temps["_chamber_decoded_target"]
  1841. # Remove internal temp key before merging
  1842. temps.pop("_chamber_decoded_target", None)
  1843. # Merge new temps into existing, preserving valid values when new ones are filtered out
  1844. for key, value in temps.items():
  1845. self.state.temperatures[key] = value
  1846. # Calculate chamber_heating after all targets are known
  1847. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  1848. if "chamber" in temps and "chamber_heating" not in temps:
  1849. current = self.state.temperatures.get("chamber", 0)
  1850. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  1851. respect_local = (time.time() - local_set_time) < 5.0
  1852. if respect_local:
  1853. # Use locally-set target
  1854. target = self.state.temperatures.get("chamber_target", 0)
  1855. else:
  1856. # Use explicit/decoded target from MQTT
  1857. target = self.state.temperatures.get("chamber_target", 0)
  1858. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  1859. logger.debug(
  1860. f"[{self.serial_number}] Chamber heating calculated: target={target}, current={current}, heating={self.state.temperatures['chamber_heating']}, respect_local={respect_local}"
  1861. )
  1862. # Debug: log chamber value if it was updated
  1863. if "chamber" in temps:
  1864. logger.debug(
  1865. 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')}"
  1866. )
  1867. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  1868. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  1869. if "nozzle" in temps and "nozzle_heating" not in temps:
  1870. current = self.state.temperatures.get("nozzle", 0)
  1871. target = self.state.temperatures.get("nozzle_target", 0)
  1872. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  1873. # Parse HMS (Health Management System) errors
  1874. if "hms" in data:
  1875. hms_list = data["hms"]
  1876. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  1877. self.state.hms_errors = []
  1878. if isinstance(hms_list, list):
  1879. for hms in hms_list:
  1880. if isinstance(hms, dict):
  1881. # HMS format: {"attr": attribute_code, "code": error_code}
  1882. # attr contains module/severity info, code contains error number
  1883. # Both are needed to construct the wiki URL
  1884. attr = hms.get("attr", 0)
  1885. code = hms.get("code", 0)
  1886. if isinstance(attr, str):
  1887. attr = int(attr.replace("0x", ""), 16) if attr else 0
  1888. if isinstance(code, str):
  1889. code = int(code.replace("0x", ""), 16) if code else 0
  1890. # Severity is in attr byte 1 (bits 8-15)
  1891. severity = (attr >> 8) & 0xF
  1892. # Module is in attr byte 3 (bits 24-31)
  1893. module = (attr >> 24) & 0xFF
  1894. # Skip non-error status codes — all real HMS errors
  1895. # have code >= 0x4000. Lower values are status/phase
  1896. # indicators that some firmware sends during normal printing.
  1897. if code < 0x4000:
  1898. continue
  1899. self.state.hms_errors.append(
  1900. HMSError(
  1901. code=f"0x{code:x}" if code else "0x0",
  1902. attr=attr,
  1903. module=module,
  1904. severity=severity if severity > 0 else 2,
  1905. )
  1906. )
  1907. # Parse print_error - this is a different error format than HMS
  1908. # print_error is a 32-bit integer where:
  1909. # - High 16 bits contain module info (e.g., 0x0500)
  1910. # - Low 16 bits contain error code (e.g., 0x8061)
  1911. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  1912. if "print_error" in data:
  1913. print_error = data["print_error"]
  1914. if print_error and print_error != 0:
  1915. # Extract components: MMMMEEEE -> MMMM_EEEE
  1916. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  1917. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  1918. # Values below 0x4000 are status/phase indicators, not real errors.
  1919. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  1920. # Some firmware sends low values like 0x0002 during normal printing.
  1921. if error < 0x4000:
  1922. pass # Skip — not a real error
  1923. else:
  1924. # Store in a format that matches the community error database
  1925. # attr stores the full 32-bit value for reconstruction
  1926. # code stores the short format string for lookup
  1927. short_code = f"{module:04X}_{error:04X}"
  1928. logger.debug(
  1929. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  1930. )
  1931. # Only add if not already in HMS errors (avoid duplicates)
  1932. existing_short_codes = set()
  1933. for e in self.state.hms_errors:
  1934. # Extract short code from existing errors
  1935. e_module = (e.attr >> 16) & 0xFFFF
  1936. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  1937. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  1938. if short_code not in existing_short_codes:
  1939. self.state.hms_errors.append(
  1940. HMSError(
  1941. code=f"0x{error:x}",
  1942. attr=print_error, # Store full value for display
  1943. module=module >> 8, # High byte of module (e.g., 0x05)
  1944. severity=3, # Warning level for print_error
  1945. )
  1946. )
  1947. # Parse SD card status
  1948. if "sdcard" in data:
  1949. self.state.sdcard = data["sdcard"] is True
  1950. # Parse home_flag for "Store Sent Files on External Storage" setting (bit 11)
  1951. if "home_flag" in data:
  1952. home_flag = data["home_flag"]
  1953. # Bit 11 controls "Store Sent Files on External Storage"
  1954. # Convert to unsigned 32-bit if negative
  1955. if home_flag < 0:
  1956. home_flag = home_flag & 0xFFFFFFFF
  1957. store_to_sdcard = bool((home_flag >> 11) & 1)
  1958. if store_to_sdcard != self.state.store_to_sdcard:
  1959. logger.debug(
  1960. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  1961. )
  1962. self.state.store_to_sdcard = store_to_sdcard
  1963. # Parse timelapse status (recording active during print)
  1964. if "timelapse" in data:
  1965. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  1966. self.state.timelapse = data["timelapse"] is True
  1967. # Track if timelapse was ever active during this print
  1968. if self.state.timelapse and self._was_running:
  1969. self._timelapse_during_print = True
  1970. # Parse ipcam/live view status
  1971. if "ipcam" in data:
  1972. ipcam_data = data["ipcam"]
  1973. logger.debug("[%s] ipcam field: %s", self.serial_number, ipcam_data)
  1974. if isinstance(ipcam_data, dict):
  1975. # Check ipcam_record field for live view status
  1976. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  1977. # Check timelapse field (H2D sends it here, not in xcam)
  1978. if "timelapse" in ipcam_data:
  1979. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  1980. if timelapse_enabled != self.state.timelapse:
  1981. logger.debug(
  1982. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  1983. )
  1984. self.state.timelapse = timelapse_enabled
  1985. # Track if timelapse was ever active during this print
  1986. if self.state.timelapse and self._was_running:
  1987. self._timelapse_during_print = True
  1988. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  1989. else:
  1990. self.state.ipcam = ipcam_data is True
  1991. # Parse WiFi signal strength (dBm)
  1992. if "wifi_signal" in data:
  1993. wifi_signal = data["wifi_signal"]
  1994. logger.debug("[%s] wifi_signal received: %s", self.serial_number, wifi_signal)
  1995. if isinstance(wifi_signal, (int, float)):
  1996. self.state.wifi_signal = int(wifi_signal)
  1997. elif isinstance(wifi_signal, str):
  1998. # Handle string format like "-52dBm"
  1999. try:
  2000. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2001. except ValueError:
  2002. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2003. # Detect ethernet connection: printers on ethernet with WiFi disabled
  2004. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  2005. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  2006. from backend.app.utils.printer_models import has_ethernet
  2007. if has_ethernet(self.model):
  2008. self.state.wired_network = self.state.wifi_signal == -90
  2009. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  2010. if "spd_lvl" in data:
  2011. new_speed = data["spd_lvl"]
  2012. if new_speed != self.state.speed_level:
  2013. logger.debug(
  2014. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  2015. )
  2016. self.state.speed_level = new_speed
  2017. # Parse skipped objects from printer status (s_obj field)
  2018. # This allows us to restore skipped objects state after reconnection
  2019. if "s_obj" in data:
  2020. s_obj = data["s_obj"]
  2021. if isinstance(s_obj, list):
  2022. # Update skipped objects from printer's list
  2023. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  2024. if new_skipped != self.state.skipped_objects:
  2025. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  2026. self.state.skipped_objects = new_skipped
  2027. # Parse chamber light status from lights_report
  2028. if "lights_report" in data:
  2029. lights = data["lights_report"]
  2030. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  2031. if isinstance(lights, list):
  2032. for light in lights:
  2033. if isinstance(light, dict) and light.get("node") == "chamber_light":
  2034. new_light_state = light.get("mode") == "on"
  2035. if new_light_state != self.state.chamber_light:
  2036. logger.debug(
  2037. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  2038. )
  2039. self.state.chamber_light = new_light_state
  2040. break
  2041. # Parse nozzle hardware info (single nozzle printers)
  2042. if "nozzle_type" in data:
  2043. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  2044. if "nozzle_diameter" in data:
  2045. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  2046. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  2047. # Left nozzle
  2048. if "left_nozzle_type" in data:
  2049. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  2050. if "left_nozzle_diameter" in data:
  2051. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  2052. # Right nozzle
  2053. if "right_nozzle_type" in data:
  2054. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  2055. if "right_nozzle_diameter" in data:
  2056. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  2057. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  2058. if "nozzle_type_2" in data:
  2059. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  2060. if "nozzle_diameter_2" in data:
  2061. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  2062. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  2063. if "device" in data and isinstance(data["device"], dict):
  2064. device = data["device"]
  2065. nozzle_data = device.get("nozzle", {})
  2066. nozzle_info = nozzle_data.get("info", [])
  2067. if isinstance(nozzle_info, list):
  2068. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  2069. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  2070. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  2071. # for hover cards on both the L/R indicator and the nozzle rack card.
  2072. if nozzle_info:
  2073. self.state.nozzle_rack = sorted(
  2074. [
  2075. {
  2076. "id": n.get("id", i),
  2077. "type": str(n.get("type", "")),
  2078. "diameter": str(n.get("diameter", "")),
  2079. "wear": n.get("wear"),
  2080. "stat": n.get("stat"),
  2081. # H2C uses "tm", H2D uses "max_temp"
  2082. "max_temp": n.get("max_temp") or n.get("tm", 0),
  2083. # H2C uses "sn", H2D uses "serial_number"
  2084. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  2085. # H2C uses "color_m", H2D uses "filament_colour"
  2086. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  2087. # H2C uses "fila_id", H2D uses "filament_id"
  2088. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  2089. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  2090. }
  2091. for i, n in enumerate(nozzle_info)
  2092. ],
  2093. key=lambda x: x["id"],
  2094. )
  2095. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  2096. self._nozzle_rack_logged = True
  2097. logger.debug(
  2098. "[%s] Nozzle info: %d entries, IDs: %s",
  2099. self.serial_number,
  2100. len(nozzle_info),
  2101. [n.get("id") for n in nozzle_info],
  2102. )
  2103. for nozzle in nozzle_info:
  2104. idx = nozzle.get("id", 0)
  2105. if idx < len(self.state.nozzles):
  2106. if "type" in nozzle and nozzle["type"]:
  2107. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  2108. if "diameter" in nozzle:
  2109. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  2110. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  2111. # (these fields aren't sent in every MQTT push, only when changed)
  2112. ams_data = self.state.raw_data.get("ams")
  2113. vt_tray_data = self.state.raw_data.get("vt_tray")
  2114. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  2115. mapping_data = self.state.raw_data.get("mapping")
  2116. self.state.raw_data = data
  2117. # Parse developer LAN mode from "fun" field
  2118. if "fun" in data:
  2119. try:
  2120. fun_val = data["fun"]
  2121. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2122. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2123. except (ValueError, TypeError):
  2124. pass
  2125. if ams_data is not None:
  2126. self.state.raw_data["ams"] = ams_data
  2127. if vt_tray_data is not None:
  2128. self.state.raw_data["vt_tray"] = vt_tray_data
  2129. if ams_extruder_map_data is not None:
  2130. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  2131. if mapping_data is not None and "mapping" not in data:
  2132. self.state.raw_data["mapping"] = mapping_data
  2133. # Log mapping data when received (for usage tracking debugging)
  2134. if "mapping" in data:
  2135. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  2136. # Log state transitions for debugging
  2137. if "gcode_state" in data:
  2138. logger.debug(
  2139. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  2140. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  2141. )
  2142. # Detect print start (state changes TO RUNNING with a file)
  2143. current_file = self.state.gcode_file or self.state.current_print
  2144. is_new_print = (
  2145. self.state.state == "RUNNING"
  2146. and self._previous_gcode_state != "RUNNING"
  2147. and current_file
  2148. and not self._was_running # Prevent duplicates when resuming from PAUSE
  2149. )
  2150. # Also detect if file changed while running (new print started)
  2151. is_file_change = (
  2152. self.state.state == "RUNNING"
  2153. and current_file
  2154. and current_file != self._previous_gcode_file
  2155. and self._previous_gcode_file is not None
  2156. )
  2157. # Track RUNNING state for more robust completion detection
  2158. if self.state.state == "RUNNING" and current_file:
  2159. if not self._was_running:
  2160. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  2161. # Check if timelapse was enabled in the same message (xcam parsed before this)
  2162. if self.state.timelapse:
  2163. self._timelapse_during_print = True
  2164. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  2165. self._was_running = True
  2166. self._completion_triggered = False
  2167. if is_new_print or is_file_change:
  2168. # Clear any old HMS errors when a new print starts
  2169. self.state.hms_errors = []
  2170. # Reset layer tracking for new print (needed for layer-based timelapse)
  2171. self.state.layer_num = 0
  2172. # Reset completion tracking for new print
  2173. self._was_running = True
  2174. self._completion_triggered = False
  2175. # Reset last valid progress/layer for usage tracking
  2176. self._last_valid_progress = 0.0
  2177. self._last_valid_layer_num = 0
  2178. # Clear and seed tray change log for mid-print usage splitting
  2179. self.state.tray_change_log.clear()
  2180. tn = self.state.tray_now
  2181. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  2182. self.state.tray_change_log.append((tn, 0))
  2183. # Initialize timelapse tracking based on current state
  2184. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  2185. # so self.state.timelapse may already be set from this message.
  2186. # We preserve that value instead of blindly resetting to False.
  2187. if self.state.timelapse:
  2188. self._timelapse_during_print = True
  2189. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  2190. else:
  2191. self._timelapse_during_print = False
  2192. if (is_new_print or is_file_change) and self.on_print_start:
  2193. logger.info(
  2194. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  2195. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  2196. )
  2197. self.on_print_start(
  2198. {
  2199. "filename": current_file,
  2200. "subtask_name": self.state.subtask_name,
  2201. "remaining_time": self.state.remaining_time * 60
  2202. if self.state.remaining_time > 0
  2203. else None, # Convert minutes to seconds
  2204. "raw_data": data,
  2205. "ams_mapping": self._captured_ams_mapping,
  2206. }
  2207. )
  2208. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  2209. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  2210. # This handles cases where server restarts during a print
  2211. should_trigger_completion = (
  2212. self.state.state in ("FINISH", "FAILED")
  2213. and not self._completion_triggered
  2214. and self.on_print_complete
  2215. and (
  2216. self._previous_gcode_state == "RUNNING" # Normal transition
  2217. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  2218. )
  2219. )
  2220. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  2221. if (
  2222. self.state.state == "IDLE"
  2223. and self._previous_gcode_state == "RUNNING"
  2224. and not self._completion_triggered
  2225. and self.on_print_complete
  2226. ):
  2227. should_trigger_completion = True
  2228. # Log when we see a terminal state but DON'T trigger completion (diagnostics)
  2229. if not should_trigger_completion and self.state.state in ("FINISH", "FAILED"):
  2230. logger.info(
  2231. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  2232. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  2233. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  2234. )
  2235. if should_trigger_completion:
  2236. if self.state.state == "FINISH":
  2237. status = "completed"
  2238. elif self.state.state == "FAILED":
  2239. status = "failed"
  2240. else:
  2241. status = "aborted"
  2242. logger.info(
  2243. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  2244. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  2245. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  2246. f"timelapse_during_print: {self._timelapse_during_print}"
  2247. )
  2248. timelapse_was_active = self._timelapse_during_print
  2249. self._completion_triggered = True
  2250. self._was_running = False
  2251. self._timelapse_during_print = False # Reset for next print
  2252. # Include HMS errors for failure reason detection
  2253. hms_errors_data = (
  2254. [
  2255. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  2256. for e in self.state.hms_errors
  2257. ]
  2258. if self.state.hms_errors
  2259. else []
  2260. )
  2261. self.on_print_complete(
  2262. {
  2263. "status": status,
  2264. "filename": self._previous_gcode_file or current_file,
  2265. "subtask_name": self.state.subtask_name,
  2266. "raw_data": data,
  2267. "timelapse_was_active": timelapse_was_active,
  2268. "hms_errors": hms_errors_data,
  2269. "ams_mapping": self._captured_ams_mapping,
  2270. # Last valid progress/layer before firmware reset (for partial usage tracking)
  2271. "last_progress": self._last_valid_progress,
  2272. "last_layer_num": self._last_valid_layer_num,
  2273. }
  2274. )
  2275. self._captured_ams_mapping = None
  2276. self._previous_gcode_state = self.state.state
  2277. if current_file:
  2278. self._previous_gcode_file = current_file
  2279. if self.on_state_change:
  2280. self.on_state_change(self.state)
  2281. def _request_push_all(self):
  2282. """Request full status update from printer."""
  2283. if self._client:
  2284. message = {"pushing": {"command": "pushall"}}
  2285. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  2286. def _request_version(self):
  2287. """Request firmware version info from printer."""
  2288. if self._client:
  2289. self._sequence_id += 1
  2290. message = {
  2291. "info": {
  2292. "sequence_id": str(self._sequence_id),
  2293. "command": "get_version",
  2294. }
  2295. }
  2296. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  2297. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  2298. def request_status_update(self) -> bool:
  2299. """Request a full status update from the printer (public API).
  2300. Sends both pushall and get_accessories commands to refresh all data
  2301. including nozzle hardware info.
  2302. Returns:
  2303. True if the request was sent, False if not connected.
  2304. """
  2305. if not self._client or not self.state.connected:
  2306. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  2307. return False
  2308. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  2309. self._request_push_all()
  2310. # Note: get_accessories returns stale nozzle data on H2D.
  2311. # The correct nozzle data comes from push_status response.
  2312. return True
  2313. def _request_accessories(self):
  2314. """Request accessories info (nozzle type, etc.) from printer."""
  2315. if self._client:
  2316. self._sequence_id += 1
  2317. message = {
  2318. "system": {
  2319. "sequence_id": str(self._sequence_id),
  2320. "command": "get_accessories",
  2321. "accessory_type": "none",
  2322. }
  2323. }
  2324. logger.debug("[%s] Requesting accessories info", self.serial_number)
  2325. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  2326. def _prime_kprofile_request(self):
  2327. """Send a priming K-profile request on connect.
  2328. Bambu printers often ignore the first K-profile request after connection,
  2329. so we send a dummy request on connect to 'prime' the system.
  2330. """
  2331. if self._client:
  2332. self._sequence_id += 1
  2333. command = {
  2334. "print": {
  2335. "command": "extrusion_cali_get",
  2336. "filament_id": "",
  2337. "nozzle_diameter": "0.4",
  2338. "sequence_id": str(self._sequence_id),
  2339. }
  2340. }
  2341. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  2342. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2343. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  2344. """Connect to the printer MQTT broker.
  2345. Args:
  2346. loop: The asyncio event loop to use for thread-safe callbacks.
  2347. If not provided, will try to get the running loop.
  2348. """
  2349. self._loop = loop
  2350. self._client = mqtt.Client(
  2351. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  2352. client_id=f"bambuddy_{self.serial_number}",
  2353. protocol=mqtt.MQTTv311,
  2354. )
  2355. self._client.username_pw_set("bblp", self.access_code)
  2356. self._client.on_connect = self._on_connect
  2357. self._client.on_disconnect = self._on_disconnect
  2358. self._client.on_subscribe = self._on_subscribe
  2359. self._client.on_message = self._on_message
  2360. # TLS setup - Bambu uses self-signed certs
  2361. ssl_context = ssl.create_default_context()
  2362. ssl_context.check_hostname = False
  2363. ssl_context.verify_mode = ssl.CERT_NONE
  2364. self._client.tls_set_context(ssl_context)
  2365. # Use shorter keepalive (15s) for faster disconnect detection
  2366. # Paho considers connection lost after 1.5x keepalive with no response
  2367. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=15)
  2368. self._client.loop_start()
  2369. def start_print(
  2370. self,
  2371. filename: str,
  2372. plate_id: int = 1,
  2373. ams_mapping: list[int] | None = None,
  2374. bed_levelling: bool = True,
  2375. flow_cali: bool = False,
  2376. vibration_cali: bool = True,
  2377. layer_inspect: bool = False,
  2378. timelapse: bool = False,
  2379. use_ams: bool = True,
  2380. ):
  2381. """Start a print job on the printer.
  2382. The file should already be uploaded to the printer's root directory via FTP.
  2383. Args:
  2384. filename: Name of the uploaded file
  2385. plate_id: Plate number to print (default 1)
  2386. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  2387. Global tray ID = (ams_id * 4) + slot_id, external = 254
  2388. timelapse: Record timelapse video
  2389. bed_levelling: Auto bed levelling before print
  2390. flow_cali: Flow/pressure advance calibration
  2391. vibration_cali: Vibration compensation calibration
  2392. layer_inspect: First layer AI inspection
  2393. use_ams: Use AMS for automatic filament changes
  2394. """
  2395. if self._client and self.state.connected:
  2396. # Bambu print command format - matches Bambu Studio's format
  2397. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  2398. ams_mapping2 = []
  2399. if ams_mapping is not None:
  2400. for tray_id in ams_mapping:
  2401. # Ensure tray_id is an integer (may be string from JSON)
  2402. tray_id = int(tray_id) if tray_id is not None else -1
  2403. if tray_id == -1:
  2404. # Unmapped filament slot
  2405. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  2406. elif tray_id >= 254:
  2407. # External spool: 254 = main nozzle, 255 = deputy nozzle
  2408. # For ams_mapping2, slot_id is 0 (main) or 1 (deputy), not the tray_id
  2409. external_slot = 0 if tray_id == 254 else 1
  2410. ams_mapping2.append({"ams_id": 255, "slot_id": external_slot})
  2411. elif tray_id >= 128:
  2412. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  2413. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  2414. else:
  2415. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  2416. ams_id = tray_id // 4
  2417. slot_id = tray_id % 4
  2418. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  2419. # H2D series requires integer values (0/1) for calibration/leveling fields
  2420. # but use_ams MUST remain boolean — H2D Pro firmware interprets integer
  2421. # values as nozzle index (1 = deputy nozzle), causing wrong extruder routing
  2422. # Other printers (X1C, P1S, A1, etc.) require actual booleans for all fields
  2423. is_h2d = self.model and self.model.upper().strip() in ("H2D", "H2D PRO", "H2DPRO", "H2C", "H2S")
  2424. command = {
  2425. "print": {
  2426. "sequence_id": "20000",
  2427. "command": "project_file",
  2428. "param": f"Metadata/plate_{plate_id}.gcode",
  2429. "url": f"ftp://{filename}",
  2430. "file": filename,
  2431. "md5": "",
  2432. "bed_type": "auto",
  2433. "timelapse": (1 if timelapse else 0) if is_h2d else timelapse,
  2434. "bed_leveling": (1 if bed_levelling else 0) if is_h2d else bed_levelling,
  2435. "auto_bed_leveling": 1 if bed_levelling else 0,
  2436. "flow_cali": (1 if flow_cali else 0) if is_h2d else flow_cali,
  2437. "vibration_cali": (1 if vibration_cali else 0) if is_h2d else vibration_cali,
  2438. "layer_inspect": (1 if layer_inspect else 0) if is_h2d else layer_inspect,
  2439. "use_ams": use_ams,
  2440. "cfg": "0",
  2441. "extrude_cali_flag": 0,
  2442. "extrude_cali_manual_mode": 0,
  2443. "nozzle_offset_cali": 2,
  2444. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  2445. "profile_id": "0",
  2446. "project_id": "0",
  2447. "subtask_id": "0",
  2448. "task_id": "0",
  2449. }
  2450. }
  2451. if is_h2d:
  2452. logger.debug(
  2453. "[%s] H2D series detected: using integer format for calibration fields (use_ams stays boolean)",
  2454. self.serial_number,
  2455. )
  2456. # P2S-specific parameter adjustments
  2457. # P2S printer doesn't support vibration calibration like X1/P1 series
  2458. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  2459. command["print"]["vibration_cali"] = False
  2460. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  2461. # Add AMS mapping if provided
  2462. if ams_mapping is not None:
  2463. command["print"]["ams_mapping"] = ams_mapping
  2464. command["print"]["ams_mapping2"] = ams_mapping2
  2465. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  2466. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2467. return True
  2468. else:
  2469. # Log why we couldn't send the command
  2470. if not self._client:
  2471. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  2472. elif not self.state.connected:
  2473. logger.error(
  2474. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  2475. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  2476. )
  2477. return False
  2478. def stop_print(self) -> bool:
  2479. """Stop the current print job."""
  2480. if self._client and self.state.connected:
  2481. command = {"print": {"command": "stop", "sequence_id": "0"}}
  2482. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2483. logger.info("[%s] Sent stop print command", self.serial_number)
  2484. return True
  2485. return False
  2486. def set_xcam_option(
  2487. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  2488. ) -> bool:
  2489. """Set an xcam (AI detection) option on the printer.
  2490. Args:
  2491. module_name: The xcam module to control (e.g., "spaghetti_detector",
  2492. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  2493. enabled: Whether to enable or disable the feature
  2494. print_halt: Whether to halt print on detection (only applies to some detectors)
  2495. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  2496. Returns:
  2497. True if command was sent, False if not connected
  2498. """
  2499. if not self._client or not self.state.connected:
  2500. return False
  2501. # auto_recovery_step_loss uses a different command format (print.print_option)
  2502. if module_name == "auto_recovery_step_loss":
  2503. return self._set_print_option("auto_recovery", enabled)
  2504. self._sequence_id += 1
  2505. # Build the xcam control command (exact OrcaSlicer format)
  2506. # Key findings from OrcaSlicer source:
  2507. # - Uses "xcam" wrapper (not "print")
  2508. # - print_halt is ALWAYS true (legacy protocol requirement)
  2509. # - Both "control" and "enable" are set to the same value
  2510. # - halt_print_sensitivity controls actual halt behavior
  2511. command = {
  2512. "xcam": {
  2513. "command": "xcam_control_set",
  2514. "sequence_id": str(self._sequence_id),
  2515. "module_name": module_name,
  2516. "control": enabled,
  2517. "enable": enabled, # old protocol compatibility
  2518. "print_halt": True, # ALWAYS true per OrcaSlicer
  2519. }
  2520. }
  2521. # Only add sensitivity if not "never_halt"
  2522. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  2523. # The module_name field determines which detector's sensitivity is being set
  2524. if sensitivity and sensitivity != "never_halt":
  2525. command["xcam"]["halt_print_sensitivity"] = sensitivity
  2526. command_json = json.dumps(command)
  2527. self._client.publish(self.topic_publish, command_json, qos=1)
  2528. logger.debug(
  2529. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  2530. )
  2531. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  2532. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  2533. # This prevents stale MQTT data from immediately overwriting our change
  2534. self._xcam_hold_start[module_name] = time.time()
  2535. # Update local state immediately for responsive UI
  2536. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  2537. # When spaghetti_detector sensitivity is changed, pileup also changes
  2538. if module_name == "spaghetti_detector":
  2539. self.state.print_options.spaghetti_detector = enabled
  2540. self.state.print_options.print_halt = print_halt
  2541. if sensitivity and sensitivity != "never_halt":
  2542. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  2543. self.state.print_options.halt_print_sensitivity = sensitivity
  2544. self.state.print_options.pileup_sensitivity = sensitivity
  2545. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  2546. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  2547. elif module_name == "first_layer_inspector":
  2548. self.state.print_options.first_layer_inspector = enabled
  2549. elif module_name == "printing_monitor":
  2550. self.state.print_options.printing_monitor = enabled
  2551. elif module_name == "buildplate_marker_detector":
  2552. self.state.print_options.buildplate_marker_detector = enabled
  2553. elif module_name == "allow_skip_parts":
  2554. self.state.print_options.allow_skip_parts = enabled
  2555. elif module_name == "pileup_detector":
  2556. self.state.print_options.pileup_detector = enabled
  2557. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  2558. elif module_name == "clump_detector":
  2559. self.state.print_options.nozzle_clumping_detector = enabled
  2560. if sensitivity and sensitivity != "never_halt":
  2561. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  2562. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  2563. elif module_name == "airprint_detector":
  2564. self.state.print_options.airprint_detector = enabled
  2565. if sensitivity and sensitivity != "never_halt":
  2566. self.state.print_options.airprint_sensitivity = sensitivity
  2567. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  2568. elif module_name == "auto_recovery_step_loss":
  2569. self.state.print_options.auto_recovery_step_loss = enabled
  2570. return True
  2571. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  2572. """Set a print option using the print.print_option command.
  2573. This is different from xcam_control_set and is used for options like:
  2574. - auto_recovery
  2575. - air_print_detect
  2576. - filament_tangle_detect
  2577. - nozzle_blob_detect
  2578. - sound_enable
  2579. Args:
  2580. option_name: The option to control (e.g., "auto_recovery")
  2581. enabled: Whether to enable or disable the option
  2582. Returns:
  2583. True if command was sent, False if not connected
  2584. """
  2585. if not self._client or not self.state.connected:
  2586. return False
  2587. self._sequence_id += 1
  2588. command = {
  2589. "print": {
  2590. "command": "print_option",
  2591. "sequence_id": str(self._sequence_id),
  2592. option_name: enabled,
  2593. }
  2594. }
  2595. command_json = json.dumps(command)
  2596. self._client.publish(self.topic_publish, command_json, qos=1)
  2597. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  2598. # Set hold timer
  2599. hold_key = f"print_option_{option_name}"
  2600. self._xcam_hold_start[hold_key] = time.time()
  2601. # Update local state immediately
  2602. if option_name == "auto_recovery":
  2603. self.state.print_options.auto_recovery_step_loss = enabled
  2604. return True
  2605. def start_calibration(
  2606. self,
  2607. bed_leveling: bool = False,
  2608. vibration: bool = False,
  2609. motor_noise: bool = False,
  2610. nozzle_offset: bool = False,
  2611. high_temp_heatbed: bool = False,
  2612. ) -> bool:
  2613. """Start printer calibration with selected options.
  2614. Args:
  2615. bed_leveling: Run bed leveling calibration
  2616. vibration: Run vibration compensation calibration
  2617. motor_noise: Run motor noise cancellation calibration
  2618. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  2619. high_temp_heatbed: Run high-temperature heatbed calibration
  2620. Returns:
  2621. True if command was sent, False if not connected
  2622. """
  2623. if not self._client or not self.state.connected:
  2624. return False
  2625. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  2626. # Bit 0: xcam_cali (not exposed in UI)
  2627. # Bit 1: bed_leveling
  2628. # Bit 2: vibration
  2629. # Bit 3: motor_noise
  2630. # Bit 4: nozzle_cali
  2631. # Bit 5: bed_cali (high-temp heatbed)
  2632. # Bit 6: clumppos_cali (not exposed in UI)
  2633. option = 0
  2634. if bed_leveling:
  2635. option |= 1 << 1
  2636. if vibration:
  2637. option |= 1 << 2
  2638. if motor_noise:
  2639. option |= 1 << 3
  2640. if nozzle_offset:
  2641. option |= 1 << 4
  2642. if high_temp_heatbed:
  2643. option |= 1 << 5
  2644. if option == 0:
  2645. logger.warning("[%s] No calibration options selected", self.serial_number)
  2646. return False
  2647. self._sequence_id += 1
  2648. command = {
  2649. "print": {
  2650. "command": "calibration",
  2651. "sequence_id": str(self._sequence_id),
  2652. "option": option,
  2653. }
  2654. }
  2655. command_json = json.dumps(command)
  2656. self._client.publish(self.topic_publish, command_json, qos=1)
  2657. logger.info(
  2658. f"[{self.serial_number}] Starting calibration: "
  2659. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  2660. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  2661. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  2662. )
  2663. return True
  2664. def disconnect(self, timeout: float = 0):
  2665. """Disconnect from the printer."""
  2666. if self._client:
  2667. self._disconnection_event = threading.Event()
  2668. self._client.disconnect()
  2669. self._disconnection_event.wait(timeout=timeout)
  2670. self._client.loop_stop()
  2671. self._client = None
  2672. self.state.connected = False
  2673. def send_command(self, command: dict):
  2674. """Send a command to the printer."""
  2675. if self._client and self.state.connected:
  2676. # Log outgoing message if logging is enabled
  2677. if self._logging_enabled:
  2678. self._message_log.append(
  2679. MQTTLogEntry(
  2680. timestamp=datetime.now(timezone.utc).isoformat(),
  2681. topic=self.topic_publish,
  2682. direction="out",
  2683. payload=command,
  2684. )
  2685. )
  2686. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2687. def enable_logging(self, enabled: bool = True):
  2688. """Enable or disable MQTT message logging."""
  2689. self._logging_enabled = enabled
  2690. # Don't clear logs when stopping - user can manually clear with clear_logs()
  2691. def get_logs(self) -> list[MQTTLogEntry]:
  2692. """Get all logged MQTT messages."""
  2693. return list(self._message_log)
  2694. def clear_logs(self):
  2695. """Clear the message log."""
  2696. self._message_log.clear()
  2697. @property
  2698. def logging_enabled(self) -> bool:
  2699. """Check if logging is enabled."""
  2700. return self._logging_enabled
  2701. def send_drying_command(
  2702. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  2703. ):
  2704. """Send AMS drying start/stop command.
  2705. Args:
  2706. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  2707. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  2708. duration: Drying duration in hours
  2709. mode: 1=start, 0=stop
  2710. filament: Filament type string (e.g. "PLA", "PETG")
  2711. rotate_tray: Whether to rotate the spool during drying for even heat
  2712. """
  2713. if not self._client:
  2714. return False
  2715. self._sequence_id += 1
  2716. command = {
  2717. "print": {
  2718. "sequence_id": str(self._sequence_id),
  2719. "command": "ams_filament_drying",
  2720. "ams_id": ams_id,
  2721. "temp": temp,
  2722. "cooling_temp": 20 if mode == 1 else 0,
  2723. "duration": duration,
  2724. "humidity": 0,
  2725. "mode": mode,
  2726. "rotate_tray": rotate_tray,
  2727. "filament": filament,
  2728. "close_power_conflict": False,
  2729. }
  2730. }
  2731. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2732. logger.info(
  2733. "[%s] Sent drying command: ams_id=%d, temp=%d, duration=%d, mode=%d",
  2734. self.serial_number,
  2735. ams_id,
  2736. temp,
  2737. duration,
  2738. mode,
  2739. )
  2740. return True
  2741. def _handle_kprofile_response(self, data: dict):
  2742. """Handle K-profile response from printer."""
  2743. response_nozzle = data.get("nozzle_diameter")
  2744. response_seq_id = data.get("sequence_id", "?")
  2745. filaments = data.get("filaments", [])
  2746. expected_nozzle = getattr(self, "_expected_kprofile_nozzle", None)
  2747. has_pending_request = self._pending_kprofile_response is not None
  2748. # Log all incoming responses when we have a pending request (for debugging)
  2749. if has_pending_request:
  2750. logger.info(
  2751. f"[{self.serial_number}] K-profile response: nozzle={response_nozzle}, "
  2752. f"seq_id={response_seq_id}, {len(filaments)} profiles, expected={expected_nozzle}"
  2753. )
  2754. # If we have a pending request, only accept responses with matching nozzle_diameter
  2755. # The printer broadcasts 0.4mm profiles constantly - we need to wait for the actual response
  2756. if has_pending_request and expected_nozzle and response_nozzle != expected_nozzle:
  2757. # Ignore this broadcast, keep waiting for matching response
  2758. logger.debug(
  2759. f"[{self.serial_number}] Ignoring broadcast: got nozzle={response_nozzle}, waiting for {expected_nozzle}"
  2760. )
  2761. return
  2762. # If no pending request, this is just a broadcast - update state silently and return early
  2763. if not has_pending_request:
  2764. # Still parse profiles to keep state updated, but don't log
  2765. profiles = []
  2766. for f in filaments:
  2767. if isinstance(f, dict):
  2768. try:
  2769. cali_idx = f.get("cali_idx", 0)
  2770. profiles.append(
  2771. KProfile(
  2772. slot_id=cali_idx,
  2773. extruder_id=int(f.get("extruder_id", 0)),
  2774. nozzle_id=str(f.get("nozzle_id", "")),
  2775. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  2776. filament_id=str(f.get("filament_id", "")),
  2777. name=str(f.get("name", "")),
  2778. k_value=str(f.get("k_value", "0.000000")),
  2779. n_coef=str(f.get("n_coef", "0.000000")),
  2780. ams_id=int(f.get("ams_id", 0)),
  2781. tray_id=int(f.get("tray_id", -1)),
  2782. setting_id=f.get("setting_id"),
  2783. )
  2784. )
  2785. except (ValueError, TypeError):
  2786. pass # Skip malformed K-profile entries; remaining profiles still usable
  2787. self.state.kprofiles = profiles
  2788. return
  2789. profiles = []
  2790. for i, f in enumerate(filaments):
  2791. if isinstance(f, dict):
  2792. try:
  2793. # cali_idx is the actual slot/calibration index from the printer
  2794. cali_idx = f.get("cali_idx", i)
  2795. profiles.append(
  2796. KProfile(
  2797. slot_id=cali_idx,
  2798. extruder_id=int(f.get("extruder_id", 0)),
  2799. nozzle_id=str(f.get("nozzle_id", "")),
  2800. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  2801. filament_id=str(f.get("filament_id", "")),
  2802. name=str(f.get("name", "")),
  2803. k_value=str(f.get("k_value", "0.000000")),
  2804. n_coef=str(f.get("n_coef", "0.000000")),
  2805. ams_id=int(f.get("ams_id", 0)),
  2806. tray_id=int(f.get("tray_id", -1)),
  2807. setting_id=f.get("setting_id"),
  2808. )
  2809. )
  2810. except (ValueError, TypeError) as e:
  2811. logger.warning("Failed to parse K-profile: %s", e)
  2812. self.state.kprofiles = profiles
  2813. self._kprofile_response_data = profiles
  2814. # Signal that we received the response (only if we were waiting for one)
  2815. # Use thread-safe method since MQTT callbacks run in a different thread
  2816. # Capture in local var to avoid TOCTOU race: asyncio thread can clear
  2817. # self._pending_kprofile_response between the check and the .set() call
  2818. event = self._pending_kprofile_response
  2819. if event:
  2820. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  2821. if self._loop and self._loop.is_running():
  2822. self._loop.call_soon_threadsafe(event.set)
  2823. else:
  2824. # Fallback for when loop is not available
  2825. event.set()
  2826. async def get_kprofiles(
  2827. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  2828. ) -> list[KProfile]:
  2829. """Request K-profiles from the printer with retry logic.
  2830. Bambu printers sometimes ignore the first K-profile request, so we
  2831. implement retry logic to ensure reliable retrieval.
  2832. Args:
  2833. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  2834. timeout: Timeout in seconds to wait for each response attempt
  2835. max_retries: Maximum number of retry attempts
  2836. Returns:
  2837. List of KProfile objects
  2838. """
  2839. if not self._client or not self.state.connected:
  2840. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  2841. return []
  2842. # Capture current event loop for thread-safe callback
  2843. try:
  2844. self._loop = asyncio.get_running_loop()
  2845. except RuntimeError:
  2846. logger.warning("[%s] No running event loop", self.serial_number)
  2847. return []
  2848. for attempt in range(max_retries):
  2849. # Set up response event for this attempt
  2850. self._sequence_id += 1
  2851. self._pending_kprofile_response = asyncio.Event()
  2852. self._kprofile_response_data = None
  2853. self._expected_kprofile_nozzle = nozzle_diameter # Track which nozzle response we expect
  2854. # Send the command with nozzle_diameter filter
  2855. command = {
  2856. "print": {
  2857. "command": "extrusion_cali_get",
  2858. "filament_id": "",
  2859. "nozzle_diameter": nozzle_diameter,
  2860. "sequence_id": str(self._sequence_id),
  2861. }
  2862. }
  2863. logger.info(
  2864. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries})"
  2865. )
  2866. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  2867. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  2868. # Wait for response (response handler already filters by nozzle_diameter)
  2869. try:
  2870. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  2871. profiles = self._kprofile_response_data or []
  2872. logger.info(
  2873. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  2874. )
  2875. return profiles
  2876. except TimeoutError:
  2877. logger.warning(
  2878. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  2879. )
  2880. if attempt < max_retries - 1:
  2881. # Brief delay before retry
  2882. await asyncio.sleep(0.5)
  2883. finally:
  2884. self._pending_kprofile_response = None
  2885. self._expected_kprofile_nozzle = None
  2886. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  2887. return []
  2888. def set_kprofile(
  2889. self,
  2890. filament_id: str,
  2891. name: str,
  2892. k_value: str,
  2893. nozzle_diameter: str = "0.4",
  2894. nozzle_id: str = "HS00-0.4",
  2895. extruder_id: int = 0,
  2896. setting_id: str | None = None,
  2897. slot_id: int = 0,
  2898. cali_idx: int | None = None,
  2899. ) -> bool:
  2900. """Set/update a K-profile on the printer.
  2901. Args:
  2902. filament_id: Bambu filament identifier
  2903. name: Profile name
  2904. k_value: Pressure advance value (e.g., "0.020000")
  2905. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  2906. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  2907. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  2908. setting_id: Existing setting ID for updates, None for new
  2909. slot_id: Calibration index (cali_idx) for the profile
  2910. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  2911. Returns:
  2912. True if command was sent, False otherwise
  2913. """
  2914. if not self._client or not self.state.connected:
  2915. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  2916. return False
  2917. self._sequence_id += 1
  2918. # Build the filament entry - printer uses cali_idx for profile identification
  2919. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  2920. # For edits, use the provided cali_idx or slot_id
  2921. if cali_idx is not None:
  2922. effective_cali_idx = cali_idx
  2923. else:
  2924. effective_cali_idx = -1 if slot_id == 0 else slot_id
  2925. # Generate a setting_id for new profiles (required by printer)
  2926. # Format: "PF" + 17 random digits
  2927. import random
  2928. if not setting_id and slot_id == 0:
  2929. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  2930. filament_entry = {
  2931. "ams_id": 0,
  2932. "cali_idx": effective_cali_idx,
  2933. "extruder_id": extruder_id,
  2934. "filament_id": filament_id,
  2935. "k_value": k_value,
  2936. "n_coef": "0.000000",
  2937. "name": name,
  2938. "nozzle_diameter": nozzle_diameter,
  2939. "nozzle_id": nozzle_id,
  2940. "setting_id": setting_id if setting_id else "",
  2941. "tray_id": -1,
  2942. }
  2943. command = {
  2944. "print": {
  2945. "command": "extrusion_cali_set",
  2946. "filaments": [filament_entry],
  2947. "nozzle_diameter": nozzle_diameter,
  2948. "sequence_id": str(self._sequence_id),
  2949. }
  2950. }
  2951. command_json = json.dumps(command)
  2952. logger.info(
  2953. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  2954. )
  2955. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  2956. self._client.publish(self.topic_publish, command_json, qos=1)
  2957. return True
  2958. def set_kprofiles_batch(
  2959. self,
  2960. profiles: list[dict],
  2961. nozzle_diameter: str = "0.4",
  2962. ) -> bool:
  2963. """Set multiple K-profiles in a single command (for dual-nozzle).
  2964. Args:
  2965. profiles: List of profile dicts, each with:
  2966. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  2967. nozzle_diameter: Common nozzle diameter for all profiles
  2968. Returns:
  2969. True if command was sent, False otherwise
  2970. """
  2971. if not self._client or not self.state.connected:
  2972. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  2973. return False
  2974. import random
  2975. self._sequence_id += 1
  2976. filament_entries = []
  2977. for p in profiles:
  2978. slot_id = p.get("slot_id", 0)
  2979. cali_idx = p.get("cali_idx")
  2980. if cali_idx is not None:
  2981. effective_cali_idx = cali_idx
  2982. else:
  2983. effective_cali_idx = -1 if slot_id == 0 else slot_id
  2984. setting_id = p.get("setting_id")
  2985. if not setting_id and slot_id == 0:
  2986. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  2987. filament_entries.append(
  2988. {
  2989. "ams_id": 0,
  2990. "cali_idx": effective_cali_idx,
  2991. "extruder_id": p.get("extruder_id", 0),
  2992. "filament_id": p.get("filament_id", ""),
  2993. "k_value": p.get("k_value", "0.020000"),
  2994. "n_coef": "0.000000",
  2995. "name": p.get("name", ""),
  2996. "nozzle_diameter": nozzle_diameter,
  2997. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  2998. "setting_id": setting_id if setting_id else "",
  2999. "tray_id": -1,
  3000. }
  3001. )
  3002. command = {
  3003. "print": {
  3004. "command": "extrusion_cali_set",
  3005. "filaments": filament_entries,
  3006. "nozzle_diameter": nozzle_diameter,
  3007. "sequence_id": str(self._sequence_id),
  3008. }
  3009. }
  3010. command_json = json.dumps(command)
  3011. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  3012. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  3013. self._client.publish(self.topic_publish, command_json, qos=1)
  3014. return True
  3015. def delete_kprofile(
  3016. self,
  3017. cali_idx: int,
  3018. filament_id: str,
  3019. nozzle_id: str,
  3020. nozzle_diameter: str = "0.4",
  3021. extruder_id: int = 0,
  3022. setting_id: str | None = None,
  3023. ) -> bool:
  3024. """Delete a K-profile from the printer.
  3025. Args:
  3026. cali_idx: The calibration index (slot_id) of the profile to delete
  3027. filament_id: Bambu filament identifier
  3028. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  3029. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  3030. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  3031. setting_id: Unique setting identifier (for X1C series)
  3032. Returns:
  3033. True if command was sent, False otherwise
  3034. """
  3035. if not self._client or not self.state.connected:
  3036. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  3037. return False
  3038. self._sequence_id += 1
  3039. # Detect printer type by serial number prefix
  3040. # H2D series (dual nozzle): serial starts with "094"
  3041. is_dual_nozzle = self.serial_number.startswith("094")
  3042. if is_dual_nozzle:
  3043. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  3044. command = {
  3045. "print": {
  3046. "command": "extrusion_cali_del",
  3047. "sequence_id": str(self._sequence_id),
  3048. "extruder_id": extruder_id,
  3049. "nozzle_id": nozzle_id,
  3050. "filament_id": filament_id,
  3051. "cali_idx": cali_idx,
  3052. "nozzle_diameter": nozzle_diameter,
  3053. }
  3054. }
  3055. else:
  3056. # X1C/P1/A1 format: include all fields like the set command
  3057. # The delete command structure should match what set uses
  3058. command = {
  3059. "print": {
  3060. "command": "extrusion_cali_del",
  3061. "sequence_id": str(self._sequence_id),
  3062. "filament_id": filament_id,
  3063. "cali_idx": cali_idx,
  3064. "setting_id": setting_id if setting_id else "",
  3065. "nozzle_diameter": nozzle_diameter,
  3066. "nozzle_id": nozzle_id,
  3067. "extruder_id": extruder_id,
  3068. }
  3069. }
  3070. command_json = json.dumps(command)
  3071. logger.info(
  3072. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  3073. )
  3074. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  3075. # Use QoS 1 for reliable delivery (at least once)
  3076. self._client.publish(self.topic_publish, command_json, qos=1)
  3077. return True
  3078. # =========================================================================
  3079. # Printer Control Commands
  3080. # =========================================================================
  3081. def pause_print(self) -> bool:
  3082. """Pause the current print job."""
  3083. if not self._client or not self.state.connected:
  3084. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  3085. return False
  3086. command = {"print": {"command": "pause", "sequence_id": "0"}}
  3087. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3088. logger.info("[%s] Sent pause print command", self.serial_number)
  3089. return True
  3090. def resume_print(self) -> bool:
  3091. """Resume a paused print job."""
  3092. if not self._client or not self.state.connected:
  3093. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  3094. return False
  3095. command = {"print": {"command": "resume", "sequence_id": "0"}}
  3096. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3097. logger.info("[%s] Sent resume print command", self.serial_number)
  3098. return True
  3099. def clear_hms_errors(self) -> bool:
  3100. """Clear HMS/print errors on the printer and locally."""
  3101. if not self._client or not self.state.connected:
  3102. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  3103. return False
  3104. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  3105. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3106. self.state.hms_errors = []
  3107. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  3108. return True
  3109. def skip_objects(self, object_ids: list[int]) -> bool:
  3110. """Skip specific objects during a print.
  3111. This command tells the printer to skip printing the specified objects.
  3112. The object IDs come from the slice_info.config file in the 3MF.
  3113. Args:
  3114. object_ids: List of identify_id values from slice_info.config
  3115. Returns:
  3116. True if command was sent, False otherwise
  3117. """
  3118. if not self._client or not self.state.connected:
  3119. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  3120. return False
  3121. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  3122. logger.warning(
  3123. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  3124. )
  3125. return False
  3126. if not object_ids:
  3127. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  3128. return False
  3129. # Validate all IDs are integers
  3130. try:
  3131. obj_list = [int(oid) for oid in object_ids]
  3132. except (ValueError, TypeError) as e:
  3133. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  3134. return False
  3135. self._sequence_id += 1
  3136. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  3137. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3138. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  3139. # Track skipped objects in state
  3140. for oid in obj_list:
  3141. if oid not in self.state.skipped_objects:
  3142. self.state.skipped_objects.append(oid)
  3143. return True
  3144. def send_gcode(self, gcode: str) -> bool:
  3145. """Send G-code command(s) to the printer.
  3146. Multiple commands can be separated by newlines.
  3147. Args:
  3148. gcode: G-code command(s) to send
  3149. Returns:
  3150. True if command was sent, False otherwise
  3151. """
  3152. if not self._client or not self.state.connected:
  3153. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  3154. return False
  3155. self._sequence_id += 1
  3156. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  3157. # Use QoS 1 for reliable delivery (at least once)
  3158. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3159. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  3160. return True
  3161. def set_bed_temperature(self, target: int) -> bool:
  3162. """Set the bed target temperature.
  3163. Args:
  3164. target: Target temperature in Celsius (0 to turn off)
  3165. Returns:
  3166. True if command was sent, False otherwise
  3167. """
  3168. return self.send_gcode(f"M140 S{target}")
  3169. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  3170. """Set the nozzle target temperature.
  3171. Args:
  3172. target: Target temperature in Celsius (0 to turn off)
  3173. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  3174. Returns:
  3175. True if command was sent, False otherwise
  3176. """
  3177. # Use M104 for non-blocking
  3178. # Always use T parameter for H2D compatibility
  3179. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  3180. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  3181. # Track it locally so we can display it correctly
  3182. if result and nozzle == 1:
  3183. self.state.temperatures["nozzle_target"] = float(target)
  3184. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  3185. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  3186. return result
  3187. def set_chamber_temperature(self, target: int) -> bool:
  3188. """Set the chamber target temperature.
  3189. Args:
  3190. target: Target temperature in Celsius (0 to turn off heating)
  3191. Returns:
  3192. True if command was sent, False otherwise
  3193. """
  3194. # M141 sets chamber temperature
  3195. result = self.send_gcode(f"M141 S{target}")
  3196. # Track chamber target locally (MQTT reports encoded values that need filtering)
  3197. if result:
  3198. self.state.temperatures["chamber_target"] = float(target)
  3199. self.state.temperatures["_chamber_target_set_time"] = time.time()
  3200. # Update heating state immediately based on new target
  3201. current_temp = self.state.temperatures.get("chamber", 0)
  3202. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  3203. logger.info(
  3204. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  3205. )
  3206. return result
  3207. def set_print_speed(self, mode: int) -> bool:
  3208. """Set the print speed mode.
  3209. Args:
  3210. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  3211. Returns:
  3212. True if command was sent, False otherwise
  3213. """
  3214. if not self._client or not self.state.connected:
  3215. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  3216. return False
  3217. if mode not in (1, 2, 3, 4):
  3218. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  3219. return False
  3220. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  3221. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3222. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  3223. return True
  3224. def set_fan_speed(self, fan: int, speed: int) -> bool:
  3225. """Set fan speed.
  3226. Args:
  3227. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber)
  3228. speed: Speed 0-255 (0=off, 255=full)
  3229. Returns:
  3230. True if command was sent, False otherwise
  3231. """
  3232. if fan not in (1, 2, 3):
  3233. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  3234. return False
  3235. speed = max(0, min(255, speed)) # Clamp to 0-255
  3236. return self.send_gcode(f"M106 P{fan} S{speed}")
  3237. def set_part_fan(self, speed: int) -> bool:
  3238. """Set part cooling fan speed (0-255)."""
  3239. return self.set_fan_speed(1, speed)
  3240. def set_aux_fan(self, speed: int) -> bool:
  3241. """Set auxiliary fan speed (0-255)."""
  3242. return self.set_fan_speed(2, speed)
  3243. def set_chamber_fan(self, speed: int) -> bool:
  3244. """Set chamber fan speed (0-255)."""
  3245. return self.set_fan_speed(3, speed)
  3246. def set_airduct_mode(self, mode: str) -> bool:
  3247. """Set air conditioning mode (cooling or heating).
  3248. Args:
  3249. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  3250. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  3251. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  3252. closes top exhaust flap
  3253. Returns:
  3254. True if command was sent, False otherwise
  3255. """
  3256. if not self._client or not self.state.connected:
  3257. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  3258. return False
  3259. self._sequence_id += 1
  3260. mode_id = 0 if mode == "cooling" else 1
  3261. command = {
  3262. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  3263. }
  3264. # Use QoS 1 for reliable delivery
  3265. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3266. logger.info(
  3267. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  3268. )
  3269. return True
  3270. def set_chamber_light(self, on: bool) -> bool:
  3271. """Turn chamber light on or off.
  3272. Args:
  3273. on: True to turn on, False to turn off
  3274. Returns:
  3275. True if command was sent, False otherwise
  3276. """
  3277. if not self._client or not self.state.connected:
  3278. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  3279. return False
  3280. mode = "on" if on else "off"
  3281. # Control both chamber lights (some printers like H2D have two)
  3282. for led_node in ["chamber_light", "chamber_light2"]:
  3283. self._sequence_id += 1
  3284. command = {
  3285. "system": {
  3286. "command": "ledctrl",
  3287. "led_node": led_node,
  3288. "led_mode": mode,
  3289. "led_on_time": 500,
  3290. "led_off_time": 500,
  3291. "loop_times": 0,
  3292. "interval_time": 0,
  3293. "sequence_id": str(self._sequence_id),
  3294. }
  3295. }
  3296. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3297. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  3298. return True
  3299. def select_extruder(self, extruder: int) -> bool:
  3300. """Select the active extruder for dual-nozzle printers (H2D).
  3301. Args:
  3302. extruder: Extruder index (0=right, 1=left for H2D)
  3303. Returns:
  3304. True if command was sent, False otherwise
  3305. """
  3306. if extruder not in (0, 1):
  3307. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  3308. return False
  3309. if not self._client or not self.state.connected:
  3310. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  3311. return False
  3312. # H2D extruder switching via select_extruder command
  3313. # Command format captured from OrcaSlicer:
  3314. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  3315. # extruder_index: 0 = RIGHT, 1 = LEFT
  3316. self._sequence_id += 1
  3317. command = {
  3318. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  3319. }
  3320. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3321. logger.info(
  3322. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  3323. )
  3324. return True
  3325. def home_axes(self, axes: str = "XYZ") -> bool:
  3326. """Home the specified axes.
  3327. Args:
  3328. axes: Axes to home (e.g., "XYZ", "X", "XY", "Z")
  3329. Returns:
  3330. True if command was sent, False otherwise
  3331. """
  3332. # G28 homes all axes, G28 X Y Z homes specific axes
  3333. axes_param = " ".join(axes.upper())
  3334. return self.send_gcode(f"G28 {axes_param}")
  3335. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  3336. """Move an axis by a relative distance.
  3337. Args:
  3338. axis: Axis to move ("X", "Y", or "Z")
  3339. distance: Distance to move in mm (positive or negative)
  3340. speed: Movement speed in mm/min
  3341. Returns:
  3342. True if command was sent, False otherwise
  3343. """
  3344. axis = axis.upper()
  3345. if axis not in ("X", "Y", "Z"):
  3346. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  3347. return False
  3348. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  3349. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  3350. return self.send_gcode(gcode)
  3351. def disable_motors(self) -> bool:
  3352. """Disable all stepper motors.
  3353. Warning: This will cause the printer to lose its position.
  3354. A homing operation will be required before printing.
  3355. Returns:
  3356. True if command was sent, False otherwise
  3357. """
  3358. return self.send_gcode("M18")
  3359. def enable_motors(self) -> bool:
  3360. """Enable all stepper motors.
  3361. Returns:
  3362. True if command was sent, False otherwise
  3363. """
  3364. return self.send_gcode("M17")
  3365. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  3366. """Load filament from a specific AMS tray.
  3367. Args:
  3368. tray_id: Global tray ID (0-15 for AMS slots, or 254 for external spool)
  3369. extruder_id: Unused - kept for API compatibility
  3370. Returns:
  3371. True if command was sent, False otherwise
  3372. """
  3373. if not self._client or not self.state.connected:
  3374. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  3375. return False
  3376. # Calculate ams_id and slot_id for logging
  3377. if tray_id == 254:
  3378. ams_id = 255 # External spool
  3379. slot_id = 254
  3380. else:
  3381. ams_id = tray_id // 4 # AMS unit (0, 1, 2, 3...)
  3382. slot_id = tray_id % 4 # Slot within AMS (0, 1, 2, 3)
  3383. # Command format from BambuStudio traffic capture:
  3384. # - No extruder_id field
  3385. # - curr_temp and tar_temp are -1 (not 0)
  3386. self._sequence_id += 1
  3387. command = {
  3388. "print": {
  3389. "command": "ams_change_filament",
  3390. "sequence_id": str(self._sequence_id),
  3391. "ams_id": ams_id,
  3392. "slot_id": slot_id,
  3393. "target": tray_id,
  3394. "curr_temp": -1,
  3395. "tar_temp": -1,
  3396. }
  3397. }
  3398. command_json = json.dumps(command)
  3399. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  3400. self._client.publish(self.topic_publish, command_json, qos=1)
  3401. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  3402. # Track this load request for H2D dual-nozzle disambiguation
  3403. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  3404. self._last_load_tray_id = tray_id
  3405. self.state.pending_tray_target = tray_id
  3406. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  3407. return True
  3408. def ams_unload_filament(self) -> bool:
  3409. """Unload the currently loaded filament.
  3410. Returns:
  3411. True if command was sent, False otherwise
  3412. """
  3413. if not self._client or not self.state.connected:
  3414. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  3415. return False
  3416. # Get the currently loaded tray info
  3417. tray_now = self.state.tray_now
  3418. logger.info("[%s] Unload requested, tray_now=%s", self.serial_number, tray_now)
  3419. # Determine source ams_id for the unload command
  3420. if tray_now == 255 or tray_now == 254:
  3421. ams_id = 255 # No filament or external spool
  3422. else:
  3423. ams_id = tray_now // 4 # Source AMS
  3424. # Command format from BambuStudio traffic capture:
  3425. # - No extruder_id field
  3426. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  3427. # - slot_id=255 and target=255 for unload
  3428. # Get current nozzle temperature for the unload command
  3429. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  3430. if nozzle_temp < 180:
  3431. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  3432. self._sequence_id += 1
  3433. command = {
  3434. "print": {
  3435. "command": "ams_change_filament",
  3436. "sequence_id": str(self._sequence_id),
  3437. "ams_id": ams_id,
  3438. "slot_id": 255, # 255 = unload marker
  3439. "target": 255, # 255 = unload destination
  3440. "curr_temp": nozzle_temp,
  3441. "tar_temp": nozzle_temp,
  3442. }
  3443. }
  3444. command_json = json.dumps(command)
  3445. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  3446. self._client.publish(self.topic_publish, command_json, qos=1)
  3447. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  3448. # Clear tracked load request since we're unloading
  3449. self._last_load_tray_id = None
  3450. self.state.pending_tray_target = None
  3451. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  3452. return True
  3453. def ams_control(self, action: str) -> bool:
  3454. """Control AMS operations.
  3455. Args:
  3456. action: "resume", "reset", or "pause"
  3457. Returns:
  3458. True if command was sent, False otherwise
  3459. """
  3460. if not self._client or not self.state.connected:
  3461. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  3462. return False
  3463. if action not in ("resume", "reset", "pause"):
  3464. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  3465. return False
  3466. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  3467. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3468. logger.info("[%s] AMS control: %s", self.serial_number, action)
  3469. return True
  3470. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  3471. """Trigger RFID re-read for a specific AMS tray.
  3472. Args:
  3473. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  3474. tray_id: Tray ID within the AMS (0-3)
  3475. Returns:
  3476. Tuple of (success, message)
  3477. """
  3478. if not self._client or not self.state.connected:
  3479. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  3480. return False, "Printer not connected"
  3481. # Check if filament is currently loaded (tray_now != 255)
  3482. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  3483. tray_now = self.state.tray_now
  3484. if tray_now != 255:
  3485. # Decode which tray is loaded for the message
  3486. if tray_now == 254:
  3487. loaded_tray = "external spool"
  3488. elif tray_now >= 0 and tray_now < 128:
  3489. loaded_ams = tray_now // 4
  3490. loaded_slot = tray_now % 4
  3491. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  3492. else:
  3493. loaded_tray = f"tray {tray_now}"
  3494. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  3495. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  3496. # Use ams_get_rfid command to trigger RFID re-read
  3497. # This command is used by Bambu Studio to re-read the RFID tag
  3498. command = {"print": {"command": "ams_get_rfid", "ams_id": ams_id, "slot_id": tray_id, "sequence_id": "0"}}
  3499. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3500. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  3501. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  3502. def ams_set_filament_setting(
  3503. self,
  3504. ams_id: int,
  3505. tray_id: int,
  3506. tray_info_idx: str,
  3507. tray_type: str,
  3508. tray_sub_brands: str,
  3509. tray_color: str,
  3510. nozzle_temp_min: int,
  3511. nozzle_temp_max: int,
  3512. setting_id: str = "",
  3513. ) -> bool:
  3514. """Set AMS tray filament settings (type, color, temperature).
  3515. Note: K value is set separately via extrusion_cali_sel command.
  3516. Args:
  3517. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  3518. tray_id: Tray ID within the AMS (0-3)
  3519. tray_info_idx: Filament ID short format (e.g., "GFL05")
  3520. tray_type: Filament type (e.g., "PLA", "PETG")
  3521. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  3522. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  3523. nozzle_temp_min: Minimum nozzle temperature
  3524. nozzle_temp_max: Maximum nozzle temperature
  3525. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  3526. Returns:
  3527. True if command was sent, False otherwise
  3528. """
  3529. if not self._client or not self.state.connected:
  3530. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  3531. return False
  3532. # Calculate mqtt IDs based on AMS type
  3533. if ams_id == 255:
  3534. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  3535. if len(vt_tray) > 1:
  3536. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  3537. # (254=ext-L / slot 0, 255=ext-R / slot 1)
  3538. mqtt_ams_id = 254 + tray_id
  3539. else:
  3540. # Single external slot (X1C, P1S, A1): always ams_id=255
  3541. mqtt_ams_id = 255
  3542. mqtt_tray_id = 0
  3543. slot_id = 0
  3544. elif ams_id <= 3:
  3545. mqtt_ams_id = ams_id
  3546. mqtt_tray_id = tray_id
  3547. slot_id = tray_id
  3548. else:
  3549. # AMS-HT: single tray per unit
  3550. mqtt_ams_id = ams_id
  3551. mqtt_tray_id = tray_id
  3552. slot_id = 0
  3553. command = {
  3554. "print": {
  3555. "command": "ams_filament_setting",
  3556. "ams_id": mqtt_ams_id,
  3557. "tray_id": mqtt_tray_id,
  3558. "slot_id": slot_id,
  3559. "tray_info_idx": tray_info_idx,
  3560. "tray_type": tray_type,
  3561. "tray_sub_brands": tray_sub_brands,
  3562. "tray_color": tray_color,
  3563. "nozzle_temp_min": nozzle_temp_min,
  3564. "nozzle_temp_max": nozzle_temp_max,
  3565. "sequence_id": "0",
  3566. }
  3567. }
  3568. # Include setting_id if provided (helps slicer show correct profile)
  3569. if setting_id:
  3570. command["print"]["setting_id"] = setting_id
  3571. command_json = json.dumps(command)
  3572. logger.info(
  3573. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  3574. )
  3575. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  3576. self._client.publish(self.topic_publish, command_json, qos=1)
  3577. return True
  3578. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  3579. """Reset an AMS slot to empty/unconfigured state.
  3580. Args:
  3581. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  3582. tray_id: Tray ID within the AMS (0-3)
  3583. Returns:
  3584. True if command was sent, False otherwise
  3585. """
  3586. if not self._client or not self.state.connected:
  3587. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  3588. return False
  3589. # Calculate mqtt IDs based on AMS type
  3590. if ams_id == 255:
  3591. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  3592. if len(vt_tray) > 1:
  3593. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  3594. mqtt_ams_id = 254 + tray_id
  3595. else:
  3596. # Single external slot (X1C, P1S, A1): always ams_id=255
  3597. mqtt_ams_id = 255
  3598. mqtt_tray_id = 0
  3599. slot_id = 0
  3600. elif ams_id <= 3:
  3601. mqtt_ams_id = ams_id
  3602. mqtt_tray_id = tray_id
  3603. slot_id = tray_id
  3604. else:
  3605. # AMS-HT: single tray per unit
  3606. mqtt_ams_id = ams_id
  3607. mqtt_tray_id = tray_id
  3608. slot_id = 0
  3609. command = {
  3610. "print": {
  3611. "command": "ams_filament_setting",
  3612. "ams_id": mqtt_ams_id,
  3613. "tray_id": mqtt_tray_id,
  3614. "slot_id": slot_id,
  3615. "tray_info_idx": "",
  3616. "tray_type": "",
  3617. "tray_sub_brands": "",
  3618. "tray_color": "00000000",
  3619. "nozzle_temp_min": 0,
  3620. "nozzle_temp_max": 0,
  3621. "sequence_id": "0",
  3622. }
  3623. }
  3624. command_json = json.dumps(command)
  3625. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  3626. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  3627. self._client.publish(self.topic_publish, command_json, qos=1)
  3628. return True
  3629. def extrusion_cali_sel(
  3630. self,
  3631. ams_id: int,
  3632. tray_id: int,
  3633. cali_idx: int,
  3634. filament_id: str,
  3635. nozzle_diameter: str = "0.4",
  3636. ) -> bool:
  3637. """Set calibration profile (K value) for an AMS slot.
  3638. This command selects a K profile from the printer's calibration list.
  3639. Use cali_idx=-1 to use the default K value (0.020).
  3640. Note: Do NOT send setting_id in this command — BambuStudio never includes
  3641. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  3642. Args:
  3643. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  3644. tray_id: Tray ID within the AMS (0-3)
  3645. cali_idx: Calibration profile index (-1 for default)
  3646. filament_id: Filament preset ID (same as tray_info_idx)
  3647. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  3648. Returns:
  3649. True if command was sent, False otherwise
  3650. """
  3651. if not self._client or not self.state.connected:
  3652. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  3653. return False
  3654. # Calculate mqtt IDs based on AMS type.
  3655. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  3656. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  3657. if ams_id == 255:
  3658. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  3659. # ams_filament_setting which uses LOCAL tray_id=0).
  3660. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  3661. if len(vt_tray) > 1:
  3662. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  3663. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  3664. mqtt_ams_id = 254 + tray_id
  3665. mqtt_tray_id = 254 + tray_id
  3666. else:
  3667. # Single external slot (X1C, P1S, A1): global tray_id=254
  3668. mqtt_ams_id = 254
  3669. mqtt_tray_id = 254
  3670. slot_id = 0
  3671. elif ams_id <= 3:
  3672. mqtt_ams_id = ams_id
  3673. mqtt_tray_id = ams_id * 4 + tray_id
  3674. slot_id = tray_id
  3675. elif ams_id >= 128 and ams_id <= 135:
  3676. mqtt_ams_id = ams_id
  3677. mqtt_tray_id = tray_id
  3678. slot_id = 0
  3679. else:
  3680. mqtt_ams_id = ams_id
  3681. mqtt_tray_id = tray_id
  3682. slot_id = 0
  3683. command = {
  3684. "print": {
  3685. "command": "extrusion_cali_sel",
  3686. "cali_idx": cali_idx,
  3687. "filament_id": filament_id,
  3688. "nozzle_diameter": nozzle_diameter,
  3689. "ams_id": mqtt_ams_id,
  3690. "tray_id": mqtt_tray_id,
  3691. "slot_id": slot_id,
  3692. "sequence_id": "0",
  3693. }
  3694. }
  3695. command_json = json.dumps(command)
  3696. logger.info(
  3697. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  3698. )
  3699. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  3700. self._client.publish(self.topic_publish, command_json, qos=1)
  3701. return True
  3702. def extrusion_cali_set(
  3703. self,
  3704. tray_id: int,
  3705. k_value: float,
  3706. nozzle_diameter: str = "0.4",
  3707. nozzle_temp: int = 220,
  3708. filament_id: str = "",
  3709. setting_id: str = "",
  3710. name: str = "",
  3711. cali_idx: int = -1,
  3712. ) -> bool:
  3713. """Directly set K value (pressure advance) for a tray.
  3714. Uses the filaments array format required by current firmware.
  3715. Args:
  3716. tray_id: Global tray ID (ams_id * 4 + slot)
  3717. k_value: Pressure advance K value (e.g., 0.020)
  3718. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  3719. nozzle_temp: Nozzle temperature for calibration reference
  3720. filament_id: Filament preset ID (e.g., "GFA02")
  3721. setting_id: Setting ID (e.g., "GFSA02_07")
  3722. name: Profile display name
  3723. cali_idx: Calibration index (-1 for new)
  3724. Returns:
  3725. True if command was sent, False otherwise
  3726. """
  3727. if not self._client or not self.state.connected:
  3728. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  3729. return False
  3730. nozzle_id = f"HS00-{nozzle_diameter}"
  3731. filament_entry = {
  3732. "ams_id": 0,
  3733. "cali_idx": cali_idx,
  3734. "extruder_id": 0,
  3735. "filament_id": filament_id,
  3736. "k_value": f"{k_value:.6f}",
  3737. "n_coef": "1.400000",
  3738. "name": name,
  3739. "nozzle_diameter": nozzle_diameter,
  3740. "nozzle_id": nozzle_id,
  3741. "setting_id": setting_id,
  3742. "tray_id": tray_id,
  3743. }
  3744. command = {
  3745. "print": {
  3746. "command": "extrusion_cali_set",
  3747. "filaments": [filament_entry],
  3748. "nozzle_diameter": nozzle_diameter,
  3749. "sequence_id": str(self._sequence_id),
  3750. }
  3751. }
  3752. command_json = json.dumps(command)
  3753. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  3754. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  3755. self._client.publish(self.topic_publish, command_json, qos=1)
  3756. return True
  3757. def set_timelapse(self, enable: bool) -> bool:
  3758. """Enable or disable timelapse recording.
  3759. Args:
  3760. enable: True to enable, False to disable
  3761. Returns:
  3762. True if command was sent, False otherwise
  3763. """
  3764. if not self._client or not self.state.connected:
  3765. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  3766. return False
  3767. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  3768. # First send the timelapse setting
  3769. timelapse_cmd = {
  3770. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  3771. }
  3772. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  3773. # Request status update
  3774. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3775. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  3776. return True
  3777. def set_liveview(self, enable: bool) -> bool:
  3778. """Enable or disable live view / camera streaming.
  3779. Args:
  3780. enable: True to enable, False to disable
  3781. Returns:
  3782. True if command was sent, False otherwise
  3783. """
  3784. if not self._client or not self.state.connected:
  3785. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  3786. return False
  3787. command = {
  3788. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  3789. }
  3790. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3791. # Request status update
  3792. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  3793. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  3794. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  3795. return True