Put the connecting task in aioclient

This commit is contained in:
atse 2023-07-14 15:49:17 +08:00 committed by Tse Kwok Yan
parent 4f246780b4
commit 2a8d240986
2 changed files with 12 additions and 11 deletions

View File

@ -9,13 +9,21 @@ class Client:
def __init__(self):
self._reader = None
self._writer = None
self._connecting_task = None
self._command_lock = asyncio.Lock()
async def connect(self, host='192.168.1.26', port=23, timeout=None):
self._reader, self._writer = await asyncio.open_connection(host, port)
self._connecting_task = asyncio.create_task(asyncio.open_connection(host, port))
self._reader, self._writer = await self._connecting_task
self._connecting_task = None
await self._check_zero_limits()
async def disconnect(self):
if self._connecting_task is not None:
self._connecting_task.cancel()
return
self._writer.close()
await self._writer.wait_closed()

View File

@ -163,13 +163,11 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.connect_btn.setText("Stop")
self.tec_client = Client()
self.connect_task = asyncio.create_task(self.tec_client.connect(host=ip, port=port, timeout=30))
try:
await self.connect_task
except asyncio.exceptions.CancelledError:
await self.tec_client.connect(host=ip, port=port, timeout=30)
except asyncio.CancelledError:
return
self.connect_btn.setEnabled(True)
self._on_connection_changed(True)
self._status(await self.tec_client.hw_rev())
self.fan_update(await self.tec_client.fan())
@ -181,12 +179,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
)
self.client_watcher.start_watching()
else:
if self.client_watcher is None:
self.connect_task.cancel()
self.tec_client = None
self.on_connection_changed(False)
return
else:
if self.client_watcher is not None:
self.client_watcher.stop_watching()
self.client_watcher = None