Skip to content

feat(v2): add websocket client with typed events, reconnect, and tests - #602

Closed
tomquist wants to merge 1 commit into
homewizard:mainfrom
tomquist:feat/websocket-support
Closed

tomquist wants to merge 1 commit into
homewizard:mainfrom
tomquist:feat/websocket-support

Conversation

@tomquist

@tomquist tomquist commented Mar 5, 2026 •

Copy link
Copy Markdown

Summary

This PR adds HomeWizard v2 WebSocket support (/api/ws) with authentication, reconnect handling, typed events, docs, and tests.

Added

  • New HomeWizardEnergyWebSocket client in homewizard_energy/v2/websocket.py
  • HomeWizardEnergyV2.websocket() helper to create a websocket client
  • Public exports:
    • HomeWizardEnergyWebSocket
    • WebSocketTopic
    • HomeWizardEnergyWebSocketEvent

WebSocket behavior

  • Connects to wss://<host>/api/ws
  • Handshake flow:
    • wait for authorization_requested
    • send authorization with token
    • require authorized
  • Token is required (UnauthorizedError when missing)
  • Keeps handshake serialized under lock and only exposes self._ws after auth completes
  • Handles dropped connections with reconnect/backoff
    • exponential backoff with jitter
    • avoids reconnect loops for externally owned + closed sessions

API additions

  • Raw API remains available:
    • send, receive, events, subscribe, unsubscribe, identify, request
  • Typed API added:
    • receive_typed()
    • events_typed(reconnect=...)
    • WebSocketTopic enum for topic-safe subscribe/request calls
  • Best-effort model decoding for known topics:
    • device -> Device
    • measurement -> Measurement
    • system -> System
    • batteries -> Batteries

Error handling / lifecycle

  • Normalizes websocket receive/send failures to RequestError
  • Handles websocket { "type": "error" } payloads as RequestError
  • Guards against shared-session lifecycle issues and clarifies ownership in docs
  • Serializes close/reconnect teardown with lock

Documentation

  • Updated README.md websocket example to use typed API (WebSocketTopic, events_typed)

Tests

Added tests/v2/test_v2_websocket.py covering:

  • token requirement and handshake
  • invalid handshake
  • helper payloads for subscribe/unsubscribe/identify/request
  • websocket error payload handling
  • invalid JSON shape handling
  • reconnect on dropped socket
  • reconnect after transient connect failure
  • no reconnect when externally owned session is closed
  • typed event decoding

Note that I wasn't able to test this change E2E because I don't own a HomeWizard device.

Validation

  • pre-commit run --all-files ✅
  • websocket/v2 targeted tests pass locally

Fixes #599

@thomwiggers

Copy link
Copy Markdown

I tested this PR using the Claude-written script below against my P1 meter and it seemed to work great! It would be nice if this could be merged, as this could unlock much better integration with HomeAssistant.

Script

Details
#!/usr/bin/env python3
"""Manual end-to-end test for HomeWizardEnergyWebSocket against a real device.

Not part of the pytest suite -- run directly against real hardware.

Usage:
    poetry run python scripts/e2e_websocket.py --host 192.168.1.123
    poetry run python scripts/e2e_websocket.py --host 192.168.1.123 --token <token>

If no --token is given, the script polls the device for one following the
v2 authorization flow (see
https://api-documentation.homewizard.com/docs/v2/authorization): it keeps
requesting a token, the device rejects each attempt with 403 until you
press the physical pairing button, then the next poll within ~30s of the
press receives the token. Local API (v2) must already be enabled in the
HomeWizard app (device settings > Local API).
"""

from __future__ import annotations

import argparse
import asyncio
import logging
import sys

from homewizard_energy import HomeWizardEnergyV2, WebSocketTopic
from homewizard_energy.errors import DisabledError, RequestError, UnauthorizedError

LOGGER = logging.getLogger("e2e_websocket")


async def get_or_request_token(
    api: HomeWizardEnergyV2, token: str | None, poll_timeout: float = 60.0
) -> str:
    """Return the given token, or poll the device for a new one.

    Per the HomeWizard v2 authorization flow, the device rejects the
    request with a 403 (DisabledError here) until the user presses the
    physical button. The client is expected to keep polling -- each poll
    resets the device's wait timer -- and once the button is pressed there
    is a 30s window in which a poll must land to receive the token.
    """
    if token is not None:
        return token

    print(
        "Requesting token; press the device's pairing button now (P1 meter: "
        "brief press; kWh meter: 1-3s press). Polling...",
        file=sys.stderr,
    )

    deadline = asyncio.get_running_loop().time() + poll_timeout
    while True:
        try:
            token = await api.get_token(name="e2e-websocket-script")
        except DisabledError:
            if asyncio.get_running_loop().time() >= deadline:
                print(
                    f"Gave up after {poll_timeout:.0f}s waiting for button press.",
                    file=sys.stderr,
                )
                raise
            await asyncio.sleep(1.0)
            continue
        break

    print(f"Got token: {token}", file=sys.stderr)
    print("(pass --token next time to skip pairing)", file=sys.stderr)
    return token


