Does WebSocket API have a way of retrieving state of the single entity?
From what I see, it only has a way of retrieving all entities at once which is a bit overkill for my taste.
Does WebSocket API have a way of retrieving state of the single entity?
From what I see, it only has a way of retrieving all entities at once which is a bit overkill for my taste.
Maybe this helps.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src='http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type="text/javascript">
var myentity;
function getvalue() {
$(document).ready(function () {
function msg(str) {
$('#msg').append('<p>' + str + '</p>');
};
ws = new WebSocket('wss://youraddress/api/websocket');
ws.addEventListener('open', function (event) {
ws.send(JSON.stringify({"type": "auth","access_token": "yourtoken"}))
ws.send('{"id": 1, "type": "get_states"}\n');
});
ws.onmessage = function(event) {
//this if removes other messages comming from the websocket (e.g. auth ok)
if (event.data.length > 2000) {
window.myentity = JSON.parse(event.data)["result"].filter(function (el) { return el.entity_id == "sun.sun"})[0].state;
msg(myentity);
ws.close();
}
};
ws.onopen = function() {msg('Connected...');};
ws.onclose = function() {msg('Socket closed');};
});
}
</script>
</head>
<body onload="getvalue()">
<button onclick="getvalue()">Get new value</button>
<div id="msg"></div>
</body>
</html>
No, this uses get_states which fetches all states and then filters them out on the client side.
From what I read on the official page (I didn’t dig too much in the code) you can’t access a single entity - using the current options for the HASS WebSocket API. You either get them all and filter them (as I do) or keep an event subscription open and filter the incoming messages.
You can use the REST API. With that one you can access a single entity easily.
Looking at the source code of version 2023.11.2 in /components/websocket_api/commands.py this is possible.
There is a (currently) undocumented websocket command of ‘subscribe_entities’.
I’ve tested with the following websocket command it provides state updates for a limited set of entities.
{ “id”: 18,
“type”: “subscribe_entities”,
“entity_ids”: [“switch.test_lamp”]
}