@@ -38,14 +38,23 @@ def setup(self):
3838
3939 def close (self , exc = None ):
4040 """Close the transport gracefully."""
41+ if not self .sync_serial :
42+ return
43+ with contextlib .suppress (Exception ):
44+ self .sync_serial .flush ()
45+
4146 if self ._has_reader :
4247 if os .name == "nt" :
4348 self ._has_reader .cancel ()
4449 else :
4550 self .async_loop .remove_reader (self .sync_serial .fileno ())
4651 self ._has_reader = False
4752 self ._remove_writer ()
48- self .async_loop .call_soon (self ._call_connection_lost , exc )
53+ self .sync_serial .close ()
54+ self .sync_serial = None
55+ with contextlib .suppress (Exception ):
56+ self ._protocol .connection_lost (exc )
57+ self ._write_buffer .clear ()
4958
5059 def write (self , data ):
5160 """Write some data to the transport."""
@@ -121,7 +130,7 @@ def _read_ready(self):
121130 try :
122131 data = self .sync_serial .read (1024 )
123132 except serial .SerialException as exc :
124- self .close (exc )
133+ self .close (exc = exc )
125134 else :
126135 if data :
127136 self ._protocol .data_received (data )
@@ -138,7 +147,7 @@ def _write_ready(self):
138147 except (BlockingIOError , InterruptedError ):
139148 return
140149 except serial .SerialException as exc :
141- self .close (exc )
150+ self .close (exc = exc )
142151
143152 if os .name == "nt" :
144153
@@ -151,8 +160,7 @@ def _poll_read(self):
151160 if self .sync_serial .in_waiting :
152161 self ._read_ready ()
153162 except serial .SerialException as exc :
154- self .async_loop .call_soon (self ._call_connection_lost , exc )
155- self .abort ()
163+ self .close (exc = exc )
156164
157165 def _poll_write (self ):
158166 if self ._has_writer :
@@ -173,21 +181,6 @@ def _remove_writer(self):
173181 self .async_loop .remove_writer (self .sync_serial .fileno ())
174182 self ._has_writer = False
175183
176- def _call_connection_lost (self , exc ):
177- """Close the connection."""
178- if self .sync_serial :
179- with contextlib .suppress (Exception ):
180- self .sync_serial .flush ()
181-
182- self .sync_serial .close ()
183- self .sync_serial = None
184- if self ._protocol :
185- with contextlib .suppress (Exception ):
186- self ._protocol .connection_lost (exc )
187-
188- self ._write_buffer .clear ()
189- self ._write_buffer .clear ()
190-
191184
192185async def create_serial_connection (loop , protocol_factory , * args , ** kwargs ):
193186 """Create a connection to a new serial port instance."""
0 commit comments