Repository navigation
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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>
|
This probably also replaces #426 |
|
Thanks @lexpostma, tested #644 on my own P1 Meter, both before and after Setup
Run 1 -
Run 2 -
The callback API fits Home Assistant nicely: a coordinator can just register callbacks and react to Observations / questions
Home Assistant |
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>
|
@lexpostma Retested This time two outages, both from my UniFi controller:
94 measurements in 180 s, longest gap ~66 s (the block). No errors, no manual intervention needed. The shorter heartbeat works as intended here. 👍 |
|
Thank you @martin-g-it, both for the first round and for coming back to retest 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.
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. |
|
Thanks @lexpostma, great to read, and happy the retest was useful.
(The elided fields are identical in all messages.) With Home Assistant
Would you prefer that I wait for the release, or is an early draft PR against |
hoefnageltom
left a comment
There was a problem hiding this comment.
Looks good, minor comments
- 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>
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.
Taken over from #426
This also replaces #426. What that PR had and this one lacked is added:
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.api.websocketis a property that creates the client on first use and always returns the same one. It is closed together with the API client.api.tokenandapi.request_timeoutare public properties.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()orevents_typed()still works. Use one of the two. Using both at the same time raises aRuntimeErrorthat 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.
authorizederrormessage ended the streamErrorEventUnauthorizedErrorandUnsupportedErrorend the stream. Every other error is retried with a backoff. A 404 on/api/wsraisesUnsupportedError. The matching on error text is goneclose()didn't stopevents(reconnect=True)and leaked a sessionclose()ends the stream, also while it waits to reconnectRequestErrorUnauthorizedErrorws.connected, andws.on_connection_change(callback)RuntimeErrorwas caught on receiveevent.datawasAnyDeviceEvent,MeasurementEvent,SystemEvent,BatteriesEventandErrorEvent. A message that can't be decoded is logged as a warning and yielded as the base eventSmaller things: the wait for
authorization_requesteduses the request timeout, the change tomodels.pyis 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:
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.
HomeWizardEnergyWebSocketis taken fromapi.websocket, and no longer takeshostandtoken.errormessage no longer raisesRequestErrorfromreceive()andevents().WebSocketDisconnectedError, which is aRequestError.Tests
The tests run against a local aiohttp server that follows the documented flow, instead of mocks. Coverage of
websocket.pyis 100%. They cover an unsupported model, a resubscribe after a reconnect, an error mid-stream, a rejected token, a 404 on/api/ws, andclose()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_MODELSof #643, this addsSUPPORTED_WEBSOCKET_MODELSandDevice.supports_websocket(). Connecting to a model that is not in the list raisesUnsupportedError, without opening a connection. A 4xx on/api/wsraises the same error, except 401, which raisesUnauthorizedError. Both are also raised withreconnect=True.The list follows the WebSocket docs: P1 Meter, kWh Meter and Plug-In Battery.
Tested on hardware
P1 Meter, firmware 6.0503:
HEARTBEAT_INTERVALat that time), and the connection stayed open for 180 seconds.request:unknown-subscriptionasErrorEvent, and the connection stays open.identifyand a request for each topic work.user:unauthorized. That looks the same as a lost connection, so the client then does one HTTP request to/api. A 401 raisesUnauthorizedError; anything else is treated as a lost connection and retried. Confirmed on the device.connected -> disconnected -> connected.Energy Socket, v2 API firmware without WebSocket (PR-601 build):
supports_websocket()is False, and connecting raisesUnsupportedErrorwithout opening a connection./api/wswith 400, not 404. Both now raiseUnsupportedError, 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):
UnauthorizedError.ErrorEvent, and the connection stays open.device,systemanduserare decoded on all three.measurementandbatteriesare decoded on the P1 Meter and the kWh Meter, including battery modepredictive.measurementwithrequest:unknown-type, although it has/api/measurementover HTTP. The client passes this on asErrorEvent.measurementupdates arrived, about one per second, and 17 of 17 HTTP requests succeeded. So subscribing tomeasurementworks on the battery; only the one-off request fails.measurementupdates (one per second), 17 of 17 HTTP requests succeeded.measurementupdates (one per 10 seconds, the rate of the smart meter), 17 of 17 HTTP requests succeeded.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):
receive()while callbacks are in use raises theRuntimeError.measurementupdates, 11 of 11 HTTP requests succeeded.on_errorgotUnauthorizedErrorand receiving stopped. No endless retrying.batteriesis 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_count0).Energy Socket, firmware build PR-606:
UnsupportedError, and HTTP requests are answered normally.Heartbeat
A ping is only sent when no message was received for
HEARTBEAT_INTERVALseconds, and the pong must arrive within half that time. This is how aiohttp'sheartbeatworks. 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_INTERVALis 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:
ws:not-subscribed.🤖 Generated with Claude Code