light

Go types for Home Assistant's light domain: control over HTTP and MQTT, serve over MQTT discovery.

Control: HTTP Control: MQTT Serve a device Discovery config
import "github.com/taumatix/homeassistant-go/domains/light"

Overview

Package light is Home Assistant's light domain: its types and its MQTT discovery config.

Entity controls one light entity over HTTP or MQTT. Device serves one over MQTT.

MQTT support covers the basic (default) schema only; the json and template schemas and the color subsystems are reachable through WithConfig on the device side.

Home Assistant documents the domain here:

Integration: https://www.home-assistant.io/integrations/light/

MQTT discovery: https://www.home-assistant.io/integrations/light.mqtt/

Entity model (developers): https://contributors.home-assistant.io/core/entities/light/

Control

// client is an *api.Client or a connected *mqtt.Client
target := light.Get(client, "my_light")
state, err := target.State(ctx)
err = target.Toggle(ctx)

Serve

// mqttClient is a connected *mqtt.Client
device, err := light.NewDevice(ctx, mqttClient, "my-light",
	light.WithName("My light"),
)

Commands

What each Entity method does on each transport. MQTT publishes to the topic the entity's discovery config names in that option.

MethodOver HTTP, callsOver MQTT, publishes to
SetBrightness not available brightness_command_topic
SetColorTemp not available color_temp_command_topic
SetEffect not available effect_command_topic
Toggle light.toggle not available
TurnOff light.turn_off command_topic
TurnOn light.turn_on command_topic

Control

type Entity struct

Entity controls one light entity over HTTP (api.Client) or MQTT (mqtt.Client). State and Subscribe come from the embedded Handle.

Embeds entity.Handle[Attributes], whose methods it has too.

func Get(transport entity.Transport, id string) *Entity

Get returns the light entity with the given id: an entity id over HTTP (the "light." prefix may be omitted), a discovery object path or unique id over MQTT. It does no I/O.

func List(ctx context.Context, transport entity.Transport) ([]*Entity, error)

List returns every light entity the transport can see: all of Home Assistant's over HTTP, the discovered ones over MQTT.

func (e *Entity) SetBrightness(ctx context.Context, brightness float64) error

SetBrightness publishes to brightness_command_topic. Home Assistant has no service for it.

func (e *Entity) SetColorTemp(ctx context.Context, colorTemp float64) error

SetColorTemp publishes to color_temp_command_topic. Home Assistant has no service for it.

func (e *Entity) SetEffect(ctx context.Context, effect string) error

SetEffect publishes to effect_command_topic. Home Assistant has no service for it.

func (e *Entity) Toggle(ctx context.Context, options ...entity.ServiceOption) error

Toggle calls light.toggle. It has no MQTT equivalent. Core describes the service: Toggles one or more lights, from on to off, or off to on, based on their current state.

func (e *Entity) TurnOff(ctx context.Context, options ...entity.ServiceOption) error

TurnOff calls light.turn_off, or publishes payload_off to command_topic. Core describes the service: Turns off one or more lights.

func (e *Entity) TurnOn(ctx context.Context, options ...entity.ServiceOption) error

TurnOn calls light.turn_on, or publishes payload_on to command_topic. Core describes the service: Turns on one or more lights and adjusts their properties, even when they are turned on already.

type State = entity.State[Attributes]

State is a snapshot of one light entity.

func Brightness(value float64) entity.ServiceOption

Brightness sets the "brightness" service data field.

func BrightnessPct(value float64) entity.ServiceOption

BrightnessPct sets the "brightness_pct" service data field.

func BrightnessStep(value float64) entity.ServiceOption

BrightnessStep sets the "brightness_step" service data field.

func BrightnessStepPct(value float64) entity.ServiceOption

BrightnessStepPct sets the "brightness_step_pct" service data field.

func ColorName(value string) entity.ServiceOption

ColorName sets the "color_name" service data field.

func ColorTempKelvin(value float64) entity.ServiceOption

ColorTempKelvin sets the "color_temp_kelvin" service data field.

