Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 121 additions & 22 deletions homewizard_energy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
"""HomeWizard Energy API library."""

from aiohttp import ClientSession, ClientTimeout
import asyncio
from contextlib import suppress
from typing import Any

from aiohttp import ClientSession

from .const import MODEL_TO_ID, SUPPORTED_V2_MODELS
from .errors import DisabledError, InvalidStateError, RequestError, UnsupportedError
from .homewizard_energy import HomeWizardEnergy
from .v1 import HomeWizardEnergyV1
from .v2 import HomeWizardEnergyV2
from .v2 import HomeWizardEnergyV2, create_ssl_context

__all__ = [
"DisabledError",
Expand All @@ -17,28 +22,122 @@
"UnsupportedError",
]

# Product type identifiers as used in the device certificate,
# for the models that are supported via the v2 API
SUPPORTED_V2_CERTIFICATE_IDS = frozenset(
MODEL_TO_ID[model] for model in SUPPORTED_V2_MODELS
)

# Development units have a certificate without product type,
# formatted as `appliance/generic/<serial>`
GENERIC_CERTIFICATE_ID = "generic"

# Timeout in seconds for connecting to the device and for its response
TIMEOUT = 5


def _get_certificate_product_id(certificate: dict[str, Any] | None) -> str | None:
"""Get the product type identifier from a device certificate.

The common name of the certificate is formatted as
`appliance/<product type identifier>/<serial>`, see `MODEL_TO_ID`.
"""
for rdn in (certificate or {}).get("subject", ()):
for key, value in rdn:
if key != "commonName":
continue
parts = value.split("/")
if len(parts) == 3 and parts[0] == "appliance":
return parts[1]

return None

async def has_v2_api(host: str, websession: ClientSession | None = None) -> bool:
"""Check if the device has support for the v2 api."""
websession_provided = websession is not None
if websession is None:
websession = ClientSession()

async def _get_v2_product_id(host: str) -> str | None:
"""Get the product type identifier of a device that serves the v2 API.

Only devices with the v2 API serve HTTPS with a valid device certificate,
which contains the product type identifier. Some firmware serves this
certificate without the v2 API, so also check that the API responds to a
request without a token with 401 Unauthorized.

This works without authorization, and needs only a single connection,
as devices have very few connection slots.
"""
loop = asyncio.get_running_loop()
# Creating an SSL context has some blocking IO so need to run it in the executor
context = await loop.run_in_executor(None, create_ssl_context, False)

reader, writer = await asyncio.wait_for(
asyncio.open_connection(host, 443, ssl=context), timeout=TIMEOUT
)
try:
# v2 api is https only and returns a 401 Unauthorized when no key provided,
# no connection can be made if the device is not v2
url = f"https://{host}/api"
res = await websession.get(
url,
ssl=False,
raise_for_status=False,
timeout=ClientTimeout(total=5),
product_id = _get_certificate_product_id(writer.get_extra_info("peercert"))
if product_id is None:
return None

host_header = f"[{host}]" if ":" in host else host
request = (
f"GET /api HTTP/1.1\r\nHost: {host_header}\r\nConnection: close\r\n\r\n"
)
res.close()
writer.write(request.encode())
await writer.drain()
status_line = await asyncio.wait_for(reader.readline(), timeout=TIMEOUT)
finally:
writer.close()
# Closing raises an SSL error when the rest of the response is not read yet
with suppress(OSError):
await asyncio.wait_for(writer.wait_closed(), timeout=TIMEOUT)

# Status line is formatted as `HTTP/1.1 401 Unauthorized`
parts = status_line.split()
if len(parts) < 2 or parts[1] != b"401":
return None

return res.status == 401
except Exception: # pylint: disable=broad-except
# all other status/exceptions means the device is not v2 or not reachable at this time
return product_id


async def has_v2_api(
host: str,
websession: ClientSession | None = None,
product_type: str | None = None,
) -> bool:
"""Check if the device has support for the v2 api.

Only returns True for models that are supported via the v2 API by this
version of the library (see `SUPPORTED_V2_MODELS`), so devices that enable
the v2 API before it is officially supported keep using the v1 API.

The product type is read from the device certificate, and the device must
respond to a request without a token with 401 Unauthorized. Pass `product_type`
when it is already known (e.g. from discovery or an existing configuration):
unsupported models then return False without connecting to the device, and
a device of another product type at this host returns False as well.
Development units have a generic certificate without product type; those
are reported as v2 capable when they serve the v2 API and `product_type`,
when passed, is supported.

`websession` is no longer used and only kept for backwards compatibility.
"""
del websession # Kept for backwards compatibility

if product_type is not None and product_type not in SUPPORTED_V2_MODELS:
return False
finally:
if not websession_provided:
await websession.close()

try:
product_id = await _get_v2_product_id(host)
except OSError:
# Includes SSL errors and timeouts. No (valid) HTTPS connection means
# the device is not v2 or not reachable at this time
return False

if product_id == GENERIC_CERTIFICATE_ID:
# The certificate of a development unit doesn't tell the product type,
# so rely on the `product_type` that passed the check above, or on the
# API response
return True

if product_type is not None:
return product_id == MODEL_TO_ID[product_type]

return product_id in SUPPORTED_V2_CERTIFICATE_IDS
16 changes: 16 additions & 0 deletions homewizard_energy/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ class Model(StrEnum):
Model.BATTERY: "battery",
}

