bambu_mqtt.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 PrinterState:
  42. connected: bool = False
  43. state: str = "unknown"
  44. current_print: str | None = None
  45. subtask_name: str | None = None
  46. progress: float = 0.0
  47. remaining_time: int = 0
  48. layer_num: int = 0
  49. total_layers: int = 0
  50. temperatures: dict = field(default_factory=dict)
  51. raw_data: dict = field(default_factory=dict)
  52. gcode_file: str | None = None
  53. subtask_id: str | None = None
  54. hms_errors: list = field(default_factory=list) # List of HMSError
  55. kprofiles: list = field(default_factory=list) # List of KProfile
  56. class BambuMQTTClient:
  57. """MQTT client for Bambu Lab printer communication."""
  58. MQTT_PORT = 8883
  59. def __init__(
  60. self,
  61. ip_address: str,
  62. serial_number: str,
  63. access_code: str,
  64. on_state_change: Callable[[PrinterState], None] | None = None,
  65. on_print_start: Callable[[dict], None] | None = None,
  66. on_print_complete: Callable[[dict], None] | None = None,
  67. ):
  68. self.ip_address = ip_address
  69. self.serial_number = serial_number
  70. self.access_code = access_code
  71. self.on_state_change = on_state_change
  72. self.on_print_start = on_print_start
  73. self.on_print_complete = on_print_complete
  74. self.state = PrinterState()
  75. self._client: mqtt.Client | None = None
  76. self._loop: asyncio.AbstractEventLoop | None = None
  77. self._previous_gcode_state: str | None = None
  78. self._previous_gcode_file: str | None = None
  79. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  80. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  81. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  82. self._logging_enabled: bool = False
  83. self._last_message_time: float = 0.0 # Track when we last received a message
  84. # K-profile command tracking
  85. self._sequence_id: int = 0
  86. self._pending_kprofile_response: asyncio.Event | None = None
  87. self._kprofile_response_data: list | None = None
  88. @property
  89. def topic_subscribe(self) -> str:
  90. return f"device/{self.serial_number}/report"
  91. @property
  92. def topic_publish(self) -> str:
  93. return f"device/{self.serial_number}/request"
  94. def _on_connect(self, client, userdata, flags, rc, properties=None):
  95. if rc == 0:
  96. self.state.connected = True
  97. client.subscribe(self.topic_subscribe)
  98. # Request full status update
  99. self._request_push_all()
  100. else:
  101. self.state.connected = False
  102. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  103. # Ignore spurious disconnect callbacks if we've received a message recently
  104. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active
  105. time_since_last_message = time.time() - self._last_message_time
  106. if time_since_last_message < 30.0 and self._last_message_time > 0:
  107. logger.debug(
  108. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  109. )
  110. return
  111. logger.warning(f"[{self.serial_number}] MQTT disconnected: rc={rc}, flags={disconnect_flags}")
  112. self.state.connected = False
  113. if self.on_state_change:
  114. self.on_state_change(self.state)
  115. def _on_message(self, client, userdata, msg):
  116. try:
  117. payload = json.loads(msg.payload.decode())
  118. # Track last message time - receiving a message proves we're connected
  119. self._last_message_time = time.time()
  120. self.state.connected = True
  121. # Log message if logging is enabled
  122. if self._logging_enabled:
  123. self._message_log.append(MQTTLogEntry(
  124. timestamp=datetime.now().isoformat(),
  125. topic=msg.topic,
  126. direction="in",
  127. payload=payload,
  128. ))
  129. self._process_message(payload)
  130. except json.JSONDecodeError:
  131. pass
  132. def _process_message(self, payload: dict):
  133. """Process incoming MQTT message from printer."""
  134. if "print" in payload:
  135. print_data = payload["print"]
  136. # Log when we see gcode_state changes
  137. if "gcode_state" in print_data:
  138. logger.info(
  139. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  140. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  141. )
  142. # Check for K-profile response (extrusion_cali)
  143. if "command" in print_data and print_data.get("command") == "extrusion_cali_get":
  144. self._handle_kprofile_response(print_data)
  145. self._update_state(print_data)
  146. def _update_state(self, data: dict):
  147. """Update printer state from message data."""
  148. previous_state = self.state.state
  149. # Update state fields
  150. if "gcode_state" in data:
  151. self.state.state = data["gcode_state"]
  152. if "gcode_file" in data:
  153. self.state.gcode_file = data["gcode_file"]
  154. self.state.current_print = data["gcode_file"]
  155. if "subtask_name" in data:
  156. self.state.subtask_name = data["subtask_name"]
  157. # Prefer subtask_name as current_print if available
  158. if data["subtask_name"]:
  159. self.state.current_print = data["subtask_name"]
  160. if "subtask_id" in data:
  161. self.state.subtask_id = data["subtask_id"]
  162. if "mc_percent" in data:
  163. self.state.progress = float(data["mc_percent"])
  164. if "mc_remaining_time" in data:
  165. self.state.remaining_time = int(data["mc_remaining_time"])
  166. if "layer_num" in data:
  167. self.state.layer_num = int(data["layer_num"])
  168. if "total_layer_num" in data:
  169. self.state.total_layers = int(data["total_layer_num"])
  170. # Temperature data
  171. temps = {}
  172. # Log all temperature-related fields for debugging (only when we have temp data)
  173. temp_fields = {k: v for k, v in data.items() if 'temp' in k.lower() or 'nozzle' in k.lower()}
  174. if temp_fields and not hasattr(self, '_temp_fields_logged'):
  175. logger.info(f"[{self.serial_number}] Temperature fields in MQTT data: {temp_fields}")
  176. self._temp_fields_logged = True
  177. if "bed_temper" in data:
  178. temps["bed"] = float(data["bed_temper"])
  179. if "bed_target_temper" in data:
  180. temps["bed_target"] = float(data["bed_target_temper"])
  181. if "nozzle_temper" in data:
  182. temps["nozzle"] = float(data["nozzle_temper"])
  183. if "nozzle_target_temper" in data:
  184. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  185. # Second nozzle for dual-extruder printers (H2 series)
  186. # Try multiple possible field names used by different firmware versions
  187. if "nozzle_temper_2" in data:
  188. temps["nozzle_2"] = float(data["nozzle_temper_2"])
  189. elif "right_nozzle_temper" in data:
  190. temps["nozzle_2"] = float(data["right_nozzle_temper"])
  191. if "nozzle_target_temper_2" in data:
  192. temps["nozzle_2_target"] = float(data["nozzle_target_temper_2"])
  193. elif "right_nozzle_target_temper" in data:
  194. temps["nozzle_2_target"] = float(data["right_nozzle_target_temper"])
  195. # Also check for left nozzle as primary (some H2 models)
  196. if "left_nozzle_temper" in data and "nozzle" not in temps:
  197. temps["nozzle"] = float(data["left_nozzle_temper"])
  198. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  199. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  200. if "chamber_temper" in data:
  201. temps["chamber"] = float(data["chamber_temper"])
  202. if temps:
  203. self.state.temperatures = temps
  204. # Parse HMS (Health Management System) errors
  205. if "hms" in data:
  206. hms_list = data["hms"]
  207. self.state.hms_errors = []
  208. if isinstance(hms_list, list):
  209. for hms in hms_list:
  210. if isinstance(hms, dict):
  211. # HMS format: {"attr": code, "code": full_code}
  212. # The code is a hex string, severity is in bits
  213. code = hms.get("code", hms.get("attr", "0"))
  214. if isinstance(code, int):
  215. code = hex(code)
  216. # Parse severity from code (typically last 4 bits indicate level)
  217. try:
  218. code_int = int(str(code).replace("0x", ""), 16) if code else 0
  219. severity = (code_int >> 16) & 0xF # Extract severity bits
  220. module = (code_int >> 24) & 0xFF # Extract module bits
  221. except (ValueError, TypeError):
  222. severity = 3
  223. module = 0
  224. self.state.hms_errors.append(HMSError(
  225. code=str(code),
  226. module=module,
  227. severity=severity if severity > 0 else 3,
  228. ))
  229. self.state.raw_data = data
  230. # Log state transitions for debugging
  231. if "gcode_state" in data:
  232. logger.debug(
  233. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  234. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  235. )
  236. # Detect print start (state changes TO RUNNING with a file)
  237. current_file = self.state.gcode_file or self.state.current_print
  238. is_new_print = (
  239. self.state.state == "RUNNING"
  240. and self._previous_gcode_state != "RUNNING"
  241. and current_file
  242. )
  243. # Also detect if file changed while running (new print started)
  244. is_file_change = (
  245. self.state.state == "RUNNING"
  246. and current_file
  247. and current_file != self._previous_gcode_file
  248. and self._previous_gcode_file is not None
  249. )
  250. # Track RUNNING state for more robust completion detection
  251. if self.state.state == "RUNNING" and current_file:
  252. if not self._was_running:
  253. logger.info(f"[{self.serial_number}] Now tracking RUNNING state for {current_file}")
  254. self._was_running = True
  255. self._completion_triggered = False
  256. if is_new_print or is_file_change:
  257. # Clear any old HMS errors when a new print starts
  258. self.state.hms_errors = []
  259. # Reset completion tracking for new print
  260. self._was_running = True
  261. self._completion_triggered = False
  262. if (is_new_print or is_file_change) and self.on_print_start:
  263. logger.info(
  264. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  265. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  266. )
  267. self.on_print_start({
  268. "filename": current_file,
  269. "subtask_name": self.state.subtask_name,
  270. "raw_data": data,
  271. })
  272. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  273. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  274. # This handles cases where server restarts during a print
  275. should_trigger_completion = (
  276. self.state.state in ("FINISH", "FAILED")
  277. and not self._completion_triggered
  278. and self.on_print_complete
  279. and (
  280. self._previous_gcode_state == "RUNNING" # Normal transition
  281. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  282. )
  283. )
  284. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  285. if (
  286. self.state.state == "IDLE"
  287. and self._previous_gcode_state == "RUNNING"
  288. and not self._completion_triggered
  289. and self.on_print_complete
  290. ):
  291. should_trigger_completion = True
  292. if should_trigger_completion:
  293. if self.state.state == "FINISH":
  294. status = "completed"
  295. elif self.state.state == "FAILED":
  296. status = "failed"
  297. else:
  298. status = "aborted"
  299. logger.info(
  300. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  301. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  302. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}"
  303. )
  304. self._completion_triggered = True
  305. self._was_running = False
  306. self.on_print_complete({
  307. "status": status,
  308. "filename": self._previous_gcode_file or current_file,
  309. "subtask_name": self.state.subtask_name,
  310. "raw_data": data,
  311. })
  312. self._previous_gcode_state = self.state.state
  313. if current_file:
  314. self._previous_gcode_file = current_file
  315. if self.on_state_change:
  316. self.on_state_change(self.state)
  317. def _request_push_all(self):
  318. """Request full status update from printer."""
  319. if self._client:
  320. message = {"pushing": {"command": "pushall"}}
  321. self._client.publish(self.topic_publish, json.dumps(message))
  322. def connect(self):
  323. """Connect to the printer MQTT broker."""
  324. self._client = mqtt.Client(
  325. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  326. client_id=f"bambutrack_{self.serial_number}",
  327. protocol=mqtt.MQTTv311,
  328. )
  329. self._client.username_pw_set("bblp", self.access_code)
  330. self._client.on_connect = self._on_connect
  331. self._client.on_disconnect = self._on_disconnect
  332. self._client.on_message = self._on_message
  333. # TLS setup - Bambu uses self-signed certs
  334. ssl_context = ssl.create_default_context()
  335. ssl_context.check_hostname = False
  336. ssl_context.verify_mode = ssl.CERT_NONE
  337. self._client.tls_set_context(ssl_context)
  338. # Use shorter keepalive (15s) for faster disconnect detection
  339. # Paho considers connection lost after 1.5x keepalive with no response
  340. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=15)
  341. self._client.loop_start()
  342. def start_print(self, filename: str, plate_id: int = 1):
  343. """Start a print job on the printer.
  344. The file should already be uploaded to /cache/ on the printer via FTP.
  345. """
  346. if self._client and self.state.connected:
  347. # Bambu print command format
  348. # Based on: https://github.com/darkorb/bambu-ftp-and-print
  349. command = {
  350. "print": {
  351. "sequence_id": 0,
  352. "command": "project_file",
  353. "param": f"Metadata/plate_{plate_id}.gcode",
  354. "subtask_name": filename,
  355. "url": f"ftp://{filename}",
  356. "timelapse": False,
  357. "bed_leveling": True,
  358. "flow_cali": True,
  359. "vibration_cali": True,
  360. "layer_inspect": False,
  361. "use_ams": True,
  362. }
  363. }
  364. logger.info(f"[{self.serial_number}] Sending print command: {json.dumps(command)}")
  365. self._client.publish(self.topic_publish, json.dumps(command))
  366. return True
  367. return False
  368. def stop_print(self) -> bool:
  369. """Stop the current print job."""
  370. if self._client and self.state.connected:
  371. command = {
  372. "print": {
  373. "command": "stop",
  374. "sequence_id": "0"
  375. }
  376. }
  377. self._client.publish(self.topic_publish, json.dumps(command))
  378. logger.info(f"[{self.serial_number}] Sent stop print command")
  379. return True
  380. return False
  381. def disconnect(self):
  382. """Disconnect from the printer."""
  383. if self._client:
  384. self._client.loop_stop()
  385. self._client.disconnect()
  386. self._client = None
  387. self.state.connected = False
  388. def send_command(self, command: dict):
  389. """Send a command to the printer."""
  390. if self._client and self.state.connected:
  391. # Log outgoing message if logging is enabled
  392. if self._logging_enabled:
  393. self._message_log.append(MQTTLogEntry(
  394. timestamp=datetime.now().isoformat(),
  395. topic=self.topic_publish,
  396. direction="out",
  397. payload=command,
  398. ))
  399. self._client.publish(self.topic_publish, json.dumps(command))
  400. def enable_logging(self, enabled: bool = True):
  401. """Enable or disable MQTT message logging."""
  402. self._logging_enabled = enabled
  403. # Don't clear logs when stopping - user can manually clear with clear_logs()
  404. def get_logs(self) -> list[MQTTLogEntry]:
  405. """Get all logged MQTT messages."""
  406. return list(self._message_log)
  407. def clear_logs(self):
  408. """Clear the message log."""
  409. self._message_log.clear()
  410. @property
  411. def logging_enabled(self) -> bool:
  412. """Check if logging is enabled."""
  413. return self._logging_enabled
  414. def _handle_kprofile_response(self, data: dict):
  415. """Handle K-profile response from printer."""
  416. filaments = data.get("filaments", [])
  417. profiles = []
  418. # Log first profile to see what fields the printer returns
  419. if filaments and isinstance(filaments[0], dict):
  420. logger.debug(f"[{self.serial_number}] Raw K-profile fields: {list(filaments[0].keys())}")
  421. logger.debug(f"[{self.serial_number}] First K-profile: {filaments[0]}")
  422. for i, f in enumerate(filaments):
  423. if isinstance(f, dict):
  424. try:
  425. # cali_idx is the actual slot/calibration index from the printer
  426. cali_idx = f.get("cali_idx", i)
  427. profiles.append(KProfile(
  428. slot_id=cali_idx,
  429. extruder_id=int(f.get("extruder_id", 0)),
  430. nozzle_id=str(f.get("nozzle_id", "")),
  431. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  432. filament_id=str(f.get("filament_id", "")),
  433. name=str(f.get("name", "")),
  434. k_value=str(f.get("k_value", "0.000000")),
  435. n_coef=str(f.get("n_coef", "0.000000")),
  436. ams_id=int(f.get("ams_id", 0)),
  437. tray_id=int(f.get("tray_id", -1)),
  438. setting_id=f.get("setting_id"),
  439. ))
  440. except (ValueError, TypeError) as e:
  441. logger.warning(f"Failed to parse K-profile: {e}")
  442. self.state.kprofiles = profiles
  443. self._kprofile_response_data = profiles
  444. # Signal that we received the response
  445. if self._pending_kprofile_response:
  446. self._pending_kprofile_response.set()
  447. logger.info(f"[{self.serial_number}] Received {len(profiles)} K-profiles")
  448. async def get_kprofiles(self, nozzle_diameter: str = "0.4", timeout: float = 5.0) -> list[KProfile]:
  449. """Request K-profiles from the printer.
  450. Args:
  451. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  452. timeout: Timeout in seconds to wait for response
  453. Returns:
  454. List of KProfile objects
  455. """
  456. if not self._client or not self.state.connected:
  457. logger.warning(f"[{self.serial_number}] Cannot get K-profiles: not connected")
  458. return []
  459. # Set up response event
  460. self._sequence_id += 1
  461. self._pending_kprofile_response = asyncio.Event()
  462. self._kprofile_response_data = None
  463. # Send the command
  464. command = {
  465. "print": {
  466. "command": "extrusion_cali_get",
  467. "filament_id": "",
  468. "nozzle_diameter": nozzle_diameter,
  469. "sequence_id": str(self._sequence_id),
  470. }
  471. }
  472. logger.info(f"[{self.serial_number}] Requesting K-profiles for nozzle {nozzle_diameter}")
  473. self._client.publish(self.topic_publish, json.dumps(command))
  474. # Wait for response
  475. try:
  476. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  477. return self._kprofile_response_data or []
  478. except asyncio.TimeoutError:
  479. logger.warning(f"[{self.serial_number}] Timeout waiting for K-profiles response")
  480. return []
  481. finally:
  482. self._pending_kprofile_response = None
  483. def set_kprofile(
  484. self,
  485. filament_id: str,
  486. name: str,
  487. k_value: str,
  488. nozzle_diameter: str = "0.4",
  489. nozzle_id: str = "HS00-0.4",
  490. extruder_id: int = 0,
  491. setting_id: str | None = None,
  492. slot_id: int = 0,
  493. ) -> bool:
  494. """Set/update a K-profile on the printer.
  495. Args:
  496. filament_id: Bambu filament identifier
  497. name: Profile name
  498. k_value: Pressure advance value (e.g., "0.020000")
  499. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  500. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  501. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  502. setting_id: Existing setting ID for updates, None for new
  503. slot_id: Calibration index (cali_idx) for the profile
  504. Returns:
  505. True if command was sent, False otherwise
  506. """
  507. if not self._client or not self.state.connected:
  508. logger.warning(f"[{self.serial_number}] Cannot set K-profile: not connected")
  509. return False
  510. self._sequence_id += 1
  511. # Build the filament entry - printer uses cali_idx for profile identification
  512. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  513. cali_idx = -1 if slot_id == 0 else slot_id
  514. # Generate a setting_id for new profiles (required by printer)
  515. # Format: "PF" + 17 random digits
  516. import random
  517. if not setting_id and slot_id == 0:
  518. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  519. filament_entry = {
  520. "ams_id": 0,
  521. "cali_idx": cali_idx,
  522. "extruder_id": extruder_id,
  523. "filament_id": filament_id,
  524. "k_value": k_value,
  525. "n_coef": "0.000000",
  526. "name": name,
  527. "nozzle_diameter": nozzle_diameter,
  528. "nozzle_id": nozzle_id,
  529. "setting_id": setting_id, # Always include setting_id
  530. "tray_id": -1,
  531. }
  532. command = {
  533. "print": {
  534. "command": "extrusion_cali_set",
  535. "filaments": [filament_entry],
  536. "nozzle_diameter": nozzle_diameter,
  537. "sequence_id": str(self._sequence_id),
  538. }
  539. }
  540. command_json = json.dumps(command)
  541. logger.info(f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={cali_idx}, new={slot_id==0})")
  542. logger.debug(f"[{self.serial_number}] K-profile command: {command_json}")
  543. self._client.publish(self.topic_publish, command_json)
  544. return True
  545. def delete_kprofile(
  546. self,
  547. cali_idx: int,
  548. filament_id: str,
  549. nozzle_id: str,
  550. nozzle_diameter: str = "0.4",
  551. extruder_id: int = 0,
  552. ) -> bool:
  553. """Delete a K-profile from the printer.
  554. Args:
  555. cali_idx: The calibration index (slot_id) of the profile to delete
  556. filament_id: Bambu filament identifier
  557. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  558. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  559. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  560. Returns:
  561. True if command was sent, False otherwise
  562. """
  563. if not self._client or not self.state.connected:
  564. logger.warning(f"[{self.serial_number}] Cannot delete K-profile: not connected")
  565. return False
  566. self._sequence_id += 1
  567. command = {
  568. "print": {
  569. "command": "extrusion_cali_del",
  570. "sequence_id": str(self._sequence_id),
  571. "extruder_id": extruder_id,
  572. "nozzle_id": nozzle_id,
  573. "filament_id": filament_id,
  574. "cali_idx": cali_idx,
  575. "nozzle_diameter": nozzle_diameter,
  576. }
  577. }
  578. command_json = json.dumps(command)
  579. logger.info(f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}")
  580. logger.debug(f"[{self.serial_number}] K-profile delete command: {command_json}")
  581. self._client.publish(self.topic_publish, command_json)
  582. return True