python-homewizard-energy 6.3.0b2__tar.gz → 7.0.0b1__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.
Files changed (16) hide show
  1. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/PKG-INFO +6 -8
  2. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/README.md +3 -3
  3. python_homewizard_energy-7.0.0b1/homewizard_energy/__init__.py +14 -0
  4. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/homewizard_energy/errors.py +8 -0
  5. python_homewizard_energy-6.3.0b2/homewizard_energy/homewizard_energy.py → python_homewizard_energy-7.0.0b1/homewizard_energy/v1/__init__.py +11 -5
  6. {python_homewizard_energy-6.3.0b2/homewizard_energy → python_homewizard_energy-7.0.0b1/homewizard_energy/v1}/const.py +1 -1
  7. {python_homewizard_energy-6.3.0b2/homewizard_energy → python_homewizard_energy-7.0.0b1/homewizard_energy/v1}/models.py +2 -2
  8. python_homewizard_energy-7.0.0b1/homewizard_energy/v2/__init__.py +295 -0
  9. python_homewizard_energy-7.0.0b1/homewizard_energy/v2/cacert.py +23 -0
  10. python_homewizard_energy-7.0.0b1/homewizard_energy/v2/const.py +1 -0
  11. python_homewizard_energy-7.0.0b1/homewizard_energy/v2/models.py +313 -0
  12. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/pyproject.toml +10 -14
  13. python_homewizard_energy-6.3.0b2/homewizard_energy/__init__.py +0 -20
  14. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/LICENSE +0 -0
  15. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/homewizard_energy/brand.py +0 -0
  16. {python_homewizard_energy-6.3.0b2 → python_homewizard_energy-7.0.0b1}/homewizard_energy/py.typed +0 -0
@@ -1,18 +1,16 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-homewizard-energy
3
- Version: 6.3.0b2
3
+ Version: 7.0.0b1
4
4
  Summary: Asynchronous Python client for the HomeWizard Energy
5
5
  Home-page: https://github.com/homewizard/python-homewizard-energy
6
6
  License: Apache-2.0
7
7
  Author: DCSBL
8
8
  Maintainer: DCSBL
9
- Requires-Python: >=3.9,<4.0
9
+ Requires-Python: >=3.12,<4.0
10
10
  Classifier: License :: OSI Approved :: Apache Software License
11
11
  Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
12
  Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
16
14
  Requires-Dist: aiohttp (>=3.0.0)
17
15
  Requires-Dist: async-timeout (>=4.0.3,<5.0.0)
18
16
  Requires-Dist: backoff (>=2.2.1,<3.0.0)
@@ -46,14 +44,14 @@ python3 -m pip install python-homewizard-energy
46
44
  ## Example
47
45
  ```python
48
46
  import asyncio
49
- from homewizard_energy import HomeWizardEnergy
47
+ from homewizard_energy import HomeWizardEnergyV1V1
50
48
 
51
49
  IP_ADDRESS = "192.168.1.123"
52
50
 
53
51
 
54
52
  async def main():
55
53
 
56
- async with HomeWizardEnergy(host=IP_ADDRESS) as api:
54
+ async with HomeWizardEnergyV1(host=IP_ADDRESS) as api:
57
55
 
58
56
  # Get device information, like firmware version
59
57
  print(await api.device())
@@ -73,7 +71,7 @@ asyncio.run(main())
73
71
  Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
74
72
 
75
73
  ## Requirements
76
- - Python 3.9 or higher
74
+ - Python 3.10 or higher
77
75
  - [Poetry](https://python-poetry.org/docs/#installing-with-pipx)
78
76
 
79
77
  ## Installation and setup
@@ -21,14 +21,14 @@ python3 -m pip install python-homewizard-energy
21
21
  ## Example
22
22
  ```python
23
23
  import asyncio
24
- from homewizard_energy import HomeWizardEnergy
24
+ from homewizard_energy import HomeWizardEnergyV1V1
25
25
 
26
26
  IP_ADDRESS = "192.168.1.123"
27
27
 
28
28
 
29
29
  async def main():
30
30
 
31
- async with HomeWizardEnergy(host=IP_ADDRESS) as api:
31
+ async with HomeWizardEnergyV1(host=IP_ADDRESS) as api:
32
32
 
33
33
  # Get device information, like firmware version
34
34
  print(await api.device())
@@ -48,7 +48,7 @@ asyncio.run(main())
48
48
  Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
49
49
 
50
50
  ## Requirements
51
- - Python 3.9 or higher
51
+ - Python 3.10 or higher
52
52
  - [Poetry](https://python-poetry.org/docs/#installing-with-pipx)
53
53
 
54
54
  ## Installation and setup
@@ -0,0 +1,14 @@
1
+ """HomeWizard Energy API library."""
2
+
3
+ from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError
4
+ from .v1 import HomeWizardEnergyV1
5
+ from .v2 import HomeWizardEnergyV2
6
+
7
+ __all__ = [
8
+ "DisabledError",
9
+ "HomeWizardEnergyV1",
10
+ "HomeWizardEnergyV2",
11
+ "InvalidStateError",
12
+ "RequestError",
13
+ "UnsupportedError",
14
+ ]
@@ -12,6 +12,10 @@ class RequestError(HomeWizardEnergyException):
12
12
  """
13
13
 
14
14
 
15
+ class ResponseError(HomeWizardEnergyException):
16
+ """API responded unexpected."""
17
+
18
+
15
19
  class NotFoundError(HomeWizardEnergyException):
16
20
  """Request not found.
17
21
 
@@ -29,3 +33,7 @@ class UnsupportedError(HomeWizardEnergyException):
29
33
 
30
34
  class DisabledError(HomeWizardEnergyException):
31
35
  """Raised when device API is disabled. User has to enable API in app."""
36
+
37
+
38
+ class UnauthorizedError(HomeWizardEnergyException):
39
+ """Raised when request is not authorized."""
@@ -13,8 +13,14 @@ import backoff
13
13
  from aiohttp.client import ClientError, ClientResponseError, ClientSession
14
14
  from aiohttp.hdrs import METH_GET, METH_PUT
15
15
 
16
+ from homewizard_energy.errors import (
17
+ DisabledError,
18
+ NotFoundError,
19
+ RequestError,
20
+ UnsupportedError,
21
+ )
22
+
16
23
  from .const import SUPPORTED_API_VERSION
17
- from .errors import DisabledError, NotFoundError, RequestError, UnsupportedError
18
24
  from .models import Data, Device, State, System
19
25
 
20
26
  _LOGGER = logging.getLogger(__name__)
@@ -23,7 +29,7 @@ T = TypeVar("T")
23
29
 
24
30
 
25
31
  def optional_method(
26
- func: Callable[..., Coroutine[Any, Any, T]]
32
+ func: Callable[..., Coroutine[Any, Any, T]],
27
33
  ) -> Callable[..., Coroutine[Any, Any, T]]:
28
34
  """Check if method is supported."""
29
35
 
@@ -36,7 +42,7 @@ def optional_method(
36
42
  return wrapper
37
43
 
38
44
 
39
- class HomeWizardEnergy:
45
+ class HomeWizardEnergyV1:
40
46
  """Communicate with a HomeWizard Energy device."""
41
47
 
42
48
  _session: ClientSession | None
@@ -204,11 +210,11 @@ class HomeWizardEnergy:
204
210
  if self._session and self._close_session:
205
211
  await self._session.close()
206
212
 
207
- async def __aenter__(self) -> HomeWizardEnergy:
213
+ async def __aenter__(self) -> HomeWizardEnergyV1:
208
214
  """Async enter.
209
215
 
210
216
  Returns:
211
- The HomeWizardEnergy object.
217
+ The HomeWizardEnergyV1 object.
212
218
  """
213
219
  return self
214
220
 
@@ -1,4 +1,4 @@
1
- """Constants for HomeWizard Energy."""
1
+ """Constants for HomeWizard Energy v1."""
2
2
 
3
3
  SUPPORTED_API_VERSION = "v1"
4
4
 
@@ -8,7 +8,7 @@ from datetime import datetime
8
8
  from enum import Enum
9
9
  from typing import Any
10
10
 
11
- from .brand import Product, from_type
11
+ from homewizard_energy.brand import Product, from_type
12
12
 
13
13
 
14
14
  @dataclass
@@ -154,7 +154,7 @@ class Data:
154
154
 
155
155
  @staticmethod
156
156
  def get_external_devices(
157
- external_devices: list[dict[str, Any]] | None
157
+ external_devices: list[dict[str, Any]] | None,
158
158
  ) -> dict[str, ExternalDevice] | None:
159
159
  """Convert external device object to ExternalDevice Object List."""
160
160
  devices: dict[str, ExternalDevice] = {}
@@ -0,0 +1,295 @@
1
+ """Representation of a HomeWizard Energy device."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import ssl
8
+ from collections.abc import Callable, Coroutine
9
+ from http import HTTPStatus
10
+ from typing import Any, TypeVar
11
+
12
+ import async_timeout
13
+ import backoff
14
+ from aiohttp.client import (
15
+ ClientError,
16
+ ClientResponseError,
17
+ ClientSession,
18
+ ClientTimeout,
19
+ TCPConnector,
20
+ )
21
+ from aiohttp.hdrs import METH_DELETE, METH_GET, METH_POST, METH_PUT
22
+
23
+ from homewizard_energy.errors import (
24
+ DisabledError,
25
+ RequestError,
26
+ ResponseError,
27
+ UnauthorizedError,
28
+ )
29
+
30
+ from .cacert import CACERT
31
+ from .models import Device, Measurement, System, SystemUpdate
32
+
33
+ _LOGGER = logging.getLogger(__name__)
34
+
35
+ T = TypeVar("T")
36
+
37
+
38
+ def authorized_method(
39
+ func: Callable[..., Coroutine[Any, Any, T]],
40
+ ) -> Callable[..., Coroutine[Any, Any, T]]:
41
+ """Decorator method to check if token is set."""
42
+
43
+ async def wrapper(self, *args, **kwargs) -> T:
44
+ # pylint: disable=protected-access
45
+ if self._token is None:
46
+ raise UnauthorizedError("Token missing")
47
+
48
+ return await func(self, *args, **kwargs)
49
+
50
+ return wrapper
51
+
52
+
53
+ class HomeWizardEnergyV2:
54
+ """Communicate with a HomeWizard Energy device."""
55
+
56
+ _clientsession: ClientSession | None = None
57
+ _request_timeout: int = 10
58
+
59
+ def __init__(
60
+ self,
61
+ host: str,
62
+ identifier: str | None = None,
63
+ token: str | None = None,
64
+ timeout: int = 10,
65
+ ):
66
+ """Create a HomeWizard Energy object.
67
+
68
+ Args:
69
+ host: IP or URL for device.
70
+ id: ID for device.
71
+ token: Token for device.
72
+ timeout: Request timeout in seconds.
73
+ """
74
+
75
+ self._host = host
76
+ self._identifier = identifier
77
+ self._token = token
78
+ self._request_timeout = timeout
79
+
80
+ @property
81
+ def host(self) -> str:
82
+ """Return the hostname of the device.
83
+
84
+ Returns:
85
+ host: The used host
86
+
87
+ """
88
+ return self._host
89
+
90
+ @authorized_method
91
+ async def device(self) -> Device:
92
+ """Return the device object."""
93
+ _, response = await self._request("/api")
94
+ device = Device.from_dict(response)
95
+
96
+ return device
97
+
98
+ @authorized_method
99
+ async def measurement(self) -> Measurement:
100
+ """Return the measurement object."""
101
+ _, response = await self._request("/api/measurement")
102
+ measurement = Measurement.from_dict(response)
103
+
104
+ return measurement
105
+
106
+ @authorized_method
107
+ async def system(
108
+ self,
109
+ update: SystemUpdate | None = None,
110
+ ) -> System:
111
+ """Return the system object."""
112
+
113
+ if update is not None:
114
+ data = update.as_dict()
115
+ status, response = await self._request(
116
+ "/api/system", method=METH_PUT, data=data
117
+ )
118
+
119
+ else:
120
+ status, response = await self._request("/api/system")
121
+
122
+ if status != HTTPStatus.OK:
123
+ error = response.get("error", response)
124
+ raise RequestError(f"Failed to get system: {error}")
125
+
126
+ system = System.from_dict(response)
127
+ return system
128
+
129
+ @authorized_method
130
+ async def identify(
131
+ self,
132
+ ) -> None:
133
+ """Send identify request."""
134
+ await self._request("/api/system/identify", method=METH_PUT)
135
+
136
+ @authorized_method
137
+ async def reboot(
138
+ self,
139
+ ) -> None:
140
+ """Reboot the HomeWizard Energy device.
141
+
142
+ This will cause the device to restart, resulting in temporary unavailability.
143
+ The reboot process typically takes a few seconds to complete.
144
+
145
+ Note: A reboot is usually not necessary.
146
+ Make sure to inform the user that if the issue persists and frequent reboots are required,
147
+ they need to contact our support team to help identify and resolve the root cause.
148
+ """
149
+ await self._request("/api/system/reboot", method=METH_PUT)
150
+
151
+ async def get_token(
152
+ self,
153
+ name: str,
154
+ ) -> str:
155
+ """Get authorization token from device."""
156
+ status, response = await self._request(
157
+ "/api/user", method=METH_POST, data={"name": f"local/{name}"}
158
+ )
159
+
160
+ if status == HTTPStatus.FORBIDDEN:
161
+ raise DisabledError("User creation is not enabled on the device")
162
+
163
+ if status != HTTPStatus.OK:
164
+ error = response.get("error", response)
165
+ raise RequestError(f"Error occurred while getting token: {error}", error)
166
+
167
+ try:
168
+ token = response["token"]
169
+ except KeyError as ex:
170
+ raise ResponseError("Failed to get token") from ex
171
+
172
+ self._token = token
173
+ return token
174
+
175
+ @authorized_method
176
+ async def delete_token(
177
+ self,
178
+ name: str | None = None,
179
+ ) -> None:
180
+ """Delete authorization token from device."""
181
+ status, response = await self._request(
182
+ "/api/user",
183
+ method=METH_DELETE,
184
+ data={"name": name} if name is not None else None,
185
+ )
186
+
187
+ if status != HTTPStatus.NO_CONTENT:
188
+ error = response.get("error", response)
189
+ raise RequestError(f"Error occurred while getting token: {error}", error)
190
+
191
+ # Our token was invalided, resetting it
192
+ if name is None:
193
+ self._token = None
194
+
195
+ async def _get_clientsession(self) -> ClientSession:
196
+ """
197
+ Get a clientsession that is tuned for communication with the HomeWizard Energy Device
198
+ """
199
+
200
+ def _build_ssl_context() -> ssl.SSLContext:
201
+ context = ssl.create_default_context(cadata=CACERT)
202
+ if self._identifier is not None:
203
+ context.hostname_checks_common_name = True
204
+ else:
205
+ _LOGGER.warning("No hostname provided, skipping hostname validation")
206
+ context.check_hostname = False # Skip hostname validation
207
+ context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active
208
+ return context
209
+
210
+ # Creating an SSL context has some blocking IO so need to run it in the executor
211
+ loop = asyncio.get_running_loop()
212
+ context = await loop.run_in_executor(None, _build_ssl_context)
213
+
214
+ connector = TCPConnector(
215
+ enable_cleanup_closed=True,
216
+ ssl=context,
217
+ limit_per_host=1,
218
+ )
219
+
220
+ return ClientSession(
221
+ connector=connector, timeout=ClientTimeout(total=self._request_timeout)
222
+ )
223
+
224
+ @backoff.on_exception(backoff.expo, RequestError, max_tries=5, logger=None)
225
+ async def _request(
226
+ self, path: str, method: str = METH_GET, data: object = None
227
+ ) -> tuple[HTTPStatus, dict[str, Any] | None]:
228
+ """Make a request to the API."""
229
+
230
+ if self._clientsession is None:
231
+ self._clientsession = await self._get_clientsession()
232
+
233
+ # Construct request
234
+ url = f"https://{self.host}{path}"
235
+ headers = {
236
+ "Content-Type": "application/json",
237
+ }
238
+ if self._token is not None:
239
+ headers["Authorization"] = f"Bearer {self._token}"
240
+
241
+ _LOGGER.debug("%s, %s, %s", method, url, data)
242
+
243
+ try:
244
+ async with async_timeout.timeout(self._request_timeout):
245
+ resp = await self._clientsession.request(
246
+ method,
247
+ url,
248
+ json=data,
249
+ headers=headers,
250
+ server_hostname=self._identifier
251
+ if self._identifier is not None
252
+ else None,
253
+ )
254
+ _LOGGER.debug("%s, %s", resp.status, await resp.text("utf-8"))
255
+ except asyncio.TimeoutError as exception:
256
+ raise RequestError(
257
+ f"Timeout occurred while connecting to the HomeWizard Energy device at {self.host}"
258
+ ) from exception
259
+ except (ClientError, ClientResponseError) as exception:
260
+ raise RequestError(
261
+ f"Error occurred while communicating with the HomeWizard Energy device at {self.host}"
262
+ ) from exception
263
+
264
+ match resp.status:
265
+ case HTTPStatus.UNAUTHORIZED:
266
+ raise UnauthorizedError("Token rejected")
267
+ case HTTPStatus.NO_CONTENT:
268
+ # No content, just return
269
+ return (HTTPStatus.NO_CONTENT, None)
270
+ case HTTPStatus.OK:
271
+ pass
272
+
273
+ return (resp.status, await resp.json())
274
+
275
+ async def close(self) -> None:
276
+ """Close client session."""
277
+ _LOGGER.debug("Closing clientsession")
278
+ if self._clientsession is not None:
279
+ await self._clientsession.close()
280
+
281
+ async def __aenter__(self) -> HomeWizardEnergyV2:
282
+ """Async enter.
283
+
284
+ Returns:
285
+ The HomeWizardEnergyV2 object.
286
+ """
287
+ return self
288
+
289
+ async def __aexit__(self, *_exc_info: Any) -> None:
290
+ """Async exit.
291
+
292
+ Args:
293
+ _exc_info: Exec type.
294
+ """
295
+ await self.close()
@@ -0,0 +1,23 @@
1
+ """Contents of homewizard-ca-cert.pem file"""
2
+
3
+ CACERT = """
4
+ -----BEGIN CERTIFICATE-----
5
+ MIIDITCCAgkCFDn7cwYLioTM3VxdAygLl/Px9ovFMA0GCSqGSIb3DQEBCwUAME0x
6
+ CzAJBgNVBAYTAk5MMQswCQYDVQQIDAJaSDETMBEGA1UECgwKSG9tZVdpemFyZDEc
7
+ MBoGA1UEAwwTQXBwbGlhbmNlIEFjY2VzcyBDQTAeFw0yMTEyMTgxOTEyMTJaFw0z
8
+ MTEyMTYxOTEyMTJaME0xCzAJBgNVBAYTAk5MMQswCQYDVQQIDAJaSDETMBEGA1UE
9
+ CgwKSG9tZVdpemFyZDEcMBoGA1UEAwwTQXBwbGlhbmNlIEFjY2VzcyBDQTCCASIw
10
+ DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAPBIvW8NRffqdvzHZY0M32fQHiGm
11
+ pJgNGhiaQmpJfRDhT9yihM0S/hYcN8IqnfrMqoCQb/56Ub0+dZizmtfcGsE+Lpm1
12
+ K1znkWqSDlpnuTNOb70TrsxBmbFuNOZQEi/xOjzT2j98wT0GSfxz1RVq6lZhDRRz
13
+ xoe08+Xo4+ttUGanfOggJi0BXygeFEVBpbctVVJ9EgqeEE9itjcMlcxMe1QN14f8
14
+ hCcOnId+9PSsdmyUCLrTB0FVYrbNfbJPk/vMU57fu6swBjWhYBxPx9ZhFy+7WnPR
15
+ 9BFg4seHNVQIqZNrf1YwBXlmZQIL32SRPaiH/+AVNMrYGXBvncY0Km6ZHIMCAwEA
16
+ ATANBgkqhkiG9w0BAQsFAAOCAQEA6ybM8xm0PCXg8Rr/q0v1vPxQy44PmwXTDj0e
17
+ r2vW4ZMiEwXZCp0Kk2K16KJYz4iJyfiQk8ikAIMiRSbyXzmyQ7XmL1O4l4d8E1Pg
18
+ 8EImvcyoBxFhd0Lq7VKriLc8Bw8SXbahPMGT+Y8Yz0uIsLAYVwlkLfgppVPmBaLD
19
+ QautcQnI8WxPvCIQf5anyzgAyJC5ac6/CkB+iyPcuWcG3RMYvXnC0QoTlRa5YMlE
20
+ FweVDlT2C/MdDyOxiAD/H1EP/eaySnU0zsxyD0yNFRKsQfQ+UJEPd2GS1AGA1lTy
21
+ CGdyYj/Gghrusw0hM4rYXQSERWGF0mpEnuJ+7bHDolHu0rzgTQ==
22
+ -----END CERTIFICATE-----
23
+ """
@@ -0,0 +1 @@
1
+ """Constants for HomeWizard Energy v2."""
@@ -0,0 +1,313 @@
1
+ """Models for HomeWizard Energy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ from datetime import datetime
7
+ from enum import Enum
8
+ from typing import Any
9
+
10
+ from homewizard_energy.brand import Product, from_type
11
+
12
+
13
+ @dataclass
14
+ class Device:
15
+ """Represent Device config."""
16
+
17
+ product: Product | None
18
+ product_name: str | None
19
+ product_type: str | None
20
+ serial: str | None
21
+ api_version: str | None
22
+ firmware_version: str | None
23
+
24
+ @staticmethod
25
+ def from_dict(data: dict[str, str]) -> Device:
26
+ """Return Device object from API response.
27
+
28
+ Args:
29
+ data: The data from the HomeWizard Energy `api` API.
30
+
31
+ Returns:
32
+ A Device object.
33
+ """
34
+ return Device(
35
+ product=from_type(data.get("product_type")),
36
+ product_name=data.get("product_name"),
37
+ product_type=data.get("product_type"),
38
+ serial=data.get("serial"),
39
+ api_version=data.get("api_version"),
40
+ firmware_version=data.get("firmware_version"),
41
+ )
42
+
43
+
44
+ @dataclass
45
+ class Measurement:
46
+ """Represent Measurement."""
47
+
48
+ protocol_version: int | None
49
+ meter_model: str | None
50
+ unique_id: str | None
51
+
52
+ tariff: int | None
53
+
54
+ energy_import_kwh: float | None
55
+ energy_import_t1_kwh: float | None
56
+ energy_import_t2_kwh: float | None
57
+ energy_import_t3_kwh: float | None
58
+ energy_import_t4_kwh: float | None
59
+ energy_export_kwh: float | None
60
+ energy_export_t1_kwh: float | None
61
+ energy_export_t2_kwh: float | None
62
+ energy_export_t3_kwh: float | None
63
+ energy_export_t4_kwh: float | None
64
+
65
+ power_w: float | None
66
+ power_l1_w: float | None
67
+ power_l2_w: float | None
68
+ power_l3_w: float | None
69
+
70
+ voltage_l1_v: float | None
71
+ voltage_l2_v: float | None
72
+ voltage_l3_v: float | None
73
+
74
+ current_a: float | None
75
+ current_l1_a: float | None
76
+ current_l2_a: float | None
77
+ current_l3_a: float | None
78
+
79
+ frequency_hz: float | None
80
+
81
+ voltage_sag_l1_count: int | None
82
+ voltage_sag_l2_count: int | None
83
+ voltage_sag_l3_count: int | None
84
+
85
+ voltage_swell_l1_count: int | None
86
+ voltage_swell_l2_count: int | None
87
+ voltage_swell_l3_count: int | None
88
+
89
+ any_power_fail_count: int | None
90
+ long_power_fail_count: int | None
91
+
92
+ average_power_15m_w: float | None
93
+ monthly_power_peak_w: float | None
94
+ monthly_power_peak_timestamp: datetime | None
95
+
96
+ external_devices: dict[str, ExternalDevice] | None
97
+
98
+ @staticmethod
99
+ def convert_timestamp_to_datetime(timestamp: str | None) -> datetime | None:
100
+ """Convert SRM gas-timestamp to datetime object.
101
+
102
+ Args:
103
+ timestamp: Timestamp string, formatted as yymmddhhmmss
104
+
105
+ Returns:
106
+ A datetime object.
107
+ """
108
+ if timestamp is None:
109
+ return None
110
+
111
+ return datetime.fromisoformat(timestamp)
112
+
113
+ @staticmethod
114
+ def convert_hex_string_to_readable(value: str | None) -> str | None:
115
+ """Convert hex string to readable string, if possible.
116
+
117
+ Args:
118
+ value: String to convert, e.g. '4E47475955'
119
+
120
+ Returns:
121
+ A string formatted or original value when failed.
122
+ """
123
+ try:
124
+ return bytes.fromhex(value).decode("utf-8")
125
+ except (TypeError, ValueError):
126
+ return value
127
+
128
+ @staticmethod
129
+ def get_external_devices(
130
+ external_devices: list[dict[str, Any]] | None,
131
+ ) -> dict[str, ExternalDevice] | None:
132
+ """Convert external device object to ExternalDevice Object List."""
133
+ devices: dict[str, ExternalDevice] = {}
134
+
135
+ if external_devices is None:
136
+ return None
137
+
138
+ for external in external_devices:
139
+ try:
140
+ device = ExternalDevice.from_dict(external)
141
+ except KeyError:
142
+ continue
143
+
144
+ type_unique_id = f"{external.get('type')}_{device.unique_id}"
145
+ devices[type_unique_id] = device
146
+
147
+ return devices
148
+
149
+ @staticmethod
150
+ def from_dict(data: dict[str, Any]) -> Measurement:
151
+ """Return Measurement object from API response.
152
+
153
+ Args:
154
+ data: The data from the HomeWizard Energy `api/v1/measurement` API.
155
+
156
+ Returns:
157
+ A Measurement object.
158
+ """
159
+ return Measurement(
160
+ protocol_version=data.get("smr_version"),
161
+ meter_model=data.get("meter_model"),
162
+ unique_id=Measurement.convert_hex_string_to_readable(data.get("unique_id")),
163
+ tariff=data.get("active_tariff"),
164
+ energy_import_kwh=data.get("energy_import_kwh"),
165
+ energy_import_t1_kwh=data.get("energy_import_t1_kwh"),
166
+ energy_import_t2_kwh=data.get("energy_import_t2_kwh"),
167
+ energy_import_t3_kwh=data.get("energy_import_t3_kwh"),
168
+ energy_import_t4_kwh=data.get("energy_import_t4_kwh"),
169
+ energy_export_kwh=data.get("energy_export_kwh"),
170
+ energy_export_t1_kwh=data.get("energy_export_t1_kwh"),
171
+ energy_export_t2_kwh=data.get("energy_export_t2_kwh"),
172
+ energy_export_t3_kwh=data.get("energy_export_t3_kwh"),
173
+ energy_export_t4_kwh=data.get("energy_export_t4_kwh"),
174
+ power_w=data.get("power_w"),
175
+ power_l1_w=data.get("power_l1_w"),
176
+ power_l2_w=data.get("power_l2_w"),
177
+ power_l3_w=data.get("power_l3_w"),
178
+ voltage_l1_v=data.get("voltage_l1_v"),
179
+ voltage_l2_v=data.get("voltage_l2_v"),
180
+ voltage_l3_v=data.get("voltage_l3_v"),
181
+ current_a=data.get("current_a"),
182
+ current_l1_a=data.get("current_l1_a"),
183
+ current_l2_a=data.get("current_l2_a"),
184
+ current_l3_a=data.get("current_l3_a"),
185
+ frequency_hz=data.get("frequency_hz"),
186
+ voltage_sag_l1_count=data.get("voltage_sag_l1_count"),
187
+ voltage_sag_l2_count=data.get("voltage_sag_l2_count"),
188
+ voltage_sag_l3_count=data.get("voltage_sag_l3_count"),
189
+ voltage_swell_l1_count=data.get("voltage_swell_l1_count"),
190
+ voltage_swell_l2_count=data.get("voltage_swell_l2_count"),
191
+ voltage_swell_l3_count=data.get("voltage_swell_l3_count"),
192
+ any_power_fail_count=data.get("any_power_fail_count"),
193
+ long_power_fail_count=data.get("long_power_fail_count"),
194
+ average_power_15m_w=data.get("average_power_15m_w"),
195
+ monthly_power_peak_w=data.get("monthly_power_peak_w"),
196
+ monthly_power_peak_timestamp=Measurement.convert_timestamp_to_datetime(
197
+ data.get("monthly_power_peak_timestamp")
198
+ ),
199
+ external_devices=Measurement.get_external_devices(data.get("external")),
200
+ )
201
+
202
+
203
+ @dataclass
204
+ class ExternalDevice:
205
+ """Represents externally connected device."""
206
+
207
+ class DeviceType(Enum):
208
+ """Device type allocations.
209
+
210
+ Based on:
211
+ https://oms-group.org/fileadmin/files/download4all/omsSpezifikationen/generation4/spezifikation/vol2/OMS-Spec_Vol2_Primary_v442.pdf
212
+ Page 18, Chapter 2.3, Table 2
213
+ """
214
+
215
+ UNKNOWN = -1
216
+ GAS_METER = 3
217
+ HEAT_METER = 4
218
+ WARM_WATER_METER = 6
219
+ WATER_METER = 7
220
+ INLET_HEAT_METER = 12
221
+
222
+ @staticmethod
223
+ def from_string(value: str) -> ExternalDevice.DeviceType:
224
+ """Convert string to enum."""
225
+ try:
226
+ return {
227
+ "gas_meter": ExternalDevice.DeviceType.GAS_METER,
228
+ "heat_meter": ExternalDevice.DeviceType.HEAT_METER,
229
+ "warm_water_meter": ExternalDevice.DeviceType.WARM_WATER_METER,
230
+ "water_meter": ExternalDevice.DeviceType.WATER_METER,
231
+ "inlet_heat_meter": ExternalDevice.DeviceType.INLET_HEAT_METER,
232
+ }[value]
233
+ except KeyError:
234
+ return ExternalDevice.DeviceType.UNKNOWN
235
+
236
+ unique_id: str
237
+ meter_type: DeviceType
238
+ value: float
239
+ unit: str
240
+ timestamp: datetime
241
+
242
+ @staticmethod
243
+ def from_dict(data: dict[str, Any]) -> ExternalDevice:
244
+ """Return State object from API response.
245
+
246
+ Args:
247
+ data: The data from a external device in the HomeWizard Energy
248
+ `api/v1/state` API.
249
+ Returns:
250
+ An ExternalDevice Device object.
251
+ """
252
+ if data.get("unique_id") is None:
253
+ raise KeyError("unique_id must be set")
254
+
255
+ return ExternalDevice(
256
+ unique_id=Measurement.convert_hex_string_to_readable(data.get("unique_id")),
257
+ meter_type=ExternalDevice.DeviceType.from_string(data.get("type", "")),
258
+ value=data.get("value", 0),
259
+ unit=data.get("unit", ""),
260
+ timestamp=Measurement.convert_timestamp_to_datetime(data.get("timestamp")),
261
+ )
262
+
263
+
264
+ @dataclass
265
+ class SystemUpdate:
266
+ """Represent System update config."""
267
+
268
+ cloud_enabled: bool = field(default=None)
269
+ status_led_brightness_pct: int = field(default=None)
270
+ api_v1_enabled: bool | None = field(default=None)
271
+
272
+ def as_dict(self) -> dict[str, bool | int]:
273
+ """Return SystemUpdate object as dict.
274
+
275
+ Only include values that are not None.
276
+ """
277
+ _dict = {k: v for k, v in asdict(self).items() if v is not None}
278
+
279
+ if not _dict:
280
+ raise ValueError("No values to update")
281
+
282
+ return _dict
283
+
284
+
285
+ @dataclass
286
+ class System:
287
+ """Represent System config."""
288
+
289
+ wifi_ssid: str
290
+ wifi_rssi_db: int
291
+ cloud_enabled: bool
292
+ uptime_s: str
293
+ status_led_brightness_pct: int
294
+ api_v1_enabled: bool | None
295
+
296
+ @staticmethod
297
+ def from_dict(data: dict[str, str]) -> System:
298
+ """Return System object from API response.
299
+
300
+ Args:
301
+ data: The data from the HomeWizard Energy `api/v2/system` API.
302
+
303
+ Returns:
304
+ A System object.
305
+ """
306
+ return System(
307
+ wifi_ssid=data.get("wifi_ssid"),
308
+ wifi_rssi_db=data.get("wifi_rssi_db"),
309
+ cloud_enabled=data.get("cloud_enabled"),
310
+ uptime_s=data.get("uptime_s"),
311
+ status_led_brightness_pct=data.get("status_led_brightness_pct"),
312
+ api_v1_enabled=data.get("api_v1_enabled"),
313
+ )
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "python-homewizard-energy"
3
- version = "6.3.0-beta-2"
3
+ version = "7.0.0-beta-1"
4
4
  description = "Asynchronous Python client for the HomeWizard Energy"
5
5
  authors = ["DCSBL"]
6
6
  maintainers = ["DCSBL"]
@@ -16,7 +16,7 @@ packages = [
16
16
  ]
17
17
 
18
18
  [tool.poetry.dependencies]
19
- python = "^3.9"
19
+ python = "^3.12"
20
20
  aiohttp = ">=3.0.0"
21
21
  async-timeout = "^4.0.3"
22
22
  multidict = "^6.0.5" ## To fix aiohttp dependency at python 3.12
@@ -24,40 +24,36 @@ backoff = "^2.2.1"
24
24
 
25
25
  [tool.poetry.dev-dependencies]
26
26
  aresponses = "^3.0.0"
27
- black = "^24.4"
28
- blacken-docs = "^1.18.0"
29
27
  flake8 = "^4.0.1"
30
28
  flake8-docstrings = "^1.7.0"
31
29
  isort = "^5.13.2"
32
30
  pre-commit = "^3.7.1"
33
31
  pre-commit-hooks = "^4.6.0"
34
- pylint = "^3.1.0"
35
- pytest = "^7.4.4"
36
- pytest-asyncio = "^0.23.8"
32
+ pylint = "^3.3.1"
33
+ pytest = "^8.3.3"
34
+ pytest-asyncio = "^0.24.0"
37
35
  pytest-cov = "^5.0.0"
38
36
  yamllint = "^1.35.1"
39
- pyupgrade = "^3.16.0"
37
+ pyupgrade = "^3.19.0"
40
38
  flake8-simplify = "^0.21.0"
41
- vulture = "^2.11"
39
+ vulture = "^2.13"
42
40
  flake8-bandit = "^3.0.0"
43
41
  flake8-bugbear = "^23.3.12"
44
42
  flake8-builtins = "^2.5.0"
45
43
  flake8-comprehensions = "^3.15.0"
46
44
  flake8-eradicate = "^1.2.1"
47
45
  flake8-markdown = "^0.3.0"
46
+ ruff = "0.7.1"
48
47
  darglint = "^1.8.1"
49
- safety = "^3.0.1"
48
+ safety = "^3.2.10"
50
49
  codespell = "^2.3.0"
51
50
  bandit = "^1.7.9"
52
- syrupy = "^4.6.0"
51
+ syrupy = "^4.7.2"
53
52
 
54
53
  [tool.poetry.urls]
55
54
  "Bug Tracker" = "https://github.com/homewizard/python-homewizard-energy/issues"
56
55
  Changelog = "https://github.com/homewizard/python-homewizard-energy/releases"
57
56
 
58
- [tool.black]
59
- target-version = ['py39']
60
-
61
57
  [tool.coverage.paths]
62
58
  source = ["homewizard_energy"]
63
59
 
@@ -1,20 +0,0 @@
1
- """HomeWizard Energy API library."""
2
-
3
- from .brand import Product
4
- from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError
5
- from .homewizard_energy import HomeWizardEnergy
6
- from .models import Data, Device, ExternalDevice, State, System
7
-
8
- __all__ = [
9
- "HomeWizardEnergy",
10
- "RequestError",
11
- "InvalidStateError",
12
- "UnsupportedError",
13
- "DisabledError",
14
- "Data",
15
- "Device",
16
- "ExternalDevice",
17
- "State",
18
- "System",
19
- "Product",
20
- ]