haconnect

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2025 License: MIT Imports: 5 Imported by: 0

README

haconnect

Go Reference MIT License

This package aims to provide an easy interface for exposing entities to Home Assistant via MQTT.

Installation

Adding haconnect to your application is as easy as:

import "github.com/nathan-osman/haconnect"

Usage

To expose entities to Home Assistant, you must first create a connection (Conn):

c, err := haconnect.New(&haconnect.Config{
    Addr:     "1.2.3.4:1883",
    Username: "myusername",
    Password: "password123",
})
if err != nil {
    panic(err)
}
defer c.Close()

From there, you can create entities by calling their respective member function. For example, to create a light:

l, err := c.Light(
    &haconnect.EntityConfig{
        ID:   "mylight",
        Name: "My Light",
    },
    &haconnect.LightConfig{
        ChangeCallback: func(on bool) bool {
            if on {
                fmt.Println("Light turned on")
            } else {
                fmt.Println("Light turned off")
            }
            return true
        },
    },
)

This will create a corresponding entity for your light that you can then control directly from the Home Assistant UI:

Screenshot of light control in Home Assistant

Toggling the switch should cause the appropriate message to be written to your application's console.

The availability of the light is maintained automatically while your client is running but if you want to manually indicate that the light is unavailable, you can run:

l.SetAvailability(false)

Documentation

Index

Constants

