Rearrange client_watcher to hold its own task

This commit is contained in:
atse 2023-07-06 11:21:56 +08:00
parent 608573c03c
commit d0d33f42da
1 changed files with 8 additions and 6 deletions

View File

@ -38,6 +38,7 @@ class ClientWatcher(QObject):
self.update_s = update_s self.update_s = update_s
self.running = True self.running = True
self.client = client self.client = client
self.watch_task = None
super().__init__(parent) super().__init__(parent)
async def run(self): async def run(self):
@ -50,6 +51,9 @@ class ClientWatcher(QObject):
async def update_params(self): async def update_params(self):
self.fan_update.emit(await self.client.fan()) self.fan_update.emit(await self.client.fan())
def start_watching(self):
self.watch_task = asyncio.create_task(self.run())
@pyqtSlot() @pyqtSlot()
def stop_watching(self): def stop_watching(self):
self.running = False self.running = False
@ -71,7 +75,6 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.tec_client: Client = None self.tec_client: Client = None
self.client_watcher: ClientWatcher = None self.client_watcher: ClientWatcher = None
self.client_watcher_task = None
if args.connect: if args.connect:
if args.IP: if args.IP:
@ -149,16 +152,15 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
lambda: self.client_watcher.set_update_s(self.report_refresh_spin.value()) lambda: self.client_watcher.set_update_s(self.report_refresh_spin.value())
) )
QtWidgets.QApplication.instance().aboutToQuit.connect(self.client_watcher.stop_watching) QtWidgets.QApplication.instance().aboutToQuit.connect(self.client_watcher.stop_watching)
self.client_watcher_task = asyncio.create_task(self.client_watcher.run()) self.client_watcher.start_watching()
else: else:
self.client_watcher.stop_watching()
self.client_watcher = None
await self.tec_client.disconnect() await self.tec_client.disconnect()
self.tec_client = None self.tec_client = None
self._on_connection_changed(False) self._on_connection_changed(False)
self.client_watcher.stop_watching()
self.client_watcher = None
await self.client_watcher_task
self.client_watcher_task = None
except Exception as e: except Exception as e:
logging.error(f"Failed communicating to the {ip}:{port}: {e}") logging.error(f"Failed communicating to the {ip}:{port}: {e}")
self._on_connection_changed(False) self._on_connection_changed(False)