bambu_mqtt.py 242 KB

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