bambu_mqtt.py 241 KB

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