Skip to content

Only report v2 API support for officially supported models - #643

Merged
lexpostma merged 5 commits into
mainfrom
claude/strict-v2-check-f447be
Nov 26, 2026
Merged

lexpostma merged 5 commits into
mainfrom
claude/strict-v2-check-f447be

Conversation

@lexpostma

@lexpostma lexpostma commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

has_v2_api() returned True for any device that answers 401 on the unauthenticated https://<host>/api, without looking at the product type. So a device that enables the v2 API before it's officially supported (for example with beta firmware) was treated as a v2 device. Home Assistant then offered the "migrate to v2" repair, or went to the v2 authorize step during setup, for devices it can't handle on v2. This was seen with an Energy Socket on beta firmware and an older Home Assistant release.

What changes

  • Allowlist: a new SUPPORTED_V2_MODELS in const.py lists the models this library supports on v2. It follows the device table in the API docs:

    Watermeter and Energy Display ("Planned" / "In development") are left out and keep using v1.

  • Product type from the certificate: the unauthenticated v2 API only answers 401, so the product type is read from the device's HTTPS certificate instead. Its common name is appliance/<type>/<serial>, the same name the v2 client already validates against (see the "SSL Certificate Validation" section of the docs). The certificate is validated against the HomeWizard CA, but the hostname isn't checked.

  • One connection: the separate GET /api request is gone. Only v2 devices serve HTTPS, so a valid certificate is enough. The check is now a single TLS handshake, which matters because devices have very few connection slots. websession is still accepted, but no longer used.

  • Optional product_type: callers that already know the product type, from discovery or an existing config entry, can pass it. Unsupported models then return False without connecting to the device. A device of another product type at that address also returns False.

Effect on Home Assistant

  • No code change needed: both call sites (the repair in __init__.py and async_try_connect in config_flow.py) get the stricter check once HA bumps the library. HA's tests mock has_v2_api.
  • Optional follow-up in HA: pass product_type, taken from the entry's unique_id in the repair check and from the zeroconf properties in discovery.
  • Home Assistant versions that are already released pin an older library version, so they aren't affected unless they get a patch release that bumps the library.

Tests

  • Unit tests cover the allowlist, an unknown or missing certificate type, connection and certificate errors, product_type (supported, unsupported, mismatch), and parsing of the certificate subject.

  • Checked manually against a local TLS server with a self-signed certificate (CN=appliance/energysocket/…). With that certificate trusted, the type is read correctly. With the real HomeWizard CA, the certificate is rejected.

  • Tested against a real Energy Socket on beta firmware with v2 enabled; details are in the test results comment. The certificate is CN=appliance/energysocket/<serial> and validates against the library's CA. has_v2_api returns True on its own and with product_type="HWE-SKT", and False for other product types. A Home Assistant instance kept polling the Socket without errors during the test. Other device types weren't tested on hardware.

🤖 Generated with Claude Code

lexpostma and others added 2 commits November 23, 2026 21:47
has_v2_api returned True for any device that answers 401 on the
unauthenticated https /api endpoint. Devices that enable the v2 API
before it is officially supported (for example with beta firmware) were
therefore treated as v2 devices, and Home Assistant offered to migrate
them to the v2 API.

The unauthenticated v2 endpoint does not tell which product it is, so
read the product type from the device certificate instead. Its common
name is `appliance/<product type>/<serial>` and it is validated against
the HomeWizard CA, without authorization. Only models in the new
SUPPORTED_V2_MODELS allowlist are reported as v2 capable: P1 Meter,
Energy Socket, kWh Meters and Plug-In Battery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Drop the separate unauthenticated `GET /api` request: only v2 devices
serve HTTPS, so a certificate that validates against the HomeWizard CA
is enough to know the device runs the v2 API. This halves the number of
connections, which matters because devices have very few connection
slots. The websession argument is no longer used and only kept for
backwards compatibility.

