![]() |
|
<< Previous | Index | Next >> | |
|
This chapter describes how to create a ZigBee application using Dynamic C and Rabbit-based ZigBee-capable boards.
5.1 Implementation Overview
The state machine that describes the underlying logic of a Dynamic C implementation of ZigBee at the application level is pictured in Figure 5.1. It is coded in the tick function
xbee_tick()1
which is defined inxbee_api.lib
. The states are described in the subsections below.5.1.1 Initialization State
This state configures the radio on the RF module, which includes setting the PAN ID and node string defaults. There are two types of firmware used with Rabbit-based hardware: ZNet 2.5 and ZB. They are similar, but are not compatible. That is, a device running ZNet 2.5 firmware cannot talk to one running ZB.
When using ZNet 2.5, the PAN ID defaults to 0x0234. When using ZB firmware, the PAN ID defaults to "0x0123456789abcdef". This longer PAN ID is called the extended PAN ID in the ZigBee specification. Since it is 64 bits in length it is represented as a string in Dynamic C. The node string defaults to "RabbitXBee" in both ZNet and ZB firmware.
The radio's firmware version and the ZigBee device type are checked against the application's expectation; they must match or the initialization will fail.
More information on the firmware is available in Section 5.4.
5.1.2 Discovery State
A Node Discover (ND) command is sent in the discovery state. The ND command discovers and reports on all RF modules found. This is useful for mapping out the network. An ND command is one of many commands that is used to communicate with the local XBee. For more information on the available AT commands, refer to Table 5-1 or the RF module manual, XBee® / XBee-Pro® ZB OEM RF Module, at www.digi.com; or run the sample program
\Samples\XBee\AT_interactive.c
to explore the AT commands yourself.The following information is returned for each RF module found during discovery. The first four correspond to AT commands, each of which may be used separately to read or set a parameter on the XBee.
- MY
16-bit network (NWK) address
- SH
Serial number high; this is the high 32 bits of the RF module's unique IEEE address
- SL
Serial number low; this is the low 32 bits of the RF module's unique IEEE address
- NI
String identifier
- MP
16-bit network address of the discovered node's parent.
- Device Type
1 byte: 0 = coordinator; 1 = router; 2 = end device
- Status
1 byte: Reserved
- Profile Id
2 bytes: Application profile identifier
- Manufacturer ID
2 bytes: Manufacturer specific identifier; the Digi International Inc. identifier is 0x101E.
By default, Node Discover (ND) takes approximately 6 seconds to terminate. During this time, it is essential to call
xbee_tick()
orZB_ND_RUNNING
(which calls the tick function) to correctly process the incoming ND packets. Prior to Dynamic C 10.44, other communication with the radio was prohibited during node discovery. But as of Dynamic C 10.44 this is no longer the case. Not being able to get up-to-date information from the node table, which is populated during node discovery, is the only restriction.The ND timeout should be set larger than the maximum sleep time of any sleeping end devices that will be discovered. For example, if ND times out after 6 seconds and an end device sleeps for 20 seconds, the end device may not be discovered until after the ND timeout imposed by the library.
The ND timeout is controlled by the NT command. For more information on NT, refer to the description for xb_NT in Table 5-1.
5.1.3 Ready State
In this state the radio is queried for new packets. If a new packet is waiting, it is processed. The radio is also queried for status on its networking association. The response lets us know if a network has been joined successfully, or if not, what happened.
The function
xbee_tick()
must be called in the Dynamic C application in order to service new messages. A good rule of thumb is to callxbee_tick()
whenever the Dynamic C application would otherwise be idle. Special care must be taken to prevent blocking operations and break lengthy processing into small segments. While dependant on expected network traffic, long delays between calls toxbee_tick()
can result in unwelcome latency and even dropped messages.Data message processing is performed in
xbee_tick()
using one of three methods.
Appropriately addressed messages are automatically routed to an endpoint and cluster function.
Messages not processed in a cluster function are passed to an application-defined general message handler.
Any message not already processed will cause
xbee_tick()
to return withZB_MESSAGE
. The Dynamic C application can then get the message and process it outside ofxbee_tick()
.Most API functions only apply to the latest received message.
xbee_tick()
must not be called while directly processing a message or a new incoming message may overwrite the old. This could result in data corruption and a multitude of problems depending on the specific API function called. Prior to Dynamic C 10.21, sending AT commands was also forbidden during message processing. The library enforced this restriction for cluster functions; however, the general message handler and theZB_MESSAGE
processing were uncontrolled and the application was responsible for not callingxbee_tick()
or sending AT commands while processing the message. The restriction on sending/receiving AT commands during message processing has been removed with Dynamic C 10.21. The restriction on callingxbee_tick()
still applies.
NOTE For more information on AT commands, please refer to Table 5-3. 5.1.4 End Device Sleep Mode
End devices, unlike coordinators and routers, can sleep in order to save power. This is controlled by the radio hardware via its /DTR|SLEEP_RQ|DIO8 pin (or "sleep pin" for short). The XBee's sleep pin connection to the Rabbit-based target is design dependent.
On the RCM4510W, the sleep pin is connected to power, which means that the non-radio sections of the Rabbit core module are powered down when the XBee makes a sleep request. On the BL4S100, in contrast, the XBee's sleep pin is not connected to power. So, instead of being powered down when a sleep request is made, an application running on the BL4S100 has options for its power saving strategy. The sample program
sleep.c
illustrates several ways to save power: It turns off the Ethernet interface and the ADC before changing the clock to the real-time clock (i.e., putting the Rabbit into sleepy mode).Both hardware designs lead to significant savings in power use. In the case of the RCM4510W, the backup battery will maintain SRAM contents and will keep the real-time clock running.
Once put into sleep mode, the XBee module will periodically wake up and poll its parent to determine if there is an incoming message. If a message is found, it will be received and the Rabbit target board will either be restarted (in the case of the RCM4510W), which restarts the user application, or the application will unwind whatever power-saving methods it employed, such as being brought out of sleepy mode. In this latter case, the user application is not restarted since it was not stopped to begin with. The received message will be handled in the normal way by the application.
If no message is found, the XBee module will return to sleep. Depending on initialization of sleep mode, the radio may also restart the RCM4510W or bring the BL4S100 out of sleepy mode after a time-out has passed.
There are several limitations that must be accounted for:
The RCM4510W and its user application will fully restart upon coming back from sleep.
Variables that need to be retained between power cycles can be placed in battery-backed RAM if it is available. See the "bbram" keyword in the Dynamic C User's Manual for information on how to place variables in battery-backed RAM.
User data should be initialized prior to calling
xbee_init()
to ensure that a cluster function or the default message handler correctly process an incoming wake message.Every sleep request will be preceded by at least 2 seconds of full power operation. This time is set when calling
xb_sleep()
. Any RF or serial traffic received during this time will reset the countdown. If a message is received during this time, it must be immediately processed as it will be unavailable after sleep has begun and then terminated. An application can callxb_stayawake()
to cancel an imminent sleep if an incoming message must be processed.There are several sample programs that illustrate how to control sleep mode. If you have a Dynamic C version prior to 10.42, refer to
/Samples/ZigBee/SleepMode.c
. Otherwise, see the board-specific folders (e.g.,Samples/BL4S1xx/XBee/
orSamples/RCM4500W/XBee/
) for the sleep mode sample programs available for your hardware.5.2 Sample Programs
This section discusses the Dynamic C sample programs that exercise ZigBee functionality.
Dynamic C sample programs that use ZigBee communication are in the folder
/Samples/XBee2
relative to the Dynamic C installation folder. ZigBee sample programs can also be found in folders specific to the hardware, such as:/Samples/RCM4500W/XBee
,/Samples/BL4S1xx/XBee
and/Samples/BLxS2xx/XBee
.Some of the sample programs can be run with one Rabbit-based board and a DIGI XBee USB device. This device is a simple USB dongle. Its purpose is to aid development by providing a ZigBee coordinator to create a network that the Rabbit-based target can then join as either a router or end device node.
Several sample programs require two Rabbit-based boards.
5.2.1 Sample Program Initialization Requirements
There are several tasks that must be done by all Dynamic C applications that use ZigBee. If you study the supplied samples, you will see similarities in the configuration code as well as some of the initialization code in
main()
.All the sample programs define the configuration macros
XBEE_ROLE
andNODEID_STR
. They both have library default values, but they are useful to put directly in the application code even if you are using the current defaults. Not only is it possible for library default values to change with a newer release of Dynamic C, but having them in the application code is more convenient when you are developing and debugging your software.After
XBEE_ROLE
andNODEID_STR
have been defined, as well as any other configuration macros from Section 5.3.2.1, the application must #use the ZigBee library. The next requirement is the creation of the endpoint table. At a minimum your application program will have the following code beforemain()
:#define XBEE_ROLE NODE_TYPE_ROUTER
#define NODEID_STR "My Descriptive String"
#use xbee_api.libEvery ZigBee application must construct an endpoint table, even if it is empty:
// empty endpoint table
ENDPOINT_TABLE_BEGIN
ENDPOINT_TABLE_ENDIn
main()
there are two tasks that every ZigBee application must accomplish. If the tasks cannot be accomplished, the application should handle any error condition that arises from the attempt:
The radio portion of the board must be initialized by calling
xbee_init()
. This function will start the process of joining a network (router or end device) or creating one (coordinator) if the network is not already present.Check the device's network join status and wait until the device is on an active network or has returned an error.
The sample programs illustrate how to accomplish these two tasks. They all have code similar to the following:
// Initialize the radio portion of the board
join_start = 0;
while ( (initres = xbee_init()) == -EBUSY){
if (! join_start){
join_start = SEC_TIMER;
printf("Waiting for sleeping XBee to wake before continuing.");
}
if (join_start != SEC_TIMER){
join_start = SEC_TIMER;
printf( ".");
}
}
printf( "\n");
if (initres){
printf("xbee_init failed");
exit();
}It is possible for the Rabbit to start while its XBee module is sleeping. The XBee module will not respond while it is sleeping, thus
xbee_init()
will return-EBUSY3
to indicate that fact. But by looping on the return code-EBUSY
, an application can wait untilxbee_init()
returns something else (such as the return code-ETIMEOUT
for failure or 0 for success if the XBee woke up). In this way, the initialization function will not return a failure simply because the XBee is asleep.// Check the join status. For more information on ZB_JOINING_NETWORK,
// perform a function lookup (ctrl-H) on ZB_LAST_STATUS().
printf("Waiting to join network...\n");
join_start = MS_TIMER;
while (ZB_JOINING_NETWORK()) {
// If unable to join a network, timeout after arbitrary time
if (MS_TIMER - join_start > XBEE_JOIN_TIMEOUT) {
printf("\n*** Error ***\n");
printf("Timed out while trying to join a network.\n");
exit(-ETIME)
}
}
printf("Done (%s network)\n", xbee_protocol());Please note that if the device is a ZigBee coordinator, the application may use the same macro (
ZB_JOINING_NETWORK
) that is used to check the join status of routers and end devices in order to determine whether or not a coordinator has finished creating the network.5.2.2 Summary of ZigBee Sample Programs
The bulleted lists below are the available sample programs.
5.2.2.1 Sample Programs for One Rabbit-Based Board
API_Test.c - This sample is only available prior to Dynamic C 10.44. Using the simple text interface you can bring up secondary menus that allow you to:
send_msg.c - This sample program shows how to send a message from a ZigBee end device to the Digi XBee USB ZigBee coordinator or to another end device. (This sample is only available prior to Dynamic C 10.44.)
AT_interactive.c - This sample program illustrates how to set up and send an AT command. It's also useful for debugging purposes, and to configure some of the registers/commands on the XBee. It displays a menu of some of the more useful AT commands, then prompts user to select one. Running this program successfully verifies that the communication link between the RF module and its Rabbit-based board is working properly.
AT_runOnce.c - This sample program illustrates how to set up and send an AT command. It sends some of the more useful AT commands to the RF module one time only. It reads the parameters that are returned and displays them in the Stdio window. Running this program successfully verifies that the communication link between the RF module and its Rabbit-based board is working properly.
5.2.2.2 Sample Programs for Two Rabbit-Based Boards
sleep.c/SleepMode.c/SleepMode2.c - These sample programs are hardware specific. They demonstrate how to put a Rabbit device into sleep mode within a ZigBee environment. The Rabbit device must be an end device, as only end devices are allowed to sleep in a ZigBee network.
EndPoint.c - This sample program requires two Rabbit-based targets. It shows how to set up and use endpoints.
GeneralMessageHandler.c - This sample program requires two Rabbit-based targets. It demonstrates the use of the General Message Handler function, which sends a message between two Rabbit-based boards.
5.2.3 GPIO Server/Client Sample Programs
This collection of sample programs has both server and client applications. The GPIO protocol defined for these sample programs is described at the top of the server program files. The protocol defines a message handling agreement between the two sides, which is essentially the frame formats for the GPIO requests and their responses.
General purpose I/O includes both digital and analog I/O, making these applications a useful template for developing a wide variety of embedded systems software.
5.2.3.1 Running the GPIO Applications
The server application is hardware specific. The sample programs are in hardware specific folders (e.g.,
\Samples\RCM4500W\XBee\XBee_GPIO_Server.c
). After the server application has been compiled and is running on the target board, it will attempt to join a network and if successful, will then wait for client requests.The client application can be run in two different ways:
In the "Serial Port List" window select the COM port that is connected to the Digi XBee USB device. Make sure the baud rate matches. (The default is 115200 bps from the factory; however, 9600 is also very common.) Click on the button labeled "Open Com Port." This results in the radio parameters being filled in.
The first way uses the Digi XBee USB device. Plug the Digi XBee USB into your host PC. There is a Visual Basic application,
\Utilities\XBee GPIO GUI\XBEE_GPIO_GUI.exe
, that when run will display something very similar to the screen in Figure 5.2.
If an error occurs when you try to open the COM port, make sure you don't have something else open on that port. This is a common reason for getting an error.
After you have successfully connected the VB GPIO GUI client to the Digi XBee USB device, click on the tab labeled "Command Window." Select a device in the "Devices Discovered" area. This results in information being displayed for the selected device in the lower half of the GUI window, as shown below in Figure 5.3:
The tabs in the lower half of the "Command Window" screen let you view and modify values for the various I/O signals on the selected device. Which tabs contain information depends on the available I/O of the selected device.
The third main tab, "Messages," displays the messages transmitted and received by the client. This message window is a valuable resource for understanding the communication between the server and client. Figure 5.4 shows the messages exchanged when the "Send Discovery Cmd" button is clicked.
As you can see, a Node Discovery (ND) command was transmitted from the client in response to clicking the "Send Discovery Cmd" button. The actual byte values are followed by an English translation of their meaning.
In this example, two ZigBee devices responded with the following information:
- MY - 16-bit network address
- IEEE - 64-bit IEEE address
- NI - node identifier
- Parent Network Address - 16-bit parent network address; a value of 0xFFFE indicates no parent; only end devices have parents since they are the only devices that need messages buffered
- Device Type: 0=Coordinator, 1=Router, 2=End Device
- Status - reserved
- Profile - application profile
- Manufacturer ID - manufacturer's identifier
In this example, there was one GPIO server found by the scan. From the "Network Commands" menu you can list the I/O signal names and types available on the GPIO server by entering the server's number at the prompt. This will also result in a new command menu being displayed that will allow for the reading and setting of the individual I/O signals.
The second way to run the GPIO client uses a Rabbit-based board instead of the Digi XBee USB device. The Dynamic C sample program,
\Samples\XBee\XBee_GPIO_Client.c
, when compiled and run on a ZigBee-capable board performs the client side of the GPIO application. It is a command line version of the VB GUI application. The opening screen is shown in Figure 5.5.
5.2.3.2 Studying the Code
The GPIO server/client application illustrates the setting up and use of endpoints and clusters. The protocol defined for the GPIO application requires that the cluster ID values on both the server and client must match if the server is to recognize the client's request and likewise if the client is to recognize the server's response.
In both
XBee_GPIO_Server.c
andXBee_GPIO_Client.c
the cluster IDs have the same values and are named:
XBEE_GPIO_CLUST_INFO
XBEE_GPIO_CLUST_NAME
XBEE_GPIO_CLUST_ANA_RANGE
XBEE_GPIO_CLUST_READ
XBEE_GPIO_CLUST_WRITE
Although the cluster IDs are the same, the functions associated with them differ between the server and the client. The client makes a request that is then handled by the server. The client will then handle the response that is sent back from the server. This is shown in the code below.
RabbitClusterIDList_t const gpioEndPointReq = {
{XBEE_GPIO_CLUST_INFO, XBEE_GPIO_CLUST_NAME, XBEE_GPIO_CLUST_ANA_RANGE, XBEE_GPIO_CLUST_READ, XBEE_GPIO_CLUST_WRITE },
{xbeeGpioDevInfoReq, xbeeGpioNameReq, xbeeGpioAnaRangeReq, xbeeGpioReadReq, xbeeGpioWriteReq }
};ENDPOINT_TABLE_BEGIN
ENDPOINT_TABLE_ENTRY(XBEE_ENDPOINT_GPIO,0,XB_PROFILE_DIGI,1,0,5,0,\
&gpioEndPointReq, NULL)
ENDPOINT_TABLE_ENDThe code in
RabbitClusterIDList_t const gpioEndPointResp = {XBee_GPIO_Client.c
uses the same cluster ID values, but associates those cluster IDs with the functions that handle the various server responses.
};{XBEE_GPIO_CLUST_INFO, XBEE_GPIO_CLUST_NAME, XBEE_GPIO_CLUST_ANA_RANGE, XBEE_GPIO_CLUST_READ, XBEE_GPIO_CLUST_WRITE },
{xbeeGpioDevInfoResp, xbeeGpioNameResp, xbeeGpioAnaRangeResp, xbeeGpioReadResp, xbeeGpioWriteResp }
ENDPOINT_TABLE_BEGIN
ENDPOINT_TABLE_ENTRY(XBEE_ENDPOINT_RESPONSE, 0, XB_PROFILE_DIGI, 1, 0, 5, 0,\
&gpioEndPointResp, NULL)
ENDPOINT_TABLE_ENDWhat you will notice if you search through the server and client code is that the cluster functions are not explicity called within the code of either program. This is because the messages received by the ZigBee device are handled within the tick function of
xbee_api.lib
, as described in Section 5.1.3.For more information about the parameters for
ENDPOINT_TABLE_ENTRY
, see the description for the ENDPOINT_TABLE_* macros in Section 5.3.2.1.5.3 Dynamic C Library for ZigBee Applications
This section contains information about the library provided for ZigBee-capable devices. Data structures, error codes and configuration macros from the library are also discussed.
The Dynamic C library that supports ZigBee connectivity is
xbee_api.lib
. It is located in the folderlib\..\XBee
relative to the Dynamic C installation folder. (Prior to Dynamic C 10.44, the folder was named "ZigBee.") The inclusion of the library in the application code must come after the configuration macro definitions. For example, if you are compiling and running your application on an end device, your program must order the lines of code as follows:#define XBEE_ROLE NODE_TYPE_ENDDEV4
#use "xbee_api.lib"Instead of defining the logical device type in the application, it can be defined in the application's project file. (See the "Defines" tab in the menu: Options | Program Options.)
5.3.1 Communication with an RF Module
Using Dynamic C, a Rabbit-based device on a ZigBee network may communicate with its XBee module to read or modify radio parameters, as well as communicate with other devices on its network. The API mode of operation is used as an alternative to the Transparent Operation (serial line replacement) of the RF module. The API mode requires a data frame structure be passed between the Rabbit-based device and the XBee.
The Dynamic C function
zb_sendAPICmd()
takes care of sending the data frame to the RF module.zb_sendAPICmd()
is called by several other Dynamic C functions. Which one of these preliminary functions to use depends on what the application requires. The application will need to send a message to a remote device or will need to send an AT command to the RF module.5.3.1.1 Sending Data to a Remote Device
If a message is being sent to a remote device on the network, the application must call the API function
zb_send()
.(For information on handling messages received from a remote device, please see Section 5.1.3.)
5.3.1.2 Radio Commands
If an AT command is being sent to the XBee, the application must call either the non-blocking function
zb_sendATCmd()
or the blocking functionzb_API_ATCmdResponse()
. Starting with Dynamic C 10.44, you can also use one of three wrapper functions forzb_API_ATCmdResponse()
; they are:xb_get_register()
,xb_set_register()
, andxb_send_command()
.The non-blocking function does not wait for a reply, whereas the blocking functions do.
5.3.2 Configuration Macros and Constants
This section lists the Dynamic C configuration macros and constants that are of interest to application developers.
5.3.2.1 Compile-Time Macros
All of the configuration macros listed here, except for the ones that build the endpoint table, must be defined either in the application program prior to the "#use xbee_api.lib" statement or in the "Defines" tab in the Options | Project Options dialog.
DEFAULT_CHANNELS
This is a bitmask of the channels that will be scanned when a device attempts to associate with a network. It is valid for both ZNet 2.5 and ZigBee (ZB) firmware.
Default =
ZB_DEFAULT_CHANNELS
prior to Dynamic C 10.44
Default =XBEE_DEFAULT_CHANNELS
starting with Dynamic C 10.44Both default values (0x1FFE) allow 12 channels to be scanned and used by the coordinator.
DEFAULT_EXTPANID
Default = "0x0123456789abcdef". Every ZigBee network requires a personal area network (PAN) ID. A coordinator with ZB firmware uses
DEFAULT_EXTPANID
as the 64-bit PAN ID for the network it is creating. Note that this macro is defined as a string in order to fulfill the requirement of it being a 64-bit value.If you are using ZB firmware and have set
DEFAULT_PANID
in your program, but notDEFAULT_EXTPANID
,xbee_api.lib
will useDEFAULT_PANID
padded to the left with zeros as the PAN ID for the network.Setting
DEFAULT_EXTPANID
to "0x00" tells a coordinator to pick a random value for the PAN ID, and tells a router or end device to join any network.DEFAULT_PANID
Default = 0x0234. Every network requires a personal area network (PAN) ID. A coordinator with ZNet firmware uses
DEFAULT_PANID
as the 16-bit PAN ID for the network it is creating.The range for a valid PAN ID is 0x0 to 0x3FFF, inclusive. The value 0xFFFF is also valid. It is used to tell a coordinator to choose a random value for the PAN ID, and tells a routers or end device to join any network.
ENDPOINT_TABLE_*
This group of macros builds the endpoint table.
Before the endpoint table can be created, the Dynamic C application must initialize the structure that holds cluster ID and function information. Cluster IDs refer to the functions implemented on an endpoint. Endpoints may implement zero, one, or any number of the functions listed in a Cluster ID list.
Some variation of the following code is needed in a Dynamic C application that wants to run in a ZigBee network.
RabbitClusterIDList_t const StringInCluster = {
{ CLUSTER_ID },
{ recvString }
};In the above code,
CLUSTER_ID
is associated with the functionrecvString()
. Functions that are associated with a cluster ID are called cluster functions.The application uses the cluster ID/function structure (
RabbitClusterIDlist_t)
to create entries in the endpoint table with theENDPOINT_TABLE_*
macros provided for this purpose. The code below is an example of building an endpoint table.ENDPOINT_TABLE_BEGIN
ENDPOINT_TABLE_ENTRY(EP_NUM, 0, PROFILE_ID, 1, 0, 1, 0, &StringInCluster, NULL)
ENDPOINT_TABLE_ENDThe parameters for
ENDPOINT_TABLE_ENTRY
are:
- EP
Endpoint number, in the range 1 to 219, inclusive.
- DSC
Reserved for future use. Currently set to 0 in sample programs.
- PID
Application profile identifier; the macro XB_PROFILE_DIGI indicates Digi's private application profile.
- DID
Device identifier, in the range 0 to 65,535, inclusive. This number can be used any way desired by the application.
- flags
User-defined byte.
- ICCOUNT
The number of input cluster functions in the RabbitClusterIDList_t structure referenced in the "ICL" field.
- OCCOUNT
The number of output cluster functions in the RabbitClusterIDList_t structure referenced in the "OCL" field. This field is not currently used and should be set to 0.
- ICL
Input cluster ID list. This is the address of a
RabbitClusterIDList_t
structure.- OCL
Output cluster ID list. This is the address
RabbitClusterIDList_t
, but not currently used and should be set to NULL.Any device using
xbee_api.lib
must define an endpoint table, even if it is empty. An empty table is defined as:ENDPOINT_TABLE_BEGIN
ENDPOINT_TABLE_ENDNODEID_STR
This macro defines the NI value for the node and contains a maximum of 20 characters. It gives each node a unique identifier.
Default = "RabbitZigBee" prior to Dynamic C 10.40.
Default = "RabbitXBee" starting with Dynamic C 10.40.XBEE_DEBUG
This configuration macro enables debugger functionality. This is necessary for things like setting breakpoints and stepping through the ZigBee library code. This macro replaced the deprecated macro
ZB_DEBUG
starting with Dynamic C 10.44.XBEE_IN_BUF / XBEE_OUT_BUF
Default = 255 bytes for each buffer. This is the recommended minimum size for the serial buffers. They should be large enough to hold an entire frame.
XBEE_ROLE
This configuration macro defines the device type. It defaults to
NODE_TYPE_ROUTER
. It can be defined to one of the following:
NODE_TYPE_COORD
- the device will be a coordinator.
NODE_TYPE_ROUTER
- the device will be a router.
NODE_TYPE_ENDDEV
- the device will be an end device.XBEE_VERBOSE
This configuration macro enables/disables the printing of extra information generated from the library code to the Stdio window. This macro replaced the deprecated macro
ZB_VERBOSE
starting with Dynamic C 10.44.ZB_CONSTRUCT_NODE_ID
Define this if you want to construct your own node ID string at runtime.
#define ZB_CONSTRUCT_NODE_ID <function-name>
This will allow your software to construct an ID that could contain information about what the capabilities of the device connected to the radio are. A node ID string must be made up of printable ASCII characters, and be no more than
_MAX_NODE_ID_LEN
(20) characters long.The function prototype must be:
char *<function-name>(void);
The function must return a pointer to static data.
ZB_FATAL_ERROR
The
ZB_FATAL_ERROR
macro handles the case where the libraryxbee_api.lib
is reporting that it is experiencing an error beyond its capability to handle. This will usually occur during startup if the radio is not responding.#define ZB_FATAL_ERROR <function-name>
The fatal error handler callback function prototype must be:
void <function-name>(int errorcode);
The error code is one of the defined errors in
/Lib/../ERRNO.LIB
, relative to the Dynamic C installation folder.ZB_MULTI_PROFILE
The #define of this macro enables Profile ID checking in the message interpretation function for explicitly addressed messages. This check will require a received Profile ID to match an associated Endpoint Table Endpoint Descriptor Profile ID before calling the associated callback function.
5.3.2.2 Information Macros
The macros listed here are defined in
xbee_api.li
b and should not be modified by an application.XBEE_IS_COORD
This macro will equal TRUE if the device is configured to be a coordinator, and FALSE otherwise.
XBEE_IS_ENDDEV
This macro will equal TRUE if the device is configured to be an end device, and FALSE otherwise.
XBEE_IS_ROUTER
This macro will equal TRUE if the device is configured to be a router, and FALSE otherwise.
5.3.2.3 Deprecated Device Type Macros
The macros listed here were deprecated starting with Dynamic C 10.40 in favor of
t
heXBEE_ROLE
macro.ZIGBEE_COORDINATOR
This configuration macro defines the device as a coordinator.
ZIGBEE_ENDDEV
This configuration macro defines the device as an end device.
ZIGBEE_ROUTER
This configuration macro defines the device as a router.
5.3.3 Error Codes
Most of the error codes returned from the API functions in
xbee_api.lib
are defined inLib\..\errno.lib
. There are no true fatal errors; however, the I/O error -EIO is fatal in terms of not being able to recover from it without having specialized knowledge and making some low-level internal function calls.Refer to ZB_FATAL_ERROR for handling error conditions that are beyond the capability of the library.
5.3.4 Data Structures
There are many data structures defined in
xbee_api.lib
. Most of them are related to the data packets that are received and transmitted via the RF module. There are also data structures for information about endpoints.api_frame_t
This data structure holds data packet information. It is used by both send and receive functions. Many of the data structures defined at the beginning of the ZigBee library are used to construct
api_frame_t
.A pointer to an instance of this data structure is returned by
zb_receive()
, which is a function that is called whenxbee_tick()
indicates that a message is waiting to be handled. A pointer to an instance of this data structure is passed byzb_sendAPICmd()
to the RF module when the application wants to send a message to another device or wants to read or modify radio parameters.xb_io_sample_t
This data structure holds information about the function and state of digital and analog pins on the XBee module.
_zb_NodeData_t
This data structure holds a node data entry. The information on a network node includes:
16-bit NWK address
64-bit IEEE address
string identifier, 21 characters including NULL
16-bit NWK address of node's parent
device type: coordinator, router, or end device.
application profile ID
whether the node is currently on the network
zb_sendAddress_t
This is the address data structure. It is used whenever a Rabbit ZigBee device transmits a message to another ZigBee device. The functions zb_MakeEndpointClusterAddr() and zb_MakeIEEENetworkAddr() build the data structure (passed as an argument) and then return the pointer passed to them.
The difference between
zb_MakeEndpointClusterAddr()
andzb_MakeIEEENetworkAddr()
is that the former uses the endpoints and the cluster ID for addressing, while the latter function does not. Choosing which one to call allows the Dynamic C application to specify how a message is addressed.The
zb_sendAddress_t
data structure is used by the functions that send messages to another ZigBee device: zb_send() and zb_reply(). The application will typically fill in the message and message length fields, either directly before callingzb_send()
, or indirectly by passing the information tozb_reply()
.5.3.5 API Functions and Macros
This section contains function descriptions for ZigBee-specific functions and macros.
_zb_NodeData_t * GET_NODE_DATA ( int index )
Description
- This macro gets the node data located at the indexed spot in the array. The node array is typically populated by nodes that responded to a Network Discovery (ND) command. Information about the nodes are stored in the array in the order received.
- The macro calls a function to determine where in memory the element is because the array could extend into xmem. Repeated calls to this macro do not incur a processing penalty since the last access is remembered. Note that the node structure is used internally by the library for addressing. The data stored in the node structure must be in network order.
- This macro is non-reentrant.
Parameter
- index
Index into the node array
Return Value
- Address of the node in root memory or NULL if index is out of range.
Library
Description
- Reset the XBee radio by toggling its reset line.
Return Value
- None
Library
Description
- This device-specific macro reads the XBee module's SLEEP_REQ pin (if available). Used by Rabbit hardware running XBee end device firmware to enter and exit low power mode.
- This function was introduced in Dynamic C 10.46.
Return Value
- 1 = XBee is not asking the Rabbit to sleep (not asserting -SLEEP_REQ).
0 = XBee is asking the Rabbit to sleep (asserting -SLEEP_REQ).Library
See Also
- xbee_wait_for_wake()
Description
- Initialize the Rabbit XBee driver and the XBee radio.
- This function was introduced in Dynamic C 10.40, replacing the deprecated function
zigbee_init()
.Return Value
- 0: successful
-EBUSY
: XBee end device is sleeping, try again. After 28 seconds of-EBUSY
,xbee_init()
will return-ETIME
: XBee timed out
-ETIME
!=0: failure- See
_zb_error
for the specific error code. The values for_zb_error
are defined in/Lib/../ERRNO.LIB
relative to the Dynamic C installation folder.Library
Description
- Returns a string identifying the network protocol in use by the XBee connected to the Rabbit.
Return Value
int xbee_tick ( api_frame_t * frame );
Description
- Drive the Rabbit XBee radio communications. Performs a Network Discovery once at initialization time.
- This function was introduced in Dynamic C 10.44 and replaces the deprecated function
zb_tick()
.Parameter
- frame
Pointer to
api_frame_t
structure to receive a copy of the last frame.Note that the received frame may be a response to a packet sent by
xbee_api.lib
, or a non-response frame from another device on the network. Check the frame type (frame->cmd.api_id
) and the frame id (frame->cmd.u.frame_id
) to confirm that it is the expected response.Return Value
ZB_NOMESSAGE
: no messages receivedZB_MESSAGE
: a message has arrivedZB_RADIO_STAT
: radio status changeZB_MSG_STAT
: message transmission status availableZB_ATRESP
: response to AT commandZB_REMOTE_RESP
: response to remote AT command
-ENOMEM
: out of memory processing node discovery response
(various codes)<0: an error has occurredLibrary
int xbee_wait_for_wake( void );
Description
- If the XBee is sleeping, this function will queue a null byte in the serial buffer so the XBee will stay awake as soon as it wakes up (and asserts CTS and receives the null byte).
- Called from user program to wait for a sleeping end device to wake up. Can only be used after calling
xbee_init()
.while (xbee_wait_for_wake()) {
twiddle_thumbs();
do_other_stuff();
}- On a router or coordinator,
xbee_wait_for_wake()
always returns 0.- This function was introduced in Dynamic C 10.46.
Return Value
TRUE
: if waiting for the XBee to wake upFALSE
: if XBee is awake.Library
See Also
- xbee_awake
int xb_get_register( word reg, unsigned long * dest );
Description
- Read an XBee register (up to 32 bits).
- This function was introduced in Dynamic C 10.44.
Parameters
- reg
Register to read, as a 16-bit word (see
xb_XX
definitions in Table 5-1 for values to use). Also possible to use *(word *)"XX" for reading the ATXX register.Examples:
xb_VR
for firmware version,xb_SH
for top 4 bytes of serial number,xb_AI
for the association indicator.- dest
Address to store up to a 32-bit result. Can be NULL to send a command to the XBee and ignore the result.
Return Value
- 0: Success
-ZBERR_AT_CMD_RESP_STATUS
: Radio returned failure-ETIME
: Timeout-EIO
: Serial I/O error-ENOSPC
: Output buffer fullLibrary
void xb_hexdump( void * data, int len );
Description
- Hex dump <len> bytes from <data>. Displays 8 hex bytes and their printable characters or a '.'.
- This function was introduced in Dynamic C 10.44.
Parameters
- data
Pointer to buffer.
- len
Number of bytes to print.
Return Value
- None
Library
far char * xb_io_conf_desc ( int dio, int config );
Description
- Returns a description of an XBee module's I/O pin configuration.
Parameters
- dio
DIO number, 0 <= dio <
XBEE_IO_COUNT
(13).- config
Configuration for pin (ATDx or ATPx setting), 0 to 5.
Return Value
NULL
: Invalid parameters passed in (dio or config out of range).XB_IO_CONF_INVALID
: Invalid configuration for given dio (e.g., digital-only pin configured as analog input)!NULL
: String describing a pin's configuration.Library
void xb_io_sample_clear (far xb_io_sample_t * sample );
Description
- Reset the sample structure to default values (0x00 for first two values, -1 for the next five).
- This function was introduced in Dynamic C 10.40.
Parameters
- xb_io_sample_t
Pointer to the
xb_io_sample_t
structure to clear.Return Value
- None
Library
int xb_IS_parse ( far xb_io_sample_t * sample, far char * IS_data );
Description
- Parse the return data from an ATIS command or 0x92 (
_API_FRAME_IO_SAMPLE
) frame.- This function was introduced in Dynamic C 10.40.
Parameters
- sample
Pointer to the
xb_io_sample_t
buffer to receive the parsed data.- IS_data
Pointer to the data returned from ATIS or the 0x92 frame.
Return Value
- 0: if parsed successfully
-EINVAL
: if there's a problem with parameter 2Library
Description
- Display list of nodes from the node table to Stdout. Useful when displaying information to the Stdio window and prompting the user to select a node.
- Each node is listed with its index (for selecting a node), 16-bit network address, 16-bit parent address, 64-bit IEEE address, Active/Inactive state and its Node ID string.
- This function was introduced in Dynamic C 10.44.
Return Value
- none
Library
char * xb_nd_nodetype_str ( int nd_type );
Description
- Used to convert from the node type field in an ND response to a string describing the type.
- This function was introduced in Dynamic C 10.44.
Parameter
Return Value
- If
nd_type
=XB_ND_NODETYPE_COORD
, the return value is "coordinator"
Ifnd_type
=XB_ND_NODETYPE_ROUTER
, the return value is "router"
Ifnd_type
=XB_ND_NODETYPE_ENDDEV
, the return value is "end device"- If
nd_type
is anything else, the return value is "invalid"Library
int xb_sendAPIremoteATcmd ( far char dest_ieee[8], word nwk_addr, int options, int remote_cmd, far void * remote_data, int len );
Description
- Send a command frame to a remote device using the XBee API format.
- This function was introduced in Dynamic C 10.44.
Parameters
- dest_ieee
64-bit IEEE address of target device. Only used if nwk_addr (parameter 2) is set to
ZB_NETWORK_BROADCAST
..- nwk_addr
16-bit network address of target device, or
ZB_NETWORK_BROADCAST
to use IEEE addressing.- options
Options for the frame, valid choices are 0 (default) or
XB_REMOTE_REQ_OPT_APPLY
(0x02) (apply changes on remote).- remote_cmd
16-bit command to send (see the
xb_XX
macro definitions in Table 5-1 for values to use). Also possible to use *(word *)"XX" to send an ATXX command.- remote_data
Pointer to data to send.
- len
Amount of data.
Return Value
- 0: success
-ENOSPC
: not enough buffer space to send command-EIO
: XBee holding CTS low, or IO did not complete correctly- _zb_error will be set on error or successful message transmission.
Library
Macro Definitions
- The
remote_cmd
parameter can be one of the macros in Table 5-1. Be careful when sending an AT command to the XBee, as some of the commands will cause a loss of communication (for example, sending xb_BD to change the baud rate). More information on AT commands is in the manual XBee® / XBee-PRO® ZB OEM RF Modules available at: www.digi.com.
int xb_send_command( word cmd );
Description
- Send an AT command to the XBee. Same behavior as reading an XBee register and ignoring the result.
- This function was introduced in Dynamic C 10.44.
NOTE xb_send_command
is a macro forxb_get_register()
.Parameter
- cmd
Command to send, as a 16-bit word (see
xb_XX
definitions in Table 5-1 for values to use). Also possible to use *(word *)"XX" for reading the ATXX register.Examples:
Return Value
- 0: Success
-ZBERR_AT_CMD_RESP_STATUS
: Radio returned failure-ETIME
: Timeout-EIO
: Serial I/O error-ENOSPC
: Output buffer fullLibrary
int xb_set_register( word reg, unsigned long value );
Description
- Set an XBee register (up to 32 bits).
- This function was introduced in Dynamic C 10.44.
Parameters
- reg
Register to write, as a 16-bit word (see
xb_XX
definitions in Table 5-1 for values to use). Also possible to use *(word *)"XX" for reading the ATXX register.Examples:
xb_SC
to set list of channels to scan,xb_D0
to set the I/O mode for DIO0.- value
Value to store in register (Parameter1).
Return Value
- 0: Success
-ZBERR_AT_CMD_RESP_STATUS
: Radio returned failure, possibly due to setting an out-of-range value (e.g., 16-bit value in an 8-bit register).-ETIME
: Timeout-EIO
: Serial I/O error-ENOSPC
: Output buffer fullLibrary
int xb_sleep( word st, word sp, word sn, word so, word sm );
Description
- Set the parameters that control the sleep mode, using the default XBee parameters. For more details refer to the manual XBee® / XBee-PRO® ZB OEM RF Modules available at: www.digi.com.
- This function was introduced in Dynamic C 10.44 to replace the deprecated function
zb_Rabbit_Sleep()
.Parameters
- st
Time Before Sleep (in milliseconds).
st controls how long the Rabbit module will stay awake. The minimum value shown below exists because this is the time that the module takes to become fully operational. If st is set to a value smaller than 2000, the module will be go back to sleep before it has the chance to run its code. The minimum value for st is
ZB_MIN_ST_TIME
(0x07D0, 2.000 secs) The maximum value for st isZB_MAX_ST_TIME
(0xFFFE, 65.534 secs)- sp
Cyclic Sleep Period (in 1/100 seconds).
sp controls how often the XBee module will wake up and check for new frames (end devices) or how long the XBee will buffer frames for sleeping end devices (routers and coordinators).
The minimum value for sp isZB_MIN_SP_TIME
(0x0020, 0.32 seconds) The maximum value for sp isZB_MAX_SP_TIME
(0x0AF0, 28.00 seconds)- sn
Sleep Time Extender. This parameter is used in cases where we want the Rabbit module to stay asleep for periods longer than the sp cyclic sleep period. The Rabbit module will remain asleep for a period of sn * sp. However, the radio will wake up briefly every time sp expires and it will poll its parent for messages. If there is a message waiting, the radio wakes up the Rabbit module and forwards the message. If there is no message, the radio goes to sleep again for another sp period. sn can be any non-zero value.
- so
Sleep Options. This parameter is a bitmask made up of the following options. Read the XBee Module manual for more details on these settings.
- sm
Sleep Mode. This parameter is a bitmask made up of the following options. On Rabbit products, the sleep pin is not connected so
XB_SM_CYCLIC
is the only useful option.Warning: On XBee end devices with ZNet firmware,
XB_SM_DISABLED
is considered an invalid parameter (and xb_sleep will return-EINVAL
). With ZNet, setting the sm parameter toXB_SM_DISABLED
will cause the end device to become a router, perform a network reset and rejoin the network.OReturn Value
- 0: Successful, power will turn off after the ST timer expires.
-EINVAL
: Invalid parameters-EOPNOTSUPP
: Operation not supported (on routers and coordinators)-ZBERR_AT_CMD_RESP_STATUS
: Couldn't set one of the sleep parameters-ETIME
: Timeout-EIO
: Serial I/O error-ENOSPC
: Output buffer fullLibrary
Description
- This function is for end devices only. It sets the idle timeout (ST) to maximum value, and keeps the XBee awake by sending serial data to it periodically.
- This function was introduced in Dynamic C 10.44.
Return Value
- 0: Successful
-EOPNOTSUPP
: Operation not supported (on Routers and Coordinators)-ZBERR_AT_CMD_RESP_STATUS
: Could not set ST register-ETIME
: Timeout-EIO
: Serial I/O error-ENOSPC
: Output buffer full.Library
Description
- Read the analog input pin on the local XBee using AT commands. Return the 10-bit value. To convert the reading to millivolts perform the following calculation:
- Note: The pin number is NOT the same as the
DIO_xx
macros, which are for configuring the function of the pin only.Parameter
- dio
Analog input pin to read. This value corresponds to the DIO number. Valid analog DIO values range from 0 to 3.
Return Value
- 0-1023: valid data
-EINVAL
: invalid pinLibrary
int zb_API_ATCmdResponse ( char * _cmdstr, void * data, int dlen, _at_cmdresp_t * resp );
Description
- Send an API AT command and get the response.
Parameters
- _cmdstr
pointer to command string: we expect "ATcc", so we skip the first two bytes for API format commands
- data
address of data to send
- dlen
length of data to send
- resp
address of AT response buffer
Return Value
- 0: success
-ZBERR_AT_CMD_RESP_STATUS
: Radio returned failure-ETIME
: Timeout-EIO
: Serial I/O error-ENOSPC
: Output buffer fullLibrary
int zb_check_sleep_params ( unsigned int st, unsigned int sp, unsigned int sn );
Description
- This is an auxiliary function that checks if the main sleep mode parameters are within valid limits. For more details on the parameters, refer to the description for xb_sleep().
Parameters
- st
Time Before Sleep
- sp
Cyclic Sleep Period
- sn
Sleep Time Extender
Return Value
- 0: successful, all parameters are valid
-EINVAL
: invalid parametersLibrary
Description
- Read a digital input pin on the XBee module.
Parameter
- dio
The pin number (0-
ZB_MAX_PIN
). This value corresponds to the DIO number. Valid digital DIO values are 0-5, 10, 11, and 12.Note: The pin number is NOT the same as the
DIO_xx
macros. Those are for configuring the function of the pin only.Return Value
- 0 or 1: valid data
-EINVAL
: invalid pinLibrary
int zb_dio_out ( int dio, int value );
Description
- Set the digital output value on the XBee module pin.
Parameters
- dio
The pin number (0-
ZB_MAX_PIN
). This value corresponds to the DIO number. Valid digital DIO values are 0-5, 10, 11, and 12.Note: The pin number is NOT the same as the DIO_xx macros. Those are for configuring the function of the pin only.
- value
The value of the pin (1 or 0).
Return Value
- 0: successful
-EINVAL
: invalid pin numberLibrary
Description
- Returns the last error encountered. This is a macro to access the error code variable of the
XBee_API.lib
library.Library
#define ZB_GENERAL_MESSAGE_HANDLER <functionName>
Description
- Define the general message handler for messages that do not have endpoints or other addressing means specified. The general message handler callback function prototype must be:
- "data" points to the message data. To get more data about the message call
zb_receive()
. This will give you access to any addressing information that was received.- To reply to this message directly use
zb_reply()
before another message arrives. To assure that no messages arrive before you have replied do not callxbee_tick()
until your reply has been sent (i.e.,zb_reply()
orzb_send()
has been called).- If the message cannot be handled by the general message handler it may return non-zero, and the
xbee_tick()
function will indicate that a message is available. You may access the message usingzb_receive()
and handle it then.- Return a zero to indicate that the message has been completely processed.
xbee_tick()
will then not indicate that a message is available.Library
int zb_getATCmdResponse ( _at_cmdresp_t * buffer, int blen );
Description
- Wait (i.e., block) for a response to the current AT command.
Parameters
- buffer
Pointer to where to put the response
- blen
Size of buffer (deprecated starting with Dynamic C 10.46)
Return Value
- 0: success
-ETIME
: timeout_zb_error
will be set to the same value as the return value.Library
Description
- Initializes the I/O subsystem on the XBee module. The default behavior for each pin is predefined but can be overridden prior to #using xbee_api.lib by #defining the appropriate macro:
#define DIO_00 XBEE_IO_CONF_ANAIN
#define DIO_05 XBEE_IO_CONF_DIGOUT_HIGH
#define DIO_10 XBEE_IO_CONF_DIGOUT_LOW
#define DIO_12 XBEE_IO_CONF_DIGIN
#use xbee_api.lib- The DIO_xx defines automatically generate four additional macros for
zb_io_init()
:DIO_INPUTS
,DIO_OUTPUTS
,AIO_INPUTS
, andDIO_PULLEDUP
.DIO_PULLEDUP
sets which pins are pulled up. By default, all input pins are pulled up, but this can be overridden by #definingDIO_PULLEDUP
prior to #using xbee_api.lib (note: the mask order forDIO_PULLEDUP
is different than forDIO_INPUTS
, see below).- While all pins can be configured as either inputs or outputs, only
DIO_00
-DIO_03
can be configured as analog inputs.- The default configuration is:
- On the RCM45xxW, the DIO_xx signals map to AUX I/O header (J4 on the core module) as follows:
- AUX I/O (J4) Header Pins
-----------------------------
1 2
DIO_00 --- oo --- DIO_01
DIO_02 --- oo --- DIO_03
GND --- oo --- DIO_12
No Connection --- oo --- +3.3V
SysPwr --- oo --- DIO_05
DIO_04 --- oo --- No Connection
DIO_10 --- oo --- DIO_11
13 14
Return Value
- 0: success
!=0: the error code returned by a call tozb_API_ATCmdResponse()
Library
See Also
- zb_API_ATCmdResponse() for error codes
api_frame_t *ZB_LATEST_MESSAGE()
Description
- This macro gives the address of the
api_frame_t
structure holding the last message received.Library
See Also
- ZB_LAST_MSG_DATA(), ZB_LAST_MSG_DATALEN()
Description
- This macro points to the RF payload of the last frame received.
Library
See Also
- ZB_LATEST_MESSAGE(), ZB_LAST_MSG_DATALEN()
Description
- This macro is set to the size of the RF payload of the last frame received.
Library
See Also
- ZB_LATEST_MESSAGE(), ZB_LAST_MSG_DATA()
Description
- This macro returns the RF module status of this node. See the defined constants below for values and their meanings.
ZB_HARDWARE_RESET
, module is performing a hardware resetZB_WATCHDOG_RESET
, module is resetting from a watchdog timeoutZB_JOINED
, module has joined a networkZB_UNJOINED
, module has left (unjoined) a networkZB_COORD_STARTED
, coordinator started- Additionally, the macro
ZB_JOINING_NETWORK
returns TRUE (1) whenZB_LAST_STATUS() != ZB_JOINED
. You can use a statement like:- to check if the arbitrary maximum time to join has expired. If it did, process the timeout error condition.
Library
zb_sendAddress_t * zb_MakeEndpointClusterAddr ( int node, int srcEP, int destEP, word clusterID, zb_sendAddress_t * addr );
Description
- Fill in the address structure for sending to
zb_send()
.Parameters
- node
Index into the node lookup table. Sending -1 indicates a broadcast address.
- srcEP
Source (sending) endpoint.
- destEP
Destination endpoint.
- clusterID
Destination cluster ID.
- addr
Buffer to put the address data into.
Return Value
- A pointer to the address buffer.
A NULL return value means that either:
- the node value is out of range
- a valid node entry was not foundLibrary
zb_sendAddress_t * zb_MakeIEEENetworkAddr ( int node, zb_sendAddress_t * buffer );
Description
- Create an address for
zb_send()
consisting of the 8-byte IEEE address and the 2-byte network address.Parameters
- node
Index into the node lookup table. Sending -1 indicates a broadcast address.
- buffer
Where to put the address data.
Return Value
- A pointer to the address buffer.
A NULL return value means that either:
- the node value is out of range
- a valid node entry was not foundLibrary
int zb_missed_messages ( void );
Description
- Return the number of missed messages since the last time
zb_receive()
was called.Return Value
- Count of missed messages.
Library
Description
- This macro tracks when a node is currently performing a Node Discovery (ND) command. Be aware that this macro calls
xbee_tick()
, which will then silently drop any received packets.- It is typically used in the following way:
printf("Waiting for node discovery...\n");
while (ZB_ND_RUNNING());
printf("Discovery done.\n\n");- Prior to Dynamic C 10.44, no other AT command could be sent to the radio while performing node discovery.
Return Value
- TRUE: node discovery in progress
FALSE: node discovery not in progressLibrary
int zb_Rabbit_poweroff( _zb_power_control_t * zbp );
Description
- Send the wake-up parameters to the Radio and instruct it to power-down the Rabbit.
- This function is for use on the RCM45xxW only.
Parameter
- zbp
Wake-up parameter structure address. The
_zb_power_control_t
structure is defined as follows:typedef struct {
char wakeFlag; // See below for valid flag values
int digIOMask; // bits = digital I/O pins on RF module
// 0 - ignore this I/O pin
// 1 - wake on change to this pin
char anaChannelMask; // bits = analog I/O channels on RF module
// 0: ignore this channel
// 1: wake on level reached for this channel
int anaChannelLevels[XBEE_ANA_CHANNELS];
// wake Rabbit when read value exceeds this level
// if the level is negative, the read value must
// be <= the level.
// if the level is positive, the read value must
// be >= the level.
long time_in_ms; // Length of time (millisecs) for Rabbit to sleep
// The actual sleep time will be
// (int)(radio_duty * (time_in_ms / radio_duty))
int radio_duty; // Sleep time in 1/100 seconds
// Please note that the sleep time will determine
// analog read interval if "wake on analog level"
// is active. The max value for the radio sleep
// cycle is 28 seconds (0x0Af0)
} _zb_power_control_t;Return Value
- 0: successful, power will turn off after the ST timer5 expires (
ZB_MIN_ST_TIME
).-EINVAL
: invalid parameters-EOPNOTSUPP
: operation not supported (on Routers or Coordinators) or function was called while in debug mode.Library
zb_Rabbit_Sleep ( unsigned st, unsigned sp, unsigned sn );
Description
- Set the parameters that control the sleep mode using the default XBee parameters.
- As of Dynamic C 10.44, this function has been deprecated in favor of xb_sleep(), which includes parametersfor setting the XBee SO and SM registers.
Parameters
- st
Time Before Sleep (in milliseconds): this timer must be set in msecs.
st controls how long the Rabbit module will stay awake.The minimum value shown below exists because this is the time that the module takes to become fully operational. If st is set to a value smaller than 2000, the module will go back to sleep before it has the chance to run its code.
- sp
Cyclic Sleep Period (in 1/100 seconds)
sp controls how often the XBee module will wake up and check for new frames (end devices) or how long the XBee will buffer frames for sleeping end devices (routers and coordinators).
- sn
Sleep Time Extender:
sn is used in cases where we want the Rabbit module to stay asleep for periods longer than the sp time. The Rabbit module will remain asleep for a period of sn * sp. However, the radio will wake up briefly every time sp expires and it will poll its parent for messages.
If there is a message waiting, the radio wakes up the Rabbit module and forwards the message. If there is no message the radio goes to sleep again for another sp period. sn can be any non-zero value.
Return Value
- 0: Successful, power will turn off after the st timer expires.
-EINVAL
: invalid parameters.-EOPNOTSUPP
: operation not supported (on routers or coordinators) or function was called while in debug mode (on RCM45xxW).Library
api_frame_t * zb_receive ( char * data, int * len );
Description
- This function should be called when the
xbee_tick()
function indicates that a message is waiting to be handled.- The parameter to this routine will be the address of the buffer which will accept the new message. The buffer should be
XBEE_MAX_RFPAYLOAD
bytes long to ensure there is sufficient space to receive the data.- The function returns the address of the beginning of the entire message (a pointer to an
api_frame_t
). If the function returns NULL there was no message. The current message will be held until the next message arrives.- Note that no new messages will arrive until
xbee_tick()
is called.Parameters
- data
Buffer to receive data. Send NULL to get only the length of
api_frame_t
.- len
Buffer to receive data length. Send NULL to get only the address of
api_frame_t
.Return Value
- NULL: no message was received
!=NULL: address of current message.Library
int zb_reply ( char * reply, int len );
Description
- Send a reply to the last message received. This function uses the address of the last message's sender as the addressee of the reply. The reply will be sent using explicit addressing.
Parameters
- reply
Pointer to message to send.
- len
Length of message.
Return Value
- 0: Queued, the message has been sent to the Radio for transmission.
-EINVAL
: bad parameters-ENOSPC
: cannot give message to serial portLibrary
int zb_send ( zb_sendAddress_t * addr );
Description
- Send a message to other XBee radios. The addressing modes may be combined to more completely direct messages. If endpoints and cluster ID are not specified, they will be set to zero.
Parameter
- addr
Pointer to the address data structure.
Return Value
- 0: Queued - the message has been sent to the Radio for transmission.
-EINVAL
: Bad parameters.-ENOSPC
: Cannot give msg to serial port.-ENONET
: Radio has not joined a network.-EIO
: XBee holding CTS low, or serial write did not complete correctly.Library
See Also
- zb_MakeIEEENetworkAddr(), zb_MakeEndpointClusterAddr()
int zb_sendAPICmd ( int cmd, void * data, int len );
Description
- Send a raw command frame using the XBee API format.
Parameters
- cmd
API frame identifier.
- data
Pointer to data to send.
- len
Length of data.
Return Value
- 0: Success.
-ENOSPC
: Not enough buffer space to send command.-EIO
: XBee is holding CTS low, or serial write did not complete correctly.- SIDE EFFECTS: _zb_error will be set on error or successful message transmission.
Library
int zb_sendATCmd ( char * _cmdstr, char * data, int dlen );
Description
- Send an AT command to the XBee module without waiting for a response. This is useful when a command is expected to take too long to respond (>
_XBEE_TIMEOUT
milliseconds).Parameters
- _cmdstr
Pointer to command text ("ATxx", "AT" is ignored and "xx" used for command)
- data
Pointer to command parameters.
- dlen
Length of command parameters.
Return Value
- 0: success
-EIO
: serial I/O error-ENOSPC
: output buffer full- SIDE EFFECTS:
_zb_error
will be set on error or successful message transmission.Library
int zb_swapBytes ( int * value );
Description
- Swap the bytes of a word-sized (two-byte) value.
Parameter
- value
Address of word to change.
Return Value
- New value of "value"
See Also
- htons (host to network short)
Library
Description
- Drive the Rabbit XBee radio communications. Performs a Network Discovery once at initialization time.
NOTE This function has been deprecated, please use xbee_tick()
(which includes more return values and can return a copy of the last frame processed) instead.Return Value
ZB_NOMESSAGE
: no messages receivedZB_MESSAGE
: a message has arrivedZB_RADIO_STAT
: radio status changeZB_MSG_STAT
: message transmission status available-ENOMEM
: out of memory processing node discovery response
(various codes)<0: an error has occurredLibrary
Description
- This macro returns the overhead required to send the last message.
Return Value
NO_DISC_OVERHEAD
ADDR_DISCOVERY
ROUTE_DISCOVERY
ADDR_AND_ROUTE
Description
- This macro return the status of the last transmission sent by this software.
- Under normal operation an application will be mostly concerned with
ADDR_NOT_FOUND
orROUTE_NOT_FOUND
. The first status would indicate that the device in question has shut down or moved out of range. The second status would indicate that some intermediate nodes that provided the route to the wanted device have shut down.Return Value
DELIVERY_SUCCESS
CCA_FAILURE
BAD_DEST_ENDPOINT
NET_ACK_FAILURE
NOT_JOINED
SELF_ADDRESSED
ADDR_NOT_FOUND
ROUTE_NOT_FOUND
Description
- Initialize the Rabbit XBee driver and the XBee radio.
- This function was deprecated in Dynamic C 10.40.
Return Value
- 0: successful
!=0: failure- See
_zb_error
for the specific error code. The values for_zb_error
are defined in/Lib/../ERRNO.LIB
relative to the Dynamic C installation folder.Library
5.4 Protocol Firmware
ZigBee-capable Rabbit-based boards must be programmed with the appropriate RF module firmware. There are two sets of firmware to consider: one for ZNet 2.5 and one for ZigBee PRO (ZB).
ZNet 2.5 firmware is only supported on RCM4510W core modules.
5.4.1 Updating RF Module FW on a Rabbit-Based Target
To update the protocol firmware on the XBee RF module housed on the Rabbit-based target board, use the Dynamic C sample program
\Samples\XBee\ModemFWLoad.c
located relative to the Dynamic C installlation folder.The instructions at the top of
ModemFWLoad.c
explain the two macros you need to set in order to download the correct firmware. They are:
XBEE_PROTOCOL
- this macro must be #defined toXBEE_PROTOCOL_ZB
orZBEE_PROTOCOL_ZNET
, depending on the protocol desired.
XBEE_ROLE6
- this macro must be #defined toNODE_TYPE_COORD
,NODE_TYPE_ROUTER
orNODE_TYPE_ENDDEV
, depending on the ZigBee device type desired. The supported protocols (ZNet and ZB) have different versions of firmware for each ZigBee device type.To change these macros from their default values (
NODE_TYPE_ROUTER
andXBEE_PROTOCOL_ZB
) find their #define statements at the top ofModemFWLoad.c
and modify the program code.5.4.2 X-CTU: Updating RF Module FW on a DIGI XBee USB Device
A utility program, X-CTU, is provided for reading and writing the firmware on the Digi XBee USB device. The utility is described in the following subsections.
5.4.2.1 X-CTU Installation
To install the X-CTU utility, run its setup program,
Setup_XCTU_XXXX.exe,
found in\Utilities\X-CTU
relative to the Dynamic C installation folder. The installation process will create a desktop icon for the utility.5.4.2.2 PC Settings Tab
Click on the X-CTU icon to run the utility. The PC Settings tab is the first screen displayed when it starts. Before doing anything else, check the box labeled "Enable API". This box may be unchecked by default, but it must be checked because only the API mode of communication is supported.
You can change serial parameters (baud, etc.) and test/query the COM port high-lighted in the "Select COM Port" window to test the connection between X-CTU and the selected COM port.
In Figure 5.6, the values shown on the "Host Setup" tab at the bottom half of the "PC Settings" tab are the default values. Leave them as is. To update the firmware on the DIGI XBee USB device, select the COM port that the device is connected to, in this case, COM9. Follow the instructions given in the next section.
5.4.2.3 Modem Configuration Tab
Click on the Modem Configuration tab. A screen similar to the one shown in Figure 5.7 will be displayed.
Click on the button labeled "Read". This will cause the firmware that is loaded onto the DIGI XBee USB device to be read and its parameters displayed, as shown in Figure 5.8.
Do not click on the button labeled "Restore" unless you want to write default parameter values for the current firmware version to the device; for example., the PAN ID and Node Identifier will be zeroed out. Also, do not check the box labeled "Always update firmware." If this box is checked, the entire firmware will be reloaded when you attempt to write network parameters. When the entire firmware is reloaded to the device, it takes significantly more time than just writing network parameters. In addition, reloading the firmware will cause a network reset.
5.4.2.3.1 Selecting the Firmware
The buttons "Save" and "Load" under the label "Profile" allow use of files ending in .pro that contain firmware configuration settings. To load the default configuration values for the firmware, navigate to
Utilities/X-CTU
and selectXBee-USB ZB defaults.pro
. These default values will not take effect until they are written to the Digi XBee USB device by clicking on the "Write" button.Three drop-down menus labeled "Modem:", "Function Set" and "Version" are available for selecting the firmware to write to the DIGI XBee USB device. If the firmware version you want is not included in these drop-down menus, click on the button labeled "Download new versions...". Click on "File..." in the resulting popup box:
![]()
Then browse to the Dynamic C installation folder. From there go to the folder /Utilities/X-CTU/MODEMFW/ to select the .zip file containing the desired firmware. After X-CTU's firmware list has been updated, make your selection using the three drop-down menus. Then click on the button labeled "Write" in order to load the selected firmware onto the device. Writing new firmware always causes a network reset.
5.4.2.3.2 Modem Parameters
The parameters read from the device are described in Table 5-3. The available AT commands and their categories differ slightly between firmware versions. The following table reflects a read of firmware XB24-ZB version 2141, with the default configuration values from
Utilities/X-CTU
/XBee-USB ZB defaults.pro
. The mnemonic for the AT command is given, followed by its default value in parenthesis.5.4.2.3.3 Saving "Modem Parameters" to a File
The function of the button "Save" located under the label "Profile" is to save the parameter values in the display window to a file. The "Load" button lets you browse to a previously saved ".pro" file and open it to display its contents. To write the contents to the device attached to the selected COM port, you must click on "Write."
5.5 Summary
This is the ground floor of a very useful new standard. Dynamic C offers an easy-to-use implementation of ZigBee that works seamlessly with the Rabbit hardware as a solid foundation for a variety of embedded system projects that include wireless networking in their design.
1 As of Dynamic C 10.44, xbee_tick() is used in place of the deprecated function zb_tick().
2 All folders named "XBee" were named "ZigBee" prior to Dynamic 10.44.
3 There are error conditions that will cause the XBee module to be unresponsive, for example, a bad firmware image. In such cases, xbee_init() will return -EBUSY before ultimately returning -ETIMEOUT.
4 Prior to Dynamic C 10.40, the #define statement would be: #define ZIGBEE_ENDEV
5 By default, the AT command ST (time before sleep) is set to 65.534 seconds
6 Prior to Dynamic C 10.40, the configuration macros ZIGBEE_COORDINATOR, ZIGBEE_ROUTER and ZIGBEE_ENDDEV were used instead of XBEE_ROLE.
An Introduction to ZigBee | << Previous | Index | Next>> | rabbit.com |