Repository navigation
Conversation
|
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. ScriptDetails#!/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
left a comment
There was a problem hiding this comment.
Seems legit, and worked on my system
|
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. |
|
Looks like @DCSBL is/was the main maintainer of the repo. |
|
I recently left HomeWizard, leaving maintenance to my former colleagues. @lexpostma, could you see if you can add this to a sprint sometime? |
lexpostma
left a comment
There was a problem hiding this comment.
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
-
Subscriptions are lost after a reconnect.
events(reconnect=True)reconnects and authorizes again, but never sends thesubscribemessages 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 insubscribe()andunsubscribe(), and sending them again inconnect()afterauthorized, fixes it. The earlierwebsocket-bare-minimumbranch in this repo already does this in_on_authorized, so it may be a useful reference. -
Any error frame ends the event stream, even with
reconnect=True._receive_messageraises 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")makesevents()raiserequest:unknown-subscriptionbefore it yields a single event. Could errors only be fatal during the handshake, and be yielded as events after that? -
Errors that won't go away are retried forever. A device without
/api/wsanswers the upgrade with a 404. aiohttp raisesWSServerHandshakeError, which is aClientError, so_is_transient_errortreats 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 raiseUnsupportedError. 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. -
close()doesn't stop a runningevents(reconnect=True)loop. The pending receive gets a CLOSED frame, which counts as temporary, so the loop reconnects. Becauseclose()cleared the owned session, it creates a newClientSessionthat is never closed (#L213-L220). A closing flag thatevents()andconnect()check would solve this.
Should change
-
A rejected token raises
RequestError("user:unauthorized")instead ofUnauthorizedError. Home Assistant starts its reauthentication flow onUnauthorizedError, so mapping this during the handshake is important for the integration. -
The caller can't see the connection state. With
reconnect=Truethe 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. -
Catching
RuntimeErrorin_receive_ws_messageis too broad (#L236). aiohttp raises it for two concurrentreceive()calls. That becomes "WebSocket receive failed", which counts as temporary, so a healthy socket gets torn down. -
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()passesself._session, which isNoneuntil the first HTTP request (v2/init.py#L324). Whether the session is shared therefore depends on the order of calls._get_ssl_contextand_create_clientsessionare copies of the HTTP client's versions, and the SSL context is built again for each WebSocket. Passing the parent client, as thewebsocket-bare-minimumbranch 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.
-
Typing.
HomeWizardEnergyWebSocketEvent.dataisAnyandtypeisstr, so type checkers can't narrowevent.data.power_wfrom the README. When decoding fails, a plaindictis 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. -
Heartbeat.
heartbeat=30relies 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, soself._request_timeoutis enough. receive_typed()andevents_typed()decode events the same way; a shared helper would remove the duplication.- In
connect(), each of the threeexceptbranches calls_close_ws(ws)and then_reset_ws(). - The change to
models.pyonly reformats code thatruff formatonmainalready 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.
|
@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. |
|
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. |
|
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. |
Summary
This PR adds HomeWizard v2 WebSocket support (
/api/ws) with authentication, reconnect handling, typed events, docs, and tests.Added
HomeWizardEnergyWebSocketclient inhomewizard_energy/v2/websocket.pyHomeWizardEnergyV2.websocket()helper to create a websocket clientHomeWizardEnergyWebSocketWebSocketTopicHomeWizardEnergyWebSocketEventWebSocket behavior
wss://<host>/api/wsauthorization_requestedauthorizationwith tokenauthorizedUnauthorizedErrorwhen missing)self._wsafter auth completesAPI additions
send,receive,events,subscribe,unsubscribe,identify,requestreceive_typed()events_typed(reconnect=...)WebSocketTopicenum for topic-safe subscribe/request callsdevice->Devicemeasurement->Measurementsystem->Systembatteries->BatteriesError handling / lifecycle
RequestError{ "type": "error" }payloads asRequestErrorDocumentation
README.mdwebsocket example to use typed API (WebSocketTopic,events_typed)Tests
Added
tests/v2/test_v2_websocket.pycovering: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✅Fixes #599