bambu_mqtt.py 221 KB

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