adapter

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package adapter provides a high-level API for Z-Stack Zigbee adapters.

Index

Constants

View Source
const (
	// StatusSuccess indicates the operation completed successfully.
	StatusSuccess uint8 = 0x00
	// StatusAlreadyRegistered indicates the endpoint is already registered.
	// This is returned by AfRegister when trying to register an existing endpoint.
	StatusAlreadyRegistered uint8 = 0xB8
)

ZNP status codes returned by various operations.

View Source
const CoordinatorEndpoint = 1

Default coordinator endpoint (Home Automation profile).

View Source
const DedupeWindow = 2 * time.Second

DedupeWindow is the default time window for message deduplication. Messages with the same (srcAddr, clusterID, transSeqNum) within this window are considered duplicates and filtered out.

Variables

View Source
var CoordinatorEndpoints = []EndpointDef{

	{
		Endpoint:  1,
		ProfileID: znp.ProfileHomeAutomation,
		DeviceID:  0x0005,
		InClusters: []uint16{
			uint16(zcl.ClusterBasic),
		},
		OutClusters: []uint16{
			uint16(zcl.ClusterBasic),
			uint16(zcl.ClusterOnOff),
			uint16(zcl.ClusterLevelControl),
			uint16(zcl.ClusterColorControl),
			uint16(zcl.ClusterPowerConfig),
		},
	},

	{
		Endpoint:  2,
		ProfileID: znp.ProfileSmartEnergy,
		DeviceID:  0x0005,
		InClusters: []uint16{
			uint16(zcl.ClusterBasic),
		},
		OutClusters: []uint16{
			uint16(zcl.ClusterBasic),
		},
	},

	{
		Endpoint:  3,
		ProfileID: znp.ProfileGreenPower,
		DeviceID:  0x0005,
		InClusters: []uint16{
			uint16(zcl.ClusterBasic),
		},
		OutClusters: []uint16{
			uint16(zcl.ClusterBasic),
		},
	},

	{
		Endpoint:  11,
		ProfileID: znp.ProfileGreenPower,
		DeviceID:  0x0066,
		InClusters: []uint16{
			0x0021,
		},
		OutClusters: []uint16{
			0x0021,
		},
	},

	{
		Endpoint:  110,
		ProfileID: znp.ProfileLightLink,
		DeviceID:  0x0005,
		InClusters: []uint16{
			uint16(zcl.ClusterBasic),
		},
		OutClusters: []uint16{
			uint16(zcl.ClusterBasic),
			uint16(zcl.ClusterOnOff),
			uint16(zcl.ClusterLevelControl),
			uint16(zcl.ClusterColorControl),
		},
	},

	{
		Endpoint:  242,
		ProfileID: znp.ProfileGreenPower,
		DeviceID:  0x0061,
		InClusters: []uint16{
			0x0021,
		},
		OutClusters: []uint16{
			0x0021,
		},
	},
}

Standard coordinator endpoints. Each endpoint is registered with a specific Application Profile to enable communication with devices using that profile.

View Source
var ErrNotOpen = errors.New("adapter not open")

ErrNotOpen is returned when an operation is attempted on a closed adapter.

ProfileToEndpoint maps application profiles to their primary endpoint.

Functions

func GetEndpointForProfile

func GetEndpointForProfile(profile znp.ApplicationProfile) uint8

GetEndpointForProfile returns the coordinator endpoint to use for a given profile. Returns endpoint 1 (HA) as default for unknown profiles.

func QuarterSecondsToSeconds

func QuarterSecondsToSeconds(quarterSecs uint32) float64

QuarterSecondsToSeconds converts quarter seconds to seconds. Quarter seconds are commonly used in Zigbee for timing intervals. 4 quarter seconds = 1 second.

func SecondsToQuarterSeconds

func SecondsToQuarterSeconds(secs float64) uint32

SecondsToQuarterSeconds converts seconds to quarter seconds. Quarter seconds are commonly used in Zigbee for timing intervals. 1 second = 4 quarter seconds.

func SupportedProfiles

func SupportedProfiles() []znp.ApplicationProfile

SupportedProfiles returns all Application Profiles that zigbee-herdsman supports. These are the profiles for which endpoints are registered on the coordinator.

func UnixToZigbeeTime

func UnixToZigbeeTime(t time.Time) uint32

UnixToZigbeeTime converts Unix time to Zigbee time (seconds since 2000-01-01). Returns uint32 seconds since January 1, 2000 00:00:00 UTC.

func ZigbeeTimeToUnix

func ZigbeeTimeToUnix(zigbeeTime uint32) time.Time

ZigbeeTimeToUnix converts Zigbee time (seconds since 2000-01-01) to Unix time. Zigbee time is uint32 seconds since January 1, 2000 00:00:00 UTC. Unix time is int64 seconds since January 1, 1970 00:00:00 UTC.

Types

type Adapter

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

Adapter represents a Z-Stack Zigbee adapter.

func New

func New(opts ...Option) *Adapter

New creates a new adapter with the given options.

func (*Adapter) AddScene

func (a *Adapter) AddScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, sceneID uint8, transitionTime uint16, sceneName string) error

AddScene adds a scene with explicit parameters. This is an advanced command that allows specifying scene details explicitly rather than capturing current device state like StoreScene does. groupID must be a valid group the device belongs to (or 0x0000 for global scenes). sceneID is 0-255. transitionTime is in tenths of a second (e.g., 10 = 1 second). sceneName is optional (max 16 characters). Note: This only creates the scene metadata. To capture device state, use StoreScene instead.

func (*Adapter) AddToGroup

func (a *Adapter) AddToGroup(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, groupName string) error

AddToGroup adds a device endpoint to a group. groupID is the 16-bit group address (1-65535). groupName is optional (can be empty string).

func (*Adapter) AdjustThermostatSetpoint

func (a *Adapter) AdjustThermostatSetpoint(ctx context.Context, nwkAddr uint16, endpoint uint8, mode uint8, amount int8) error

AdjustThermostatSetpoint raises or lowers the thermostat setpoint. This uses the SetpointRaiseLower command to adjust the setpoint by a relative amount.

Parameters:

  • mode: 0=Heat, 1=Cool, 2=Both
  • amount: Adjustment amount in 0.1°C increments (positive to raise, negative to lower)

Example: Raise heating setpoint by 1°C:

err := adapter.AdjustThermostatSetpoint(ctx, nwkAddr, endpoint, 0, 10)

func (*Adapter) Bind

func (a *Adapter) Bind(ctx context.Context, deviceIEEEAddr [8]byte, deviceNwkAddr uint16, deviceEndpoint uint8, clusterID uint16, coordinatorIEEEAddr [8]byte, coordinatorEndpoint uint8) error

Bind creates a binding entry on a device, telling it where to send reports. This is essential for devices to automatically send attribute reports to the coordinator. Without binding, devices don't know where to send their reports.

Typical usage: Bind a device's cluster to the coordinator so it reports state changes.

Parameters:

  • deviceIEEEAddr: IEEE address of the device to configure binding on
  • deviceNwkAddr: Network address of the device
  • deviceEndpoint: Source endpoint on the device
  • clusterID: Cluster ID to bind (e.g., OnOff, Temperature)
  • coordinatorIEEEAddr: IEEE address of the coordinator (destination)
  • coordinatorEndpoint: Coordinator endpoint (typically 1)

Example:

// Bind device's OnOff cluster to coordinator
err := adapter.Bind(ctx, deviceIEEE, deviceNwk, 1, zcl.ClusterOnOff, coordIEEE, 1)

func (*Adapter) CancelSEMessage

func (a *Adapter) CancelSEMessage(ctx context.Context, nwkAddr uint16, endpoint uint8, messageID uint32) error

CancelSEMessage cancels a specific message on a Smart Energy device. This sends a CancelMessage command to remove a previously displayed message.

Parameters:

  • messageID: The unique identifier of the message to cancel

Example: Cancel message with ID 1:

err := adapter.CancelSEMessage(ctx, nwkAddr, endpoint, 1)

func (*Adapter) ChangeChannel

func (a *Adapter) ChangeChannel(ctx context.Context, channel uint8, seamless bool) error

ChangeChannel changes the network channel. If seamless is true, broadcasts update to all devices (requires formed network). If seamless is false, forces local channel change (breaks existing network).

func (*Adapter) ClearDoorLockPIN

func (a *Adapter) ClearDoorLockPIN(ctx context.Context, nwkAddr uint16, endpoint uint8, userID uint16) error

ClearDoorLockPIN removes a user's PIN code. userID is the user identifier to clear.

func (*Adapter) Close

func (a *Adapter) Close() error

Close closes the adapter and releases all resources.

func (*Adapter) CloseWindowCovering

func (a *Adapter) CloseWindowCovering(ctx context.Context, nwkAddr uint16, endpoint uint8) error

CloseWindowCovering fully closes (lowers) the covering. This sends the DownClose command to the device.

func (*Adapter) ConfigureReporting

func (a *Adapter) ConfigureReporting(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, attributeID zcl.AttributeID, dataType zcl.DataType, minInterval, maxInterval uint16, reportableChange interface{}) error

ConfigureReporting configures a device to automatically report attribute changes. This allows devices to push updates instead of requiring polling.

Parameters:

  • nwkAddr: Network address of the target device
  • endpoint: Endpoint number on the device
  • clusterID: Cluster ID containing the attribute
  • attributeID: Attribute ID to configure
  • dataType: Data type of the attribute
  • minInterval: Minimum reporting interval in seconds (0 = no minimum)
  • maxInterval: Maximum reporting interval in seconds (0xFFFF = no periodic reports)
  • reportableChange: Minimum change to trigger a report (for analog types, nil for discrete types)

Example: Configure temperature sensor to report every 60-300s or on 0.5°C change:

err := adapter.ConfigureReporting(ctx, nwkAddr, endpoint, zcl.ClusterTempMeasurement,
    zcl.AttrTempMeasuredValue, zcl.TypeInt16, 60, 300, int16(50)) // 50 = 0.5°C in 0.01 units

func (*Adapter) CreateBackup

func (a *Adapter) CreateBackup(ctx context.Context) (*backup.Backup, error)

CreateBackup creates a full backup of the adapter configuration.

func (*Adapter) DeleteDeviceName

func (a *Adapter) DeleteDeviceName(ctx context.Context, ieeeAddr [8]byte) error

DeleteDeviceName removes the custom name for a device.

func (*Adapter) DisplaySEMessage

func (a *Adapter) DisplaySEMessage(ctx context.Context, nwkAddr uint16, endpoint uint8, msg SEMessage) error

DisplaySEMessage sends a message to be displayed on a Smart Energy device. The message is sent using the Messaging cluster (0x0703) DisplayMessage command.

Parameters:

  • msg: The message to display, including message ID, control flags, timing, and text

