bambu_mqtt.py 220 KB

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