bambu_mqtt.py 83 KB

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