The Control field is a bitmap specifying:

  • Transmission type (normal or anonymous)
  • Importance level (low, medium, high, critical)
  • Whether confirmation is required

Use zcl.SEMsgCtrl* constants to build the control byte.

Example: Display a high-importance message immediately for 60 minutes:

msg := adapter.SEMessage{
    MessageID: 1,
    Control:   zcl.SEMsgCtrlImportanceHigh | zcl.SEMsgCtrlConfirmationRequired,
    StartTime: 0, // Display now
    Duration:  60, // 60 minutes
    Message:   "High electricity demand. Please reduce usage.",
}
err := adapter.DisplaySEMessage(ctx, nwkAddr, endpoint, msg)

func (*Adapter) EnrollIASZone

func (a *Adapter) EnrollIASZone(ctx context.Context, nwkAddr uint16, endpoint uint8, responseCode uint8, zoneID uint8) error

EnrollIASZone sends an enroll response to a zone device. This must be called after receiving an enroll request from the device.

Parameters:

  • responseCode: Enrollment response code 0x00 = Success 0x01 = Not supported 0x02 = No enroll permit 0x03 = Too many zones
  • zoneID: Assigned zone ID (0-254)

The device will not send zone status change notifications until it is enrolled.

func (*Adapter) FactoryReset

func (a *Adapter) FactoryReset(ctx context.Context) error

FactoryReset performs a factory reset, clearing all network configuration.

func (*Adapter) ForceRemoveDevice

func (a *Adapter) ForceRemoveDevice(ctx context.Context, ieeeAddr [8]byte) error

ForceRemoveDevice removes a device from the coordinator's NVRAM directly. This is used when a device is offline/asleep and doesn't respond to MgmtLeaveReq. Unlike RemoveDevice, this only removes the coordinator's record - the device itself still thinks it's joined and will need to be factory reset.

func (*Adapter) FormNetwork

func (a *Adapter) FormNetwork(ctx context.Context, config NetworkFormConfig) error

FormNetwork forms a new Zigbee network as coordinator.

func (*Adapter) GetActiveEndpoints

func (a *Adapter) GetActiveEndpoints(ctx context.Context, nwkAddr uint16) ([]uint8, error)

GetActiveEndpoints queries a device for its active endpoints.

func (*Adapter) GetAirQuality

func (a *Adapter) GetAirQuality(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AirQualityData, error)

GetAirQuality reads air quality measurements from a device. It will read from whichever clusters the device supports. Values are nil if the device doesn't support that measurement type.

func (*Adapter) GetAlarm

func (a *Adapter) GetAlarm(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AlarmEntry, error)

GetAlarm retrieves the oldest alarm entry from the device's alarm log. The device returns the first alarm in its log (FIFO order). Returns nil if there are no alarms in the log.

The alarm is not removed from the log by this command; use ResetAlarm or ResetAllAlarms to clear it.

func (*Adapter) GetAlarmCount

func (a *Adapter) GetAlarmCount(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint16, error)

GetAlarmCount reads the number of alarm entries currently stored in the device's alarm log. Returns the count of active alarms.

func (*Adapter) GetAnalogInput

func (a *Adapter) GetAnalogInput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AnalogInputInfo, error)

GetAnalogInput reads all key analog input attributes from a device. Returns comprehensive information about the analog input including current value, status, units, and range.

func (*Adapter) GetAnalogInputValue

func (a *Adapter) GetAnalogInputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (float32, error)

GetAnalogInputValue reads just the present value from an analog input. This is a simplified method for quickly reading the current analog value. Returns the analog value as float32.

func (*Adapter) GetAnalogOutput

func (a *Adapter) GetAnalogOutput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AnalogOutputInfo, error)

GetAnalogOutput reads all key analog output attributes from a device. Returns comprehensive information about the analog output including current value, status, units, and range.

func (*Adapter) GetAnalogOutputValue

func (a *Adapter) GetAnalogOutputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (float32, error)

GetAnalogOutputValue reads just the present value from an analog output. This is a simplified method for quickly reading the current analog output value. Returns the analog value as float32.

func (*Adapter) GetAnalogValue

func (a *Adapter) GetAnalogValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AnalogValueInfo, error)

GetAnalogValue reads all key analog value attributes from a device. Returns comprehensive information about the analog value including current value, status, and units.

func (*Adapter) GetBatteryInfo

func (a *Adapter) GetBatteryInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BatteryInfo, error)

GetBatteryInfo reads battery status from a device. Returns battery voltage, percentage, and alarm status from the PowerConfiguration cluster. Voltage is converted from device units (0.1V) to volts. Percentage is converted from device range (0-200 = 0-100%) to 0-100%.

func (*Adapter) GetBinaryInput

func (a *Adapter) GetBinaryInput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BinaryInputInfo, error)

GetBinaryInput reads the binary input status from a device. Returns the present value, out-of-service flag, status flags, and reliability. This provides complete information about a binary input sensor.

func (*Adapter) GetBinaryInputValue

func (a *Adapter) GetBinaryInputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (bool, error)

GetBinaryInputValue reads only the present value from a binary input device. Returns the current input state (true=active, false=inactive). This is a convenience method when you only need the input value.

func (*Adapter) GetBinaryOutput

func (a *Adapter) GetBinaryOutput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BinaryOutputInfo, error)

GetBinaryOutput reads the current status from a BinaryOutput device. Returns present value, out of service flag, status flags, and polarity.

func (*Adapter) GetBinaryOutputValue

func (a *Adapter) GetBinaryOutputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (bool, error)

GetBinaryOutputValue reads just the current output value from a BinaryOutput device. This is a convenience method that returns only the PresentValue attribute. Returns true for active state, false for inactive state.

func (*Adapter) GetBinaryValue

func (a *Adapter) GetBinaryValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BinaryValueInfo, error)

GetBinaryValue reads all key binary value attributes from a device. Returns comprehensive information about the binary value including current value, status, and reliability.

func (*Adapter) GetBindingTable

func (a *Adapter) GetBindingTable(ctx context.Context, nwkAddr uint16) ([]BindingInfo, error)

GetBindingTable retrieves the binding table from a device. This shows where the device will send reports for each cluster.

func (*Adapter) GetBrightness

func (a *Adapter) GetBrightness(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint8, error)

GetBrightness reads the current brightness level from a device. Returns 0-254 (0=off, 254=full brightness).

func (*Adapter) GetCO2Level

func (a *Adapter) GetCO2Level(ctx context.Context, nwkAddr uint16, endpoint uint8) (*float32, error)

GetCO2Level reads carbon dioxide concentration. Returns the CO2 level in ppm, or nil if not available.

func (*Adapter) GetColor

func (a *Adapter) GetColor(ctx context.Context, nwkAddr uint16, endpoint uint8) (*ColorState, error)

GetColor reads the current color state from a device. Returns the current hue, saturation, X/Y coordinates, and color mode.

func (*Adapter) GetColorTempInfo

func (a *Adapter) GetColorTempInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*ColorTempInfo, error)

GetColorTempInfo reads color temperature and range from a device.

func (*Adapter) GetColorTemperature

func (a *Adapter) GetColorTemperature(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint16, error)

GetColorTemperature reads the current color temperature from a device. Returns the color temperature in mireds.

func (*Adapter) GetCoordinatorIEEE

func (a *Adapter) GetCoordinatorIEEE(ctx context.Context) ([8]byte, error)

GetCoordinatorIEEE returns the coordinator's IEEE address.

func (*Adapter) GetCurrentChannel

func (a *Adapter) GetCurrentChannel(ctx context.Context) (uint8, error)

GetCurrentChannel returns the current network channel.

func (*Adapter) GetCurrentPrice

func (a *Adapter) GetCurrentPrice(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PriceInfo, error)

GetCurrentPrice requests the current price from a smart energy device. This sends a GetCurrentPrice command to the device and waits for a PublishPrice response containing the current pricing information.

The device must support the Price cluster (0x0700) for this to work. This is commonly used with smart meters and energy management systems.

Returns PriceInfo with pricing details, or an error if the request fails.

func (*Adapter) GetDRLCInfo

func (a *Adapter) GetDRLCInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DRLCEventInfo, error)

GetDRLCInfo reads the current DRLC configuration from a device. This retrieves the device's demand response settings including which utility group it belongs to, the device class, and randomization settings.

The device class bitmap indicates which types of loads this device can control. Use the zcl.DRLCDeviceClass* constants to check which classes are supported.

Returns the utility enrolment group, device class, and randomization settings.

func (*Adapter) GetDevice

func (a *Adapter) GetDevice(ieeeAddr [8]byte) *Device

GetDevice returns a device by IEEE address.

func (*Adapter) GetDeviceByNwkAddr

func (a *Adapter) GetDeviceByNwkAddr(nwkAddr uint16) *Device

GetDeviceByNwkAddr returns a device by network address.

func (*Adapter) GetDeviceCapabilities

func (a *Adapter) GetDeviceCapabilities(ctx context.Context, nwkAddr uint16) (*DeviceCapabilities, error)

GetDeviceCapabilities queries all endpoints and their clusters from a device.

func (*Adapter) GetDeviceName

func (a *Adapter) GetDeviceName(ctx context.Context, ieeeAddr [8]byte) (*DeviceNameInfo, error)

GetDeviceName retrieves the custom name for a device. Returns nil if no name is set for this device.

func (*Adapter) GetDeviceStatus

func (a *Adapter) GetDeviceStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DeviceStatus, error)

GetDeviceStatus queries common status attributes from a device.

func (*Adapter) GetDevices

func (a *Adapter) GetDevices(ctx context.Context) ([]*Device, error)

GetDevices returns all devices from the coordinator's NVRAM Address Manager table.

func (*Adapter) GetDoorLockStatus

func (a *Adapter) GetDoorLockStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DoorLockStatus, error)

GetDoorLockStatus reads the current door lock status from a device. Returns the lock state, door state (if available), actuator status, and auto-relock time (if configured).

func (*Adapter) GetEndpointForProfile

func (a *Adapter) GetEndpointForProfile(profile znp.ApplicationProfile) uint8

GetEndpointForProfile returns the coordinator endpoint to use for a given device profile.

func (*Adapter) GetFanStatus

func (a *Adapter) GetFanStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*FanStatus, error)

GetFanStatus reads the current fan status from a device. Returns all available fan attributes including mode, speed, and percentages.

func (*Adapter) GetGroupMembership

func (a *Adapter) GetGroupMembership(ctx context.Context, nwkAddr uint16, endpoint uint8) (*GroupMembership, error)

GetGroupMembership queries which groups a device endpoint belongs to.

func (*Adapter) GetIASZoneStatus

func (a *Adapter) GetIASZoneStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*IASZoneStatus, error)

GetIASZoneStatus reads the current status from an IAS Zone device. This queries all relevant attributes and parses the zone status bitmap.

