ZigBee

ZigBee library #

Load the library:

local zb = require('applibs.zigbee')

Library functions #

step() #

Waits for a single message sent from/to ZigBee.

Returns the received message or nil plus an error message on timeout.


loop(timeout, callback) #

Reads messages for up to timeout seconds.

Optional callback function is executed for each received message.


addcallback(address, callback) #

Adds a callback function for all messages sent from the given address. address is a device IEEE address (string, 64-bit identifier in a lowercase hexadecimal form). See below for message structure explanation.


cmd(fnname, address, ...) #

cmdep(fnname, address, endpoint, ...) #

Sends a single command message to the given address/group. address must be either a device IEEE address (string, 64-bit identifier in a lowercase hexadecimal form) or a group (number, between 1 and 65535).

cmdep allows passing the endpoint number directly.

cmd uses the first endpoint that contains the required cluster.

Additional arguments can be passed depending on the command.


cmdsync(fnname, address, ...) #

cmdepsync(fnname, address, endpoint, ...) #

Similar to cmd and cmdep but waits for a reply.

Default timeout is 20 seconds, it can be changed by setting the cmdtimeout variable.

Returns the command result or nil plus an error message in case of an error.


Available commands #

Arguments should be passed to the function in the same order as documented. See examples below.


getcolortemp #

Retrieve color temperature. Returns a table with the following fields:

  • ctemp_min - minimum supported color temperature
  • ctemp_max - maximum supported color temperature
  • ctemp - current color temperature

getlevel #

Retrieve current level. Returns a number with the current level from 0 to 254.


getonoff #

Retrieve On/Off status. Returns a Boolean with the current On/Off status.


getxy #

Retrieve color space coordinates. Returns a table with the following fields:

  • x - color space X coordinate
  • y - color space Y coordinate

identify #

Start/stop device identification.

Arguments:

  • time (number, default: 5) - identification time in seconds, set to 0 to stop the procedure

setonoff #

Arguments:

  • cmd (string) - command to send, either Off, On or Toggle

setlevel #

Set light level.

Arguments:

  • level (number) - light level between 0 and 254, note that some devices treat level 1 as Off
  • transition (number, default: 1) - transition time in seconds

setlevelup #

setleveldown #

Move the light level up/down at a given rate.

Arguments:

  • rate (number, default: 51) - light level change rate per second, full range is from 0 to 254

setlevelstop #

Stop the light level change.


setcolortemp #

Set color temperature.

Arguments:

  • kelvin (number, default: 3000) - color temperature in Kelvin
  • transition (number, default: 1) - transition time in seconds

setrgb #

Set RGB color value.

This function calculates the required level and XY coordinates from the given RGB color values. Each color value must be a number between 0 and 255.

Arguments:

  • red (number) - red color value
  • green (number) - blue color value
  • blue (number) - blue color value
  • transition (number, default: 1) - transition time in seconds, only applies to the color transition but not the light level transition

setxy #

Set color space coordinates.

Both coordinates must be a number between 0 and 65534.

Arguments:

  • x (number) - color space X coordinate
  • y (number) - color space Y coordinate
  • transition (number, default: 1) - transition time in seconds

sethuesat #

Set hue and saturation.

Both hue and saturation must be a number between 0 and 254.

Arguments:

  • hue (number) - color hue value
  • saturation (number) - color saturation value
  • transition (number, default: 1) - transition time in seconds

setdoor #

Lock/unlock a door.

Arguments:

  • cmd (string) - command name, either LockDoor, UnlockDoor, ToggleDoor or UnlockWithTimeout
  • pincode (string, default: empty string) - door PIN code
  • timeout (number) - lock the door after timeout seconds, only for the UnlockWithTimeout command

getnamedattribute #

Returns a given named attribute value or nil plus an error message if the operation failed.

Arguments:

  • cluster (string or number) - cluster name or id
  • attr (string) - attribute name
  • manufcode (number, optional) - manufacturer code, only for manufacturer-specific attributes

setnamedattribute #

Sets a given named attribute value. Returns the operation result or nil plus an error message if it failed.

Arguments:

  • cluster (string or number) - cluster name or id
  • attr (string) - attribute name
  • value (mixed) - attribute value
  • manufcode (number, optional) - manufacturer code, only for manufacturer-specific attributes

