A domain package takes any entity.Transport. Both *api.Client and *mqtt.Client are one, so the calls below are the same for either.
Get and command
thermostat := climate.Get(transport, "living_room")
if err := thermostat.SetHVACMode(ctx, climate.HVACModeHeat); err != nil {
return err
}
if err := thermostat.SetTemperature(ctx, 21.5); err != nil {
return err
}
Get does no I/O. An id that does not exist is reported by the first method that needs it. The id means:
- over HTTP, an entity id, with or without its
domain.prefix; - over MQTT, a discovery object path (
object_idornode_id/object_id) or aunique_id.
Read the state
thermostat := climate.Get(transport, "living_room")
state, err := thermostat.State(ctx)
if err != nil {
return "", err
}
mode := climate.HVACModeOf(state) // "unavailable" and "unknown" are HVACModeUnknown
summary := string(mode)
// Attributes Home Assistant may leave out are pointers.
if current := state.Attributes.CurrentTemperature; current != nil {
summary = fmt.Sprintf("%s at %.1f", mode, *current)
}
Watch changes
thermostat := climate.Get(transport, "living_room")
// old is nil for an entity not seen before, new is nil when it is removed.
unsubscribe, err := thermostat.Subscribe(ctx, func(old, new *climate.State) {
if new != nil {
changed(new.State)
}
})
Call the returned function to stop. A change whose attributes do not decode into the typed struct is not delivered. It goes to WithOnError instead, so set it. Read what happens to HTTP subscriptions when the connection drops.
List entities
thermostats, err := climate.List(ctx, transport)
if err != nil {
return nil, err
}
for _, thermostat := range thermostats {
ids = append(ids, thermostat.ID())
}
Over HTTP this is every entity of the domain that Home Assistant has. Over MQTT it is the entities announced through discovery.
Switch to MQTT
client := mqtt.NewClient(mqtt.WithBroker(broker))
if err := client.Connect(ctx, nil); err != nil { // nil authenticator: anonymous
return nil, err
}
// The same domain packages now work over MQTT:
// climate.Get(client, "living_room") takes a discovery object path or a unique_id.
Over MQTT, commands go to the topics in the entity's discovery config, and the state is assembled from its state topics. Two things only Home Assistant can do:
- Services without a topic return
ha.ErrNotSupportedOverMQTT. - Jinja templates. A command whose topic has a template is refused. A state topic with a template, including through
value_template, is skipped, so the attributes it would fill stay empty.
err := light.Get(transport, "kitchen").Toggle(ctx)
if errors.Is(err, ha.ErrNotSupportedOverMQTT) {
// climate, light and others have services MQTT has no topic for.
return false, nil
}
Each domain page has a table of which command works on which transport, for example cover.
Commands the packages do not cover
Entity.Execute takes an entity.Command naming a service, MQTT topics, or both. Over HTTP you can also call any service by name.