Proper timeout implementation

This commit is contained in:
atse 2023-08-08 16:23:07 +08:00
parent e82437ca9f
commit 3e20658107
1 changed files with 3 additions and 1 deletions

View File

@ -15,6 +15,7 @@ class Client:
self._connecting_task = None self._connecting_task = None
self._command_lock = asyncio.Lock() self._command_lock = asyncio.Lock()
self._report_mode_on = False self._report_mode_on = False
self.timeout = None
async def connect(self, host='192.168.1.26', port=23, timeout=None): async def connect(self, host='192.168.1.26', port=23, timeout=None):
"""Connect to the Thermostat with host and port. """Connect to the Thermostat with host and port.
@ -31,6 +32,7 @@ class Client:
self._connecting_task = asyncio.create_task( self._connecting_task = asyncio.create_task(
asyncio.wait_for(asyncio.open_connection(host, port), timeout) asyncio.wait_for(asyncio.open_connection(host, port), timeout)
) )
self.timeout = timeout
try: try:
self._reader, self._writer = await self._connecting_task self._reader, self._writer = await self._connecting_task
except asyncio.CancelledError: except asyncio.CancelledError:
@ -71,7 +73,7 @@ class Client:
async def _read_line(self): async def _read_line(self):
# read 1 line # read 1 line
chunk = await self._reader.readline() chunk = await asyncio.wait_for(self._reader.readline(), self.timeout) # Only wait for response until timeout
return chunk.decode('utf-8', errors='ignore') return chunk.decode('utf-8', errors='ignore')
async def _read_write(self, command): async def _read_write(self, command):