Add an optional product_type argument for callers that already know it
(discovery or an existing configuration). Unsupported models return
False without connecting to the device, and a device of another product
type at this host returns False as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.32%. Comparing base (ebe44f7) to head (01c7075).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #643      +/-   ##
==========================================
+ Coverage   99.28%   99.32%   +0.03%     
==========================================
  Files           9        9              
  Lines         704      741      +37     
  Branches       70       78       +8     
==========================================
+ Hits          699      736      +37     
  Misses          2        2              
  Partials        3        3              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lexpostma

Copy link
Copy Markdown
Member Author

Tested against a real Energy Socket

Device: Energy Socket (HWE-SKT) with v2 enabled on beta firmware. Its mDNS record advertises api_version=2.3.0. Code: this branch, with no mocks.

Certificate (openssl s_client with the library's CACERT and -partial_chain):

  • Subject: CN=appliance/energysocket/5c2faf46522a
  • Issuer: C=NL, ST=ZH, O=HomeWizard, CN=Appliance Access CA
  • Validates against the library's CA (verify return code 0)
  • SAN: DNS:5c2faf46522a.energysocket.device.homewizard.energy
  • Protocol: TLSv1.2

has_v2_api results:

Call Result Time
_get_certificate_product_id(host) energysocket 820 ms
has_v2_api(host) True 794 ms
has_v2_api(host, websession) True 735 ms
has_v2_api(host, product_type="HWE-SKT") True 799 ms
product_type="HWE-P1" / "HWE-KWH1" / "HWE-BAT" (type mismatch) False ~790 ms
product_type="HWE-WTR" / "HWE-DSP" (not supported on v2) False 0 ms, no connection
Unreachable address False 1.0 s
20 calls in a row 20/20 True 806 ms on average

Effect on the device:

  • For comparison, the old check (unauthenticated GET /api) took 937 ms on average on the same Socket. The new check uses one TLS handshake and is slightly faster.
  • A Home Assistant instance with a v2 config entry for this Socket kept polling it throughout the test. All 24 polls in that window succeeded, the slowest taking 1.2 s.

Not tested on other device types. The battery, P1 and kWh Meter certificate names come from the API docs and from get_verification_hostname().

🤖 Generated with Claude Code

@lexpostma
lexpostma marked this pull request as ready for review November 24, 2026 08:07
@lexpostma

Copy link
Copy Markdown
Member Author

Setup tested in Home Assistant, including the button press

Setup: a Home Assistant dev instance (dev branch) running this PR's library, and the same Energy Socket with v2 enabled on beta firmware. I deleted its existing config entry and added it again by IP through Add device.

Time (UTC) What happened
08:10:59 IP submitted. has_v2_api returned True, so the flow went to the Authorize step.
08:10:59–08:11:03 POST /api/user → 403 user:creation-not-enabled three times (button not pressed yet, as expected)
08:11:05 Button pressed on the Socket. POST /api/user → 200, token received.
08:11:06 New config entry HWE-SKT_<serial> created with IP and token: 1 device, 19 entities, same as before
from 08:11:13 Every poll of /api/measurement and /api/system succeeds
  • No "migrate to v2" repair issue was created.
  • The only warning in the log is the expected "Skipping requirement python-homewizard-energy==10.3.0", because the library was installed from this branch.

🤖 Generated with Claude Code

@hoefnageltom hoefnageltom left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some things to take in consideration

Comment thread homewizard_energy/__init__.py Resolved
Comment thread homewizard_energy/__init__.py Resolved
Comment thread homewizard_energy/__init__.py Resolved
Comment thread homewizard_energy/__init__.py Resolved
Comment thread homewizard_energy/__init__.py Resolved
…ates

- Send GET /api over the same TLS connection and require 401 Unauthorized,
  as some firmware serves a valid certificate without the v2 API.
- Accept certificates with `appliance/generic/<serial>`, as used by early
  batteries that do serve the v2 API, instead of reporting them as not v2.
- Wait for the connection to close, ignoring errors while closing.
- Only catch OSError (includes SSL errors and timeouts) instead of Exception.
- Share the SSL context with HomeWizardEnergyV2 via create_ssl_context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lexpostma

Copy link
Copy Markdown
Member Author

Review changes, tested against a P1 Meter, the Energy Socket and 4 batteries

Commit 4a659bd addresses the review:

  • After reading the certificate, GET /api is sent over the same TLS connection, and the device must respond with 401 Unauthorized. This rejects firmware that serves a valid certificate without the v2 API. It's still one connection.
  • Certificates with appliance/generic/<serial> are now accepted (see below).
  • The connection is closed with wait_closed().
  • Only OSError is caught. That includes SSL errors, connection errors and timeouts.
  • The SSL context is shared with HomeWizardEnergyV2 through create_ssl_context().

Results with this commit (no mocks):

Device Certificate id GET /api has_v2_api With product_type
P1 Meter (HWE-P1, firmware 6.0503) p1dongle 401 True, 20/20, avg 867 ms HWE-P1 True. HWE-SKT, HWE-KWH1, HWE-BAT False. HWE-WTR, HWE-DSP False without connecting
Energy Socket (HWE-SKT, beta) energysocket 401 True, 20/20, avg 832 ms HWE-SKT True, others False
3 Plug-In Batteries (API 2.0.1) battery 401 True HWE-BAT True, HWE-P1 False
1 Plug-In Battery (API 2.0.1, serial 3c39e7…) generic 401 True HWE-BAT True, HWE-P1 True

Finding: the battery with a generic certificate. One battery has CN=appliance/generic/3c39e7……, with no SAN, valid 2019–2034. Its mDNS record has product_type=HWE-BAT and id=appliance/generic/…. It serves the v2 API and works in HA today. The previous commit returned False for it, a regression compared to main. A generic certificate doesn't tell the product type, so for these devices the check now relies on the 401 response and on product_type when it's passed. Without product_type the result is the same as on main.

Not tested: the old Socket firmware that has a certificate without the v2 API. It's covered by unit tests for 404, 200 and empty responses.

Side note, not changed in this PR: for that battery, get_verification_hostname() gives appliance/battery/<serial>, which doesn't match its certificate. So passing identifier to HomeWizardEnergyV2 would make hostname validation fail. HA doesn't pass it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lexpostma

Copy link
Copy Markdown
Member Author

Follow-up: firmware 4.1101 and development units

Generic certificates. These are development units. 34a771a rewords the code comments, and the behaviour stays the same. I kept the support so development units keep working on v2 in Home Assistant: a battery has no v1 API to fall back to. Users don't have these units, so for them the check isn't any less strict. This corrects my earlier comment: the previous commit was only a regression for development units.

Firmware 4.1101 (current external beta), on the same Energy Socket:

  • With v1 disabled, with v1 enabled, and after a power cycle, only port 80 is open. I scanned ports 1–10000.
  • Port 443 refuses connections, and there's no _homewizard._tcp record.
  • So the Socket doesn't serve HTTPS and sends no certificate. has_v2_api returns False in about 15 ms, and setup falls back to v1.

Still untested: firmware where HTTPS is running and the certificate is sent, but without the v2 handlers. For that case the check relies on GET /api not returning 401. @hoefnageltom, do you know a build or a unit where port 443 is open without the v2 API? Then we can test that too.

Keep this branch's has_v2_api. It no longer sends the aiohttp request that
#640 fixed the timeout of; the TLS connection and the GET /api response use
asyncio.wait_for with a 5 second timeout instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lexpostma
lexpostma merged commit 90dc57d into main Nov 26, 2026
32 of 33 checks passed
@lexpostma
lexpostma deleted the claude/strict-v2-check-f447be branch November 26, 2026 11:01
lexpostma added a commit that referenced this pull request Nov 26, 2026
…rejected token

Found by testing on a P1 Meter (firmware 6.0503):
- The device closes the connection when the token is not accepted, instead
  of sending an error. This now raises UnauthorizedError
- A failed connect left the session of the WebSocket open

The Energy Socket gets the v2 API before it gets a WebSocket, so add
SUPPORTED_WEBSOCKET_MODELS and Device.supports_websocket(), in line with
SUPPORTED_V2_MODELS of #643. Connecting to another model raises
UnsupportedError without opening a connection.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants