hqtt

package module
v0.0.0-...-45466fc Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2025 License: MIT Imports: 13 Imported by: 0

README

hqtt - Go SDK for writing Home Assistant MQTT Integrations

Go Reference Coverage Status Go Report Card License

[!IMPORTANT] This SDK Requires Go 1.25+. If using Go 1.25, the jsonv2 GOEXPERIMENT must be enabled.

[!WARNING] This SDK is still under active development. The API probably will change. Feel free to experiment but expect missing features, bugs, and functionality to break as development continues.

The SDK is designed around Home Assistant MQTT Device Discovery via the Device type. Devices contain one or more Component[T Platform] components which map to entities provided by the device. The Platform interface provides basic platform information that is required to form the Device Discovery payload:

package hqtt

// Platform is the interface implemented by every MQTT Entity Component type.
type Platform interface {
    mqtt.Handler

    // MarshalDiscoveryTo marshals MQTT Device Discovery information to the specified jsontext.Encoder using the
    // provided prefix for all MQTT Topics.
    MarshalDiscoveryTo(e *jsontext.Encoder, prefix string) error

    // PlatformName returns the value for the `platform` field when configuring a component using this platform for MQTT
    // Device Discovery.
    PlatformName() string

    // Subscriptions returns the set of paho.SubscribeOptions for configured fields of this component. Only fields that
    // are properly configured should be included. Typically, each subscription is individually subscribed to, but other
    // mqtt.Subscriber implementations may choose to group topics with wildcards.
    Subscriptions(prefix string) []mqtt.Subscription
}

The following platforms are currently implemented:

You can create a Component for other MQTT Entity types by providing a type that satisfies the Platform interface, but if you find yourself implementing a core MQTT Entity type provided by Home Assistant please send a pull request to add it to the SDK!

The discovery package provides helpers for constructing minified Device Discovery payloads (including constants for abbreviated field keys). Unless you are implementing support for a new platform you will typically not need to import this package.

This package also contains a helper for watching the state of Home Assistant itself (which it publishes to homeassistant/status by default).

A subset of Home Assistant core types (e.g. Availability, Power/Switch state, etc.) are provided by the hass package.

HQTT utilizes log/slog for logging. See the log package package for details on configuring logging for the SDK.

MQTT Client Support

MQTT abstractions are provided by the mqtt package. The two main types you will interact with are Value[T any] (for values that should be written to an MQTT topic), and RemoteValute[T any] (for values to be read from MQTT Subscriptions).

Values require a ValueMarshaler[T] which is used to encode the value when writing to MQTT. Typically, this is a StringMarshaler (which encodes the value as a string), or a JsonValueMarshaler (which encodes the value using its JSON representation).

RemoteValues require a ValueUnmarshaler[T], which does the same thing but in reverse.

Right now, the only officially supported client is github.com/eclipse/paho.golang/autopaho, a v5 MQTT client by Eclipse. You can implement your own adapter for any client by implementing the following interfaces from the mqtt package:

package mqtt

// Writer is the minimum abstraction around writing values to MQTT.
type Writer interface {
	// WriteTopic writes the provided value to the specified topic with the specified WriteOptions.
	WriteTopic(ctx context.Context, topic string, options WriteOptions, value []byte) error
}

// Subscriber manages MQTT Subscriptions
type Subscriber interface {
    // Subscribe configures the underlying MQTT connection to send the client messages for the provided subscriptions.
    // The provided Handler will be called for all subscribed topics in this call.
    Subscribe(ctx context.Context, handler Handler, subscriptions ...Subscription) error

    // Unsubscribe removes any subscriptions configured for the specified topics.
    Unsubscribe(ctx context.Context, topics ...string) error
}

See example/fake_light for a small example.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// DefaultOrigin provides origin information to Home Assistant for applications that do not otherwise specify one.
	DefaultOrigin = Origin{
		Name:            "hqtt",
		SoftwareVersion: "master",
		SupportURL:      hqttSupportUrl,
	}
)
View Source
var ErrComponentAlreadySubscribed = errors.New("component already subscribed")

ErrComponentAlreadySubscribed is the error returned by Component.Subscribe when it has already been subscribed. Call Component.Unsubscribe first.

View Source
var ErrInvalidDevice = errors.New("device must have at least one identifying value in 'identifiers' and/or 'connections'")

ErrInvalidDevice is the error returned by Device.Configure and Device.Valid if it is not properly configured.

Functions

This section is empty.

Types

type Component