func (*Adapter) GetInfo

func (a *Adapter) GetInfo(ctx context.Context) (*Info, error)

GetInfo returns comprehensive adapter information including version and capabilities.

func (*Adapter) GetLastSEMessage

func (a *Adapter) GetLastSEMessage(ctx context.Context, nwkAddr uint16, endpoint uint8) error

GetLastSEMessage requests the last message from a Smart Energy device. This sends a GetLastMessage command and waits for the device to respond with the last message it received.

Returns the last message, or nil if no message is available.

Note: This is an asynchronous operation. The device will respond with a DisplayMessage command containing the last message. This method sends the request but does not wait for the response. You'll need to listen for incoming DisplayMessage commands to receive the message.

Example:

err := adapter.GetLastSEMessage(ctx, nwkAddr, endpoint)
// Listen for DisplayMessage response separately

func (*Adapter) GetMainsInfo

func (a *Adapter) GetMainsInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MainsInfo, error)

GetMainsInfo reads mains power information from a device. Returns mains voltage and frequency from the PowerConfiguration cluster. Voltage is converted from device units (0.1V) to volts. Frequency is converted from device units (2Hz increments) to Hz.

func (*Adapter) GetMultistateInput

func (a *Adapter) GetMultistateInput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MultistateInputInfo, error)

GetMultistateInput reads all key multistate input attributes from a device. Returns comprehensive information about the multistate input including current value, number of states, status, and reliability.

func (*Adapter) GetMultistateInputValue

func (a *Adapter) GetMultistateInputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint16, error)

GetMultistateInputValue reads just the current state value from a multistate input. This is a simplified method for quickly reading the current state. Returns the state value as uint16 (1-based indexing).

func (*Adapter) GetMultistateOutput

func (a *Adapter) GetMultistateOutput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MultistateOutputInfo, error)

GetMultistateOutput reads the current status from a MultistateOutput device. Returns present value, number of states, out of service flag, and status flags.

func (*Adapter) GetMultistateValue

func (a *Adapter) GetMultistateValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MultistateValueInfo, error)

GetMultistateValue reads the current status from a MultistateValue device. Returns present value, number of states, out of service flag, status flags, and reliability.

func (*Adapter) GetNeighborTable

func (a *Adapter) GetNeighborTable(ctx context.Context, nwkAddr uint16) ([]NeighborInfo, error)

GetNeighborTable retrieves the neighbor table from a device. This shows which devices this node can directly communicate with.

func (*Adapter) GetNetworkInfo

func (a *Adapter) GetNetworkInfo(ctx context.Context) (*NetworkInfo, error)

GetNetworkInfo retrieves comprehensive network information.

func (*Adapter) GetOTAInfo

func (a *Adapter) GetOTAInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*OTAInfo, error)

GetOTAInfo reads OTA upgrade status information from a device. Returns current firmware version, upgrade status, manufacturer/image IDs, and file offset. This provides a comprehensive view of the device's OTA upgrade state.

func (*Adapter) GetOTAUpgradeStatus

func (a *Adapter) GetOTAUpgradeStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (zcl.OTAUpgradeStatus, error)

GetOTAUpgradeStatus reads the current OTA upgrade status from a device. Returns the upgrade status enum indicating the device's current state (Normal, DownloadInProgress, DownloadComplete, etc.).

func (*Adapter) GetOnOffState

func (a *Adapter) GetOnOffState(ctx context.Context, nwkAddr uint16, endpoint uint8) (bool, error)

GetOnOffState reads the current on/off state.

func (*Adapter) GetPM25Level

func (a *Adapter) GetPM25Level(ctx context.Context, nwkAddr uint16, endpoint uint8) (*float32, error)

GetPM25Level reads PM2.5 particulate concentration. Returns the PM2.5 level in µg/m³, or nil if not available.

func (*Adapter) GetPollControlInfo

func (a *Adapter) GetPollControlInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PollControlInfo, error)

GetPollControlInfo reads poll control configuration from a device. Returns the check-in interval, long poll interval, short poll interval, and fast poll timeout. All intervals are in quarter seconds.

To convert to seconds, use QuarterSecondsToSeconds():

info, err := adapter.GetPollControlInfo(ctx, nwkAddr, endpoint)
if err != nil {
	return err
}
checkInSecs := QuarterSecondsToSeconds(info.CheckInInterval)

func (*Adapter) GetPressure

func (a *Adapter) GetPressure(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PressureData, error)

GetPressure reads atmospheric pressure from a device. Returns pressure in hPa (hectopascals), also known as millibars. The device reports pressure in units of 10 Pa (0.1 hPa), which is converted to hPa. Some devices support scaled values with a scale attribute (10^scale multiplier).

func (*Adapter) GetSceneMembership

func (a *Adapter) GetSceneMembership(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16) (*SceneMembership, error)

GetSceneMembership queries which scenes are stored on a device for a group.

func (*Adapter) GetSimpleDescriptor

func (a *Adapter) GetSimpleDescriptor(ctx context.Context, nwkAddr uint16, endpoint uint8) (*EndpointDescriptor, error)

GetSimpleDescriptor queries a device endpoint for its simple descriptor.

func (*Adapter) GetThermostatStatus

func (a *Adapter) GetThermostatStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*ThermostatStatus, error)

GetThermostatStatus reads the current thermostat status from a device. Returns the current temperature, setpoints, mode, and demand values. Temperature values are converted from centidegrees (0.01°C) to degrees Celsius.

func (*Adapter) GetTime

func (a *Adapter) GetTime(ctx context.Context, nwkAddr uint16, endpoint uint8) (*TimeInfo, error)

GetTime reads the current time and status from a Time cluster device. Returns time information including UTC time, status flags, timezone offset, and local time. Use ZigbeeTimeToUnix() to convert the Time field to a standard time.Time value.

func (*Adapter) GetTimeZone

func (a *Adapter) GetTimeZone(ctx context.Context, nwkAddr uint16, endpoint uint8) (int32, error)

GetTimeZone reads the timezone offset from a Time cluster device. Returns the timezone offset in seconds from UTC. For example: UTC+2 = 7200 seconds, UTC-5 = -18000 seconds.

func (*Adapter) GetTxPower

func (a *Adapter) GetTxPower(ctx context.Context) (int8, error)

GetTxPower reads the current TX power from NV memory. Returns the power in dBm, or an error if not available.

func (*Adapter) GetWindowCoveringStatus

func (a *Adapter) GetWindowCoveringStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*WindowCoveringStatus, error)

GetWindowCoveringStatus reads the current window covering status from a device. Returns the covering type, lift percentage (0=fully open, 100=fully closed), tilt percentage, and configuration status.

func (*Adapter) GroupRecallScene

func (a *Adapter) GroupRecallScene(ctx context.Context, groupID uint16, sceneID uint8) error

GroupRecallScene recalls a scene on all devices in a group. sceneID is the scene to recall (0-255).

func (*Adapter) GroupSetBrightness

func (a *Adapter) GroupSetBrightness(ctx context.Context, groupID uint16, level uint8, transitionTime uint16) error

GroupSetBrightness sets the brightness level on all dimmable devices in a group. level is 0-254 (0=off, 254=full brightness). transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) GroupToggle

func (a *Adapter) GroupToggle(ctx context.Context, groupID uint16) error

GroupToggle sends Toggle command to all devices in a group.

func (*Adapter) GroupTurnOff

func (a *Adapter) GroupTurnOff(ctx context.Context, groupID uint16) error

GroupTurnOff sends Off command to all devices in a group.

func (*Adapter) GroupTurnOn

func (a *Adapter) GroupTurnOn(ctx context.Context, groupID uint16) error

GroupTurnOn sends On command to all devices in a group.

func (*Adapter) Identify

func (a *Adapter) Identify(ctx context.Context, nwkAddr uint16, endpoint uint8, durationSecs uint16) error

Identify starts the identify mode on a device for the specified duration. The device will perform a visual/audible identification (e.g., flashing lights). Duration is in seconds. Use 0 to stop identifying.

func (*Adapter) InterviewAllDevices

func (a *Adapter) InterviewAllDevices(ctx context.Context) ([]*InterviewResult, error)

InterviewAllDevices interviews all known devices from the NVRAM. Returns results for each device. Errors for individual devices are recorded in the InterviewResult.Errors field rather than failing the entire operation.

func (*Adapter) InterviewAllDevicesWithOptions

func (a *Adapter) InterviewAllDevicesWithOptions(ctx context.Context, opts InterviewOptions) ([]*InterviewResult, error)

InterviewAllDevicesWithOptions interviews all devices with custom options.

func (*Adapter) InterviewDevice

func (a *Adapter) InterviewDevice(ctx context.Context, nwkAddr uint16) (*InterviewResult, error)

InterviewDevice performs a full device interview to discover capabilities. This queries the device for its node descriptor, endpoints, clusters, and basic identification attributes (manufacturer, model).

func (*Adapter) InterviewDeviceByIEEE

func (a *Adapter) InterviewDeviceByIEEE(ctx context.Context, ieeeAddr [8]byte) (*InterviewResult, error)

InterviewDeviceByIEEE performs interview when IEEE address is known. It first resolves the network address from the device manager.

func (*Adapter) InterviewDeviceWithAddr

func (a *Adapter) InterviewDeviceWithAddr(ctx context.Context, nwkAddr uint16, ieeeAddr [8]byte) (*InterviewResult, error)

InterviewDeviceWithAddr performs interview when both addresses are known. This skips the IeeeAddrReq call which is useful for sleeping end devices.

func (*Adapter) InterviewDeviceWithOptions

func (a *Adapter) InterviewDeviceWithOptions(ctx context.Context, nwkAddr uint16, opts InterviewOptions) (*InterviewResult, error)

InterviewDeviceWithOptions performs device interview with custom options.

func (*Adapter) IsOpen

func (a *Adapter) IsOpen() bool

IsOpen returns true if the adapter is open and ready for communication.

func (*Adapter) ListDeviceNames

func (a *Adapter) ListDeviceNames(ctx context.Context) ([]DeviceNameInfo, error)

ListDeviceNames returns all devices with custom names.

func (*Adapter) LockDoor

func (a *Adapter) LockDoor(ctx context.Context, nwkAddr uint16, endpoint uint8) error

LockDoor sends a lock command to the door lock device.

func (*Adapter) MoveLevel

func (a *Adapter) MoveLevel(ctx context.Context, nwkAddr uint16, endpoint uint8, moveMode, rate uint8) error

MoveLevel starts continuously changing the level at the specified rate. The level will continue changing until it reaches the limit or StopLevel is called.

