Skip to content

Add WebSocket client for the v2 API - #644

Open
lexpostma wants to merge 11 commits into
mainfrom
websocket-support
Open

lexpostma wants to merge 11 commits into
mainfrom
websocket-support

Conversation

@lexpostma

@lexpostma lexpostma commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Continues #602 by @tomquist, who asked us to take it over. The original commit is kept in the history of this branch, so the credit stays. Fixes #599.

This adds a client for the WebSocket of the v2 API, to receive real-time updates.

async with HomeWizardEnergyV2(host=IP_ADDRESS, token=TOKEN) as api:
    async with api.websocket as ws:
        await ws.subscribe(WebSocketTopic.MEASUREMENT)

        async for event in ws.events_typed(reconnect=True):
            if isinstance(event, MeasurementEvent):
                print(event.data.power_w)

Taken over from #426

This also replaces #426. What that PR had and this one lacked is added:

  • Callbacks. subscribe(topic, callback) returns a function that removes the callback. With a callback, messages are received in the background, so there is no need to iterate. The callback gets the event, and may be a coroutine function.
  • One WebSocket per API client. api.websocket is a property that creates the client on first use and always returns the same one. It is closed together with the API client.
  • api.token and api.request_timeout are public properties.
def on_measurement(event: MeasurementEvent) -> None:
    print(event.data.power_w)

unsubscribe = await api.websocket.subscribe(WebSocketTopic.MEASUREMENT, on_measurement)

With callbacks the connection is restored when it is lost. An error that does not go away by connecting again, such as a rejected token, ends the background task. It is logged and passed to ws.on_error(callback), so the caller can start a reauthorization.

Iterating with events() or events_typed() still works. Use one of the two. Using both at the same time raises a RuntimeError that explains why.

The callback code is covered by tests against the fake device, and is tested on hardware. See below.

Changes since #602

The numbers refer to the review of #602.

# Problem Now
1 Subscriptions were lost after a reconnect Topics are remembered and sent again after authorized
2 Any error message ended the stream Errors are only fatal during authorization. After that they are yielded as ErrorEvent
3 Errors that won't go away were retried forever Only UnauthorizedError and UnsupportedError end the stream. Every other error is retried with a backoff. A 404 on /api/ws raises UnsupportedError. The matching on error text is gone
4 close() didn't stop events(reconnect=True) and leaked a session close() ends the stream, also while it waits to reconnect
5 A rejected token raised RequestError Raises UnauthorizedError
6 No way to see the connection state ws.connected, and ws.on_connection_change(callback)
7 RuntimeError was caught on receive No longer caught
8 Session and SSL context were duplicated, sharing depended on call order The WebSocket is created from the API client and reuses its SSL context. See below for the session
9 event.data was Any DeviceEvent, MeasurementEvent, SystemEvent, BatteriesEvent and ErrorEvent. A message that can't be decoded is logged as a warning and yielded as the base event

Smaller things: the wait for authorization_requested uses the request timeout, the change to models.py is dropped, and messages that are not a JSON object are skipped with a warning instead of ending the stream.

Session

The review said that sharing the session doesn't block HTTP requests. That turned out to be true only for a session without connection limit. Since #642, the session that the API client creates for itself has limit_per_host=1. An open WebSocket keeps that one connection, so every HTTP request then waits until it times out.

So the WebSocket uses:

  • the session that was passed to the API client, as Home Assistant does, or
  • its own session with one connection, when the API client created its own.

Either way the device sees two connections: one for the WebSocket and one for HTTP.

Breaking changes compared to #602

Nothing of #602 was released, so this only matters to people who run that branch.

  • HomeWizardEnergyWebSocket is taken from api.websocket, and no longer takes host and token.
  • An error message no longer raises RequestError from receive() and events().
  • A lost connection raises WebSocketDisconnectedError, which is a RequestError.

Tests

The tests run against a local aiohttp server that follows the documented flow, instead of mocks. Coverage of websocket.py is 100%. They cover an unsupported model, a resubscribe after a reconnect, an error mid-stream, a rejected token, a 404 on /api/ws, and close() during iteration and during the reconnect wait.

Supported devices

The Energy Socket gets the v2 API before it gets a WebSocket. In line with SUPPORTED_V2_MODELS of #643, this adds SUPPORTED_WEBSOCKET_MODELS and Device.supports_websocket(). Connecting to a model that is not in the list raises UnsupportedError, without opening a connection. A 4xx on /api/ws raises the same error, except 401, which raises UnauthorizedError. Both are also raised with reconnect=True.

