bambu_mqtt.py 247 KB

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