python-homewizard-energy 10.3.0__tar.gz → 10.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/PKG-INFO +1 -1
- python_homewizard_energy-10.4.0/homewizard_energy/__init__.py +143 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/const.py +16 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v1/__init__.py +17 -1
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/__init__.py +48 -26
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/pyproject.toml +1 -1
- python_homewizard_energy-10.3.0/homewizard_energy/__init__.py +0 -39
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/LICENSE +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/README.md +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/errors.py +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/homewizard_energy.py +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/models.py +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/py.typed +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/utils.py +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v1/const.py +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/cacert.py +0 -0
- {python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/const.py +0 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""HomeWizard Energy API library."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from contextlib import suppress
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from aiohttp import ClientSession
|
|
8
|
+
|
|
9
|
+
from .const import MODEL_TO_ID, SUPPORTED_V2_MODELS
|
|
10
|
+
from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError
|
|
11
|
+
from .homewizard_energy import HomeWizardEnergy
|
|
12
|
+
from .v1 import HomeWizardEnergyV1
|
|
13
|
+
from .v2 import HomeWizardEnergyV2, create_ssl_context
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DisabledError",
|
|
17
|
+
"HomeWizardEnergy",
|
|
18
|
+
"HomeWizardEnergyV1",
|
|
19
|
+
"HomeWizardEnergyV2",
|
|
20
|
+
"InvalidStateError",
|
|
21
|
+
"RequestError",
|
|
22
|
+
"UnsupportedError",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
# Product type identifiers as used in the device certificate,
|
|
26
|
+
# for the models that are supported via the v2 API
|
|
27
|
+
SUPPORTED_V2_CERTIFICATE_IDS = frozenset(
|
|
28
|
+
MODEL_TO_ID[model] for model in SUPPORTED_V2_MODELS
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# Development units have a certificate without product type,
|
|
32
|
+
# formatted as `appliance/generic/<serial>`
|
|
33
|
+
GENERIC_CERTIFICATE_ID = "generic"
|
|
34
|
+
|
|
35
|
+
# Timeout in seconds for connecting to the device and for its response
|
|
36
|
+
TIMEOUT = 5
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _get_certificate_product_id(certificate: dict[str, Any] | None) -> str | None:
|
|
40
|
+
"""Get the product type identifier from a device certificate.
|
|
41
|
+
|
|
42
|
+
The common name of the certificate is formatted as
|
|
43
|
+
`appliance/<product type identifier>/<serial>`, see `MODEL_TO_ID`.
|
|
44
|
+
"""
|
|
45
|
+
for rdn in (certificate or {}).get("subject", ()):
|
|
46
|
+
for key, value in rdn:
|
|
47
|
+
if key != "commonName":
|
|
48
|
+
continue
|
|
49
|
+
parts = value.split("/")
|
|
50
|
+
if len(parts) == 3 and parts[0] == "appliance":
|
|
51
|
+
return parts[1]
|
|
52
|
+
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def _get_v2_product_id(host: str) -> str | None:
|
|
57
|
+
"""Get the product type identifier of a device that serves the v2 API.
|
|
58
|
+
|
|
59
|
+
Only devices with the v2 API serve HTTPS with a valid device certificate,
|
|
60
|
+
which contains the product type identifier. Some firmware serves this
|
|
61
|
+
certificate without the v2 API, so also check that the API responds to a
|
|
62
|
+
request without a token with 401 Unauthorized.
|
|
63
|
+
|
|
64
|
+
This works without authorization, and needs only a single connection,
|
|
65
|
+
as devices have very few connection slots.
|
|
66
|
+
"""
|
|
67
|
+
loop = asyncio.get_running_loop()
|
|
68
|
+
# Creating an SSL context has some blocking IO so need to run it in the executor
|
|
69
|
+
context = await loop.run_in_executor(None, create_ssl_context, False)
|
|
70
|
+
|
|
71
|
+
reader, writer = await asyncio.wait_for(
|
|
72
|
+
asyncio.open_connection(host, 443, ssl=context), timeout=TIMEOUT
|
|
73
|
+
)
|
|
74
|
+
try:
|
|
75
|
+
product_id = _get_certificate_product_id(writer.get_extra_info("peercert"))
|
|
76
|
+
if product_id is None:
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
host_header = f"[{host}]" if ":" in host else host
|
|
80
|
+
request = (
|
|
81
|
+
f"GET /api HTTP/1.1\r\nHost: {host_header}\r\nConnection: close\r\n\r\n"
|
|
82
|
+
)
|
|
83
|
+
writer.write(request.encode())
|
|
84
|
+
await writer.drain()
|
|
85
|
+
status_line = await asyncio.wait_for(reader.readline(), timeout=TIMEOUT)
|
|
86
|
+
finally:
|
|
87
|
+
writer.close()
|
|
88
|
+
# Closing raises an SSL error when the rest of the response is not read yet
|
|
89
|
+
with suppress(OSError):
|
|
90
|
+
await asyncio.wait_for(writer.wait_closed(), timeout=TIMEOUT)
|
|
91
|
+
|
|
92
|
+
# Status line is formatted as `HTTP/1.1 401 Unauthorized`
|
|
93
|
+
parts = status_line.split()
|
|
94
|
+
if len(parts) < 2 or parts[1] != b"401":
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
return product_id
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
async def has_v2_api(
|
|
101
|
+
host: str,
|
|
102
|
+
websession: ClientSession | None = None,
|
|
103
|
+
product_type: str | None = None,
|
|
104
|
+
) -> bool:
|
|
105
|
+
"""Check if the device has support for the v2 api.
|
|
106
|
+
|
|
107
|
+
Only returns True for models that are supported via the v2 API by this
|
|
108
|
+
version of the library (see `SUPPORTED_V2_MODELS`), so devices that enable
|
|
109
|
+
the v2 API before it is officially supported keep using the v1 API.
|
|
110
|
+
|
|
111
|
+
The product type is read from the device certificate, and the device must
|
|
112
|
+
respond to a request without a token with 401 Unauthorized. Pass `product_type`
|
|
113
|
+
when it is already known (e.g. from discovery or an existing configuration):
|
|
114
|
+
unsupported models then return False without connecting to the device, and
|
|
115
|
+
a device of another product type at this host returns False as well.
|
|
116
|
+
Development units have a generic certificate without product type; those
|
|
117
|
+
are reported as v2 capable when they serve the v2 API and `product_type`,
|
|
118
|
+
when passed, is supported.
|
|
119
|
+
|
|
120
|
+
`websession` is no longer used and only kept for backwards compatibility.
|
|
121
|
+
"""
|
|
122
|
+
del websession # Kept for backwards compatibility
|
|
123
|
+
|
|
124
|
+
if product_type is not None and product_type not in SUPPORTED_V2_MODELS:
|
|
125
|
+
return False
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
product_id = await _get_v2_product_id(host)
|
|
129
|
+
except OSError:
|
|
130
|
+
# Includes SSL errors and timeouts. No (valid) HTTPS connection means
|
|
131
|
+
# the device is not v2 or not reachable at this time
|
|
132
|
+
return False
|
|
133
|
+
|
|
134
|
+
if product_id == GENERIC_CERTIFICATE_ID:
|
|
135
|
+
# The certificate of a development unit doesn't tell the product type,
|
|
136
|
+
# so rely on the `product_type` that passed the check above, or on the
|
|
137
|
+
# API response
|
|
138
|
+
return True
|
|
139
|
+
|
|
140
|
+
if product_type is not None:
|
|
141
|
+
return product_id == MODEL_TO_ID[product_type]
|
|
142
|
+
|
|
143
|
+
return product_id in SUPPORTED_V2_CERTIFICATE_IDS
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/const.py
RENAMED
|
@@ -32,6 +32,22 @@ MODEL_TO_ID = {
|
|
|
32
32
|
Model.BATTERY: "battery",
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
# Models that are supported via the v2 API by this version of the library.
|
|
36
|
+
# Keep in sync with https://api-documentation.homewizard.com/docs/introduction#devices
|
|
37
|
+
# Devices of other models may enable the v2 API (e.g. with beta firmware), but are
|
|
38
|
+
# not reported as v2 capable by `has_v2_api` until they are added here.
|
|
39
|
+
SUPPORTED_V2_MODELS = frozenset(
|
|
40
|
+
{
|
|
41
|
+
Model.P1_METER,
|
|
42
|
+
Model.ENERGY_SOCKET,
|
|
43
|
+
Model.ENERGY_METER_1_PHASE,
|
|
44
|
+
Model.ENERGY_METER_3_PHASE,
|
|
45
|
+
Model.ENERGY_METER_EASTRON_SDM230,
|
|
46
|
+
Model.ENERGY_METER_EASTRON_SDM630,
|
|
47
|
+
Model.BATTERY,
|
|
48
|
+
}
|
|
49
|
+
)
|
|
50
|
+
|
|
35
51
|
MODEL_TO_NAME = {
|
|
36
52
|
Model.P1_METER: "P1 Meter",
|
|
37
53
|
Model.ENERGY_SOCKET: "Energy Socket",
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v1/__init__.py
RENAMED
|
@@ -162,7 +162,20 @@ class HomeWizardEnergyV1(HomeWizardEnergy):
|
|
|
162
162
|
async def _request(
|
|
163
163
|
self, path: str, method: str = METH_GET, data: object = None
|
|
164
164
|
) -> tuple[HTTPStatus, dict[str, Any] | None]:
|
|
165
|
-
"""Make a request to the API.
|
|
165
|
+
"""Make a request to the API, one request at a time.
|
|
166
|
+
|
|
167
|
+
Devices have very few connection slots, so requests are serialized to
|
|
168
|
+
keep at most one connection open. The lock is taken per attempt, so it
|
|
169
|
+
is released during backoff sleeps, and it is taken before the timeout
|
|
170
|
+
starts, so time spent waiting for the lock does not count towards it.
|
|
171
|
+
"""
|
|
172
|
+
async with self._lock:
|
|
173
|
+
return await self._request_unlocked(path, method, data)
|
|
174
|
+
|
|
175
|
+
async def _request_unlocked(
|
|
176
|
+
self, path: str, method: str = METH_GET, data: object = None
|
|
177
|
+
) -> tuple[HTTPStatus, dict[str, Any] | None]:
|
|
178
|
+
"""Make a request to the API. Must be called while holding the lock."""
|
|
166
179
|
|
|
167
180
|
if self._session is None:
|
|
168
181
|
await self._create_clientsession()
|
|
@@ -181,6 +194,9 @@ class HomeWizardEnergyV1(HomeWizardEnergy):
|
|
|
181
194
|
json=data,
|
|
182
195
|
headers=headers,
|
|
183
196
|
)
|
|
197
|
+
# Read the full body while holding the lock, so the connection
|
|
198
|
+
# is back in the pool before the next request starts.
|
|
199
|
+
await resp.read()
|
|
184
200
|
LOGGER.debug("%s, %s", resp.status, await resp.text("utf-8"))
|
|
185
201
|
except TimeoutError as exception:
|
|
186
202
|
raise RequestError(
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/__init__.py
RENAMED
|
@@ -39,6 +39,23 @@ from .cacert import CACERT
|
|
|
39
39
|
T = TypeVar("T")
|
|
40
40
|
|
|
41
41
|
|
|
42
|
+
def create_ssl_context(validate_hostname: bool) -> ssl.SSLContext:
|
|
43
|
+
"""Create an SSL context that validates the certificate of a device.
|
|
44
|
+
|
|
45
|
+
The hostname is only validated when `validate_hostname` is set, as it is based
|
|
46
|
+
on the device identifier. Creating an SSL context has some blocking IO, so
|
|
47
|
+
call this in the executor.
|
|
48
|
+
"""
|
|
49
|
+
context = ssl.create_default_context(cadata=CACERT)
|
|
50
|
+
context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member
|
|
51
|
+
if validate_hostname:
|
|
52
|
+
context.hostname_checks_common_name = True
|
|
53
|
+
else:
|
|
54
|
+
context.check_hostname = False # Skip hostname validation
|
|
55
|
+
context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active
|
|
56
|
+
return context
|
|
57
|
+
|
|
58
|
+
|
|
42
59
|
def authorized_method(
|
|
43
60
|
func: Callable[..., Coroutine[Any, Any, T]],
|
|
44
61
|
) -> Callable[..., Coroutine[Any, Any, T]]:
|
|
@@ -260,33 +277,36 @@ class HomeWizardEnergyV2(HomeWizardEnergy):
|
|
|
260
277
|
Get a clientsession that is tuned for communication with the HomeWizard Energy Device
|
|
261
278
|
"""
|
|
262
279
|
|
|
263
|
-
def _build_ssl_context() -> ssl.SSLContext:
|
|
264
|
-
context = ssl.create_default_context(cadata=CACERT)
|
|
265
|
-
context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member
|
|
266
|
-
if self._identifier is not None:
|
|
267
|
-
context.hostname_checks_common_name = True
|
|
268
|
-
else:
|
|
269
|
-
context.check_hostname = False # Skip hostname validation
|
|
270
|
-
context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active
|
|
271
|
-
return context
|
|
272
|
-
|
|
273
280
|
# Creating an SSL context has some blocking IO so need to run it in the executor
|
|
274
281
|
loop = asyncio.get_running_loop()
|
|
275
|
-
return await loop.run_in_executor(
|
|
282
|
+
return await loop.run_in_executor(
|
|
283
|
+
None, create_ssl_context, self._identifier is not None
|
|
284
|
+
)
|
|
276
285
|
|
|
277
286
|
@backoff.on_exception(backoff.expo, RequestError, max_tries=3, logger=None)
|
|
278
287
|
async def _request(
|
|
279
288
|
self, path: str, method: str = METH_GET, data: object = None
|
|
280
289
|
) -> tuple[HTTPStatus, dict[str, Any] | None]:
|
|
281
|
-
"""Make a request to the API.
|
|
290
|
+
"""Make a request to the API, one request at a time.
|
|
282
291
|
|
|
292
|
+
Devices have very few connection slots, so requests are serialized to
|
|
293
|
+
keep at most one connection open. The lock is taken per attempt, so it
|
|
294
|
+
is released during backoff sleeps, and it is taken before the timeout
|
|
295
|
+
starts, so time spent waiting for the lock does not count towards it.
|
|
296
|
+
"""
|
|
283
297
|
async with self._lock:
|
|
284
|
-
|
|
285
|
-
await self._create_clientsession()
|
|
298
|
+
return await self._request_unlocked(path, method, data)
|
|
286
299
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
300
|
+
async def _request_unlocked(
|
|
301
|
+
self, path: str, method: str = METH_GET, data: object = None
|
|
302
|
+
) -> tuple[HTTPStatus, dict[str, Any] | None]:
|
|
303
|
+
"""Make a request to the API. Must be called while holding the lock."""
|
|
304
|
+
|
|
305
|
+
if self._session is None:
|
|
306
|
+
await self._create_clientsession()
|
|
307
|
+
|
|
308
|
+
if self._ssl is False:
|
|
309
|
+
self._ssl = await self._get_ssl_context()
|
|
290
310
|
|
|
291
311
|
# Construct request
|
|
292
312
|
url = f"https://{self.host}{path}"
|
|
@@ -300,15 +320,17 @@ class HomeWizardEnergyV2(HomeWizardEnergy):
|
|
|
300
320
|
|
|
301
321
|
try:
|
|
302
322
|
async with asyncio.timeout(self._request_timeout):
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
323
|
+
resp = await self._session.request(
|
|
324
|
+
method,
|
|
325
|
+
url,
|
|
326
|
+
json=data,
|
|
327
|
+
headers=headers,
|
|
328
|
+
ssl=self._ssl,
|
|
329
|
+
server_hostname=self._identifier,
|
|
330
|
+
)
|
|
331
|
+
# Read the full body while holding the lock, so the connection
|
|
332
|
+
# is back in the pool before the next request starts.
|
|
333
|
+
await resp.read()
|
|
312
334
|
LOGGER.debug("%s, %s", resp.status, await resp.text("utf-8"))
|
|
313
335
|
except TimeoutError as exception:
|
|
314
336
|
raise RequestError(
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
"""HomeWizard Energy API library."""
|
|
2
|
-
|
|
3
|
-
from aiohttp import ClientSession
|
|
4
|
-
|
|
5
|
-
from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError
|
|
6
|
-
from .homewizard_energy import HomeWizardEnergy
|
|
7
|
-
from .v1 import HomeWizardEnergyV1
|
|
8
|
-
from .v2 import HomeWizardEnergyV2
|
|
9
|
-
|
|
10
|
-
__all__ = [
|
|
11
|
-
"DisabledError",
|
|
12
|
-
"HomeWizardEnergy",
|
|
13
|
-
"HomeWizardEnergyV1",
|
|
14
|
-
"HomeWizardEnergyV2",
|
|
15
|
-
"InvalidStateError",
|
|
16
|
-
"RequestError",
|
|
17
|
-
"UnsupportedError",
|
|
18
|
-
]
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
async def has_v2_api(host: str, websession: ClientSession | None = None) -> bool:
|
|
22
|
-
"""Check if the device has support for the v2 api."""
|
|
23
|
-
websession_provided = websession is not None
|
|
24
|
-
if websession is None:
|
|
25
|
-
websession = ClientSession()
|
|
26
|
-
try:
|
|
27
|
-
# v2 api is https only and returns a 401 Unauthorized when no key provided,
|
|
28
|
-
# no connection can be made if the device is not v2
|
|
29
|
-
url = f"https://{host}/api"
|
|
30
|
-
res = await websession.get(url, ssl=False, raise_for_status=False, timeout=5)
|
|
31
|
-
res.close()
|
|
32
|
-
|
|
33
|
-
return res.status == 401
|
|
34
|
-
except Exception: # pylint: disable=broad-except
|
|
35
|
-
# all other status/exceptions means the device is not v2 or not reachable at this time
|
|
36
|
-
return False
|
|
37
|
-
finally:
|
|
38
|
-
if not websession_provided:
|
|
39
|
-
await websession.close()
|
|
File without changes
|
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/errors.py
RENAMED
|
File without changes
|
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/models.py
RENAMED
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/py.typed
RENAMED
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/utils.py
RENAMED
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v1/const.py
RENAMED
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/cacert.py
RENAMED
|
File without changes
|
{python_homewizard_energy-10.3.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/const.py
RENAMED
|
File without changes
|