Gathering detailed insights and metrics for home-assistant-js-websocket
Gathering detailed insights and metrics for home-assistant-js-websocket
Gathering detailed insights and metrics for home-assistant-js-websocket
Gathering detailed insights and metrics for home-assistant-js-websocket
npm install home-assistant-js-websocket
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
284 Stars
562 Commits
85 Forks
20 Watching
10 Branches
42 Contributors
Updated on 26 Nov 2024
TypeScript (93.74%)
HTML (5.93%)
JavaScript (0.33%)
Cumulative downloads
Total Downloads
Last day
203.5%
1,648
Compared to previous day
Last week
-12.6%
7,806
Compared to previous week
Last month
71%
29,568
Compared to previous month
Last year
28.7%
187,010
Compared to previous year
This is a websocket client written in JavaScript that allows retrieving authentication tokens and communicate with the Home Assistant websocket API. It can be used to integrate Home Assistant into your apps. It has 0 dependencies.
Check the demo. The repository also includes an example client:
Clone this repository, then go to home-assistant-js-websocket folder and run the following commands:
1yarn install 2yarn build 3npx http-server -o 4# A browser will open, navigate to example.html
1# With npm 2npm i home-assistant-js-websocket 3 4# With yarn 5yarn add home-assistant-js-websocket
To initialize a connection, you need an authentication token for the instance that you want to connect to. This library implements the necessary steps to guide the user to authenticate your website with their Home Assistant instance and give you a token. All you need from the user is the url of their instance.
1// Example connect code 2import { 3 getAuth, 4 createConnection, 5 subscribeEntities, 6 ERR_HASS_HOST_REQUIRED, 7} from "home-assistant-js-websocket"; 8 9async function connect() { 10 let auth; 11 try { 12 // Try to pick up authentication after user logs in 13 auth = await getAuth(); 14 } catch (err) { 15 if (err === ERR_HASS_HOST_REQUIRED) { 16 const hassUrl = prompt( 17 "What host to connect to?", 18 "http://localhost:8123", 19 ); 20 // Redirect user to log in on their instance 21 auth = await getAuth({ hassUrl }); 22 } else { 23 alert(`Unknown error: ${err}`); 24 return; 25 } 26 } 27 const connection = await createConnection({ auth }); 28 subscribeEntities(connection, (ent) => console.log(ent)); 29} 30 31connect();
getAuth()
Use this method to get authentication from a server via OAuth2. This method will handle redirecting to an instance and fetching the token after the user successful logs in.
You can pass options using the syntax:
1getAuth({ hassUrl: "http://localhost:8123" });
Option | Description |
---|---|
hassUrl | The url where the Home Assistant instance can be reached. This option is needed so we know where to redirect the user for authentication. Once redirected back, it is not needed to pass this option in. |
clientId | Client ID to use. Client IDs for Home Assistant is the url of your application. Defaults to domain of current page. Pass null if you are making requests on behalf of a system user. |
redirectUrl | The url to redirect back to when the user has logged in. Defaults to current page. |
saveTokens | Function to store an object containing the token information. |
loadTokens | Function that returns a promise that resolves to previously stored token information object or undefined if no info available. |
authCode | If you have an auth code received via other means, you can pass it in and it will be used to fetch tokens instead of going through the OAuth2 flow. |
limitHassInstance | If set to true, allow only authentication credentials for the passed in hassUrl and clientId . Defaults to false. |
In certain instances getAuth
will raise an error. These errors can be imported from the package:
1// When bundling your application 2import { 3 ERR_HASS_HOST_REQUIRED, 4 ERR_INVALID_AUTH, 5} from "home-assistant-js-websocket"; 6 7// When using the UMD build 8HAWS.ERR_HASS_HOST_REQUIRED;
Error | Description |
---|---|
ERR_HASS_HOST_REQUIRED | You need to pass in hassUrl to getAuth to continue getting auth. This option is not needed when the user is redirected back after successfully logging in. |
ERR_INVALID_AUTH | This error will be raised if the url contains an authorization code that is no longer valid. |
ERR_INVALID_HTTPS_TO_HTTP | This error is raised if your code is being run from a secure context (hosted via https) and you're trying to fetch tokens from a Home Assistant instance via a non secure context (http). This is called mixed active content and the browser forbids this. |
ERR_INVALID_AUTH_CALLBACK | This error is raised if only credentials for the specified Home Assistant instance are allowed and the client ID or hassURL in the auth callback state do not match the expected ones. |
Other errors | Unknown error! |
createConnection()
You need to either provide auth
or createSocket
as options to createConnection:
1createConnection({ auth });
Option | Description |
---|---|
auth | Auth object to use to create a connection. |
createSocket | Override the createSocket method with your own. (options) => Promise<WebSocket> . Needs to return a connection that is already authenticated. |
setupRetry | Number of times to retry initial connection when it fails. Set to -1 for infinite retries. Default is 0 (no retries) |
Currently the following error codes can be raised by createConnection:
Error | Description |
---|---|
ERR_CANNOT_CONNECT | If the client was unable to connect to the websocket API. |
ERR_INVALID_AUTH | If the supplied authentication was invalid. |
You can import them into your code as follows:
1import { 2 ERR_CANNOT_CONNECT, 3 ERR_INVALID_AUTH, 4} from "home-assistant-js-websocket";
The connection object will automatically try to reconnect to the server when the connection gets lost. On reconnect, it will automatically resubscribe the event listeners.
If you don't want to automatically try to reconnect to the server when the connection is lost, you can pass a promise to wait for. The connection will try to reconnect after the promise is resolved.
1connection.suspendReconnectUntil( 2 new Promise((resolve) => { 3 // When you want to try to reconnect again, resolve the promise. 4 resolve(); 5 }), 6);
When the suspend promise resolves until the connection is re-established, all messages being send will be delayed until the connection is established. If the first reconnect fails, the queued messages will be rejected.
You can also actively close the connection and wait for a promise to resolve to reconnect again. This promise can be passed either with suspendReconnectUntil
or with the suspend
command itself.
If you don't provide a promise with either of these functions, an error will be thrown.
1connection.suspendReconnectUntil( 2 new Promise((resolve) => { 3 // When you want to try to reconnect again, resolve the promise. 4 resolve(); 5 }), 6); 7connection.suspend();
or
1connection.suspend( 2 new Promise((resolve) => { 3 // When you want to try to reconnect again, resolve the promise. 4 resolve(); 5 }), 6);
You can also close the connection, without any reconnect, with connection.close()
.
The Connection
object implements three events related to the reconnecting logic.
Event | Data | Description |
---|---|---|
ready | - | Fired when authentication is successful and the connection is ready to take commands. |
disconnected | - | Fired when the connection is lost. |
reconnect-error | Error code | Fired when we encounter a fatal error when trying to reconnect. Currently limited to ERR_INVALID_AUTH . |
You can attach and remove listeners as follows:
1function eventHandler(connection, data) { 2 console.log("Connection has been established again"); 3} 4 5conn.addEventListener("ready", eventHandler); 6conn.removeEventListener("ready", eventHandler);
You can subscribe to the entities of Home Assistant. Your callback will be called when the entities are first loaded and on every change to the state of any of the entities after that. The callback will be called with a single object that contains the entities keyed by entity_id.
The function subscribeEntities
will return an unsubscribe function.
1import { subscribeEntities } from "home-assistant-js-websocket"; 2 3// conn is the connection from earlier. 4subscribeEntities(conn, (entities) => console.log("New entities!", entities));
You can also import the collection:
1import { entitiesColl } from "home-assistant-js-websocket"; 2 3// conn is the connection from earlier. 4const coll = entitiesColl(connection); 5console.log(coll.state); 6await coll.refresh(); 7coll.subscribe((entities) => console.log(entities));
You can subscribe to the config of Home Assistant. Config can change when either a component gets loaded.
The function subscribeConfig
will return an unsubscribe function.
1import { subscribeConfig } from "home-assistant-js-websocket"; 2 3// conn is the connection from earlier. 4subscribeConfig(conn, (config) => console.log("New config!", config));
You can also import the collection:
1import { configColl } from "home-assistant-js-websocket"; 2 3// conn is the connection from earlier. 4const coll = configColl(connection); 5console.log(coll.state); 6await coll.refresh(); 7coll.subscribe((config) => console.log(config));
You can subscribe to the available services of Home Assistant. Services can change when a new service gets registered or removed.
The function subscribeServices
will return an unsubscribe function.
1import { subscribeServices } from "home-assistant-js-websocket"; 2 3// conn is the connection from earlier. 4subscribeServices(conn, (services) => console.log("New services!", services));
You can also import the collection:
1import { servicesColl } from "home-assistant-js-websocket"; 2 3// conn is the connection from earlier. 4const coll = servicesColl(connection); 5console.log(coll.state); 6await coll.refresh(); 7coll.subscribe((services) => console.log(services));
Besides entities, config and services you might want to create your own collections. A collection has the following features:
1// Will only initialize one collection per connection. 2getCollection<State>( 3 conn: Connection, 4 key: string, 5 fetchCollection: (conn: Connection) => Promise<State>, 6 subscribeUpdates: ( 7 conn: Connection, 8 store: Store<State> 9 ) => Promise<UnsubscribeFunc>, 10): Collection<State> 11 12// Returns object with following type 13class Collection<State> { 14 state: State; 15 async refresh(): Promise<void>; 16 subscribe(subscriber: (state: State) => void): UnsubscribeFunc; 17}
conn
is the connection to subscribe to.key
a unique key for the collectionfetchCollection
needs to return a Promsise that resolves to the full statesubscribeUpdates
needs to subscribe to the updates and update the store. Returns a promise that resolves to an unsubscribe function.1import { getCollection } from "home-assistant-js-websocket"; 2 3function panelRegistered(state, event) { 4 // Returning null means no change. 5 if (state === undefined) return null; 6 7 // This will be merged with the existing state. 8 return { 9 panels: state.panels.concat(event.data.panel), 10 }; 11} 12 13const fetchPanels = (conn) => conn.sendMessagePromise({ type: "get_panels" }); 14const subscribeUpdates = (conn, store) => 15 conn.subscribeEvents(store.action(panelRegistered), "panel_registered"); 16 17const panelsColl = getCollection(conn, "_pnl", fetchPanels, subscribeUpdates); 18 19// Now use collection 20console.log(panelsColl.state); 21await panelsColl.refresh(); 22panelsColl.subscribe((panels) => console.log("New panels!", panels));
Collections are useful to define if data is needed for initial data load. You can create a collection and have code on your page call it before you start rendering the UI. By the time UI is loaded, the data will be available to use.
A connection object is obtained by calling createConnection()
.
conn.haVersion
String containing the current version of Home Assistant. Examples:
0.107.0
0.107.0b1
0.107.0.dev0
2021.3.0
conn.subscribeEvents(eventCallback[, eventType])
Subscribe to all or specific events on the Home Assistant bus. Calls eventCallback
for each event that gets received.
Returns a promise that will resolve to a function that will cancel the subscription once called.
Subscription will be automatically re-established after a reconnect.
Uses conn.subscribeMessage
under the hood.
conn.addEventListener(eventType, listener)
Listen for events on the connection. See docs.
conn.sendMessagePromise(message)
Send a message to the server. Returns a promise that resolves or rejects based on the result of the server. Special case rejection is ERR_CONNECTION_LOST
if the connection is lost while the command is in progress.
conn.subscribeMessage(callback, subscribeMessage[, options])
Call an endpoint in Home Assistant that creates a subscription. Calls callback
for each item that gets received.
Returns a promise that will resolve to a function that will cancel the subscription once called.
Subscription will be automatically re-established after a reconnect unless options.resubscribe
is false.
Option | Description |
---|---|
resubscribe | Re-established a subscription after a reconnect |
An instance of Auth is returned from the getAuth
method. It has the following properties:
wsUrl
: the websocket url of the instanceaccessToken
: the access tokenexpired
: boolean that indicates if the access token has expiredauth.refreshAccessToken()
Fetches a new access token from the server.
auth.revoke()
Makes a request to the server to revoke the refresh and all related access token. Returns a promise that resolves when the request is finished.
Note: If you support storing and retrieving tokens, the returned auth object might load tokens from your cache that are no longer valid. If this happens, the promise returned by createConnection
will reject with ERR_INVALID_AUTH
. If that happens, clear your tokens with storeTokens(null
) and call getAuth
again. This will pick up the auth flow without relying on stored tokens.
Error constant | Error number |
---|---|
ERR_CANNOT_CONNECT | 1 |
ERR_INVALID_AUTH | 2 |
ERR_CONNECTION_LOST | 3 |
ERR_HASS_HOST_REQUIRED | 4 |
ERR_INVALID_HTTPS_TO_HTTP | 5 |
The library also contains a few helper method that you can use to ineract with the API.
getUser(connection) -> Promise<HassUser>
callService(connection, domain, service, serviceData?, target?) -> Promise
(Support for target
was added in Home Assistant Core 2021.3)The following are also available, but it's recommended that you use the subscribe methods documented above.
getStates(connection) -> Promise<HassEntity[]>
getServices(connection) -> Promise<HassEntity[]>
getConfig(connection) -> Promise<HassEntity[]>
If you are in a browser, you should prefer to use the getAuth()
flow. This will use the more secure refresh/access token pair. If that is not possible, you can ask the user to create a long-lived access token.
You will need to create your own auth object if you want to use this library with a long-lived access token.
1import { 2 Auth, 3 createConnection, 4 subscribeEntities, 5 createLongLivedTokenAuth, 6} from "home-assistant-js-websocket"; 7 8(async () => { 9 const auth = createLongLivedTokenAuth( 10 "http://localhost:8123", 11 "YOUR ACCESS TOKEN", 12 ); 13 14 const connection = await createConnection({ auth }); 15 subscribeEntities(connection, (entities) => console.log(entities)); 16})();
NodeJS does not have a WebSocket client built-in, but there are some good ones on NPM. We recommend ws. The easiest way to enable WebSocket is to polyfill it into the global namespace. Look at https://github.com/keesschollaart81/vscode-home-assistant/blob/master/src/language-service/src/home-assistant/socket.ts as an example using ws.
If using TypeScript, you will need to install @types/ws
as well.
1globalThis.WebSocket = require("ws");
or in TypeScript:
1const wnd = globalThis; 2wnd.WebSocket = require("ws");
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
21 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
3 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Morenode-red-contrib-home-assistant-websocket
Node-RED integration with Home Assistant through websocket and REST API
@ciesielskico/home-assistant-rxjs
rxjs addons for home-assistant-js-websocket
faye-websocket
Standards-compliant WebSocket server and client
@scrypted/homeassistant
The Home Assistant Plugin for Scrypted imports `notify` services to be used within Scrypted.