The list follows the WebSocket docs: P1 Meter, kWh Meter and Plug-In Battery.

Tested on hardware

P1 Meter, firmware 6.0503:

  • The device answers WebSocket pings: this unit had no smart meter connected and sent no updates, so the client pinged it after every 30 seconds of silence (HEARTBEAT_INTERVAL at that time), and the connection stayed open for 180 seconds.
  • HTTP requests keep working while the WebSocket is open: 17 of 17 succeeded.
  • An unknown topic gives request:unknown-subscription as ErrorEvent, and the connection stays open.
  • identify and a request for each topic work.
  • A rejected token: the device drops the connection without close frame (close code 1006) instead of sending user:unauthorized. That looks the same as a lost connection, so the client then does one HTTP request to /api. A 401 raises UnauthorizedError; anything else is treated as a lost connection and retried. Confirmed on the device.
  • The stream comes back after the device restarts: after a power cycle the client reconnected within 3 seconds of noticing the loss, and all subscribed topics were delivered again. The connection change callback reported connected -> disconnected -> connected.

Energy Socket, v2 API firmware without WebSocket (PR-601 build):

  • supports_websocket() is False, and connecting raises UnsupportedError without opening a connection.
  • The device answers the upgrade on /api/ws with 400, not 404. Both now raise UnsupportedError, so they are not retried.

A second P1 Meter with a smart meter connected (firmware 6.0503), a kWh Meter 1-phase (firmware 5.0200-beta-2) and a Plug-In Battery (firmware 1.1008):

  • A rejected token is handled the same on all three: the connection is dropped with close code 1006, and the client raises UnauthorizedError.
  • An unknown topic gives an ErrorEvent, and the connection stays open.
  • device, system and user are decoded on all three. measurement and batteries are decoded on the P1 Meter and the kWh Meter, including battery mode predictive.
  • The Plug-In Battery answers a request for measurement with request:unknown-type, although it has /api/measurement over HTTP. The client passes this on as ErrorEvent.
  • Plug-In Battery, 180 seconds subscribed to all topics: the connection stayed open. 173 measurement updates arrived, about one per second, and 17 of 17 HTTP requests succeeded. So subscribing to measurement works on the battery; only the one-off request fails.
  • kWh Meter, 180 seconds: the connection stayed open, 179 measurement updates (one per second), 17 of 17 HTTP requests succeeded.
  • P1 Meter with a smart meter, 180 seconds: the connection stayed open, 19 measurement updates (one per 10 seconds, the rate of the smart meter), 17 of 17 HTTP requests succeeded.
  • Plug-In Battery, power cycle: the stream came back with all topics, 2.6 seconds after the client noticed the loss.

Callbacks and the 20-second heartbeat

Tested on the current state of this branch, with all topics received via callbacks, and a HTTP request every 10 seconds next to it. P1 Meter (firmware 6.0503, one with and one without a Plug-In Battery connected), kWh Meter 1-phase (firmware 5.0200-beta-2) and Plug-In Battery (firmware 1.1008):

  • Callbacks receive all topics on all three. Calling receive() while callbacks are in use raises the RuntimeError.
  • kWh Meter, 120 seconds: 120 measurement updates, 11 of 11 HTTP requests succeeded.
  • Plug-In Battery, power cycle: the loss was noticed 27 seconds after the last message, the connection was back 3.4 seconds later, and the callbacks kept receiving.
  • P1 Meter, power cycle: the loss was noticed 25 seconds after the last message, the connection was back 2.9 seconds later, and the callbacks kept receiving.
  • P1 Meter without smart meter, 180 seconds: the device sent nothing after the first messages, so it was pinged after every 20 seconds of silence. The connection stayed open, and 17 of 17 HTTP requests succeeded.
  • P1 Meter, token removed in the app and then a power cycle: reconnecting failed with a rejected token, on_error got UnauthorizedError and receiving stopped. No endless retrying.
  • batteries is only pushed when a value changes: once on connect, and nothing after that in 120 seconds, on a P1 Meter with an idle battery and on one without battery (battery_count 0).

Energy Socket, firmware build PR-606:

  • Connecting raises UnsupportedError, and HTTP requests are answered normally.

Heartbeat

