Skip to content

Commit

Permalink
Ignore error when closing an already closed serial connection
Browse files Browse the repository at this point in the history
An OSError would be raised when reader and writer threads were
concurrently closing the serial connection. One of them would close
an already closed connection.

Ideally this would be synchronized so we'd be able to detect an issue
closing the connection. In this case a global resource in the system may
be broken rendering the system un-usable.

For now just we just ignore any issues while closing, not taking a
a potential later use of the device into account.
  • Loading branch information
clssn committed Apr 22, 2024
1 parent 8a8090e commit 670edff
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/numato_gpio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,11 @@ def cleanup(self):
self.iodir = self._mask_all_ports
if self.can_notify:
self.notify = False
self._ser.close()
try:
self._ser.close()
except OSError:
pass
self._poll_thread.join()

def write(self, port, value):
"""Write the logic level of a single port.
Expand Down Expand Up @@ -406,7 +410,10 @@ def _write(self, query):
with self._rw_lock:
self._ser.write(query)
except serial.serialutil.SerialException as err:
self._ser.close()
try:
self._ser.close()
except OSError:
pass
raise NumatoGpioError("Serial communication failure") from err

def _read_expected_string(self, expected: str) -> None:
Expand Down Expand Up @@ -526,7 +533,6 @@ def _poll(self): # noqa: C901
"""
try:
while self._ser and self._ser.is_open:

if not (b := self._serial_read(1).decode()):
continue

Expand All @@ -540,7 +546,11 @@ def _poll(self): # noqa: C901
self._read_notification()

except (TypeError, serial.serialutil.SerialException):
self._ser.close() # ends the polling loop and its thread
# ends the polling loop and its thread
try:
self._ser.close()
except OSError:
pass

def _check_port_range(self, port):
if port not in range(self.ports):
Expand Down

0 comments on commit 670edff

Please sign in to comment.