@@ -156,25 +156,28 @@ def connect(self) -> None:
156156
157157 def disconnect (self ) -> None :
158158 """Close the WebSocket connection."""
159- if self ._ws :
159+ ws = self ._ws
160+ self ._ws = None
161+ if ws :
160162 try :
161- self . _ws .close ()
163+ ws .close ()
162164 except Exception :
163165 pass
164- self ._ws = None
165166
166167 @property
167168 def connected (self ) -> bool :
168169 """True if the WebSocket is currently connected."""
169- return self ._ws is not None and self ._ws .connected
170+ ws = self ._ws
171+ return ws is not None and ws .connected
170172
171173 # ------------------------------------------------------------------
172174 # I/O
173175
174176 def send (self , data : bytes ) -> None :
175177 """Send raw bytes (keystrokes) to the device shell."""
176- if self ._ws and self ._ws .connected :
177- self ._ws .send_binary (data )
178+ ws = self ._ws
179+ if ws and ws .connected :
180+ ws .send_binary (data )
178181
179182 def send_text (self , text : str ) -> None :
180183 """Send a text string as binary data to the device shell."""
@@ -187,12 +190,13 @@ def recv(self, timeout: float = 0.1) -> bytes | None:
187190 Returns None if no data is available within the timeout, or if
188191 the connection is closed.
189192 """
190- if not self ._ws or not self ._ws .connected :
193+ ws = self ._ws
194+ if not ws or not ws .connected :
191195 return None
192- old_timeout = self . _ws .gettimeout ()
196+ old_timeout = ws .gettimeout ()
193197 try :
194- self . _ws .settimeout (timeout )
195- data = self . _ws .recv ()
198+ ws .settimeout (timeout )
199+ data = ws .recv ()
196200 if isinstance (data , str ):
197201 return data .encode ("utf-8" )
198202 return data
@@ -204,14 +208,15 @@ def recv(self, timeout: float = 0.1) -> bytes | None:
204208 ):
205209 return None
206210 finally :
207- self . _ws .settimeout (old_timeout )
211+ ws .settimeout (old_timeout )
208212
209213 def resize (self , rows : int , cols : int ) -> None :
210214 """Send a terminal resize message to the device."""
211215 self ._rows = rows
212216 self ._cols = cols
213- if self ._ws and self ._ws .connected :
214- self ._ws .send (json .dumps ({"resize" : {"width" : cols , "height" : rows }}))
217+ ws = self ._ws
218+ if ws and ws .connected :
219+ ws .send (json .dumps ({"resize" : {"width" : cols , "height" : rows }}))
215220
216221 # ------------------------------------------------------------------
217222 # Context manager
0 commit comments