bambu_mqtt.py 223 KB

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