@clinth/ha-api
v1.0.0
Published
Typed Home Assistant WebSocket API client with auto-reconnect and subscriptions for Node.js and browsers
Maintainers
Readme
@clinth/ha-api
Typed client for the Home Assistant WebSocket API.
- Authentication, request/response matching and request timeouts
- Keep-alive pings and automatic reconnection with backoff
- Subscriptions that are restored after a reconnect
- Typed helpers for states, services, config, areas, devices and entities
- Zero dependencies; runs in browsers and Node 22+ (uses the global
WebSocket)
Install
npm install @clinth/ha-apiUsage
import { HaSocket } from '@clinth/ha-api'
const ha = new HaSocket({
url: `ws://homeassistant.local:8123/api/websocket`,
token: process.env.HA_TOKEN!, // long-lived access token
})
await ha.whenReady()
await ha.callService(`light`, `turn_on`, { brightness: 128 }, { entity_id: `light.kitchen` })
const state = await ha.getState(`light.kitchen`)
// Subscriptions return a function that cancels them
declare function handleState(s?: string): void
const stop = await ha.subscribeEntity(`light.kitchen`, ({ new_state }) => {
handleState(new_state?.state)
})
await stop()
ha.close()Requests made before the connection is authenticated wait until it is.
Failed requests reject with HaError (with a code); a rejected token rejects
whenReady() with HaAuthError and is not retried.
Older Node versions
Node 20 and earlier have no global WebSocket. Install ws and pass it in:
import { WebSocket } from 'ws'
const ha = new HaSocket({ url, token, webSocket: WebSocket as any })API
| Member | Description |
| --- | --- |
| new HaSocket(options) | url, token, keepAliveSeconds (30, 0 disables), requestTimeoutMs (30000), reconnect (true), autoConnect (true), webSocket, debug |
| connect() / close() | Open or close the connection |
| whenReady() | Resolves once authenticated |
| connectionState / isAuthorized | closed, connecting or ready |
| request(command) | Send any command, e.g. { type: 'get_panels' } |
| callService(domain, service, data?, target?, returnResponse?) | Call a service |
| fireHaEvent(type, data?) | Fire an event on the bus |
| fetchStates() / getState(id) | All states (cached) / one entity |
| fetchConfig() / fetchServices() | Instance config / service definitions |
| fetchAreas() / fetchDevices() / fetchEntities() | Registries |
| ping() | Round-trip latency in ms |
| subscribeEvent(type?, cb?) | Subscribe to events |
| subscribeEntity(id, cb) | Subscribe to one entity's state changes |
| subscribeTrigger(trigger, cb?) | Subscribe to an automation trigger |
| addEventListener(name, fn) | state, event and error events |
| lastState / lastConfig / lastServices | Cached data |
Development
pnpm lint # check
pnpm lint:fix # fix (also runs on commit via lint-staged)
pnpm test
pnpm buildLicense
ISC
