Chapter 8
ZigApi application programming interface
This chapter explains in details of the application programming interface of ZigApi. In order to avoid name conflicts, all the names are included in the global namespace ZigApi.
8.1 Network
A Network object represents a ZigBee network, manages the connection with the gateway and the list of connected devices. It realizes the CIL[4] standard IDisposable interface.
8.1.1 Constructor
public Network(Network.Initializer initializer);
Creates a new Network object with the specified initialization parameters.
The Network.Initializer structure has the following fields:
52
8.1. Network 53
IPAddress GatewayAddress;
ushort GatewayPort;
Gateway IP address and port.
IPAddress MyAddress;
The IP address of the application, needed by gateway connection.
bool AcceptAnnouncements;
True if the network will accept asynchronous device announcements. If this parameter is false, the list of connected devices can change only after Connect, Disconnect, Inquiry and LeaveDevice operations.
AnnouncementDelegate AnnouncementCallback;
A handler function that ZigApi will call everytime an asynchronous an- nouncement is received. Put null for disabling the callback. If AcceptAn- nouncements is false, this parameter is not significant.
bool AcceptAttrReports;
True if the devices on the network will accept asynchronous attributes reports. If this parameter is false, the stored value of the attributes can chage only after ReadAttr, ReadAllAttr and WriteAttr.
AsyncExceptionThrownDelegate AsyncExceptionThrownCallback;
A handler function that ZigApi will call everytime an exception is thrown in code that is asynchronous from the programmer’s code. For example a gateway communication error inside an asynchronous announcement. Put null for disabling the callback.
bool LogConcurrency;
If true, ZigApi will log on the standard output all the concurrency-related operations. This is used for testing purposes only.
Signatures of the used delegates:
8.1. Network 54
public delegate void AnnouncementDelegate(Device device);
public delegate void AsyncExceptionThrownDelegate(
Exception exc);
The parameters are self-explanatory.
8.1.2 Default constructor
public Network();
Creates a new Network object with the default initialization parameters.
The default initialization parameters are the following.
GatewayAddress = IPAddress.Loopback, GatewayPort = 9000,
MyAddress = IPAddress.Loopback, AcceptAnnouncements = false, AnnouncementCallback = null, AcceptAttrReports = false,
AsyncExceptionThrownCallback = null, LogConcurrency = false,
Be careful that asynchronous device announcements and attribute reports are disabled by default. Programmer has eventually to enable these features in the Network object constructor.
8.1.3 Dispose method and destructor
8.1. Network 55
public void Dispose();
Destroys the Network object and the managed objects. If still connected, it closes the connection with the gateway.
~Network();
Destroys the Network object. If still connected, it closes the connection with the gateway.
8.1.4 Miscellaneous properties
public IPAddress GatewayAddress;
Gets or sets the IP address where the Network object will search the gate- way during connection.
Exceptions thrown:
System.InvalidOperationException
Attempting to write this property while the gateway connection is up.
public ushort GatewayPort;
Gets or sets the TCP port where the Network object will search the gateway during connection.
Exceptions thrown:
System.InvalidOperationException
Attempting to write this property while the gateway connection is up.
8.1. Network 56
public IPAddress MyAddress;
Gets or sets the IP address of the application.
Exceptions thrown:
System.InvalidOperationException
Attempting to write this property while the gateway connection is up.
8.1.5 Registering custom devices
public void RegisterCustomDeviceType(
string name, ushort profileId, ushort deviceId,
string virtualDeviceModelIdentifier, CustomDeviceConstructor constructor);
Registers a custom device type. This method is used for external extensi- bility. See section 9.6 for further informations.
Exceptions thrown:
System.InvalidOperationException
The gateway connection is estabilished, or a device type with this name is already registered, or a device type with this profileId/deviceId is already registered.
This operation must be performed before connecting to the gateway.
• name: the name of the custom device type.
• profileId: the profile identifier of the custom device type.
• deviceId: the ZigBee device identifier of the custom device type.
• virtualDeviceModelIdentifier: the value of the ModelIdentifier attribute
(of Basic Cluster) that a virtual device of this type will return. It’s only
8.1. Network 57
needed with custom virtual devices, in order to detect their type (see section 9.2).
• constructor: a function that creates a device object of this custom type.
The CustomDeviceConstructor signature is the following.
public delegate Device CustomDeviceConstructor(
Device.Initializer initializer);
8.1.6 Connect, inquiry and disconnect operations
public void Connect(int timeOut);
Connects to the gateway and performs an inquiry operation (searching for reachable devices).
Exceptions thrown:
System.InvalidOperationException
The calling thread owns the freeze on the network, or the gateway connec- tion is already on.
ZigApi.GatewayCommunicationException
Gateway is unreachable or a communication error with it has occurred.
ZigApi.ZclException
Only if virtual devices are connected to the network. A ZCL protocol error has occurred while determining the type of a virtual device.
ZigApi.ZigApiTimeoutException
Only if virtual devices are connected to the network. A virtual device has
not responded while determining its type.
8.1. Network 58
The application will be a ZigBee coordinator, so GAL has to run in “coordina- tor” mode. After connecting to gateway, ZigApi automatically orders an inquiry operation and blocks for timeOut milliseconds in order to receive the inquiry responses. If an inquiry response arrives after the time-out, it’s considered an asynchronous announcement. If timeOut is 0 the function doesn’t block, and the eventual inquiry responses are all considered asynchronous announcements.
This function always generates ZigBee traffic.
Connect operation has three possible results.
1. Success. The connect and the following inquiry operations are performed without errors. Effects: no exceptions are thrown, the gateway connection is up, some devices could be connected.
2. Successful connection and error during inquiry. The gateway connection is estabilished, but an error occurs during the inquiry operation. Effects:
an exception is thrown, the gateway connection is up, some devices could be connected.
3. Error on connection. The gateway connection is not estabilished. Effects:
an exception is thrown, the gateway connection is down, no connected devices.
public void Inquiry(int timeOut);
Performs an inquiry operation (searching for new reachable devices).
Exceptions thrown:
System.InvalidOperationException
The calling thread owns the freeze on the network, or the gateway connec- tion is off.
ZigApi.GatewayCommunicationException
Gateway is unreachable or a communication error with it has occurred.
ZigApi.ZclException
8.1. Network 59
Only if virtual devices are connected to the network. A ZCL protocol error has occurred while determining the type of a virtual device.
ZigApi.ZigApiTimeoutException
Only if virtual devices are connected to the network. A virtual device has not responded while determining its type.
ZigApi orders an inquiry operation and blocks for timeOut milliseconds in order to receive the inquiry responses. If an inquiry response arrives after the time-out, it’s considered an asynchronous announcement. If timeOut is 0 the function doesn’t block, and the eventual inquiry responses are all considered asynchronous announcements. This function always generates ZigBee traffic.
Devices that don’t reply to the inquiry are not removed from the list. As a matter of fact, device list can only be grown after this operation.
Inquiry operation has two possible results.
1. Success. The inquiry operation has been performed without errors. Effects:
no exceptions are thrown, some new devices could be connected.
2. Error during inquiry. An error has occurred during the inquiry operation.
Effects: an exception is thrown, but some new devices could be connected anyway.
public void Disconnect();
Disconnects from the gateway. This command doesn’t produces ZigBee traffic. If the gateway connection is already off, it does nothing.
Exceptions thrown:
System.InvalidOperationException
The calling thread owns the freeze on the network.
8.1. Network 60
bool IsConnected;
Returns true if the Network object is connected with the gateway.
8.1.7 Leave device
public void LeaveDevice(string longAddress);
Orders a device to leave the network. The ZigBee Leave message is not yet implemented by the GAL, so this function puts out the device from the network only logically, and doesn’t inform the device about it. A successive inquiry operation will detect the device, and it will be part of the network again.
Exceptions thrown:
System.InvalidOperationException
The calling thread owns the freeze on the network, or gateway connection is not estabilished.
8.1.8 Retrieving a Device object
public DeviceCollection Devices;
Gets the devices currently connected to the network.
public Device DeviceAt(int index);
Returns the device object at index position in the network. The order of the devices in the network is the order followed by the foreach statement on Devices.
Exceptions thrown:
8.1. Network 61
System.InvalidOperationException The gateway connection is off.
System.IndexOutOfRangeException No such device exists.
public Device DeviceAt(string longAddress);
Returns the device with longAddress address.
Exceptions thrown:
System.InvalidOperationException The gateway connection is off.
System.Collections.Generic.KeyNotFoundException No such device exists.
8.1.9 Broadcast device group
public readonly DeviceGroup BroadcastGroup;
The broadcast device group of this network.
See section 8.2 for further information about device groups.
8.1.10 Locking methods
There are three possible locks of the network:
1. Freeze (or read lock ). Excludes other write locks.
2. FreezeToChange (or upgradeable read lock ). Excludes other write locks and
upgradeable read locks.
8.1. Network 62
3. Lock (or write lock ). Excludes other write locks, upgradeable read locks and write locks.
Some operations on Network object automatically lock the network at the beginning of their execution and release the lock at the end. The following list shows which operation asks which type of lock.
• Connect, Disconnect, Inquiry → Lock.
• LeaveDevice → Lock.
• Devices, DeviceAt → Freeze.
• Getting of properties GatewayAddress, GatewayPort, MyAddress, IsCon- nected → Freeze.
• Setting of properties GatewayAddress, GatewayPort, MyAddress → Lock.
• Any Device object’s operation that generates ZigBee traffic → Freeze.
Besides, the programmer can manually ask and release the locks with dedi- cated methods.
public void Freeze();
Gets the read lock on the network.
public void Unfreeze();
Releases a read lock on the network, previously got with Freeze.
Exceptions thrown:
System.Threading.SynchronizationLockException
The current thread wasn’t holding the read lock.
8.1. Network 63
public bool IsFreezeHeld;
Returns true if the current thread is owning the read lock.
Until the current thread is holding the read lock, the network will be protec- ted against disconnections, connections and device list changes. While holding the read lock, write operations (Disconnect, Inquiry, LeaveDevice, ecc.) throw an exception if called from the locking thread, or they are blocked if called from another thread. The table in figure 8.1 shows which operations are allo- wed and which are not for the different locks. The Unfreeze method has to be invoked by the same thread that invoked Freeze method. The Freeze can be nested, meaning that a thread already holding the read lock can call Freeze another time. After that, it must call Unfreeze twice to effectively release the lock. Table in figure 8.2 shows which combinations of nested locks are possible.
public void FreezeToChange();
Gets the lock of the network in read mode, upgradeable to write mode.
Exceptions thrown:
System.Threading.LockRecursionException
The current thread was holding a read lock (got with Freeze).
public void UnfreezeToChange();
Releases the upgradeable read mode on the network, previously got with FreezeToChange.
Exceptions thrown:
System.Threading.SynchronizationLockException
The current thread wasn’t holding the upgradeable read lock.
8.1. Network 64
public bool IsFreezeToChangeHeld;
Returns true if the current thread is owning the upgradeable read lock.
Until the current thread call UnfreezeToChange, the network will be protec- ted against disconnections, connections, device list changes and other FreezeTo- Change operations. The table in figure 8.1 shows which operations are allowed and which are not for the different locks. The UnfreezeToChange method has to be invoked by the same thread that invoked FreezeToChange method. The FreezeToChange can be nested, meaning that a thread already holding the up- gradeable read lock can call FreezeToChange another time. After that, it must call UnfreezeToChange twice to effectively release the lock. Table in figure 8.2 shows which combinations of nested locks are possible.
In order to upgrade to write lock, a Lock method must be called. Successive Unlock method call will downgrade in upgradeable read lock again. This kind of lock is useful when the programmer wants to perform long read operations on the network (without blocking other reading thread) and then, atomically, perform some changes; or when the programmer wants to test some conditions on the network status and, dependly on the results, eventually perform some change operations.
public void Lock();
Gets the write lock on the network.
Exceptions thrown:
System.Threading.SynchronizationLockException
The current thread was holding a read lock (got with Freeze).
public void Unlock();
8.2. DeviceGroup 65
Releases the lock of the network in write mode, previously got with Lock.
Exceptions thrown:
System.Threading.SynchronizationLockException The current thread wasn’t holding the write lock.
public bool IsLockHeld;
Returns true if the current thread is owning the write lock.
Until the current thread call Unlock, the network will be protected against disconnections, connections, device list changes or readings, and other Freeze and Lock operations. The table in figure 8.1 shows which operations are allowed and which are not for the different locks. The Unlock method has to be invo- ked by the same thread that invoked Lock method. The Lock can be nested, meaning that a thread already holding the upgradeable read lock can call Lock another time. After that, it must call Unlock twice to effectively release the lock. Table in figure 8.2 shows which combinations of nested locks are possible.
8.2 DeviceGroup
DeviceGroup represents a multicast or broadcast ZigBee device group. It used to perform multicast communications. Broadcast communication is considered a special case of multicast communication, with its own DeviceGroup. Device- Group has the following public properties.
public string Address;
Gets the multicast or broadcast short address.
public DeviceCollection Devices;
Gets the list of devices included in this multicast/broadcast group.
8.2. DeviceGroup 66
Figure 8.1: Allowed operations against locks
Figure 8.2: Allowed nested locks
8.3. Device 67
public Network Network;
Gets the reference network.
Multicast is not supported by GAL yet. At the moment, DeviceGroup class is used only for broadcast communication.
8.3 Device
A Device object represents a generic ZigBee device. This class is abstract. It implements the standard operations that every ZigBee device can perform. It realizes the CIL[4] standard IDisposable interface.
8.3.1 Constructor
There is no public constructor for Device objects. They can be created only by the network. A protected Device constructor is used by the programmer only for external extensibility purposes (see section 9.6).
protected Device(
Initializer initializer, DeviceType deviceType,
string customDeviceTypeName, ushort deviceProfileId, Device ownerDevice) Creates a new Device object.
Exceptions thrown:
System.ArgumentNullException Some initializer’s fields are null.
ZigApi.GatewayCommunicationException
Invalid XML in initializer.Info.
8.3. Device 68
The following list explains the meaning of each parameter.
• initializer. Some initialization parameters.
• deviceType. The device type.
• customDeviceTypeName. In case the device type is CustomDevice, this contains the name of the custom device type.
• deviceProfileId. ZigBee profile which the device belongs to.
• ownerDevice. The owner of this implementor. If this device isn’t an im- plementor, this is null.
The fields of Device.Initializer structure are the following:
public XMLDocument Info;
The device’s information in XML format, as it comes directly from GAL.
Can’t be null.
public Network network;
Reference to the Network object. Can’t be null.
public bool AcceptAttrReports;
If true, the Device object accepts asynchronous attribute reports from the device.
public bool LogConcurrency;
If true, the concurrency operations are logged to the standard output.
8.3.2 Dispose method and destructor
public void Dispose();
Destroys the Device object and all the managed objects.
8.3. Device 69
~Device();
Destroys the Device object.
8.3.3 Miscellaneous properties
public DeviceType Type;
Gets the device type.
Possible values of DeviceType are the following.
• Unknown. Internal use only (used for implementor objects).
• CustomDevice. The device has a programmer-defined type (sse section 9.6).
• Plug. The device is a Telecom Italia’s smart plug. The Device object is a Plug (see section 8.10).
• Refrigerator. The device is a refrigerator. The Device object is a Refrige- rator (see section 8.11).
• HeatingDevice. The device is a heating device. The Device object is a HeatingDevice (see section 8.12).
• Lamp. The device is a lighting device. The Device object is a Lamp (see section 8.13).
public string CustomDeviceTypeName;
Gets the name of the custom device type. If Type is not CustomDevice, the
value of this property is not significant.
8.3. Device 70
public string LongAddress;
Gets the 64-bit extended address of the device in hex digits with capital letters.
public string ShortAddress;
Gets the eventual 16-bit address of the device in hex digits with capital letters.
public string NodeId;
Gets the eventual GAL URI suffix of the node. For example ”/wsn- nodes/node1234”.
public string ParentShortAddress;
Gets the eventual 16-bit address of the device’s parent in hex digits with capital letters.
8.3.4 Methods generating ZigBee traffic
All the Device methods that generates ZigBee traffic ask the freeze lock on the network. They can throw the following exceptions.
System.InvalidOperationException
The device’s network has closed its gateway connection or the device is not (anymore) in the network.
ZigApi.GatewayCommunicationException
8.3. Device 71
An error has occurred in gateway communication.
ZigApi.ZclException
An error has occurred in ZCL protocol (the device has sent an invalid reply to a command).
ZigApi.ZigApiTimeoutException
The device has not replied within the time-out.
Every method that receives replies from the devices takes a time-out ar- gument (in milliseconds) and blocks until the reply arrives or the time-out exceedes. If the time-out is 0 (when permitted) the operation is performed in reply-less mode, meaning that ZigApi does not wait for any reply. In this case, the method does not block and the operation is considered always successful.
This can bring to some consistency problems if the operation actually fails.
As a matter of fact, performing operations in reply-less mode is risky. It is recommended only for urgent operations, final/deinitialization operations and for those operations whose result is indifferent to the application.
8.3.5 Attribute database
In ZigApi, a ZigBee attribute is identified by a string, called attribute name.
The attribute names are those defined in ZigBee Cluster Library without spaces and in proper case, with the cluster name and a slash as prefix. For example, the ZigBee attribute “Local temperature” of the cluster “Thermostat” is “Thermo- stat/LocalTemperature”. Every device maintains internally a ZigBee attribute database. For each attribute, the database contains the last known value of the attribute (if exists), and the know time of this value. The know time is a 32-bit signed integer representing the instant at which the value has been retrieved from the device. The instant is calculated in milliseconds from the system’s start. The bigger is the know time, the fresher is the value in the database.
When a new local value of an attribute is known, the old one is over-written.
Obviously the values in the attribute database are only local copies (eventually
out-of-date) of the actual values stored in devices. In the rest of the text, the
8.3. Device 72
values stored in the devices will be called actual values, whereas the copies in the database will be called local values.
Every ZigBee attribute has a type (for example, signed 16-bit integer or character string) that is mapped to a standard type of Common Infrastructure Language. The following list shows the mapping of the basic types (ZigBee type
→ CIL type).
• Signed 8-bit integer → System.SByte
• Unsigned 8-bit integer → System.Byte
• Signed 16-bit integer → System.Int16
• Unsigned 16-bit integer → System.UInt16
• Signed 24-bit integer → System.Int32
• Unsigned 24-bit integer → System.UInt32
• Signed 32-bit integer → System.Int32
• Unsigned 32-bit integer → System.UInt32
• 8-bit bitmap → System.Byte
• 16-bit bitmap → System.UInt16
• 24-bit bitmap → System.UInt32
• 32-bit bitmap → System.UInt32
• Character string → System.String
• Long character string → System.String
• Date → System.DateTime
• Boolean → System.Boolean
• 8-bit enumeration → System.Byte
Beside its name, its type and its value, every ZigBee attribute has a further
set of characteristics, described in the following list.
8.3. Device 73
• Read-only: the actual value of a read-only attribute can not be written by the application.
• Reportable: devices can send unsolicited reports of reportable attributes.
• Report-configurable: (only if the attribute is also reportable) the applica- tion can configure the reporting parameters of report-configurable attri- butes.
8.3.6 Getting attributes’ characteristics
public AttrInfo GetAttributeInfo(string attributeName);
Returns the information about a particular attribute.
Exceptions thrown:
System.ArgumentException No such attribute exists.
public AttrInfo[] GetAllAttributesInfo();
Returns the information about all attributes.
These methods do not generate ZigBee traffic.
The AttrInfo structure has the following fields.
public string name;
Name of the attribute.
public Type dataType;
CIL type of the attribute’s value.
public bool isReportable;
8.3. Device 74
True if the attribute is reportable by devices.
public bool isReportConfigurable;
True if the attribute’s reporting is configurable with ConfigureReporting.
It is significant only if isReportable is true.
public bool isReadonly;
True if the attribute is read only.
8.3.7 Attribute reading
public virtual object ReadAttr(string attributeName, int timeOut);
Retrieves the value of an attribute from a device.
public virtual void ReadAllAttr(int timeOut) Retrieves the values of all attributes from a device.
Exceptions thrown:
System.ArgumentException Negative or 0 time-out specified.
These functions generate ZigBee traffic. The reply-less mode is not permitted, so timeOut has to be grater than 0. These are always a blocking functions.
Calling ReadAllAttr is more time- and bandwidth-performant than reading all the attributes individually with a sequence of ReadAttr calls. If these methods succeed, the values of the read attributes are stored in the attribute database.
ReadAttr returns the local value of the read attribute.
8.3. Device 75
8.3.8 Retrieving values from attribute database
public virtual object GetAttrVal(string attributeName);
public virtual object GetAttrVal(string attributeName, object defaultValue);
These functions return the local value of an attribute (if exists). If the defaultValue is specified and the local value is not present, the defaultValue is returned.
Exceptions thrown:
System.ArgumentException Unknown attribute name.
System.InvalidOperationException
(Only if a defaultValue is not specified.) A local value of the attribute is not present in the database.
public virtual bool IsKnownAttrVal(string attributeName);
Returns true if a local value of the attribute is present in the attribute database.
public virtual int GetAttrKnowTime(string attributeName);
Returns the know time of the local value of the attribute.
Exceptions thrown:
System.ArgumentException Unknown attribute name.
System.InvalidOperationException
A local value of the attribute is not present in database.
8.3. Device 76
public static int GetCurrentTime();
Gets the current number of milliseconds elapsed from the system’s start.
This function is useful for comparing its result to an attribute’s know time.
GetCurrentTime() - GetAttrKnowTime(. . . ) calculates how old is the local value of an attribute, in milliseconds.
All these functions do not generate ZigBee traffic.
8.3.9 Attribute writing
public virtual void WriteAttr(
string attributeName, object newValue, int timeOut);
Writes an attribute’s value on a device.
Exceptions thrown:
System.ArgumentException
The attribute name is unknown, or the newValue’s type is not consistent, or the attribute is read-only, or a negative time-out has been specified.
This function generates ZigBee traffic. The reply-less mode is permitted. The type of newValue has to be consistent with the ZigBee attribute’s type (see subsection 8.3.5 for type’s correspondences. If this function succeeds, the new value of the attributes is stored also in the attribute database. The attribute can’t be read-only.
8.3.10 Attribute reporting configuration
If the attribute reports receiving is enabled (see subsection 8.1.1) the program-
mer can set the reporting parameters of the ZigBee attribute. The attribute
must be reportable and report-configurable (see subsection 8.3.5).
8.3. Device 77
public virtual void ConfigureReporting(
string attributeName, ushort minReportInterval, ushort maxReportInterval, object reportableChange, int timeOut);
Configures the automatic reports of a device’s attribute.
Exceptions thrown:
System.ArgumentException
The attribute name is unknown, or the reportableChange’s types is not consistent, or a negative time-out has been specified.
The parameters and their meaning correspond to the ZigBee Cluster Library standards.Put maxReport to ushort.MaxValue in order to disable all reports for this attribute. This function generates ZigBee traffic. The reply-less mode is permitted.
8.3.11 Attribute reports callback
The programmer can be notified of the attribute reports arrivals, by means of handler function callbacks. These callbacks are asynchronous to the program- mer’s code. So, the programmer has to pay attention to threading issues.
public virtual void SetAttrReportCallback(
string attributeName,
AttributeReportDelegate callback);
Sets the handler function for the reports of a device’s attribute.
Exceptions thrown:
System.ArgumentException
The attribute name is unknown or the attribute is not reportable.
8.3. Device 78
public virtual void SetAllAttrReportCallback(
AttributeReportDelegate callback);
Sets the handler function for the reports of all the reportable device’s at- tributes.
The signature of AttributeReportDelegate is the following.
public delegate void AttributeReportDelegate(
Device device,
string attributeName, object value,
int knowTime);
The following list explains the parameters.
• device: The device that generated the report.
• attributeName: The attribute name being reported.
• value: The value of the reported attribute.
• knowTime: The know time of the reported attribute.
8.3.12 Attribute locking methods
Device object operations that access the attribute database, automatically locks it. These operations are: ReadAttr, ReadAllAttr, WriteAttr, GetAttrVal, GetAttrKnowTime, and asynchronous attribute reports. The lock is held not for the entire operation, but only for the update of the attribute database. For example, pseudocode 8.1 shows the execution schema of a ReadAttr operation.
Besides, the programmer can manually ask and release the lock on the at-
tribute database of a Device object with dedicated methods.
8.3. Device 79
Algorithm 8.1 ReadAttr execution schema object ReadAttr(...) {
network.Freeze();
<Performing the ZigBee handshake...>
if (<error>) {
network.Unfreeze();
return null;
}
LockAttr();
<Updating the attribute’s value and know-time...>
object ret = localValue;
UnlockAttr();
network.Unfreeze();
return ret;
}
public void LockAttr();
Gets the exclusive access to the attribute database.
public void UnlockAttr();
Releases the exclusive access to the attribute database.
Exceptions thrown:
System.Threading.SynchronizationLockException The current thread was not holding the lock.
public bool IsLockAttrHeld();
Returns true if the current thread owns the exclusive access to the attribute
database.
8.5. IOnOffCluster interface 80
Until the current thread is holding the lock, the local values of the attributes will be protected against asynchronous changes. The UnlockAttr method has to be invoked by the same thread that invoked LockAttr. The lock can be nested, meaning that a thread already holding the lock can call LockAttr another time.
After that, it must call UnlockAttr twice in order to effectively release the lock.
8.4 IBasicCluster interface
IBasicCluster offers the attributes and the operations of the ZigBee Basic cluster.
8.4.1 Attributes
A Device object implementing the IBasicCluster interface must implement the following attributes.
• “Basic/ZCLVersion” (Unsigned 8-bit integer, read-only): Version of the ZCL stack implementation.
• “Basic/ModelIdentifier” (Character string, read-only): The model identi- fier.
• “Basic/PowerSource” (8-bit enumeration, read-only): Power source iden- tifier.
8.5 IOnOffCluster interface
IOnOffCluster offers the attributes and the operations of the ZigBee On/off cluster.
8.5.1 Attributes
A Device object implementing the IOnOffCluster interface must implement the following attributes.
• “OnOff/OnOff” (Boolean, read-only): true if the smart plug is in turned
on, false otherwise.
8.5. IOnOffCluster interface 81
8.5.2 Operations
A Device object implementing the IOnOffCluster interface must implement the following operations.
public void On(int timeOut);
Turns on the device. It updates also the local value of “OnOff” attribute.
Exceptions thrown:
System.ArgumentException Negative time-out specified.
public void Off(int timeOut);
Turns off the device. It updates also the local value of “OnOff” attribute.
Exceptions thrown:
System.ArgumentException Negative time-out specified.
public void Toggle(int timeOut);
Inverts the on/off state of the device. It updates (if exists) also the local value of “OnOff” attribute.
Exceptions thrown:
System.ArgumentException Negative time-out specified.
All these operations generate ZigBee traffic. The reply-less mode is permit-
ted.
8.6. IIdentifyCluster interface 82
8.6 IIdentifyCluster interface
IIdentifyCluster offers the attributes and the operations of the ZigBee Identify cluster.
8.6.1 Attributes
A Device object implementing the IIdentifyCluster interface must implement the following attributes.
• “Identify/IdentifyTime” (Unsigned 16-bit integer): Identification time left, in seconds.
8.6.2 Operations
A device implementing the IIdentifyCluster interface, must implement the fol- lowing operations.
public void Identify(ushort identifyTime, int timeOut);
Orders an identification to the device. The device will blink its identification light for a time specified by identifyTime, in seconds. The command has the same effect of writing the value identifyTime on the attribute “Identi- fyTime”.
Exceptions throws:
System.ArgumentException Negative time-out specified.
This function generates ZigBee traffic. The reply-less mode is permitted.
public static DeviceCollection
IdentifyClusterImpl.IdentifyQuery(
DeviceGroup group,
int timeOut);
8.7. IAlarmsCluster interface 83
Asks a group of devices which of them is currently identifying itself.
Exceptions throws:
System.ArgumentException Negative or 0 time-out specified.
The parameter group identifies the multicast/broadcast group which send the query to. The function returns the set of devices that are identifying them- selves. The set is a subset of the devices identified by group. This function generates multicast (or broadcast) ZigBee traffic. The reply-less mode is not permitted. If a device is not identifying, it will not respond. This function un- blocks when the time-out has been exceeded or when all the devices in the group have responded, so this can be a long-blocking function. In order to ask a single device, use ReadAttr function on the “IdentifyTime” attribute instead.
The code 8.2 shows an example of a broadcast IdentifyQuiery operation.
Algorithm 8.2 Broadcast IdentifyQuery example
DeviceCollection devList = IdentifyClusterImpl.IdentifyQuery(
theNetwork.BroadcastGroup, 5000);
Console.WriteLine("Devices that are currently identifying:");
foreach (Device dev in devList) { Console.WriteLine(dev.LongAddress);
}
8.7 IAlarmsCluster interface
IAlarmsCluster offers the attributes and the operations of the ZigBee Alarms cluster. In ZigApi, each alarm type in a device is identified by a string, called alarm name. The alarm names are those defined in ZigBee Cluster Library without spaces and in proper case, with the cluster name and a slash as prefix.
For example, the “Hardware failure” alarm of the cluster “Thermostat” is
“Thermostat/HardwareFailure”.
8.7. IAlarmsCluster interface 84
8.7.1 Operations
A Device object implementing the IAlarmsCluster interface must implement the following operations.
public void SetAlarmCallback(
string alarmName,
AlarmDelegate alarmCallback);
Sets a handler function that ZigApi will called every time a specific type of alarm is signaled. The callback is asynchronous to the programmer’s code.
So, the programmer has to pay attention to threading issues.
Exceptions thrown:
System.ArgumentException Alarm type name unknown.
public void SetAllAlarmsCallback(
AlarmDelegate alarmCallback);
Sets a handler function that ZigApi will called every time a generic alarm is signaled. The callback is asynchronous to the programmer’s code. So, the programmer has to pay attention to threading issues.
These functions do not generate ZigBee traffic.
void ResetAlarm(string alarmName, int timeOut);
Resets a specific signaled alarm.
Exceptions thrown:
System.ArgumentException
Negative time-out specified or alarm type name unknown.
8.8. IThermostatCluster interface 85
void ResetAllAlarms(int timeOut);
Resets all signaled alarms.
Exceptions thrown:
System.ArgumentException Negative time-out specified.
These functions generate ZigBee traffic. The reply-less mode is permitted.
Calling ResetAllAlarms is more time- and bandwidth-performant than reset- ting all the alarms individually with a sequence of ResetAlarm calls.
8.8 IThermostatCluster interface
IThermostatCluster offers the attributes and the operations of the ZigBee Ther- mostat cluster.
8.8.1 Attributes
A Device object implementing the IThermostatCluster interface must imple- ment the following attributes.
• “Thermostat/LocalTemperature” (Signed 16-bit integer, read-only, repor- table, report-configurable): The temperature measured by the device’s ther- mostat, in hundredths of Celsius degrees.
• “Thermostat/AbsMinHeatSetpointLimit” (Signed 16-bit integer, read-only):
The minimum heating setpoint that the device’s thermostat supports, in hundredths of Celsius degrees. 0xFFFF if the device can’t heat.
• “Thermostat/AbsMaxHeatSetpointLimit” (Signed 16-bit integer, read-only):
The maximum heating setpoint that the device’s thermostat supports, in hundredths of Celsius degrees. 0xFFFF if the device can’t heat.
• “Thermostat/AbsMinCoolSetpointLimit” (Signed 16-bit integer, read-only):
The minimum cooling setpoint that the device’s thermostat supports, in
8.8. IThermostatCluster interface 86
hundredths of Celsius degrees. 0xFFFF if the device can’t cool.
• “Thermostat/AbsMaxCoolSetpointLimit” (Signed 16-bit integer, read-only):
The maximum cooling setpoint that the device’s thermostat supports, in hundredths of Celsius degrees. 0xFFFF if the device can’t cool.
• “Thermostat/OccupiedHeatingSetpoint” (Signed 16-bit integer, reportable):
The current heating setpoint of the device’s thermostat, in hundredths of Celsius degrees. 0xFFFF if the device can’t cool.
• “Thermostat/OccupiedCoolingSetpoint” (Signed 16-bit integer, reportable):
The current cooling setpoint of the device’s thermostat, in hundredths of Celsius degrees. 0xFFFF if the device can’t heat.
• “Thermostat/AlarmMask” (8-bit bitmap, read-only): The signaled alarms’
mask of the Thermostat cluster. Each bit is 1 or 0 whether the corres- pondent alarm is currently signaled or not.
8.8.2 Alarms
A device implementing the IThermostatCluster interface must implement also the IAlarmsInterface and the following alarm types.
• “Thermostat/InitializationFailure”: The device failed to complete initia- lization at power-up.
• “Thermostat/HardwareFailure”: A general hardware failure in thermostat has occurred.
• “Thermostat/SelfCalibrationFailure”: A general self-calibration failure in thermostat has occurred.
8.8.3 Operations
A Device object implementing the IAlarmsCluster interface must implement
the following operations.
8.9. IBoxCluster interface 87
public void public void SetpointRaiseLower(
ThermostatClusterImpl.SetpointRaiseLowerMode mode, sbyte amount,
int timeOut);
Increases or decreases the specified setpoint. It updates (if exist) also the local values of “Thermostat/OccupiedHeatingSetpoint” and/or “Thermo- stat/OccupiedCoolingSetpoint” attributes.
Exceptions thrown:
System.ArgumentException Negative time-out specified.
This function generates ZigBee traffic. The reply-less mode is permitted.
The argument mode is an enumerated and it has the following possible values.
• Heat: increase/decrease the heating setpoint.
• Cool: increase/decrease the cooling setpoint.
• Both: increase/decrease the heating and the cooling setpoints.
The argument amount is the quantity by which increase (if positive) or decrease (if negative) the specified setpoint(s), in tenths of Celsius degrees.
8.9 IBoxCluster interface
IBoxCluster offers the attributes and the operations of the (non-standard) ZigBee Box cluster.
8.9.1 Attributes
A Device object implementing the IBoxCluster interface must implement the following attributes.
• “Box/DoorOpen” (Boolean, read-only, reportable): true if the device’s
door is currently open.
8.10. Plug 88
• “Box/ContentCount” (Unsigned 16-bit integer, read-only, reportable): The number of objects the device contains.
• “Box/Content” (Complex type, read-only): The content of the device. The ZigBee type of this attribute is a bag of structures, each containing two fields: a character string named name (the name of the object) and a date named expirationDate (the expiration date of the object). This attribute is mapped in CIL environment with the following type.
List<BoxClusterImpl.ContentItem>;
public struct BoxClusterImpl.ContentItem { public string name;
public DateTime expirationDate;
}
8.10 Plug
A Plug object represents a (physical or virtual) Telecom Italia smart plug.
It implements On/off cluster and Analog input (basic) cluster. Its applicative protocol is not compliant to the ZigBee Standard Library document.
8.10.1 Attributes
Plug implements all the attributes of IOnOffCluster interface (see section 8.5) and the following dedicated attributes.
• “/PowerConsumption” (Unsigned 32-bit interger, read-only, reportable, report-configurable): The instantaneous power consumption of the smart plug, in watts.
• “/EnergyConsumption” (Unsigned 32-bit integer, read-only, reportable,
report-configurable): The energy consumption calculated over a particular
time interval, in tens of watt-hours (each unit is 10Wh).
8.10. Plug 89
Figure 8.3: Plug’s attributes graph
• “/MeasureInterval” (Unsigned 32-bit integer, reportable, report-configurable):
The time interval over which the energy consumption is calculated, in se- conds.
The measure time interval has a fixed extreme (measure start instant) and the other extreme follows the current instant. In this way, the measure time length and the energy consumption always grow with time. Writing the value 0 in the attribute “/MeasureInterval” resets the energy measuring. This means that the measure starts again from current instant, so that the “/EnergyConsump- tion”’s value starts again from 0. The local value of “/EnergyConsumption”
is also updated. The value 0 is the only accepted value when writing ”/Mea- sureInterval”. The figure 8.3 illustrate the plug’s attributes in a power-time graph.
8.10.2 Operations
Plug implements the operations of Device (see section 8.3), of IOnOffCluster interface and the following dedicated operations.
public void ResetMeasureInterval(int timeOut);
8.12. HeatingDevice 90
Writes 0 on the attribute “/MeasureInterval”. It updates also the local value of “/EnergyConsumption”.
Exceptions thrown:
System.ArgumentException Negative time-out specified.
This operation generates ZigBee traffic. The reply-less mode is permitted.
8.11 Refrigerator
A Refrigerator object represents a (physical or virtual) smart refrigerator. It implements Basic cluster, Identify cluster, Thermostat cluster, Alarms cluster and Box cluster. Its applicative protocol is compliant to the ZigBee Standard Library document.
8.11.1 Attributes
HeatingDevice implements all the attributes of IBasicCluster interface (see section 8.4), IIdentifyCluster interface (see section 8.6), IThermostatCluster interface (see section 8.8), IAlarmsCluster interface (see section 8.7) and IBox- Cluster interface (see section 8.9).
8.11.2 Operations
Refrigerator implements the operations of Device (see section 8.3), of IBasic- Cluster interface, of IIdentifyCluster interface, of IThermostatCluster interface, of IAlarmsCluster interface, of IBoxCluster interface.
8.12 HeatingDevice
A HeatingDevice object represents a (physical or virtual) smart heating de-
vice, like a centralized heating device or a single radiator. It implements Basic
8.13. Lamp 91