func Effect(value string) entity.ServiceOption

Effect sets the "effect" service data field.

func Flash(value string) entity.ServiceOption

Flash sets the "flash" service data field.

func Profile(value string) entity.ServiceOption

Profile sets the "profile" service data field.

func RgbColor(value []int) entity.ServiceOption

RgbColor sets the "rgb_color" service data field.

func Transition(value float64) entity.ServiceOption

Transition sets the "transition" service data field.

Serve over MQTT

type Device struct

Device is one light entity served by this process over MQTT. Close, Delete and ReportAvailability come from the embedded mqtt.Device.

Commands from Home Assistant arrive through the On*Command callbacks. A callback's ctx is cancelled when the client closes; an error it returns goes to the client's error path (mqtt.WithLogger, mqtt.WithOnError).

Embeds *mqtt.Device, whose methods it has too.

func NewDevice(ctx context.Context, client *mqtt.Client, objectID string, options ...DeviceOption) (*Device, error)

NewDevice announces a light entity through MQTT discovery and returns the device serving it. objectID may carry one "node_id/" prefix. Command, state and availability topics default to <topic root>/light/<objectID>/... and the options can override them. The client must be connected.

func (d *Device) Config() Config

Config returns the discovery config announced to Home Assistant.

func (d *Device) OnBrightnessCommand(fn func(ctx context.Context, brightness float64) error)

OnBrightnessCommand registers the callback for Home Assistant requesting a change of brightness.

func (d *Device) OnColorTempCommand(fn func(ctx context.Context, colorTemp float64) error)

OnColorTempCommand registers the callback for Home Assistant requesting a change of color_temp.

func (d *Device) OnEffectCommand(fn func(ctx context.Context, effect string) error)

OnEffectCommand registers the callback for Home Assistant requesting a change of effect.

func (d *Device) OnPowerCommand(fn func(ctx context.Context, on bool) error)

OnPowerCommand registers the callback for Home Assistant turning the device on or off.

func (d *Device) ReportBrightness(ctx context.Context, brightness float64, opts ...mqtt.StateOption) error

ReportBrightness reports the brightness on brightness_state_topic. opts override the client's state QoS and retain defaults for this publish.

func (d *Device) ReportColorMode(ctx context.Context, mode ColorMode, opts ...mqtt.StateOption) error

ReportColorMode reports the color_mode on color_mode_state_topic. opts override the client's state QoS and retain defaults for this publish.

func (d *Device) ReportColorTempKelvin(ctx context.Context, colorTemp float64, opts ...mqtt.StateOption) error

ReportColorTempKelvin reports the color_temp_kelvin on color_temp_state_topic. opts override the client's state QoS and retain defaults for this publish.

func (d *Device) ReportEffect(ctx context.Context, effect string, opts ...mqtt.StateOption) error

ReportEffect reports the effect on effect_state_topic. opts override the client's state QoS and retain defaults for this publish.

func (d *Device) ReportState(ctx context.Context, on bool, opts ...mqtt.StateOption) error

ReportState reports the entity as on or off on state_topic. opts override the client's state QoS and retain defaults for this publish.

type DeviceOption func(config *Config)

DeviceOption customizes the discovery config of a device before it is announced. Options run before the default topics are derived, so a topic they set is kept.

func WithConfig(fn func(config *Config)) DeviceOption

WithConfig applies fn to the discovery config for adjustments not covered by the other options.

func WithDeviceDetails(details ha.MQTTDeviceDetails) DeviceOption

WithDeviceDetails ties the entity to a device in the Home Assistant device registry.

func WithName(name string) DeviceOption

WithName sets the friendly name announced to Home Assistant.

State and values

type Attributes struct

Attributes are the state attributes of a light entity, under the names Home Assistant publishes them with.

See: https://www.home-assistant.io/integrations/light/

FieldTypeWire keyDescription
Brightness*intbrightness

Brightness. Over MQTT it comes from brightness_state_topic.

ColorMode*ColorModecolor_mode

