bambu_mqtt.py 73 KB

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