bambu_mqtt.py 252 KB

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