homeassistant-ws
Minimalist client library for Homeassistant's Websocket API. Works in node, and also in the browser.
Installation:
Using npm
:
$ npm i --save homeassistant-ws
Import it in your project:
import hass from 'homeassistant-ws';
async function main() {
const client = await hass({
token: 'my-secret-token',
});
}
Tokens are available from your profile page under the Homeassistant UI. For documentation on the authentication API, see the official HA documentation.
Configuration options
The following properties (shown with their defaults) can be passed to the constructor. All are optional.
hass({
protocol: 'ws',
host: 'localhost',
port: 8123,
path: '/api/websocket',
token: null,
messageSerializer: (outgoingMessage) => JSON.stringify(outgoingMessage),
messageParser: (incomingMessage) => JSON.parse(incomingMessage.data),
ws: (opts) => {
return new WebSocket(
`${opts.protocol}://${opts.host}:${opts.port}${opts.path}`
);
},
});
Example
The following example includes all available methods. For more details on available Homeassistant event types, states, etc. see the official Websocket API
import hass from 'hass';
async function main() {
const client = await hass({ token: 'my-token' });
await client.getStates();
await client.getServices();
await client.getPanels();
await client.getConfig();
await client.getMediaPlayerThumbnail('media_player.my_player');
await client.getCameraThumbnail('camera.front_yard');
await client.callService('lights', 'turn_on', {
entity_id: 'light.my_light',
});
client.on('message', (rawMessageData) => {
console.log(rawMessageData);
});
client.on('state_changed', (stateChangedEvent) => {
console.log(stateChangedEvent.data.new_state.state);
});
}