bambu_mqtt.py 214 KB

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