A ping is only sent when no message was received for HEARTBEAT_INTERVAL seconds, and the pong must arrive within half that time. This is how aiohttp's heartbeat works. A device that sends a measurement every second is therefore never pinged, so the runs above only show answered pings for the P1 Meter without smart meter.

A device that loses power or Wi-Fi does not close the connection, so the client only notices after the silence plus the pong timeout. The hardware runs above used 30 seconds, which gives 45 seconds at most; a power cycle of the Plug-In Battery was noticed after about 27 seconds.

After checking with the firmware team, HEARTBEAT_INTERVAL is now 20 seconds. Devices need up to 10 seconds to answer a ping, and that is the pong timeout this gives. A lost connection is noticed within 30 seconds. Both are confirmed on hardware, see above.

Three things that the docs don't mention:

  • Unsubscribing from a topic that was not subscribed gives the error ws:not-subscribed.
  • A rejected token drops the connection without a close frame.
  • Removing a token in the app does not end a WebSocket that was authorized with it. The device kept sending updates, while HTTP requests with that token were rejected. The token is only rejected on the next connect.

🤖 Generated with Claude Code

tomquist and others added 2 commits March 5, 2026 09:03
Continues #602 by @tomquist, merged with main, and reworked after review:

- Subscriptions are restored after a reconnect
- Errors sent by the device are events, and no longer end the stream
- Only a lost connection is retried. A missing WebSocket raises
  UnsupportedError and a rejected token raises UnauthorizedError
- close() ends events(), also while waiting to reconnect
- Connection state is available via a callback and a property
- Events of known topics have their own type
- The WebSocket uses the session passed to the API client, or its own
  session. The session that the API client creates is limited to one
  connection, which the WebSocket would keep occupied
- Tests run against a local server instead of mocks

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.56%. Comparing base (a33b3ba) to head (369a374).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #644      +/-   ##
==========================================
+ Coverage   99.33%   99.56%   +0.23%     
==========================================
  Files           9       10       +1     
  Lines         751     1148     +397     
  Branches       79      130      +51     
==========================================
+ Hits          746     1143     +397     
  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 and others added 4 commits November 26, 2026 13:19
…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>
A P1 Meter (firmware 6.0503) drops the connection without close frame when
it does not accept the token. That can't be told apart from a connection
that is lost for another reason, so do one HTTP request: a 401 raises
UnauthorizedError, anything else is treated as a lost connection.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
An Energy Socket with v2 API firmware, but without WebSocket, answers the
upgrade with 400 instead of 404.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@thomwiggers

Copy link
Copy Markdown

This probably also replaces #426

@martin-g-it

martin-g-it commented Nov 27, 2026 •

Copy link
Copy Markdown

Thanks @lexpostma, tested #644 on my own P1 Meter, both before and after ceeb557.

Setup

  • HWE-P1, firmware 6.0503, API 2.3.0 - supports_websocket() returns True
  • Powered via the HomeWizard Active P1 Splitter, no Plug-In Battery
  • Each run 180 s from a separate container. My Home Assistant was connected to the P1 at the same time (HTTP + a second WebSocket), so 2 WebSockets + HTTP in parallel - no connection issues
  • In each run I forced a Wi-Fi reconnect of the P1 from my UniFi controller (P1 stays powered)

Run 1 - 8316b2d, iterator API
subscribe(WebSocketTopic.ALL) + events_typed(reconnect=True)

  • On subscribe: batteries, device, measurement, system, user (raw list) arrive immediately, decoded to the expected models
  • 149 measurement events (~1/s) and 129 batteries events, although no battery is connected
  • Reconnect: last event 08:20:03, disconnect reported 08:20:34, reconnected 08:20:37, snapshot + measurements resumed at 08:20:40 → resubscribe works

Run 2 - ceeb557, callback API
api.websocket.on_connection_change(...) + subscribe(topic, callback) for MEASUREMENT, SYSTEM and DEVICE

  • 149 measurement events (~1/s), device/system snapshot on (re)connect, no batteries events → per-topic subscription keeps the noise out
  • Reconnect: last event before the drop ~08:42:21, disconnect reported 08:42:53, reconnected 08:42:56, snapshot + measurements resumed immediately → background listener reconnects and resubscribes on its own
  • WebSocket closed together with the API client at the end (connection: DOWN on exit) — as documented
  • No ErrorEvents in either run

The callback API fits Home Assistant nicely: a coordinator can just register callbacks and react to on_connection_change, without its own receive/reconnect loop.

