python-homewizard-energy 10.2.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.
Files changed (17) hide show
  1. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/PKG-INFO +3 -3
  2. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/README.md +2 -2
  3. python_homewizard_energy-10.4.0/homewizard_energy/__init__.py +143 -0
  4. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/const.py +16 -0
  5. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/homewizard_energy.py +3 -0
  6. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/models.py +16 -0
  7. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v1/__init__.py +43 -5
  8. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/__init__.py +61 -26
  9. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/pyproject.toml +1 -1
  10. python_homewizard_energy-10.2.0/homewizard_energy/__init__.py +0 -39
  11. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/LICENSE +0 -0
  12. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/errors.py +0 -0
  13. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/py.typed +0 -0
  14. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/utils.py +0 -0
  15. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v1/const.py +0 -0
  16. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/cacert.py +0 -0
  17. {python_homewizard_energy-10.2.0 → python_homewizard_energy-10.4.0}/homewizard_energy/v2/const.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-homewizard-energy
3
- Version: 10.2.0
3
+ Version: 10.4.0
4
4
  Summary: Asynchronous Python client for the HomeWizard Energy
5
5
  License: Apache-2.0
6
6
  License-File: LICENSE
@@ -73,8 +73,8 @@ async def main():
73
73
  # Get all data and remap v1 data to new v2 structure
74
74
  print(await api.combined())
75
75
 
76
- # Turn on the Energy Socket outlet
77
- await api.state(power_on=True)
76
+ # Turn on the Energy Socket outlet (works with both v1 and v2 API)
77
+ await api.system(power_on=True)
78
78
 
79
79
 
80
80
  asyncio.run(main())
@@ -46,8 +46,8 @@ async def main():
46
46
  # Get all data and remap v1 data to new v2 structure
47
47
  print(await api.combined())
48
48
 
49
- # Turn on the Energy Socket outlet
50
- await api.state(power_on=True)
49
+ # Turn on the Energy Socket outlet (works with both v1 and v2 API)
50
+ await api.system(power_on=True)
51
51
 
52
52
 
53
53
  asyncio.run(main())
@@ -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
@@ -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",
@@ -91,11 +91,14 @@ class HomeWizardEnergy:
91
91
  """Get the latest telegram."""
92
92
  raise NotImplementedError
93
93
 
94
+ # pylint: disable-next=too-many-arguments,too-many-positional-arguments
94
95
  async def system(
95
96
  self,
96
97
  cloud_enabled: bool | None = None,
97
98
  status_led_brightness_pct: int | None = None,
98
99
  api_v1_enabled: bool | None = None,
100
+ power_on: bool | None = None,
101
+ switch_lock: bool | None = None,
99
102
  ) -> System:
100
103
  """Get/set the system."""
101
104
  raise NotImplementedError
@@ -102,6 +102,18 @@ class CombinedModels:
102
102
  self.system = System()
103
103
  self.system.status_led_brightness_pct = (self.state.brightness / 255) * 100
104
104
 
105
+ ## state.power_on -> system.power_on
106
+ if self.state is not None and self.state.power_on is not None:
107
+ if self.system is None:
108
+ self.system = System()
109
+ self.system.power_on = self.state.power_on
110
+
111
+ ## state.switch_lock -> system.switch_lock
112
+ if self.state is not None and self.state.switch_lock is not None:
113
+ if self.system is None:
114
+ self.system = System()
115
+ self.system.switch_lock = self.state.switch_lock
116
+
105
117
 
106
118
  def get_verification_hostname(model: str, serial_number: str) -> str:
107
119
  """Helper method to convert device model and serial to identifier
@@ -595,6 +607,8 @@ class SystemUpdate(UpdateBaseModel):
595
607
  cloud_enabled: bool | None = field(default=None)
596
608
  status_led_brightness_pct: int | None = field(default=None)
597
609
  api_v1_enabled: bool | None = field(default=None)
610
+ power_on: bool | None = field(default=None)
611
+ switch_lock: bool | None = field(default=None)
598
612
 
599
613
 
600
614
  @dataclass(kw_only=True)
@@ -609,6 +623,8 @@ class System(BaseModel):
609
623
  uptime_s: int | None = field(default=None)
610
624
  status_led_brightness_pct: int | None = field(default=None)
611
625
  api_v1_enabled: bool | None = field(default=None)
626
+ power_on: bool | None = field(default=None)
627
+ switch_lock: bool | None = field(default=None)
612
628
 
613
629
  @classmethod
614
630
  def __post_deserialize__(cls, obj: System) -> System:
@@ -68,11 +68,14 @@ class HomeWizardEnergyV1(HomeWizardEnergy):
68
68
  return telegram
69
69
 
70
70
  @optional_method
71
+ # pylint: disable-next=too-many-arguments,too-many-positional-arguments
71
72
  async def system(
72
73
  self,
73
74
  cloud_enabled: bool | None = None,
74
75
  status_led_brightness_pct: int | None = None,
75
76
  api_v1_enabled: bool | None = None,
77
+ power_on: bool | None = None,
78
+ switch_lock: bool | None = None,
76
79
  ) -> System:
77
80
  """Return the system object."""
78
81
 
@@ -80,10 +83,29 @@ class HomeWizardEnergyV1(HomeWizardEnergy):
80
83
  if api_v1_enabled is not None:
81
84
  raise UnsupportedError("Setting api_v1_enabled is not supported in v1")
82
85
 
83
- # Legacy: route 'status_led_brightness_pct' to state
84
- if status_led_brightness_pct is not None:
85
- state = await self.state(brightness=status_led_brightness_pct * 2.55)
86
- return System(status_led_brightness_pct=state.brightness / 2.55)
86
+ # Legacy: route 'status_led_brightness_pct', 'power_on' and 'switch_lock'
87
+ # to state, as v1 exposes these via the state endpoint
88
+ if (
89
+ status_led_brightness_pct is not None
90
+ or power_on is not None
91
+ or switch_lock is not None
92
+ ):
93
+ state = await self.state(
94
+ power_on=power_on,
95
+ switch_lock=switch_lock,
96
+ brightness=(
97
+ status_led_brightness_pct * 2.55
98
+ if status_led_brightness_pct is not None
99
+ else None
100
+ ),
101
+ )
102
+ return System(
103
+ status_led_brightness_pct=(
104
+ state.brightness / 2.55 if state.brightness is not None else None
105
+ ),
106
+ power_on=state.power_on,
107
+ switch_lock=state.switch_lock,
108
+ )
87
109
 
88
110
  if cloud_enabled is not None:
89
111
  # Executing the update
@@ -140,7 +162,20 @@ class HomeWizardEnergyV1(HomeWizardEnergy):
140
162
  async def _request(
141
163
  self, path: str, method: str = METH_GET, data: object = None
142
164
  ) -> tuple[HTTPStatus, dict[str, Any] | None]:
143
- """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."""
144
179
 
145
180
  if self._session is None:
146
181
  await self._create_clientsession()
@@ -159,6 +194,9 @@ class HomeWizardEnergyV1(HomeWizardEnergy):
159
194
  json=data,
160
195
  headers=headers,
161
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()
162
200
  LOGGER.debug("%s, %s", resp.status, await resp.text("utf-8"))
163
201
  except TimeoutError as exception:
164
202
  raise RequestError(
@@ -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]]:
@@ -119,18 +136,31 @@ class HomeWizardEnergyV2(HomeWizardEnergy):
119
136
  cloud_enabled: bool | None = None,
120
137
  status_led_brightness_pct: int | None = None,
121
138
  api_v1_enabled: bool | None = None,
139
+ power_on: bool | None = None,
140
+ switch_lock: bool | None = None,
122
141
  ) -> System:
123
142
  """Return the system object."""
124
143
 
144
+ if (
145
+ (power_on is not None or switch_lock is not None)
146
+ and self._device is not None
147
+ and self._device.supports_state() is False
148
+ ):
149
+ raise UnsupportedError("Setting power_on or switch_lock is not supported")
150
+
125
151
  if (
126
152
  cloud_enabled is not None
127
153
  or status_led_brightness_pct is not None
128
154
  or api_v1_enabled is not None
155
+ or power_on is not None
156
+ or switch_lock is not None
129
157
  ):
130
158
  data = SystemUpdate(
131
159
  cloud_enabled=cloud_enabled,
132
160
  status_led_brightness_pct=status_led_brightness_pct,
133
161
  api_v1_enabled=api_v1_enabled,
162
+ power_on=power_on,
163
+ switch_lock=switch_lock,
134
164
  ).to_dict()
135
165
  status, response = await self._request(
136
166
  "/api/system", method=METH_PUT, data=data
@@ -247,33 +277,36 @@ class HomeWizardEnergyV2(HomeWizardEnergy):
247
277
  Get a clientsession that is tuned for communication with the HomeWizard Energy Device
248
278
  """
249
279
 
250
- def _build_ssl_context() -> ssl.SSLContext:
251
- context = ssl.create_default_context(cadata=CACERT)
252
- context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member
253
- if self._identifier is not None:
254
- context.hostname_checks_common_name = True
255
- else:
256
- context.check_hostname = False # Skip hostname validation
257
- context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active
258
- return context
259
-
260
280
  # Creating an SSL context has some blocking IO so need to run it in the executor
261
281
  loop = asyncio.get_running_loop()
262
- return await loop.run_in_executor(None, _build_ssl_context)
282
+ return await loop.run_in_executor(
283
+ None, create_ssl_context, self._identifier is not None
284
+ )
263
285
 
264
286
  @backoff.on_exception(backoff.expo, RequestError, max_tries=3, logger=None)
265
287
  async def _request(
266
288
  self, path: str, method: str = METH_GET, data: object = None
267
289
  ) -> tuple[HTTPStatus, dict[str, Any] | None]:
268
- """Make a request to the API."""
290
+ """Make a request to the API, one request at a time.
269
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
+ """
270
297
  async with self._lock:
271
- if self._session is None:
272
- await self._create_clientsession()
298
+ return await self._request_unlocked(path, method, data)
273
299
 
274
- async with self._lock:
275
- if self._ssl is False:
276
- self._ssl = await self._get_ssl_context()
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()
277
310
 
278
311
  # Construct request
279
312
  url = f"https://{self.host}{path}"
@@ -287,15 +320,17 @@ class HomeWizardEnergyV2(HomeWizardEnergy):
287
320
 
288
321
  try:
289
322
  async with asyncio.timeout(self._request_timeout):
290
- async with self._lock:
291
- resp = await self._session.request(
292
- method,
293
- url,
294
- json=data,
295
- headers=headers,
296
- ssl=self._ssl,
297
- server_hostname=self._identifier,
298
- )
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()
299
334
  LOGGER.debug("%s, %s", resp.status, await resp.text("utf-8"))
300
335
  except TimeoutError as exception:
301
336
  raise RequestError(
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "python-homewizard-energy"
3
- version = "10.2.0"
3
+ version = "10.4.0"
4
4
  description = "Asynchronous Python client for the HomeWizard Energy"
5
5
  authors = ["DCSBL"]
6
6
  maintainers = ["DCSBL"]
@@ -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()