Skip to content

Commit

Permalink
recreate serial instead of reopen
Browse files Browse the repository at this point in the history
  • Loading branch information
ianohara committed Jan 21, 2025
1 parent 9d52067 commit 041d06d
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions software/control/microcontroller.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,8 @@ def exponential_backoff_time(attempt_index: int, initial_interval: float) -> flo

def __init__(self, port: str, baudrate: int):
super().__init__()
self._port = port
self._baudrate = baudrate
self._serial = serial.Serial(port, baudrate)

def close(self) -> None:
Expand Down Expand Up @@ -303,6 +305,8 @@ def bytes_available(self) -> int:

def is_open(self) -> bool:
try:
if not self._serial.is_open:
return False
# pyserial is_open is sortof useless - it doesn't force a check to see if the device is still valid.
# but the in_waiting does an ioctl to check for the bytes in the read buffer. This is a system call, so
# not the best from a performance perspective, but we are operating with 2 mega baud and a system call
Expand All @@ -321,12 +325,18 @@ def reconnect(self, attempts: int) -> bool:
MicrocontrollerSerial.exponential_backoff_time(i, MicrocontrollerSerial.INITIAL_RECONNECT_INTERVAL)
)
try:
self._serial.close()
self._serial.open()
try:
self._serial.close()
except OSError:
pass
self._serial = serial.Serial(port=self._port, baudrate=self._baudrate)
except SerialException as se:
if i + 1 == attempts:
exc_info = se
else:
exc_info = None
self._log.warning(
f"Couldn't reconnect serial={self._serial.port} @ baud={self._serial.baudrate}. Attempt {i + 1}/{attempts}.", exc_info=se
)
f"Couldn't reconnect serial={self._serial.port} @ baud={self._serial.baudrate}. Attempt {i + 1}/{attempts}.", exc_info=exc_info)
else:
break

Expand Down

0 comments on commit 041d06d

Please sign in to comment.