Skip to content

Commit

Permalink
revert to aiohttp and resolve errors
Browse files Browse the repository at this point in the history
  • Loading branch information
msp1974 committed Dec 16, 2023
1 parent 8b4590f commit 2eb4ea2
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 54 deletions.
76 changes: 38 additions & 38 deletions aioWiserHeatAPI/rest_controller.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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,
Expand All @@ -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(
Expand Down
27 changes: 18 additions & 9 deletions aioWiserHeatAPI/wiserhub.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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 = {}
Expand All @@ -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 != {}:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 6 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
},
Expand Down

0 comments on commit 2eb4ea2

Please sign in to comment.