Parameters:

  • moveMode: Direction of movement (zcl.MoveModeUp or zcl.MoveModeDown)
  • rate: Units per second to change the level (0 = use device's DefaultMoveRate attribute)

Example: Increase brightness at 50 units/second:

err := adapter.MoveLevel(ctx, nwkAddr, endpoint, uint8(zcl.MoveModeUp), 50)

func (*Adapter) OffWithEffect

func (a *Adapter) OffWithEffect(ctx context.Context, nwkAddr uint16, endpoint uint8, effectID, effectVariant uint8) error

OffWithEffect turns off a device with a visual effect (typically for lights). effectID specifies the effect type:

  • 0x00: DelayedAllOff - fade to off over 0.8 seconds
  • 0x01: DyingLight - 50% dim down in 0.8s then fade to off in 12s

effectVariant is an effect-specific variant value (typically 0 for default).

func (*Adapter) OnDeviceEvent

func (a *Adapter) OnDeviceEvent(handler func(DeviceEvent))

OnDeviceEvent sets a callback for device join/leave events.

func (*Adapter) OnWithTimedOff

func (a *Adapter) OnWithTimedOff(ctx context.Context, nwkAddr uint16, endpoint uint8, onTime, offWaitTime uint16) error

OnWithTimedOff turns on a device for a specified duration. The device will automatically turn off after the specified time. onTime and offWaitTime are in 1/10th seconds (e.g., 10 = 1 second).

Parameters:

  • onTime: Duration the device stays on (1/10th seconds)
  • offWaitTime: Additional delay before turning off (1/10th seconds)

The onOffControl parameter is typically 0x00 for normal operation.

func (*Adapter) Open

func (a *Adapter) Open(ctx context.Context) error

Open opens the adapter and establishes communication with the Z-Stack coordinator. It opens the serial port, initializes the ZNP protocol layer, verifies connectivity, registers coordinator endpoints, and starts the Zigbee network.

func (*Adapter) OpenWindowCovering

func (a *Adapter) OpenWindowCovering(ctx context.Context, nwkAddr uint16, endpoint uint8) error

OpenWindowCovering fully opens (raises) the covering. This sends the UpOpen command to the device.

func (*Adapter) PermitJoin

func (a *Adapter) PermitJoin(ctx context.Context, duration uint8) error

PermitJoin opens or closes the network for device joining. duration: 0=close, 1-254=seconds, 255=always open

func (*Adapter) Ping

func (a *Adapter) Ping(ctx context.Context) (*znp.PingCapabilities, error)

Ping sends a ping request to the adapter and returns capabilities.

func (*Adapter) ReadAttributes

func (a *Adapter) ReadAttributes(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, attributeIDs ...zcl.AttributeID) ([]AttributeResult, error)

ReadAttributes reads attributes from a device endpoint.

func (*Adapter) ReadDeviceInfo

func (a *Adapter) ReadDeviceInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DeviceInfo, error)

ReadDeviceInfo reads all Basic cluster attributes from a device. Returns a DeviceInfo struct with all available attributes. Attributes that are not supported or fail to read will be nil.

func (*Adapter) ReadPowerData

func (a *Adapter) ReadPowerData(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PowerData, error)

ReadPowerData reads power consumption data from a smart plug.

func (*Adapter) ReadReportingConfig

func (a *Adapter) ReadReportingConfig(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, attributeIDs ...zcl.AttributeID) ([]ReportingConfigResult, error)

ReadReportingConfig reads the current reporting configuration for attributes on a device. This queries the device for how it's configured to send attribute reports.

func (*Adapter) ReadSensorData

func (a *Adapter) ReadSensorData(ctx context.Context, nwkAddr uint16, endpoint uint8) (*SensorData, error)

ReadSensorData reads temperature, humidity, and battery from a sensor.

func (*Adapter) RecallScene

func (a *Adapter) RecallScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, sceneID uint8, transitionTime *uint16) error

RecallScene activates a previously stored scene. The device transitions to the saved attribute values. transitionTime is optional (0xFFFF = use scene's stored transition time).

func (*Adapter) RegisteredProfiles

func (a *Adapter) RegisteredProfiles() []znp.ApplicationProfile

RegisteredProfiles returns the list of Application Profiles supported by registered endpoints.

func (*Adapter) RemoveAllScenes

func (a *Adapter) RemoveAllScenes(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16) error

RemoveAllScenes removes all scenes for a group from the device.

func (*Adapter) RemoveDevice

func (a *Adapter) RemoveDevice(ctx context.Context, nwkAddr uint16, ieeeAddr [8]byte, removeChildren, rejoin bool) error

RemoveDevice sends a leave request to remove a device from the network. If removeChildren is true, the device will also remove any children it has. If rejoin is false, the device will not attempt to rejoin the network.

func (*Adapter) RemoveFromAllGroups

func (a *Adapter) RemoveFromAllGroups(ctx context.Context, nwkAddr uint16, endpoint uint8) error

RemoveFromAllGroups removes a device endpoint from all groups.

func (*Adapter) RemoveFromGroup

func (a *Adapter) RemoveFromGroup(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16) error

RemoveFromGroup removes a device endpoint from a group.

func (*Adapter) RemoveScene

func (a *Adapter) RemoveScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, sceneID uint8) error

RemoveScene removes a specific scene from the device.

func (*Adapter) Reset

func (a *Adapter) Reset(ctx context.Context) error

Reset performs a soft reset of the adapter.

func (*Adapter) ResetAlarm

func (a *Adapter) ResetAlarm(ctx context.Context, nwkAddr uint16, endpoint uint8, alarmCode uint8, clusterID zcl.ClusterID) error

ResetAlarm clears a specific alarm from the device's alarm log. The alarm is identified by its alarm code and the cluster that generated it.

Parameters:

  • alarmCode: The alarm code to reset (device-specific)
  • clusterID: The cluster ID that generated the alarm

Example: Reset a low battery alarm (code 0x00) from PowerConfiguration cluster:

err := adapter.ResetAlarm(ctx, nwkAddr, endpoint, 0x00, zcl.ClusterPowerConfig)

func (*Adapter) ResetAlarmLog

func (a *Adapter) ResetAlarmLog(ctx context.Context, nwkAddr uint16, endpoint uint8) error

ResetAlarmLog clears the entire alarm log on the device. This removes all alarm history but does not prevent new alarms from being generated.

func (*Adapter) ResetAllAlarms

func (a *Adapter) ResetAllAlarms(ctx context.Context, nwkAddr uint16, endpoint uint8) error

ResetAllAlarms clears all alarms from the device's alarm log. This removes all active alarm entries.

func (*Adapter) ResetEnergy

func (a *Adapter) ResetEnergy(ctx context.Context, nwkAddr uint16, endpoint uint8) error

ResetEnergy attempts to reset the energy counter on a smart plug. This uses manufacturer-specific methods and may not work on all devices. For Tuya TS011F plugs, zigbee2mqtt uses Basic cluster resetFactDefault command.

func (*Adapter) ResetToFactoryDefaults

func (a *Adapter) ResetToFactoryDefaults(ctx context.Context, nwkAddr uint16, endpoint uint8) error

ResetToFactoryDefaults sends the reset to factory defaults command to a device. This resets all writeable attributes in the Basic cluster to their factory default values. Note: The device behavior may vary - some devices may reset all settings, while others may only reset specific attributes. Refer to the device documentation for details.

func (*Adapter) RestoreBackup

func (a *Adapter) RestoreBackup(ctx context.Context, b *backup.Backup) error

RestoreBackup restores adapter configuration from a backup. WARNING: This will overwrite the current configuration!

func (*Adapter) SendCheckInResponse

func (a *Adapter) SendCheckInResponse(ctx context.Context, nwkAddr uint16, endpoint uint8, startFastPolling bool, fastPollTimeout uint16) error

SendCheckInResponse responds to a check-in notification from a sleepy device. This tells the device whether to enter fast polling mode and for how long.

Parameters:

  • startFastPolling: Whether the device should enter fast polling mode
  • fastPollTimeout: Duration of fast polling in quarter seconds (0 = use device default)

The device will poll more frequently during fast polling, allowing the coordinator to send pending commands. After the timeout, the device returns to normal polling.

Example: Enable fast polling for 10 seconds (40 quarter seconds):

err := adapter.SendCheckInResponse(ctx, nwkAddr, endpoint, true, 40)

func (*Adapter) SendClusterCommand

func (a *Adapter) SendClusterCommand(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, commandID uint8, payload []byte) error

SendClusterCommand sends a cluster-specific command to a device.

func (*Adapter) SendGroupCommand

func (a *Adapter) SendGroupCommand(ctx context.Context, groupID uint16, clusterID zcl.ClusterID, commandID uint8, payload []byte) error

SendGroupCommand sends a cluster command to all devices in a group. This uses group addressing (multicast) so the command is received by all group members simultaneously. groupID is the 16-bit group address. clusterID is the cluster to send the command on, commandID is the cluster-specific command, and payload is the command payload.

Example: Turn on all lights in group 1:

err := adapter.SendGroupCommand(ctx, 1, zcl.ClusterOnOff, zcl.CmdOnOffOn, nil)

func (*Adapter) SetAnalogOutput

func (a *Adapter) SetAnalogOutput(ctx context.Context, nwkAddr uint16, endpoint uint8, value float32) error

SetAnalogOutput sets the output value on an analog output device. value is the desired analog output value to set. This writes to the PresentValue attribute (0x0055) which is writable.

func (*Adapter) SetAnalogValue

func (a *Adapter) SetAnalogValue(ctx context.Context, nwkAddr uint16, endpoint uint8, value float32) error

SetAnalogValue sets the present value of an analog value object. value is the desired float32 value to set.

func (*Adapter) SetBinaryOutput

func (a *Adapter) SetBinaryOutput(ctx context.Context, nwkAddr uint16, endpoint uint8, value bool) error

SetBinaryOutput sets the output value on a BinaryOutput device. value specifies the desired output state (true=active, false=inactive). This writes to the PresentValue attribute (0x0055) which is writable.

func (*Adapter) SetBinaryValue

func (a *Adapter) SetBinaryValue(ctx context.Context, nwkAddr uint16, endpoint uint8, value bool) error

SetBinaryValue sets the present value of a binary value object. value is the desired boolean state to set.

func (*Adapter) SetBrightness

func (a *Adapter) SetBrightness(ctx context.Context, nwkAddr uint16, endpoint uint8, level uint8, transitionTime uint16) error

SetBrightness sets the brightness level on a dimmable device. level is 0-254 (0=off, 254=full brightness). transitionTime is in tenths of a second (e.g., 10 = 1 second). Uses MoveToLevelWithOnOff command which also handles on/off state.

func (*Adapter) SetColorKelvin

func (a *Adapter) SetColorKelvin(ctx context.Context, nwkAddr uint16, endpoint uint8, kelvin uint16, transitionTime uint16) error

