Skip to content

Commit cf256c6

Browse files
andrewleechrob-smallshire
authored andcommitted
Windows: handle serial errors when the device is removed (#38)
* Windows: detect serial port error in _poll_read() On windows, _poll_read() is typically the first function to throw an exception when the serial port disappears. The exception is currently lost on the event loop, this catches it and escalates to a fatal_error * Windows: when closing, ignore errors in flush
1 parent df2e42f commit cf256c6

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

serial_asyncio/__init__.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -275,9 +275,12 @@ def _write_ready(self):
275275
if os.name == "nt":
276276
def _poll_read(self):
277277
if self._has_reader:
278-
if self.serial.in_waiting:
279-
self._loop.call_soon(self._read_ready)
280-
self._loop.call_later(self._poll_wait_time, self._poll_read)
278+
try:
279+
if self.serial.in_waiting:
280+
self._loop.call_soon(self._read_ready)
281+
self._loop.call_later(self._poll_wait_time, self._poll_read)
282+
except serial.SerialException as exc:
283+
self._fatal_error(exc, 'Fatal write error on serial transport')
281284

282285
def _ensure_reader(self):
283286
if (not self._has_reader) and (not self._closing):
@@ -389,15 +392,12 @@ def _call_connection_lost(self, exc):
389392
assert self._closing
390393
assert not self._has_writer
391394
assert not self._has_reader
392-
if os.name == "nt":
395+
try:
393396
self._serial.flush()
394-
else:
395-
try:
396-
self._serial.flush()
397-
except termios.error:
398-
# ignore termios errors which may happen if the serial device was
399-
# hot-unplugged.
400-
pass
397+
except (serial.SerialException if os.name == "nt" else termios.error):
398+
# ignore serial errors which may happen if the serial device was
399+
# hot-unplugged.
400+
pass
401401
try:
402402
self._protocol.connection_lost(exc)
403403
finally:

0 commit comments

Comments
 (0)