Observations / questions

  • batteries is sent about every second on a P1 without any battery. Is that intended? Not an issue with per-topic subscriptions, but anyone using ALL gets ~2 updates per second.
  • After a Wi-Fi drop the old connection dies silently and is only detected after ~30 s (heartbeat); reconnecting then takes ~3 s. Since measurements arrive every second, a shorter heartbeat or a receive timeout could detect this sooner. Not a blocker for me.

Home Assistant
I have a working (private/patched) WebSocket-first setup for the P1 in Home Assistant: WebSocket for live updates, coordinator HTTP polling disabled while the WebSocket is healthy, and polling resumed automatically on disconnect; other devices (my v1 watermeter) keep normal polling. Once this is released, are you planning to do the Home Assistant integration side yourselves, or would a PR from me be welcome? Happy to align on the approach first.

lexpostma and others added 2 commits November 27, 2026 09:36
Takes over the ideas of #426 that were missing:
- subscribe() accepts a callback and returns a function to remove it.
  With a callback, messages are received in the background.
- api.websocket is a property that always returns the same client, and
  the client is closed together with the API client.
- token and request_timeout are public properties of the API client.

The connection state callback moved to ws.on_connection_change().

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- ws.on_error() gets the error when receiving for the callbacks stops,
  such as a token that got rejected. Before, it was only logged.
- Receiving messages while callbacks are in use, or the other way
  around, raises a RuntimeError with an explanation.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A ping is only sent when nothing was received for this time, and the
pong must arrive within half of it. With 20 seconds the device gets the
10 seconds it needs to answer, and a lost connection is noticed within
30 seconds instead of 45.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@martin-g-it

Copy link
Copy Markdown

@lexpostma Retested 988b30a (confirmed HEARTBEAT_INTERVAL = 20 in the installed package) on the same P1 (fw 6.0503), callback API with MEASUREMENT, SYSTEM and DEVICE, 180 s.

This time two outages, both from my UniFi controller:

  1. Wi-Fi reconnect — disconnect reported ~20 s after the last measurement (was ~30 s with the previous heartbeat), reconnected 4 s later, device/system snapshot and measurements resumed.
  2. Client blocked ~1 minute, then unblocked — disconnect reported ~30 s after the last measurement (20 s + 10 s pong timeout, as described in the commit). After unblocking, reconnected on its own, snapshot received within a second and measurements back at ~1/s.

94 measurements in 180 s, longest gap ~66 s (the block). No errors, no manual intervention needed. The shorter heartbeat works as intended here. 👍

@lexpostma

Copy link
Copy Markdown
Member Author

Thank you @martin-g-it, both for the first round and for coming back to retest 988b30a with two outages. We really appreciate the time you put into this. The run next to Home Assistant, the Wi-Fi reconnect and the blocked client are exactly the cases we had not covered ourselves, and this PR is better for it.

Heartbeat: this improvement is yours. You pointed out that a drop took too long to notice, and you were right. We only needed to check with our firmware team how far we could safely go, which is why it took a few days. Their advice had two parts. A device should get 10 seconds to answer a ping. And the silence before a ping has to be longer than 10 seconds, because older smart meters only send data every 10 seconds, so a P1 Meter on such a meter is quiet that long by design. We chose 20 seconds of silence because aiohttp's built-in heartbeat always gives the device half of that to answer, which is exactly the 10 seconds. A shorter silence would mean writing our own ping logic in place of aiohttp's, and we prefer not to maintain that for a few seconds of gain. Your retest shows it works as intended: about 20 seconds when the device comes back and no longer knows the connection, as with your Wi-Fi reconnect, and 30 seconds when nothing answers at all, as with the blocked client. We saw 25 to 27 seconds on a power cycle here. Thanks for confirming it so quickly.

batteries without a battery: a good observation, and we have not been able to reproduce it. On a P1 Meter without a battery we get batteries once on connect and then nothing, with battery_count: 0. On a unit with batteries it does arrive about every second, and there each message differs from the previous one in target_power_w, which follows the grid power. So it looks like a push on change, and something may still be changing in your setup. Our test meter reports a constant 0 W, so we would not see that here. If you have a moment, could you share three or four consecutive raw batteries messages (ws.events() gives them as received)? That would help us a lot in finding out what happens. In the meantime, subscribing to only the topics you need, as you do now, avoids it.