SetColorKelvin sets the color temperature using Kelvin values. kelvin is the color temperature in Kelvin (typically 2000-6500K for Hue lights). The function converts Kelvin to mireds using the conversion function from the zcl package. transitionTime is in tenths of a second (e.g., 10 = 1 second). Returns an error if the kelvin value is outside the valid range (1500-10000K).

func (*Adapter) SetColorRGB

func (a *Adapter) SetColorRGB(ctx context.Context, nwkAddr uint16, endpoint uint8, r, g, b uint8, transitionTime uint16) error

SetColorRGB sets the color using RGB values. RGB values are 0-255. The function converts RGB to CIE XY color space using the conversion function from the zcl package. transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) SetColorTemperature

func (a *Adapter) SetColorTemperature(ctx context.Context, nwkAddr uint16, endpoint uint8, tempMireds uint16, transitionTime uint16) error

SetColorTemperature sets the color temperature on a tunable white light. tempMireds is the color temperature in mireds (1,000,000 / Kelvin). For example: 2700K = 370 mireds, 6500K = 154 mireds. transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) SetColorXY

func (a *Adapter) SetColorXY(ctx context.Context, nwkAddr uint16, endpoint uint8, x uint16, y uint16, transitionTime uint16) error

SetColorXY sets the color using CIE XY chromaticity coordinates. x and y are 0-65535 representing the CIE 1931 color space coordinates. transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) SetDeviceName

func (a *Adapter) SetDeviceName(ctx context.Context, ieeeAddr [8]byte, name, description string) error

SetDeviceName sets a custom name and description for a device. Name is limited to 32 characters, description to 64 characters. Names are stored in NVRAM and persist across restarts.

func (*Adapter) SetDoorLockPIN

func (a *Adapter) SetDoorLockPIN(ctx context.Context, nwkAddr uint16, endpoint uint8, userID uint16, pin string) error

SetDoorLockPIN sets a PIN code for a user. userID is the user identifier (0-65535). pin is the PIN code string. The userStatus and userType are set to default values (enabled user with unrestricted access).

func (*Adapter) SetFanMode

func (a *Adapter) SetFanMode(ctx context.Context, nwkAddr uint16, endpoint uint8, mode zcl.FanMode) error

SetFanMode sets the operating mode of a fan. mode specifies the desired fan mode (Off, Low, Medium, High, On, Auto, Smart).

func (*Adapter) SetFanSpeed

func (a *Adapter) SetFanSpeed(ctx context.Context, nwkAddr uint16, endpoint uint8, percent uint8) error

SetFanSpeed sets the fan speed as a percentage. percent is 0-100 where 0 is off and 100 is maximum speed.

func (*Adapter) SetHue

func (a *Adapter) SetHue(ctx context.Context, nwkAddr uint16, endpoint uint8, hue uint8, direction uint8, transitionTime uint16) error

SetHue sets only the hue of a color-capable light. hue is 0-254 (0=red, 85=green, 170=blue). direction: 0=shortest, 1=longest, 2=up, 3=down. transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) SetHueSaturation

func (a *Adapter) SetHueSaturation(ctx context.Context, nwkAddr uint16, endpoint uint8, hue uint8, saturation uint8, transitionTime uint16) error

SetHueSaturation sets both the hue and saturation of a color-capable light. hue is 0-254 (0=red, 85=green, 170=blue), saturation is 0-254 (0=white, 254=fully saturated). transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) SetLongPollInterval

func (a *Adapter) SetLongPollInterval(ctx context.Context, nwkAddr uint16, endpoint uint8, intervalQuarterSecs uint32) error

SetLongPollInterval sets the long poll interval on a sleepy device. The long poll interval is how often the device wakes up to check for messages when it's in normal (non-fast-polling) mode.

intervalQuarterSecs is the interval in quarter seconds (4 = 1 second).

Example: Set long poll interval to 5 minutes (1200 quarter seconds):

err := adapter.SetLongPollInterval(ctx, nwkAddr, endpoint, 1200)

func (*Adapter) SetMultistateOutput

func (a *Adapter) SetMultistateOutput(ctx context.Context, nwkAddr uint16, endpoint uint8, value uint16) error

SetMultistateOutput sets the output state on a MultistateOutput device. value specifies the desired state (1 to NumberOfStates). This writes to the PresentValue attribute (0x0055) which is writable.

func (*Adapter) SetMultistateValue

func (a *Adapter) SetMultistateValue(ctx context.Context, nwkAddr uint16, endpoint uint8, value uint16) error

SetMultistateValue sets the value on a MultistateValue device. value specifies the desired state (1 to NumberOfStates). This writes to the PresentValue attribute (0x0055) which is read/write.

func (*Adapter) SetSaturation

func (a *Adapter) SetSaturation(ctx context.Context, nwkAddr uint16, endpoint uint8, saturation uint8, transitionTime uint16) error

SetSaturation sets only the saturation of a color-capable light. saturation is 0-254 (0=white, 254=fully saturated). transitionTime is in tenths of a second (e.g., 10 = 1 second).

func (*Adapter) SetShortPollInterval

func (a *Adapter) SetShortPollInterval(ctx context.Context, nwkAddr uint16, endpoint uint8, intervalQuarterSecs uint16) error

SetShortPollInterval sets the short poll interval (fast poll interval) on a sleepy device. The short poll interval is how often the device polls when in fast polling mode.

intervalQuarterSecs is the interval in quarter seconds (4 = 1 second).

Example: Set short poll interval to 250ms (1 quarter second):

err := adapter.SetShortPollInterval(ctx, nwkAddr, endpoint, 1)

func (*Adapter) SetStartupLevel

func (a *Adapter) SetStartupLevel(ctx context.Context, nwkAddr uint16, endpoint uint8, level uint8) error

SetStartupLevel configures the brightness level the device uses when powered on. This persists across power cycles, allowing devices to remember their preferred startup state.

Parameters:

  • level: The startup level (0-254 for specific level, 255 to restore previous level)

Special values:

  • 0-254: Set to a specific brightness level on power-up
  • 255 (0xFF): Restore the level from before power loss

Example: Set device to turn on at 50% brightness:

err := adapter.SetStartupLevel(ctx, nwkAddr, endpoint, 127)

Example: Set device to restore previous level on power-up:

err := adapter.SetStartupLevel(ctx, nwkAddr, endpoint, 255)

func (*Adapter) SetStartupOnOff

func (a *Adapter) SetStartupOnOff(ctx context.Context, nwkAddr uint16, endpoint uint8, value uint8) error

SetStartupOnOff configures the device behavior when it powers on. value specifies the startup behavior:

  • 0x00: Turn off when powered on
  • 0x01: Turn on when powered on
  • 0x02: Toggle state when powered on
  • 0xFF: Restore previous state when powered on

This setting is persistent across power cycles.

func (*Adapter) SetThermostatMode

func (a *Adapter) SetThermostatMode(ctx context.Context, nwkAddr uint16, endpoint uint8, mode zcl.ThermostatSystemMode) error

SetThermostatMode sets the operating mode of a thermostat. mode specifies the desired operating mode (Off, Auto, Cool, Heat, etc.).

func (*Adapter) SetThermostatSetpoint

func (a *Adapter) SetThermostatSetpoint(ctx context.Context, nwkAddr uint16, endpoint uint8, heating, cooling float64) error

SetThermostatSetpoint sets the heating and cooling setpoints on a thermostat. Temperatures are in degrees Celsius and are converted to centidegrees (0.01°C) for the device. heating: Desired heating setpoint in °C cooling: Desired cooling setpoint in °C

func (*Adapter) SetTime

func (a *Adapter) SetTime(ctx context.Context, nwkAddr uint16, endpoint uint8, zigbeeTime uint32) error

SetTime sets the UTC time on a Time cluster device. zigbeeTime is seconds since January 1, 2000 00:00:00 UTC. Use UnixToZigbeeTime() to convert from time.Time to Zigbee time.

Example: Set device to current time:

zigbeeTime := adapter.UnixToZigbeeTime(time.Now())
err := adapter.SetTime(ctx, nwkAddr, endpoint, zigbeeTime)

func (*Adapter) SetTimeZone

func (a *Adapter) SetTimeZone(ctx context.Context, nwkAddr uint16, endpoint uint8, offsetSeconds int32) error

SetTimeZone sets the timezone offset on a Time cluster device. offsetSeconds is the timezone offset in seconds from UTC. For example: UTC+2 = 7200 seconds, UTC-5 = -18000 seconds.

Example: Set timezone to UTC+1 (Central European Time):

err := adapter.SetTimeZone(ctx, nwkAddr, endpoint, 3600)

func (*Adapter) SetTxPower

func (a *Adapter) SetTxPower(ctx context.Context, power int8) error

SetTxPower sets the transmit power level. The value is stored in NV memory and persists across restarts.

func (*Adapter) SetWindowCoveringPosition

func (a *Adapter) SetWindowCoveringPosition(ctx context.Context, nwkAddr uint16, endpoint uint8, percent uint8) error

SetWindowCoveringPosition sets the lift position as percentage (0=open, 100=closed). The covering will move to the specified position. percent is 0-100 where 0 is fully open and 100 is fully closed.

func (*Adapter) SetWindowCoveringTilt

func (a *Adapter) SetWindowCoveringTilt(ctx context.Context, nwkAddr uint16, endpoint uint8, percent uint8) error

SetWindowCoveringTilt sets the tilt angle as percentage (0=open, 100=closed). The covering slats will tilt to the specified angle. percent is 0-100 where 0 is fully open and 100 is fully closed.

func (*Adapter) Squawk

func (a *Adapter) Squawk(ctx context.Context, nwkAddr uint16, endpoint uint8, mode uint8, useStrobe bool, level zcl.SirenLevel) error

Squawk makes a brief sound on the device (for arming/disarming feedback). This is typically used to provide audio feedback when arming or disarming a security system.

Parameters:

  • mode: Squawk mode (0=armed, 1=disarmed)
  • useStrobe: Whether to flash the strobe
  • level: Volume level (Low, Medium, High, VeryHigh)

Example: Play disarmed squawk with medium volume and strobe:

err := adapter.Squawk(ctx, nwkAddr, endpoint, 1, true, zcl.SirenLevelMedium)

func (*Adapter) StartWarning

func (a *Adapter) StartWarning(ctx context.Context, nwkAddr uint16, endpoint uint8, mode zcl.WarningMode, useStrobe bool, sirenLevel zcl.SirenLevel, durationSecs uint16, strobeDutyCycle uint8, strobeLevel zcl.StrobeLevel) error

StartWarning activates the warning device (siren/strobe). This sends a command to the device to start sounding an alarm with the specified parameters.

Parameters:

  • mode: Type of warning (Burglar, Fire, Emergency, etc.)
  • useStrobe: Whether to activate the strobe light
  • sirenLevel: Loudness of the siren (Low, Medium, High, VeryHigh)
  • durationSecs: How long to sound the alarm (max depends on device, typically 240 seconds)
  • strobeDutyCycle: Duty cycle percentage for strobe (0-100), where 100 = always on
  • strobeLevel: Brightness of the strobe (Low, Medium, High, VeryHigh)

