1
0

connection_manager.py 27 KB

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