Color mode. Over MQTT it comes from color_mode_state_topic.

ColorTempKelvin*intcolor_temp_kelvin

Color temperature (Kelvin). Over MQTT it comes from color_temp_state_topic.

Effect*stringeffect

Effect. Over MQTT it comes from effect_state_topic.

EffectList*[]stringeffect_list

Available effects. Over MQTT it comes from the effect_list option.

HsColor*[]float64hs_color
MaxColorTempKelvinintmax_color_temp_kelvin

Maximum color temperature (Kelvin).

MinColorTempKelvinintmin_color_temp_kelvin

Minimum color temperature (Kelvin).

RgbColor*[]intrgb_color
RgbwColor*[]intrgbw_color
RgbwwColor*[]intrgbww_color
SupportedColorModes*[]ColorModesupported_color_modes

Available color modes.

SupportedFeaturesFeaturesupported_features

A set of Feature flags.

XyColor*[]float64xy_color

ColorMode

type ColorMode string

ColorMode is core's ColorMode.

ConstantValue
ColorModeUnknown"unknown"
ColorModeOnoff"onoff"
ColorModeBrightness"brightness"
ColorModeColorTemp"color_temp"
ColorModeHs"hs"
ColorModeXy"xy"
ColorModeRgb"rgb"
ColorModeRgbw"rgbw"
ColorModeRgbww"rgbww"
ColorModeWhite"white"
func ColorModeFromString(s string) ColorMode

ColorModeFromString returns the ColorMode spelled s, by its value or by the name of core's member, and ColorModeUnknown for anything else.

func (v *ColorMode) UnmarshalJSON(data []byte) error

UnmarshalJSON reads any spelling ColorModeFromString accepts.

Feature

type Feature uint64

Feature is a set of light supported features, with the values of core's LightEntityFeature: the supported_features attribute decodes into it.

ConstantValue
FeatureUnknown0
FeatureEffect1 << 2
FeatureFlash1 << 3
FeatureTransition1 << 5
func FeatureFromString(s string) Feature

FeatureFromString returns the Feature spelled s, by its value or by the name of core's member, and FeatureUnknown for anything else.

MQTT discovery config

type Config struct

Config is the MQTT discovery config of light.

It has the options of every variant of the "schema" option: basic, json, template.

See: https://www.home-assistant.io/integrations/light.mqtt/

FieldTypeWire keyDescription
Availability[]ha.MQTTAvailabilityavailability
AvailabilityMode*stringavailability_mode

Allowed: "all", "any", "latest".

Default: "latest"

AvailabilityTemplate*ha.Templateavailability_template
AvailabilityTopic*stringavailability_topic

Topic to receive the availability payload on. NewDevice defaults it to <base>/availability.

BlueTemplate*ha.Templateblue_template

Only in the template variant.

Brightness*boolbrightness

Flag that defines if light supports brightness when the RGB, RGBW, or RGBWW color mode is supported. Only in the json variant.

Default: false

BrightnessCommandTemplate*ha.Templatebrightness_command_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity refuses to publish to brightness_command_topic.

BrightnessCommandTopic*stringbrightness_command_topic

Only in the basic variant. Entity.SetBrightness publishes to it. Device.OnBrightnessCommand receives what is published to it. NewDevice defaults it to <base>/brightness/set.

BrightnessScale*intbrightness_scale

Defines the maximum brightness value (i.e., 100%) of the maximum brightness. Only in the basic and json variant.

Default: 255

BrightnessStateTopic*stringbrightness_state_topic

Only in the basic variant. Over MQTT, Entity reads the "brightness" attribute from it. Device.ReportBrightness publishes to it. NewDevice defaults it to <base>/brightness/state.

BrightnessTemplate*ha.Templatebrightness_template

Only in the template variant.

BrightnessValueTemplate*ha.Templatebrightness_value_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity skips brightness_state_topic when reading state.

ColorModeStateTopic*stringcolor_mode_state_topic