type Component[TPlatform Platform] struct {
	Platform    TPlatform
	TopicPrefix string

	// The name of the entity. Set to the empty string if only the device name is relevant.
	Name string

	// The category of the entity. See https://developers.home-assistant.io/docs/core/entity/#generic-properties
	EntityCategory string

	// The Icon to use in the frontend for this entity
	Icon string

	// Picture URL for the entity.
	Picture *url.URL

	// Identifies to home assistant whether this entity is available
	Availability *mqtt.Value[hass.Availability] `hqtt:"required"`
	// Custom values to use for available and unavailable states
	CustomAvailabilityValues hass.CustomAvailability

	// Use this value instead of name for automatic generation of the entity ID. For example, `light.foobar`. When used
	// without a UniqueID, the entity ID will update during restart or reload if the entity ID is available. If the
	// entity ID already exists, the entity ID will be created with a number at the end. When used with a UniqueID, the
	// DefaultEntityID is only used when the entity is added for the first time. When set, this overrides a
	// user-customized entity ID if the entity was deleted and added again.
	DefaultEntityID string

	// An ID that uniquely identifies this light. If two lights have the same unique ID, Home Assistant will raise an
	// exception. Required when used with device-based discovery.
	UniqueID string `hqtt:"required"`

	// MQTT Options to use when publishing updates for this device
	WriteOptions mqtt.WriteOptions
	// contains filtered or unexported fields
}

Component exposes HomeAssistant components (sensors, switches, lights, etc.) associated with a given device. It implements json.MarshalerTo by encoding the component for a Home Assistant Device Discovery payload.

func (*Component[TPlatform]) ForRemoval

func (c *Component[TPlatform]) ForRemoval() RemoveComponent

func (*Component[TPlatform]) MarshalJSONTo

func (c *Component[TPlatform]) MarshalJSONTo(e *jsontext.Encoder) error

func (*Component[TPlatform]) Subscribe

func (c *Component[TPlatform]) Subscribe(ctx context.Context, s mqtt.Subscriber) error

Subscribe registers MQTT Subscriptions for fields in use by this Component using the provided mqtt.SubscriptionManager. The subscriptions can be removed by calling Unsubscribe.

TODO: Wire LWT to availability.

func (*Component[TPlatform]) Unsubscribe

func (c *Component[TPlatform]) Unsubscribe(ctx context.Context, s mqtt.Subscriber) error

Unsubscribe removes MQTT Subscriptions for fields in use by this Component from the provided mqtt.SubscriptionManager.

type Device

type Device struct {
	// The ID to use for discovery. If empty, an ID is calculated from other fields.
	DiscoveryID string `json:"-"`

	// The name of the device.
	Name string `json:"name,omitempty"`

	// The serial number of the device
	Serial string `json:"sn,omitempty"`

	// The manufacturer of the device.
	Manufacturer string `json:"mf,omitempty"`

	// The model of the device.
	Model string `json:"mdl,omitempty"`

	// The model identifier of the device.
	ModelID string `json:"mdl_id,omitempty"`

	// A link to the webpage that can manage the configuration of this device. Can be either a http://, https:// or an
	// internal homeassistant:// URL.
	ConfigurationURL *url.URL `json:"cu,omitempty"`

	// A list of connections of the device to the outside world. For example, `[]DeviceConnection{{Kind: "mac", Value: "02:5b:26:a8:dc:12"]}}`
	Connections []DeviceConnection `json:"cns,omitempty"`

	// The hardware version of the device.
	HardwareVersion string `json:"hw,omitempty"`

	// The firmware version of the device
	FirmwareVersion string `json:"sw,omitempty"`

	// A list of IDs that uniquely identify the device. For example a serial number.
	Identifiers []string `json:"ids,omitempty"`

	// Suggest an area if the devic e isn't in one yet
	SuggestedArea string `json:"sa,omitempty"`

	// It is recommended to add information about the origin of MQTT entities. The origin details will be logged in the
	// core event log when an item is discovered or updated. Adding origin information helps with troubleshooting and
	// provides valuable context about the source of MQTT messages in your Home Assistant setup. Home Assistant requires
	// origin information be specified when using Device-based Discovery. If omitted, DefaultOrigin will be used when
	// serializing the discovery payload instead.
	Origin *Origin `json:"-"`

	// Identifier of a device that routes messages between this device and Home Assistant. Examples of such devices are
	// hubs, or parent devices of a sub-device. This is used to show device topology in Home Assistant.
	ViaDevice string `json:"via_device,omitempty"`
}

