forked from M-Labs/thermostat
More elegant connection stopping
This commit is contained in:
parent
d52aafd7f6
commit
b32062d855
@ -5,6 +5,9 @@ import logging
|
||||
class CommandError(Exception):
|
||||
pass
|
||||
|
||||
class StoppedConnecting(Exception):
|
||||
pass
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
self._reader = None
|
||||
@ -14,25 +17,28 @@ class Client:
|
||||
self._report_mode_on = False
|
||||
|
||||
async def connect(self, host='192.168.1.26', port=23, timeout=None):
|
||||
"""Connect to the TEC with host and port, throws TimeoutError if
|
||||
unable to connect. Returns True if not cancelled with disconnect.
|
||||
"""Connect to the Thermostat with host and port.
|
||||
Throws StoppedConnecting if disconnect was called while connecting.
|
||||
Throws asyncio.TimeoutError if timeout was exceeded.
|
||||
|
||||
Example::
|
||||
client = aioclient.Client()
|
||||
connected = await client.connect()
|
||||
if connected:
|
||||
return
|
||||
client = Client()
|
||||
try:
|
||||
await client.connect()
|
||||
except StoppedConnecting:
|
||||
print("Stopped connecting")
|
||||
"""
|
||||
self._connecting_task = asyncio.create_task(asyncio.wait_for(asyncio.open_connection(host, port), timeout))
|
||||
self._connecting_task = asyncio.create_task(
|
||||
asyncio.wait_for(asyncio.open_connection(host, port), timeout)
|
||||
)
|
||||
try:
|
||||
self._reader, self._writer = await self._connecting_task
|
||||
except asyncio.CancelledError:
|
||||
return False
|
||||
raise StoppedConnecting
|
||||
finally:
|
||||
self._connecting_task = None
|
||||
|
||||
await self._check_zero_limits()
|
||||
return True
|
||||
|
||||
def is_connecting(self):
|
||||
"""Returns True if client is connecting"""
|
||||
|
@ -11,7 +11,7 @@ import sys
|
||||
import argparse
|
||||
import logging
|
||||
import asyncio
|
||||
from pytec.aioclient import Client
|
||||
from pytec.aioclient import Client, StoppedConnecting
|
||||
import qasync
|
||||
from qasync import asyncSlot, asyncClose
|
||||
|
||||
@ -483,15 +483,16 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
|
||||
self.ip_set_line.setEnabled(False)
|
||||
self.port_set_spin.setEnabled(False)
|
||||
|
||||
connected = await self.tec_client.connect(host=ip, port=port, timeout=30)
|
||||
if not connected:
|
||||
try:
|
||||
await self.tec_client.connect(host=ip, port=port, timeout=30)
|
||||
except StoppedConnecting:
|
||||
return
|
||||
await self._on_connection_changed(True)
|
||||
else:
|
||||
await self._on_connection_changed(False)
|
||||
await self.tec_client.disconnect()
|
||||
|
||||
except (OSError, TimeoutError) as e:
|
||||
except (OSError, TimeoutError, asyncio.TimeoutError) as e: # TODO: Remove asyncio.TimeoutError in Python 3.11
|
||||
logging.error(f"Failed communicating to {ip}:{port}: {e}")
|
||||
await self._on_connection_changed(False)
|
||||
await self.tec_client.disconnect()
|
||||
|
Loading…
Reference in New Issue
Block a user