async def run(host: str, token: str | None, duration: float | None) -> None:
    """Connect, subscribe to all topics, and print events until interrupted."""
    async with HomeWizardEnergyV2(host=host, token=token) as api:
        await get_or_request_token(api, token)

        print(f"Device info: {await api.device()}", file=sys.stderr)

        async with api.websocket() as ws:
            await ws.subscribe(WebSocketTopic.ALL)
            print("Subscribed to all topics, waiting for events (Ctrl+C to stop)...")

            async def consume() -> None:
                async for event in ws.events_typed(reconnect=True):
                    print(f"[{event.type}] {event.data}")

            if duration is None:
                await consume()
            else:
                try:
                    await asyncio.wait_for(consume(), timeout=duration)
                except asyncio.TimeoutError:
                    print(f"Stopping after {duration}s", file=sys.stderr)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--host", required=True, help="Device IP address or hostname")
    parser.add_argument(
        "--token", default=None, help="Existing API token (skips pairing)"
    )
    parser.add_argument(
        "--duration",
        type=float,
        default=None,
        help="Stop after N seconds (default: run until Ctrl+C)",
    )
    parser.add_argument("--debug", action="store_true", help="Enable debug logging")
    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.debug else logging.INFO,
        format="%(asctime)s %(name)s %(levelname)s %(message)s",
    )

    try:
        asyncio.run(run(args.host, args.token, args.duration))
    except KeyboardInterrupt:
        pass
    except (RequestError, UnauthorizedError, DisabledError) as ex:
        print(f"Error: {ex}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

@thomwiggers thomwiggers left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Seems legit, and worked on my system

@martin-g-it

Copy link
Copy Markdown

Anything needed to get this one moving @tomquist @thomwiggers ? Happy to support.

@thomwiggers

Copy link
Copy Markdown

Anything needed to get this one moving @tomquist @thomwiggers ? Happy to support.

Neither of us have permissions in this repository, you're barking up the wrong tree.

@tomquist

Copy link
Copy Markdown
Author

Looks like @DCSBL is/was the main maintainer of the repo.

@DCSBL

DCSBL commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

I recently left HomeWizard, leaving maintenance to my former colleagues. @lexpostma, could you see if you can add this to a sprint sometime?

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

Hi @tomquist, thank you for this PR, and for the thorough description and tests. Real-time updates over the WebSocket are something a lot of people have asked for, so this is a very welcome contribution. Thanks also to @thomwiggers for testing it on a real P1 Meter.

The overall shape works well: the handshake follows the WebSocket docs, _ws is only exposed after authorization, the backoff has jitter, TLS is set up the same way as the HTTP client, and externally owned sessions are respected. It also still merges cleanly with main, and the full test suite passes after the merge.

I ran the client against a local aiohttp server that follows the documented /api/ws flow. That turned up a few problems in the reconnect and error handling that the mocked tests can't see. I'm happy to share the script if it helps.

Needs a change before merging

  1. Subscriptions are lost after a reconnect. events(reconnect=True) reconnects and authorizes again, but never sends the subscribe messages again (websocket.py#L367-L409). Subscriptions belong to a connection, so after a drop the stream goes quiet without an error. In my test the first connection delivered events and the second delivered none. The README example is exactly this case. Keeping the topics in a set in subscribe() and unsubscribe(), and sending them again in connect() after authorized, fixes it. The earlier websocket-bare-minimum branch in this repo already does this in _on_authorized, so it may be a useful reference.

  2. Any error frame ends the event stream, even with reconnect=True. _receive_message raises on every {"type": "error"} frame (#L258-L262). The device doesn't say which command an error answers, and the connection stays open. For example, subscribe("bogus") makes events() raise request:unknown-subscription before it yields a single event. Could errors only be fatal during the handshake, and be yielded as events after that?

  3. Errors that won't go away are retried forever. A device without /api/ws answers the upgrade with a 404. aiohttp raises WSServerHandshakeError, which is a ClientError, so _is_transient_error treats it as temporary (#L352-L365). In my test it retried 120 times, with backoffs up to 30 seconds, without surfacing an error. This matters soon: the Energy Socket is getting the v2 API (#641, #643), but its WebSocket support is still planned. A 404 should raise UnsupportedError. More generally, matching substrings of error messages (TRANSIENT_PATTERNS) is fragile, because any message that contains "closed" or "timeout" is retried. A dedicated exception for "disconnected", raised where the connection actually drops, would be more robust.

  4. close() doesn't stop a running events(reconnect=True) loop. The pending receive gets a CLOSED frame, which counts as temporary, so the loop reconnects. Because close() cleared the owned session, it creates a new ClientSession that is never closed (#L213-L220). A closing flag that events() and connect() check would solve this.

Should change

  1. A rejected token raises RequestError("user:unauthorized") instead of UnauthorizedError. Home Assistant starts its reauthentication flow on UnauthorizedError, so mapping this during the handshake is important for the integration.

  2. The caller can't see the connection state. With reconnect=True the client retries without limit and without notice, so Home Assistant can't mark entities as unavailable during an outage. A connection state callback or event would help. Leaving reconnecting to the caller is also fine.

  3. Catching RuntimeError in _receive_ws_message is too broad (#L236). aiohttp raises it for two concurrent receive() calls. That becomes "WebSocket receive failed", which counts as temporary, so a healthy socket gets torn down.

  4. Connections and session sharing. Devices only have a few connection slots. We're working on this from two sides: #642 keeps HTTP traffic to one connection per device, and a firmware update will give the Energy Socket more room and let it close idle connections when a new client connects. A WebSocket still permanently holds a connection next to the HTTP one, so it's good to keep the client's footprint small. Related points:

    • HomeWizardEnergyV2.websocket() passes self._session, which is None until the first HTTP request (v2/init.py#L324). Whether the session is shared therefore depends on the order of calls.
    • _get_ssl_context and _create_clientsession are copies of the HTTP client's versions, and the SSL context is built again for each WebSocket. Passing the parent client, as the websocket-bare-minimum branch does, would reuse both.

    For what it's worth, I checked that sharing the session doesn't block HTTP requests while the WebSocket is open.

  5. Typing. HomeWizardEnergyWebSocketEvent.data is Any and type is str, so type checkers can't narrow event.data.power_w from the README. When decoding fails, a plain dict is returned silently (#L291-L295), so callers sometimes get a model and sometimes a dict. Separate event types per topic, or at least a warning log, would make this safer.

  6. Heartbeat. heartbeat=30 relies on the firmware answering WebSocket pings. We'll confirm this on the P1 Meter, kWh Meter and Plug-In Battery on our side.

Smaller things

  • The handshake waits 40 seconds for authorization_requested (#L180). In the docs, 40 seconds is the deadline for the client to send its token; the device sends its request straight away, so self._request_timeout is enough.
  • receive_typed() and events_typed() decode events the same way; a shared helper would remove the duplication.
  • In connect(), each of the three except branches calls _close_ws(ws) and then _reset_ws().
  • The change to models.py only reformats code that ruff format on main already accepts, so it can be dropped.
  • #643 also edits homewizard_energy/__init__.py, so whichever PR lands second needs a small rebase.

Tests

Coverage of websocket.py is 76%. close(), creating an owned session, the context manager, events_typed(), send failures and non-text frames aren't tested yet. Tests against a real aiohttp test server, instead of FakeWebSocket and AsyncMock, would have caught points 1 to 4. It would be great to have tests for a resubscribe after a reconnect, an error frame mid-stream, a rejected token, a 404 on /api/ws, and close() during iteration.

Thanks again for all the work on this. And sorry it took us so long to respond: this PR deserved a review much sooner.

@tomquist

Copy link
Copy Markdown
Author

@lexpostma Thanks for the review. I'm closing the PR, though, because I'm not able to work on this feedback. Feel free to take over the change and bring it over the finish line.

@tomquist tomquist closed this Nov 25, 2026
@lexpostma lexpostma mentioned this pull request Nov 26, 2026
24 tasks done
@lexpostma

Copy link
Copy Markdown
Member

Thanks for the head start, @tomquist. We're picking this up in #644, which builds on your commit so the credit stays with you.

It addresses the points from the review above, and has been tested on a P1 Meter, a kWh Meter and a Plug-In Battery. It's still a draft; feedback from anyone following along here is welcome there.

@lexpostma

Copy link
Copy Markdown
Member

We're picking this up in #644, which continues from this PR. @tomquist, your commit is kept in the history of that branch, so the credit stays with you. Thanks again for getting this started.

#644 addresses the points from the review above, and adds a check for which models have a WebSocket. It is tested on a P1 Meter, a kWh Meter and a Plug-In Battery, including reconnecting after a power cycle.

@thomwiggers and @martin-g-it, if you'd like to try it on your own devices, feedback on #644 is very welcome.

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

5 participants