bambu_mqtt.py 234 KB

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