bambu_mqtt.py 218 KB

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