Example: Sound burglar alarm for 30 seconds with high siren and medium strobe:

err := adapter.StartWarning(ctx, nwkAddr, endpoint,
    zcl.WarningModeBurglar, true, zcl.SirenLevelHigh,
    30, 50, zcl.StrobeLevelMedium)

func (*Adapter) StepLevel

func (a *Adapter) StepLevel(ctx context.Context, nwkAddr uint16, endpoint uint8, stepMode, stepSize uint8, transitionTime uint16) error

StepLevel changes the level by a fixed amount over a transition time. This is useful for dimming/brightening by a specific increment.

Parameters:

  • stepMode: Direction of step (zcl.StepModeUp or zcl.StepModeDown)
  • stepSize: Amount to change the level (0-254)
  • transitionTime: Time for the transition in tenths of a second (e.g., 10 = 1 second)

Example: Decrease brightness by 20 units over 0.5 seconds:

err := adapter.StepLevel(ctx, nwkAddr, endpoint, uint8(zcl.StepModeDown), 20, 5)

func (*Adapter) StopFastPolling

func (a *Adapter) StopFastPolling(ctx context.Context, nwkAddr uint16, endpoint uint8) error

StopFastPolling instructs a sleepy device to stop fast polling immediately. The device will return to its normal long poll interval.

This is useful to conserve battery when you no longer have pending commands for the device.

func (*Adapter) StopLevel

func (a *Adapter) StopLevel(ctx context.Context, nwkAddr uint16, endpoint uint8) error

StopLevel stops any ongoing level change started by MoveLevel or StepLevel. This command immediately halts the level transition and maintains the current level.

Example:

err := adapter.StopLevel(ctx, nwkAddr, endpoint)

func (*Adapter) StopWarning

func (a *Adapter) StopWarning(ctx context.Context, nwkAddr uint16, endpoint uint8) error

StopWarning stops any active warning on the device. This immediately silences the alarm and turns off any strobe.

This is equivalent to calling StartWarning with WarningModeStop.

func (*Adapter) StopWindowCovering

func (a *Adapter) StopWindowCovering(ctx context.Context, nwkAddr uint16, endpoint uint8) error

StopWindowCovering stops any ongoing movement. This immediately halts the covering's motion and maintains the current position.

func (*Adapter) StoreScene

func (a *Adapter) StoreScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, sceneID uint8) error

StoreScene stores the current device state as a scene. The device saves its current attribute values (brightness, color, etc.) to the scene. groupID must be a valid group the device belongs to (or 0x0000 for global scenes). sceneID is 0-255.

func (*Adapter) Toggle

func (a *Adapter) Toggle(ctx context.Context, nwkAddr uint16, endpoint uint8) error

Toggle sends Toggle command to a device.

func (*Adapter) ToggleDoorLock

func (a *Adapter) ToggleDoorLock(ctx context.Context, nwkAddr uint16, endpoint uint8) error

ToggleDoorLock toggles the lock state (locked <-> unlocked).

func (*Adapter) TriggerEffect

func (a *Adapter) TriggerEffect(ctx context.Context, nwkAddr uint16, endpoint uint8, effectID uint8, effectVariant uint8) error

TriggerEffect triggers a specific identification effect on a device. Effects: Blink (0x00), Breathe (0x01), Okay (0x02), ChannelChange (0x0B), FinishEffect (0xFE), StopEffect (0xFF)

func (*Adapter) TurnOff

func (a *Adapter) TurnOff(ctx context.Context, nwkAddr uint16, endpoint uint8) error

TurnOff sends Off command to a device.

func (*Adapter) TurnOn

func (a *Adapter) TurnOn(ctx context.Context, nwkAddr uint16, endpoint uint8) error

TurnOn sends On command to a device.

func (*Adapter) Unbind

func (a *Adapter) Unbind(ctx context.Context, deviceIEEEAddr [8]byte, deviceNwkAddr uint16, deviceEndpoint uint8, clusterID uint16, coordinatorIEEEAddr [8]byte, coordinatorEndpoint uint8) error

Unbind removes a binding entry from a device. This stops the device from sending reports to the specified destination.

Parameters:

  • deviceIEEEAddr: IEEE address of the device to remove binding from
  • deviceNwkAddr: Network address of the device
  • deviceEndpoint: Source endpoint on the device
  • clusterID: Cluster ID to unbind
  • coordinatorIEEEAddr: IEEE address of the coordinator (destination)
  • coordinatorEndpoint: Coordinator endpoint (typically 1)

func (*Adapter) UnlockDoor

func (a *Adapter) UnlockDoor(ctx context.Context, nwkAddr uint16, endpoint uint8) error

UnlockDoor sends an unlock command to the door lock device.

func (*Adapter) UnlockDoorWithTimeout

func (a *Adapter) UnlockDoorWithTimeout(ctx context.Context, nwkAddr uint16, endpoint uint8, timeoutSeconds uint16) error

UnlockDoorWithTimeout unlocks the door and automatically relocks after the specified timeout. timeoutSeconds is the number of seconds before the door automatically relocks.

func (*Adapter) Version

func (a *Adapter) Version() *znp.VersionInfo

Version returns the cached version information. Returns nil if the adapter is not open.

func (*Adapter) WaitForIASZoneNotification

func (a *Adapter) WaitForIASZoneNotification(ctx context.Context, timeout time.Duration) (*IASZoneNotification, error)

WaitForIASZoneNotification waits for an incoming IAS Zone status change notification. Returns when a zone notification is received or timeout occurs.

Note: The device must be enrolled before it will send notifications. Use EnrollIASZone to enroll the device first.

func (*Adapter) WaitForSensorReport

func (a *Adapter) WaitForSensorReport(ctx context.Context, timeout time.Duration) (*SensorReport, error)

WaitForSensorReport waits for an incoming sensor report from any device. Returns when a temperature, humidity, or battery report is received. Duplicate messages (same source, cluster, and sequence number within the deduplication window) are automatically filtered out.

func (*Adapter) WriteAttributes

func (a *Adapter) WriteAttributes(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, values map[zcl.AttributeID]zcl.AttributeValue) error

WriteAttributes writes attributes to a device endpoint.

func (*Adapter) WriteIASZoneCIEAddress

func (a *Adapter) WriteIASZoneCIEAddress(ctx context.Context, nwkAddr uint16, endpoint uint8, cieAddress [8]byte) error

WriteIASZoneCIEAddress writes the coordinator's IEEE address to the zone device. This is required before a device can be enrolled. The device needs to know which coordinator (CIE - Control and Indicating Equipment) to send notifications to.

The cieAddress should be the coordinator's IEEE address, which can be obtained from the network configuration or device information.

type AirQualityData

type AirQualityData struct {
	CO           *float32 // Carbon monoxide in ppm
	CO2          *float32 // Carbon dioxide in ppm
	PM25         *float32 // PM2.5 in µg/m³
	Formaldehyde *float32 // Formaldehyde in ppm
}

AirQualityData contains air quality sensor readings.

type AlarmEntry

type AlarmEntry struct {
	AlarmCode uint8         // Alarm code identifying the type of alarm
	ClusterID zcl.ClusterID // Cluster that generated the alarm
	Timestamp uint32        // Time when alarm occurred (Zigbee time, seconds since 2000-01-01)
}

AlarmEntry represents an entry in the device's alarm log. Alarms can be generated by various conditions on the device (e.g., low battery, temperature threshold).

type AnalogInputInfo

type AnalogInputInfo struct {
	PresentValue     float32              // Current analog value
	OutOfService     bool                 // Out of service flag
	StatusFlags      uint8                // Status bitmap
	EngineeringUnits zcl.EngineeringUnits // Engineering units
	MinValue         float32              // Minimum value
	MaxValue         float32              // Maximum value
}

AnalogInputInfo contains analog input sensor information.

type AnalogOutputInfo

type AnalogOutputInfo struct {
	PresentValue     float32              // Current output value
	OutOfService     bool                 // Out of service flag
	StatusFlags      uint8                // Status bitmap
	EngineeringUnits zcl.EngineeringUnits // Engineering units
	MinValue         float32              // Minimum value
	MaxValue         float32              // Maximum value
}

AnalogOutputInfo contains analog output control information.

type AnalogValueInfo

type AnalogValueInfo struct {
	PresentValue     float32              // Current analog value (read/write)
	OutOfService     bool                 // Out of service flag
	StatusFlags      uint8                // Status bitmap
	EngineeringUnits zcl.EngineeringUnits // Engineering units
}

AnalogValueInfo contains analog value information.

type AttributeResult

type AttributeResult struct {
	AttributeID zcl.AttributeID
	Status      uint8
	DataType    zcl.DataType
	Value       interface{}
}

AttributeResult represents a single attribute read result.

type BatteryInfo

type BatteryInfo struct {
	Voltage    *float64 // Voltage in V (nil if not available)
	Percentage *uint8   // Percentage remaining 0-100% (nil if not available)
	LowBattery bool     // True if battery alarm is active
}

BatteryInfo contains battery status information.

type BinaryInputInfo

type BinaryInputInfo struct {
	PresentValue bool              // Current input value (active/inactive)
	OutOfService bool              // Out of service flag
	StatusFlags  uint8             // Status bitmap
	Reliability  zcl.IOReliability // Reliability state
}

BinaryInputInfo contains binary input status information.

type BinaryOutputInfo

type BinaryOutputInfo struct {
	PresentValue bool  // Current output value
	OutOfService bool  // Out of service flag
	StatusFlags  uint8 // Status flags bitmap
	Polarity     uint8 // 0=normal, 1=reversed
}

BinaryOutputInfo contains the status information for a BinaryOutput device.

type BinaryValueInfo

type BinaryValueInfo struct {
	PresentValue bool              // Current value (read/write)
	OutOfService bool              // Out of service flag
	StatusFlags  uint8             // Status bitmap
	Reliability  zcl.IOReliability // Reliability status
}

BinaryValueInfo contains binary value information.

type BindingInfo

type BindingInfo struct {
	SrcAddr     [8]byte // Source device IEEE address
	SrcEndpoint uint8   // Source endpoint
	ClusterID   uint16  // Cluster ID
	DstAddrMode uint8   // 0x01=group, 0x03=IEEE address
	DstAddr     [8]byte // Destination IEEE address (or group ID)
	DstEndpoint uint8   // Destination endpoint
}

BindingInfo contains information about a binding entry on a device.

type ColorState

type ColorState struct {
	Hue        uint8  // Current hue (0-254)
	Saturation uint8  // Current saturation (0-254)
	X          uint16 // Current X chromaticity coordinate
	Y          uint16 // Current Y chromaticity coordinate
	ColorMode  uint8  // 0=HS, 1=XY, 2=ColorTemp
}

ColorState contains the current color state of a device.

type ColorTempInfo

type ColorTempInfo struct {
	CurrentMireds uint16 // Current color temp in mireds
	MinMireds     uint16 // Minimum (warmest, lowest Kelvin)
	MaxMireds     uint16 // Maximum (coolest, highest Kelvin)
}

ColorTempInfo contains color temperature range information.

type DRLCEventInfo

type DRLCEventInfo struct {
	IssuerEventID    uint32 // Unique event ID from utility
	DeviceClass      uint16 // Device class bitmap (which devices should respond)
	UtilityGroupID   uint8  // Utility enrolment group
	StartTime        uint32 // Event start time (Zigbee time, seconds since 2000-01-01)
	Duration         uint16 // Event duration in minutes
	CriticalityLevel uint8  // Criticality level (0-15, higher = more critical)
	CoolingOffset    uint8  // Temperature offset for cooling (°C)
	HeatingOffset    uint8  // Temperature offset for heating (°C)
}

DRLCEventInfo contains information about a demand response load control event. This represents a request from the utility to reduce or shift energy consumption.

type Device

type Device struct {
	IEEEAddr     [8]byte
	NwkAddr      uint16
	Capabilities uint8
	Endpoints    []uint8
	LastSeen     time.Time
}

Device represents a paired Zigbee device.

func (*Device) IsBatteryPowered

func (d *Device) IsBatteryPowered() bool

IsBatteryPowered returns true if battery powered.

func (*Device) IsRouter

func (d *Device) IsRouter() bool

IsRouter returns true if device is a router.

type DeviceCapabilities

type DeviceCapabilities struct {
	NwkAddr   uint16
	Endpoints []*EndpointDescriptor
}

DeviceCapabilities contains full device capability information.

type DeviceEvent

type DeviceEvent struct {
	Type     DeviceEventType
	Device   *Device
	IEEEAddr [8]byte // For leave events
}

DeviceEvent represents a device join/leave event.

type DeviceEventType

type DeviceEventType int

DeviceEventType defines device event types.

const (
	DeviceEventJoined DeviceEventType = iota
	DeviceEventLeft
)

type DeviceInfo

type DeviceInfo struct {
	// Core Device Information
	ZCLVersion       *uint8  // ZCL version supported
	AppVersion       *uint8  // Application version
	StackVersion     *uint8  // Stack version
	HWVersion        *uint8  // Hardware version
	ManufacturerName *string // Manufacturer name
	ModelIdentifier  *string // Model identifier
	DateCode         *string // Manufacturing date code (YYYYMMDD format)
	PowerSource      *zcl.PowerSource
	SWBuildID        *string // Software build ID

	// Extended Device Information
	ProductCode                *string // Product code (octet string)
	ProductURL                 *string // Product URL
	ManufacturerVersionDetails *string // Manufacturer version details
	SerialNumber               *string // Serial number
	ProductLabel               *string // Product label

	// Optional Device Information
	LocationDescription *string // Physical location description (max 16 chars)
	PhysicalEnvironment *uint8  // Physical environment type (enum8)
	DeviceEnabled       *bool   // Whether device is enabled
	AlarmMask           *uint8  // Alarm mask (bitmap8)
	DisableLocalConfig  *uint8  // Local config disable mask (bitmap8)

	// Generic Device Information (ZCL 7+)
	GenericDeviceClass *uint8 // Generic device class (enum8)
	GenericDeviceType  *uint8 // Generic device type (enum8)
}

DeviceInfo contains all Basic cluster attributes for a device.

type DeviceNameInfo

type DeviceNameInfo struct {
	IEEEAddr    [8]byte
	Name        string
	Description string
}

DeviceNameInfo contains the custom name and description for a device.

func (*DeviceNameInfo) IEEEAddrString

func (d *DeviceNameInfo) IEEEAddrString() string

IEEEAddrString formats the IEEE address as a hex string. Returns format: "00:11:22:33:44:55:66:77" (reversed byte order, high byte first in display).

type DeviceStatus

type DeviceStatus struct {
	NwkAddr        uint16
	Manufacturer   string
	Model          string
	PowerSource    zcl.PowerSource
	BatteryPercent *uint8 // nil if not available
	OnOff          *bool  // nil if not on/off device
}

DeviceStatus contains common device status information.

type DeviceType

type DeviceType uint8

DeviceType represents the logical type of a Zigbee device.

const (
	DeviceTypeCoordinator DeviceType = 0
	DeviceTypeRouter      DeviceType = 1
	DeviceTypeEndDevice   DeviceType = 2
)

func (DeviceType) String

func (dt DeviceType) String() string

String returns human-readable device type name.

type DoorLockStatus

type DoorLockStatus struct {
	LockState       zcl.DoorLockState
	DoorState       *zcl.DoorState
	ActuatorEnabled bool
	AutoRelockTime  *uint32
}

DoorLockStatus contains current lock state.

type EndpointDef

type EndpointDef struct {
	Endpoint    uint8
	ProfileID   znp.ApplicationProfile
	DeviceID    uint16
	InClusters  []uint16
	OutClusters []uint16
}

EndpointDef defines a coordinator endpoint configuration.

type EndpointDescriptor

type EndpointDescriptor struct {
	Endpoint      uint8
	ProfileID     uint16
	DeviceID      uint16
	DeviceVersion uint8
	InClusters    []uint16
	OutClusters   []uint16
}

EndpointDescriptor contains cluster information for an endpoint.

type EndpointInfo

type EndpointInfo struct {
	Endpoint      uint8
	ProfileID     uint16
	DeviceID      uint16
	DeviceVersion uint8
	InClusters    []uint16
	OutClusters   []uint16
}

EndpointInfo contains cluster information for an endpoint.

func (*EndpointInfo) HasCluster

func (e *EndpointInfo) HasCluster(clusterID uint16) bool

HasCluster returns true if the endpoint has the specified input cluster.

type FanStatus

type FanStatus struct {
	Mode           *zcl.FanMode         // Current fan mode
	ModeSequence   *zcl.FanModeSequence // Supported fan mode sequence
	PercentSetting *uint8               // Fan speed setting as percentage (0-100%)
	PercentCurrent *uint8               // Current fan speed as percentage (0-100%)
	SpeedMax       *uint8               // Maximum fan speed
	SpeedSetting   *uint8               // Fan speed setting
	SpeedCurrent   *uint8               // Current fan speed
}

FanStatus contains current fan state.

type GroupMembership

type GroupMembership struct {
	Capacity uint8    // Remaining capacity for group memberships (0xFF = unknown)
	Groups   []uint16 // List of group IDs the device belongs to
}

GroupMembership contains the groups a device belongs to.

type IASZoneNotification

type IASZoneNotification struct {
	SrcAddr    uint16 // Source device network address
	Endpoint   uint8  // Source endpoint
	ZoneStatus uint16 // Status bitmap
	ExtStatus  uint8  // Extended status
	ZoneID     uint8  // Zone ID
	Delay      uint16 // Delay in quarter-seconds

	// Parsed status flags for convenience
	Alarm1        bool // Alarm 1 active
	Alarm2        bool // Alarm 2 active
	Tamper        bool // Tamper detected
	LowBattery    bool // Low battery
	Trouble       bool // Trouble/failure
	ACMains       bool // AC mains fault
	Test          bool // Test mode
	BatteryDefect bool // Battery defect
}

IASZoneNotification represents a zone status change notification from a device. These are sent automatically by enrolled IAS Zone devices when their status changes (e.g., motion detected, door opened, tamper alert).

type IASZoneStatus

type IASZoneStatus struct {
	ZoneState  uint8           // 0=not enrolled, 1=enrolled
	ZoneType   zcl.IASZoneType // Type of sensor
	ZoneStatus uint16          // Bitmap of current alarms and states
	ZoneID     *uint8          // Zone ID (0-254), nil if not available
	CIEAddress *[8]byte        // IEEE address of CIE, nil if not available

	// Parsed status flags for convenience
	Alarm1        bool // Alarm 1 active (e.g., motion detected, door open)
	Alarm2        bool // Alarm 2 active (secondary alarm)
	Tamper        bool // Tamper detected
	LowBattery    bool // Low battery warning
	Trouble       bool // Sensor trouble/failure
	ACMains       bool // AC mains fault
	Test          bool // Sensor in test mode
	BatteryDefect bool // Battery defect detected
}

IASZoneStatus contains current zone sensor state.

type Info

type Info struct {
	Version      *znp.VersionInfo
	Capabilities uint16
}

Info contains comprehensive adapter information.

type InterviewOptions

type InterviewOptions struct {
	// Timeout per individual ZDO/ZCL request (default: 10s)
	RequestTimeout time.Duration

	// Skip reading Basic cluster attributes (faster but less info)
	SkipBasicCluster bool

	// Number of retries for failed requests (default: 1)
	Retries int
}

InterviewOptions configures the interview process.

func DefaultInterviewOptions

func DefaultInterviewOptions() InterviewOptions

DefaultInterviewOptions returns sensible defaults for interviewing.

type InterviewResult

type InterviewResult struct {
	// Device addressing
	IEEEAddr [8]byte
	NwkAddr  uint16

	// From NodeDescriptor
	DeviceType       DeviceType
	ManufacturerCode uint16

	// From Basic cluster
	Manufacturer               string
	Model                      string
	PowerSource                PowerSource
	SWBuildID                  string // Software build ID (optional)
	ProductCode                string // Product code (optional, octet string)
	ProductURL                 string // Product URL (optional)
	ManufacturerVersionDetails string // Manufacturer version details (optional)
	SerialNumber               string // Serial number (optional)
	ProductLabel               string // Product label (optional)

	// All endpoints with their clusters
	Endpoints []EndpointInfo

	// Interview metadata
	InterviewedAt time.Time
	Success       bool
	Errors        []string // Non-fatal errors encountered during interview
}

InterviewResult contains all discovered information about a device.

func (*InterviewResult) FindEndpointWithCluster

func (r *InterviewResult) FindEndpointWithCluster(clusterID uint16) *EndpointInfo

FindEndpointWithCluster returns the first endpoint that has the specified cluster.

func (*InterviewResult) IEEEAddrString

func (r *InterviewResult) IEEEAddrString() string

IEEEAddrString returns the IEEE address as a hex string.

type MainsInfo

type MainsInfo struct {
	Voltage   *float64 // Voltage in V (nil if not available)
	Frequency *uint8   // Frequency in Hz (nil if not available)
}

MainsInfo contains mains power information.

type MultistateInputInfo

type MultistateInputInfo struct {
	PresentValue   uint16            // Current state value (1-based)
	NumberOfStates uint16            // Number of possible states
	OutOfService   bool              // Out of service flag
	StatusFlags    uint8             // Status bitmap
	Reliability    zcl.IOReliability // Reliability state
}

