bambu_mqtt.py 183 KB

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