Home Assistant: we love this idea, and a PR from you would be very welcome. Your setup sounds like the right shape for it: live updates over the WebSocket where real-time matters, such as the 1-second P1 data, and polling over the v2 API for everything else and as fallback. It would also make the integration "local push", which is a nice step up.

One thing we want to be open about: we're still looking into how far we can take WebSocket support on the P1 Meter. The device has a limited number of connections, and HTTPS requests and WebSockets share them. Each connected Plug-In Battery holds one as well. Today Home Assistant uses one connection for polling. With a WebSocket next to it, that becomes two that are open all the time, and with several batteries that adds up. We want to understand those limits before making it the default in Home Assistant. Your approach of pausing polling while the WebSocket is healthy helps here, as long as the HTTPS connection is really closed and not kept alive in between. Polling over the v1 API is not a way around this: it is not secured, and we are moving to the v2 API over HTTPS by default. A small first step, for example only the P1 Meter measurements, would be easiest for us to review. We're happy to think along on the approach whenever you start, and thanks again for all your help.

@martin-g-it

Copy link
Copy Markdown

Thanks @lexpostma, great to read, and happy the retest was useful.

batteries without a battery
Your guess looks right. Six consecutive raw messages (988b30a, ws.events(), subscribed to batteries and measurement), with the grid power in between:

08:22:54 {"type": "batteries", "data": {"mode": "zero", "permissions": ["charge_allowed", "discharge_allowed"], "charge_to_full": false, "battery_count": 0, "power_w": 0, "max_consumption_w": 0, "max_production_w": 0, "target_power_w": -12}}
08:22:54 measurement power_w = 11
08:22:55 measurement power_w = -37
08:22:55 {"type": "batteries", "data": {... "battery_count": 0, ... "target_power_w": 3}}
08:22:56 measurement power_w = -35
08:22:56 {"type": "batteries", "data": {... "battery_count": 0, ... "target_power_w": 20}}
08:22:57 measurement power_w = -40
08:22:57 {"type": "batteries", "data": {... "battery_count": 0, ... "target_power_w": 37}}
08:22:58 measurement power_w = -16
08:22:58 {"type": "batteries", "data": {... "battery_count": 0, ... "target_power_w": 30}}
08:22:59 measurement power_w = 23
08:22:59 {"type": "batteries", "data": {... "battery_count": 0, ... "target_power_w": 11}}

(The elided fields are identical in all messages.) With battery_count: 0 and mode: zero, only target_power_w changes, and it follows the grid power with the opposite sign, about one sample behind. My grid power hovers around 0 W at the moment with a lot of small changes, so the target changes every second as well. On a meter at a constant 0 W you would never see it. Perhaps the firmware could skip the target calculation, or the push, when battery_count is 0? Either way, per-topic subscriptions avoid it on the client side.

Home Assistant
Great, I'll take that on. My plan, aligned with your points:

  • Start once Add WebSocket client for the v2 API #644 is released, on a fresh branch from dev, and keep it small: only a P1 Meter where supports_websocket() is true, and only measurement over the WebSocket. All other devices keep their current polling.
  • Use the callback API: subscribe(MEASUREMENT, ...), on_connection_change to pause and resume polling, and on_error to start a reauth on UnauthorizedError.
  • Verify on my own P1 that the HTTPS connection is really closed while polling is paused, not just idle in a keep-alive pool, before calling it ready.
  • Switch iot_class to local_push.

Would you prefer that I wait for the release, or is an early draft PR against dev welcome so we can discuss the approach in code? Thanks again for the quick follow-ups.

@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.

Looks good, minor comments

Comment thread homewizard_energy/v2/websocket.py Resolved
Comment thread homewizard_energy/v2/websocket.py Resolved
Comment thread homewizard_energy/v2/websocket.py Resolved
Comment thread homewizard_energy/v2/websocket.py Resolved
Comment thread homewizard_energy/v2/websocket.py Resolved
lexpostma and others added 2 commits December 2, 2026 14:06
- Wrap an IPv6 host in brackets in the WebSocket URL.
- Subscribe and unsubscribe while holding the lock, so that a topic that
  is added during a reconnect is not missed.
- Let close() cancel the background task while holding the lock, so that
  it can't wait forever when connect() is called at the same time.
- With reconnect, try again after every error except a rejected token
  and a device without WebSocket.
- Accept status codes that are not known as a HTTP status.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@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.

Looks good to me now

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.

Add WebSocket support for real-time updates

6 participants