MultistateInputInfo contains multistate input information.

type MultistateOutputInfo

type MultistateOutputInfo struct {
	PresentValue   uint16 // Current state value
	NumberOfStates uint16 // Number of possible states
	OutOfService   bool   // Out of service flag
	StatusFlags    uint8  // Status flags bitmap
}

MultistateOutputInfo contains the status information for a MultistateOutput device.

type MultistateValueInfo

type MultistateValueInfo struct {
	PresentValue   uint16            // Current value (read/write)
	NumberOfStates uint16            // Number of possible states
	OutOfService   bool              // Out of service flag
	StatusFlags    uint8             // Status flags bitmap
	Reliability    zcl.IOReliability // Reliability state
}

MultistateValueInfo contains the status information for a MultistateValue device.

type NeighborInfo

type NeighborInfo struct {
	NwkAddr    uint16
	IEEEAddr   [8]byte
	DeviceType uint8 // 0=Coordinator, 1=Router, 2=EndDevice
	Relation   uint8 // 0=Parent, 1=Child, 2=Sibling, 3=None, 4=PreviousChild
	LQI        uint8 // Link Quality (0-255, higher is better)
	Depth      uint8 // Tree depth from coordinator
}

NeighborInfo contains information about a neighbor in the mesh network.

type NetworkFormConfig

type NetworkFormConfig struct {
	// Channel is the Zigbee channel (11-26). If 0, uses a default channel.
	Channel uint8
	// PanID is the PAN ID. If 0, a random PAN ID is generated.
	PanID uint16
	// Profile is the Zigbee application profile. Default is "ha" (Home Automation).
	Profile string
}

NetworkFormConfig contains configuration for forming a new network.

type NetworkInfo

type NetworkInfo struct {
	// Coordinator info
	IEEEAddr  [8]byte
	ShortAddr uint16

	// Network config
	PanID         uint16
	ExtendedPanID [8]byte
	Channel       uint8

	// Registered endpoint profiles
	Profiles []znp.ApplicationProfile

	// Device info
	DeviceType      uint8
	DeviceState     uint8
	NumAssocDevices uint8
}

NetworkInfo contains comprehensive network information.

type OTAInfo

type OTAInfo struct {
	CurrentFileVersion uint32               // Current firmware version
	UpgradeStatus      zcl.OTAUpgradeStatus // Current upgrade status
	ManufacturerID     uint16               // Manufacturer ID
	ImageTypeID        uint16               // Image type ID
	FileOffset         uint32               // Current file offset
}

OTAInfo contains OTA upgrade status information.

type Option

type Option func(*Options)

Option is a functional option for configuring the adapter.

func WithBaudRate

func WithBaudRate(rate int) Option

WithBaudRate sets the serial port baud rate.

func WithPingRetries

func WithPingRetries(retries int) Option

WithPingRetries sets the number of ping retry attempts.

func WithPingTimeout

func WithPingTimeout(timeout time.Duration) Option

WithPingTimeout sets the timeout for ping operations.

func WithRTSCTSFlow

func WithRTSCTSFlow(enabled bool) Option

WithRTSCTSFlow enables or disables RTS/CTS hardware flow control.

func WithResetTimeout

func WithResetTimeout(timeout time.Duration) Option

WithResetTimeout sets the timeout for reset operations.

func WithSerialPath

func WithSerialPath(path string) Option

WithSerialPath sets the serial port path.

type Options

type Options struct {
	SerialConfig serial.Config
	PingRetries  int
	PingTimeout  time.Duration
	ResetTimeout time.Duration
}

Options configures the adapter.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns default adapter options.

type PollControlInfo

type PollControlInfo struct {
	CheckInInterval   uint32 // In quarter seconds
	LongPollInterval  uint32 // In quarter seconds
	ShortPollInterval uint16 // In quarter seconds
	FastPollTimeout   uint16 // In quarter seconds
}

PollControlInfo contains poll control configuration for a sleepy end device.

type PowerData

type PowerData struct {
	// Electrical Measurement cluster (0x0B04) - instantaneous values
	Voltage     *float64 // RMS Voltage in volts
	Current     *float64 // RMS Current in amps
	ActivePower *float64 // Active power in watts
	PowerFactor *int8    // Power factor (-100 to 100%)

	// Simple Metering cluster (0x0702) - cumulative values
	TotalEnergy  *float64 // Total energy in kWh
	InstantPower *float64 // Instantaneous demand in watts (from metering)

	// Debug info
	RawVoltage uint16
	RawCurrent uint16
	RawPower   int16
	RawEnergy  uint64
}

PowerData contains power consumption readings from a smart plug.

type PowerSource

type PowerSource uint8

PowerSource represents how a device is powered.

const (
	PowerSourceUnknown          PowerSource = 0x00
	PowerSourceMains            PowerSource = 0x01
	PowerSourceBattery          PowerSource = 0x03
	PowerSourceDC               PowerSource = 0x04
	PowerSourceEmergencyMains   PowerSource = 0x05
	PowerSourceEmergencyBattery PowerSource = 0x06
)

func (PowerSource) String

func (ps PowerSource) String() string

String returns human-readable power source name.

type PressureData

type PressureData struct {
	Pressure    *float64 // Pressure in hPa (hectopascals)
	MinPressure *float64 // Minimum measurable pressure in hPa
	MaxPressure *float64 // Maximum measurable pressure in hPa
}

PressureData contains atmospheric pressure readings.

type PriceInfo

type PriceInfo struct {
	ProviderId         uint32 // Unique identifier for the commodity supplier
	RateLabel          string // User-defined rate label (e.g., "Peak", "Off-Peak")
	IssuerEventId      uint32 // Unique identifier for this pricing event
	CurrentTime        uint32 // Current time in Zigbee time (seconds since 2000-01-01)
	UnitOfMeasure      uint8  // Unit of measurement (kWh, m3, etc.)
	Currency           uint16 // ISO 4217 currency code (e.g., 840 = USD)
	PriceTrailingDigit uint8  // Number of digits to right of decimal point
	NumberOfTiers      uint8  // Number of price tiers in use
	Price              uint32 // Price in currency units (apply trailing digit)
	StartTime          uint32 // When this price becomes effective (Zigbee time)
	DurationInMinutes  uint16 // How long this price is valid
}

PriceInfo contains pricing information from the Price cluster. This is part of the Smart Energy profile used for dynamic pricing and demand response applications.

type RegisteredEndpoints

type RegisteredEndpoints struct {
	Endpoints []uint8
	Profiles  map[uint8]znp.ApplicationProfile
}

RegisteredEndpoints holds the list of successfully registered endpoints.

func NewRegisteredEndpoints

func NewRegisteredEndpoints() *RegisteredEndpoints

NewRegisteredEndpoints creates a new RegisteredEndpoints tracker.

func (*RegisteredEndpoints) Add

func (r *RegisteredEndpoints) Add(endpoint uint8, profile znp.ApplicationProfile)

Add records a successfully registered endpoint.

func (*RegisteredEndpoints) GetProfiles

func (r *RegisteredEndpoints) GetProfiles() []znp.ApplicationProfile

GetProfiles returns all registered profiles.

func (*RegisteredEndpoints) HasProfile

func (r *RegisteredEndpoints) HasProfile(profile znp.ApplicationProfile) bool

HasProfile returns true if any endpoint with the given profile is registered.

type ReportedAttribute

type ReportedAttribute struct {
	ID    uint16
	Value interface{}
}

ReportedAttribute contains raw attribute data for debugging.

type ReportingConfigResult

type ReportingConfigResult struct {
	Status           uint8
	Direction        uint8
	AttributeID      zcl.AttributeID
	DataType         zcl.DataType
	MinInterval      uint16
	MaxInterval      uint16
	ReportableChange interface{}
	TimeoutPeriod    uint16
}

ReportingConfigResult contains the reporting configuration for a single attribute.

type SEMessage

type SEMessage struct {
	MessageID uint32 // Unique message identifier
	Control   uint8  // MessageControl bitmap (transmission, importance, confirmation)
	StartTime uint32 // Zigbee time when message should be displayed (0 = now)
	Duration  uint16 // Duration to display message in minutes (0xFFFF = until explicitly cancelled)
	Message   string // Message text to display
}

SEMessage represents a Smart Energy message to be displayed on a device. This is used with the Messaging cluster (0x0703) in the Smart Energy profile.

type SceneMembership

type SceneMembership struct {
	Status   uint8   // ZCL status (0 = success)
	Capacity uint8   // Remaining capacity for scenes (0xFF = unknown)
	GroupID  uint16  // The group these scenes belong to
	Scenes   []uint8 // List of scene IDs
}

SceneMembership contains the scenes stored on a device for a group.

type SensorData

type SensorData struct {
	Temperature *float32 // Celsius, nil if not available
	Humidity    *float32 // Percent, nil if not available
	Battery     *uint8   // Percent, nil if not available
}

SensorData contains temperature and humidity sensor readings.

type SensorReport

type SensorReport struct {
	NwkAddr     uint16
	ClusterID   uint16 // For debugging
	Endpoint    uint8  // For debugging
	Temperature *float32
	Humidity    *float32
	Battery     *uint8
	// Power consumption data from smart plugs
	Voltage *float64 // RMS Voltage in volts
	Current *float64 // RMS Current in amps
	Power   *float64 // Active power in watts
	Energy  *float64 // Total energy in kWh
	// On/Off state
	OnOff *bool
	// Debug info
	FrameCommandID uint8
	ParseError     string
	Attributes     []ReportedAttribute
}

SensorReport contains a sensor report with device address.

type ThermostatStatus

type ThermostatStatus struct {
	LocalTemperature *float64                  // Current temperature in °C
	CoolingSetpoint  *float64                  // Cooling setpoint in °C
	HeatingSetpoint  *float64                  // Heating setpoint in °C
	SystemMode       *zcl.ThermostatSystemMode // Current operating mode
	RunningState     *uint16                   // Bitmap of running states
	CoolingDemand    *uint8                    // 0-100%
	HeatingDemand    *uint8                    // 0-100%
}

ThermostatStatus contains current thermostat state.

type TimeInfo

type TimeInfo struct {
	Time       uint32 // UTC time since 2000-01-01 (Zigbee epoch)
	TimeStatus uint8  // Status bitmap
	TimeZone   int32  // Timezone offset in seconds
	LocalTime  uint32 // Local time
}

TimeInfo contains time information from a Time cluster device.

type WindowCoveringStatus

type WindowCoveringStatus struct {
	Type         *zcl.WindowCoveringType
	LiftPercent  *uint8 // 0=fully open, 100=fully closed
	TiltPercent  *uint8 // 0=fully open, 100=fully closed
	ConfigStatus *uint8
}

WindowCoveringStatus contains current covering position.

Jump to

Keyboard shortcuts

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