connection_manager.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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. else:
  423. state.table_type = None
  424. logger.warning(f"Unknown table type with Y steps/mm: {y_steps_per_mm}")
  425. logger.info(f"Machine type detected: {state.table_type}")
  426. return True
  427. else:
  428. missing = []
  429. if x_steps_per_mm is None: missing.append("X steps/mm")
  430. if y_steps_per_mm is None: missing.append("Y steps/mm")
  431. if gear_ratio is None: missing.append("gear ratio")
  432. logger.error(f"Failed to get all machine parameters after {timeout}s. Missing: {', '.join(missing)}")
  433. return False
  434. def home(timeout=30):
  435. """
  436. Perform homing by checking device configuration and sending the appropriate commands.
  437. Args:
  438. timeout: Maximum time in seconds to wait for homing to complete (default: 15)
  439. """
  440. import threading
  441. # Check for alarm state before homing and unlock if needed
  442. if not check_and_unlock_alarm():
  443. logger.error("Failed to unlock device from alarm state, cannot proceed with homing")
  444. return False
  445. # Flag to track if homing completed
  446. homing_complete = threading.Event()
  447. homing_success = False
  448. def home_internal():
  449. nonlocal homing_success
  450. try:
  451. if state.homing:
  452. logger.info("Using sensorless homing")
  453. state.conn.send("$H\n")
  454. state.conn.send("G1 Y0 F100\n")
  455. else:
  456. homing_speed = 400
  457. if state.table_type == 'dune_weaver_mini':
  458. homing_speed = 120
  459. logger.info("Sensorless homing not supported. Using crash homing")
  460. logger.info(f"Homing with speed {homing_speed}")
  461. # Run async function in new event loop
  462. loop = asyncio.new_event_loop()
  463. asyncio.set_event_loop(loop)
  464. try:
  465. if state.table_type == 'dune_weaver_mini':
  466. result = loop.run_until_complete(send_grbl_coordinates(0, - 30, homing_speed, home=True))
  467. if result == False:
  468. logger.error("Homing failed - send_grbl_coordinates returned False")
  469. homing_complete.set()
  470. return
  471. state.machine_y -= 30
  472. else:
  473. result = loop.run_until_complete(send_grbl_coordinates(0, -22, homing_speed, home=True))
  474. if result == False:
  475. logger.error("Homing failed - send_grbl_coordinates returned False")
  476. homing_complete.set()
  477. return
  478. state.machine_y -= 22
  479. finally:
  480. loop.close()
  481. # Wait for device to reach idle state after homing
  482. logger.info("Waiting for device to reach idle state after homing...")
  483. idle_reached = check_idle()
  484. if idle_reached:
  485. state.current_rho = 0
  486. if not state.current_theta:
  487. state.current_theta = 0
  488. homing_success = True
  489. logger.info("Homing completed and device is idle")
  490. else:
  491. logger.error("Device did not reach idle state after homing")
  492. homing_complete.set()
  493. except Exception as e:
  494. logger.error(f"Error during homing: {e}")
  495. homing_complete.set()
  496. # Start homing in a separate thread
  497. homing_thread = threading.Thread(target=home_internal)
  498. homing_thread.daemon = True
  499. homing_thread.start()
  500. # Wait for homing to complete or timeout
  501. if not homing_complete.wait(timeout):
  502. logger.error(f"Homing timeout after {timeout} seconds")
  503. # Try to stop any ongoing movement
  504. try:
  505. if state.conn and state.conn.is_connected():
  506. state.conn.send("!\n") # Send feed hold
  507. time.sleep(0.1)
  508. state.conn.send("\x18\n") # Send reset
  509. except Exception as e:
  510. logger.error(f"Error stopping movement after timeout: {e}")
  511. return False
  512. if not homing_success:
  513. logger.error("Homing failed")
  514. return False
  515. logger.info("Homing completed successfully")
  516. return True
  517. def check_idle():
  518. """
  519. Continuously check if the device is idle (synchronous version).
  520. """
  521. logger.info("Checking idle")
  522. while True:
  523. response = get_status_response()
  524. if response and "Idle" in response:
  525. logger.info("Device is idle")
  526. # Schedule async update_machine_position in the existing event loop
  527. try:
  528. # Try to schedule in existing event loop if available
  529. try:
  530. loop = asyncio.get_running_loop()
  531. # Create a task but don't await it (fire and forget)
  532. asyncio.create_task(update_machine_position())
  533. logger.debug("Scheduled machine position update task")
  534. except RuntimeError:
  535. # No event loop running, skip machine position update
  536. logger.debug("No event loop running, skipping machine position update")
  537. except Exception as e:
  538. logger.error(f"Error scheduling machine position update: {e}")
  539. return True
  540. time.sleep(1)
  541. async def check_idle_async():
  542. """
  543. Continuously check if the device is idle (async version).
  544. """
  545. logger.info("Checking idle (async)")
  546. while True:
  547. response = await asyncio.to_thread(get_status_response)
  548. if response and "Idle" in response:
  549. logger.info("Device is idle")
  550. try:
  551. await update_machine_position()
  552. except Exception as e:
  553. logger.error(f"Error updating machine position: {e}")
  554. return True
  555. await asyncio.sleep(1)
  556. def get_machine_position(timeout=5):
  557. """
  558. Query the device for its position.
  559. """
  560. start_time = time.time()
  561. while time.time() - start_time < timeout:
  562. try:
  563. state.conn.send('?')
  564. response = state.conn.readline()
  565. logger.debug(f"Raw status response: {response}")
  566. if "MPos" in response:
  567. pos = parse_machine_position(response)
  568. if pos:
  569. machine_x, machine_y = pos
  570. logger.debug(f"Machine position: X={machine_x}, Y={machine_y}")
  571. return machine_x, machine_y
  572. except Exception as e:
  573. logger.error(f"Error getting machine position: {e}")
  574. return
  575. time.sleep(0.1)
  576. logger.warning("Timeout reached waiting for machine position")
  577. return None, None
  578. async def update_machine_position():
  579. if (state.conn.is_connected() if state.conn else False):
  580. try:
  581. logger.info('Saving machine position')
  582. state.machine_x, state.machine_y = await asyncio.to_thread(get_machine_position)
  583. await asyncio.to_thread(state.save)
  584. logger.info(f'Machine position saved: {state.machine_x}, {state.machine_y}')
  585. except Exception as e:
  586. logger.error(f"Error updating machine position: {e}")
  587. def restart_connection(homing=False):
  588. """
  589. Restart the connection. If a connection exists, close it and attempt to establish a new one.
  590. It will try to connect via serial first (if available), otherwise it will fall back to websocket.
  591. The new connection is saved to state.conn.
  592. Returns:
  593. True if the connection was restarted successfully, False otherwise.
  594. """
  595. try:
  596. if (state.conn.is_connected() if state.conn else False):
  597. logger.info("Closing current connection...")
  598. state.conn.close()
  599. except Exception as e:
  600. logger.error(f"Error while closing connection: {e}")
  601. # Clear the connection reference.
  602. state.conn = None
  603. logger.info("Attempting to restart connection...")
  604. try:
  605. connect_device(homing) # This will set state.conn appropriately.
  606. if (state.conn.is_connected() if state.conn else False):
  607. logger.info("Connection restarted successfully.")
  608. return True
  609. else:
  610. logger.error("Failed to restart connection.")
  611. return False
  612. except Exception as e:
  613. logger.error(f"Error restarting connection: {e}")
  614. return False