Serve your own devices

Announce entities through MQTT discovery and answer Home Assistant's commands.

A served device is an entity your program owns. It announces itself through MQTT discovery, receives Home Assistant's commands and reports its state. It needs a connected *mqtt.Client, and a broker that Home Assistant's MQTT integration uses too.

Announce a device and answer commands

device, err := climate.NewDevice(ctx, client, "living-room-hvac",
	climate.WithName("Living Room HVAC"),
	climate.WithHVACModes(climate.HVACModeOff, climate.HVACModeHeat),
	climate.WithFanModes(climate.FanModeLow, climate.FanModeHigh),
	climate.WithTemperatureLimits(5, 30),
)
if err != nil {
	return nil, err
}

// Home Assistant to the device: apply the command, then report what is now true.
device.OnHVACModeCommand(func(ctx context.Context, mode climate.HVACMode) error {
	return device.ReportHVACMode(ctx, mode)
})
device.OnTemperatureCommand(func(ctx context.Context, target float64) error {
	return device.ReportTargetTemperature(ctx, target)
})

// The device to Home Assistant. State is retained by default.
if err := device.ReportCurrentTemperature(ctx, 21.5); err != nil {
	return nil, err
}

Callbacks of one command topic run one at a time, in order. The context of a callback is cancelled when the client closes. An error it returns goes to the client's logger and WithOnError, not back to Home Assistant, so report the state that is actually true.

Options

Every Device has WithName and WithConfig. Most also have WithDeviceDetails and options for their lists of modes or limits. The domain page lists them with the discovery option each one sets.

// Home Assistant groups the entities that share a device identifier.
station := ha.MQTTDeviceDetails{
	Identifiers:  []string{"weather-station-1"},
	Name:         "Weather station",
	Manufacturer: "Example",
}

temperature, err := sensor.NewDevice(ctx, client, "station_temperature",
	sensor.WithName("Temperature"),
	sensor.WithDeviceDetails(station),
	// WithConfig sets any discovery option the other options do not cover.
	sensor.WithConfig(func(config *sensor.Config) {
		config.UnitOfMeasurement = ha.P("°C")
		config.ExpireAfter = ha.P(120)
	}),
)
if err != nil {
	return nil, err
}
// With expire_after, do not retain: the broker would replay an expired value.
if err := temperature.ReportState(ctx, "21.5", mqtt.StateRetained(false)); err != nil {
	return nil, err
}

Topics

Discovery: <discovery prefix>/<component>/[<node_id>/]<object_id>/config
State:     <topic root>/<component>/[<node_id>/]<object_id>/.../state
Command:   <topic root>/<component>/[<node_id>/]<object_id>/.../set

mqtt.WithDiscoveryPrefix (default homeassistant) moves the discovery topics. mqtt.WithTopicRoot (default homeassistant-go) moves the others, for devices announced afterwards. A broker with access rules has to allow both. Object and node ids must match ^[a-zA-Z0-9_-]*$.

Defaults are filled after your options run, so a topic you set is kept. The discovery config table of each domain page says which options get a default topic, and when.

Close or delete

  • device.Close(ctx) reports the entity offline and stops listening. The discovery config stays on the broker, so the entity comes back when you serve it again.
  • device.Delete(ctx) removes it from Home Assistant: it clears the retained config, state and availability topics.
  • Close or delete devices before client.Close: they need the connection to publish.

A process that is killed runs neither. Register a Last Will so the broker can say it is gone.

Platforms and options the packages do not cover

mqtt.Client.Announce serves a device from your own discovery config and command routes. It subscribes to the command topics, publishes the config, then reports the device online, in that order.