bambu_mqtt.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  1. import json
  2. import ssl
  3. import asyncio
  4. import logging
  5. import time
  6. from collections import deque
  7. from datetime import datetime
  8. from typing import Callable
  9. from dataclasses import dataclass, field
  10. import paho.mqtt.client as mqtt
  11. logger = logging.getLogger(__name__)
  12. @dataclass
  13. class MQTTLogEntry:
  14. """Log entry for MQTT message debugging."""
  15. timestamp: str
  16. topic: str
  17. direction: str # "in" or "out"
  18. payload: dict
  19. @dataclass
  20. class HMSError:
  21. """Health Management System error from printer."""
  22. code: str
  23. module: int
  24. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  25. message: str = ""
  26. @dataclass
  27. class KProfile:
  28. """Pressure advance (K) calibration profile from printer."""
  29. slot_id: int
  30. extruder_id: int
  31. nozzle_id: str
  32. nozzle_diameter: str
  33. filament_id: str
  34. name: str
  35. k_value: str
  36. n_coef: str = "0.000000"
  37. ams_id: int = 0
  38. tray_id: int = -1
  39. setting_id: str | None = None
  40. @dataclass
  41. class NozzleInfo:
  42. """Nozzle hardware configuration."""
  43. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  44. nozzle_diameter: str = "" # e.g., "0.4"
  45. @dataclass
  46. class PrintOptions:
  47. """AI detection and print options from xcam data."""
  48. # Core AI detectors
  49. spaghetti_detector: bool = False
  50. print_halt: bool = False
  51. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  52. first_layer_inspector: bool = False
  53. printing_monitor: bool = False # AI print quality monitoring
  54. buildplate_marker_detector: bool = False
  55. allow_skip_parts: bool = False
  56. # Additional AI detectors - decoded from cfg bitmask
  57. nozzle_clumping_detector: bool = True
  58. nozzle_clumping_sensitivity: str = "medium"
  59. pileup_detector: bool = True
  60. pileup_sensitivity: str = "medium"
  61. airprint_detector: bool = True
  62. airprint_sensitivity: str = "medium"
  63. auto_recovery_step_loss: bool = True # Uses print.print_option command
  64. filament_tangle_detect: bool = False
  65. @dataclass
  66. class PrinterState:
  67. connected: bool = False
  68. state: str = "unknown"
  69. current_print: str | None = None
  70. subtask_name: str | None = None
  71. progress: float = 0.0
  72. remaining_time: int = 0
  73. layer_num: int = 0
  74. total_layers: int = 0
  75. temperatures: dict = field(default_factory=dict)
  76. raw_data: dict = field(default_factory=dict)
  77. gcode_file: str | None = None
  78. subtask_id: str | None = None
  79. hms_errors: list = field(default_factory=list) # List of HMSError
  80. kprofiles: list = field(default_factory=list) # List of KProfile
  81. sdcard: bool = False # SD card inserted
  82. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  83. timelapse: bool = False # Timelapse recording active
  84. ipcam: bool = False # Live view / camera streaming enabled
  85. # Nozzle hardware info (for dual nozzle printers, index 0 = left, 1 = right)
  86. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  87. # AI detection and print options
  88. print_options: PrintOptions = field(default_factory=PrintOptions)
  89. # Calibration stage tracking (from stg_cur and stg fields)
  90. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  91. stg: list = field(default_factory=list) # List of stages to execute
  92. # Air conditioning mode (0=cooling, 1=heating)
  93. airduct_mode: int = 0
  94. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  95. speed_level: int = 2
  96. # Chamber light on/off
  97. chamber_light: bool = False
  98. # Stage name mapping from BambuStudio DeviceManager.cpp
  99. STAGE_NAMES = {
  100. 0: "Printing",
  101. 1: "Auto bed leveling",
  102. 2: "Heatbed preheating",
  103. 3: "Vibration compensation",
  104. 4: "Changing filament",
  105. 5: "M400 pause",
  106. 6: "Paused (filament ran out)",
  107. 7: "Heating nozzle",
  108. 8: "Calibrating dynamic flow",
  109. 9: "Scanning bed surface",
  110. 10: "Inspecting first layer",
  111. 11: "Identifying build plate type",
  112. 12: "Calibrating Micro Lidar",
  113. 13: "Homing toolhead",
  114. 14: "Cleaning nozzle tip",
  115. 15: "Checking extruder temperature",
  116. 16: "Paused by the user",
  117. 17: "Pause (front cover fall off)",
  118. 18: "Calibrating the micro lidar",
  119. 19: "Calibrating flow ratio",
  120. 20: "Pause (nozzle temperature malfunction)",
  121. 21: "Pause (heatbed temperature malfunction)",
  122. 22: "Filament unloading",
  123. 23: "Pause (step loss)",
  124. 24: "Filament loading",
  125. 25: "Motor noise cancellation",
  126. 26: "Pause (AMS offline)",
  127. 27: "Pause (low speed of the heatbreak fan)",
  128. 28: "Pause (chamber temperature control problem)",
  129. 29: "Cooling chamber",
  130. 30: "Pause (Gcode inserted by user)",
  131. 31: "Motor noise showoff",
  132. 32: "Pause (nozzle clumping)",
  133. 33: "Pause (cutter error)",
  134. 34: "Pause (first layer error)",
  135. 35: "Pause (nozzle clog)",
  136. 36: "Measuring motion precision",
  137. 37: "Enhancing motion precision",
  138. 38: "Measure motion accuracy",
  139. 39: "Nozzle offset calibration",
  140. 40: "High temperature auto bed leveling",
  141. 41: "Auto Check: Quick Release Lever",
  142. 42: "Auto Check: Door and Upper Cover",
  143. 43: "Laser Calibration",
  144. 44: "Auto Check: Platform",
  145. 45: "Confirming BirdsEye Camera location",
  146. 46: "Calibrating BirdsEye Camera",
  147. 47: "Auto bed leveling - phase 1",
  148. 48: "Auto bed leveling - phase 2",
  149. 49: "Heating chamber",
  150. 50: "Cooling heatbed",
  151. 51: "Printing calibration lines",
  152. 52: "Auto Check: Material",
  153. 53: "Live View Camera Calibration",
  154. 54: "Waiting for heatbed temperature",
  155. 55: "Auto Check: Material Position",
  156. 56: "Cutting Module Offset Calibration",
  157. 57: "Measuring Surface",
  158. 58: "Thermal Preconditioning",
  159. 59: "Homing Blade Holder",
  160. 60: "Calibrating Camera Offset",
  161. 61: "Calibrating Blade Holder Position",
  162. 62: "Hotend Pick and Place Test",
  163. 63: "Waiting for Chamber temperature",
  164. 64: "Preparing Hotend",
  165. 65: "Calibrating nozzle clumping detection",
  166. 66: "Purifying the chamber air",
  167. }
  168. def get_stage_name(stage: int) -> str:
  169. """Get human-readable stage name from stage number."""
  170. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  171. class BambuMQTTClient:
  172. """MQTT client for Bambu Lab printer communication."""
  173. MQTT_PORT = 8883
  174. def __init__(
  175. self,
  176. ip_address: str,
  177. serial_number: str,
  178. access_code: str,
  179. on_state_change: Callable[[PrinterState], None] | None = None,
  180. on_print_start: Callable[[dict], None] | None = None,
  181. on_print_complete: Callable[[dict], None] | None = None,
  182. on_ams_change: Callable[[list], None] | None = None,
  183. ):
  184. self.ip_address = ip_address
  185. self.serial_number = serial_number
  186. self.access_code = access_code
  187. self.on_state_change = on_state_change
  188. self.on_print_start = on_print_start
  189. self.on_print_complete = on_print_complete
  190. self.on_ams_change = on_ams_change
  191. self.state = PrinterState()
  192. self._client: mqtt.Client | None = None
  193. self._loop: asyncio.AbstractEventLoop | None = None
  194. self._previous_gcode_state: str | None = None
  195. self._previous_gcode_file: str | None = None
  196. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  197. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  198. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  199. self._logging_enabled: bool = False
  200. self._last_message_time: float = 0.0 # Track when we last received a message
  201. self._previous_ams_hash: str | None = None # Track AMS changes
  202. # K-profile command tracking
  203. self._sequence_id: int = 0
  204. self._pending_kprofile_response: asyncio.Event | None = None
  205. self._kprofile_response_data: list | None = None
  206. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  207. # Key: module_name, Value: timestamp when command was sent
  208. self._xcam_hold_start: dict[str, float] = {}
  209. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  210. @property
  211. def topic_subscribe(self) -> str:
  212. return f"device/{self.serial_number}/report"
  213. @property
  214. def topic_publish(self) -> str:
  215. return f"device/{self.serial_number}/request"
  216. def _on_connect(self, client, userdata, flags, rc, properties=None):
  217. if rc == 0:
  218. self.state.connected = True
  219. client.subscribe(self.topic_subscribe)
  220. # Request full status update (includes nozzle info in push_status response)
  221. self._request_push_all()
  222. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  223. # The correct nozzle data comes from push_status.
  224. # Prime K-profile request (Bambu printers often ignore first request)
  225. self._prime_kprofile_request()
  226. # Immediately broadcast connection state change
  227. if self.on_state_change:
  228. self.on_state_change(self.state)
  229. else:
  230. self.state.connected = False
  231. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  232. # Ignore spurious disconnect callbacks if we've received a message recently
  233. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active
  234. time_since_last_message = time.time() - self._last_message_time
  235. if time_since_last_message < 30.0 and self._last_message_time > 0:
  236. logger.debug(
  237. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  238. )
  239. return
  240. logger.warning(f"[{self.serial_number}] MQTT disconnected: rc={rc}, flags={disconnect_flags}")
  241. self.state.connected = False
  242. if self.on_state_change:
  243. self.on_state_change(self.state)
  244. def _on_message(self, client, userdata, msg):
  245. try:
  246. payload = json.loads(msg.payload.decode())
  247. # Track last message time - receiving a message proves we're connected
  248. self._last_message_time = time.time()
  249. self.state.connected = True
  250. # Log message if logging is enabled
  251. if self._logging_enabled:
  252. self._message_log.append(MQTTLogEntry(
  253. timestamp=datetime.now().isoformat(),
  254. topic=msg.topic,
  255. direction="in",
  256. payload=payload,
  257. ))
  258. self._process_message(payload)
  259. except json.JSONDecodeError:
  260. pass
  261. def _process_message(self, payload: dict):
  262. """Process incoming MQTT message from printer."""
  263. # Handle top-level AMS data (comes outside of "print" key)
  264. # Wrap in try/except to prevent breaking the MQTT connection
  265. if "ams" in payload:
  266. try:
  267. self._handle_ams_data(payload["ams"])
  268. except Exception as e:
  269. logger.error(f"[{self.serial_number}] Error handling AMS data: {e}")
  270. # Handle xcam data (camera settings and AI detection) at top level
  271. if "xcam" in payload:
  272. xcam_data = payload["xcam"]
  273. logger.info(f"[{self.serial_number}] Received xcam data at top level: {xcam_data}")
  274. self._parse_xcam_data(xcam_data)
  275. # Fire state change callback for top-level xcam (not nested in "print")
  276. if "print" not in payload and self.on_state_change:
  277. self.on_state_change(self.state)
  278. # Handle system responses (accessories info, etc.)
  279. if "system" in payload:
  280. system_data = payload["system"]
  281. logger.info(f"[{self.serial_number}] Received system data: {system_data}")
  282. self._handle_system_response(system_data)
  283. if "print" in payload:
  284. print_data = payload["print"]
  285. # Check if xcam is nested inside print data
  286. if "xcam" in print_data:
  287. logger.info(f"[{self.serial_number}] Found xcam inside print data: {print_data['xcam']}")
  288. self._parse_xcam_data(print_data["xcam"])
  289. # Log when we see gcode_state changes
  290. if "gcode_state" in print_data:
  291. logger.info(
  292. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  293. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  294. )
  295. # Handle AMS data that comes inside print key
  296. if "ams" in print_data:
  297. try:
  298. self._handle_ams_data(print_data["ams"])
  299. except Exception as e:
  300. logger.error(f"[{self.serial_number}] Error handling AMS data from print: {e}")
  301. # Handle vt_tray (virtual tray / external spool) data
  302. if "vt_tray" in print_data:
  303. self.state.raw_data["vt_tray"] = print_data["vt_tray"]
  304. # Check for K-profile response (extrusion_cali)
  305. if "command" in print_data:
  306. logger.debug(f"[{self.serial_number}] Received command response: {print_data.get('command')}")
  307. if "command" in print_data and print_data.get("command") == "extrusion_cali_get":
  308. self._handle_kprofile_response(print_data)
  309. self._update_state(print_data)
  310. def _handle_system_response(self, data: dict):
  311. """Handle system responses including accessories info.
  312. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  313. The correct nozzle data comes from push_status, so we don't update
  314. nozzle type/diameter from get_accessories. We just log the response
  315. for debugging purposes.
  316. """
  317. command = data.get("command")
  318. if command == "get_accessories":
  319. # Log response for debugging - but DON'T use it to update nozzle data
  320. # because it returns stale values (e.g., 'stainless_steel' when the
  321. # actual nozzle is 'HH01' hardened steel high-flow)
  322. logger.info(f"[{self.serial_number}] Accessories response (not used for nozzle data): {data}")
  323. def _parse_xcam_data(self, xcam_data):
  324. """Parse xcam data for camera settings and AI detection options."""
  325. if not isinstance(xcam_data, dict):
  326. return
  327. current_time = time.time()
  328. # Helper to check if we should accept incoming value for a module
  329. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  330. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  331. """Check if we should accept an incoming xcam value.
  332. OrcaSlicer pattern: After sending a command, ignore incoming data
  333. for 3 seconds. After that, accept whatever the printer sends.
  334. """
  335. if module_name not in self._xcam_hold_start:
  336. return True # No hold timer, accept incoming
  337. hold_start = self._xcam_hold_start[module_name]
  338. elapsed = current_time - hold_start
  339. if elapsed > self._xcam_hold_time:
  340. # Hold timer expired - accept incoming and clear hold
  341. del self._xcam_hold_start[module_name]
  342. logger.debug(
  343. f"[{self.serial_number}] Hold expired for {module_name}, accepting {incoming_value}"
  344. )
  345. return True
  346. # Within hold period - ignore incoming data
  347. logger.debug(
  348. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  349. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  350. )
  351. return False
  352. # Log all xcam fields for debugging
  353. logger.debug(f"[{self.serial_number}] Parsing xcam data - all fields: {list(xcam_data.keys())}")
  354. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  355. # fields (spaghetti_detector, etc.) are often stale/cached.
  356. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  357. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  358. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  359. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  360. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  361. # Sensitivity values: 0=low, 1=medium, 2=high
  362. if "cfg" in xcam_data:
  363. cfg = xcam_data["cfg"]
  364. logger.debug(f"[{self.serial_number}] xcam cfg bitmask: {cfg} (binary: {bin(cfg)})")
  365. def decode_detector(start_bit):
  366. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  367. sens_bits = (cfg >> start_bit) & 0x3
  368. enabled = bool((cfg >> (start_bit + 2)) & 1)
  369. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  370. return enabled, sensitivity
  371. # Spaghetti detector (bits 5-7)
  372. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  373. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  374. old_value = self.state.print_options.spaghetti_detector
  375. if cfg_spaghetti != old_value:
  376. logger.info(f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}")
  377. self.state.print_options.spaghetti_detector = cfg_spaghetti
  378. # Check hold timer for sensitivity before accepting
  379. if "halt_print_sensitivity" not in self._xcam_hold_start:
  380. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  381. logger.info(
  382. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  383. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  384. )
  385. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  386. else:
  387. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  388. elapsed = current_time - hold_start
  389. if elapsed <= self._xcam_hold_time:
  390. logger.debug(
  391. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  392. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  393. )
  394. else:
  395. # Hold expired - accept from cfg
  396. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  397. logger.info(
  398. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  399. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  400. )
  401. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  402. del self._xcam_hold_start["halt_print_sensitivity"]
  403. # Pileup detector (bits 8-10)
  404. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  405. if should_accept_value("pileup_detector", cfg_pileup):
  406. if cfg_pileup != self.state.print_options.pileup_detector:
  407. logger.info(f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}")
  408. self.state.print_options.pileup_detector = cfg_pileup
  409. # Pileup sensitivity with hold timer
  410. if "pileup_sensitivity" not in self._xcam_hold_start:
  411. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  412. logger.info(f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}")
  413. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  414. else:
  415. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  416. elapsed = current_time - hold_start
  417. if elapsed > self._xcam_hold_time:
  418. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  419. logger.info(f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}")
  420. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  421. del self._xcam_hold_start["pileup_sensitivity"]
  422. # Clump/nozzle clumping detector (bits 11-13)
  423. cfg_clump, cfg_clump_sens = decode_detector(11)
  424. if should_accept_value("clump_detector", cfg_clump):
  425. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  426. logger.info(f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}")
  427. self.state.print_options.nozzle_clumping_detector = cfg_clump
  428. # Clump sensitivity with hold timer
  429. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  430. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  431. logger.info(f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}")
  432. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  433. else:
  434. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  435. elapsed = current_time - hold_start
  436. if elapsed > self._xcam_hold_time:
  437. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  438. logger.info(f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}")
  439. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  440. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  441. # Airprint detector (bits 14-16)
  442. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  443. if should_accept_value("airprint_detector", cfg_airprint):
  444. if cfg_airprint != self.state.print_options.airprint_detector:
  445. logger.info(f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}")
  446. self.state.print_options.airprint_detector = cfg_airprint
  447. # Airprint sensitivity with hold timer
  448. if "airprint_sensitivity" not in self._xcam_hold_start:
  449. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  450. logger.info(f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}")
  451. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  452. else:
  453. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  454. elapsed = current_time - hold_start
  455. if elapsed > self._xcam_hold_time:
  456. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  457. logger.info(f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}")
  458. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  459. del self._xcam_hold_start["airprint_sensitivity"]
  460. # Camera settings
  461. if "ipcam_record" in xcam_data:
  462. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  463. if "timelapse" in xcam_data:
  464. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  465. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  466. if "print_halt" in xcam_data:
  467. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  468. # Skip halt_print_sensitivity field - it's always stale ("medium")
  469. # We read the actual sensitivity from cfg bits 5-6 above
  470. if "first_layer_inspector" in xcam_data:
  471. new_value = bool(xcam_data.get("first_layer_inspector"))
  472. if should_accept_value("first_layer_inspector", new_value):
  473. self.state.print_options.first_layer_inspector = new_value
  474. if "printing_monitor" in xcam_data:
  475. new_value = bool(xcam_data.get("printing_monitor"))
  476. if should_accept_value("printing_monitor", new_value):
  477. self.state.print_options.printing_monitor = new_value
  478. if "buildplate_marker_detector" in xcam_data:
  479. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  480. if should_accept_value("buildplate_marker_detector", new_value):
  481. self.state.print_options.buildplate_marker_detector = new_value
  482. if "allow_skip_parts" in xcam_data:
  483. new_value = bool(xcam_data.get("allow_skip_parts"))
  484. if should_accept_value("allow_skip_parts", new_value):
  485. self.state.print_options.allow_skip_parts = new_value
  486. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  487. # individual boolean fields (which are not sent by the printer)
  488. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  489. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  490. if "auto_recovery_step_loss" in xcam_data:
  491. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  492. if "filament_tangle_detect" in xcam_data:
  493. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  494. def _handle_ams_data(self, ams_data):
  495. """Handle AMS data changes for Spoolman integration.
  496. This is called when we receive top-level AMS data in MQTT messages.
  497. It detects changes and triggers the callback for Spoolman sync.
  498. """
  499. import hashlib
  500. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  501. if isinstance(ams_data, dict) and "ams" in ams_data:
  502. ams_list = ams_data["ams"]
  503. elif isinstance(ams_data, list):
  504. ams_list = ams_data
  505. else:
  506. logger.warning(f"[{self.serial_number}] Unexpected AMS data format: {type(ams_data)}")
  507. return
  508. # Store AMS data in raw_data so it's accessible via API
  509. self.state.raw_data["ams"] = ams_list
  510. logger.debug(f"[{self.serial_number}] Stored AMS data with {len(ams_list)} units")
  511. # Create a hash of relevant AMS data to detect changes
  512. ams_hash_data = []
  513. for ams_unit in ams_list:
  514. for tray in ams_unit.get("tray", []):
  515. # Include fields that matter for filament tracking
  516. ams_hash_data.append(
  517. f"{ams_unit.get('id')}:{tray.get('id')}:"
  518. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  519. )
  520. ams_hash = hashlib.md5(":".join(ams_hash_data).encode()).hexdigest()
  521. # Only trigger callback if AMS data actually changed
  522. if ams_hash != self._previous_ams_hash:
  523. self._previous_ams_hash = ams_hash
  524. if self.on_ams_change:
  525. logger.info(f"[{self.serial_number}] AMS data changed, triggering sync callback")
  526. self.on_ams_change(ams_list)
  527. def _update_state(self, data: dict):
  528. """Update printer state from message data."""
  529. previous_state = self.state.state
  530. # Update state fields
  531. if "gcode_state" in data:
  532. self.state.state = data["gcode_state"]
  533. if "gcode_file" in data:
  534. self.state.gcode_file = data["gcode_file"]
  535. self.state.current_print = data["gcode_file"]
  536. if "subtask_name" in data:
  537. self.state.subtask_name = data["subtask_name"]
  538. # Prefer subtask_name as current_print if available
  539. if data["subtask_name"]:
  540. self.state.current_print = data["subtask_name"]
  541. if "subtask_id" in data:
  542. self.state.subtask_id = data["subtask_id"]
  543. if "mc_percent" in data:
  544. self.state.progress = float(data["mc_percent"])
  545. if "mc_remaining_time" in data:
  546. self.state.remaining_time = int(data["mc_remaining_time"])
  547. if "layer_num" in data:
  548. self.state.layer_num = int(data["layer_num"])
  549. if "total_layer_num" in data:
  550. self.state.total_layers = int(data["total_layer_num"])
  551. # Calibration stage tracking
  552. if "stg_cur" in data:
  553. new_stg = data["stg_cur"]
  554. if new_stg != self.state.stg_cur:
  555. logger.info(
  556. f"[{self.serial_number}] Calibration stage changed: "
  557. f"{self.state.stg_cur} -> {new_stg} ({get_stage_name(new_stg)})"
  558. )
  559. self.state.stg_cur = new_stg
  560. if "stg" in data:
  561. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  562. # Temperature data
  563. temps = {}
  564. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  565. if "bed_temper" in data and not hasattr(self, '_temp_fields_logged'):
  566. temp_fields = {k: v for k, v in data.items() if 'temp' in k.lower() or 'chamber' in k.lower()}
  567. logger.info(f"[{self.serial_number}] Temperature-related fields: {temp_fields}")
  568. # Log ALL keys in print data for H2D temperature discovery
  569. all_keys = sorted(data.keys())
  570. logger.info(f"[{self.serial_number}] ALL print data keys ({len(all_keys)}): {all_keys}")
  571. self._temp_fields_logged = True
  572. # Log nozzle hardware info fields (once)
  573. nozzle_fields = {k: v for k, v in data.items() if 'nozzle' in k.lower() or 'hw' in k.lower() or 'extruder' in k.lower() or 'upgrade' in k.lower()}
  574. if nozzle_fields and not hasattr(self, '_nozzle_fields_logged'):
  575. logger.info(f"[{self.serial_number}] Nozzle/hardware fields in MQTT data: {nozzle_fields}")
  576. self._nozzle_fields_logged = True
  577. if "bed_temper" in data:
  578. temps["bed"] = float(data["bed_temper"])
  579. if "bed_target_temper" in data:
  580. temps["bed_target"] = float(data["bed_target_temper"])
  581. # Check if this is H2D (has device.extruder.info with 2 extruders)
  582. has_h2d_extruder_info = (
  583. "device" in data and
  584. isinstance(data.get("device"), dict) and
  585. "extruder" in data["device"] and
  586. isinstance(data["device"]["extruder"].get("info"), list) and
  587. len(data["device"]["extruder"]["info"]) >= 2
  588. )
  589. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  590. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  591. if "nozzle_temper" in data:
  592. if has_h2d_extruder_info:
  593. temps["nozzle_2"] = float(data["nozzle_temper"]) # RIGHT nozzle on H2D
  594. else:
  595. temps["nozzle"] = float(data["nozzle_temper"])
  596. if "nozzle_target_temper" in data:
  597. if has_h2d_extruder_info:
  598. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  599. else:
  600. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  601. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  602. if not has_h2d_extruder_info:
  603. # Try multiple possible field names used by different firmware versions
  604. if "nozzle_temper_2" in data:
  605. val = float(data["nozzle_temper_2"])
  606. if -50 < val < 500: # Valid temp range
  607. temps["nozzle_2"] = val
  608. else:
  609. logger.debug(f"[{self.serial_number}] nozzle_temper_2={val} out of range")
  610. elif "right_nozzle_temper" in data:
  611. val = float(data["right_nozzle_temper"])
  612. if -50 < val < 500: # Valid temp range
  613. temps["nozzle_2"] = val
  614. else:
  615. logger.debug(f"[{self.serial_number}] right_nozzle_temper={val} out of range")
  616. if "nozzle_target_temper_2" in data:
  617. val = float(data["nozzle_target_temper_2"])
  618. if 0 <= val < 500: # Valid temp range
  619. temps["nozzle_2_target"] = val
  620. else:
  621. logger.debug(f"[{self.serial_number}] nozzle_target_temper_2={val} out of range")
  622. elif "right_nozzle_target_temper" in data:
  623. val = float(data["right_nozzle_target_temper"])
  624. if 0 <= val < 500: # Valid temp range
  625. temps["nozzle_2_target"] = val
  626. else:
  627. logger.debug(f"[{self.serial_number}] right_nozzle_target_temper={val} out of range")
  628. # Also check for left nozzle as primary (some H2 models)
  629. if "left_nozzle_temper" in data and "nozzle" not in temps:
  630. temps["nozzle"] = float(data["left_nozzle_temper"])
  631. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  632. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  633. if "chamber_temper" in data:
  634. temps["chamber"] = float(data["chamber_temper"])
  635. # Chamber target temperature (set by print file or display)
  636. if "mc_target_cham" in data:
  637. temps["chamber_target"] = float(data["mc_target_cham"])
  638. # H2D series: Chamber temp is in info.temp (directly in °C)
  639. try:
  640. if "info" in data and isinstance(data["info"], dict):
  641. info_temp = data["info"].get("temp")
  642. if info_temp is not None and "chamber" not in temps:
  643. temps["chamber"] = float(info_temp)
  644. # H2D series: Dual extruder temps are in device.extruder.info array
  645. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  646. if "device" in data and isinstance(data["device"], dict):
  647. device = data["device"]
  648. # Parse dual extruder temperatures
  649. extruder_data = device.get("extruder", {})
  650. extruder_info = extruder_data.get("info", [])
  651. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  652. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  653. # RIGHT nozzle uses standard nozzle_temper/nozzle_target_temper fields (already parsed above)
  654. # LEFT nozzle uses extruder_info[1] - no standard fields available
  655. # Note: hnow/htar flags are unreliable (static values, not actual heating state)
  656. # Real heating indicator: temp > 500 means encoded (target*65536+current)
  657. # Heating = target > 0 AND current < target
  658. # Right nozzle (extruder 0)
  659. if len(extruder_info) >= 1 and "temp" in extruder_info[0]:
  660. temp_val = extruder_info[0]["temp"]
  661. if temp_val > 500:
  662. target = temp_val // 65536
  663. current = temp_val % 65536
  664. temps["nozzle_2_heating"] = target > 0 and current < target
  665. else:
  666. temps["nozzle_2_heating"] = False
  667. # Left nozzle (extruder 1)
  668. # H2D protocol: temp field encoding depends on value
  669. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  670. # - When < 500: direct Celsius current temp only - heater is OFF
  671. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  672. ext1 = extruder_info[1]
  673. temp_val = ext1["temp"]
  674. # Check if we recently set the target locally (within 5 seconds)
  675. # If so, don't let MQTT data overwrite it
  676. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  677. respect_local_target = (time.time() - local_set_time) < 5.0
  678. if temp_val > 500:
  679. # Encoded format: temp = target * 65536 + current
  680. target = temp_val // 65536
  681. current = temp_val % 65536
  682. if 0 < target < 500 and not respect_local_target:
  683. temps["nozzle_target"] = float(target)
  684. if -50 < current < 500:
  685. temps["nozzle"] = float(current)
  686. # Heating = encoded AND we're using the MQTT target (not local override)
  687. # If local target is being respected, use local target to determine heating
  688. if respect_local_target:
  689. local_target = self.state.temperatures.get("nozzle_target", 0)
  690. temps["nozzle_heating"] = local_target > 0 and current < local_target
  691. else:
  692. temps["nozzle_heating"] = target > 0 and current < target
  693. elif -50 < temp_val < 500:
  694. # Direct Celsius = heater is OFF (or at target with heater off)
  695. temps["nozzle"] = float(temp_val)
  696. if not respect_local_target:
  697. temps["nozzle_target"] = 0.0
  698. temps["nozzle_heating"] = False # Direct = not heating
  699. # Parse bed heating state from device.bed.info.temp encoding
  700. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  701. bed_data = device.get("bed", {})
  702. bed_info = bed_data.get("info", {})
  703. if "temp" in bed_info:
  704. temp_val = bed_info["temp"]
  705. if temp_val > 500:
  706. target = temp_val // 65536
  707. current = temp_val % 65536
  708. temps["bed_heating"] = target > 0 and current < target
  709. else:
  710. temps["bed_heating"] = False
  711. # Parse chamber temp from device.ctc.info.temp if not already set
  712. ctc_data = device.get("ctc", {})
  713. ctc_info = ctc_data.get("info", {})
  714. # Parse airduct mode (0=cooling, 1=heating)
  715. airduct_data = device.get("airduct", {})
  716. if "modeCur" in airduct_data:
  717. new_mode = airduct_data["modeCur"]
  718. if new_mode != self.state.airduct_mode:
  719. logger.info(f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}")
  720. self.state.airduct_mode = new_mode
  721. if "temp" in ctc_info and "chamber" not in temps:
  722. temps["chamber"] = float(ctc_info["temp"])
  723. # Parse chamber target from ctc.info.target if available
  724. if "target" in ctc_info and "chamber_target" not in temps:
  725. temps["chamber_target"] = float(ctc_info["target"])
  726. # Parse chamber heating state from temp encoding
  727. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  728. if "temp" in ctc_info:
  729. temp_val = ctc_info["temp"]
  730. if temp_val > 500:
  731. target = temp_val // 65536
  732. current = temp_val % 65536
  733. temps["chamber_heating"] = target > 0 and current < target
  734. else:
  735. temps["chamber_heating"] = False
  736. except Exception as e:
  737. logger.warning(f"[{self.serial_number}] Error parsing H2D temperatures: {e}")
  738. if temps:
  739. # Merge new temps into existing, preserving valid values when new ones are filtered out
  740. for key, value in temps.items():
  741. self.state.temperatures[key] = value
  742. # Parse HMS (Health Management System) errors
  743. if "hms" in data:
  744. hms_list = data["hms"]
  745. self.state.hms_errors = []
  746. if isinstance(hms_list, list):
  747. for hms in hms_list:
  748. if isinstance(hms, dict):
  749. # HMS format: {"attr": code, "code": full_code}
  750. # The code is a hex string, severity is in bits
  751. code = hms.get("code", hms.get("attr", "0"))
  752. if isinstance(code, int):
  753. code = hex(code)
  754. # Parse severity from code (typically last 4 bits indicate level)
  755. try:
  756. code_int = int(str(code).replace("0x", ""), 16) if code else 0
  757. severity = (code_int >> 16) & 0xF # Extract severity bits
  758. module = (code_int >> 24) & 0xFF # Extract module bits
  759. except (ValueError, TypeError):
  760. severity = 3
  761. module = 0
  762. self.state.hms_errors.append(HMSError(
  763. code=str(code),
  764. module=module,
  765. severity=severity if severity > 0 else 3,
  766. ))
  767. # Parse SD card status
  768. if "sdcard" in data:
  769. self.state.sdcard = data["sdcard"] is True
  770. # Parse home_flag for "Store Sent Files on External Storage" setting (bit 11)
  771. if "home_flag" in data:
  772. home_flag = data["home_flag"]
  773. # Bit 11 controls "Store Sent Files on External Storage"
  774. # Convert to unsigned 32-bit if negative
  775. if home_flag < 0:
  776. home_flag = home_flag & 0xFFFFFFFF
  777. store_to_sdcard = bool((home_flag >> 11) & 1)
  778. if store_to_sdcard != self.state.store_to_sdcard:
  779. logger.info(f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}")
  780. self.state.store_to_sdcard = store_to_sdcard
  781. # Parse timelapse status (recording active during print)
  782. if "timelapse" in data:
  783. logger.debug(f"[{self.serial_number}] timelapse field: {data['timelapse']}")
  784. self.state.timelapse = data["timelapse"] is True
  785. # Parse ipcam/live view status
  786. if "ipcam" in data:
  787. ipcam_data = data["ipcam"]
  788. logger.debug(f"[{self.serial_number}] ipcam field: {ipcam_data}")
  789. if isinstance(ipcam_data, dict):
  790. # Check ipcam_record field for live view status
  791. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  792. else:
  793. self.state.ipcam = ipcam_data is True
  794. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  795. if "spd_lvl" in data:
  796. new_speed = data["spd_lvl"]
  797. if new_speed != self.state.speed_level:
  798. logger.info(f"[{self.serial_number}] speed_level changed: {self.state.speed_level} -> {new_speed}")
  799. self.state.speed_level = new_speed
  800. # Parse chamber light status from lights_report
  801. if "lights_report" in data:
  802. lights = data["lights_report"]
  803. logger.debug(f"[{self.serial_number}] lights_report: {lights}")
  804. if isinstance(lights, list):
  805. for light in lights:
  806. if isinstance(light, dict) and light.get("node") == "chamber_light":
  807. new_light_state = light.get("mode") == "on"
  808. if new_light_state != self.state.chamber_light:
  809. logger.info(f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}")
  810. self.state.chamber_light = new_light_state
  811. break
  812. # Parse nozzle hardware info (single nozzle printers)
  813. if "nozzle_type" in data:
  814. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  815. if "nozzle_diameter" in data:
  816. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  817. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  818. # Left nozzle
  819. if "left_nozzle_type" in data:
  820. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  821. if "left_nozzle_diameter" in data:
  822. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  823. # Right nozzle
  824. if "right_nozzle_type" in data:
  825. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  826. if "right_nozzle_diameter" in data:
  827. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  828. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  829. if "nozzle_type_2" in data:
  830. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  831. if "nozzle_diameter_2" in data:
  832. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  833. # H2D series: Nozzle hardware info is in device.nozzle.info array
  834. if "device" in data and isinstance(data["device"], dict):
  835. device = data["device"]
  836. nozzle_data = device.get("nozzle", {})
  837. nozzle_info = nozzle_data.get("info", [])
  838. if isinstance(nozzle_info, list):
  839. for nozzle in nozzle_info:
  840. idx = nozzle.get("id", 0)
  841. if idx < len(self.state.nozzles):
  842. if "type" in nozzle and nozzle["type"]:
  843. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  844. if "diameter" in nozzle:
  845. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  846. # Preserve AMS and vt_tray data when updating raw_data
  847. ams_data = self.state.raw_data.get("ams")
  848. vt_tray_data = self.state.raw_data.get("vt_tray")
  849. self.state.raw_data = data
  850. if ams_data is not None:
  851. self.state.raw_data["ams"] = ams_data
  852. if vt_tray_data is not None:
  853. self.state.raw_data["vt_tray"] = vt_tray_data
  854. # Log state transitions for debugging
  855. if "gcode_state" in data:
  856. logger.debug(
  857. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  858. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  859. )
  860. # Detect print start (state changes TO RUNNING with a file)
  861. current_file = self.state.gcode_file or self.state.current_print
  862. is_new_print = (
  863. self.state.state == "RUNNING"
  864. and self._previous_gcode_state != "RUNNING"
  865. and current_file
  866. )
  867. # Also detect if file changed while running (new print started)
  868. is_file_change = (
  869. self.state.state == "RUNNING"
  870. and current_file
  871. and current_file != self._previous_gcode_file
  872. and self._previous_gcode_file is not None
  873. )
  874. # Track RUNNING state for more robust completion detection
  875. if self.state.state == "RUNNING" and current_file:
  876. if not self._was_running:
  877. logger.info(f"[{self.serial_number}] Now tracking RUNNING state for {current_file}")
  878. self._was_running = True
  879. self._completion_triggered = False
  880. if is_new_print or is_file_change:
  881. # Clear any old HMS errors when a new print starts
  882. self.state.hms_errors = []
  883. # Reset completion tracking for new print
  884. self._was_running = True
  885. self._completion_triggered = False
  886. if (is_new_print or is_file_change) and self.on_print_start:
  887. logger.info(
  888. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  889. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  890. )
  891. self.on_print_start({
  892. "filename": current_file,
  893. "subtask_name": self.state.subtask_name,
  894. "raw_data": data,
  895. })
  896. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  897. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  898. # This handles cases where server restarts during a print
  899. should_trigger_completion = (
  900. self.state.state in ("FINISH", "FAILED")
  901. and not self._completion_triggered
  902. and self.on_print_complete
  903. and (
  904. self._previous_gcode_state == "RUNNING" # Normal transition
  905. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  906. )
  907. )
  908. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  909. if (
  910. self.state.state == "IDLE"
  911. and self._previous_gcode_state == "RUNNING"
  912. and not self._completion_triggered
  913. and self.on_print_complete
  914. ):
  915. should_trigger_completion = True
  916. if should_trigger_completion:
  917. if self.state.state == "FINISH":
  918. status = "completed"
  919. elif self.state.state == "FAILED":
  920. status = "failed"
  921. else:
  922. status = "aborted"
  923. logger.info(
  924. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  925. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  926. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}"
  927. )
  928. self._completion_triggered = True
  929. self._was_running = False
  930. self.on_print_complete({
  931. "status": status,
  932. "filename": self._previous_gcode_file or current_file,
  933. "subtask_name": self.state.subtask_name,
  934. "raw_data": data,
  935. })
  936. self._previous_gcode_state = self.state.state
  937. if current_file:
  938. self._previous_gcode_file = current_file
  939. if self.on_state_change:
  940. self.on_state_change(self.state)
  941. def _request_push_all(self):
  942. """Request full status update from printer."""
  943. if self._client:
  944. message = {"pushing": {"command": "pushall"}}
  945. self._client.publish(self.topic_publish, json.dumps(message))
  946. def request_status_update(self) -> bool:
  947. """Request a full status update from the printer (public API).
  948. Sends both pushall and get_accessories commands to refresh all data
  949. including nozzle hardware info.
  950. Returns:
  951. True if the request was sent, False if not connected.
  952. """
  953. if not self._client or not self.state.connected:
  954. return False
  955. self._request_push_all()
  956. # Note: get_accessories returns stale nozzle data on H2D.
  957. # The correct nozzle data comes from push_status response.
  958. return True
  959. def _request_accessories(self):
  960. """Request accessories info (nozzle type, etc.) from printer."""
  961. if self._client:
  962. self._sequence_id += 1
  963. message = {
  964. "system": {
  965. "sequence_id": str(self._sequence_id),
  966. "command": "get_accessories",
  967. "accessory_type": "none"
  968. }
  969. }
  970. logger.debug(f"[{self.serial_number}] Requesting accessories info")
  971. self._client.publish(self.topic_publish, json.dumps(message))
  972. def _prime_kprofile_request(self):
  973. """Send a priming K-profile request on connect.
  974. Bambu printers often ignore the first K-profile request after connection,
  975. so we send a dummy request on connect to 'prime' the system.
  976. """
  977. if self._client:
  978. self._sequence_id += 1
  979. command = {
  980. "print": {
  981. "command": "extrusion_cali_get",
  982. "filament_id": "",
  983. "nozzle_diameter": "0.4",
  984. "sequence_id": str(self._sequence_id),
  985. }
  986. }
  987. logger.debug(f"[{self.serial_number}] Sending K-profile priming request")
  988. self._client.publish(self.topic_publish, json.dumps(command))
  989. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  990. """Connect to the printer MQTT broker.
  991. Args:
  992. loop: The asyncio event loop to use for thread-safe callbacks.
  993. If not provided, will try to get the running loop.
  994. """
  995. self._loop = loop
  996. self._client = mqtt.Client(
  997. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  998. client_id=f"bambutrack_{self.serial_number}",
  999. protocol=mqtt.MQTTv311,
  1000. )
  1001. self._client.username_pw_set("bblp", self.access_code)
  1002. self._client.on_connect = self._on_connect
  1003. self._client.on_disconnect = self._on_disconnect
  1004. self._client.on_message = self._on_message
  1005. # TLS setup - Bambu uses self-signed certs
  1006. ssl_context = ssl.create_default_context()
  1007. ssl_context.check_hostname = False
  1008. ssl_context.verify_mode = ssl.CERT_NONE
  1009. self._client.tls_set_context(ssl_context)
  1010. # Use shorter keepalive (15s) for faster disconnect detection
  1011. # Paho considers connection lost after 1.5x keepalive with no response
  1012. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=15)
  1013. self._client.loop_start()
  1014. def start_print(self, filename: str, plate_id: int = 1):
  1015. """Start a print job on the printer.
  1016. The file should already be uploaded to /cache/ on the printer via FTP.
  1017. """
  1018. if self._client and self.state.connected:
  1019. # Bambu print command format
  1020. # Based on: https://github.com/darkorb/bambu-ftp-and-print
  1021. command = {
  1022. "print": {
  1023. "sequence_id": 0,
  1024. "command": "project_file",
  1025. "param": f"Metadata/plate_{plate_id}.gcode",
  1026. "subtask_name": filename,
  1027. "url": f"ftp://{filename}",
  1028. "timelapse": False,
  1029. "bed_leveling": True,
  1030. "flow_cali": True,
  1031. "vibration_cali": True,
  1032. "layer_inspect": False,
  1033. "use_ams": True,
  1034. }
  1035. }
  1036. logger.info(f"[{self.serial_number}] Sending print command: {json.dumps(command)}")
  1037. self._client.publish(self.topic_publish, json.dumps(command))
  1038. return True
  1039. return False
  1040. def stop_print(self) -> bool:
  1041. """Stop the current print job."""
  1042. if self._client and self.state.connected:
  1043. command = {
  1044. "print": {
  1045. "command": "stop",
  1046. "sequence_id": "0"
  1047. }
  1048. }
  1049. self._client.publish(self.topic_publish, json.dumps(command))
  1050. logger.info(f"[{self.serial_number}] Sent stop print command")
  1051. return True
  1052. return False
  1053. def set_xcam_option(
  1054. self,
  1055. module_name: str,
  1056. enabled: bool,
  1057. print_halt: bool = True,
  1058. sensitivity: str = "medium"
  1059. ) -> bool:
  1060. """Set an xcam (AI detection) option on the printer.
  1061. Args:
  1062. module_name: The xcam module to control (e.g., "spaghetti_detector",
  1063. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  1064. enabled: Whether to enable or disable the feature
  1065. print_halt: Whether to halt print on detection (only applies to some detectors)
  1066. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  1067. Returns:
  1068. True if command was sent, False if not connected
  1069. """
  1070. if not self._client or not self.state.connected:
  1071. return False
  1072. # auto_recovery_step_loss uses a different command format (print.print_option)
  1073. if module_name == "auto_recovery_step_loss":
  1074. return self._set_print_option("auto_recovery", enabled)
  1075. self._sequence_id += 1
  1076. # Build the xcam control command (exact OrcaSlicer format)
  1077. # Key findings from OrcaSlicer source:
  1078. # - Uses "xcam" wrapper (not "print")
  1079. # - print_halt is ALWAYS true (legacy protocol requirement)
  1080. # - Both "control" and "enable" are set to the same value
  1081. # - halt_print_sensitivity controls actual halt behavior
  1082. command = {
  1083. "xcam": {
  1084. "command": "xcam_control_set",
  1085. "sequence_id": str(self._sequence_id),
  1086. "module_name": module_name,
  1087. "control": enabled,
  1088. "enable": enabled, # old protocol compatibility
  1089. "print_halt": True, # ALWAYS true per OrcaSlicer
  1090. }
  1091. }
  1092. # Only add sensitivity if not "never_halt"
  1093. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  1094. # The module_name field determines which detector's sensitivity is being set
  1095. if sensitivity and sensitivity != "never_halt":
  1096. command["xcam"]["halt_print_sensitivity"] = sensitivity
  1097. command_json = json.dumps(command)
  1098. self._client.publish(self.topic_publish, command_json, qos=1)
  1099. logger.info(f"[{self.serial_number}] Set xcam option: {module_name}={enabled}, sensitivity={sensitivity}")
  1100. logger.debug(f"[{self.serial_number}] MQTT command sent: {command_json}")
  1101. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  1102. # This prevents stale MQTT data from immediately overwriting our change
  1103. self._xcam_hold_start[module_name] = time.time()
  1104. # Update local state immediately for responsive UI
  1105. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  1106. # When spaghetti_detector sensitivity is changed, pileup also changes
  1107. if module_name == "spaghetti_detector":
  1108. self.state.print_options.spaghetti_detector = enabled
  1109. self.state.print_options.print_halt = print_halt
  1110. if sensitivity and sensitivity != "never_halt":
  1111. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  1112. self.state.print_options.halt_print_sensitivity = sensitivity
  1113. self.state.print_options.pileup_sensitivity = sensitivity
  1114. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  1115. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  1116. elif module_name == "first_layer_inspector":
  1117. self.state.print_options.first_layer_inspector = enabled
  1118. elif module_name == "printing_monitor":
  1119. self.state.print_options.printing_monitor = enabled
  1120. elif module_name == "buildplate_marker_detector":
  1121. self.state.print_options.buildplate_marker_detector = enabled
  1122. elif module_name == "allow_skip_parts":
  1123. self.state.print_options.allow_skip_parts = enabled
  1124. elif module_name == "pileup_detector":
  1125. self.state.print_options.pileup_detector = enabled
  1126. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  1127. elif module_name == "clump_detector":
  1128. self.state.print_options.nozzle_clumping_detector = enabled
  1129. if sensitivity and sensitivity != "never_halt":
  1130. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  1131. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  1132. elif module_name == "airprint_detector":
  1133. self.state.print_options.airprint_detector = enabled
  1134. if sensitivity and sensitivity != "never_halt":
  1135. self.state.print_options.airprint_sensitivity = sensitivity
  1136. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  1137. elif module_name == "auto_recovery_step_loss":
  1138. self.state.print_options.auto_recovery_step_loss = enabled
  1139. return True
  1140. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  1141. """Set a print option using the print.print_option command.
  1142. This is different from xcam_control_set and is used for options like:
  1143. - auto_recovery
  1144. - air_print_detect
  1145. - filament_tangle_detect
  1146. - nozzle_blob_detect
  1147. - sound_enable
  1148. Args:
  1149. option_name: The option to control (e.g., "auto_recovery")
  1150. enabled: Whether to enable or disable the option
  1151. Returns:
  1152. True if command was sent, False if not connected
  1153. """
  1154. if not self._client or not self.state.connected:
  1155. return False
  1156. self._sequence_id += 1
  1157. command = {
  1158. "print": {
  1159. "command": "print_option",
  1160. "sequence_id": str(self._sequence_id),
  1161. option_name: enabled,
  1162. }
  1163. }
  1164. command_json = json.dumps(command)
  1165. self._client.publish(self.topic_publish, command_json, qos=1)
  1166. logger.info(f"[{self.serial_number}] Set print option: {option_name}={enabled}")
  1167. # Set hold timer
  1168. hold_key = f"print_option_{option_name}"
  1169. self._xcam_hold_start[hold_key] = time.time()
  1170. # Update local state immediately
  1171. if option_name == "auto_recovery":
  1172. self.state.print_options.auto_recovery_step_loss = enabled
  1173. return True
  1174. def start_calibration(
  1175. self,
  1176. bed_leveling: bool = False,
  1177. vibration: bool = False,
  1178. motor_noise: bool = False,
  1179. nozzle_offset: bool = False,
  1180. high_temp_heatbed: bool = False,
  1181. ) -> bool:
  1182. """Start printer calibration with selected options.
  1183. Args:
  1184. bed_leveling: Run bed leveling calibration
  1185. vibration: Run vibration compensation calibration
  1186. motor_noise: Run motor noise cancellation calibration
  1187. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  1188. high_temp_heatbed: Run high-temperature heatbed calibration
  1189. Returns:
  1190. True if command was sent, False if not connected
  1191. """
  1192. if not self._client or not self.state.connected:
  1193. return False
  1194. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  1195. # Bit 0: xcam_cali (not exposed in UI)
  1196. # Bit 1: bed_leveling
  1197. # Bit 2: vibration
  1198. # Bit 3: motor_noise
  1199. # Bit 4: nozzle_cali
  1200. # Bit 5: bed_cali (high-temp heatbed)
  1201. # Bit 6: clumppos_cali (not exposed in UI)
  1202. option = 0
  1203. if bed_leveling:
  1204. option |= 1 << 1
  1205. if vibration:
  1206. option |= 1 << 2
  1207. if motor_noise:
  1208. option |= 1 << 3
  1209. if nozzle_offset:
  1210. option |= 1 << 4
  1211. if high_temp_heatbed:
  1212. option |= 1 << 5
  1213. if option == 0:
  1214. logger.warning(f"[{self.serial_number}] No calibration options selected")
  1215. return False
  1216. self._sequence_id += 1
  1217. command = {
  1218. "print": {
  1219. "command": "calibration",
  1220. "sequence_id": str(self._sequence_id),
  1221. "option": option,
  1222. }
  1223. }
  1224. command_json = json.dumps(command)
  1225. self._client.publish(self.topic_publish, command_json, qos=1)
  1226. logger.info(
  1227. f"[{self.serial_number}] Starting calibration: "
  1228. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  1229. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  1230. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  1231. )
  1232. return True
  1233. def disconnect(self):
  1234. """Disconnect from the printer."""
  1235. if self._client:
  1236. self._client.loop_stop()
  1237. self._client.disconnect()
  1238. self._client = None
  1239. self.state.connected = False
  1240. def send_command(self, command: dict):
  1241. """Send a command to the printer."""
  1242. if self._client and self.state.connected:
  1243. # Log outgoing message if logging is enabled
  1244. if self._logging_enabled:
  1245. self._message_log.append(MQTTLogEntry(
  1246. timestamp=datetime.now().isoformat(),
  1247. topic=self.topic_publish,
  1248. direction="out",
  1249. payload=command,
  1250. ))
  1251. self._client.publish(self.topic_publish, json.dumps(command))
  1252. def enable_logging(self, enabled: bool = True):
  1253. """Enable or disable MQTT message logging."""
  1254. self._logging_enabled = enabled
  1255. # Don't clear logs when stopping - user can manually clear with clear_logs()
  1256. def get_logs(self) -> list[MQTTLogEntry]:
  1257. """Get all logged MQTT messages."""
  1258. return list(self._message_log)
  1259. def clear_logs(self):
  1260. """Clear the message log."""
  1261. self._message_log.clear()
  1262. @property
  1263. def logging_enabled(self) -> bool:
  1264. """Check if logging is enabled."""
  1265. return self._logging_enabled
  1266. def _handle_kprofile_response(self, data: dict):
  1267. """Handle K-profile response from printer."""
  1268. filaments = data.get("filaments", [])
  1269. profiles = []
  1270. # Log first profile to see what fields the printer returns
  1271. if filaments and isinstance(filaments[0], dict):
  1272. logger.debug(f"[{self.serial_number}] Raw K-profile fields: {list(filaments[0].keys())}")
  1273. logger.debug(f"[{self.serial_number}] First K-profile: {filaments[0]}")
  1274. for i, f in enumerate(filaments):
  1275. if isinstance(f, dict):
  1276. try:
  1277. # cali_idx is the actual slot/calibration index from the printer
  1278. cali_idx = f.get("cali_idx", i)
  1279. profiles.append(KProfile(
  1280. slot_id=cali_idx,
  1281. extruder_id=int(f.get("extruder_id", 0)),
  1282. nozzle_id=str(f.get("nozzle_id", "")),
  1283. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  1284. filament_id=str(f.get("filament_id", "")),
  1285. name=str(f.get("name", "")),
  1286. k_value=str(f.get("k_value", "0.000000")),
  1287. n_coef=str(f.get("n_coef", "0.000000")),
  1288. ams_id=int(f.get("ams_id", 0)),
  1289. tray_id=int(f.get("tray_id", -1)),
  1290. setting_id=f.get("setting_id"),
  1291. ))
  1292. except (ValueError, TypeError) as e:
  1293. logger.warning(f"Failed to parse K-profile: {e}")
  1294. self.state.kprofiles = profiles
  1295. self._kprofile_response_data = profiles
  1296. # Signal that we received the response
  1297. # Use thread-safe method since MQTT callbacks run in a different thread
  1298. if self._pending_kprofile_response:
  1299. if self._loop and self._loop.is_running():
  1300. self._loop.call_soon_threadsafe(self._pending_kprofile_response.set)
  1301. else:
  1302. # Fallback for when loop is not available
  1303. self._pending_kprofile_response.set()
  1304. logger.info(f"[{self.serial_number}] Received {len(profiles)} K-profiles")
  1305. async def get_kprofiles(self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3) -> list[KProfile]:
  1306. """Request K-profiles from the printer with retry logic.
  1307. Bambu printers sometimes ignore the first K-profile request, so we
  1308. implement retry logic to ensure reliable retrieval.
  1309. Args:
  1310. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  1311. timeout: Timeout in seconds to wait for each response attempt
  1312. max_retries: Maximum number of retry attempts
  1313. Returns:
  1314. List of KProfile objects
  1315. """
  1316. if not self._client or not self.state.connected:
  1317. logger.warning(f"[{self.serial_number}] Cannot get K-profiles: not connected")
  1318. return []
  1319. # Capture current event loop for thread-safe callback
  1320. try:
  1321. self._loop = asyncio.get_running_loop()
  1322. except RuntimeError:
  1323. logger.warning(f"[{self.serial_number}] No running event loop")
  1324. return []
  1325. for attempt in range(max_retries):
  1326. # Set up response event for this attempt
  1327. self._sequence_id += 1
  1328. self._pending_kprofile_response = asyncio.Event()
  1329. self._kprofile_response_data = None
  1330. # Send the command
  1331. command = {
  1332. "print": {
  1333. "command": "extrusion_cali_get",
  1334. "filament_id": "",
  1335. "nozzle_diameter": nozzle_diameter,
  1336. "sequence_id": str(self._sequence_id),
  1337. }
  1338. }
  1339. logger.info(f"[{self.serial_number}] Requesting K-profiles for nozzle {nozzle_diameter} (attempt {attempt + 1}/{max_retries})")
  1340. self._client.publish(self.topic_publish, json.dumps(command))
  1341. # Wait for response
  1342. try:
  1343. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  1344. profiles = self._kprofile_response_data or []
  1345. logger.info(f"[{self.serial_number}] Got {len(profiles)} K-profiles on attempt {attempt + 1}")
  1346. return profiles
  1347. except asyncio.TimeoutError:
  1348. logger.warning(f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}")
  1349. if attempt < max_retries - 1:
  1350. # Brief delay before retry
  1351. await asyncio.sleep(0.5)
  1352. finally:
  1353. self._pending_kprofile_response = None
  1354. logger.error(f"[{self.serial_number}] Failed to get K-profiles after {max_retries} attempts")
  1355. return []
  1356. def set_kprofile(
  1357. self,
  1358. filament_id: str,
  1359. name: str,
  1360. k_value: str,
  1361. nozzle_diameter: str = "0.4",
  1362. nozzle_id: str = "HS00-0.4",
  1363. extruder_id: int = 0,
  1364. setting_id: str | None = None,
  1365. slot_id: int = 0,
  1366. cali_idx: int | None = None,
  1367. ) -> bool:
  1368. """Set/update a K-profile on the printer.
  1369. Args:
  1370. filament_id: Bambu filament identifier
  1371. name: Profile name
  1372. k_value: Pressure advance value (e.g., "0.020000")
  1373. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  1374. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  1375. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  1376. setting_id: Existing setting ID for updates, None for new
  1377. slot_id: Calibration index (cali_idx) for the profile
  1378. cali_idx: For H2D edits, the existing slot being edited (enables in-place edit)
  1379. Returns:
  1380. True if command was sent, False otherwise
  1381. """
  1382. if not self._client or not self.state.connected:
  1383. logger.warning(f"[{self.serial_number}] Cannot set K-profile: not connected")
  1384. return False
  1385. self._sequence_id += 1
  1386. # Detect printer type by serial number prefix
  1387. # X1C/P1/A1 series (single nozzle): serial starts with "00M", "00W", "01P", "01S", "03W", etc.
  1388. # H2D series (dual nozzle): serial starts with "094"
  1389. is_dual_nozzle = self.serial_number.startswith("094")
  1390. # For H2D edits, use empty setting_id per OrcaSlicer sniff
  1391. # For new profiles, generate a setting_id
  1392. import secrets
  1393. if cali_idx is not None:
  1394. # Edit mode - use empty setting_id per OrcaSlicer sniff
  1395. setting_id = ""
  1396. elif not setting_id and slot_id == 0:
  1397. # New profile - generate setting_id
  1398. setting_id = f"PFUS{secrets.token_hex(7)}" # 7 bytes = 14 hex chars
  1399. if is_dual_nozzle:
  1400. # H2D format - exact OrcaSlicer format (captured via MQTT sniffing)
  1401. # For edits: include cali_idx (existing slot), slot_id=0, setting_id=""
  1402. # For new profiles: no cali_idx, slot_id=0, setting_id=generated
  1403. filament_entry = {
  1404. "ams_id": 0,
  1405. "extruder_id": extruder_id,
  1406. "filament_id": filament_id,
  1407. "k_value": k_value,
  1408. "n_coef": "0.000000",
  1409. "name": name,
  1410. "nozzle_diameter": nozzle_diameter,
  1411. "nozzle_id": nozzle_id,
  1412. "setting_id": setting_id if setting_id else "",
  1413. "slot_id": slot_id,
  1414. "tray_id": -1,
  1415. }
  1416. # For edits, add cali_idx field (position matters - alphabetical order)
  1417. if cali_idx is not None:
  1418. # Insert cali_idx in alphabetical position (after ams_id, before extruder_id)
  1419. # n_coef must be "0.000000" for H2D edits (matches OrcaSlicer sniff)
  1420. filament_entry = {
  1421. "ams_id": 0,
  1422. "cali_idx": cali_idx,
  1423. "extruder_id": extruder_id,
  1424. "filament_id": filament_id,
  1425. "k_value": k_value,
  1426. "n_coef": "0.000000",
  1427. "name": name,
  1428. "nozzle_diameter": nozzle_diameter,
  1429. "nozzle_id": nozzle_id,
  1430. "setting_id": "",
  1431. "slot_id": 0,
  1432. "tray_id": -1,
  1433. }
  1434. command = {
  1435. "print": {
  1436. "command": "extrusion_cali_set",
  1437. "filaments": [filament_entry],
  1438. "nozzle_diameter": nozzle_diameter,
  1439. "sequence_id": str(self._sequence_id),
  1440. }
  1441. }
  1442. else:
  1443. # X1C/P1/A1 format - based on actual X1C profile data:
  1444. # - n_coef: "1.000000" (NOT 0.000000 like H2D)
  1445. # - nozzle_id: "" (empty string, NOT the nozzle type)
  1446. # - tray_id: -1 (NOT 0)
  1447. filament_entry = {
  1448. "ams_id": 0,
  1449. "extruder_id": 0, # X1C is single nozzle
  1450. "filament_id": filament_id,
  1451. "k_value": k_value,
  1452. "n_coef": "1.000000", # X1C uses 1.0, not 0.0
  1453. "name": name,
  1454. "nozzle_diameter": nozzle_diameter,
  1455. "nozzle_id": "", # X1C uses empty string
  1456. "setting_id": setting_id,
  1457. "slot_id": slot_id,
  1458. "tray_id": -1, # X1C uses -1
  1459. }
  1460. command = {
  1461. "print": {
  1462. "command": "extrusion_cali_set",
  1463. "filaments": [filament_entry],
  1464. "nozzle_diameter": nozzle_diameter,
  1465. "sequence_id": str(self._sequence_id),
  1466. }
  1467. }
  1468. command_json = json.dumps(command)
  1469. logger.info(f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={cali_idx}, new={slot_id==0}, dual={is_dual_nozzle})")
  1470. logger.info(f"[{self.serial_number}] K-profile SET command: {command_json}")
  1471. # Use QoS 1 for reliable delivery (at least once)
  1472. self._client.publish(self.topic_publish, command_json, qos=1)
  1473. return True
  1474. def delete_kprofile(
  1475. self,
  1476. cali_idx: int,
  1477. filament_id: str,
  1478. nozzle_id: str,
  1479. nozzle_diameter: str = "0.4",
  1480. extruder_id: int = 0,
  1481. setting_id: str | None = None,
  1482. ) -> bool:
  1483. """Delete a K-profile from the printer.
  1484. Args:
  1485. cali_idx: The calibration index (slot_id) of the profile to delete
  1486. filament_id: Bambu filament identifier
  1487. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  1488. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  1489. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  1490. setting_id: Unique setting identifier (for X1C series)
  1491. Returns:
  1492. True if command was sent, False otherwise
  1493. """
  1494. if not self._client or not self.state.connected:
  1495. logger.warning(f"[{self.serial_number}] Cannot delete K-profile: not connected")
  1496. return False
  1497. self._sequence_id += 1
  1498. # Detect printer type by serial number prefix
  1499. # H2D series (dual nozzle): serial starts with "094"
  1500. is_dual_nozzle = self.serial_number.startswith("094")
  1501. if is_dual_nozzle:
  1502. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  1503. command = {
  1504. "print": {
  1505. "command": "extrusion_cali_del",
  1506. "sequence_id": str(self._sequence_id),
  1507. "extruder_id": extruder_id,
  1508. "nozzle_id": nozzle_id,
  1509. "filament_id": filament_id,
  1510. "cali_idx": cali_idx,
  1511. "nozzle_diameter": nozzle_diameter,
  1512. }
  1513. }
  1514. else:
  1515. # X1C/P1/A1 format: uses setting_id, nozzle_diameter, no extruder/nozzle_id fields
  1516. command = {
  1517. "print": {
  1518. "command": "extrusion_cali_del",
  1519. "sequence_id": str(self._sequence_id),
  1520. "filament_id": filament_id,
  1521. "cali_idx": cali_idx,
  1522. "setting_id": setting_id,
  1523. "nozzle_diameter": nozzle_diameter,
  1524. }
  1525. }
  1526. command_json = json.dumps(command)
  1527. logger.info(f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, dual={is_dual_nozzle}")
  1528. logger.info(f"[{self.serial_number}] K-profile DELETE command: {command_json}")
  1529. # Use QoS 1 for reliable delivery (at least once)
  1530. self._client.publish(self.topic_publish, command_json, qos=1)
  1531. return True
  1532. # =========================================================================
  1533. # Printer Control Commands
  1534. # =========================================================================
  1535. def pause_print(self) -> bool:
  1536. """Pause the current print job."""
  1537. if not self._client or not self.state.connected:
  1538. logger.warning(f"[{self.serial_number}] Cannot pause print: not connected")
  1539. return False
  1540. command = {
  1541. "print": {
  1542. "command": "pause",
  1543. "sequence_id": "0"
  1544. }
  1545. }
  1546. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1547. logger.info(f"[{self.serial_number}] Sent pause print command")
  1548. return True
  1549. def resume_print(self) -> bool:
  1550. """Resume a paused print job."""
  1551. if not self._client or not self.state.connected:
  1552. logger.warning(f"[{self.serial_number}] Cannot resume print: not connected")
  1553. return False
  1554. command = {
  1555. "print": {
  1556. "command": "resume",
  1557. "sequence_id": "0"
  1558. }
  1559. }
  1560. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1561. logger.info(f"[{self.serial_number}] Sent resume print command")
  1562. return True
  1563. def send_gcode(self, gcode: str) -> bool:
  1564. """Send G-code command(s) to the printer.
  1565. Multiple commands can be separated by newlines.
  1566. Args:
  1567. gcode: G-code command(s) to send
  1568. Returns:
  1569. True if command was sent, False otherwise
  1570. """
  1571. if not self._client or not self.state.connected:
  1572. logger.warning(f"[{self.serial_number}] Cannot send G-code: not connected")
  1573. return False
  1574. self._sequence_id += 1
  1575. command = {
  1576. "print": {
  1577. "command": "gcode_line",
  1578. "param": gcode,
  1579. "sequence_id": str(self._sequence_id)
  1580. }
  1581. }
  1582. # Use QoS 1 for reliable delivery (at least once)
  1583. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1584. logger.debug(f"[{self.serial_number}] Sent G-code: {gcode[:50]}...")
  1585. return True
  1586. def set_bed_temperature(self, target: int) -> bool:
  1587. """Set the bed target temperature.
  1588. Args:
  1589. target: Target temperature in Celsius (0 to turn off)
  1590. Returns:
  1591. True if command was sent, False otherwise
  1592. """
  1593. return self.send_gcode(f"M140 S{target}")
  1594. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  1595. """Set the nozzle target temperature.
  1596. Args:
  1597. target: Target temperature in Celsius (0 to turn off)
  1598. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  1599. Returns:
  1600. True if command was sent, False otherwise
  1601. """
  1602. # Use M104 for non-blocking
  1603. # Always use T parameter for H2D compatibility
  1604. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  1605. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  1606. # Track it locally so we can display it correctly
  1607. if result and nozzle == 1:
  1608. self.state.temperatures["nozzle_target"] = float(target)
  1609. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  1610. logger.info(f"[{self.serial_number}] Tracking LEFT nozzle target locally: {target}°C")
  1611. return result
  1612. def set_chamber_temperature(self, target: int) -> bool:
  1613. """Set the chamber target temperature.
  1614. Args:
  1615. target: Target temperature in Celsius (0 to turn off heating)
  1616. Returns:
  1617. True if command was sent, False otherwise
  1618. """
  1619. # M141 sets chamber temperature
  1620. return self.send_gcode(f"M141 S{target}")
  1621. def set_print_speed(self, mode: int) -> bool:
  1622. """Set the print speed mode.
  1623. Args:
  1624. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1625. Returns:
  1626. True if command was sent, False otherwise
  1627. """
  1628. if not self._client or not self.state.connected:
  1629. logger.warning(f"[{self.serial_number}] Cannot set print speed: not connected")
  1630. return False
  1631. if mode not in (1, 2, 3, 4):
  1632. logger.warning(f"[{self.serial_number}] Invalid speed mode: {mode}")
  1633. return False
  1634. command = {
  1635. "print": {
  1636. "command": "print_speed",
  1637. "param": str(mode),
  1638. "sequence_id": "0"
  1639. }
  1640. }
  1641. self._client.publish(self.topic_publish, json.dumps(command))
  1642. logger.info(f"[{self.serial_number}] Set print speed mode to {mode}")
  1643. return True
  1644. def set_fan_speed(self, fan: int, speed: int) -> bool:
  1645. """Set fan speed.
  1646. Args:
  1647. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber)
  1648. speed: Speed 0-255 (0=off, 255=full)
  1649. Returns:
  1650. True if command was sent, False otherwise
  1651. """
  1652. if fan not in (1, 2, 3):
  1653. logger.warning(f"[{self.serial_number}] Invalid fan index: {fan}")
  1654. return False
  1655. speed = max(0, min(255, speed)) # Clamp to 0-255
  1656. return self.send_gcode(f"M106 P{fan} S{speed}")
  1657. def set_part_fan(self, speed: int) -> bool:
  1658. """Set part cooling fan speed (0-255)."""
  1659. return self.set_fan_speed(1, speed)
  1660. def set_aux_fan(self, speed: int) -> bool:
  1661. """Set auxiliary fan speed (0-255)."""
  1662. return self.set_fan_speed(2, speed)
  1663. def set_chamber_fan(self, speed: int) -> bool:
  1664. """Set chamber fan speed (0-255)."""
  1665. return self.set_fan_speed(3, speed)
  1666. def set_airduct_mode(self, mode: str) -> bool:
  1667. """Set air conditioning mode (cooling or heating).
  1668. Args:
  1669. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  1670. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  1671. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  1672. closes top exhaust flap
  1673. Returns:
  1674. True if command was sent, False otherwise
  1675. """
  1676. if not self._client or not self.state.connected:
  1677. logger.warning(f"[{self.serial_number}] Cannot set airduct mode: not connected")
  1678. return False
  1679. self._sequence_id += 1
  1680. mode_id = 0 if mode == "cooling" else 1
  1681. command = {
  1682. "print": {
  1683. "command": "set_airduct",
  1684. "modeId": mode_id,
  1685. "sequence_id": str(self._sequence_id),
  1686. "submode": -1
  1687. }
  1688. }
  1689. # Use QoS 1 for reliable delivery
  1690. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1691. logger.info(f"[{self.serial_number}] Set airduct mode to {mode} (modeId={mode_id}, seq={self._sequence_id})")
  1692. return True
  1693. def set_chamber_light(self, on: bool) -> bool:
  1694. """Turn chamber light on or off.
  1695. Args:
  1696. on: True to turn on, False to turn off
  1697. Returns:
  1698. True if command was sent, False otherwise
  1699. """
  1700. if not self._client or not self.state.connected:
  1701. logger.warning(f"[{self.serial_number}] Cannot set chamber light: not connected")
  1702. return False
  1703. mode = "on" if on else "off"
  1704. # Control both chamber lights (some printers like H2D have two)
  1705. for led_node in ["chamber_light", "chamber_light2"]:
  1706. self._sequence_id += 1
  1707. command = {
  1708. "system": {
  1709. "command": "ledctrl",
  1710. "led_node": led_node,
  1711. "led_mode": mode,
  1712. "led_on_time": 500,
  1713. "led_off_time": 500,
  1714. "loop_times": 0,
  1715. "interval_time": 0,
  1716. "sequence_id": str(self._sequence_id)
  1717. }
  1718. }
  1719. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1720. logger.info(f"[{self.serial_number}] Set chamber lights {'on' if on else 'off'} (seq={self._sequence_id})")
  1721. return True
  1722. def home_axes(self, axes: str = "XYZ") -> bool:
  1723. """Home the specified axes.
  1724. Args:
  1725. axes: Axes to home (e.g., "XYZ", "X", "XY", "Z")
  1726. Returns:
  1727. True if command was sent, False otherwise
  1728. """
  1729. # G28 homes all axes, G28 X Y Z homes specific axes
  1730. axes_param = " ".join(axes.upper())
  1731. return self.send_gcode(f"G28 {axes_param}")
  1732. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  1733. """Move an axis by a relative distance.
  1734. Args:
  1735. axis: Axis to move ("X", "Y", or "Z")
  1736. distance: Distance to move in mm (positive or negative)
  1737. speed: Movement speed in mm/min
  1738. Returns:
  1739. True if command was sent, False otherwise
  1740. """
  1741. axis = axis.upper()
  1742. if axis not in ("X", "Y", "Z"):
  1743. logger.warning(f"[{self.serial_number}] Invalid axis: {axis}")
  1744. return False
  1745. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  1746. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  1747. return self.send_gcode(gcode)
  1748. def disable_motors(self) -> bool:
  1749. """Disable all stepper motors.
  1750. Warning: This will cause the printer to lose its position.
  1751. A homing operation will be required before printing.
  1752. Returns:
  1753. True if command was sent, False otherwise
  1754. """
  1755. return self.send_gcode("M18")
  1756. def enable_motors(self) -> bool:
  1757. """Enable all stepper motors.
  1758. Returns:
  1759. True if command was sent, False otherwise
  1760. """
  1761. return self.send_gcode("M17")
  1762. def ams_load_filament(self, tray_id: int) -> bool:
  1763. """Load filament from a specific AMS tray.
  1764. Args:
  1765. tray_id: Tray ID (0-15 for AMS slots, or 254 for external spool)
  1766. Returns:
  1767. True if command was sent, False otherwise
  1768. """
  1769. if not self._client or not self.state.connected:
  1770. logger.warning(f"[{self.serial_number}] Cannot load filament: not connected")
  1771. return False
  1772. command = {
  1773. "print": {
  1774. "command": "ams_change_filament",
  1775. "target": tray_id,
  1776. "sequence_id": "0"
  1777. }
  1778. }
  1779. self._client.publish(self.topic_publish, json.dumps(command))
  1780. logger.info(f"[{self.serial_number}] Loading filament from tray {tray_id}")
  1781. return True
  1782. def ams_unload_filament(self) -> bool:
  1783. """Unload the currently loaded filament.
  1784. Returns:
  1785. True if command was sent, False otherwise
  1786. """
  1787. if not self._client or not self.state.connected:
  1788. logger.warning(f"[{self.serial_number}] Cannot unload filament: not connected")
  1789. return False
  1790. command = {
  1791. "print": {
  1792. "command": "ams_change_filament",
  1793. "target": 255, # 255 = unload
  1794. "sequence_id": "0"
  1795. }
  1796. }
  1797. self._client.publish(self.topic_publish, json.dumps(command))
  1798. logger.info(f"[{self.serial_number}] Unloading filament")
  1799. return True
  1800. def ams_control(self, action: str) -> bool:
  1801. """Control AMS operations.
  1802. Args:
  1803. action: "resume", "reset", or "pause"
  1804. Returns:
  1805. True if command was sent, False otherwise
  1806. """
  1807. if not self._client or not self.state.connected:
  1808. logger.warning(f"[{self.serial_number}] Cannot control AMS: not connected")
  1809. return False
  1810. if action not in ("resume", "reset", "pause"):
  1811. logger.warning(f"[{self.serial_number}] Invalid AMS action: {action}")
  1812. return False
  1813. command = {
  1814. "print": {
  1815. "command": "ams_control",
  1816. "param": action,
  1817. "sequence_id": "0"
  1818. }
  1819. }
  1820. self._client.publish(self.topic_publish, json.dumps(command))
  1821. logger.info(f"[{self.serial_number}] AMS control: {action}")
  1822. return True
  1823. def set_timelapse(self, enable: bool) -> bool:
  1824. """Enable or disable timelapse recording.
  1825. Args:
  1826. enable: True to enable, False to disable
  1827. Returns:
  1828. True if command was sent, False otherwise
  1829. """
  1830. if not self._client or not self.state.connected:
  1831. logger.warning(f"[{self.serial_number}] Cannot set timelapse: not connected")
  1832. return False
  1833. command = {
  1834. "pushing": {
  1835. "command": "pushall",
  1836. "sequence_id": "0"
  1837. }
  1838. }
  1839. # First send the timelapse setting
  1840. timelapse_cmd = {
  1841. "print": {
  1842. "command": "gcode_line",
  1843. "param": f"M981 S{1 if enable else 0} P20000",
  1844. "sequence_id": "0"
  1845. }
  1846. }
  1847. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd))
  1848. # Request status update
  1849. self._client.publish(self.topic_publish, json.dumps(command))
  1850. logger.info(f"[{self.serial_number}] Set timelapse {'enabled' if enable else 'disabled'}")
  1851. return True
  1852. def set_liveview(self, enable: bool) -> bool:
  1853. """Enable or disable live view / camera streaming.
  1854. Args:
  1855. enable: True to enable, False to disable
  1856. Returns:
  1857. True if command was sent, False otherwise
  1858. """
  1859. if not self._client or not self.state.connected:
  1860. logger.warning(f"[{self.serial_number}] Cannot set liveview: not connected")
  1861. return False
  1862. command = {
  1863. "xcam": {
  1864. "command": "ipcam_record_set",
  1865. "control": "enable" if enable else "disable",
  1866. "sequence_id": "0"
  1867. }
  1868. }
  1869. self._client.publish(self.topic_publish, json.dumps(command))
  1870. # Request status update
  1871. pushall = {
  1872. "pushing": {
  1873. "command": "pushall",
  1874. "sequence_id": "0"
  1875. }
  1876. }
  1877. self._client.publish(self.topic_publish, json.dumps(pushall))
  1878. logger.info(f"[{self.serial_number}] Set liveview {'enabled' if enable else 'disabled'}")
  1879. return True