I am trying to connect to a Home Assistant WebSocket API using the websockets
package.
I started by just adapting the example in the documentation to what is expected by the API:
import json
from websockets.sync.client import connect
def hello():
with connect("wss://hass.XXX/api/websocket") as ws:
# handshake
ws.send("")
message = ws.recv()
print(f"Received: {message}")
# authentication
ws.send(
json.dumps(
{
"type": "auth",
"access_token": "XXX",
}
)
)
message = ws.recv() # ← this is line 19 mentioned in the Traceback below
print(f"Received: {message}")
hello()
The first connection goes fine, I get the expected reply. When awaiting for the answer to the second request, websockets.exceptions.ConnectionClosedOK
is raised:
Received: {"type":"auth_required","ha_version":"2024.5.2"}
Traceback (most recent call last):
File "c:UsersyopPersodev-persotemphass-labelsget-entities.py", line 23, in <module>
hello()
File "c:UsersyopPersodev-persotemphass-labelsget-entities.py", line 19, in hello
message = ws.recv()
^^^^^^^^^
File "C:UsersyopscoopappspythoncurrentLibsite-packageswebsocketssyncconnection.py", line 201, in recv
raise self.protocol.close_exc from self.recv_events_exc
websockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK)
I do not understand whether it means that the connection was cleanly closed:
- by the server? (in which case it would be weird, but a server problem)
- by the client (my program)? Why would that be the case given that I am still in the
ws
context?
Or maybe I should send a chain of requests/replies another way? (it should still be in the same context to allow authentication and proper indexing of the actions)