From 2eb4ea203450a9cb504ee287f1698f66f53e1a1f Mon Sep 17 00:00:00 2001 From: Mark Parker Date: Sat, 16 Dec 2023 01:13:50 +0000 Subject: [PATCH] revert to aiohttp and resolve errors --- aioWiserHeatAPI/rest_controller.py | 76 +++++++++++++++--------------- aioWiserHeatAPI/wiserhub.py | 27 +++++++---- setup.py | 13 +++-- 3 files changed, 62 insertions(+), 54 deletions(-) diff --git a/aioWiserHeatAPI/rest_controller.py b/aioWiserHeatAPI/rest_controller.py index 22071ef..a7449a8 100644 --- a/aioWiserHeatAPI/rest_controller.py +++ b/aioWiserHeatAPI/rest_controller.py @@ -1,12 +1,10 @@ import asyncio import enum import json -import re from dataclasses import dataclass -from typing import Any, Optional, cast +from typing import Optional import aiohttp -import httpx from aioWiserHeatAPI.helpers.extra_config import _WiserExtraConfig @@ -57,14 +55,12 @@ class _WiserRestController(object): def __init__( self, - session: Optional[aiohttp.ClientSession] = None, timeout: Optional[float] = REST_TIMEOUT, wiser_connection_info: Optional[_WiserConnectionInfo] = None, ): self._wiser_connection_info = wiser_connection_info self._api_parameters = WiserAPIParams() - - self._timeout = timeout # aiohttp.ClientTimeout(total=timeout) + self._timeout = aiohttp.ClientTimeout(total=timeout) self._hub_name = None self._extra_config_file = None self._extra_config: _WiserExtraConfig = None @@ -88,12 +84,11 @@ async def _do_hub_action( self._wiser_connection_info.port, ) - kwargs = { - "headers": { - "SECRET": self._wiser_connection_info.secret, - "Content-Type": "application/json;charset=UTF-8", - "Connection": "close", - } + kwargs = {} + + kwargs["headers"] = { + "SECRET": self._wiser_connection_info.secret, + "Content-Type": "application/json;charset=UTF-8", } if data is not None: @@ -103,35 +98,40 @@ async def _do_hub_action( kwargs["timeout"] = self._timeout try: - async with httpx.AsyncClient() as client: - response = await getattr(client, action.value)( + async with aiohttp.ClientSession( + version=aiohttp.HttpVersion10, + ) as session: + async with getattr(session, action.value)( url, **kwargs, - ) - - if response.status_code >= 400: - self._process_nok_response( - response, url, data, raise_for_endpoint_error - ) - else: - content = await response.aread() - if len(content) > 0: - response = content.decode("utf-8", "ignore").encode( - "utf-8" + ) as response: + if not response.ok: + self._process_nok_response( + response, url, data, raise_for_endpoint_error ) - return json.loads(response) else: - return {} - return {} + content = await response.read() + if len(content) > 0: + response = content.decode( + "utf-8", "ignore" + ).encode("utf-8") + return json.loads(response) + else: + return {} + return {} - except httpx.TimeoutException as ex: + except asyncio.TimeoutError as ex: raise WiserHubConnectionError( - f"Connection timeout trying to communicate with Wiser Hub {self._wiser_connection_info.host} for url {url}. Error is {ex}" - ) from ex - except httpx.NetworkError as ex: + f"Connection timeout trying to communicate with Wiser Hub {self._wiser_connection_info.host} for url {url}" + ) + except aiohttp.ClientResponseError as ex: + raise WiserHubConnectionError( + f"Response error trying to communicate with Wiser Hub {self._wiser_connection_info.host} for url {url}. Error is {ex}" + ) + except aiohttp.ClientConnectorError as ex: raise WiserHubConnectionError( - f"Connection error trying to communicate with Wiser Hub {self._wiser_connection_info.host} for url {url}. Error is {ex}" - ) from ex + f"Connection error trying to communicate with Wiser Hub {self._wiser_connection_info.host} for url {url}. Error is {ex}" + ) def _process_nok_response( self, @@ -140,21 +140,21 @@ def _process_nok_response( data: dict, raise_for_endpoint_error: bool = True, ): - if response.status_code == 401: + if response.status == 401: raise WiserHubAuthenticationError( f"Error authenticating to Wiser Hub {self._wiser_connection_info.host}. Check your secret key" ) - elif response.status_code == 404 and raise_for_endpoint_error: + elif response.status == 404 and raise_for_endpoint_error: raise WiserHubRESTError( f"Rest endpoint not found on Wiser Hub {self._wiser_connection_info.host} for url {url}" ) - elif response.status_code == 408: + elif response.status == 408: raise WiserHubConnectionError( f"Connection timed out trying to communicate with Wiser Hub {self._wiser_connection_info.host} for url {url}" ) elif raise_for_endpoint_error: raise WiserHubRESTError( - f"Unknown error communicating with Wiser Hub {self._wiser_connection_info.host} for url {url} with data {data}. Error code is: {response.status_code}" + f"Unknown error communicating with Wiser Hub {self._wiser_connection_info.host} for url {url} with data {data}. Error code is: {response.status}" ) async def _get_hub_data( diff --git a/aioWiserHeatAPI/wiserhub.py b/aioWiserHeatAPI/wiserhub.py index d6efaad..68a5fa0 100644 --- a/aioWiserHeatAPI/wiserhub.py +++ b/aioWiserHeatAPI/wiserhub.py @@ -115,7 +115,7 @@ def __init__( ): # Create an instance of the rest controller self._wiser_rest_controller = _WiserRestController( - self._session, wiser_connection_info=self._wiser_api_connection + wiser_connection_info=self._wiser_api_connection ) else: raise WiserHubConnectionError( @@ -147,8 +147,8 @@ async def _build_objects(self): WISERHUBSCHEDULES ) try: - self._status_data = await self._wiser_rest_controller._get_hub_data( - WISERHUBSTATUS + self._status_data = ( + await self._wiser_rest_controller._get_hub_data(WISERHUBSTATUS) ) except WiserHubRESTError: self._status_data = {} @@ -161,16 +161,22 @@ async def _build_objects(self): ) # load extra data - self._wiser_rest_controller._extra_config_file = self._extra_config_file + self._wiser_rest_controller._extra_config_file = ( + self._extra_config_file + ) await self._wiser_rest_controller._get_extra_config_data() # Only get opentherm data if connected if ( - self._domain_data.get("System", {}).get("OpenThermConnectionStatus", "") + self._domain_data.get("System", {}).get( + "OpenThermConnectionStatus", "" + ) == "Connected" ): - self._opentherm_data = await self._wiser_rest_controller._get_hub_data( - WISERHUBOPENTHERM, False + self._opentherm_data = ( + await self._wiser_rest_controller._get_hub_data( + WISERHUBOPENTHERM, False + ) ) if self._domain_data != {} and self._network_data != {}: @@ -228,7 +234,8 @@ async def _build_objects(self): # Moments if self._domain_data.get("Moment"): self._moments = _WiserMomentCollection( - self._wiser_rest_controller, self._domain_data.get("Moment") + self._wiser_rest_controller, + self._domain_data.get("Moment"), ) # If gets here with no exceptions then success and return true @@ -326,7 +333,9 @@ def output_raw_hub_data( try: if data: # Write out to file - log_response_to_file(data, filename, False, pathlib.Path(file_path)) + log_response_to_file( + data, filename, False, pathlib.Path(file_path) + ) return True except Exception as ex: _LOGGER.error(ex) diff --git a/setup.py b/setup.py index 7a098cd..e45210a 100755 --- a/setup.py +++ b/setup.py @@ -35,18 +35,17 @@ def get_version(rel_path): classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", - "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ - "zeroconf>=0.47.1", - "aiohttp>=3.8.1", - "aiofiles>=0.8.0", - "pyyaml>=6.0", - "httpx>=0.25.0", + "zeroconf>=0.127.0", + "aiohttp>=3.9.1", + "aiofiles>=23.2.1", + "pyyaml>=6.0.1", ], - python_requires=">=3.10", + python_requires=">=3.11", entry_points={ "console_scripts": ["wiser = aioWiserHeatAPI.cli:main"], },