connection_manager.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. import threading
  2. import time
  3. import logging
  4. import serial
  5. import serial.tools.list_ports
  6. import websocket
  7. import asyncio
  8. from modules.core.state import state
  9. from modules.led.led_interface import LEDInterface
  10. from modules.led.idle_timeout_manager import idle_timeout_manager
  11. logger = logging.getLogger(__name__)
  12. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  13. async def _check_table_is_idle() -> bool:
  14. """Helper function to check if table is idle."""
  15. return not state.current_playing_file or state.pause_requested
  16. def _start_idle_led_timeout():
  17. """Start idle LED timeout if enabled."""
  18. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  19. return
  20. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  21. idle_timeout_manager.start_idle_timeout(
  22. timeout_minutes=state.dw_led_idle_timeout_minutes,
  23. state=state,
  24. check_idle_callback=_check_table_is_idle
  25. )
  26. ###############################################################################
  27. # Connection Abstraction
  28. ###############################################################################
  29. class BaseConnection:
  30. """Abstract base class for a connection."""
  31. def send(self, data: str) -> None:
  32. raise NotImplementedError
  33. def flush(self) -> None:
  34. raise NotImplementedError
  35. def readline(self) -> str:
  36. raise NotImplementedError
  37. def in_waiting(self) -> int:
  38. raise NotImplementedError
  39. def is_connected(self) -> bool:
  40. raise NotImplementedError
  41. def close(self) -> None:
  42. raise NotImplementedError
  43. ###############################################################################
  44. # Serial Connection Implementation
  45. ###############################################################################
  46. class SerialConnection(BaseConnection):
  47. def __init__(self, port: str, baudrate: int = 115200, timeout: int = 2):
  48. self.port = port
  49. self.baudrate = baudrate
  50. self.timeout = timeout
  51. self.lock = threading.RLock()
  52. logger.info(f'Connecting to Serial port {port}')
  53. self.ser = serial.Serial(port, baudrate, timeout=timeout)
  54. state.port = port
  55. logger.info(f'Connected to Serial port {port}')
  56. def send(self, data: str) -> None:
  57. with self.lock:
  58. self.ser.write(data.encode())
  59. self.ser.flush()
  60. def flush(self) -> None:
  61. with self.lock:
  62. self.ser.flush()
  63. def readline(self) -> str:
  64. with self.lock:
  65. return self.ser.readline().decode().strip()
  66. def in_waiting(self) -> int:
  67. with self.lock:
  68. return self.ser.in_waiting
  69. def is_connected(self) -> bool:
  70. return self.ser is not None and self.ser.is_open
  71. def close(self) -> None:
  72. # Run async update_machine_position in sync context
  73. try:
  74. loop = asyncio.new_event_loop()
  75. asyncio.set_event_loop(loop)
  76. loop.run_until_complete(update_machine_position())
  77. loop.close()
  78. except Exception as e:
  79. logger.error(f"Error updating machine position on close: {e}")
  80. with self.lock:
  81. if self.ser.is_open:
  82. self.ser.close()
  83. # Release the lock resources
  84. self.lock = None
  85. ###############################################################################
  86. # WebSocket Connection Implementation
  87. ###############################################################################
  88. class WebSocketConnection(BaseConnection):
  89. def __init__(self, url: str, timeout: int = 5):
  90. self.url = url
  91. self.timeout = timeout
  92. self.lock = threading.RLock()
  93. self.ws = None
  94. self.connect()
  95. def connect(self):
  96. logger.info(f'Connecting to Websocket {self.url}')
  97. self.ws = websocket.create_connection(self.url, timeout=self.timeout)
  98. state.port = self.url
  99. logger.info(f'Connected to Websocket {self.url}')
  100. def send(self, data: str) -> None:
  101. with self.lock:
  102. self.ws.send(data)
  103. def flush(self) -> None:
  104. # WebSocket sends immediately; nothing to flush.
  105. pass
  106. def readline(self) -> str:
  107. with self.lock:
  108. data = self.ws.recv()
  109. # Decode bytes to string if necessary
  110. if isinstance(data, bytes):
  111. data = data.decode('utf-8')
  112. return data.strip()
  113. def in_waiting(self) -> int:
  114. return 0 # Not applicable for WebSocket
  115. def is_connected(self) -> bool:
  116. return self.ws is not None
  117. def close(self) -> None:
  118. # Run async update_machine_position in sync context
  119. try:
  120. loop = asyncio.new_event_loop()
  121. asyncio.set_event_loop(loop)
  122. loop.run_until_complete(update_machine_position())
  123. loop.close()
  124. except Exception as e:
  125. logger.error(f"Error updating machine position on close: {e}")
  126. with self.lock:
  127. if self.ws:
  128. self.ws.close()
  129. # Release the lock resources
  130. self.lock = None
  131. def list_serial_ports():
  132. """Return a list of available serial ports."""
  133. ports = serial.tools.list_ports.comports()
  134. available_ports = [port.device for port in ports if port.device not in IGNORE_PORTS]
  135. logger.debug(f"Available serial ports: {available_ports}")
  136. return available_ports
  137. def device_init(homing=True):
  138. try:
  139. if get_machine_steps():
  140. logger.info(f"x_steps_per_mm: {state.x_steps_per_mm}, y_steps_per_mm: {state.y_steps_per_mm}, gear_ratio: {state.gear_ratio}")
  141. else:
  142. logger.fatal("Failed to get machine steps")
  143. state.conn.close()
  144. return False
  145. except:
  146. logger.fatal("Not GRBL firmware")
  147. state.conn.close()
  148. return False
  149. machine_x, machine_y = get_machine_position()
  150. if machine_x != state.machine_x or machine_y != state.machine_y:
  151. logger.info(f'x, y; {machine_x}, {machine_y}')
  152. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  153. if homing:
  154. success = home()
  155. if not success:
  156. logger.error("Homing failed during device initialization")
  157. else:
  158. logger.info('Machine position known, skipping home')
  159. logger.info(f'Theta: {state.current_theta}, rho: {state.current_rho}')
  160. logger.info(f'x, y; {machine_x}, {machine_y}')
  161. logger.info(f'State x, y; {state.machine_x}, {state.machine_y}')
  162. time.sleep(2) # Allow time for the connection to establish
  163. def connect_device(homing=True):
  164. # Initialize LED interface based on configured provider
  165. if state.led_provider == "wled" and state.wled_ip:
  166. state.led_controller = LEDInterface(provider="wled", ip_address=state.wled_ip)
  167. elif state.led_provider == "hyperion" and state.hyperion_ip:
  168. state.led_controller = LEDInterface(
  169. provider="hyperion",
  170. ip_address=state.hyperion_ip,
  171. port=state.hyperion_port
  172. )
  173. else:
  174. state.led_controller = None
  175. # Show loading effect
  176. if state.led_controller:
  177. state.led_controller.effect_loading()
  178. ports = list_serial_ports()
  179. if state.port and state.port in ports:
  180. state.conn = SerialConnection(state.port)
  181. elif ports:
  182. state.conn = SerialConnection(ports[0])
  183. else:
  184. logger.error("Auto connect failed.")
  185. # state.conn = WebSocketConnection('ws://fluidnc.local:81')
  186. if (state.conn.is_connected() if state.conn else False):
  187. # Check for alarm state and unlock if needed before initializing
  188. if not check_and_unlock_alarm():
  189. logger.error("Failed to unlock device from alarm state")
  190. # Still proceed with device_init but log the issue
  191. device_init(homing)
  192. # Show connected effect, then transition to configured idle effect
  193. if state.led_controller:
  194. logger.info("Showing LED connected effect (green flash)")
  195. state.led_controller.effect_connected()
  196. # Set the configured idle effect after connection
  197. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  198. state.led_controller.effect_idle(state.dw_led_idle_effect)
  199. _start_idle_led_timeout()
  200. def check_and_unlock_alarm():
  201. """
  202. Check if GRBL is in alarm state and unlock it with $X if needed.
  203. Uses $A command to log detailed alarm information before unlocking.
  204. Returns True if device is ready (unlocked or no alarm), False on error.
  205. """
  206. try:
  207. logger.info("Checking device status for alarm state...")
  208. # Send status query
  209. state.conn.send('?\n')
  210. time.sleep(0.1)
  211. # Read response with timeout
  212. max_attempts = 5
  213. response = None
  214. for attempt in range(max_attempts):
  215. if state.conn.in_waiting() > 0:
  216. response = state.conn.readline()
  217. logger.debug(f"Status response: {response}")
  218. break
  219. time.sleep(0.1)
  220. if not response:
  221. logger.warning("No status response received, proceeding anyway")
  222. return True
  223. # Check for alarm state
  224. if "Alarm" in response:
  225. logger.warning(f"Device in ALARM state: {response}")
  226. # Query alarm details with $A command
  227. logger.info("Querying alarm details with $A command...")
  228. state.conn.send('$A\n')
  229. time.sleep(0.2)
  230. # Read and log alarm details
  231. for attempt in range(max_attempts):
  232. if state.conn.in_waiting() > 0:
  233. alarm_details = state.conn.readline()
  234. logger.warning(f"Alarm details: {alarm_details}")
  235. break
  236. time.sleep(0.1)
  237. # Send unlock command
  238. logger.info("Sending $X to unlock...")
  239. state.conn.send('$X\n')
  240. time.sleep(0.5)
  241. # Verify unlock succeeded
  242. state.conn.send('?\n')
  243. time.sleep(0.1)
  244. verify_response = state.conn.readline()
  245. logger.debug(f"Verification response: {verify_response}")
  246. if "Alarm" in verify_response:
  247. logger.error("Failed to unlock device from alarm state")
  248. return False
  249. else:
  250. logger.info("Device successfully unlocked")
  251. return True
  252. else:
  253. logger.info("Device not in alarm state, proceeding normally")
  254. return True
  255. except Exception as e:
  256. logger.error(f"Error checking/unlocking alarm: {e}")
  257. return False
  258. def get_status_response() -> str:
  259. """
  260. Send a status query ('?') and return the response if available.
  261. """
  262. while True:
  263. try:
  264. state.conn.send('?')
  265. response = state.conn.readline()
  266. if "MPos" in response:
  267. logger.debug(f"Status response: {response}")
  268. return response
  269. except Exception as e:
  270. logger.error(f"Error getting status response: {e}")
  271. return False
  272. time.sleep(1)
  273. def parse_machine_position(response: str):
  274. """
  275. Parse the work position (MPos) from a status response.
  276. Expected format: "<...|MPos:-994.869,-321.861,0.000|...>"
  277. Returns a tuple (work_x, work_y) if found, else None.
  278. """
  279. if "MPos:" not in response:
  280. return None
  281. try:
  282. wpos_section = next((part for part in response.split("|") if part.startswith("MPos:")), None)
  283. if wpos_section:
  284. wpos_str = wpos_section.split(":", 1)[1]
  285. wpos_values = wpos_str.split(",")
  286. work_x = float(wpos_values[0])
  287. work_y = float(wpos_values[1])
  288. return work_x, work_y
  289. except Exception as e:
  290. logger.error(f"Error parsing work position: {e}")
  291. return None
  292. async def send_grbl_coordinates(x, y, speed=600, timeout=2, home=False):
  293. """
  294. Send a G-code command to FluidNC and wait for an 'ok' response.
  295. If no response after set timeout, sets state to stop and disconnects.
  296. """
  297. logger.debug(f"Sending G-code: X{x} Y{y} at F{speed}")
  298. # Track overall attempt time
  299. overall_start_time = time.time()
  300. while True:
  301. try:
  302. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  303. # Use asyncio.to_thread for both send and receive operations to avoid blocking
  304. await asyncio.to_thread(state.conn.send, gcode + "\n")
  305. logger.debug(f"Sent command: {gcode}")
  306. start_time = time.time()
  307. while True:
  308. # Use asyncio.to_thread for blocking I/O operations
  309. response = await asyncio.to_thread(state.conn.readline)
  310. logger.debug(f"Response: {response}")
  311. if response.lower() == "ok":
  312. logger.debug("Command execution confirmed.")
  313. return
  314. except Exception as e:
  315. # Store the error string inside the exception block
  316. error_str = str(e)
  317. logger.warning(f"Error sending command: {error_str}")
  318. # Immediately return for device not configured errors
  319. if "Device not configured" in error_str or "Errno 6" in error_str:
  320. logger.error(f"Device configuration error detected: {error_str}")
  321. state.stop_requested = True
  322. state.conn = None
  323. state.is_connected = False
  324. logger.info("Connection marked as disconnected due to device error")
  325. return False
  326. logger.warning(f"No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  327. await asyncio.sleep(0.1)
  328. # If we reach here, the timeout has occurred
  329. logger.error(f"Failed to receive 'ok' response after {max_total_attempt_time} seconds. Stopping and disconnecting.")
  330. # Set state to stop
  331. state.stop_requested = True
  332. # Set connection status to disconnected
  333. if state.conn:
  334. try:
  335. state.conn.disconnect()
  336. except:
  337. pass
  338. state.conn = None
  339. # Update the state connection status
  340. state.is_connected = False
  341. logger.info("Connection marked as disconnected due to timeout")
  342. return False
  343. def get_machine_steps(timeout=10):
  344. """
  345. Get machine steps/mm from the GRBL controller.
  346. Returns True if successful, False otherwise.
  347. """
  348. if not state.conn or not state.conn.is_connected():
  349. logger.error("Cannot get machine steps: No connection available")
  350. return False
  351. x_steps_per_mm = None
  352. y_steps_per_mm = None
  353. gear_ratio = None
  354. start_time = time.time()
  355. # Clear any pending data in the buffer
  356. try:
  357. while state.conn.in_waiting() > 0:
  358. state.conn.readline()
  359. except Exception as e:
  360. logger.warning(f"Error clearing buffer: {e}")
  361. # Send the command to request all settings
  362. try:
  363. logger.info("Requesting GRBL settings with $$ command")
  364. state.conn.send("$$\n")
  365. time.sleep(0.5) # Give GRBL a moment to process and respond
  366. except Exception as e:
  367. logger.error(f"Error sending $$ command: {e}")
  368. return False
  369. # Wait for and process responses
  370. settings_complete = False
  371. while time.time() - start_time < timeout and not settings_complete:
  372. try:
  373. # Attempt to read a line from the connection
  374. if state.conn.in_waiting() > 0:
  375. response = state.conn.readline()
  376. logger.debug(f"Raw response: {response}")
  377. # Process the line
  378. if response.strip(): # Only process non-empty lines
  379. for line in response.splitlines():
  380. line = line.strip()
  381. logger.debug(f"Config response: {line}")
  382. if line.startswith("$100="):
  383. x_steps_per_mm = float(line.split("=")[1])
  384. state.x_steps_per_mm = x_steps_per_mm
  385. logger.info(f"X steps per mm: {x_steps_per_mm}")
  386. elif line.startswith("$101="):
  387. y_steps_per_mm = float(line.split("=")[1])
  388. state.y_steps_per_mm = y_steps_per_mm
  389. logger.info(f"Y steps per mm: {y_steps_per_mm}")
  390. elif line.startswith("$131="):
  391. gear_ratio = float(line.split("=")[1])
  392. state.gear_ratio = gear_ratio
  393. logger.info(f"Gear ratio: {gear_ratio}")
  394. elif line.startswith("$22="):
  395. # $22 reports if the homing cycle is enabled
  396. # returns 0 if disabled, 1 if enabled
  397. homing = int(line.split('=')[1])
  398. state.homing = homing
  399. logger.info(f"Homing enabled: {homing}")
  400. # Check if we've received all the settings we need
  401. if x_steps_per_mm is not None and y_steps_per_mm is not None and gear_ratio is not None:
  402. settings_complete = True
  403. else:
  404. # No data waiting, small sleep to prevent CPU thrashing
  405. time.sleep(0.1)
  406. # If it's taking too long, try sending the command again after 3 seconds
  407. elapsed = time.time() - start_time
  408. if elapsed > 3 and elapsed < 4:
  409. logger.warning("No response yet, sending $$ command again")
  410. state.conn.send("$$\n")
  411. except Exception as e:
  412. logger.error(f"Error getting machine steps: {e}")
  413. time.sleep(0.5)
  414. # Process results and determine table type
  415. if settings_complete:
  416. if y_steps_per_mm == 180:
  417. state.table_type = 'dune_weaver_mini'
  418. elif y_steps_per_mm >= 320:
  419. state.table_type = 'dune_weaver_pro'
  420. elif y_steps_per_mm == 287:
  421. state.table_type = 'dune_weaver'
  422. elif y_steps_per_mm == 164:
  423. state.table_type == 'dune_weaver_mini_pro'
  424. else:
  425. state.table_type = None
  426. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  427. logger.info(f"Machine type detected: {state.table_type}")
  428. return True
  429. else:
  430. missing = []
  431. if x_steps_per_mm is None: missing.append("X steps/mm")
  432. if y_steps_per_mm is None: missing.append("Y steps/mm")
  433. if gear_ratio is None: missing.append("gear ratio")
  434. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  435. return False
  436. def home(timeout=30):
  437. """
  438. Perform homing by checking device configuration and sending the appropriate commands.
  439. Args:
  440. timeout: Maximum time in seconds to wait for homing to complete (default: 15)
  441. """
  442. import threading
  443. # Check for alarm state before homing and unlock if needed
  444. if not check_and_unlock_alarm():
  445. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  446. return False
  447. # Flag to track if homing completed
  448. homing_complete = threading.Event()
  449. homing_success = False
  450. def home_internal():
  451. nonlocal homing_success
  452. try:
  453. if state.homing:
  454. logger.info("Using sensorless homing")
  455. state.conn.send("$H\n")
  456. state.conn.send("G1 Y0 F100\n")
  457. else:
  458. homing_speed = 400
  459. if state.table_type == 'dune_weaver_mini':
  460. homing_speed = 120
  461. logger.info("Sensorless homing not supported. Using crash homing")
  462. logger.info(f"Homing with speed {homing_speed}")
  463. # Run async function in new event loop
  464. loop = asyncio.new_event_loop()
  465. asyncio.set_event_loop(loop)
  466. try:
  467. if state.table_type == 'dune_weaver_mini':
  468. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  469. if result == False:
  470. logger.error("Homing failed - send_grbl_coordinates returned False")
  471. homing_complete.set()
  472. return
  473. state.machine_y -= 30
  474. else:
  475. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  476. if result == False:
  477. logger.error("Homing failed - send_grbl_coordinates returned False")
  478. homing_complete.set()
  479. return
  480. state.machine_y -= 22
  481. finally:
  482. loop.close()
  483. # Wait for device to reach idle state after homing
  484. logger.info("Waiting for device to reach idle state after homing...")
  485. idle_reached = check_idle()
  486. if idle_reached:
  487. state.current_rho = 0
  488. if not state.current_theta:
  489. state.current_theta = 0
  490. homing_success = True
  491. logger.info("Homing completed and device is idle")
  492. else:
  493. logger.error("Device did not reach idle state after homing")
  494. homing_complete.set()
  495. except Exception as e:
  496. logger.error(f"Error during homing: {e}")
  497. homing_complete.set()
  498. # Start homing in a separate thread
  499. homing_thread = threading.Thread(target=home_internal)
  500. homing_thread.daemon = True
  501. homing_thread.start()
  502. # Wait for homing to complete or timeout
  503. if not homing_complete.wait(timeout):
  504. logger.error(f"Homing timeout after {timeout} seconds")
  505. # Try to stop any ongoing movement
  506. try:
  507. if state.conn and state.conn.is_connected():
  508. state.conn.send("!\n") # Send feed hold
  509. time.sleep(0.1)
  510. state.conn.send("\x18\n") # Send reset
  511. except Exception as e:
  512. logger.error(f"Error stopping movement after timeout: {e}")
  513. return False
  514. if not homing_success:
  515. logger.error("Homing failed")
  516. return False
  517. logger.info("Homing completed successfully")
  518. return True
  519. def hardware_pause():
  520. """
  521. Execute immediate hardware pause using GRBL feed hold command.
  522. Sends '!' command to GRBL for instant motion pause without flushing buffer.
  523. """
  524. try:
  525. if not state.conn or not state.conn.is_connected():
  526. logger.warning("Cannot send hardware pause - device not connected")
  527. return False
  528. logger.info("Sending hardware pause command (!) to GRBL")
  529. state.conn.send("!")
  530. # Show idle LED effect
  531. if state.led_controller:
  532. logger.debug("Setting LED to idle effect after hardware pause")
  533. state.led_controller.effect_idle(state.dw_led_idle_effect)
  534. _start_idle_led_timeout()
  535. return True
  536. except Exception as e:
  537. logger.error(f"Error sending hardware pause: {e}")
  538. return False
  539. def hardware_resume():
  540. """
  541. Execute immediate hardware resume using GRBL cycle start command.
  542. Sends '~' command to GRBL to resume motion from exact pause position.
  543. """
  544. try:
  545. if not state.conn or not state.conn.is_connected():
  546. logger.warning("Cannot send hardware resume - device not connected")
  547. return False
  548. logger.info("Sending hardware resume command (~) to GRBL")
  549. state.conn.send("~")
  550. # Show playing LED effect
  551. if state.led_controller:
  552. logger.debug("Setting LED to playing effect after hardware resume")
  553. state.led_controller.effect_playing(state.dw_led_playing_effect)
  554. # Cancel idle timeout when resuming
  555. idle_timeout_manager.cancel_timeout()
  556. return True
  557. except Exception as e:
  558. logger.error(f"Error sending hardware resume: {e}")
  559. return False
  560. def check_idle():
  561. """
  562. Continuously check if the device is idle (synchronous version).
  563. """
  564. logger.info("Checking idle")
  565. while True:
  566. response = get_status_response()
  567. if response and "Idle" in response:
  568. logger.info("Device is idle")
  569. # Schedule async update_machine_position in the existing event loop
  570. try:
  571. # Try to schedule in existing event loop if available
  572. try:
  573. loop = asyncio.get_running_loop()
  574. # Create a task but don't await it (fire and forget)
  575. asyncio.create_task(update_machine_position())
  576. logger.debug("Scheduled machine position update task")
  577. except RuntimeError:
  578. # No event loop running, skip machine position update
  579. logger.debug("No event loop running, skipping machine position update")
  580. except Exception as e:
  581. logger.error(f"Error scheduling machine position update: {e}")
  582. return True
  583. time.sleep(1)
  584. async def check_idle_async():
  585. """
  586. Continuously check if the device is idle (async version).
  587. """
  588. logger.info("Checking idle (async)")
  589. while True:
  590. response = await asyncio.to_thread(get_status_response)
  591. if response and "Idle" in response:
  592. logger.info("Device is idle")
  593. try:
  594. await update_machine_position()
  595. except Exception as e:
  596. logger.error(f"Error updating machine position: {e}")
  597. return True
  598. await asyncio.sleep(1)
  599. def get_machine_position(timeout=5):
  600. """
  601. Query the device for its position.
  602. """
  603. start_time = time.time()
  604. while time.time() - start_time < timeout:
  605. try:
  606. state.conn.send('?')
  607. response = state.conn.readline()
  608. logger.debug(f"Raw status response: {response}")
  609. if "MPos" in response:
  610. pos = parse_machine_position(response)
  611. if pos:
  612. machine_x, machine_y = pos
  613. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  614. return machine_x, machine_y
  615. except Exception as e:
  616. logger.error(f"Error getting machine position: {e}")
  617. return
  618. time.sleep(0.1)
  619. logger.warning("Timeout reached waiting for machine position")
  620. return None, None
  621. async def update_machine_position():
  622. if (state.conn.is_connected() if state.conn else False):
  623. try:
  624. logger.info('Saving machine position')
  625. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  626. await asyncio.to_thread(state.save)
  627. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  628. except Exception as e:
  629. logger.error(f"Error updating machine position: {e}")
  630. def restart_connection(homing=False):
  631. """
  632. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  633. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  634. The new connection is saved to state.conn.
  635. Returns:
  636. True if the connection was restarted successfully, False otherwise.
  637. """
  638. try:
  639. if (state.conn.is_connected() if state.conn else False):
  640. logger.info("Closing current connection...")
  641. state.conn.close()
  642. except Exception as e:
  643. logger.error(f"Error while closing connection: {e}")
  644. # Clear the connection reference.
  645. state.conn = None
  646. logger.info("Attempting to restart connection...")
  647. try:
  648. connect_device(homing) # This will set state.conn appropriately.
  649. if (state.conn.is_connected() if state.conn else False):
  650. logger.info("Connection restarted successfully.")
  651. return True
  652. else:
  653. logger.error("Failed to restart connection.")
  654. return False
  655. except Exception as e:
  656. logger.error(f"Error restarting connection: {e}")
  657. return False