bambu_mqtt.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  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. # Check if this is H2D (has device.extruder.info with 2 extruders)
  576. has_h2d_extruder_info = (
  577. "device" in data and
  578. isinstance(data.get("device"), dict) and
  579. "extruder" in data["device"] and
  580. isinstance(data["device"]["extruder"].get("info"), list) and
  581. len(data["device"]["extruder"]["info"]) >= 2
  582. )
  583. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  584. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  585. if "nozzle_temper" in data:
  586. if has_h2d_extruder_info:
  587. temps["nozzle_2"] = float(data["nozzle_temper"]) # RIGHT nozzle on H2D
  588. else:
  589. temps["nozzle"] = float(data["nozzle_temper"])
  590. if "nozzle_target_temper" in data:
  591. if has_h2d_extruder_info:
  592. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  593. else:
  594. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  595. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  596. if not has_h2d_extruder_info:
  597. # Try multiple possible field names used by different firmware versions
  598. if "nozzle_temper_2" in data:
  599. val = float(data["nozzle_temper_2"])
  600. if -50 < val < 500: # Valid temp range
  601. temps["nozzle_2"] = val
  602. else:
  603. logger.debug(f"[{self.serial_number}] nozzle_temper_2={val} out of range")
  604. elif "right_nozzle_temper" in data:
  605. val = float(data["right_nozzle_temper"])
  606. if -50 < val < 500: # Valid temp range
  607. temps["nozzle_2"] = val
  608. else:
  609. logger.debug(f"[{self.serial_number}] right_nozzle_temper={val} out of range")
  610. if "nozzle_target_temper_2" in data:
  611. val = float(data["nozzle_target_temper_2"])
  612. if 0 <= val < 500: # Valid temp range
  613. temps["nozzle_2_target"] = val
  614. else:
  615. logger.debug(f"[{self.serial_number}] nozzle_target_temper_2={val} out of range")
  616. elif "right_nozzle_target_temper" in data:
  617. val = float(data["right_nozzle_target_temper"])
  618. if 0 <= val < 500: # Valid temp range
  619. temps["nozzle_2_target"] = val
  620. else:
  621. logger.debug(f"[{self.serial_number}] right_nozzle_target_temper={val} out of range")
  622. # Also check for left nozzle as primary (some H2 models)
  623. if "left_nozzle_temper" in data and "nozzle" not in temps:
  624. temps["nozzle"] = float(data["left_nozzle_temper"])
  625. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  626. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  627. if "chamber_temper" in data:
  628. temps["chamber"] = float(data["chamber_temper"])
  629. # Chamber target temperature (set by print file or display)
  630. if "mc_target_cham" in data:
  631. temps["chamber_target"] = float(data["mc_target_cham"])
  632. # H2D series: Chamber temp is in info.temp (directly in °C)
  633. try:
  634. if "info" in data and isinstance(data["info"], dict):
  635. info_temp = data["info"].get("temp")
  636. if info_temp is not None and "chamber" not in temps:
  637. temps["chamber"] = float(info_temp)
  638. # H2D series: Dual extruder temps are in device.extruder.info array
  639. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  640. if "device" in data and isinstance(data["device"], dict):
  641. device = data["device"]
  642. # Parse dual extruder temperatures
  643. extruder_data = device.get("extruder", {})
  644. extruder_info = extruder_data.get("info", [])
  645. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  646. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  647. # RIGHT nozzle uses standard nozzle_temper/nozzle_target_temper fields (already parsed above)
  648. # LEFT nozzle uses extruder_info[1] - no standard fields available
  649. # Note: hnow/htar flags are unreliable (static values, not actual heating state)
  650. # Real heating indicator: temp > 500 means encoded (target*65536+current)
  651. # Heating = target > 0 AND current < target
  652. # Right nozzle (extruder 0)
  653. if len(extruder_info) >= 1 and "temp" in extruder_info[0]:
  654. temp_val = extruder_info[0]["temp"]
  655. if temp_val > 500:
  656. target = temp_val // 65536
  657. current = temp_val % 65536
  658. temps["nozzle_2_heating"] = target > 0 and current < target
  659. else:
  660. temps["nozzle_2_heating"] = False
  661. # Left nozzle (extruder 1)
  662. # H2D protocol: temp field encoding depends on value
  663. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  664. # - When < 500: direct Celsius current temp only - heater is OFF
  665. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  666. ext1 = extruder_info[1]
  667. temp_val = ext1["temp"]
  668. # Check if we recently set the target locally (within 5 seconds)
  669. # If so, don't let MQTT data overwrite it
  670. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  671. respect_local_target = (time.time() - local_set_time) < 5.0
  672. if temp_val > 500:
  673. # Encoded format: temp = target * 65536 + current
  674. target = temp_val // 65536
  675. current = temp_val % 65536
  676. if 0 < target < 500 and not respect_local_target:
  677. temps["nozzle_target"] = float(target)
  678. if -50 < current < 500:
  679. temps["nozzle"] = float(current)
  680. # Heating = encoded AND we're using the MQTT target (not local override)
  681. # If local target is being respected, use local target to determine heating
  682. if respect_local_target:
  683. local_target = self.state.temperatures.get("nozzle_target", 0)
  684. temps["nozzle_heating"] = local_target > 0 and current < local_target
  685. else:
  686. temps["nozzle_heating"] = target > 0 and current < target
  687. elif -50 < temp_val < 500:
  688. # Direct Celsius = heater is OFF (or at target with heater off)
  689. temps["nozzle"] = float(temp_val)
  690. if not respect_local_target:
  691. temps["nozzle_target"] = 0.0
  692. temps["nozzle_heating"] = False # Direct = not heating
  693. # Parse bed heating state from device.bed.info.temp encoding
  694. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  695. bed_data = device.get("bed", {})
  696. bed_info = bed_data.get("info", {})
  697. if "temp" in bed_info:
  698. temp_val = bed_info["temp"]
  699. if temp_val > 500:
  700. target = temp_val // 65536
  701. current = temp_val % 65536
  702. temps["bed_heating"] = target > 0 and current < target
  703. else:
  704. temps["bed_heating"] = False
  705. # Parse chamber temp from device.ctc.info.temp if not already set
  706. ctc_data = device.get("ctc", {})
  707. ctc_info = ctc_data.get("info", {})
  708. if "temp" in ctc_info and "chamber" not in temps:
  709. temps["chamber"] = float(ctc_info["temp"])
  710. # Parse chamber target from ctc.info.target if available
  711. if "target" in ctc_info and "chamber_target" not in temps:
  712. temps["chamber_target"] = float(ctc_info["target"])
  713. # Parse chamber heating state from temp encoding
  714. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  715. if "temp" in ctc_info:
  716. temp_val = ctc_info["temp"]
  717. if temp_val > 500:
  718. target = temp_val // 65536
  719. current = temp_val % 65536
  720. temps["chamber_heating"] = target > 0 and current < target
  721. else:
  722. temps["chamber_heating"] = False
  723. except Exception as e:
  724. logger.warning(f"[{self.serial_number}] Error parsing H2D temperatures: {e}")
  725. if temps:
  726. # Merge new temps into existing, preserving valid values when new ones are filtered out
  727. for key, value in temps.items():
  728. self.state.temperatures[key] = value
  729. # Parse HMS (Health Management System) errors
  730. if "hms" in data:
  731. hms_list = data["hms"]
  732. self.state.hms_errors = []
  733. if isinstance(hms_list, list):
  734. for hms in hms_list:
  735. if isinstance(hms, dict):
  736. # HMS format: {"attr": code, "code": full_code}
  737. # The code is a hex string, severity is in bits
  738. code = hms.get("code", hms.get("attr", "0"))
  739. if isinstance(code, int):
  740. code = hex(code)
  741. # Parse severity from code (typically last 4 bits indicate level)
  742. try:
  743. code_int = int(str(code).replace("0x", ""), 16) if code else 0
  744. severity = (code_int >> 16) & 0xF # Extract severity bits
  745. module = (code_int >> 24) & 0xFF # Extract module bits
  746. except (ValueError, TypeError):
  747. severity = 3
  748. module = 0
  749. self.state.hms_errors.append(HMSError(
  750. code=str(code),
  751. module=module,
  752. severity=severity if severity > 0 else 3,
  753. ))
  754. # Parse SD card status
  755. if "sdcard" in data:
  756. self.state.sdcard = data["sdcard"] is True
  757. # Parse home_flag for "Store Sent Files on External Storage" setting (bit 11)
  758. if "home_flag" in data:
  759. home_flag = data["home_flag"]
  760. # Bit 11 controls "Store Sent Files on External Storage"
  761. # Convert to unsigned 32-bit if negative
  762. if home_flag < 0:
  763. home_flag = home_flag & 0xFFFFFFFF
  764. store_to_sdcard = bool((home_flag >> 11) & 1)
  765. if store_to_sdcard != self.state.store_to_sdcard:
  766. logger.info(f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}")
  767. self.state.store_to_sdcard = store_to_sdcard
  768. # Parse timelapse status (recording active during print)
  769. if "timelapse" in data:
  770. logger.debug(f"[{self.serial_number}] timelapse field: {data['timelapse']}")
  771. self.state.timelapse = data["timelapse"] is True
  772. # Parse ipcam/live view status
  773. if "ipcam" in data:
  774. ipcam_data = data["ipcam"]
  775. logger.debug(f"[{self.serial_number}] ipcam field: {ipcam_data}")
  776. if isinstance(ipcam_data, dict):
  777. # Check ipcam_record field for live view status
  778. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  779. else:
  780. self.state.ipcam = ipcam_data is True
  781. # Parse nozzle hardware info (single nozzle printers)
  782. if "nozzle_type" in data:
  783. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  784. if "nozzle_diameter" in data:
  785. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  786. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  787. # Left nozzle
  788. if "left_nozzle_type" in data:
  789. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  790. if "left_nozzle_diameter" in data:
  791. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  792. # Right nozzle
  793. if "right_nozzle_type" in data:
  794. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  795. if "right_nozzle_diameter" in data:
  796. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  797. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  798. if "nozzle_type_2" in data:
  799. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  800. if "nozzle_diameter_2" in data:
  801. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  802. # H2D series: Nozzle hardware info is in device.nozzle.info array
  803. if "device" in data and isinstance(data["device"], dict):
  804. device = data["device"]
  805. nozzle_data = device.get("nozzle", {})
  806. nozzle_info = nozzle_data.get("info", [])
  807. if isinstance(nozzle_info, list):
  808. for nozzle in nozzle_info:
  809. idx = nozzle.get("id", 0)
  810. if idx < len(self.state.nozzles):
  811. if "type" in nozzle and nozzle["type"]:
  812. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  813. if "diameter" in nozzle:
  814. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  815. # Preserve AMS and vt_tray data when updating raw_data
  816. ams_data = self.state.raw_data.get("ams")
  817. vt_tray_data = self.state.raw_data.get("vt_tray")
  818. self.state.raw_data = data
  819. if ams_data is not None:
  820. self.state.raw_data["ams"] = ams_data
  821. if vt_tray_data is not None:
  822. self.state.raw_data["vt_tray"] = vt_tray_data
  823. # Log state transitions for debugging
  824. if "gcode_state" in data:
  825. logger.debug(
  826. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  827. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  828. )
  829. # Detect print start (state changes TO RUNNING with a file)
  830. current_file = self.state.gcode_file or self.state.current_print
  831. is_new_print = (
  832. self.state.state == "RUNNING"
  833. and self._previous_gcode_state != "RUNNING"
  834. and current_file
  835. )
  836. # Also detect if file changed while running (new print started)
  837. is_file_change = (
  838. self.state.state == "RUNNING"
  839. and current_file
  840. and current_file != self._previous_gcode_file
  841. and self._previous_gcode_file is not None
  842. )
  843. # Track RUNNING state for more robust completion detection
  844. if self.state.state == "RUNNING" and current_file:
  845. if not self._was_running:
  846. logger.info(f"[{self.serial_number}] Now tracking RUNNING state for {current_file}")
  847. self._was_running = True
  848. self._completion_triggered = False
  849. if is_new_print or is_file_change:
  850. # Clear any old HMS errors when a new print starts
  851. self.state.hms_errors = []
  852. # Reset completion tracking for new print
  853. self._was_running = True
  854. self._completion_triggered = False
  855. if (is_new_print or is_file_change) and self.on_print_start:
  856. logger.info(
  857. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  858. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  859. )
  860. self.on_print_start({
  861. "filename": current_file,
  862. "subtask_name": self.state.subtask_name,
  863. "raw_data": data,
  864. })
  865. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  866. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  867. # This handles cases where server restarts during a print
  868. should_trigger_completion = (
  869. self.state.state in ("FINISH", "FAILED")
  870. and not self._completion_triggered
  871. and self.on_print_complete
  872. and (
  873. self._previous_gcode_state == "RUNNING" # Normal transition
  874. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  875. )
  876. )
  877. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  878. if (
  879. self.state.state == "IDLE"
  880. and self._previous_gcode_state == "RUNNING"
  881. and not self._completion_triggered
  882. and self.on_print_complete
  883. ):
  884. should_trigger_completion = True
  885. if should_trigger_completion:
  886. if self.state.state == "FINISH":
  887. status = "completed"
  888. elif self.state.state == "FAILED":
  889. status = "failed"
  890. else:
  891. status = "aborted"
  892. logger.info(
  893. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  894. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  895. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}"
  896. )
  897. self._completion_triggered = True
  898. self._was_running = False
  899. self.on_print_complete({
  900. "status": status,
  901. "filename": self._previous_gcode_file or current_file,
  902. "subtask_name": self.state.subtask_name,
  903. "raw_data": data,
  904. })
  905. self._previous_gcode_state = self.state.state
  906. if current_file:
  907. self._previous_gcode_file = current_file
  908. if self.on_state_change:
  909. self.on_state_change(self.state)
  910. def _request_push_all(self):
  911. """Request full status update from printer."""
  912. if self._client:
  913. message = {"pushing": {"command": "pushall"}}
  914. self._client.publish(self.topic_publish, json.dumps(message))
  915. def request_status_update(self) -> bool:
  916. """Request a full status update from the printer (public API).
  917. Sends both pushall and get_accessories commands to refresh all data
  918. including nozzle hardware info.
  919. Returns:
  920. True if the request was sent, False if not connected.
  921. """
  922. if not self._client or not self.state.connected:
  923. return False
  924. self._request_push_all()
  925. # Note: get_accessories returns stale nozzle data on H2D.
  926. # The correct nozzle data comes from push_status response.
  927. return True
  928. def _request_accessories(self):
  929. """Request accessories info (nozzle type, etc.) from printer."""
  930. if self._client:
  931. self._sequence_id += 1
  932. message = {
  933. "system": {
  934. "sequence_id": str(self._sequence_id),
  935. "command": "get_accessories",
  936. "accessory_type": "none"
  937. }
  938. }
  939. logger.debug(f"[{self.serial_number}] Requesting accessories info")
  940. self._client.publish(self.topic_publish, json.dumps(message))
  941. def _prime_kprofile_request(self):
  942. """Send a priming K-profile request on connect.
  943. Bambu printers often ignore the first K-profile request after connection,
  944. so we send a dummy request on connect to 'prime' the system.
  945. """
  946. if self._client:
  947. self._sequence_id += 1
  948. command = {
  949. "print": {
  950. "command": "extrusion_cali_get",
  951. "filament_id": "",
  952. "nozzle_diameter": "0.4",
  953. "sequence_id": str(self._sequence_id),
  954. }
  955. }
  956. logger.debug(f"[{self.serial_number}] Sending K-profile priming request")
  957. self._client.publish(self.topic_publish, json.dumps(command))
  958. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  959. """Connect to the printer MQTT broker.
  960. Args:
  961. loop: The asyncio event loop to use for thread-safe callbacks.
  962. If not provided, will try to get the running loop.
  963. """
  964. self._loop = loop
  965. self._client = mqtt.Client(
  966. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  967. client_id=f"bambutrack_{self.serial_number}",
  968. protocol=mqtt.MQTTv311,
  969. )
  970. self._client.username_pw_set("bblp", self.access_code)
  971. self._client.on_connect = self._on_connect
  972. self._client.on_disconnect = self._on_disconnect
  973. self._client.on_message = self._on_message
  974. # TLS setup - Bambu uses self-signed certs
  975. ssl_context = ssl.create_default_context()
  976. ssl_context.check_hostname = False
  977. ssl_context.verify_mode = ssl.CERT_NONE
  978. self._client.tls_set_context(ssl_context)
  979. # Use shorter keepalive (15s) for faster disconnect detection
  980. # Paho considers connection lost after 1.5x keepalive with no response
  981. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=15)
  982. self._client.loop_start()
  983. def start_print(self, filename: str, plate_id: int = 1):
  984. """Start a print job on the printer.
  985. The file should already be uploaded to /cache/ on the printer via FTP.
  986. """
  987. if self._client and self.state.connected:
  988. # Bambu print command format
  989. # Based on: https://github.com/darkorb/bambu-ftp-and-print
  990. command = {
  991. "print": {
  992. "sequence_id": 0,
  993. "command": "project_file",
  994. "param": f"Metadata/plate_{plate_id}.gcode",
  995. "subtask_name": filename,
  996. "url": f"ftp://{filename}",
  997. "timelapse": False,
  998. "bed_leveling": True,
  999. "flow_cali": True,
  1000. "vibration_cali": True,
  1001. "layer_inspect": False,
  1002. "use_ams": True,
  1003. }
  1004. }
  1005. logger.info(f"[{self.serial_number}] Sending print command: {json.dumps(command)}")
  1006. self._client.publish(self.topic_publish, json.dumps(command))
  1007. return True
  1008. return False
  1009. def stop_print(self) -> bool:
  1010. """Stop the current print job."""
  1011. if self._client and self.state.connected:
  1012. command = {
  1013. "print": {
  1014. "command": "stop",
  1015. "sequence_id": "0"
  1016. }
  1017. }
  1018. self._client.publish(self.topic_publish, json.dumps(command))
  1019. logger.info(f"[{self.serial_number}] Sent stop print command")
  1020. return True
  1021. return False
  1022. def set_xcam_option(
  1023. self,
  1024. module_name: str,
  1025. enabled: bool,
  1026. print_halt: bool = True,
  1027. sensitivity: str = "medium"
  1028. ) -> bool:
  1029. """Set an xcam (AI detection) option on the printer.
  1030. Args:
  1031. module_name: The xcam module to control (e.g., "spaghetti_detector",
  1032. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  1033. enabled: Whether to enable or disable the feature
  1034. print_halt: Whether to halt print on detection (only applies to some detectors)
  1035. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  1036. Returns:
  1037. True if command was sent, False if not connected
  1038. """
  1039. if not self._client or not self.state.connected:
  1040. return False
  1041. # auto_recovery_step_loss uses a different command format (print.print_option)
  1042. if module_name == "auto_recovery_step_loss":
  1043. return self._set_print_option("auto_recovery", enabled)
  1044. self._sequence_id += 1
  1045. # Build the xcam control command (exact OrcaSlicer format)
  1046. # Key findings from OrcaSlicer source:
  1047. # - Uses "xcam" wrapper (not "print")
  1048. # - print_halt is ALWAYS true (legacy protocol requirement)
  1049. # - Both "control" and "enable" are set to the same value
  1050. # - halt_print_sensitivity controls actual halt behavior
  1051. command = {
  1052. "xcam": {
  1053. "command": "xcam_control_set",
  1054. "sequence_id": str(self._sequence_id),
  1055. "module_name": module_name,
  1056. "control": enabled,
  1057. "enable": enabled, # old protocol compatibility
  1058. "print_halt": True, # ALWAYS true per OrcaSlicer
  1059. }
  1060. }
  1061. # Only add sensitivity if not "never_halt"
  1062. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  1063. # The module_name field determines which detector's sensitivity is being set
  1064. if sensitivity and sensitivity != "never_halt":
  1065. command["xcam"]["halt_print_sensitivity"] = sensitivity
  1066. command_json = json.dumps(command)
  1067. self._client.publish(self.topic_publish, command_json, qos=1)
  1068. logger.info(f"[{self.serial_number}] Set xcam option: {module_name}={enabled}, sensitivity={sensitivity}")
  1069. logger.debug(f"[{self.serial_number}] MQTT command sent: {command_json}")
  1070. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  1071. # This prevents stale MQTT data from immediately overwriting our change
  1072. self._xcam_hold_start[module_name] = time.time()
  1073. # Update local state immediately for responsive UI
  1074. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  1075. # When spaghetti_detector sensitivity is changed, pileup also changes
  1076. if module_name == "spaghetti_detector":
  1077. self.state.print_options.spaghetti_detector = enabled
  1078. self.state.print_options.print_halt = print_halt
  1079. if sensitivity and sensitivity != "never_halt":
  1080. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  1081. self.state.print_options.halt_print_sensitivity = sensitivity
  1082. self.state.print_options.pileup_sensitivity = sensitivity
  1083. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  1084. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  1085. elif module_name == "first_layer_inspector":
  1086. self.state.print_options.first_layer_inspector = enabled
  1087. elif module_name == "printing_monitor":
  1088. self.state.print_options.printing_monitor = enabled
  1089. elif module_name == "buildplate_marker_detector":
  1090. self.state.print_options.buildplate_marker_detector = enabled
  1091. elif module_name == "allow_skip_parts":
  1092. self.state.print_options.allow_skip_parts = enabled
  1093. elif module_name == "pileup_detector":
  1094. self.state.print_options.pileup_detector = enabled
  1095. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  1096. elif module_name == "clump_detector":
  1097. self.state.print_options.nozzle_clumping_detector = enabled
  1098. if sensitivity and sensitivity != "never_halt":
  1099. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  1100. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  1101. elif module_name == "airprint_detector":
  1102. self.state.print_options.airprint_detector = enabled
  1103. if sensitivity and sensitivity != "never_halt":
  1104. self.state.print_options.airprint_sensitivity = sensitivity
  1105. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  1106. elif module_name == "auto_recovery_step_loss":
  1107. self.state.print_options.auto_recovery_step_loss = enabled
  1108. return True
  1109. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  1110. """Set a print option using the print.print_option command.
  1111. This is different from xcam_control_set and is used for options like:
  1112. - auto_recovery
  1113. - air_print_detect
  1114. - filament_tangle_detect
  1115. - nozzle_blob_detect
  1116. - sound_enable
  1117. Args:
  1118. option_name: The option to control (e.g., "auto_recovery")
  1119. enabled: Whether to enable or disable the option
  1120. Returns:
  1121. True if command was sent, False if not connected
  1122. """
  1123. if not self._client or not self.state.connected:
  1124. return False
  1125. self._sequence_id += 1
  1126. command = {
  1127. "print": {
  1128. "command": "print_option",
  1129. "sequence_id": str(self._sequence_id),
  1130. option_name: enabled,
  1131. }
  1132. }
  1133. command_json = json.dumps(command)
  1134. self._client.publish(self.topic_publish, command_json, qos=1)
  1135. logger.info(f"[{self.serial_number}] Set print option: {option_name}={enabled}")
  1136. # Set hold timer
  1137. hold_key = f"print_option_{option_name}"
  1138. self._xcam_hold_start[hold_key] = time.time()
  1139. # Update local state immediately
  1140. if option_name == "auto_recovery":
  1141. self.state.print_options.auto_recovery_step_loss = enabled
  1142. return True
  1143. def start_calibration(
  1144. self,
  1145. bed_leveling: bool = False,
  1146. vibration: bool = False,
  1147. motor_noise: bool = False,
  1148. nozzle_offset: bool = False,
  1149. high_temp_heatbed: bool = False,
  1150. ) -> bool:
  1151. """Start printer calibration with selected options.
  1152. Args:
  1153. bed_leveling: Run bed leveling calibration
  1154. vibration: Run vibration compensation calibration
  1155. motor_noise: Run motor noise cancellation calibration
  1156. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  1157. high_temp_heatbed: Run high-temperature heatbed calibration
  1158. Returns:
  1159. True if command was sent, False if not connected
  1160. """
  1161. if not self._client or not self.state.connected:
  1162. return False
  1163. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  1164. # Bit 0: xcam_cali (not exposed in UI)
  1165. # Bit 1: bed_leveling
  1166. # Bit 2: vibration
  1167. # Bit 3: motor_noise
  1168. # Bit 4: nozzle_cali
  1169. # Bit 5: bed_cali (high-temp heatbed)
  1170. # Bit 6: clumppos_cali (not exposed in UI)
  1171. option = 0
  1172. if bed_leveling:
  1173. option |= 1 << 1
  1174. if vibration:
  1175. option |= 1 << 2
  1176. if motor_noise:
  1177. option |= 1 << 3
  1178. if nozzle_offset:
  1179. option |= 1 << 4
  1180. if high_temp_heatbed:
  1181. option |= 1 << 5
  1182. if option == 0:
  1183. logger.warning(f"[{self.serial_number}] No calibration options selected")
  1184. return False
  1185. self._sequence_id += 1
  1186. command = {
  1187. "print": {
  1188. "command": "calibration",
  1189. "sequence_id": str(self._sequence_id),
  1190. "option": option,
  1191. }
  1192. }
  1193. command_json = json.dumps(command)
  1194. self._client.publish(self.topic_publish, command_json, qos=1)
  1195. logger.info(
  1196. f"[{self.serial_number}] Starting calibration: "
  1197. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  1198. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  1199. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  1200. )
  1201. return True
  1202. def disconnect(self):
  1203. """Disconnect from the printer."""
  1204. if self._client:
  1205. self._client.loop_stop()
  1206. self._client.disconnect()
  1207. self._client = None
  1208. self.state.connected = False
  1209. def send_command(self, command: dict):
  1210. """Send a command to the printer."""
  1211. if self._client and self.state.connected:
  1212. # Log outgoing message if logging is enabled
  1213. if self._logging_enabled:
  1214. self._message_log.append(MQTTLogEntry(
  1215. timestamp=datetime.now().isoformat(),
  1216. topic=self.topic_publish,
  1217. direction="out",
  1218. payload=command,
  1219. ))
  1220. self._client.publish(self.topic_publish, json.dumps(command))
  1221. def enable_logging(self, enabled: bool = True):
  1222. """Enable or disable MQTT message logging."""
  1223. self._logging_enabled = enabled
  1224. # Don't clear logs when stopping - user can manually clear with clear_logs()
  1225. def get_logs(self) -> list[MQTTLogEntry]:
  1226. """Get all logged MQTT messages."""
  1227. return list(self._message_log)
  1228. def clear_logs(self):
  1229. """Clear the message log."""
  1230. self._message_log.clear()
  1231. @property
  1232. def logging_enabled(self) -> bool:
  1233. """Check if logging is enabled."""
  1234. return self._logging_enabled
  1235. def _handle_kprofile_response(self, data: dict):
  1236. """Handle K-profile response from printer."""
  1237. filaments = data.get("filaments", [])
  1238. profiles = []
  1239. # Log first profile to see what fields the printer returns
  1240. if filaments and isinstance(filaments[0], dict):
  1241. logger.debug(f"[{self.serial_number}] Raw K-profile fields: {list(filaments[0].keys())}")
  1242. logger.debug(f"[{self.serial_number}] First K-profile: {filaments[0]}")
  1243. for i, f in enumerate(filaments):
  1244. if isinstance(f, dict):
  1245. try:
  1246. # cali_idx is the actual slot/calibration index from the printer
  1247. cali_idx = f.get("cali_idx", i)
  1248. profiles.append(KProfile(
  1249. slot_id=cali_idx,
  1250. extruder_id=int(f.get("extruder_id", 0)),
  1251. nozzle_id=str(f.get("nozzle_id", "")),
  1252. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  1253. filament_id=str(f.get("filament_id", "")),
  1254. name=str(f.get("name", "")),
  1255. k_value=str(f.get("k_value", "0.000000")),
  1256. n_coef=str(f.get("n_coef", "0.000000")),
  1257. ams_id=int(f.get("ams_id", 0)),
  1258. tray_id=int(f.get("tray_id", -1)),
  1259. setting_id=f.get("setting_id"),
  1260. ))
  1261. except (ValueError, TypeError) as e:
  1262. logger.warning(f"Failed to parse K-profile: {e}")
  1263. self.state.kprofiles = profiles
  1264. self._kprofile_response_data = profiles
  1265. # Signal that we received the response
  1266. # Use thread-safe method since MQTT callbacks run in a different thread
  1267. if self._pending_kprofile_response:
  1268. if self._loop and self._loop.is_running():
  1269. self._loop.call_soon_threadsafe(self._pending_kprofile_response.set)
  1270. else:
  1271. # Fallback for when loop is not available
  1272. self._pending_kprofile_response.set()
  1273. logger.info(f"[{self.serial_number}] Received {len(profiles)} K-profiles")
  1274. async def get_kprofiles(self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3) -> list[KProfile]:
  1275. """Request K-profiles from the printer with retry logic.
  1276. Bambu printers sometimes ignore the first K-profile request, so we
  1277. implement retry logic to ensure reliable retrieval.
  1278. Args:
  1279. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  1280. timeout: Timeout in seconds to wait for each response attempt
  1281. max_retries: Maximum number of retry attempts
  1282. Returns:
  1283. List of KProfile objects
  1284. """
  1285. if not self._client or not self.state.connected:
  1286. logger.warning(f"[{self.serial_number}] Cannot get K-profiles: not connected")
  1287. return []
  1288. # Capture current event loop for thread-safe callback
  1289. try:
  1290. self._loop = asyncio.get_running_loop()
  1291. except RuntimeError:
  1292. logger.warning(f"[{self.serial_number}] No running event loop")
  1293. return []
  1294. for attempt in range(max_retries):
  1295. # Set up response event for this attempt
  1296. self._sequence_id += 1
  1297. self._pending_kprofile_response = asyncio.Event()
  1298. self._kprofile_response_data = None
  1299. # Send the command
  1300. command = {
  1301. "print": {
  1302. "command": "extrusion_cali_get",
  1303. "filament_id": "",
  1304. "nozzle_diameter": nozzle_diameter,
  1305. "sequence_id": str(self._sequence_id),
  1306. }
  1307. }
  1308. logger.info(f"[{self.serial_number}] Requesting K-profiles for nozzle {nozzle_diameter} (attempt {attempt + 1}/{max_retries})")
  1309. self._client.publish(self.topic_publish, json.dumps(command))
  1310. # Wait for response
  1311. try:
  1312. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  1313. profiles = self._kprofile_response_data or []
  1314. logger.info(f"[{self.serial_number}] Got {len(profiles)} K-profiles on attempt {attempt + 1}")
  1315. return profiles
  1316. except asyncio.TimeoutError:
  1317. logger.warning(f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}")
  1318. if attempt < max_retries - 1:
  1319. # Brief delay before retry
  1320. await asyncio.sleep(0.5)
  1321. finally:
  1322. self._pending_kprofile_response = None
  1323. logger.error(f"[{self.serial_number}] Failed to get K-profiles after {max_retries} attempts")
  1324. return []
  1325. def set_kprofile(
  1326. self,
  1327. filament_id: str,
  1328. name: str,
  1329. k_value: str,
  1330. nozzle_diameter: str = "0.4",
  1331. nozzle_id: str = "HS00-0.4",
  1332. extruder_id: int = 0,
  1333. setting_id: str | None = None,
  1334. slot_id: int = 0,
  1335. cali_idx: int | None = None,
  1336. ) -> bool:
  1337. """Set/update a K-profile on the printer.
  1338. Args:
  1339. filament_id: Bambu filament identifier
  1340. name: Profile name
  1341. k_value: Pressure advance value (e.g., "0.020000")
  1342. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  1343. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  1344. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  1345. setting_id: Existing setting ID for updates, None for new
  1346. slot_id: Calibration index (cali_idx) for the profile
  1347. cali_idx: For H2D edits, the existing slot being edited (enables in-place edit)
  1348. Returns:
  1349. True if command was sent, False otherwise
  1350. """
  1351. if not self._client or not self.state.connected:
  1352. logger.warning(f"[{self.serial_number}] Cannot set K-profile: not connected")
  1353. return False
  1354. self._sequence_id += 1
  1355. # Detect printer type by serial number prefix
  1356. # X1C/P1/A1 series (single nozzle): serial starts with "00M", "00W", "01P", "01S", "03W", etc.
  1357. # H2D series (dual nozzle): serial starts with "094"
  1358. is_dual_nozzle = self.serial_number.startswith("094")
  1359. # For H2D edits, use empty setting_id per OrcaSlicer sniff
  1360. # For new profiles, generate a setting_id
  1361. import secrets
  1362. if cali_idx is not None:
  1363. # Edit mode - use empty setting_id per OrcaSlicer sniff
  1364. setting_id = ""
  1365. elif not setting_id and slot_id == 0:
  1366. # New profile - generate setting_id
  1367. setting_id = f"PFUS{secrets.token_hex(7)}" # 7 bytes = 14 hex chars
  1368. if is_dual_nozzle:
  1369. # H2D format - exact OrcaSlicer format (captured via MQTT sniffing)
  1370. # For edits: include cali_idx (existing slot), slot_id=0, setting_id=""
  1371. # For new profiles: no cali_idx, slot_id=0, setting_id=generated
  1372. filament_entry = {
  1373. "ams_id": 0,
  1374. "extruder_id": extruder_id,
  1375. "filament_id": filament_id,
  1376. "k_value": k_value,
  1377. "n_coef": "0.000000",
  1378. "name": name,
  1379. "nozzle_diameter": nozzle_diameter,
  1380. "nozzle_id": nozzle_id,
  1381. "setting_id": setting_id if setting_id else "",
  1382. "slot_id": slot_id,
  1383. "tray_id": -1,
  1384. }
  1385. # For edits, add cali_idx field (position matters - alphabetical order)
  1386. if cali_idx is not None:
  1387. # Insert cali_idx in alphabetical position (after ams_id, before extruder_id)
  1388. # n_coef must be "0.000000" for H2D edits (matches OrcaSlicer sniff)
  1389. filament_entry = {
  1390. "ams_id": 0,
  1391. "cali_idx": cali_idx,
  1392. "extruder_id": extruder_id,
  1393. "filament_id": filament_id,
  1394. "k_value": k_value,
  1395. "n_coef": "0.000000",
  1396. "name": name,
  1397. "nozzle_diameter": nozzle_diameter,
  1398. "nozzle_id": nozzle_id,
  1399. "setting_id": "",
  1400. "slot_id": 0,
  1401. "tray_id": -1,
  1402. }
  1403. command = {
  1404. "print": {
  1405. "command": "extrusion_cali_set",
  1406. "filaments": [filament_entry],
  1407. "nozzle_diameter": nozzle_diameter,
  1408. "sequence_id": str(self._sequence_id),
  1409. }
  1410. }
  1411. else:
  1412. # X1C/P1/A1 format - based on actual X1C profile data:
  1413. # - n_coef: "1.000000" (NOT 0.000000 like H2D)
  1414. # - nozzle_id: "" (empty string, NOT the nozzle type)
  1415. # - tray_id: -1 (NOT 0)
  1416. filament_entry = {
  1417. "ams_id": 0,
  1418. "extruder_id": 0, # X1C is single nozzle
  1419. "filament_id": filament_id,
  1420. "k_value": k_value,
  1421. "n_coef": "1.000000", # X1C uses 1.0, not 0.0
  1422. "name": name,
  1423. "nozzle_diameter": nozzle_diameter,
  1424. "nozzle_id": "", # X1C uses empty string
  1425. "setting_id": setting_id,
  1426. "slot_id": slot_id,
  1427. "tray_id": -1, # X1C uses -1
  1428. }
  1429. command = {
  1430. "print": {
  1431. "command": "extrusion_cali_set",
  1432. "filaments": [filament_entry],
  1433. "nozzle_diameter": nozzle_diameter,
  1434. "sequence_id": str(self._sequence_id),
  1435. }
  1436. }
  1437. command_json = json.dumps(command)
  1438. logger.info(f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={cali_idx}, new={slot_id==0}, dual={is_dual_nozzle})")
  1439. logger.info(f"[{self.serial_number}] K-profile SET command: {command_json}")
  1440. # Use QoS 1 for reliable delivery (at least once)
  1441. self._client.publish(self.topic_publish, command_json, qos=1)
  1442. return True
  1443. def delete_kprofile(
  1444. self,
  1445. cali_idx: int,
  1446. filament_id: str,
  1447. nozzle_id: str,
  1448. nozzle_diameter: str = "0.4",
  1449. extruder_id: int = 0,
  1450. setting_id: str | None = None,
  1451. ) -> bool:
  1452. """Delete a K-profile from the printer.
  1453. Args:
  1454. cali_idx: The calibration index (slot_id) of the profile to delete
  1455. filament_id: Bambu filament identifier
  1456. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  1457. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  1458. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  1459. setting_id: Unique setting identifier (for X1C series)
  1460. Returns:
  1461. True if command was sent, False otherwise
  1462. """
  1463. if not self._client or not self.state.connected:
  1464. logger.warning(f"[{self.serial_number}] Cannot delete K-profile: not connected")
  1465. return False
  1466. self._sequence_id += 1
  1467. # Detect printer type by serial number prefix
  1468. # H2D series (dual nozzle): serial starts with "094"
  1469. is_dual_nozzle = self.serial_number.startswith("094")
  1470. if is_dual_nozzle:
  1471. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  1472. command = {
  1473. "print": {
  1474. "command": "extrusion_cali_del",
  1475. "sequence_id": str(self._sequence_id),
  1476. "extruder_id": extruder_id,
  1477. "nozzle_id": nozzle_id,
  1478. "filament_id": filament_id,
  1479. "cali_idx": cali_idx,
  1480. "nozzle_diameter": nozzle_diameter,
  1481. }
  1482. }
  1483. else:
  1484. # X1C/P1/A1 format: uses setting_id, nozzle_diameter, no extruder/nozzle_id fields
  1485. command = {
  1486. "print": {
  1487. "command": "extrusion_cali_del",
  1488. "sequence_id": str(self._sequence_id),
  1489. "filament_id": filament_id,
  1490. "cali_idx": cali_idx,
  1491. "setting_id": setting_id,
  1492. "nozzle_diameter": nozzle_diameter,
  1493. }
  1494. }
  1495. command_json = json.dumps(command)
  1496. logger.info(f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, dual={is_dual_nozzle}")
  1497. logger.info(f"[{self.serial_number}] K-profile DELETE command: {command_json}")
  1498. # Use QoS 1 for reliable delivery (at least once)
  1499. self._client.publish(self.topic_publish, command_json, qos=1)
  1500. return True
  1501. # =========================================================================
  1502. # Printer Control Commands
  1503. # =========================================================================
  1504. def pause_print(self) -> bool:
  1505. """Pause the current print job."""
  1506. if not self._client or not self.state.connected:
  1507. logger.warning(f"[{self.serial_number}] Cannot pause print: not connected")
  1508. return False
  1509. command = {
  1510. "print": {
  1511. "command": "pause",
  1512. "sequence_id": "0"
  1513. }
  1514. }
  1515. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1516. logger.info(f"[{self.serial_number}] Sent pause print command")
  1517. return True
  1518. def resume_print(self) -> bool:
  1519. """Resume a paused print job."""
  1520. if not self._client or not self.state.connected:
  1521. logger.warning(f"[{self.serial_number}] Cannot resume print: not connected")
  1522. return False
  1523. command = {
  1524. "print": {
  1525. "command": "resume",
  1526. "sequence_id": "0"
  1527. }
  1528. }
  1529. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1530. logger.info(f"[{self.serial_number}] Sent resume print command")
  1531. return True
  1532. def send_gcode(self, gcode: str) -> bool:
  1533. """Send G-code command(s) to the printer.
  1534. Multiple commands can be separated by newlines.
  1535. Args:
  1536. gcode: G-code command(s) to send
  1537. Returns:
  1538. True if command was sent, False otherwise
  1539. """
  1540. if not self._client or not self.state.connected:
  1541. logger.warning(f"[{self.serial_number}] Cannot send G-code: not connected")
  1542. return False
  1543. self._sequence_id += 1
  1544. command = {
  1545. "print": {
  1546. "command": "gcode_line",
  1547. "param": gcode,
  1548. "sequence_id": str(self._sequence_id)
  1549. }
  1550. }
  1551. # Use QoS 1 for reliable delivery (at least once)
  1552. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  1553. logger.debug(f"[{self.serial_number}] Sent G-code: {gcode[:50]}...")
  1554. return True
  1555. def set_bed_temperature(self, target: int) -> bool:
  1556. """Set the bed target temperature.
  1557. Args:
  1558. target: Target temperature in Celsius (0 to turn off)
  1559. Returns:
  1560. True if command was sent, False otherwise
  1561. """
  1562. return self.send_gcode(f"M140 S{target}")
  1563. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  1564. """Set the nozzle target temperature.
  1565. Args:
  1566. target: Target temperature in Celsius (0 to turn off)
  1567. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  1568. Returns:
  1569. True if command was sent, False otherwise
  1570. """
  1571. # Use M104 for non-blocking
  1572. # Always use T parameter for H2D compatibility
  1573. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  1574. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  1575. # Track it locally so we can display it correctly
  1576. if result and nozzle == 1:
  1577. self.state.temperatures["nozzle_target"] = float(target)
  1578. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  1579. logger.info(f"[{self.serial_number}] Tracking LEFT nozzle target locally: {target}°C")
  1580. return result
  1581. def set_print_speed(self, mode: int) -> bool:
  1582. """Set the print speed mode.
  1583. Args:
  1584. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  1585. Returns:
  1586. True if command was sent, False otherwise
  1587. """
  1588. if not self._client or not self.state.connected:
  1589. logger.warning(f"[{self.serial_number}] Cannot set print speed: not connected")
  1590. return False
  1591. if mode not in (1, 2, 3, 4):
  1592. logger.warning(f"[{self.serial_number}] Invalid speed mode: {mode}")
  1593. return False
  1594. command = {
  1595. "print": {
  1596. "command": "print_speed",
  1597. "param": str(mode),
  1598. "sequence_id": "0"
  1599. }
  1600. }
  1601. self._client.publish(self.topic_publish, json.dumps(command))
  1602. logger.info(f"[{self.serial_number}] Set print speed mode to {mode}")
  1603. return True
  1604. def set_fan_speed(self, fan: int, speed: int) -> bool:
  1605. """Set fan speed.
  1606. Args:
  1607. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber)
  1608. speed: Speed 0-255 (0=off, 255=full)
  1609. Returns:
  1610. True if command was sent, False otherwise
  1611. """
  1612. if fan not in (1, 2, 3):
  1613. logger.warning(f"[{self.serial_number}] Invalid fan index: {fan}")
  1614. return False
  1615. speed = max(0, min(255, speed)) # Clamp to 0-255
  1616. return self.send_gcode(f"M106 P{fan} S{speed}")
  1617. def set_part_fan(self, speed: int) -> bool:
  1618. """Set part cooling fan speed (0-255)."""
  1619. return self.set_fan_speed(1, speed)
  1620. def set_aux_fan(self, speed: int) -> bool:
  1621. """Set auxiliary fan speed (0-255)."""
  1622. return self.set_fan_speed(2, speed)
  1623. def set_chamber_fan(self, speed: int) -> bool:
  1624. """Set chamber fan speed (0-255)."""
  1625. return self.set_fan_speed(3, speed)
  1626. def set_chamber_light(self, on: bool) -> bool:
  1627. """Turn chamber light on or off.
  1628. Args:
  1629. on: True to turn on, False to turn off
  1630. Returns:
  1631. True if command was sent, False otherwise
  1632. """
  1633. if not self._client or not self.state.connected:
  1634. logger.warning(f"[{self.serial_number}] Cannot set chamber light: not connected")
  1635. return False
  1636. command = {
  1637. "system": {
  1638. "command": "ledctrl",
  1639. "led_node": "chamber_light",
  1640. "led_mode": "on" if on else "off",
  1641. "led_on_time": 500,
  1642. "led_off_time": 500,
  1643. "loop_times": 0,
  1644. "interval_time": 0,
  1645. "sequence_id": "0"
  1646. }
  1647. }
  1648. self._client.publish(self.topic_publish, json.dumps(command))
  1649. logger.info(f"[{self.serial_number}] Set chamber light {'on' if on else 'off'}")
  1650. return True
  1651. def home_axes(self, axes: str = "XYZ") -> bool:
  1652. """Home the specified axes.
  1653. Args:
  1654. axes: Axes to home (e.g., "XYZ", "X", "XY", "Z")
  1655. Returns:
  1656. True if command was sent, False otherwise
  1657. """
  1658. # G28 homes all axes, G28 X Y Z homes specific axes
  1659. axes_param = " ".join(axes.upper())
  1660. return self.send_gcode(f"G28 {axes_param}")
  1661. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  1662. """Move an axis by a relative distance.
  1663. Args:
  1664. axis: Axis to move ("X", "Y", or "Z")
  1665. distance: Distance to move in mm (positive or negative)
  1666. speed: Movement speed in mm/min
  1667. Returns:
  1668. True if command was sent, False otherwise
  1669. """
  1670. axis = axis.upper()
  1671. if axis not in ("X", "Y", "Z"):
  1672. logger.warning(f"[{self.serial_number}] Invalid axis: {axis}")
  1673. return False
  1674. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  1675. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  1676. return self.send_gcode(gcode)
  1677. def disable_motors(self) -> bool:
  1678. """Disable all stepper motors.
  1679. Warning: This will cause the printer to lose its position.
  1680. A homing operation will be required before printing.
  1681. Returns:
  1682. True if command was sent, False otherwise
  1683. """
  1684. return self.send_gcode("M18")
  1685. def enable_motors(self) -> bool:
  1686. """Enable all stepper motors.
  1687. Returns:
  1688. True if command was sent, False otherwise
  1689. """
  1690. return self.send_gcode("M17")
  1691. def ams_load_filament(self, tray_id: int) -> bool:
  1692. """Load filament from a specific AMS tray.
  1693. Args:
  1694. tray_id: Tray ID (0-15 for AMS slots, or 254 for external spool)
  1695. Returns:
  1696. True if command was sent, False otherwise
  1697. """
  1698. if not self._client or not self.state.connected:
  1699. logger.warning(f"[{self.serial_number}] Cannot load filament: not connected")
  1700. return False
  1701. command = {
  1702. "print": {
  1703. "command": "ams_change_filament",
  1704. "target": tray_id,
  1705. "sequence_id": "0"
  1706. }
  1707. }
  1708. self._client.publish(self.topic_publish, json.dumps(command))
  1709. logger.info(f"[{self.serial_number}] Loading filament from tray {tray_id}")
  1710. return True
  1711. def ams_unload_filament(self) -> bool:
  1712. """Unload the currently loaded filament.
  1713. Returns:
  1714. True if command was sent, False otherwise
  1715. """
  1716. if not self._client or not self.state.connected:
  1717. logger.warning(f"[{self.serial_number}] Cannot unload filament: not connected")
  1718. return False
  1719. command = {
  1720. "print": {
  1721. "command": "ams_change_filament",
  1722. "target": 255, # 255 = unload
  1723. "sequence_id": "0"
  1724. }
  1725. }
  1726. self._client.publish(self.topic_publish, json.dumps(command))
  1727. logger.info(f"[{self.serial_number}] Unloading filament")
  1728. return True
  1729. def ams_control(self, action: str) -> bool:
  1730. """Control AMS operations.
  1731. Args:
  1732. action: "resume", "reset", or "pause"
  1733. Returns:
  1734. True if command was sent, False otherwise
  1735. """
  1736. if not self._client or not self.state.connected:
  1737. logger.warning(f"[{self.serial_number}] Cannot control AMS: not connected")
  1738. return False
  1739. if action not in ("resume", "reset", "pause"):
  1740. logger.warning(f"[{self.serial_number}] Invalid AMS action: {action}")
  1741. return False
  1742. command = {
  1743. "print": {
  1744. "command": "ams_control",
  1745. "param": action,
  1746. "sequence_id": "0"
  1747. }
  1748. }
  1749. self._client.publish(self.topic_publish, json.dumps(command))
  1750. logger.info(f"[{self.serial_number}] AMS control: {action}")
  1751. return True
  1752. def set_timelapse(self, enable: bool) -> bool:
  1753. """Enable or disable timelapse recording.
  1754. Args:
  1755. enable: True to enable, False to disable
  1756. Returns:
  1757. True if command was sent, False otherwise
  1758. """
  1759. if not self._client or not self.state.connected:
  1760. logger.warning(f"[{self.serial_number}] Cannot set timelapse: not connected")
  1761. return False
  1762. command = {
  1763. "pushing": {
  1764. "command": "pushall",
  1765. "sequence_id": "0"
  1766. }
  1767. }
  1768. # First send the timelapse setting
  1769. timelapse_cmd = {
  1770. "print": {
  1771. "command": "gcode_line",
  1772. "param": f"M981 S{1 if enable else 0} P20000",
  1773. "sequence_id": "0"
  1774. }
  1775. }
  1776. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd))
  1777. # Request status update
  1778. self._client.publish(self.topic_publish, json.dumps(command))
  1779. logger.info(f"[{self.serial_number}] Set timelapse {'enabled' if enable else 'disabled'}")
  1780. return True
  1781. def set_liveview(self, enable: bool) -> bool:
  1782. """Enable or disable live view / camera streaming.
  1783. Args:
  1784. enable: True to enable, False to disable
  1785. Returns:
  1786. True if command was sent, False otherwise
  1787. """
  1788. if not self._client or not self.state.connected:
  1789. logger.warning(f"[{self.serial_number}] Cannot set liveview: not connected")
  1790. return False
  1791. command = {
  1792. "xcam": {
  1793. "command": "ipcam_record_set",
  1794. "control": "enable" if enable else "disable",
  1795. "sequence_id": "0"
  1796. }
  1797. }
  1798. self._client.publish(self.topic_publish, json.dumps(command))
  1799. # Request status update
  1800. pushall = {
  1801. "pushing": {
  1802. "command": "pushall",
  1803. "sequence_id": "0"
  1804. }
  1805. }
  1806. self._client.publish(self.topic_publish, json.dumps(pushall))
  1807. logger.info(f"[{self.serial_number}] Set liveview {'enabled' if enable else 'disabled'}")
  1808. return True