Device represents an MQTT-based HomeAssistant device. In the Home Assistant MQTT Integration, a Device is a collection of "Components" (entities). This relationship is only constructed when marshaling the discovery payload to the MQTT Broker.

See https://www.home-assistant.io/integrations/mqtt/#device-discovery-payload

func (*Device) Configure

func (d *Device) Configure(ctx context.Context, w mqtt.Writer, discoveryPrefix string, components map[string]json.MarshalerTo) error

Configure updates the device discovery payload for this device and the provided components, which are associated with this Device. To remove components from the device, replace the component in the map with a RemoveComponent when calling Configure.

The device must pass validation performed by Device.Valid.

func (*Device) ID

func (d *Device) ID() string

ID calculates an identifier for this device. If the Device.DiscoveryID is specified, that value will be used. Otherwise, if any of the following fields are set, they are used (separated by discovery.IDSep): All Device.Identifiers, Device.Name, Device.Serial, Device.Manufacturer, Device.Model, and Device.ModelID.

func (*Device) Valid

func (d *Device) Valid() error

Valid checks if this Device is configured appropriately. Home Assistant requires at least one value be configured for Device.Identifiers, or at least one value be configured for Device.Connections.

type DeviceConnection

type DeviceConnection struct {
	Kind  string
	Value string
}

DeviceConnection maps this Device to the outside world. For example:

DeviceConnection{
    Kind: "mac",
    Value: "02:5b:26:a8:dc:12",
}

It implements fmt.Stringer and slog.LogValuer

func (DeviceConnection) LogValue

func (d DeviceConnection) LogValue() slog.Value

func (DeviceConnection) MarshalJSONTo

func (d DeviceConnection) MarshalJSONTo(e *jsontext.Encoder) error

func (DeviceConnection) String

func (d DeviceConnection) String() string

type Origin

type Origin struct {
	// The name of the application that is the origin of the discovered MQTT item.
	Name string `json:"name"`
	// Software version of the application that supplies the discovered MQTT item.
	SoftwareVersion string `json:"sw,omitempty"`
	// Support URL of the application that supplies the discovered MQTT item.
	SupportURL *url.URL `json:"url,omitempty"`
}

Origin provides information about the software providing devices over MQTT to Home Assistant. See the documentation for Device.Origin for details.

type Platform

type Platform interface {
	mqtt.Handler

	// MarshalDiscoveryTo marshals MQTT Device Discovery information to the specified jsontext.Encoder using the
	// provided prefix for all MQTT Topics.
	MarshalDiscoveryTo(e *jsontext.Encoder, prefix string) error

	// PlatformName returns the value for the `platform` field when configuring a component using this platform for MQTT
	// Device Discovery.
	PlatformName() string

	// Subscriptions returns the set of paho.SubscribeOptions for configured fields of this component. Only fields that
	// are properly configured should be included. Typically, each subscription is individually subscribed to, but other
	// mqtt.Subscriber implementations may choose to group topics with wildcards.
	Subscriptions(prefix string) []mqtt.Subscription
}

Platform is the interface implemented by every MQTT Entity Component type.

type RemoveComponent

type RemoveComponent struct {
	Platform string `json:"platform"`
}

RemoveComponent is used to remove a Component from device discovery. Construct a RemoveComponent with the appropriate platform name manually or use Component.ForRemoval.

func (RemoveComponent) MarshalJSONTo

func (r RemoveComponent) MarshalJSONTo(e *jsontext.Encoder) error

Directories

Path Synopsis
Package discovery contains constants and utilities for constructing Home Assistant Device Discovery MQTT Payloads.
Package discovery contains constants and utilities for constructing Home Assistant Device Discovery MQTT Payloads.
Package hass defines constants and helpers for interacting with Home Assistant.
Package hass defines constants and helpers for interacting with Home Assistant.
Package log provides utilities for using log/slog with hqtt.
Package log provides utilities for using log/slog with hqtt.
Package mqtt contains utilities for interacting with MQTT Brokers using the github.com/eclipse/paho.golang, a v5 MQTT client.
Package mqtt contains utilities for interacting with MQTT Brokers using the github.com/eclipse/paho.golang, a v5 MQTT client.
adapter/autopaho
Package autopaho adapts github.com/eclipse/paho.golang/autopaho for use with github.com/nlowe/hqtt.
Package autopaho adapts github.com/eclipse/paho.golang/autopaho for use with github.com/nlowe/hqtt.
Package platform contains implementations for various Home Assistant MQTT platforms.
Package platform contains implementations for various Home Assistant MQTT platforms.