44import logging
55import socket
66from asyncio import Lock
7- from typing import Callable , Coroutine
7+ from typing import Callable , Coroutine , Any
88
99import async_timeout
1010
@@ -37,6 +37,9 @@ async def async_connect(self):
3737 for listener in self .device_listener .values ()
3838 ])
3939
40+ async def async_disconnect (self ) -> Any :
41+ await asyncio .gather (* [listener .disconnect () for listener in self .device_listener .values ()])
42+
4043 async def send_command (
4144 self , device_id : str , method : RoborockCommand , params : list = None
4245 ):
@@ -87,17 +90,23 @@ async def _main_coro(self):
8790 except Exception as e :
8891 _LOGGER .exception (e )
8992 except BrokenPipeError :
90- self .socket . close ()
93+ await self .disconnect ()
9194
9295 async def connect (self ):
9396 async with self ._mutex :
9497 if not self .is_connected or self .socket .is_closed :
98+ self .socket = RoborockSocket (socket .AF_INET , socket .SOCK_STREAM )
99+ self .socket .setblocking (False )
95100 async with async_timeout .timeout (self .timeout ):
96101 _LOGGER .info (f"Connecting to { self .ip } " )
97102 await self .loop .sock_connect (self .socket , (self .ip , 58867 ))
98103 self .is_connected = True
99104 self .loop .create_task (self ._main_coro ())
100105
106+ async def disconnect (self ):
107+ self .socket .close ()
108+ self .is_connected = False
109+
101110 async def send_message (self , data : bytes ):
102111 response = {}
103112 await self .connect ()
@@ -110,5 +119,5 @@ async def send_message(self, data: bytes):
110119 f"Timeout after { self .timeout } seconds waiting for response"
111120 ) from None
112121 except BrokenPipeError :
113- self .socket . close ()
122+ await self .disconnect ()
114123 return response
0 commit comments