4
4
import logging
5
5
import socket
6
6
from asyncio import Lock
7
- from typing import Callable , Coroutine
7
+ from typing import Callable , Coroutine , Any
8
8
9
9
import async_timeout
10
10
@@ -37,6 +37,9 @@ async def async_connect(self):
37
37
for listener in self .device_listener .values ()
38
38
])
39
39
40
+ async def async_disconnect (self ) -> Any :
41
+ await asyncio .gather (* [listener .disconnect () for listener in self .device_listener .values ()])
42
+
40
43
async def send_command (
41
44
self , device_id : str , method : RoborockCommand , params : list = None
42
45
):
@@ -87,17 +90,23 @@ async def _main_coro(self):
87
90
except Exception as e :
88
91
_LOGGER .exception (e )
89
92
except BrokenPipeError :
90
- self .socket . close ()
93
+ await self .disconnect ()
91
94
92
95
async def connect (self ):
93
96
async with self ._mutex :
94
97
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 )
95
100
async with async_timeout .timeout (self .timeout ):
96
101
_LOGGER .info (f"Connecting to { self .ip } " )
97
102
await self .loop .sock_connect (self .socket , (self .ip , 58867 ))
98
103
self .is_connected = True
99
104
self .loop .create_task (self ._main_coro ())
100
105
106
+ async def disconnect (self ):
107
+ self .socket .close ()
108
+ self .is_connected = False
109
+
101
110
async def send_message (self , data : bytes ):
102
111
response = {}
103
112
await self .connect ()
@@ -110,5 +119,5 @@ async def send_message(self, data: bytes):
110
119
f"Timeout after { self .timeout } seconds waiting for response"
111
120
) from None
112
121
except BrokenPipeError :
113
- self .socket . close ()
122
+ await self .disconnect ()
114
123
return response
0 commit comments