# Models that are supported via the v2 API by this version of the library.
# Keep in sync with https://api-documentation.homewizard.com/docs/introduction#devices
# Devices of other models may enable the v2 API (e.g. with beta firmware), but are
# not reported as v2 capable by `has_v2_api` until they are added here.
SUPPORTED_V2_MODELS = frozenset(
{
Model.P1_METER,
Model.ENERGY_SOCKET,
Model.ENERGY_METER_1_PHASE,
Model.ENERGY_METER_3_PHASE,
Model.ENERGY_METER_EASTRON_SDM230,
Model.ENERGY_METER_EASTRON_SDM630,
Model.BATTERY,
}
)

MODEL_TO_NAME = {
Model.P1_METER: "P1 Meter",
Model.ENERGY_SOCKET: "Energy Socket",
Expand Down
31 changes: 20 additions & 11 deletions homewizard_energy/v2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@
T = TypeVar("T")


def create_ssl_context(validate_hostname: bool) -> ssl.SSLContext:
"""Create an SSL context that validates the certificate of a device.

The hostname is only validated when `validate_hostname` is set, as it is based
on the device identifier. Creating an SSL context has some blocking IO, so
call this in the executor.
"""
context = ssl.create_default_context(cadata=CACERT)
context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member
if validate_hostname:
context.hostname_checks_common_name = True
else:
context.check_hostname = False # Skip hostname validation
context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active
return context


def authorized_method(
func: Callable[..., Coroutine[Any, Any, T]],
) -> Callable[..., Coroutine[Any, Any, T]]:
Expand Down Expand Up @@ -260,19 +277,11 @@ async def _get_ssl_context(self) -> ssl.SSLContext:
Get a clientsession that is tuned for communication with the HomeWizard Energy Device
"""

def _build_ssl_context() -> ssl.SSLContext:
context = ssl.create_default_context(cadata=CACERT)
context.verify_flags = ssl.VERIFY_X509_PARTIAL_CHAIN # pylint: disable=no-member
if self._identifier is not None:
context.hostname_checks_common_name = True
else:
context.check_hostname = False # Skip hostname validation
context.verify_mode = ssl.CERT_REQUIRED # Keep SSL verification active
return context

# Creating an SSL context has some blocking IO so need to run it in the executor
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, _build_ssl_context)
return await loop.run_in_executor(
None, create_ssl_context, self._identifier is not None
)

@backoff.on_exception(backoff.expo, RequestError, max_tries=3, logger=None)
async def _request(
Expand Down
Loading
Loading