REST and WebSocket

Call Home Assistant's APIs directly and subscribe to events.

api.Client is also a plain client of Home Assistant's REST API and WebSocket API.

REST

states, err := client.GetStates(ctx)
if err != nil {
	return 0, err
}
// Any service, typed or not. It returns the states which changed.
_, err = client.CallService(ctx, "light", "turn_on", map[string]any{"entity_id": "light.kitchen"})
var status *api.StatusError
if errors.As(err, &status) && status.Code == http.StatusBadRequest {
	return 0, fmt.Errorf("the call was refused: %s", status.Body)
}

Every REST method returns *api.StatusError for a status other than 2xx, with the start of the response body, where Home Assistant puts its reason.

A service that answers with data, such as weather.get_forecasts, has no typed method. Use CallServiceForResponse.

WebSocket events

conn, err := client.ConnectWebSocket(ctx)
if err != nil {
	return nil, err
}
subscription, err := conn.SubscribeEvents(ctx, "state_changed", func(event api.WSEvent) {
	if data, err := event.StateChanged(); err == nil {
		changed(data.EntityID)
	}
})
if err != nil {
	return nil, errors.Join(err, conn.Close())
}
// Later: conn.UnsubscribeEvents(ctx, subscription), then conn.Close().
// conn.Done() is closed when the connection ends; reconnect from there.

For a command without a helper, WSConn.Call sends any message type and returns the raw result.

All methods

The full list is on pkg.go.dev.