getrawattribute #

Returns a given attribute value or nil plus an error message if the operation failed.

Arguments:

  • cluster (string or number) - cluster name or id
  • attr (number) - attribute id
  • manufcode (number, optional) - manufacturer code, only for manufacturer-specific attributes

setrawattribute #

Sets a given attribute value. Returns the operation result or nil plus an error message if it failed.

Arguments:

  • cluster (string or number) - cluster name or id
  • attr (number) - attribute id
  • value (mixed) - attribute value
  • dtype (string) - data type name
  • manufcode (number, optional) - manufacturer code, only for manufacturer-specific attributes

Examples #

Get device attribute #

Get StartUpCurrentLevel attribute from LevelCtrl cluster from a device with address 0123456789abcdef.

zb = require('applibs.zigbee')

res, err = zb.cmdsync('getnamedattribute', '0123456789abcdef', 'LevelCtrl', 'StartUpCurrentLevel')
log(res, err)

Set device attribute #

Set StartUpCurrentLevel attribute from LevelCtrl cluster from a device with address 0123456789abcdef to current event value (0..255).

zb = require('applibs.zigbee')

value = event.getvalue() -- 0..254 = fixed level, 255 = last level

res, err = zb.cmdsync('setnamedattribute', 'cc86ecfffe728382', 'LevelCtrl', 'StartUpCurrentLevel', value)
log(res, err)

Resident script for monitoring several devices #

Sleep time set to 0. Devices with addresses 0123456789abcdef and abcdef0123456789 are monitored.

if not zb then
  zb = require('applibs.zigbee')

  zb.addcallback('0123456789abcdef', function(msg)
    log(msg)
  end)

  zb.addcallback('abcdef0123456789', function(msg)
    log(msg)
  end)
end

zb.loop(1)

Sending commands and reading status responses #

zb = require('applibs.zigbee')

-- toggle device 0123456789abcdef on/off
zb.cmd('setonoff', '0123456789abcdef', 'Toggle')

-- set RGB to (255, 127, 0) for device abcdef0123456789, endpoint 4
endpoint = 4
red = 255
green = 127
blue = 0
zb.cmdep('setrgb', 'abcdef0123456789', endpoint, red, green blue)

-- set level to 100 for group 123
group = 123
level = 100
zb.cmd('setlevel', group, level)

-- get current color temperature of device 0123456789abcdef
res, err = zb.cmdsync('getcolortemp', '0123456789abcdef')
log(res, err)

-- get current level of device 0123456789abcdef, endpoint 5
endpoint = 5
res, err = zb.cmdepsync('getlevel', '0123456789abcdef', endpoint)
log(res, err)

Message table structure #

  • direction (string) - message direction, RX is from ZigBee network, TX is to ZigBee network

The following fields are mostly applicable to messages from ZigBee network:

  • linkquality (number) - signal quality level from 0 (lowest) to 255 (highest)
  • srcep (number) - source endpoint number
  • from (string) - device IEEE address
  • group (number) - group number, 0 means no group
  • cluster (number) - cluster type in a numeric form
  • clustername (string) - cluster name, if available
  • clusterdata (table) - cluster data extracted from the whole message, if available
  • attributes (table) - reported attributes in name → value form, if available
  • data (table) - whole message data

Attribute table example #

The following attributes are sent from a security device like a door/window sensor. detection field is true when a door/window is opened.

attributes = {
  detection = true,
  batterylow = false,
  tamper = false
}

Cluster data example #

The following data is sent for an On command:

clusterdata = {
  CommandIdentifier = 'On'
}

The following data is sent for a Move command with Down direction with a rate of 38 per second:

clusterdata = {
  CommandIdentifier = 'Move',
  Move = {
    MoveMode = 'Down',
    Rate = 38
  }
}

Cluster / attribute list #

Cluster / Attribute ID Data type
Basic 0
ZCLVersion 0 uint8
HwVersion 3 uint8
ManufacturerName 4 string
ModelId 5 string
SwBuildId 16384 string
SeFirmwareVersion 57345 string
PowerCfg 1
BatteryVoltage 32 uint8
BatteryLevel 33 uint8
OnOff 6
OnOff 0 bool
LevelCtrl 8
CurrentLevel 0 uint8
OnOffTransitionTime 16 uint16
OnLevel 17 uint8
StartUpCurrentLevel 16384 uint8
AnalogInput 12
Description 28 string
MaxPresentValue 65 single
MinPresentValue 69 single
OutOfService 81 bool
PresentValue 85 single
Reliability 103 enum8
RelinquishDefault 104 single
Resolution 106 single
BinaryInput 15
PresentValue 85 bool
Ota 25
UpgradeServerId 0 EUI64
FileOffset 1 uint32
CurrentFileVersion 2 uint32
CurrentZigbeeStackVersion 3 uint16
DownloadedFileVersion 4 uint32
DownloadedZigbeeStackVersion 5 uint16
ImageUpgradeStatus 6 enum8
ManufacturerCode 7 uint16
ImageType 8 uint16
MinimumBlockReqDelay 9 uint16
ImageStamp 10 uint32
ClosuresDoorLock 257
LockState 0 enum8
LockType 1 enum8
ActuatorEnabled 2 bool
DoorState 3 enum8
ClosuresWindowCovering 258
WindowCoveringType 0 enum8
PhysicalClosedLimitLift 1 uint16
PhysicalClosedLimitTilt 2 uint16
CurrentPositionLift 3 uint16
CurrentPositionTilt 4 uint16
NumberOfActuationsLift 5 uint16
NumberOfActuationsTilt 6 uint16
ConfigStatus 7 map8
CurrentPositionLiftPercentage 8 uint8
CurrentPositionTiltPercentage 9 uint8
Mode 23 map8
LiftDriveUpTime 57364 uint16
LiftDriveDownTime 57365 uint16
TiltOpenCloseAndStepTime 57366 uint16
TiltPositionPercentageAfterMoveToLevel 57367 uint8
HvacThermostat 513
LocalTemperature 0 int16
OutdoorTemperature 1 int16
Occupancy 2 map8
AbsMinHeatSetpointLimit 3 int16
AbsMaxHeatSetpointLimit 4 int16
AbsMinCoolSetpointLimit 5 int16
AbsMaxCoolSetpointLimit 6 int16
PICoolingDemand 7 uint8
PIHeatingDemand 8 uint8
HVACSystemTypeConfiguration 9 map8
LocalTemperatureCalibration 16 int8
OccupiedCoolingSetpoint 17 int16
OccupiedHeatingSetpoint 18 int16
UnoccupiedCoolingSetpoint 19 int16
UnoccupiedHeatingSetpoint 20 int16
MinHeatSetpointLimit 21 int16
MaxHeatSetpointLimit 22 int16
MinCoolSetpointLimit 23 int16
MaxCoolSetpointLimit 24 int16
MinSetpointDeadBand 25 int8
RemoteSensing 26 map8
ControlSequenceOfOperation 27 enum8
SystemMode 28 enum8
AlarmMask 29 map8
ThermostatRunningMode 30 enum8
BoschSystemMode 16391 enum8
BoschPIHeatingDemand 16416 enum8
BoschWindowOpen 16450 enum8
BoschBoost 16450 enum8
SEOpenWindowStatus 57362 uint8
SEOpenWindowThreshold 57363 uint8
SEOpenWindowEventDuration 57364 uint16
SEOpenWindowGuardPeriod 57365 uint16
HvacFanCtrl 514
FanMode 0 enum8
FanModeSequence 1 enum8
LightingColorCtrl 768
CurrentHue 0 uint8
CurrentSaturation 1 uint8
RemainingTime 2 uint16
CurrentX 3 uint16
CurrentY 4 uint16
ColorTemperature 7 uint16
ColorMode 8 enum8
EnhancedCurrentHue 16384 uint16
EnhancedColorMode 16385 enum8
ColorCapabilities 16394 uint16
ColorTempPhysicalMin 16395 uint16
ColorTempPhysicalMax 16396 uint16
LightingBallastCfg 769
PhysicalMinLevel 0 uint8
PhysicalMaxLevel 1 uint8
MinLevel 16 uint8
MaxLevel 17 uint8
ControlMode 57344 enum8
MsIlluminanceMeasurement 1024
MeasuredValue 0 uint16
MsTemperatureMeasurement 1026
MeasuredValue 0 int16
TemperatureSensorType 57377 enum8
MsPressureMeasurement 1027
MeasuredValue 0 int16
MsFlowMeasurement 1028
MeasuredValue 0 uint16
MsRelativeHumidity 1029
MeasuredValue 0 uint16
MsOccupancySensing 1030
Occupancy 0 map8
OccupancySensorType 1 enum8
PirOToUDelay 16 uint16
OccupancyDfltOperationMode 57344 enum8
MsCO2 1037
MeasuredValue 0 single
MsPM25 1066
MeasuredValue 0 single
SsIasZone 1280
ZoneState 0 enum8
ZoneType 1 enum16
ZoneStatus 2 map16
IasCieAddr 16 EUI64
ZoneId 17 uint8
ZoneSensitivityLevel 19 uint8
DetectionTimeout 57345 uint16
SeMetering 1794
CurrentSummDelivered 0 uint48
CurrentSummReceived 1 uint48
SePowerMultiplier 769 uint24
SePowerDivisor 770 uint24
SeActivePower 1024 int24
HaElectricalMeasurement 2820
RmsVoltage 1285 uint16
RmsCurrent 1288 uint16
HaActivePower 1291 int16
HaReactivePower 1294 int16
HaApparentPower 1295 uint16
PowerFactor 1296 int8
VoltageMultiplier 1536 uint16
VoltageDivisor 1537 uint16
CurrentMultiplier 1538 uint16
CurrentDivisor 1539 uint16
HaPowerMultiplier 1540 uint16
HaPowerDivisor 1541 uint16
RmsVoltagePhB 2309 uint16
RmsCurrentPhB 2312 uint16
HaActivePowerPhB 2315 int16
HaReactivePowerPhB 2318 int16
HaApparentPowerPhB 2319 uint16
RmsVoltagePhC 2565 uint16
RmsCurrentPhC 2568 uint16
HaActivePowerPhC 2571 int16
HaReactivePowerPhC 2574 int16
HaApparentPowerPhC 2575 uint16
ManuSpecificDevelcoVOC 64515
MeasuredValue 0 uint16
ManuSpecificSEAvatar 64516
IndicatorLevel 0 uint8
IndicatorColor 1 uint8
SwitchIndication 2 uint8
MotorTypeChannel1 3 uint8
MotorTypeChannel2 4 uint8
CurtainStatusChannel1 5 uint8
CurtainStatusChannel2 6 uint8
KeyConfig1 16 uint8
KeyConfig2 17 uint8
KeyConfig3 18 uint8
KeyConfig4 19 uint8
KeyEvent1 32 uint8
KeyEvent2 33 uint8
KeyEvent3 34 uint8
KeyEvent4 35 uint8
KeyGroup1 48 uint16
KeyGroup2 49 uint16
KeyGroup3 50 uint16
KeyGroup4 51 uint16
KeyScene1 64 uint8
KeyScene2 65 uint8
KeyScene3 66 uint8
KeyScene4 67 uint8
ManuSpecificIkeaVOC 64638
MeasuredValue 0 single
MeasuredValueMin 1 single
MeasuredValueMax 2 single
ManuSpecificWiserEvent 65027
Event 32 string
ManuSpecificCycleTime 65302
DemandPercentage 0 uint8
CycleTime 16 uint16
DegradedModeDemandPercentage 48 uint8
ManuSpecificSESwitch 65303
SwitchIndication 0 enum8
SwitchAction 1 enum8
UpScene 16 uint8
UpGroup 17 uint16
DownScene 32 uint8
DownGroup 33 uint16
MenuSpecificSEOccupancy 65305
AmbienceLightThreshold 0 uint16
OccupancyAction 1 enum8
UnoccupiedLevelDflt 2 uint8
UnoccupiedLevel 3 uint8
ManuSpecificHeatingCooling 65315
HeatingOutputMode 49 enum8
MinOffTime 68 uint16
MinOnTime 69 uint16
FallbackTimeout 57856 uint16
FallbackHeatingDemand 57857 uint8