Documentation
¶
Overview ¶
Package adapter provides a high-level API for controlling Zigbee networks through Texas Instruments Z-Stack Network Processor (ZNP) adapters.
Basic Usage ¶
Create and open an adapter:
a := adapter.New(adapter.WithSerialPath("/dev/ttyUSB0"))
if err := a.Open(ctx); err != nil {
log.Fatal(err)
}
defer a.Close()
Network Operations ¶
Form a new network:
err := a.FormNetwork(ctx, adapter.NetworkFormConfig{Channel: 15})
Permit device joining:
err := a.PermitJoin(ctx, 254) // 254 seconds
Device Operations ¶
List all paired devices:
devices, err := a.GetDevices(ctx)
Control a device:
err := a.TurnOn(ctx, nwkAddr, endpoint)
Read device status:
status, err := a.GetDeviceStatus(ctx, nwkAddr)
Device Naming ¶
Set a custom name stored on the coordinator:
a.SetDeviceName(ctx, ieeeAddr, "Living Room Light", "Main ceiling light")
Get a device name:
name, _ := a.GetDeviceName(ctx, ieeeAddr)
Events ¶
Register for device join/leave events:
a.OnDeviceEvent(func(event adapter.DeviceEvent) {
fmt.Printf("Device event: %v\n", event)
})
Messaging ¶
Read attributes:
results, err := a.ReadAttributes(ctx, nwkAddr, endpoint, clusterID, []zcl.AttributeID{
zcl AttrOnOff,
})
Write attributes:
err := a.WriteAttributes(ctx, nwkAddr, endpoint, clusterID, []zcl.AttributeRecord{
{ID: zcl.AttrOnOff, DataType: zcl.TypeData8, Value: uint8(1)},
})
Thread Safety ¶
The Adapter is safe for concurrent use from multiple goroutines. All methods use internal mutex protection.
Context Support ¶
All methods accept a context.Context for cancellation and timeout control. Recommended timeout: 10-30 seconds for most operations.
Hardware Support ¶
This library supports Texas Instruments CC2652R/RB, CC2652P, and CC1352P coordinators running Koenkk Z-Stack 3.x.0 firmware.
Device Management ¶
Device information is maintained by the device manager, which tracks devices by their IEEE address and network address. When devices rejoin with a new network address, the device manager automatically updates.
Quirks ¶
Some devices don't follow the Zigbee specification exactly. The library includes a quirks system that can override default behavior for specific manufacturers or models. Quirks are automatically applied during device interview.
Package adapter provides a high-level API for Z-Stack Zigbee adapters.
Index ¶
- Constants
- Variables
- func ExtractBool(v interface{}) (bool, bool)
- func ExtractFloat32(v interface{}) (float32, bool)
- func ExtractInt8(v interface{}) (int8, bool)
- func ExtractInt16(v interface{}) (int16, bool)
- func ExtractInt32(v interface{}) (int32, bool)
- func ExtractString(v interface{}) (string, bool)
- func ExtractUint8(v interface{}) (uint8, bool)
- func ExtractUint16(v interface{}) (uint16, bool)
- func ExtractUint32(v interface{}) (uint32, bool)
- func ExtractUint48(v interface{}) (uint64, bool)
- func GetEndpointForProfile(profile znp.ApplicationProfile) uint8
- func QuarterSecondsToSeconds(quarterSecs uint32) float64
- func SecondsToQuarterSeconds(secs float64) uint32
- func SupportedProfiles() []znp.ApplicationProfile
- func UnixToZigbeeTime(t time.Time) uint32
- func ZigbeeTimeToUnix(zigbeeTime uint32) time.Time
- type Adapter
- func (a *Adapter) AddScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, ...) error
- func (a *Adapter) AddToGroup(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, ...) error
- func (a *Adapter) AdjustThermostatSetpoint(ctx context.Context, nwkAddr uint16, endpoint uint8, mode uint8, amount int8) error
- func (a *Adapter) Bind(ctx context.Context, deviceIEEEAddr [8]byte, deviceNwkAddr uint16, ...) error
- func (a *Adapter) CancelSEMessage(ctx context.Context, nwkAddr uint16, endpoint uint8, messageID uint32) error
- func (a *Adapter) ChangeChannel(ctx context.Context, channel uint8, seamless bool) error
- func (a *Adapter) ClearDoorLockPIN(ctx context.Context, nwkAddr uint16, endpoint uint8, userID uint16) error
- func (a *Adapter) Close() error
- func (a *Adapter) CloseWindowCovering(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) ConfigureReporting(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, ...) error
- func (a *Adapter) CreateBackup(ctx context.Context) (*backup.Backup, error)
- func (a *Adapter) DeleteDeviceName(ctx context.Context, ieeeAddr [8]byte) error
- func (a *Adapter) DisplaySEMessage(ctx context.Context, nwkAddr uint16, endpoint uint8, msg SEMessage) error
- func (a *Adapter) EnrollIASZone(ctx context.Context, nwkAddr uint16, endpoint uint8, responseCode uint8, ...) error
- func (a *Adapter) FactoryReset(ctx context.Context) error
- func (a *Adapter) ForceRemoveDevice(ctx context.Context, ieeeAddr [8]byte) error
- func (a *Adapter) FormNetwork(ctx context.Context, config NetworkFormConfig) error
- func (a *Adapter) GetActiveEndpoints(ctx context.Context, nwkAddr uint16) ([]uint8, error)
- func (a *Adapter) GetAirQuality(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AirQualityData, error)
- func (a *Adapter) GetAlarm(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AlarmEntry, error)
- func (a *Adapter) GetAlarmCount(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint16, error)
- func (a *Adapter) GetAnalogInput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AnalogInputInfo, error)
- func (a *Adapter) GetAnalogInputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (float32, error)
- func (a *Adapter) GetAnalogOutput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AnalogOutputInfo, error)
- func (a *Adapter) GetAnalogOutputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (float32, error)
- func (a *Adapter) GetAnalogValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (*AnalogValueInfo, error)
- func (a *Adapter) GetBatteryInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BatteryInfo, error)
- func (a *Adapter) GetBinaryInput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BinaryInputInfo, error)
- func (a *Adapter) GetBinaryInputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (bool, error)
- func (a *Adapter) GetBinaryOutput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BinaryOutputInfo, error)
- func (a *Adapter) GetBinaryOutputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (bool, error)
- func (a *Adapter) GetBinaryValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (*BinaryValueInfo, error)
- func (a *Adapter) GetBindingTable(ctx context.Context, nwkAddr uint16) ([]BindingInfo, error)
- func (a *Adapter) GetBrightness(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint8, error)
- func (a *Adapter) GetCO2Level(ctx context.Context, nwkAddr uint16, endpoint uint8) (*float32, error)
- func (a *Adapter) GetColor(ctx context.Context, nwkAddr uint16, endpoint uint8) (*ColorState, error)
- func (a *Adapter) GetColorTempInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*ColorTempInfo, error)
- func (a *Adapter) GetColorTemperature(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint16, error)
- func (a *Adapter) GetCoordinatorIEEE(ctx context.Context) ([8]byte, error)
- func (a *Adapter) GetCurrentChannel(ctx context.Context) (uint8, error)
- func (a *Adapter) GetCurrentPrice(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PriceInfo, error)
- func (a *Adapter) GetDRLCInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DRLCEventInfo, error)
- func (a *Adapter) GetDevice(ieeeAddr [8]byte) *Device
- func (a *Adapter) GetDeviceByNwkAddr(nwkAddr uint16) *Device
- func (a *Adapter) GetDeviceCapabilities(ctx context.Context, nwkAddr uint16) (*DeviceCapabilities, error)
- func (a *Adapter) GetDeviceHealth(ctx context.Context, nwkAddr uint16) (*DeviceHealth, error)
- func (a *Adapter) GetDeviceName(ctx context.Context, ieeeAddr [8]byte) (*DeviceNameInfo, error)
- func (a *Adapter) GetDeviceStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DeviceStatus, error)
- func (a *Adapter) GetDevices(ctx context.Context) ([]*Device, error)
- func (a *Adapter) GetDoorLockStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DoorLockStatus, error)
- func (a *Adapter) GetEndpointForProfile(profile znp.ApplicationProfile) uint8
- func (a *Adapter) GetFanStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*FanStatus, error)
- func (a *Adapter) GetGroupMembership(ctx context.Context, nwkAddr uint16, endpoint uint8) (*GroupMembership, error)
- func (a *Adapter) GetIASZoneStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*IASZoneStatus, error)
- func (a *Adapter) GetInfo(ctx context.Context) (*Info, error)
- func (a *Adapter) GetLastSEMessage(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) GetMainsInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MainsInfo, error)
- func (a *Adapter) GetMultistateInput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MultistateInputInfo, error)
- func (a *Adapter) GetMultistateInputValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (uint16, error)
- func (a *Adapter) GetMultistateOutput(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MultistateOutputInfo, error)
- func (a *Adapter) GetMultistateValue(ctx context.Context, nwkAddr uint16, endpoint uint8) (*MultistateValueInfo, error)
- func (a *Adapter) GetNeighborTable(ctx context.Context, nwkAddr uint16) ([]NeighborInfo, error)
- func (a *Adapter) GetNetworkHealth(ctx context.Context) (*NetworkHealth, error)
- func (a *Adapter) GetNetworkInfo(ctx context.Context) (*NetworkInfo, error)
- func (a *Adapter) GetOTAInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*OTAInfo, error)
- func (a *Adapter) GetOTAUpgradeStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (zcl.OTAUpgradeStatus, error)
- func (a *Adapter) GetOnOffState(ctx context.Context, nwkAddr uint16, endpoint uint8) (bool, error)
- func (a *Adapter) GetPM25Level(ctx context.Context, nwkAddr uint16, endpoint uint8) (*float32, error)
- func (a *Adapter) GetPollControlInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PollControlInfo, error)
- func (a *Adapter) GetPressure(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PressureData, error)
- func (a *Adapter) GetRoutingTable(ctx context.Context, nwkAddr uint16) ([]RoutingInfo, error)
- func (a *Adapter) GetSceneMembership(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16) (*SceneMembership, error)
- func (a *Adapter) GetSimpleDescriptor(ctx context.Context, nwkAddr uint16, endpoint uint8) (*EndpointDescriptor, error)
- func (a *Adapter) GetThermostatStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*ThermostatStatus, error)
- func (a *Adapter) GetTime(ctx context.Context, nwkAddr uint16, endpoint uint8) (*TimeInfo, error)
- func (a *Adapter) GetTimeZone(ctx context.Context, nwkAddr uint16, endpoint uint8) (int32, error)
- func (a *Adapter) GetTxPower(ctx context.Context) (int8, error)
- func (a *Adapter) GetWindowCoveringStatus(ctx context.Context, nwkAddr uint16, endpoint uint8) (*WindowCoveringStatus, error)
- func (a *Adapter) GetZNP() ZNPClient
- func (a *Adapter) GroupRecallScene(ctx context.Context, groupID uint16, sceneID uint8) error
- func (a *Adapter) GroupSetBrightness(ctx context.Context, groupID uint16, level uint8, transitionTime uint16) error
- func (a *Adapter) GroupToggle(ctx context.Context, groupID uint16) error
- func (a *Adapter) GroupTurnOff(ctx context.Context, groupID uint16) error
- func (a *Adapter) GroupTurnOn(ctx context.Context, groupID uint16) error
- func (a *Adapter) Identify(ctx context.Context, nwkAddr uint16, endpoint uint8, durationSecs uint16) error
- func (a *Adapter) InterviewAllDevices(ctx context.Context) ([]*InterviewResult, error)
- func (a *Adapter) InterviewAllDevicesWithOptions(ctx context.Context, opts InterviewOptions) ([]*InterviewResult, error)
- func (a *Adapter) InterviewDevice(ctx context.Context, nwkAddr uint16) (*InterviewResult, error)
- func (a *Adapter) InterviewDeviceByIEEE(ctx context.Context, ieeeAddr [8]byte) (*InterviewResult, error)
- func (a *Adapter) InterviewDeviceWithAddr(ctx context.Context, nwkAddr uint16, ieeeAddr [8]byte) (*InterviewResult, error)
- func (a *Adapter) InterviewDeviceWithOptions(ctx context.Context, nwkAddr uint16, opts InterviewOptions) (*InterviewResult, error)
- func (a *Adapter) IsOpen() bool
- func (a *Adapter) ListDeviceNames(ctx context.Context) ([]DeviceNameInfo, error)
- func (a *Adapter) LockDoor(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) MoveLevel(ctx context.Context, nwkAddr uint16, endpoint uint8, moveMode, rate uint8) error
- func (a *Adapter) OffWithEffect(ctx context.Context, nwkAddr uint16, endpoint uint8, ...) error
- func (a *Adapter) OnDeviceEvent(handler func(DeviceEvent))
- func (a *Adapter) OnWithTimedOff(ctx context.Context, nwkAddr uint16, endpoint uint8, ...) error
- func (a *Adapter) Open(ctx context.Context) error
- func (a *Adapter) OpenWindowCovering(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) PermitJoin(ctx context.Context, duration uint8) error
- func (a *Adapter) Ping(ctx context.Context) (*znp.PingCapabilities, error)
- func (a *Adapter) ReadAttributeBool(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (bool, error)
- func (a *Adapter) ReadAttributeFloat32(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (float32, error)
- func (a *Adapter) ReadAttributeInt8(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (int8, error)
- func (a *Adapter) ReadAttributeInt16(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (int16, error)
- func (a *Adapter) ReadAttributeInt32(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (int32, error)
- func (a *Adapter) ReadAttributeString(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (string, error)
- func (a *Adapter) ReadAttributeUint8(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (uint8, error)
- func (a *Adapter) ReadAttributeUint16(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (uint16, error)
- func (a *Adapter) ReadAttributeUint32(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (uint32, error)
- func (a *Adapter) ReadAttributeUint48(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, ...) (uint64, error)
- func (a *Adapter) ReadAttributes(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, ...) ([]AttributeResult, error)
- func (a *Adapter) ReadDeviceInfo(ctx context.Context, nwkAddr uint16, endpoint uint8) (*DeviceInfo, error)
- func (a *Adapter) ReadPowerData(ctx context.Context, nwkAddr uint16, endpoint uint8) (*PowerData, error)
- func (a *Adapter) ReadReportingConfig(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, ...) ([]ReportingConfigResult, error)
- func (a *Adapter) ReadSensorData(ctx context.Context, nwkAddr uint16, endpoint uint8) (*SensorData, error)
- func (a *Adapter) RecallScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, ...) error
- func (a *Adapter) RegisteredProfiles() []znp.ApplicationProfile
- func (a *Adapter) RemoveAllScenes(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16) error
- func (a *Adapter) RemoveDevice(ctx context.Context, nwkAddr uint16, ieeeAddr [8]byte, ...) error
- func (a *Adapter) RemoveFromAllGroups(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) RemoveFromGroup(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16) error
- func (a *Adapter) RemoveScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, ...) error
- func (a *Adapter) Reset(ctx context.Context) error
- func (a *Adapter) ResetAlarm(ctx context.Context, nwkAddr uint16, endpoint uint8, alarmCode uint8, ...) error
- func (a *Adapter) ResetAlarmLog(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) ResetAllAlarms(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) ResetEnergy(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) ResetToFactoryDefaults(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) RestoreBackup(ctx context.Context, b *backup.Backup) error
- func (a *Adapter) SendCheckInResponse(ctx context.Context, nwkAddr uint16, endpoint uint8, startFastPolling bool, ...) error
- func (a *Adapter) SendClusterCommand(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, ...) error
- func (a *Adapter) SendGroupCommand(ctx context.Context, groupID uint16, clusterID zcl.ClusterID, commandID uint8, ...) error
- func (a *Adapter) SetAnalogOutput(ctx context.Context, nwkAddr uint16, endpoint uint8, value float32) error
- func (a *Adapter) SetAnalogValue(ctx context.Context, nwkAddr uint16, endpoint uint8, value float32) error
- func (a *Adapter) SetBinaryOutput(ctx context.Context, nwkAddr uint16, endpoint uint8, value bool) error
- func (a *Adapter) SetBinaryValue(ctx context.Context, nwkAddr uint16, endpoint uint8, value bool) error
- func (a *Adapter) SetBrightness(ctx context.Context, nwkAddr uint16, endpoint uint8, level uint8, ...) error
- func (a *Adapter) SetColorKelvin(ctx context.Context, nwkAddr uint16, endpoint uint8, kelvin uint16, ...) error
- func (a *Adapter) SetColorRGB(ctx context.Context, nwkAddr uint16, endpoint uint8, r, g, b uint8, ...) error
- func (a *Adapter) SetColorTemperature(ctx context.Context, nwkAddr uint16, endpoint uint8, tempMireds uint16, ...) error
- func (a *Adapter) SetColorXY(ctx context.Context, nwkAddr uint16, endpoint uint8, x uint16, y uint16, ...) error
- func (a *Adapter) SetDeviceName(ctx context.Context, ieeeAddr [8]byte, name, comment string) error
- func (a *Adapter) SetDoorLockPIN(ctx context.Context, nwkAddr uint16, endpoint uint8, userID uint16, pin string) error
- func (a *Adapter) SetFanMode(ctx context.Context, nwkAddr uint16, endpoint uint8, mode zcl.FanMode) error
- func (a *Adapter) SetFanSpeed(ctx context.Context, nwkAddr uint16, endpoint uint8, percent uint8) error
- func (a *Adapter) SetHue(ctx context.Context, nwkAddr uint16, endpoint uint8, hue uint8, ...) error
- func (a *Adapter) SetHueSaturation(ctx context.Context, nwkAddr uint16, endpoint uint8, hue uint8, ...) error
- func (a *Adapter) SetLongPollInterval(ctx context.Context, nwkAddr uint16, endpoint uint8, ...) error
- func (a *Adapter) SetMultistateOutput(ctx context.Context, nwkAddr uint16, endpoint uint8, value uint16) error
- func (a *Adapter) SetMultistateValue(ctx context.Context, nwkAddr uint16, endpoint uint8, value uint16) error
- func (a *Adapter) SetSaturation(ctx context.Context, nwkAddr uint16, endpoint uint8, saturation uint8, ...) error
- func (a *Adapter) SetShortPollInterval(ctx context.Context, nwkAddr uint16, endpoint uint8, ...) error
- func (a *Adapter) SetStartupLevel(ctx context.Context, nwkAddr uint16, endpoint uint8, level uint8) error
- func (a *Adapter) SetStartupOnOff(ctx context.Context, nwkAddr uint16, endpoint uint8, value uint8) error
- func (a *Adapter) SetThermostatMode(ctx context.Context, nwkAddr uint16, endpoint uint8, ...) error
- func (a *Adapter) SetThermostatSetpoint(ctx context.Context, nwkAddr uint16, endpoint uint8, heating, cooling float64) error
- func (a *Adapter) SetTime(ctx context.Context, nwkAddr uint16, endpoint uint8, zigbeeTime uint32) error
- func (a *Adapter) SetTimeZone(ctx context.Context, nwkAddr uint16, endpoint uint8, offsetSeconds int32) error
- func (a *Adapter) SetTxPower(ctx context.Context, power int8) error
- func (a *Adapter) SetWindowCoveringPosition(ctx context.Context, nwkAddr uint16, endpoint uint8, percent uint8) error
- func (a *Adapter) SetWindowCoveringTilt(ctx context.Context, nwkAddr uint16, endpoint uint8, percent uint8) error
- func (a *Adapter) Squawk(ctx context.Context, nwkAddr uint16, endpoint uint8, mode uint8, ...) error
- func (a *Adapter) StartWarning(ctx context.Context, nwkAddr uint16, endpoint uint8, mode zcl.WarningMode, ...) error
- func (a *Adapter) StepLevel(ctx context.Context, nwkAddr uint16, endpoint uint8, stepMode, stepSize uint8, ...) error
- func (a *Adapter) StopFastPolling(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) StopLevel(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) StopWarning(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) StopWindowCovering(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) StoreScene(ctx context.Context, nwkAddr uint16, endpoint uint8, groupID uint16, ...) error
- func (a *Adapter) Toggle(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) ToggleDoorLock(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) TriggerEffect(ctx context.Context, nwkAddr uint16, endpoint uint8, effectID uint8, ...) error
- func (a *Adapter) TurnOff(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) TurnOn(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) Unbind(ctx context.Context, deviceIEEEAddr [8]byte, deviceNwkAddr uint16, ...) error
- func (a *Adapter) UnlockDoor(ctx context.Context, nwkAddr uint16, endpoint uint8) error
- func (a *Adapter) UnlockDoorWithTimeout(ctx context.Context, nwkAddr uint16, endpoint uint8, timeoutSeconds uint16) error
- func (a *Adapter) Version() *znp.VersionInfo
- func (a *Adapter) WaitForIASZoneNotification(ctx context.Context, timeout time.Duration) (*IASZoneNotification, error)
- func (a *Adapter) WaitForSensorReport(ctx context.Context, timeout time.Duration) (*SensorReport, error)
- func (a *Adapter) WriteAttributes(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, ...) error
- func (a *Adapter) WriteIASZoneCIEAddress(ctx context.Context, nwkAddr uint16, endpoint uint8, cieAddress [8]byte) error
- type AirQualityData
- type AlarmEntry
- type AnalogInputInfo
- type AnalogOutputInfo
- type AnalogValueInfo
- type AttributeResult
- type BatteryInfo
- type BinaryInputInfo
- type BinaryOutputInfo
- type BinaryValueInfo
- type BindingInfo
- type ColorState
- type ColorTempInfo
- type DRLCEventInfo
- type DefaultLogger
- type Device
- type DeviceCapabilities
- type DeviceEvent
- type DeviceEventType
- type DeviceHealth
- type DeviceInfo
- type DeviceNameInfo
- type DeviceStatus
- type DeviceType
- type DoorLockStatus
- type EndpointDef
- type EndpointDescriptor
- type EndpointInfo
- type FanStatus
- type GroupMembership
- type IASZoneNotification
- type IASZoneStatus
- type Info
- type InterviewOptions
- type InterviewResult
- type Logger
- type MainsInfo
- type MultistateInputInfo
- type MultistateOutputInfo
- type MultistateValueInfo
- type NeighborInfo
- type NetworkFormConfig
- type NetworkHealth
- type NetworkInfo
- type OTAInfo
- type Option
- func WithBaudRate(rate int) Option
- func WithLogger(logger Logger) Option
- func WithPingRetries(retries int) Option
- func WithPingTimeout(timeout time.Duration) Option
- func WithRTSCTSFlow(enabled bool) Option
- func WithResetTimeout(timeout time.Duration) Option
- func WithSerialPath(path string) Option
- func WithZCLRetryAttempts(attempts int) Option
- func WithZCLRetryDelay(delay time.Duration) Option
- func WithZDOInitDelay(delay time.Duration) Option
- type Options
- type PollControlInfo
- type PowerData
- type PowerSource
- type PressureData
- type PriceInfo
- type RegisteredEndpoints
- type ReportedAttribute
- type ReportingConfigResult
- type RoutingInfo
- type SEMessage
- type SceneMembership
- type SensorData
- type SensorReport
- type SlogLogger
- type ThermostatStatus
- type TimeInfo
- type TopologyNode
- type WeakLink
- type WindowCoveringStatus
- type ZNPClient
Constants ¶
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.
const ( // AddressModeGroup indicates the address is a group ID (16-bit). AddressModeGroup = 0x01 // AddressModeIEEE indicates the address is an IEEE address (64-bit). AddressModeIEEE = 0x03 )
Address modes for ZDO commands
const ( // LogicalTypeCoordinator represents a network coordinator. LogicalTypeCoordinator = 0x00 // LogicalTypeRouter represents a router device. LogicalTypeRouter = 0x01 // LogicalTypeEndDevice represents an end device. LogicalTypeEndDevice = 0x02 )
Logical types for network devices
const ( // BroadcastAddressNwk is the network broadcast address. BroadcastAddressNwk = 0xFFFF // InvalidAddressNwk is the invalid network address marker. InvalidAddressNwk = 0xFFFE // CoordinatorAddressNwk is the network address of the coordinator. CoordinatorAddressNwk = 0x0000 )
Special network addresses
const ( // NvItemCoordinatorEP is the coordinator's primary endpoint NV item ID. NvItemCoordinatorEP = 0x0001 // NvItemNIB is the Network Information Base NV item ID. NvItemNIB = 0x0021 // NvItemNwkActiveKeyInfo is the active network key info NV item ID. NvItemNwkActiveKeyInfo = 0x003F )
Magic numbers from Z-Stack NV items
const CoordinatorEndpoint = 1
Default coordinator endpoint (Home Automation profile).
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.
const (
// ReportingDirectionDeviceToCoordinator indicates the device reports to the coordinator.
ReportingDirectionDeviceToCoordinator = 0x00
)
Direction values for reporting configuration
const (
// StartupOptionClearState clears the device state and configuration.
StartupOptionClearState = 0x03
)
Startup options for NV memory
const (
// ZdoDirectCbEnabled enables ZDO direct callbacks.
ZdoDirectCbEnabled = 0x01
)
ZDO callback configuration
Variables ¶
var ( // ErrNotOpen indicates the adapter is not open. ErrNotOpen = errors.New("adapter: not open") // ErrDeviceNotFound indicates the requested device was not found. ErrDeviceNotFound = errors.New("adapter: device not found") // ErrClusterNotSupported indicates the device doesn't support the cluster. ErrClusterNotSupported = errors.New("adapter: cluster not supported by device") // ErrEndpointNotFound indicates the endpoint doesn't exist on the device. ErrEndpointNotFound = errors.New("adapter: endpoint not found") // ErrAttributeNotSupported indicates the attribute is not supported. ErrAttributeNotSupported = errors.New("adapter: attribute not supported") // ErrDeviceSleeping indicates the device is a sleepy end device and not responding. ErrDeviceSleeping = errors.New("adapter: device is sleeping") // ErrTransactionTimeout indicates a ZCL transaction timed out. ErrTransactionTimeout = errors.New("adapter: transaction timeout") // ErrInvalidResponse indicates an invalid or malformed response was received. ErrInvalidResponse = errors.New("adapter: invalid response") // ErrNetworkNotFormed indicates no network has been formed yet. ErrNetworkNotFormed = errors.New("adapter: network not formed") // ErrPermitJoinDisabled indicates permit join is not currently enabled. ErrPermitJoinDisabled = errors.New("adapter: permit join disabled") // ErrBindingFailed indicates a binding operation failed. ErrBindingFailed = errors.New("adapter: binding failed") // ErrReportingConfigFailed indicates reporting configuration failed. ErrReportingConfigFailed = errors.New("adapter: reporting configuration failed") )
Sentinel errors for adapter operations. These errors can be checked with errors.Is() for specific error handling.
var ( // ErrInvalidIEEEAddress is returned when an IEEE address is invalid. ErrInvalidIEEEAddress = errors.New("invalid IEEE address") // ErrInvalidEndpoint is returned when an endpoint number is invalid. ErrInvalidEndpoint = errors.New("invalid endpoint number") // ErrInvalidNetworkAddress is returned when a network address is invalid. ErrInvalidNetworkAddress = errors.New("invalid network address") )
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.
var ProfileToEndpoint = map[znp.ApplicationProfile]uint8{ znp.ProfileHomeAutomation: 1, znp.ProfileSmartEnergy: 2, znp.ProfileGreenPower: 3, znp.ProfileLightLink: 110, }
ProfileToEndpoint maps application profiles to their primary endpoint.
Functions ¶
func ExtractBool ¶ added in v0.2.0
ExtractBool extracts a bool from an attribute result value. Handles both native bool and uint8 representations (0 = false, non-zero = true).
func ExtractFloat32 ¶ added in v0.2.0
ExtractFloat32 extracts a float32 from an attribute result value. Returns false if the value is not a float32.
func ExtractInt8 ¶ added in v0.2.0
ExtractInt8 extracts an int8 from an attribute result value. Uses the existing toInt8 helper which handles int8, uint8, and int.
func ExtractInt16 ¶ added in v0.2.0
ExtractInt16 extracts an int16 from an attribute result value. Uses the existing toInt16 helper which handles int16, uint16, and int.
func ExtractInt32 ¶ added in v0.2.0
ExtractInt32 extracts an int32 from an attribute result value. Uses the existing toInt32 helper which handles int32, uint32, and int.
func ExtractString ¶ added in v0.2.0
ExtractString extracts a string from an attribute result value. Returns false if the value is not a string.
func ExtractUint8 ¶ added in v0.2.0
ExtractUint8 extracts a uint8 from an attribute result value. Returns false if the value cannot be converted to uint8.
func ExtractUint16 ¶ added in v0.2.0
ExtractUint16 extracts a uint16 from an attribute result value. Uses the existing toUint16 helper which handles uint16, int16, uint8, and int.
func ExtractUint32 ¶ added in v0.2.0
ExtractUint32 extracts a uint32 from an attribute result value. Uses the existing toUint32 helper which handles uint32, int32, uint16, and int.
func ExtractUint48 ¶ added in v0.2.0
ExtractUint48 extracts a uint48 (as uint64) from an attribute result value. Uses the existing toUint48 helper which handles uint64, int64, uint32, and int.
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 ¶
QuarterSecondsToSeconds converts quarter seconds to seconds. Quarter seconds are commonly used in Zigbee for timing intervals. 4 quarter seconds = 1 second.
func SecondsToQuarterSeconds ¶
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 ¶
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 ¶
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.
The Adapter provides a high-level API for managing a Zigbee network coordinator, including device pairing, ZCL messaging, and network management. It sits on top of the ZNP (Zigbee Network Processor) protocol layer, handling the low-level communication details.
Thread Safety: All public methods are thread-safe and safe for concurrent use from multiple goroutines.
Lifecycle:
- Create adapter with New() and configuration options
- Call Open() to connect to the adapter
- Use adapter methods for device/network operations
- Call Close() when done to release resources
Example:
adapter := adapter.New(
adapter.WithSerialPath("/dev/tty.usbserial-110"),
adapter.WithBaudRate(115200),
)
if err := adapter.Open(ctx); err != nil {
log.Fatal(err)
}
defer adapter.Close()
func New ¶
New creates a new adapter with the given options.
Use functional options to configure the adapter. Common options include:
- WithSerialPath: Set the serial port path (e.g., "/dev/tty.usbserial-110")
- WithBaudRate: Set baud rate (e.g., 115200)
- WithLogger: Set a logger for debug output
- WithZCLRetryAttempts: Set retry attempts for ZCL requests
The adapter is not opened until Open() is called.
Example:
adapter := adapter.New(
adapter.WithSerialPath("/dev/tty.usbserial-110"),
adapter.WithBaudRate(115200),
adapter.WithLogger(myLogger),
adapter.WithZCLRetryAttempts(3),
)
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 ¶
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) CloseWindowCovering ¶
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 method configures a device to push attribute updates instead of requiring polling, which is more efficient and reduces network traffic. The device will send reports when:
- The attribute changes by at least reportableChange (for analog types)
- The time since the last report exceeds maxInterval (periodic reports)
- The time since the last report is at least minInterval (rate limiting)
Parameters:
- ctx: Context for the operation
- nwkAddr: Network address of the target device (16-bit)
- endpoint: Endpoint number on the device (1-240)
- clusterID: Cluster ID containing the attribute
- attributeID: Attribute ID to configure
- dataType: ZCL 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 delta to trigger report (for analog), nil for discrete
Returns:
- An error if configuration fails
Notes:
- Use appropriate reportableChange values based on the attribute's precision
- For temperature in 0.01°C units: value 50 = 0.5°C change
- For discrete attributes (enums, booleans), use nil for reportableChange
- Some sleepy devices may not support reporting and will need polling
Example:
// Configure temperature sensor to report every 60-300s or on 0.5°C change
err := adapter.ConfigureReporting(ctx, 0x1234, 1, zcl.ClusterTempMeasurement,
zcl.AttrTempMeasuredValue, zcl.TypeInt16, 60, 300, int16(50)) // 50 = 0.5°C
if err != nil {
return fmt.Errorf("failed to configure reporting: %w", err)
}
func (*Adapter) CreateBackup ¶
CreateBackup creates a full backup of the adapter configuration.
func (*Adapter) DeleteDeviceName ¶
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 ¶
FactoryReset performs a factory reset, clearing all network configuration.
func (*Adapter) ForceRemoveDevice ¶
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 ¶
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 ¶
GetBindingTable retrieves the binding table from a device. This shows where the device will send reports for each cluster.
func (*Adapter) GetBrightness ¶
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 ¶
GetCoordinatorIEEE returns the coordinator's IEEE address.
func (*Adapter) GetCurrentChannel ¶
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) GetDeviceByNwkAddr ¶
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) GetDeviceHealth ¶ added in v0.2.0
GetDeviceHealth gets health info for a specific device.
func (*Adapter) GetDeviceName ¶
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 ¶
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 ¶
GetInfo returns comprehensive adapter information including version and capabilities.
func (*Adapter) GetLastSEMessage ¶
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 ¶
GetNeighborTable retrieves the neighbor table from a device. This shows which devices this node can directly communicate with.
func (*Adapter) GetNetworkHealth ¶ added in v0.2.0
func (a *Adapter) GetNetworkHealth(ctx context.Context) (*NetworkHealth, error)
GetNetworkHealth gathers comprehensive network health information. This queries all routers in the network and builds a topology map.
func (*Adapter) GetNetworkInfo ¶
func (a *Adapter) GetNetworkInfo(ctx context.Context) (*NetworkInfo, error)
GetNetworkInfo retrieves comprehensive network information.
func (*Adapter) GetOTAInfo ¶
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 ¶
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) GetRoutingTable ¶ added in v0.2.0
GetRoutingTable returns routing table from a device. Only routers and coordinators have routing tables; end devices will return an error.
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 ¶
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 ¶
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 ¶
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) GetZNP ¶ added in v0.3.0
GetZNP returns the underlying ZNP client. This provides access to the ZNP layer for advanced operations like listening for incoming messages. The returned ZNPClient is only valid while the adapter is open.
func (*Adapter) GroupRecallScene ¶
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 ¶
GroupToggle sends Toggle command to all devices in a group.
func (*Adapter) GroupTurnOff ¶
GroupTurnOff sends Off command to all devices in a group.
func (*Adapter) GroupTurnOn ¶
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 ¶
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) ListDeviceNames ¶
func (a *Adapter) ListDeviceNames(ctx context.Context) ([]DeviceNameInfo, error)
ListDeviceNames returns all devices with custom names.
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 ¶
Open opens the adapter and establishes communication with the Z-Stack coordinator.
This method performs the following initialization steps:
- Opens the serial port specified in SerialConfig
- Initializes the ZNP protocol layer
- Sends handshake pings to verify communication
- Retrieves version information from the adapter
- Registers coordinator endpoints for different profiles (HA, SE, GP, ZLL)
- Starts the Zigbee network from NV memory
- Sets up device event callbacks for join/leave notifications
The adapter must be opened before performing any device or network operations. Call Close() when done to release all resources.
If the network has not been configured, Open() will return an error indicating that FormNetwork() must be called first.
Example:
if err := adapter.Open(ctx); err != nil {
return fmt.Errorf("failed to open adapter: %w", err)
}
defer adapter.Close()
func (*Adapter) OpenWindowCovering ¶
OpenWindowCovering fully opens (raises) the covering. This sends the UpOpen command to the device.
func (*Adapter) PermitJoin ¶
PermitJoin opens or closes the network for device joining. duration: 0=close, 1-254=seconds, 255=always open
func (*Adapter) ReadAttributeBool ¶ added in v0.2.0
func (a *Adapter) ReadAttributeBool(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (bool, error)
ReadAttributeBool reads a single bool attribute from a device. Handles both native bool and uint8 representations (0 = false, non-zero = true). Returns an error if the attribute cannot be read or converted to bool.
func (*Adapter) ReadAttributeFloat32 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeFloat32(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (float32, error)
ReadAttributeFloat32 reads a single float32 attribute from a device. Returns an error if the attribute cannot be read or is not a float32.
func (*Adapter) ReadAttributeInt8 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeInt8(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (int8, error)
ReadAttributeInt8 reads a single int8 attribute from a device. Returns an error if the attribute cannot be read or converted to int8.
func (*Adapter) ReadAttributeInt16 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeInt16(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (int16, error)
ReadAttributeInt16 reads a single int16 attribute from a device. Returns an error if the attribute cannot be read or converted to int16.
func (*Adapter) ReadAttributeInt32 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeInt32(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (int32, error)
ReadAttributeInt32 reads a single int32 attribute from a device. Returns an error if the attribute cannot be read or converted to int32.
func (*Adapter) ReadAttributeString ¶ added in v0.2.0
func (a *Adapter) ReadAttributeString(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (string, error)
ReadAttributeString reads a single string attribute from a device. Returns an error if the attribute cannot be read or is not a string.
func (*Adapter) ReadAttributeUint8 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeUint8(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (uint8, error)
ReadAttributeUint8 reads a single uint8 attribute from a device. Returns an error if the attribute cannot be read or converted to uint8.
func (*Adapter) ReadAttributeUint16 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeUint16(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (uint16, error)
ReadAttributeUint16 reads a single uint16 attribute from a device. Returns an error if the attribute cannot be read or converted to uint16.
func (*Adapter) ReadAttributeUint32 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeUint32(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (uint32, error)
ReadAttributeUint32 reads a single uint32 attribute from a device. Returns an error if the attribute cannot be read or converted to uint32.
func (*Adapter) ReadAttributeUint48 ¶ added in v0.2.0
func (a *Adapter) ReadAttributeUint48(ctx context.Context, nwkAddr uint16, endpoint uint8, cluster zcl.ClusterID, attr zcl.AttributeID) (uint64, error)
ReadAttributeUint48 reads a single uint48 (as uint64) attribute from a device. Returns an error if the attribute cannot be read or converted to uint64.
func (*Adapter) ReadAttributes ¶
func (a *Adapter) ReadAttributes(ctx context.Context, nwkAddr uint16, endpoint uint8, clusterID zcl.ClusterID, attributeIDs ...zcl.AttributeID) ([]AttributeResult, error)
ReadAttributes reads one or more attributes from a device endpoint.
This method sends a ZCL read attributes request to the specified device and waits for the response. Multiple attributes can be requested in a single call to improve efficiency.
Parameters:
- ctx: Context for the operation (for cancellation/timeouts)
- nwkAddr: Network address of the target device (16-bit)
- endpoint: Endpoint number on the device (1-240)
- clusterID: Cluster ID containing the attributes
- attributeIDs: One or more attribute IDs to read
Returns:
- A slice of AttributeResult, one per requested attribute
- An error if the request fails
The returned results include the status, data type, and value for each attribute. If an attribute read fails, the status field will indicate the error (e.g., unsupported attribute, unauthorized read).
Example:
// Read OnOff attribute from a bulb
results, err := adapter.ReadAttributes(ctx, 0x1234, 1, zcl.ClusterOnOff, zcl.AttrOnOff)
if err != nil {
return err
}
for _, r := range results {
if r.Status == zcl.StatusSuccess && r.AttributeID == zcl.AttrOnOff {
isOn := r.Value.(bool)
fmt.Printf("Bulb is %s\n", map[bool]string{true: "on", false: "off"}[isOn])
}
}
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 ¶
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) 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 ¶
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 ¶
ResetAllAlarms clears all alarms from the device's alarm log. This removes all active alarm entries.
func (*Adapter) ResetEnergy ¶
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 ¶
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 ¶
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 ¶
SetDeviceName sets a custom name and comment for a device. Name is limited to 32 characters, comment 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) ToggleDoorLock ¶
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) 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 ¶
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)
Sensor Report Handling 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. WriteAttributes writes one or more attributes to a device endpoint.
This method sends a ZCL write attributes request to the specified device. Multiple attributes can be written in a single call for efficiency.
Parameters:
- ctx: Context for the operation (for cancellation/timeouts)
- nwkAddr: Network address of the target device (16-bit)
- endpoint: Endpoint number on the device (1-240)
- clusterID: Cluster ID containing the attributes
- values: Map of attribute ID to AttributeValue (value and type)
Returns:
- An error if any attribute write fails
All attributes in the request must be successfully written, or an error is returned. The response from the device indicates the status for each attribute write.
Example:
// Turn on a bulb and set brightness
values := map[zcl.AttributeID]zcl.AttributeValue{
zcl.AttrOnOff: {Type: zcl.TypeBoolean, Value: true},
zcl.AttrLevelCurrentLevel: {Type: zcl.TypeUint8, Value: uint8(200)},
}
if err := adapter.WriteAttributes(ctx, 0x1234, 1, zcl.ClusterOnOff, values); err != nil {
return err
}
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 zcl.Status
DataType zcl.DataType
Value interface{}
}
AttributeResult represents a single attribute read result.
func GetFirstResult ¶ added in v0.2.0
func GetFirstResult(results []AttributeResult) (*AttributeResult, error)
GetFirstResult returns the first successful attribute result, or an error. This is a helper for extracting and validating a single attribute 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 DefaultLogger ¶ added in v0.3.0
type DefaultLogger struct{}
DefaultLogger is a no-op logger that discards all log messages. This is used when no logger is configured.
func (*DefaultLogger) Debugf ¶ added in v0.3.0
func (l *DefaultLogger) Debugf(_ string, _ ...interface{})
func (*DefaultLogger) Errorf ¶ added in v0.3.0
func (l *DefaultLogger) Errorf(_ string, _ ...interface{})
func (*DefaultLogger) Infof ¶ added in v0.3.0
func (l *DefaultLogger) Infof(_ string, _ ...interface{})
func (*DefaultLogger) Warnf ¶ added in v0.3.0
func (l *DefaultLogger) Warnf(_ string, _ ...interface{})
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 ¶
IsBatteryPowered returns true if battery powered.
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 DeviceHealth ¶ added in v0.2.0
type DeviceHealth struct {
NwkAddr uint16
IEEEAddr [8]byte
LastSeen time.Time
LQI uint8
Depth uint8
NeighborCount int
RouteCount int
IsReachable bool
}
DeviceHealth contains health info for a single device.
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 ¶
DeviceNameInfo contains the custom name and comment for a device.
func (*DeviceNameInfo) IEEEAddrString ¶
func (d *DeviceNameInfo) IEEEAddrString() string
IEEEAddrString formats the IEEE address as a hex string. IEEE addresses are stored in little-endian format (low byte first in memory), but displayed in big-endian format (high byte first) for human readability.
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. IEEE addresses are stored in little-endian format (low byte first in memory), but displayed in big-endian format (high byte first) for human readability.
type Logger ¶ added in v0.3.0
type Logger interface {
// Debug logs a debug message.
Debugf(format string, args ...interface{})
// Info logs an informational message.
Infof(format string, args ...interface{})
// Warn logs a warning message.
Warnf(format string, args ...interface{})
// Error logs an error message.
Errorf(format string, args ...interface{})
}
Logger defines the logging interface used by the adapter. Implementations can be provided to control log output.
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 NetworkHealth ¶ added in v0.2.0
type NetworkHealth struct {
Timestamp time.Time
Channel uint8
PanID uint16
DeviceCount int
RouterCount int
EndDeviceCount int
AverageLQI uint8
MinLQI uint8
MaxLQI uint8
WeakLinks []WeakLink // LQI < 100.
Topology []TopologyNode
}
NetworkHealth contains overall network health metrics.
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 WithLogger ¶ added in v0.3.0
WithLogger sets the logger for adapter events and warnings. By default, a no-op logger is used which discards all logs.
func WithPingRetries ¶
WithPingRetries sets the number of ping retry attempts.
func WithPingTimeout ¶
WithPingTimeout sets the timeout for ping operations.
func WithRTSCTSFlow ¶
WithRTSCTSFlow enables or disables RTS/CTS hardware flow control.
func WithResetTimeout ¶
WithResetTimeout sets the timeout for reset operations.
func WithSerialPath ¶
WithSerialPath sets the serial port path.
func WithZCLRetryAttempts ¶ added in v0.3.0
WithZCLRetryAttempts sets the number of retry attempts for ZCL requests. The value is the number of retries (additional attempts after the initial attempt). For example, 3 means: initial attempt + 3 retries = 4 total attempts. Default is 0 (no retry).
func WithZCLRetryDelay ¶ added in v0.3.0
WithZCLRetryDelay sets the initial delay before the first ZCL retry. Subsequent retries use exponential backoff (delay, 2x delay, 4x delay, etc.). Default is 100ms.
func WithZDOInitDelay ¶ added in v0.3.0
WithZDOInitDelay sets the delay after StartupFromApp to allow ZDO layer initialization. Default is 200ms. Set to 0 to disable the delay if you're sure initialization is not needed.
type Options ¶
type Options struct {
SerialConfig serial.Config
PingRetries int
PingTimeout time.Duration
ResetTimeout time.Duration
ZDOInitDelay time.Duration // Delay after StartupFromApp to allow ZDO layer initialization
Logger Logger // Logger for adapter events and warnings
ZCLRetryAttempts int // Number of retry attempts for ZCL requests (excluding initial attempt)
ZCLRetryDelay time.Duration // Initial delay before first retry, with exponential backoff
}
Options configures the adapter.
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 zcl.Status
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 RoutingInfo ¶ added in v0.2.0
type RoutingInfo struct {
DstAddr uint16
Status uint8 // 0=Active, 1=Discovery, 2=Failed, 3=Inactive, 4=Validation.
NextHop uint16
Concentrator bool
RouteRecord bool
ManyToOne bool
}
RoutingInfo contains routing table information from a device.
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 canceled).
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 zcl.Status // 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 SlogLogger ¶ added in v0.3.0
type SlogLogger struct {
// contains filtered or unexported fields
}
SlogLogger adapts a log/slog.Logger to the Logger interface. This allows using Go's standard structured logging with the adapter:
adapter.New(adapter.WithLogger(adapter.NewSlogLogger(slog.Default())))
func NewSlogLogger ¶ added in v0.3.0
func NewSlogLogger(logger *slog.Logger) *SlogLogger
NewSlogLogger creates a Logger that delegates to the given slog.Logger. If logger is nil, slog.Default is used.
func (*SlogLogger) Debugf ¶ added in v0.3.0
func (l *SlogLogger) Debugf(format string, args ...any)
func (*SlogLogger) Errorf ¶ added in v0.3.0
func (l *SlogLogger) Errorf(format string, args ...any)
func (*SlogLogger) Infof ¶ added in v0.3.0
func (l *SlogLogger) Infof(format string, args ...any)
func (*SlogLogger) Warnf ¶ added in v0.3.0
func (l *SlogLogger) Warnf(format string, args ...any)
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 TopologyNode ¶ added in v0.2.0
type TopologyNode struct {
NwkAddr uint16
IEEEAddr [8]byte
DeviceType uint8 // 0=Coordinator, 1=Router, 2=EndDevice.
ParentAddr uint16 // Network address of parent.
Depth uint8
LQI uint8 // LQI to parent.
Children []uint16
}
TopologyNode represents a device in the network topology.
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.
type ZNPClient ¶ added in v0.2.0
type ZNPClient interface {
// Lifecycle methods manage the ZNP connection lifecycle.
Open(ctx context.Context) error
Close() error
// System commands query basic coordinator information and perform resets.
Ping(ctx context.Context) (*znp.PingCapabilities, error)
Version(ctx context.Context) (*znp.VersionInfo, error)
Reset(ctx context.Context, resetType znp.ResetType) (*znp.ResetIndication, error)
GetDeviceInfo(ctx context.Context) (*znp.DeviceInfo, error)
StartupFromApp(ctx context.Context, startDelay uint16) (uint8, error)
SetTxPower(ctx context.Context, power int8) (int8, error)
// Network management configures and monitors network state.
ExtNwkInfo(ctx context.Context) (*znp.ExtNetworkInfo, error)
BdbSetChannel(ctx context.Context, isPrimary bool, channel uint32) (uint8, error)
BdbStartCommissioning(ctx context.Context, mode znp.BdbCommissioningMode) (uint8, error)
WaitForStateChange(ctx context.Context, timeout time.Duration) (znp.DevState, error)
// AF (Application Framework) layer manages endpoints and data transmission.
AfRegister(ctx context.Context, config znp.EndpointConfig) (uint8, error)
AfDelete(ctx context.Context, endpoint uint8) (uint8, error)
AfDataRequest(ctx context.Context, req znp.DataRequest) (uint8, error)
WaitForDataConfirm(ctx context.Context, transID uint8, timeout time.Duration) (*znp.DataConfirm, error)
WaitForIncomingMsg(ctx context.Context, srcAddr uint16, clusterID uint16, timeout time.Duration) (*znp.IncomingMessage, error)
// ZDO (Zigbee Device Objects) commands perform device discovery and management.
MgmtPermitJoinReq(ctx context.Context, duration uint8) (uint8, error)
MgmtLeaveReq(ctx context.Context, dstAddr uint16, ieeeAddr [8]byte, removeChildren, rejoin bool) (uint8, error)
MgmtNwkUpdateReq(ctx context.Context, dstAddr uint16, dstAddrMode uint8, channelMask uint32, scanDuration uint8, scanCount uint8, nwkManagerAddr uint16) (uint8, error)
ActiveEpReq(ctx context.Context, dstAddr uint16) (*znp.ActiveEndpoints, error)
SimpleDescReq(ctx context.Context, dstAddr uint16, endpoint uint8) (*znp.SimpleDescriptor, error)
NodeDescReq(ctx context.Context, dstAddr uint16) (*znp.NodeDescriptor, error)
IeeeAddrReq(ctx context.Context, nwkAddr uint16) ([8]byte, error)
BindReq(ctx context.Context, dstAddr uint16, srcIEEEAddr [8]byte, srcEndpoint uint8, clusterID uint16, dstIEEEAddr [8]byte, dstEndpoint uint8) (uint8, error)
UnbindReq(ctx context.Context, dstAddr uint16, srcIEEEAddr [8]byte, srcEndpoint uint8, clusterID uint16, dstIEEEAddr [8]byte, dstEndpoint uint8) (uint8, error)
// Network topology queries retrieve neighbor, routing, and binding tables.
GetAllNeighbors(ctx context.Context, dstAddr uint16) ([]znp.NeighborEntry, error)
GetAllBindings(ctx context.Context, dstAddr uint16) ([]znp.BindingEntry, error)
GetAllRoutes(ctx context.Context, dstAddr uint16) ([]znp.RoutingEntry, error)
// NVRAM operations provide persistent storage access.
NvLength(ctx context.Context, id znp.NvItemID) (uint16, error)
NvRead(ctx context.Context, id znp.NvItemID, offset uint8) ([]byte, error)
NvWrite(ctx context.Context, id znp.NvItemID, offset uint8, data []byte) error
NvReadAll(ctx context.Context, id znp.NvItemID) ([]byte, error)
NvWriteAll(ctx context.Context, id znp.NvItemID, data []byte) error
NvItemInit(ctx context.Context, id znp.NvItemID, itemLen uint16, initData []byte) error
// Address Manager operations manage the coordinator's device table.
ReadAddrMgrTable(ctx context.Context) ([]znp.AddrMgrEntry, error)
DeleteAddrMgrEntry(ctx context.Context, ieeeAddr [8]byte) (bool, error)
// Device name operations provide human-readable device naming.
SetDeviceName(ctx context.Context, ieeeAddr [8]byte, name, comment string) error
GetDeviceName(ctx context.Context, ieeeAddr [8]byte) (*znp.DeviceNameEntry, error)
DeleteDeviceName(ctx context.Context, ieeeAddr [8]byte) error
ReadDeviceNameTable(ctx context.Context) (*znp.DeviceNameTable, error)
// Event callbacks register handlers for asynchronous device events.
OnDeviceJoin(handler func(*znp.TcDeviceInd))
OnDeviceLeave(handler func(*znp.DeviceLeave))
OnDeviceAnnounce(handler func(*znp.DeviceAnnounce))
}
ZNPClient defines the interface for interacting with the Z-Stack ZNP layer. This interface enables mocking the ZNP layer in tests, allowing unit tests of the adapter package without requiring a physical Zigbee coordinator.
The *znp.ZNP type implements this interface, so existing code using *znp.ZNP can seamlessly switch to using this interface type instead.
Source Files
¶
- adapter.go
- attributes.go
- backup.go
- constants.go
- device.go
- device_names.go
- diagnostics.go
- doc.go
- endpoints.go
- errors.go
- interview.go
- logger.go
- messaging.go
- messaging_basic.go
- messaging_color.go
- messaging_core.go
- messaging_groups.go
- messaging_hvac.go
- messaging_identify.go
- messaging_io.go
- messaging_level.go
- messaging_onoff.go
- messaging_power.go
- messaging_security.go
- messaging_sensors.go
- messaging_time.go
- network.go
- network_mgmt.go
- options.go
- validation.go
- znp_interface.go