bambu_mqtt.py 220 KB

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