View Source
const (
	BinarySensorBattery         = "battery"
	BinarySensorBatteryCharging = "battery_charging"
	BinarySensorCarbonMonoxide  = "carbon_monoxide"
	BinarySensorCold            = "cold"
	BinarySensorConnectivity    = "connectivity"
	BinarySensorDoor            = "door"
	BinarySensorGarageDpor      = "garage_door"
	BinarySensorGas             = "gas"
	BinarySensorHeat            = "heat"
	BinarySensorLight           = "light"
	BinarySensorLock            = "lock"
	BinarySensorMoisture        = "moisture"
	BinarySensorMotion          = "motion"
	BinarySensorMoving          = "moving"
	BinarySensorOccupancy       = "occupancy"
	BinarySensorOpening         = "opening"
	BinarySensorPlug            = "plug"
	BinarySensorPower           = "power"
	BinarySensorPresence        = "presence"
	BinarySensorProblem         = "problem"
	BinarySensorRunning         = "running"
	BinarySensorSafety          = "safety"
	BinarySensorSmoke           = "smoke"
	BinarySensorSound           = "sound"
	BinarySensorTamper          = "tamper"
	BinarySensorUpdate          = "update"
	BinarySensorVibration       = "vibration"
	BinarySensorWindow          = "window"
)
View Source
const (
	ButtonIdentify = "identify"
	ButtonRestart  = "restart"
	ButtonUpdate   = "update"
)
View Source
const (
	EventButton   = "button"
	EventDoorbell = "doorbell"
	EventMotion   = "motion"
)
View Source
const (
	SensorAbsoluteHumidity              = "absolute_humidity"
	SensorApparentPower                 = "apparent_power"
	SensorAQI                           = "aqi"
	SensorArea                          = "area"
	SensorAtmosphericPressure           = "atmospheric_pressure"
	SensorBattery                       = "battery"
	SensorBloodGlucoseConcentration     = "blood_glucose_concentration"
	SensorCarbonDioxide                 = "carbon_dioxide"
	SensorCarbonMonoxide                = "carbon_monoxide"
	SensorCurrent                       = "current"
	SensorDataRate                      = "data_rate"
	SensorDataSize                      = "data_size"
	SensorDate                          = "date"
	SensorDistance                      = "distance"
	SensorDuration                      = "duration"
	SensorEnergy                        = "energy"
	SensorEnergyDistance                = "energy_distance"
	SensorEnergyStorage                 = "energy_storage"
	SensorEnum                          = "enum"
	SensorFrequency                     = "frequency"
	SensorGas                           = "gas"
	SensorHumidity                      = "humidity"
	SensorIlluminance                   = "illuminance"
	SensorIrradiance                    = "irradiance"
	SensorMoisture                      = "moisture"
	SensorMonetary                      = "monetary"
	SensorNitrogenDioxide               = "nitrogen_dioxide"
	SensorNitrogenMonoxide              = "nitrogen_monoxide"
	SensorNitrousOxide                  = "nitrous_oxide"
	SensorOzone                         = "ozone"
	SensorPH                            = "ph"
	SensorPM1                           = "pm1"
	SensorPM25                          = "pm25"
	SensorPM4                           = "pm4"
	SensorPM10                          = "pm10"
	SensorPowerFactor                   = "power_factor"
	SensorPower                         = "power"
	SensorPrecipitation                 = "precipitation"
	SensorPrecipitationIntensity        = "precipitation_intensity"
	SensorPressure                      = "pressure"
	SensorReactiveEnergy                = "reactive_energy"
	SensorReactivePower                 = "reactive_power"
	SensorSignalStrength                = "signal_strength"
	SensorSoundPressure                 = "sound_pressure"
	SensorSpeed                         = "speed"
	SensorSulphurDioxide                = "sulphur_dioxide"
	SensorTemperature                   = "temperature"
	SensorTimestamp                     = "timestamp"
	SensorVolatileOrganicCompounds      = "volatile_organic_compounds"
	SensorVolatileOrganicCompoundsParts = "volatile_organic_compounds_parts"
	SensorVoltage                       = "voltage"
	SensorVolume                        = "volume"
	SensorVolumeFlowRate                = "volume_flow_rate"
	SensorVolumeStorage                 = "volume_storage"
	SensorWater                         = "water"
	SensorWeight                        = "weight"
	SensorWindDirection                 = "wind_direction"
	SensorWindSpeed                     = "wind_speed"

	SensorMeasurement      = "measurement"
	SensorMeasurementAngle = "measurement_angle"
	SensorTotal            = "total"
	SensorTotalIncreasing  = "total_increasing"

	SensorAcre                          = "ac"
	SensorAmpere                        = "A"
	SensorAWeightedDecibel              = "dBA"
	SensorBar                           = "bar"
	SensorBit                           = "bit"
	SensorBitsPerSecond                 = "bit/s"
	SensorBTUPerHourPerSquareFoot       = "BTU/(h⋅ft²)"
	SensorByte                          = "B"
	SensorBytesPerSecond                = "B/s"
	SensorCalorie                       = "cal"
	SensorCentibar                      = "cbar"
	SensorCentimeter                    = "cm"
	SensorCubicFeetPerMinute            = "ft³/min"
	SensorCubicFoot                     = "ft³"
	SensorCubicMeter                    = "m³"
	SensorCubicMetersPerHour            = "m³/h"
	SensorCubicMetersPerMinute          = "m³/min"
	SensorCubicMetersPerSecond          = "m³/s"
	SensorDay                           = "d"
	SensorDecibel                       = "dB"
	SensorDecibelMilliwatt              = "dBm"
	SensorDegrees                       = "°"
	SensorDegreesCelsius                = "°C"
	SensorDegreesFahrenheit             = "°F"
	SensorExabyte                       = "EB"
	SensorExbibyte                      = "EiB"
	SensorFeetPerSecond                 = "ft/s"
	SensorFluidOunce                    = "fl. oz."
	SensorGallon                        = "gal"
	SensorGallonsPerHour                = "gal/h"
	SensorGallonsPerMinute              = "gal/min"
	SensorGibibyte                      = "GiB"
	SensorGibibytesPerSecond            = "GiB/s"
	SensorGigabit                       = "Gbit"
	SensorGigabitsPerSecond             = "Gbit/s"
	SensorGigabyte                      = "GB"
	SensorGigabytesPerSecond            = "GB/s"
	SensorGigacalorie                   = "Gcal"
	SensorGigahertz                     = "GHz"
	SensorGigajoule                     = "GJ"
	SensorGigawatt                      = "GW"
	SensorGigawattHour                  = "GWh"
	SensorGram                          = "g"
	SensorGramsPerCubicMeter            = "g/m³"
	SensorHectare                       = "ha"
	SensorHectopascal                   = "hPa"
	SensorHertz                         = "Hz"
	SensorHour                          = "h"
	SensorHundredCubicFeet              = "CCF"
	SensorInch                          = "in"
	SensorInchesOfMercury               = "inHg"
	SensorInchesOfWater                 = "inH₂O"
	SensorInchesPerDay                  = "in/d"
	SensorInchesPerHour                 = "in/h"
	SensorInchesPerSecond               = "in/s"
	SensorJoule                         = "J"
	SensorKelvin                        = "K"
	SensorKibibyte                      = "KiB"
	SensorKibibytesPerSecond            = "KiB/s"
	SensorKilobit                       = "kbit"
	SensorKilobitsPerSecond             = "kbit/s"
	SensorKilobyte                      = "kB"
	SensorKilobytesPerSecond            = "kB/s"
	SensorKilocalorie                   = "kcal"
	SensorKilogram                      = "kg"
	SensorKilohertz                     = "kHz"
	SensorKilojoule                     = "kJ"
	SensorKilometer                     = "km"
	SensorKilometersPerHour             = "km/h"
	SensorKilometersPerKilowattHour     = "km/kWh"
	SensorKilopascal                    = "kPa"
	SensorKilovar                       = "kvar"
	SensorKilovarHour                   = "kvarh"
	SensorKilovolt                      = "kV"
	SensorKilovoltAmpere                = "kVA"
	SensorKilowatt                      = "kW"
	SensorKilowattHour                  = "kWh"
	SensorKilowattHoursPer100Kilometers = "kWh/100km"
	SensorKnot                          = "kn"
	SensorLiter                         = "L"
	SensorLitersPerHour                 = "L/h"
	SensorLitersPerMinute               = "L/min"
	SensorLitersPerSecond               = "L/s"
	SensorLux                           = "lx"
	SensorMebibyte                      = "MiB"
	SensorMebibytesPerSecond            = "MiB/s"
	SensorMegabit                       = "Mbit"
	SensorMegabitsPerSecond             = "Mbit/s"
	SensorMegabyte                      = "MB"
	SensorMegabytesPerSecond            = "MB/s"
	SensorMegacalorie                   = "Mcal"
	SensorMegahertz                     = "MHz"
	SensorMegajoule                     = "MJ"
	SensorMegavar                       = "mvar"
	SensorMegavolt                      = "MV"
	SensorMegawatt                      = "MW"
	SensorMegawattHour                  = "MWh"
	SensorMeter                         = "m"
	SensorMetersPerSecond               = "m/s"
	SensorMicrogram                     = "µg"
	SensorMicrogramsPerCubicCentimeter  = "µg/m³"
	SensorMicrogramsPerCubicMeter       = "µg/m³"
	SensorMicrosecond                   = "µs"
	SensorMicrosiemensPerCentimeter     = "µS/cm"
	SensorMicrovolt                     = "µV"
	SensorMile                          = "mi"
	SensorMilesPerHour                  = "mph"
	SensorMilesPerKilowattHour          = "mi/kWh"
	SensorMilliampere                   = "mA"
	SensorMillibar                      = "mbar"
	SensorMilligram                     = "mg"
	SensorMilligramsPerCubicMeter       = "mg/m³"
	SensorMilligramsPerDeciliter        = "mg/dL"
	SensorMilliliter                    = "mL"
	SensorMillilitersPerSecond          = "mL/s"
	SensorMillimeter                    = "mm"
	SensorMillimetersOfMercury          = "mmHG"
	SensorMillimetersPerDay             = "mm/d"
	SensorMillimetersPerHour            = "mm/h"
	SensorMillimetersPerSecond          = "mm/s"
	SensorMillimolesPerLiter            = "mmol/L"
	SensorMillisecond                   = "ms"
	SensorMillisiemensPerCentimeter     = "mS/cm"
	SensorMillivolt                     = "mV"
	SensorMillivoltAmpere               = "mVA"
	SensorMilliwatt                     = "mW"
	SensorMilliwattHour                 = "mWh"
	SensorMinute                        = "min"
	SensorNauticalMile                  = "nmi"
	SensorOunce                         = "oz"
	SensorPartsPerBillion               = "ppb"
	SensorPartsPerMillion               = "ppm"
	SensorPascal                        = "Pa"
	SensorPebibyte                      = "PiB"
	SensorPercentage                    = "%"
	SensorPetabyte                      = "PB"
	SensorPound                         = "lb"
	SensorPoundsPerSquareInch           = "psi"
	SensorSecond                        = "s"
	SensorSiemensPerCentimeter          = "S/cm"
	SensorSquareCentimeter              = "cm²"
	SensorSquareFoot                    = "ft²"
	SensorSquareInch                    = "in²"
	SensorSquareKilometer               = "km²"
	SensorSquareMeter                   = "m²"
	SensorSquareMile                    = "mi²"
	SensorSquareYard                    = "yd²"
	SensorStone                         = "st"
	SensorTebibyte                      = "TiB"
	SensorTerabyte                      = "TB"
	SensorTerawatt                      = "TW"
	SensorTerawattHour                  = "TWh"
	SensorThousandCubicFeet             = "MCF"
	SensorVolt                          = "V"
	SensorVoltAmpere                    = "VA"
	SensorVoltAmpereReactive            = "var"
	SensorVoltAmpereReactiveHour        = "varh"
	SensorWatt                          = "W"
	SensorWattHour                      = "Wh"
	SensorWattHoursPerKilometer         = "Wh/km"
	SensorWattsPerSquareMeter           = "W/m²"
	SensorYard                          = "yd"
	SensorYobibyte                      = "YiB"
	SensorYottabyte                     = "YB"
	SensorZebibyte                      = "ZiB"
	SensorZettabyte                     = "ZB"
)
View Source
const (
	SwitchOutlet = "outlet"
	SwitchSwitch = "switch"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BinarySensor

type BinarySensor struct {
	Entity
	// contains filtered or unexported fields
}

BinarySensor represents a sensor with binary state, such as a door being open or a switch being on.

func (*BinarySensor) SetValue

func (b *BinarySensor) SetValue(state bool) error

SetValue updates the binary sensor's value.

type BinarySensorConfig

type BinarySensorConfig struct {

	// State provides the initial state of the binary sensor.
	State bool `json:"-"`

	// DeviceClass categorizes the type of data reported by the sensor.
	DeviceClass string `json:"device_class,omitempty"`
}

BinarySensorConfig provides configuration for BinarySensor.

type Button

type Button struct {
	Entity
}

Button represents a button that can be pressed to perform an action.

type ButtonConfig

type ButtonConfig struct {

	// DeviceClass categorizes the button.
	DeviceClass string `json:"device_class,omitempty"`

	// PressCallback is invoked when the button is pressed.
	PressCallback func() `json:"-"`
}

ButtonConfig provides configuration for Button.

type Config

type Config struct {

	// Addr provides the address of the MQTT broker to connect to.
	Addr string

	// Username provides the username to use for authenticating to the broker.
	Username string

	// Password provides the password to use for authenticating to the broker.
	Password string

	// DiscoveryPrefix provides the MQTT discovery prefix to use. If left
	// empty, this defaults to "homeassistant".
	DiscoveryPrefix string

	// ID provides the unique ID of the device. If left empty, the current
	// hostname (after removing invalid characters) is used.
	ID string

	// Name provides the name of the device. If left empty, the value of ID is
	// used.
	Name string

	// Manufacturer provides the manufacturer of the device.
	Manufacturer string

	// Model provides the model of the device.
	Model string
}

Config provides configuration for instantiating Conn instances.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn maintains a connection to an MQTT broker.

func New

func New(cfg *Config) (*Conn, error)

New creates a new Conn instance with the provided configuration.

func (*Conn) BinarySensor

func (c *Conn) BinarySensor(
	entityCfg *EntityConfig,
	cfg *BinarySensorConfig,
) (*BinarySensor, error)

BinarySensor creates a new binary sensor entity.

func (*Conn) Button

func (c *Conn) Button(
	entityCfg *EntityConfig,
	cfg *ButtonConfig,
) (*Button, error)

Button creates a new button entity with the provided configuration.

func (*Conn) Close

func (c *Conn) Close()

Close shuts down the connection.

func (*Conn) Event

func (c *Conn) Event(
	entityCfg *EntityConfig,
	cfg *EventConfig,
) (*Event, error)

Event creates a new event entity.

func (*Conn) Light

func (c *Conn) Light(
	entityCfg *EntityConfig,
	cfg *LightConfig,
) (*Light, error)

Light creates a new light entity.

func (*Conn) Notify

func (c *Conn) Notify(
	entityCfg *EntityConfig,
	cfg *NotifyConfig,
) (*Notify, error)

Notify creates a new notify entity.

func (*Conn) Sensor

func (c *Conn) Sensor(
	entityCfg *EntityConfig,
	cfg *SensorConfig,
) (*Sensor, error)

Sensor creates a new sensor entity.

func (*Conn) Switch

func (c *Conn) Switch(
	entityCfg *EntityConfig,
	cfg *SwitchConfig,
) (*Switch, error)

Switch creates a new switch entity.

type Entity

type Entity struct {
	// contains filtered or unexported fields
}

Entity provides base functionality for all entities.

func (*Entity) SetAvailability

func (e *Entity) SetAvailability(availability bool) error

SetAvailability indicates whether the entity is available or not.

type EntityConfig

type EntityConfig struct {

	// ID provides the unique ID of the entity.
	ID string `json:"unique_id"`

	// Name provides the name of the entity.
	Name string `json:"name"`

	// Unavailable makes the entity unavailable until explicitly set.
	Unavailable bool `json:"-"`
}

EntityConfig provides basic configuration for all entities.

type Event

type Event struct {
	Entity
	// contains filtered or unexported fields
}

Event represents an entity that periodically sends events.

func (*Event) Send

func (e *Event) Send(eventType string) error

Send sends the specified event.

type EventConfig

type EventConfig struct {

	// DeviceClass categorizes the type of event.
	DeviceClass string `json:"device_class,omitempty"`

	// EventTypes is a list of valid events (i.e. "press", "hold", etc.).
	EventTypes []string `json:"event_types,omitempty"`
}

EventConfig provides configuration for Event.

type Light

type Light struct {
	Entity
	// contains filtered or unexported fields
}

Light represents an entity that provides illumination.

func (*Light) SetValue

func (l *Light) SetValue(value bool) error

SetValue indicates whether the light is on or off.

type LightConfig

type LightConfig struct {

	// State provides the initial state of the light.
	State bool `json:"-"`

	// ChangeCallback is invoked when the light is to be turned on or off.
	// Returning true will cause a corresponding change to the light's state.
	// Alternatively, SetValue can be used to indicate state.
	ChangeCallback func(bool) bool `json:"-"`
}

LightConfig provides configuration for Light.

type Notify

type Notify struct {
	Entity
}

Notify represents an entity that receives and processes notifications.

type NotifyConfig

type NotifyConfig struct {

	// NotifyCallback is invoked when a new notification is received.
	NotifyCallback func(payload string) `json:"-"`
}

NotifyConfig provides configuration for Notify.

type Sensor

type Sensor struct {
	Entity
	// contains filtered or unexported fields
}

Sensor represents a sensor that reports readings at regular intervals.

func (*Sensor) SetValue

func (s *Sensor) SetValue(value string) error

SetValue updates the sensor's value.

type SensorConfig

type SensorConfig struct {

	// DeviceClass categorizes the type of data reported by the sensor.
	DeviceClass string `json:"device_class,omitempty"`

	// StateClass categorizes the nature of the data reported.
	StateClass string `json:"state_class,omitempty"`

	// Options is a list of allowed values if DeviceClass is SensorEnum.
	Options []string `json:"options,omitempty"`

	// UnitOfMeasurement indicates the unit for the sensor's values.
	UnitOfMeasurement string `json:"unit_of_measurement,omitempty"`

	// SuggestedDisplayPrecision indicates the number of decimal places that
	// should be used to display the sensor's value.
	SuggestedDisplayPrecision int `json:"suggested_display_precision,omitempty"`
}

SensorConfig provides configuration for Sensor.

type Switch

type Switch struct {
	Entity
	// contains filtered or unexported fields
}

Switch represents an entity that can be switched on and off.

func (*Switch) SetValue

func (s *Switch) SetValue(value bool) error

SetValue indicates whether the switch is on or off.

type SwitchConfig

type SwitchConfig struct {

	// State provides the initial state of the switch.
	State bool `json:"-"`

	// DeviceClass categorizes the type of switch.
	DeviceClass string `json:"device_class,omitempty"`

	// ChangeCallback is invoked when the switch is to be turned on or off.
	// Returning true will cause a corresponding change to the switch's state.
	// Alternatively, SetValue can be used to indicate state.
	ChangeCallback func(bool) bool `json:"-"`
}

SwitchConfig provides configuration for Switch.

Directories

Path Synopsis
examples
binary_sensor command
button command
event command
light command
notify command
sensor command
switch command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL