bambu_mqtt.py 226 KB

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