The MQTT topic subscribed to receive color mode updates. If this is not configured, the color mode will be automatically set according to the last received valid color or color temperature. Only in the basic variant. Over MQTT, Entity reads the "color_mode" attribute from it. Device.ReportColorMode publishes to it. NewDevice defaults it to <base>/color_mode/state.

ColorModeValueTemplate*ha.Templatecolor_mode_value_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity skips color_mode_state_topic when reading state.

ColorTempCommandTemplate*ha.Templatecolor_temp_command_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity refuses to publish to color_temp_command_topic.

ColorTempCommandTopic*stringcolor_temp_command_topic

Only in the basic variant. Entity.SetColorTemp publishes to it. Device.OnColorTempCommand receives what is published to it. NewDevice defaults it to <base>/color_temp/set.

ColorTempKelvin*boolcolor_temp_kelvin

Default: false

ColorTempStateTopic*stringcolor_temp_state_topic

Only in the basic variant. Over MQTT, Entity reads the "color_temp_kelvin" attribute from it. Device.ReportColorTempKelvin publishes to it. NewDevice defaults it to <base>/color_temp/state.

ColorTempTemplate*ha.Templatecolor_temp_template

Only in the template variant.

ColorTempValueTemplate*ha.Templatecolor_temp_value_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity skips color_temp_state_topic when reading state.

CommandOffTemplate*ha.Templatecommand_off_template

Only in the template variant.

CommandOnTemplate*ha.Templatecommand_on_template

Only in the template variant.

CommandTopicstringcommand_topic

Required. Entity.TurnOff publishes to it. Entity.TurnOn publishes to it. Device.OnPowerCommand receives what is published to it. NewDevice defaults it to <base>/set.

DefaultEntityId*stringdefault_entity_id
Device*ha.MQTTDeviceDetailsdevice
Effect*booleffect

Flag that defines if the light supports effects. Only in the json variant.

Default: false

EffectCommandTemplate*ha.Templateeffect_command_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity refuses to publish to effect_command_topic.

EffectCommandTopic*stringeffect_command_topic

Only in the basic variant. Entity.SetEffect publishes to it. Device.OnEffectCommand receives what is published to it. NewDevice defaults it to <base>/effect/set.

EffectList[]stringeffect_list

The list of effects the light supports. Over MQTT, Entity reports it as the "effect_list" attribute.

EffectStateTopic*stringeffect_state_topic

Only in the basic variant. Over MQTT, Entity reads the "effect" attribute from it. Device.ReportEffect publishes to it. NewDevice defaults it to <base>/effect/state.

EffectTemplate*ha.Templateeffect_template

Only in the template variant.

EffectValueTemplate*ha.Templateeffect_value_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity skips effect_state_topic when reading state.

EnabledByDefault*boolenabled_by_default

Default: true

Encoding*stringencoding

Default: "utf-8"

EntityCategory*stringentity_category

Allowed: "config", "diagnostic".

EntityPicture*stringentity_picture

An URL to a picture to be assigned.

Flash*boolflash

Enable the flash feature for this light. Only in the json variant.

Default: true

FlashTimeLong*intflash_time_long

The duration, in seconds, of a "long" flash. Only in the json variant.

Default: 10

FlashTimeShort*intflash_time_short

The duration, in seconds, of a "short" flash. Only in the json variant.

Default: 2

GreenTemplate*ha.Templategreen_template

Only in the template variant.

Group[]stringgroup
HsCommandTemplate*ha.Templatehs_command_template

Only in the basic variant.

HsCommandTopic*stringhs_command_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

HsStateTopic*stringhs_state_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

HsValueTemplate*ha.Templatehs_value_template

Only in the basic variant.

Icon*ha.Iconicon
JsonAttributesTemplate*ha.Templatejson_attributes_template
JsonAttributesTopic*stringjson_attributes_topic

The library does not use it: extra attributes in a JSON document, which is not offered yet.

MaxKelvin*intmax_kelvin

The maximum color temperature in Kelvin.

MaxMireds*intmax_mireds
MessageExpiryInterval*map[string]anymessage_expiry_interval

