sensor

Go types for Home Assistant's sensor 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/sensor"

Overview

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

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

Home Assistant documents the domain here:

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

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

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

Control

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

Serve

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

Control

type Entity struct

Entity controls one sensor 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 sensor entity with the given id: an entity id over HTTP (the "sensor." 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 sensor entity the transport can see: all of Home Assistant's over HTTP, the discovered ones over MQTT.

type State = entity.State[Attributes]

State is a snapshot of one sensor entity.

Serve over MQTT

type Device struct

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

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 sensor 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>/sensor/<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) ReportState(ctx context.Context, state string, opts ...mqtt.StateOption) error

ReportState reports the state on state_topic. opts override the client's state QoS and retain defaults for this publish. With ExpireAfter configured pass mqtt.StateRetained(false), or Home Assistant restores a retained value after the entity has expired.

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 sensor entity, under the names Home Assistant publishes them with.

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

FieldTypeWire keyDescription
DeviceClass*DeviceClassdevice_class

Over MQTT it comes from the device_class option.

LastReset*stringlast_reset

Last reset.

Options*[]stringoptions

Possible states. Over MQTT it comes from the options option.

StateClass*StateClassstate_class

State class. Over MQTT it comes from the state_class option.

UnitOfMeasurement*stringunit_of_measurement

Over MQTT it comes from the unit_of_measurement option.

DeviceClass

type DeviceClass string

DeviceClass is core's SensorDeviceClass.

ConstantValue
DeviceClassUnknown"Unknown"
DeviceClassDate"date"
DeviceClassEnum"enum"
DeviceClassTimestamp"timestamp"
DeviceClassUptime"uptime"
DeviceClassAbsoluteHumidity"absolute_humidity"
DeviceClassApparentPower"apparent_power"
DeviceClassAqi"aqi"
DeviceClassArea"area"
DeviceClassAtmosphericPressure"atmospheric_pressure"
DeviceClassBattery"battery"
DeviceClassBloodGlucoseConcentration"blood_glucose_concentration"
DeviceClassCo"carbon_monoxide"
DeviceClassCo2"carbon_dioxide"
DeviceClassConductivity"conductivity"
DeviceClassCurrent"current"
DeviceClassDataRate"data_rate"
DeviceClassDataSize"data_size"
DeviceClassDistance"distance"
DeviceClassDuration"duration"
DeviceClassEnergy"energy"
DeviceClassEnergyDistance"energy_distance"
DeviceClassEnergyStorage"energy_storage"
DeviceClassFrequency"frequency"
DeviceClassGas"gas"
DeviceClassHumidity"humidity"
DeviceClassIlluminance"illuminance"
DeviceClassIrradiance"irradiance"
DeviceClassMoisture"moisture"
DeviceClassMonetary"monetary"
DeviceClassNitrogenDioxide"nitrogen_dioxide"
DeviceClassNitrogenMonoxide"nitrogen_monoxide"
DeviceClassNitrousOxide"nitrous_oxide"
DeviceClassOzone"ozone"
DeviceClassPh"ph"
DeviceClassPm1"pm1"
DeviceClassPm10"pm10"
DeviceClassPm25"pm25"
DeviceClassPm4"pm4"
DeviceClassPowerFactor"power_factor"
DeviceClassPower"power"
DeviceClassPrecipitation"precipitation"
DeviceClassPrecipitationIntensity"precipitation_intensity"
DeviceClassPressure"pressure"
DeviceClassRadon"radon"
DeviceClassReactiveEnergy"reactive_energy"
DeviceClassReactivePower"reactive_power"
DeviceClassSignalStrength"signal_strength"
DeviceClassSoundPressure"sound_pressure"
DeviceClassSpeed"speed"
DeviceClassSulphurDioxide"sulphur_dioxide"
DeviceClassTemperature"temperature"
DeviceClassTemperatureDelta"temperature_delta"
DeviceClassVolatileOrganicCompounds"volatile_organic_compounds"
DeviceClassVolatileOrganicCompoundsParts"volatile_organic_compounds_parts"
DeviceClassVoltage"voltage"
DeviceClassVolume"volume"
DeviceClassVolumeStorage"volume_storage"
DeviceClassVolumeFlowRate"volume_flow_rate"
DeviceClassWater"water"
DeviceClassWeight"weight"
DeviceClassWindDirection"wind_direction"
DeviceClassWindSpeed"wind_speed"
func DeviceClassFromString(s string) DeviceClass

