connection_manager.py 26 KB

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