Retention time interval for published message.

MinKelvin*intmin_kelvin

The minimum color temperature in Kelvin.

MinMireds*intmin_mireds
Name*stringname
OnCommandType*stringon_command_type

Defines when the payload "on" is sent. Using "Last" (the default) will send any style (brightness, color, etc) topics first and then a payload "on" to the command topic. Using "First" will send the payload "on" and then any style topics. Using "Brightness" will only send brightness commands instead of the payload "on" to turn the light on. Only in the basic variant. Allowed: "first", "last", "brightness".

Default: "last"

Optimistic*booloptimistic

Default: false

Origin*ha.DeviceOriginorigin
PayloadAvailable*stringpayload_available

The payload that indicates the device is available (defaults to 'online').

Default: "online"

PayloadNotAvailable*stringpayload_not_available

The payload that indicates the device is not available (defaults to 'offline').

Default: "offline"

PayloadOff*stringpayload_off

The payload that represents the "off" state. Only in the basic variant. Entity.TurnOff publishes it. Entity compares what state_topic says with it. Device.OnPowerCommand matches the received payload against it. Device.ReportState publishes it.

Default: "OFF"

PayloadOn*stringpayload_on

The payload that represents the "on" state. Only in the basic variant. Entity.TurnOn publishes it. Entity compares what state_topic says with it. Device.OnPowerCommand matches the received payload against it. Device.ReportState publishes it.

Default: "ON"

Qos*intqos

Allowed: 0, 1, 2.

Default: 0

RedTemplate*ha.Templatered_template

Only in the template variant.

Retain*boolretain

Default: false

RgbCommandTemplate*ha.Templatergb_command_template

Only in the basic variant.

RgbCommandTopic*stringrgb_command_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

RgbStateTopic*stringrgb_state_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

RgbValueTemplate*ha.Templatergb_value_template

Only in the basic variant.

RgbwCommandTemplate*ha.Templatergbw_command_template

Only in the basic variant.

RgbwCommandTopic*stringrgbw_command_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

RgbwStateTopic*stringrgbw_state_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

RgbwValueTemplate*ha.Templatergbw_value_template

Only in the basic variant.

RgbwwCommandTemplate*ha.Templatergbww_command_template

Only in the basic variant.

RgbwwCommandTopic*stringrgbww_command_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

RgbwwStateTopic*stringrgbww_state_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

RgbwwValueTemplate*ha.Templatergbww_value_template

Only in the basic variant.

Schema*stringschema

Allowed: "basic", "json", "template".

Default: "basic"

StateTemplate*ha.Templatestate_template

Only in the template variant.

StateTopic*stringstate_topic

Over MQTT, Entity reads the entity state from it. Device.ReportState publishes to it. NewDevice defaults it to <base>/state.

StateValueTemplate*ha.Templatestate_value_template

Only in the basic variant. Only Home Assistant renders templates: with it set, Entity skips state_topic when reading state.

SupportedColorModes[]stringsupported_color_modes

Only in the json variant. Allowed: "brightness", "color_temp", "hs", "onoff", "rgb", "rgbw", "rgbww", "white", "xy".

Transition*booltransition

Enable the transition feature for this light. Only in the json variant.

Default: true

UniqueId*stringunique_id
VisibleByDefault*boolvisible_by_default

Default: true

WhiteCommandTopic*stringwhite_command_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

WhiteScale*intwhite_scale

Defines the maximum white level (i.e., 100%) of the maximum. Only in the basic and json variant.

Default: 255

XyCommandTemplate*ha.Templatexy_command_template

Only in the basic variant.

XyCommandTopic*stringxy_command_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

XyStateTopic*stringxy_state_topic

Only in the basic variant. The library does not use it: the color subsystems publish compound payloads, not offered yet.

XyValueTemplate*ha.Templatexy_value_template

Only in the basic variant.

func (*Config) IsMQTTDiscoverySchema()

IsMQTTDiscoverySchema marks Config as a discovery payload (ha.MQTTDiscoverySchema).