DeviceClassFromString returns the DeviceClass spelled s, by its value or by the name of core's member, and DeviceClassUnknown for anything else.

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

UnmarshalJSON reads any spelling DeviceClassFromString accepts.

StateClass

type StateClass string

StateClass is core's SensorStateClass.

ConstantValue
StateClassUnknown"Unknown"
StateClassMeasurement"measurement"
StateClassMeasurementAngle"measurement_angle"
StateClassTotal"total"
StateClassTotalIncreasing"total_increasing"
func StateClassFromString(s string) StateClass

StateClassFromString returns the StateClass spelled s, by its value or by the name of core's member, and StateClassUnknown for anything else.

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

UnmarshalJSON reads any spelling StateClassFromString accepts.

StateValue

type StateValue string

StateValue lists the built-in values of the entity state, as Home Assistant translates them. Integrations may use others, which are kept as they are.

ConstantValue
StateValueUnknown"Unknown"
StateValueOff"off"
StateValueOn"on"
func StateValueFromString(s string) StateValue

StateValueFromString returns s as a StateValue.

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

UnmarshalJSON reads any spelling StateValueFromString accepts.

MQTT discovery config

type Config struct

Config is the MQTT discovery config of sensor.

See: https://www.home-assistant.io/integrations/sensor.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.

DefaultEntityId*stringdefault_entity_id
Device*ha.MQTTDeviceDetailsdevice
DeviceClassDeviceClassdevice_class

Allowed: "date", "enum", "timestamp", "uptime", "absolute_humidity", "apparent_power", "aqi", "area", "atmospheric_pressure", "battery", "blood_glucose_concentration", "carbon_monoxide", "carbon_dioxide", "conductivity", "current", "data_rate", "data_size", "distance", "duration", "energy", "energy_distance", "energy_storage", "frequency", "gas", "humidity", "illuminance", "irradiance", "moisture", "monetary", "nitrogen_dioxide", "nitrogen_monoxide", "nitrous_oxide", "ozone", "ph", "pm1", "pm10", "pm25", "pm4", "power_factor", "power", "precipitation", "precipitation_intensity", "pressure", "radon", "reactive_energy", "reactive_power", "signal_strength", "sound_pressure", "speed", "sulphur_dioxide", "temperature", "temperature_delta", "volatile_organic_compounds", "volatile_organic_compounds_parts", "voltage", "volume", "volume_storage", "volume_flow_rate", "water", "weight", "wind_direction", "wind_speed". Over MQTT, Entity reports it as the "device_class" attribute.

EnabledByDefault*boolenabled_by_default

Default: true

Encoding*stringencoding

Default: "utf-8"

EntityCategory*stringentity_category
EntityPicture*stringentity_picture

An URL to a picture to be assigned.

ExpireAfter*intexpire_after
ForceUpdate*boolforce_update

Default: false

Group[]stringgroup
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.

LastResetValueTemplate*ha.Templatelast_reset_value_template
MessageExpiryInterval*map[string]anymessage_expiry_interval

Retention time interval for published message.

Name*stringname
Options[]stringoptions

Over MQTT, Entity reports it as the "options" attribute.

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"

Qos*intqos

Default: 0

StateClass*stringstate_class

Allowed: "measurement", "measurement_angle", "total", "total_increasing". Over MQTT, Entity reports it as the "state_class" attribute.

StateTopicstringstate_topic

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

SuggestedDisplayPrecision*intsuggested_display_precision
UniqueId*stringunique_id
UnitOfMeasurement*stringunit_of_measurement

Defines the unit of measurement, if any. Over MQTT, Entity reports it as the "unit_of_measurement" attribute.

ValueTemplate*ha.Templatevalue_template

Only Home Assistant renders templates: with it set, Entity skips state_topic when reading state. It applies to every state topic without a template of its own; Entity skips those topics when reading state.

VisibleByDefault*boolvisible_by_default

Default: true

func (*Config) IsMQTTDiscoverySchema()

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