5633.Z-Stack Developer's Guide
5633.Z-Stack Developer's Guide
Developer’s Guide
TABLE OF CONTENTS
1. INTRODUCTION.................................................................................................................................................................. 1
1.1 PURPOSE .......................................................................................................................................................................... 1
1.2 SCOPE .............................................................................................................................................................................. 1
1.3 ACRONYMS ...................................................................................................................................................................... 1
1.4 REFERENCE DOCUMENTS .................................................................................................................................................. 1
2. ZIGBEE .................................................................................................................................................................................. 2
2.1 DEVICE TYPES .................................................................................................................................................................. 2
2.1.1 Coordinator ................................................................................................................................................................ 2
2.1.2 Router ......................................................................................................................................................................... 2
2.1.3 End-device .................................................................................................................................................................. 2
2.2 STACK PROFILE ................................................................................................................................................................ 3
3. ADDRESSING ....................................................................................................................................................................... 4
3.1 ADDRESS TYPES ................................................................................................................................................................ 4
3.2 NETWORK ADDRESS ASSIGNMENT ..................................................................................................................................... 4
3.2.1 Tree Addressing .......................................................................................................................................................... 4
3.2.2 Stochastic Addressing ................................................................................................................................................. 5
3.3 ADDRESSING IN Z-STACK ................................................................................................................................................. 5
3.3.1 Unicast ........................................................................................................................................................................ 6
3.3.2 Indirect........................................................................................................................................................................ 6
3.3.3 Broadcast .................................................................................................................................................................... 6
3.3.4 Group Addressing ....................................................................................................................................................... 6
3.4 IMPORTANT DEVICE ADDRESSES....................................................................................................................................... 6
4. BINDING ................................................................................................................................................................................ 8
4.1 BUILDING A BINDING TABLE............................................................................................................................................. 8
4.1.1 ZigBee Device Object Bind Request ........................................................................................................................... 8
4.1.1.1 The Commissioning Application .......................................................................................................8
4.1.1.2 ZigBee Device Object End Device Bind Request ..............................................................................8
4.1.2 Device Application Binding Manager ......................................................................................................................... 9
4.2 CONFIGURING SOURCE BINDING ....................................................................................................................................... 9
5. ROUTING ............................................................................................................................................................................ 10
5.1 OVERVIEW ..................................................................................................................................................................... 10
5.2 ROUTING PROTOCOL ....................................................................................................................................................... 10
5.2.1 Route Discovery and Selection ................................................................................................................................. 11
5.2.2 Route maintenance.................................................................................................................................................... 11
5.2.3 Route expiry .............................................................................................................................................................. 11
5.3 TABLE STORAGE ............................................................................................................................................................. 11
5.3.1 Routing table............................................................................................................................................................. 11
5.3.2 Route discovery table ................................................................................................................................................ 12
5.4 MANY-TO-ONE ROUTING PROTOCOL .............................................................................................................................. 12
5.4.1 Many-to-One Routing Overview ............................................................................................................................... 12
5.4.2 Many-to-One Route Discovery.................................................................................................................................. 12
5.4.3 Route Record Command ........................................................................................................................................... 13
5.4.4 Many-to-One Route Maintenance ............................................................................................................................. 14
5.5 ROUTING SETTINGS QUICK REFERENCE .......................................................................................................................... 14
5.6 ROUTER OFF-NETWORK ASSOCIATION CLEANUP ............................................................................................................ 15
6. ZDO MESSAGE REQUESTS ............................................................................................................................................ 16
7. PORTABLE DEVICES ....................................................................................................................................................... 18
8. END-TO-END ACKNOWLEDGEMENTS ....................................................................................................................... 18
9. MISCELLANEOUS ............................................................................................................................................................ 19
9.1 CONFIGURING CHANNEL ................................................................................................................................................. 19
9.2 CONFIGURING THE PAN ID AND NETWORK TO JOIN......................................................................................................... 19
9.3 MAXIMUM PAYLOAD SIZE ............................................................................................................................................... 19
9.4 LEAVE NETWORK ........................................................................................................................................................... 19
9.5 DESCRIPTORS ................................................................................................................................................................. 20
9.6 NON-VOLATILE MEMORY ITEMS .................................................................................................................................... 20
14.5.3 OSALMEM_MIN_BLKSZ..................................................................................................................................... 40
14.5.4 OSALMEM_SMALL_BLKSZ ................................................................................................................................ 40
14.5.5 OSALMEM_SMALLBLK_BUCKET ..................................................................................................................... 40
14.5.6 OSALMEM_NODEBUG ...................................................................................................................................... 40
14.5.7 OSALMEM_PROFILER_LL ................................................................................................................................ 40
15. COMPILE OPTIONS.......................................................................................................................................................... 42
15.1 OVERVIEW ..................................................................................................................................................................... 42
15.2 REQUIREMENTS .............................................................................................................................................................. 42
15.2.1 Target Development System Requirements ........................................................................................................... 42
15.3 USING Z-STACK COMPILE OPTIONS ................................................................................................................................ 42
15.3.1 Selecting the Logical Device Type ........................................................................................................................ 42
15.3.2 Locating Compile Options .................................................................................................................................... 42
15.3.2.1 Compile Options In Linker Control Files .................................................................................... 43
15.3.2.2 Compile Options In IAR Project Files ......................................................................................... 46
15.3.3 Using Compile Options ........................................................................................................................................ 47
15.4 SUPPORTED COMPILE OPTIONS AND DEFINITIONS ........................................................................................................... 48
15.4.1 General Compile Options ..................................................................................................................................... 48
15.4.2 Non-changeable Compile Options ........................................................................................................................ 50
15.4.3 Monitor-Test (MT) Compile Options .................................................................................................................... 50
15.4.4 ZigBee Device Object (ZDO) Compile Options.................................................................................................... 50
1. Introduction
1.1 Purpose
This document explains some of the components of the Texas Instruments ZigBee stack and their functioning. It
explains the configurable parameters in the ZigBee stack and how they may be changed by the application developer
to suit the application requirements.
1.2 Scope
This document describes concepts and settings for the Texas Instruments Z-Stack™ Release. This is a ZigBee-2007
compliant stack for the ZigBee and ZigBee PRO stack profiles.
1.3 Acronyms
AF Application Framework
AES Advanced Encryption Standard
AIB APS Information Base
API Application Programming Interface
APS Application Support Sub-Layer
APSDE APS Date Entity
APSME APS Management Entity
ASDU APS Service Datagram Unit
BSP Board Support Package – taken together, HAL & OSAL comprise a rudimentary operating system
commonly referred to as a BSP
CCM* Enhanced counter with CBC-MAC mode of operation
EPID Extended PAN ID
HAL Hardware (H/W) Abstraction Layer
MSG Message
NHLE Next Higher Layer Entity
NIB Network Information Base
NWK Network
OSAL Operating System (OS) Abstraction Layer
OTA Over-The-Air
PAN Personal Area Network
SE Smart Energy
ZDO ZigBee Device Object
2. ZigBee
A ZigBee network is a multi-hop network with battery-powered devices. This means that two devices that wish to
exchange data in a ZigBee network may have to depend on other intermediate devices to be able to successfully do
so. Because of this cooperative nature of the network, proper functioning requires that each device (i) perform
specific networking functions and (ii) configure certain parameters to specific values. The set of networking
functions that a device performs determines the role of the device in the network and is called a device type. The set
of parameters that need to be configured to specific values, along with those values, is called a stack profile.
An example network is shown in the diagram above, with the ZigBee Coordinator (black), the Routers (red), and the
End Devices (white).
2.1.1 Coordinator
This is the device that “starts” a ZigBee network. It is the first device on the network. The coordinator node scans
the RF environment for existing networks, chooses a channel and a network identifier (also called PAN ID) and then
starts the network.
The coordinator node can also be used, optionally, to assist in setting up security and application-level bindings in
the network.
Note that the role of the Coordinator is mainly related to starting up and configuring the network. Once that is
accomplished, the Coordinator behaves like a Router node (or may even go away). The continued operation of the
network does not depend on the presence of the Coordinator due to the distributed nature of the ZigBee network.
2.1.2 Router
A Router performs functions for (i) allowing other devices to join the network (ii) multi-hop routing (iii) assisting in
communication for its child battery-powered end devices.
In general, Routers are expected to be active all the time and thus have to be mains-powered.
2.1.3 End-device
An end device has no specific responsibility for maintaining the network infrastructure, so it can sleep and wake up
as it chooses. Thus it can be a battery-powered node.
Generally, the memory requirements (especially RAM requirements) are lower for an end device.
Notes:
In Z-Stack, the device type is usually determined at compile-time via compile options (ZDO_COORDINATOR and
RTR_NWK). All sample applications are provided with separate project files to build each device type.
All devices in a network must conform to the same stack profile (i.e., all devices must have the stack profile
parameters configured to the same values).
The ZigBee Alliance has defined two different stack profiles for the ZigBee-2007 specification, Zigbee and Zigbee
PRO, with the goal of promoting interoperability. All devices that conform to this stack profile will be able to work
in a network with devices from other vendors that also conform to it.
If application developers choose to change the settings for any of these parameters, they can do so with the caveat
that those devices will no longer be able to interoperate with devices from other vendors that choose to follow the
ZigBee specified stack profile. Thus, developers of “closed networks” may choose to change the settings of the stack
profile variables. These stack profiles are called “network-specific” stack profile.
The stack profile identifier that a device conforms to is present in the beacon transmitted by that device. This
enables a device to determine the stack profile of a network before joining to it. The “network-specific” stack profile
has an ID of 0 while the ZigBee stack profile has ID of 1, and a ZigBee PRO stack profile has ID of 2. The stack
profile is configured by the STACK_PROFILE_ID parameter in nwk_globals.h file.
Normally, a device of 1 profile (ex. ZigBee PRO) joins a network with the same profile. If a router of 1 profile (ex.
ZigBee PRO) joins a network with a different profile (ex. ZigBee-2007), it will join as a non-sleeping end device.
An end device of 1 profile (ex. ZigBee PRO) will always be an end device in a network with a different profile.
3. Addressing
3.1 Address types
ZigBee devices have two types of addresses. A 64-bit IEEE address (also called MAC address or Extended address)
and a 16-bit network address (also called logical address or short address).
The 64-bit address is a globally unique address and is assigned to the device for its lifetime. It is usually set by the
manufacturer or during installation. These addresses are maintained and allocated by the IEEE. More information on
how to acquire a block of these addresses is available at http://standards.ieee.org/regauth/oui/index.shtml. The 16-bit
address is assigned to a device when it joins a network and is intended for use while it is on the network. It is only
unique within that network. It is used for identifying devices and sending data within the network.
The addressing scheme requires that some parameters are known ahead of time and are configured in each router
that joins the network. These are the MAX_DEPTH, MAX_ROUTERS and MAX_CHILDREN parameters. These are
part of the stack profile and the ZigBee-2007 stack profile has defined values for these parameters (MAX_DEPTH =
5, MAX_CHILDREN = 20, MAX_ROUTERS = 6).
The MAX_DEPTH determines the maximum depth of the network. The coordinator is at depth 0 and its child nodes
are at depth 1 and their child nodes are at depth 2 and so on. Thus the MAX_DEPTH parameter limits how “long” the
network can be physically.
The MAX_CHILDREN parameter determines the maximum number of child nodes that a router (or coordinator) node
can possess.
The MAX_ROUTERS parameter determines the maximum number of router-capable child nodes that a router (or
coordinator) node can possess. This parameter is a subset of the MAX_CHILDREN parameter and the remaining
(MAX_CHILDREN – MAX_ROUTERS) entries are for end devices.
If developers wish to change these values, they need to follow the following steps:
First it must be ensured that the new values for these parameters are legal. Since the total address space is
limited to about 216, there are limits on how large these parameters can be set to.
After choosing legal values, the developer needs to ensure not to use the standard stack profile and instead
set it to network-specific (i.e. change the STACK_PROFILE_ID in nwk_globals.h to
NETWORK_SPECIFIC) because the values are different from the values defined for the ZigBee profile.
Then the MAX_DEPTH parameter in nwk_globals.h may be set to the appropriate value.
In addition, the array’s CskipChldrn and CskipRtrs must be set in the nwk_globals.c file. These
arrays are populated with the values for MAX_CHILDREN and MAX_ROUTERS value for the first
MAX_DEPTH indices followed by a zero value.
End devices do not participate in the “Address Conflict”. Their parents do that for them. If an “Address Conflict”
occurs for an end device, its parent will issue the end device a “Rejoin Response” message to change the end
device’s short address and the end device issues a “Device Announce” to check their new address for conflicts
within the network.
When a “Device Announce” is received, the association and binding tables are updated with the new short address,
routing table information is not updated (new routes must be established). If a parent determines that the “Device
Announce” pertains to one of its end device children, but it didn’t come directly from the child, the parent will
assume that the child moved to another parent.
typedef struct
{
union
{
uint16 shortAddr;
ZLongAddr_t extAddr;
} addr;
afAddrMode_t addrMode;
byte endPoint;
} afAddrType_t;
Note that in addition to the network address, the address mode parameter also needs to be specified. The destination
address mode can take one of the following values (AF address modes are defined in AF.h)
typedef enum
{
afAddrNotPresent = AddrNotPresent,
afAddr16Bit = Addr16Bit,
afAddr64Bit = Addr64Bit,
afAddrGroup = AddrGroup,
afAddrBroadcast = AddrBroadcast
} afAddrMode_t;
The address mode parameter is necessary because, in ZigBee, packets can be unicast, multicast or broadcast. A
unicast packet is sent to a single device, a multicast packet is destined to a group of devices and a broadcast packet is
generally sent to all devices in the network. This is explained in more detail below.
3.3.1 Unicast
This is the normal addressing mode and is used to send a packet to a single device whose network address is known.
The addrMode is set to Addr16Bit and the destination network address is carried in the packet.
3.3.2 Indirect
This is when the application is not aware of the final destination of the packet. The mode is set to
AddrNotPresent and the destination address is not specified. Instead, the destination is looked up from a
“binding table” that resides in the stack of the sending device. This feature is called Source binding (see later section
for details on binding).
When the packet is sent down to the stack, the destination address and end point is looked up from the binding table
and used. The packet is then treated as a regular unicast packet. If more than one destination device is found in the
binding table, a copy of the packet is sent to each of them. If no binding entry is found, the packet will not be sent.
3.3.3 Broadcast
This address mode is used when the application wants to send a packet to all devices in the network. The address
mode is set to AddrBroadcast and the destination address can be set to one of the following broadcast addresses:
NWK_BROADCAST_SHORTADDR_DEVALL (0xFFFF) – the message will be sent to all devices in the network
(includes sleeping devices). For sleeping devices, the message is held at its parent until the sleeping device polls for
it or the message is timed out (NWK_INDIRECT_MSG_TIMEOUT in f8wConfig.cfg).
NWK_BROADCAST_SHORTADDR_DEVRXON (0xFFFD) – the message will be sent to all devices that have the
receiver on when idle (RXONWHENIDLE). That is, all devices except sleeping devices.
NWK_BROADCAST_SHORTADDR_DEVZCZR (0xFFFC) – the message is sent to all routers (including the
coordinator ).
Before using this feature, groups must be defined in the network, see aps_AddGroup() in the Z-Stack API [2]
document.
Note that groups can also be used in conjunction with indirect addressing. The destination address found in the
binding table can be either a unicast or a group address. Also note that broadcast addressing is simply a special case
of group addressing where the groups are setup ahead of time.
aps_Group_t group;
4. Binding
Binding is a mechanism to control the flow of messages from one application to another application (or multiple
applications). The binding mechanism is implemented in all devices and is called source binding.
Binding allows an application to send a packet without knowing the destination address, the APS layer determines
the destination address from its binding table, and then forwards the message on to the destination application (or
multiple applications) or group.
The target device will send back a ZigBee Device Object Bind or Unbind Response message which the ZDO code
on the coordinator will parse and notify ZDApp.c by calling ZDApp_ProcessMsgCBs() with the status of the
action.
For the Bind Response, the status returned from the coordinator will be ZDP_SUCCESS, ZDP_TABLE_FULL,
ZDP_INVALID_EP, or ZDP_NOT_SUPPORTED.
For the Unbind Response, the status returned from the coordinator will be ZDP_SUCCESS, ZDP_NO_ENTRY,
ZDP_INVALID_EP, or ZDP_NOT_SUPPORTED.
For the Coordinator End Device Binding process, the coordinator registered ZD_RegisterForZDOMsg() to
receive End Device Bind Request, Bind Response and Unbind Response ZDO messages in
ZDApp_RegisterCBs() defined in ZDApp.c. When these message are received they are sent to
ZDApp_ProcessMsgCBs(), where they are parsed and processed.
Coordinator end device binding is a toggle process. Meaning that the first time you go through the process, it will
create a binding entry in the requesting devices. Then, when you go through the process again, it will remove the
bindings in the requesting devices. That’s why, in the following process, it will send an unbind, and wait to see if
the unbind was successful. If the unbind was successful, the binding entry must have existed and been removed,
otherwise it sends a binding request to make the entry.
When the coordinator receives 2 matching End Device Bind Requests, it will start the process of creating source
binding entries in the requesting devices. The coordinator follows the following process, assuming matches were
found in the ZDO End Device Bind Requests:
1. Send a ZDO Unbind Request to the first device. The End Device Bind is toggle process, so the unbind
is sent first to remove an existing bind entry.
2. Wait for the ZDO Unbind Response, if the response status is ZDP_NO_ENTRY, send a ZDO Bind
Request to make the binding entry in the source device. If the response status is ZDP_SUCCESS,
move on to the cluster ID for the first device (the unbind removed the entry – toggle).
3. Wait for the ZDO Bind Response. When received, move on to the next cluster ID for the first device.
4. When the first device is done, do the same process with the second device.
5. When the second device is done, send the ZDO End Device Bind Response messages to both the first
and second device.
5. Routing
5.1 Overview
A mesh network is described as a network in which the routing of messages is performed as a decentralized,
cooperative process involving many peer devices routing on each others’ behalf.
The routing is completely transparent to the application layer. The application simply sends data destined to any
device down to the stack which is then responsible for finding a route. This way, the application is unaware of the
fact that it is operating in a multi-hop network.
Routing also enables the “self healing” nature of ZigBee networks. If a particular wireless link is down, the routing
functions will eventually find a new route that avoids that particular broken link. This greatly enhances the
reliability of the wireless network and is one of the key features of ZigBee.
Many-to-one routing is a special routing scheme that handles the scenario where centralized traffic is involved. It is
part of the ZigBee PRO feature set to help minimize traffic particularly when all the devices in the network are
sending packets to a gateway or data concentrator. Many-to-one route discovery is described in details in Section
5.4.
Neighbor routers are routers that are within radio range of each other. Each router keeps track of their neighbors in
a “neighbor table”, and the “neighbor table” is updated when the router receives any message from a neighbor router
(unicast, broadcast or beacon).
When a router receives a unicast packet, from its application or from another device, the NWK layer forwards it
according to the following procedure. If the destination is one of the neighbors of the router (including its child
devices) the packet will be transmitted directly to the destination device. Otherwise, the router will check its routing
table for an entry corresponding to the routing destination of the packet. If there is an active routing table entry for
the destination address, the packet will be relayed to the next hop address stored in the routing entry. If a single
transmission attempt fails, the NWK layer will repeat the process of transmitting the packet and waiting for the
acknowledgement, up to a maximum of NWK_MAX_DATA_RETRIES times. The maximum data retries in the NWK
layer can be configured in f8wconfig.cfg. If an active entry cannot be found in the routing table or using an
entry failed after the maximum number of retries, a route discovery is initiated and the packet is buffered until that
process is completed.
ZigBee End Devices do not perform any routing functions. An end device wishing to send a packet to any device
simply forwards it to its parent device which will perform the routing on its behalf. Similarly, when any device
wishes to send a packet to an end device and initiate route discovery, the parent of the end device responds on its
behalf.
Note that the ZigBee Tree Addressing (non-PRO) assignment scheme makes it possible to derive a route to any
destination based on its address. In Z-Stack, this mechanism is used as an automatic fallback in case the regular
routing procedure cannot be initiated (usually, due to lack of routing table space).
Also in Z-Stack, the routing implementation has optimized the routing table storage. In general, a routing table
entry is needed for each destination device. But by combining all the entries for end devices of a particular parent
with the entry for that parent device, storage is optimized without loss of any functionality.
ZigBee routers, including the coordinator, perform the following routing functions (i) route discovery and selection
(ii) route maintenance (iii) route expiry.
Route selection is performed by choosing the route with the least possible cost. Each node constantly keeps track of
"link costs" to all of its neighbors. The link cost is typically a function of the strength of the received signal. By
adding up the link costs for all the links along a route, a “route cost” is derived for the whole route. The routing
algorithm tries to choose the route with the least “route cost”.
Routes are discovered by using request/response packets. A source device requests a route for a destination address
by broadcasting a Route Request (RREQ) packet to its neighbors. When a node receives an RREQ packet it in turn
rebroadcasts the RREQ packet. But before doing that, it updates the cost field in the RREQ packet by adding the
link cost for the latest link and makes an entry in its Route Discovery Table (5.3.2). This way, the RREQ packet
carries the sum of the link costs along all the links that it traverses. This process repeats until the RREQ reaches the
destination device. Many copies of the RREQ will reach the destination device traveling via different possible
routes. Each of these RREQ packets will contain the total route cost along the route that it traveled. The destination
device selects the best RREQ packet and sends back a Route Reply (RREP) back to the source.
The RREP is unicast along the reverse routes of the intermediate nodes until it reaches the original requesting node.
As the RREP packet travels back to the source, the intermediate nodes update their routing tables to indicate the
route to the destination. The Route Discovery Table, at each intermediate node, is used to determine the next hop
of the RREP traveling back to the source of the RREQ and to make the entry in to the Routing Table.
Once a route is created, data packets can be sent. When a node loses connectivity to its next hop (it doesn’t receive
a MAC ACK when sending data packets), the node invalidates its route by sending an RERR to all nodes that
potentially received its RREP and marks the link as bad in its Neighbor Table. Upon receiving a RREQ, RREP or
RERR, the nodes update their routing tables.
Routing table capacity indicates that a device routing table has a free routing table entry or it already has a routing
table entry corresponding to the destination address. The routing table size is configured in f8wconfig.cfg.
Set MAX_RTG_ENTRIES to the number of entries in the (default is 40). See the section on Route Maintenance for
route expiration details.
Source routing is part of the many-to-one routing that provides an efficient way for concentrator to send response or
acknowledgement back to the destination. The concentrator places the complete route information from the
concentrator to the destination into the data frame which needs to be transmitted. It minimizes the routing table size
and route discovery traffic in the network.
RREQ
RREQ
C RREQ
RREQ
RREQ
RREQ
RREQ
C Concentrator
Router
Many-to-one route request command is similar to unicast route request command with same command ID and
payload frame format. The option field in route request is many-to-one and the destination address is 0xFFFC. The
following Z-Stack API can be used for the concentrator to send out many-to-one route request. Please refer to the Z-
Stack API [2] documentation for detailed usage about this API.
The option field is a bitmask to specify options for the route request. It can have the following values:
Value Description
0x00 Unicast route discovery
0x01 Many-to-one route discovery with route cache (the
concentrator does not have memory constraints).
0x03 Many-to-one route discovery with no route cache (the
concentrator has memory constraints)
When the option field has value 0x01 or 0x03, the DstAddress field will be overwritten with the many-to-one
destination address 0xFFFC. Therefore, user can pass any value to DstAddress in the case of many-to-one route
request.
C Concentrator
Router R1
RREC[ ]
DATA
RREC[R2]
R3 ACK[ack]
DATA
RREC[R2,R3]
R2
DATA ACK[(R2,R3), ack]
C ACK[(R2,R3), ack]
Upon receipt of the route record command, devices on the relay path will append their own network addresses to the
relay list in the route record command payload. By the time the route record command reaches the concentrator, it
includes the complete routing path through which the data packet is relayed to the concentrator. When the
concentrator sends ACK back to R1, it shall include the source route (relay list) in the network layer header of the
packet. All devices receiving the packet shall relay the packet to the next hop device according to the source route.
For concentrator with no memory constraints, it can store all route record entries it receives and use them to send
packets to the source devices in the future. Therefore, devices only need to send route record command once.
However, for concentrator without source route caching capability, devices always need to send route record
commands along with data packets. The concentrator will store the source route temporarily in the memory and then
discard it after usage.
In brief, many-to-one routing is an efficient enhancement to the regular ZigBee unicast routing when most devices
in the network are funneling traffic to a single device. As part of the many-to-one routing, source routing is only
utilized under certain circumstances. First, it is used when the concentrator is responding to a request initiated by the
source device. Second, the concentrator should store the source route information for all devices if it has sufficient
memory. If not, whenever devices issue request to the concentrator, they should also send route record along with it.
When the concentrator receives network status command indicating many-to-one route failure, it passes the
indication to the ZDO layer and the following ZDO callback function in ZDApp.c is called:
void ZDO_ManytoOneFailureIndicationCB()
By default, this function will redo a many-to-one route discovery to recover the routes. You can modify this function
if you want a more complicated process other than the default.
Set MAX_RTG_ENTRIES
Setting Routing Table Size Note: the value must be greater than 4. (See
f8wConfig.cfg)
Set ROUTE_EXPIRY_TIME to expiry time in seconds. Set to
Setting Route Expiry Time
0 in order to turn off route expiry. (See f8wConfig.cfg)
Set MAX_RREQ_ENTRIES to the maximum number of
Setting Route Discovery Table Size simultaneous route discoveries enabled in the network. (See
f8wConfig.cfg)
In order to avoid this, it is recommended that routers prone to get off and on the network will have
zgRouterOffAssocCleanup flag set to TRUE (mapped to NV item:
ZCD_NV_ROUTER_OFF_ASSOC_CLEANUP):
When enabled, deprecated end device entries will be removed from the child table if traffic received from them was
routed by another parent.
Application Layer
Other Devices ZDO Layer
In the following example, an application would like to know when any new devices join the network. The
application would like to receive all ZDO Device Announce (Device_annce) messages.
Application Layer
Other Devices ZDO Layer
ZDO_RegisterForZDOMsg( taskID, Register with ZDO that you want all ZDO
Device_annce ); Device Announce Messages
7. Portable Devices
End devices are automatically portable. Meaning that when an end device detects that its parent isn’t responding
(out of range or incapacitated) it will try to rejoin the network (joining a new parent). There are no setup or
compile flags to setup this option.
The end device detects that a parent isn’t responding either through polling (MAC data requests) failures and/or
through data message failures. The sensitivity to the failures (amount of consecutive errors) is controlled by
MAX_POLL_FAILURE_RETRIES, which is configurable in f8wConfig.cfg (the higher the number – the less
sensitive and the longer it will take to rejoin).
When the network layer detects that its parent isn’t responding, it will call ZDO_SyncIndicationCB(), which
will initiate a “rejoin”. The rejoin process will first orphan-scan for an existing parent, then scan for a potential
parent and rejoin (network rejoin command) the network with the potential parent.
In a secure network, it is assumed that the device already has a key and a new key isn’t issued to the device.
In a ZigBee PRO network, the end device’s short address is retained when it moves from parent to parent. In a
ZigBee network, because of the tree addressing, the new parent will give the end device a new address. In either
case, routes to the moved end device have to be re-established either automatically (as the old one fails) or
intentionally (by the application).
8. End-to-end acknowledgements
For non-broadcast messages, there are basically 2 types of message retry: end-to-end acknowledgement (APS
ACK) and single-hop acknowledgement (MAC ACK). MAC ACKs are always on by default and are usually
sufficient to guarantee a high degree of reliability in the network. To provide additional reliability, as well as to
enable the sending device get confirmation that a packet has been delivered to its destination, APS
acknowledgements may be used.
APS acknowledgement is done at the APS layer and is an acknowledgement system from the destination device to
the source device. The sending device will hold the message until the destination device sends an APS ACK
message indicating that it received the message. This feature can be enabled/disabled for each message sent with the
options field of the call to AF_DataRequest(). The options field is a bit map of options, so OR in
AF_ACK_REQUEST to enable APS ACK for the message that you are sending. The number of times that the
message is retried (if APS ACK message isn’t received) and the timeout between retries are configuration items in
f8wConfig.cfg. APSC_MAX_FRAME_RETRIES is the number of retries the APS layer will send the
message if it doesn’t receive an APS ACK before giving up. APSC_ACK_WAIT_DURATION_POLLED is the time
between retries.
9. Miscellaneous
9.1 Configuring channel
Every device must have a DEFAULT_CHANLIST (in f8wConfig.cfg) that controls the channel selection. For a
ZigBee Coordinator, this list will be used to scan for a channel with the least amount of noise. For ZigBee Routers
and End Devices, this list will be used to scan for existing networks to join.
For further control of the joining procedure, the ZDO_NetworkDiscoveryConfirmCB function in the
ZDApp.c should be modified. ZDO_NetworkDiscoveryConfirmCB() is called when the network layer has
finished with the Network Discovery process, started by calling NLME_NetworkDiscoveryRequest()
defined in the Z-Stack API [2] document.
typedef struct
{
uint8 kvp;
APSDE_DataReqMTU_t aps;
} afDataReqMTU_t;
Currently the only field that should be set in the afDataReqMTU_t structure is kvp, which indicates whether
KVP is being used and this field should be set to FALSE. The aps field is reserved for future use.
In version R20 of the ZigBee PRO specification [1], processing of “NWK Leave Request” is configurable for
Routers. The application controls this feature by setting the zgNwkLeaveRequestAllowed variable to TRUE
(default value) or FALSE, to allow/disallow a Router to leave the network when a “NWK Leave Request” is
9.5 Descriptors
All devices in a ZigBee network have descriptors that describe the type of device and its applications. This
information is available to be discovered by other devices in the network.
Configuration items are setup and defined in ZDConfig.c and ZDConfig.h. These 2 files also contain the
Node, Power Descriptors and default User Descriptor. Make sure to change these descriptors to define your device.
To enable this feature include the NV_RESTORE compile option. Note that this feature must usually be always
enabled in a real ZigBee network. The ability to turn it off is only intended to be used in the development stage.
The ZDO layer is responsible for the saving and restoring of the Network Layer’s vital information. This includes
the Network Information Base (NIB - Attributes required to manage the network layer of the device); the list of
child and parent devices, and the table containing the application bindings. Also, if security is used, some
information like the frame counters will be stored.
This information is used to restore the device in the network if the device is reset. In ZDApp_Init(), a call to
NLME_RestoreFromNV() instructs the network layer to restore its network state from values stored in NV. This
function call will also initialize the NV space needed for the network layer if the space isn’t already established.
Remember: the NV items are each unique and if your application creates its own NV item is must select an ID from
the application value range (0x0401 – 0x0FFF).
In ZigBee PRO, this problem is overcome by the use of the Network Link Status message. Every router in a ZigBee
PRO network sends a periodic Link Status message. This message is a one hop broadcast message that contains the
sending device’s neighbor list. The idea is this – if you receive your neighbor’s Link Status and you are either
missing from the neighbor list or your receive cost is too low (in the list), you can assume that the link between you
and this neighbor is an asynchronous link and you should not use it for routing.
To change the time between Link Status messages you can change the compile flag
NWK_LINK_STATUS_PERIOD, which is used to initialize _NIB.nwkLinkStatusPeriod. You can also
change _NIB.nwkLinkStatusPeriod directly. Remember that only PRO routers send the link status message
and that every router in the network must have the same Link Status time period.
Another parameter that affects the Link Status message is _NIB.nwkRouterAgeLimit (defaulted to
NWK_ROUTE_AGE_LIMIT). This represents the number of Link Status periods that a router can remain in a
device’s neighbor list, without receiving a Link Status from that device, before it becomes aged out of the list. If we
haven’t received a Link Status message from a neighbor within (_NIB.nwkRouterAgeLimit *
_NIB.nwkLinkStatusPeriod), we will age the neighbor out and assume that this device is missing or that it’s
an asynchronous link and not use it.
A multicast message is sent from a device to a group as a MAC broadcast message. The receiving device will
determine if it is part of that group: if it isn’t part of the group, it will decrement the non-member radius and
rebroadcast; if it is part of the group it will first restore the group radius and then rebroadcast the message. If the
radius is decremented to 0, the message isn’t rebroadcast.
The difference between multicast and APS group messages can only be seen in very large networks where the non-
member radius will limit the number of hops away from the group.
_NIB.nwkUseMultiCast is used by the network layer to enable multicast (default is TRUE if ZIGBEEPRO
defined) for all Group messages, and if this field is FALSE the APS Group message is sent as a normal broadcast
network message.
zgApsNonMemberRadius is the value of the group radius and the non-member radius. This variable should be
controlled by the application to control the broadcast distribution. If this number is too high, the effect will be the
same as an APS group message. This variable is defined in ZGlobals.c and
ZCD_NV_APS_NONMEMBER_RADIUS (defined in ZComDef.h) is the NV item.
9.9 Fragmentation
Message Fragmentation is a process where a large message – too large to send in one APS packet – is broken down
and transmitted as smaller fragments. The fragments of the larger message are then reassembled by the receiving
device.
To turn on the APS Fragmentation feature in your Z-Stack project include the ZIGBEE_FRAGMENTATION
compile flag. By default, all projects where ZIGBEEPRO is defined include fragmentation and there is no need to
add the ZIGBEE_FRAGMENTATION compile flag. All applications using fragmentation will include the APS
Fragmentation task APSF_Init() and APSF_ProcessEvent(). If you have an existing application, make
sure the code in the OSAL_xxx.c of your application has included the header file:
And in tasksArr[] there is an entry for APSF_ProcessEvent(), like in the example below:
macTaskInit( taskID++ );
nwk_init( taskID++ );
Hal_Init( taskID++ );
#if defined( MT_TASK )
MT_TaskInit( taskID++ );
#endif
APS_Init( taskID++ );
#if defined ( ZIGBEE_FRAGMENTATION )
APSF_Init( taskID++ );
#endif
ZDApp_Init( taskID++ );
#if defined ( ZIGBEE_FREQ_AGILITY ) || defined ( ZIGBEE_PANID_CONFLICT )
ZDNwkMgr_Init( taskID++ );
#endif
xxx_Init( taskID ); /* Where xxx is your application’s name */
}
When APS Fragmentation is turned on, sending a data request with a payload larger than a normal data request
payload will automatically trigger fragmentation.
Fragmentation parameters are in the structure afAPSF_Config_t, which is part of the Endpoint Descriptor list
epList_t defined in AF.h, default values for these parametes are used when calling afRegister(), to register
the Application’s Endpoint Descriptor, which in turn calls afRegisterExtended(), the default values
APSF_DEFAULT_WINDOW_SIZE and APSF_DEFAULT_INTERFRAME_DELAY are defined in ZGlobals.h:
APSF_DEFAULT_WINDOW_SIZE - The size of a Tx window when using fragmentation. This is the
number of fragments that are sent before an APS Fragmentation ACK is expected. So, if the message is
broken up into 10 fragments and the max window size is 5, then an ACK will be sent by the receiving
device after 5 fragments are received. If one packet of the window size isn’t received, the ACK is not sent
and all the packets (within that window) are resent.
APSF_DEFAULT_INTERFRAME_DELAY – The delay between fragments within a window. This is used
by the sending device.
These values can be read and set by the application by calling afAPSF_ConfigGet() and
afAPSF_ConfigSet() respectively.
When a device starts up, it checks the value of zgExtendedPANID. If zgExtendedPANID has a non-zero
value, then the device assumes it has all the network parameters required to operate on a network.
If the device finds it is not connected to a network, then it checks to see if it’s configured to become a ZigBee
Coordinator. If it’s configured as a coordinator, then it will form a network using zgApsUseExtendedPANID if
zgApsUseExtendedPANID has a non-zero value. If zgApsUseExtendedPANID is 0x0000000000000000,
then the device will use its 64-bit Extended Address to form the network.
When the device is not the designated coordinator and zgApsUseExtendedPANID has a non-zero value, then it
will attempt to rejoin the network specified in zgApsUseExtendedPANID. The device will join only the
specified network and the procedure will fail if that network is found to be inaccessible. If
zgApsUseExtendedPANID is equal to 0x0000000000000000, then the device will join the best available
network.
If configuration element zgNwkCommissionedNwkAddr has a valid short address value during the rejoin
process, the device will put it in the _NIB.nwkDevAddress and use that in the Rejoin Request, otherwise it will
randomly generate the short address and use it in the Rejoin Request.
10. Security
10.1 Overview
ZigBee security is built with the AES block cipher and the CCM* mode of operation as the underlying security
primitive. AES/CCM* security algorithms were developed by external researchers outside of ZigBee Alliance and
are also used widely in other communication protocols.
10.2 Configuration
In order to have a secure network, first all device images must be built with the preprocessor flag SECURE set equal
to 1. This can be found in the f8wConfig.cfg file.
The default key (defaultKey in nwk_globals.c) can be preconfigured on each device in the network or it can
be configured only on the coordinator and distributed to each device over-the-air as it joins the network. This is
chosen via the zgPreConfigKeys option in ZGlobals.c file. If it is set to TRUE, then the value of default key
must be preconfigured on each device (to the exact same value). If it is set to FALSE, then the default key parameter
needs to be set only on the coordinator device. Note that in the latter case, the key will be distributed to each joining
device over-air. So there is a “moment of vulnerability” during the joining process during which an adversary can
determine the key by listening to the on-air traffic and compromise the network security.
The Trust Center may use any logic to determine if the device should be allowed into the network or not. One option
is for the Trust Center to only allow devices to join during a brief time window. This may be possible, for example,
if the Trust Center has a “push” button. When the button is pressed, it could allow any device to join the network for
a brief time window. Otherwise all join requests would be rejected. A second possible scenario would be to
configure the trust center to accept (or reject) devices based on their IEEE addresses.
This type of policy can be realized by modifying the ZDSecMgrDeviceValidate() function found in the
ZDSecMgr.c module.
There are two types of Link Keys that can be used in a network: UNIQUE and GLOBAL. The type of Link Key
used by the local device will determine how APS commands are handled as well the encryption used for those
messages.
To enable all TCLK processing code, either the TC_LINKKEY_JOIN or the SE_PROFILE compiler flag shall be
defined in the project. The application can control the type of Link Key by setting zgApsLinkKeyType, in
ZGlobals.h, to value ZG_GLOBAL_LINK_KEY or ZG_UNIQUE_LINK_KEY. The corresponding NV item for
zgApsLinkKeyType is ZCD_NV_APS_LINK_KEY_TYPE.
10.6.1 Multi-hop
When a device joins the network, but its parent isn’t the Trust Center, the transport key command is tunneled from
the Trust Center, through the parent of the joining device, to the joining device. The joining procedure is illustrated
in the following figures. Notice that the APS Update Device command sent from the parent to the trust center will be
encrypted according to the zgApsLinkKeyType configuration and using the highest APS security level. The APS
Tunnel Command with APS Transport Key command as the payload is network layer encrypted but the payload is
APS layer encrypted with the trust center link key between the trust center and the joining device. Finally, The APS
Transport Key command forwarded from the parent to the joining device is APS encrypted with the trust center link
key between the trust center and the joining device.
Figure 5: Unique Link Key Type – Joining when parent is not the Trust Center
Figure 6: Global Link Key Type – Joining when parent is not the Trust Center
10.6.2 Single-hop
When a device joins the network, and its parent is the Trust Center, the transport key command is encrypted with the
pre-configured Trust Center Link key.
Figure 7: Global/Unique Link Key Type – Joining when parent is the Trust Center
To enable the TCLK Joining feature, set SECURE=1 in f8wConfig.cfg and include the TC_LINKKEY_JOIN
or the SE_PROFILE compile flag. There are other associated compiler flags, global variables (ZGlobals) and NV
Items.
If zgApsLinkKeyType is set to ZG_UNIQUE_LINK_KEY, unique pre-configured trust center link keys are used
between the Trust Center and each individual device joining the network. If zgApsLinkKeyType is set to
ZG_GLOBAL_LINK_KEY, all devices are using the same pre-configured trust center link key to join the network.
The Global Link Key Type provides a simplified alternative procedure to set up the network.
Value The data array to be written to the Its byte format is listed in the following table. All
NV item. fields follow little endian first.
Attribute Field Extended Address Key Data Tx Frame Counter Rx Frame Counter
To remove a preconfigured trust center link key, simply write all zeros to the NV item.
It is highly recommended to erase the entire flash before using Unique Link Keys to make sure there is no
existing NV item for the preconfigured trust center link keys.
Please note that the Unique Link Key and Global Link Key shall be used exclusively.
NV IDs for security keys are defined in ZComDef.h and summarized in the table below. Active and Alternate
Network keys are defined as individual items, while Trust Center, Application and Master keys each reserve a range
of NV IDs, allowing up to 255 keys of each type.
Value NV ID Description
ZCD_NV_NWK_ACTIVE_KEY_INFO 0x003A Active Network key
ZCD_NV_NWK_ALTERN_KEY_INFO 0x003B Alternate Network Key
ZCD_NV_TCLK_TABLE_START 0x0101 First element of TCLK table
ZCD_NV_TCLK_TABLE_END 0x01FF Last element of TCLK table
ZCD_NV_APS_LINK_KEY_DATA_START 0x0201 First element of APS Link Key table
ZCD_NV_APS_LINK_KEY_DATA_END 0x02FF Last element of APS Link Key table
ZCD_NV_MASTER_KEY_DATA_START 0x0301 First element of Master Key table
ZCD_NV_MASTER_KEY_DATA_END 0x03FF Last element of Master Key table
The default address of the Network Manager is the coordinator. However, this can be updated by sending a
Mgmt_NWK_Update_req command with a different short address for the Network Manager. The device that is the
Network Manager sets the network manager bit in the server mask in the node descriptor and responds to
System_Server_Discovery_req commands.
a. Select a single channel based on the Mgmt_NWK_Update_notify based on the lowest energy.
This is the proposed new channel. If this new channel does not have an energy level below an
acceptable threshold ZDNWKMGR_ACCEPTABLE_ENERGY_LEVEL, a channel change
should not be done.
3. Prior to changing channels, the Network Manager stores the energy scan value as the last energy scan
value and the failure rate from the existing channel as the last failure rate.
4. The Network Manager broadcasts (to all routers and coordinator) a Mgmt_NWK_Update_req notifying
devices of the new channel. It then increments the nwkUpdateId parameter in the NIB and beacon
payload, and includes it in the Mgmt_NWK_Update_req. The Network Manager sets a timer based on
the value of ZDNWKMGR_UPDATE_REQUEST_TIMER (i.e., apsChannelTimer) upon issue of a
Mgmt_NWK_Update_req that changes channels and will not issue another such command until this
timer expires.
5. Upon issue of a Mgmt_NWK_Update_req with a change of channels, the local Network Manager sets a
timer equal to the nwkNetworkBroadcastDeliveryTime and switches channels upon expiration of this
timer.
Upon receipt of a Mgmt_NWK_Update_req with a change of channels from the Network Manager, a device sets a
timer equal to the nwkNetworkBroadcastDeliveryTime and switches channels upon expiration of this timer. Each
node stores the received nwkUpdateId in the NIB and beacon payload, and also resets the total transmit count and
the transmit failure counters.
For devices with RxOnWhenIdle equals FALSE, any network channel change will not be received. On these devices
or routers that have lost the network, an active scan is conducted on the channelList in the NIB (i.e.,
apsChannelMask) using the extended PAN ID (EPID) to find the network. If the extended PAN ID is found on
different channels, the device selects the channel with the higher value in the nwkUpdateId parameter. If the
extended PAN ID is not found using the apsChannelMask list, a scan is completed using all channels.
A node that has detected a PAN ID conflict sends a Network Report command of type PAN ID conflict to the
designated Network Manager identified by the nwkManagerAddr in the NIB. The Report Information field will
contain a list of all the 16-bit PAN identifiers that are being used in the local neighborhood. The list is constructed
from the results of an ACTIVE scan.
Once a new PAN ID has been selected, the Network Manager first increments the NIB attribute nwkUpdateID and
then constructs a Network Update command of type PAN identifier update. The Update Information field is set to
the value of the new PAN ID. After it sends out this command, the Network Manager starts a timer with a value
equal to nwkNetworkBroadcastDeliveryTime seconds. When the timer expires, it changes its current PAN ID to the
newly selected one.
On receipt of a Network Update command of type PAN ID update from the Network Manager, a device (in the same
network) starts a timer with a value equal to nwkNetworkBroadcastDeliveryTime seconds. When the timer expires,
the device changes its current PAN ID to the value contained within the Update Information field. It also stores the
new received nwkUpdateID in the NIB and beacon payload.
The Inter-PAN feature is implemented by the Stub APS layer, which can be included in a project by defining the
INTER_PAN compile option and including stub_aps.c and stub_aps.h files in the project.
The Stub APS layer also provides interfaces to switch channel for Inter-PAN communication and check for Inter-
PAN messages. Please refer to the Z-Stack API [2] document for detailed description of the Inter-PAN APIs.
The StubAPS_InterPan() API is used to check for Inter-PAN messages. A message is considered as an Inter-
PAN message if it meets one the following criteria:
The current communication channel is different that the device’s NIB channel, or
The current communication channel is the same as the device’s NIB channel but the message is destined for
a PAN different than the device’s NIB PAN ID, or
The current communication channel is the same as the device’s NIB channel and the message is destined
for the same PAN as device’s NIB PAN ID but the destination application endpoint is an Inter-PAN
endpoint (0xFE). This case is true for an Inter-PAN response message that’s being sent back to a requestor.
A typical usage scenario for Inter-PAN communication is as follows. The initiator device:-
Calls StubAPS_AppRegister() API to register itself with the Stub APS layer
Calls StubAPS_SetInterPanChannel() API to switch its communication channel to the channel in
use by the remote device
Specifies the destination PAN ID and address for the Inter-PAN message about to be transmitted
Calls AF_DataRequest() API to send the message to the remote device through Inter-PAN channel
Receives back (if required) a message from the remote device that implements the Stub APS layer and is
able to respond
Calls StubAPS_SetIntraPanChannel() API to switch its communication channel back to its
original channel
The TI MAC computes an 8-bit “link quality index” (LQI) for each received packet from the 2.4 GHz radio. The
LQI is computed from the raw “received signal strength index” (RSSI) by linearly scaling it between the minimum
and maximum defined RF power levels for the radio. This provides an LQI value that is based entirely on the
strength of the received signal. This can be misleading in the case of a narrowband interferer that is within the
channel bandwidth – the RSSI may be increased even though the true link quality decreases.
The TI radios also provide a “correlation value” that is a measure of the received frame quality. Although not
considered by the TI MAC in LQI calculation, the frame correlation is passed to the ZMAC layer (along with LQI
and RSSI) in MCPS data confirm and data indication callbacks. The ZMacLqiAdjust() function in
zmac_cb.c provides capability to adjust the default TI MAC value of LQI by taking the correlation into account.
MODE1 provides a simple algorithm to use the packet correlation value (related to SNR) to scale incoming LQI
value (related to signal strength) to 'de-rate' noisy packets. The incoming LQI value is linearly scaled with a
"correlation percentage" that is computed from the raw correlation value between theoretical minimum/maximum
values (LQI_CORR_MIN and LQI_CORR_MAX are defined in ZMAC.h).
MODE2 provides a “stub” for developers to implement their own proprietary algorithm. Code can be added after the
“else if ( lqiAdjMode == LQI_ADJ_MODE2 )” statement in ZMacLqiAdjust().
The ZMacLqiAdjustMode() function can be used to change the LQI adjustment mode as needed by the
application. For example, a developer might want to evaluate device/network operation using a proprietary MODE2
compared to the default MODE1 or OFF.
Tuning of MODE1 operation can be achieved by altering the values of LQI_CORR_MIN and/or LQI_CORR_MAX.
When using IAR development tools, alternate values for these parameters can be provided as compiler directives in
the IDE project file or in one of Z-Stack’s .cfg files (f8wConfig.cfg, f8wCoord.cfg, etc.). Refer to the
radio’s data sheet for information on the normal minimum/maximum correlation values.
14.1 Overview
The OSAL heap memory manager provides a POSIX-like API for allocating and re-cycling dynamic heap memory.
Two important considerations in a low-cost, resource-constrained embedded system, size and speed, have been duly
addressed in the implementation of the heap memory manager.
Overhead memory cost to manage each allocated block has been minimized – as little as 2 bytes on CPU’s
with one- or two-byte-aligned memory access (e.g. 8051 SOC and MSP430).
Interrupt latency for the allocation and free operations has been minimized – freeing is immediate with no
computational load other than bounds checks and clearing a bit; allocating is very much sped-up with a
packed long-lived memory block and a dynamically updated first-free pointer for high-frequency small-
block allocations (e.g. OSAL Timers).
14.2 API
14.2.1 osal_mem_alloc()
The osal_mem_alloc() function is a request to the memory manager to reserve a block of the heap.
14.2.1.1 Prototype
14.2.1.2 Parameters
14.2.1.3 Return
If a big enough free block is found, the function returns a void pointer to the RAM location of the heap memory
reserved for use. A NULL pointer is returned if there isn’t enough memory to allocate. Any non-NULL pointer
returned must be freed for re-use by invoking osal_mem_free().
14.2.2 osal_mem_free()
The osal_mem_free() function is a request to the memory manager to release a previously reserved block of the
heap so that the memory can be re-used.
14.2.2.1 Prototype
14.2.2.2 Parameters
ptr – a pointer to the buffer to release for re-use – this pointer must be the non-NULL pointer that was returned by
a previous call to osal_mem_alloc().
14.2.2.3 Return
None.
14.3 Strategy
Memory management should strive to maintain contiguous free space in the heap, in as few blocks as possible, with
each block as big as possible. Such a general strategy helps to ensure that requests for large memory blocks always
succeed if the total heap size has been set properly for the application’s use pattern.
Memory allocation is not penalized by having to traverse long-lived heap allocations if the system
initialization is implemented as recommended within this guide.
Memory allocation for small-blocks almost always begins searching at the first free block in the heap.
Memory allocation attempts to coalesce all contiguous free blocks traversed in an attempt to form a single
free block large enough for an allocation request.
Memory allocation uses the first free block encountered (or created by coalescing) that is big enough to
meet the request; the memory block is split if it is usefully bigger than the requested allocation.
14.4 Discussion
It is immediately after system task initialization that the effective “start of the heap” mark is set to be the first free
block. Since the memory manager always starts a “walk”, looking for a large enough free block, from the
aforementioned mark, it will greatly reduce the run-time overhead of the walk if all long-lived heap allocations are
packed at the start of the heap so that they will not have to be traversed on every memory allocation. Therefore, any
application should make all long-lived dynamic memory allocations in its respective system initialization routine
(e.g. XXX_Init(), where XXX is the Application Name). Within said system initialization routines, the long-lived
items must be allocated before any short-lived items. Any short-lived items allocated must be freed before returning,
otherwise the long-lived bucket may be fragmented and the run-time throughput adversely affected proportionally to
the number of long-lived items that the OSAL_Memory module is forced to iterate over for every allocation for the
rest of the life of the system. As an example, if the system initialization function starts an OSAL Timer
(osal_start_timerEx()), this may fragment the long-lived bucket because the memory allocated for the timer
will be freed and re-used throughout the life of the system (even if coincidence happens that every free and re-use is
simply for resetting the same timer.) The recommended solution in this case would be to set the event corresponding
to the timer (osal_set_event ()) and then continue to restart the timer as appropriate in the application’s
event handle for the corresponding event (refer to the behavior of the hal_key polling timer and corresponding
event, HAL_KEY_EVENT). On the other hand, a reload timer (osal_start_reload_timer()) is a long-lived
allocation and is recommended to be started during system initialization of all other long-lived items.
The application implementer must ensure that their use of dynamic memory does not adversely affect the operation
of the underlying layers of the Z-Stack. The Z-Stack is tested and qualified with sample applications that make
minimal use of heap memory. Thus, the user application that uses significantly more heap than the sample
applications, or the user application that is built with a smaller value set for MAXMEMHEAP than is set in the sample
applications, may inadvertently starve the lower layers of the Z-Stack to the point that they cannot function
effectively or at all. For example, an application could allocate so much dynamic memory that the underlying layers
of the stack would be unable to allocate enough memory to send and/or receive any OTA messages – the device
would not be seen to be participating OTA.
14.5 Configuration
14.5.1 MAXMEMHEAP
The MAXMEMHEAP constant is usually defined in OnBoard.h. It must be defined to be less than 32768.
MAXMEMHEAP is the number of bytes of RAM that the memory manager will reserve for the heap – it cannot be
changed dynamically at runtime – it must be defined at compile-time. If MAXMEMHEAP is defined to be greater than
or equal to 32768, a compiler error in OSAL_Memory.c will trigger. MAXMEMHEAP does not reflect the total
amount of dynamic memory that the user can expect to be usable because of the overhead cost per memory
allocation.
14.5.2 OSALMEM_PROFILER
The OSALMEM_PROFILER constant is defined locally in OSAL_Memory.c to be FALSE by default.
After the implementation of a user application is mature, the OSAL memory manager may need to be re-tuned in
order to achieve optimal run-time performance with regard to the MAXMEMHEAP and OSALMEM_SMALL_BLKSZ
constants defined. The code enabled by defining the OSALMEM_PROFILER constant to TRUE allows the user to
gather the empirical, run-time results required to tune the memory manager for the application. The profiling code
does the following.
14.5.2.1 OSALMEM_INIT
The memory manager initialization sets all of the bytes in the heap to the value of OSALMEM_INIT.
14.5.2.2 OSALMEM_ALOC
The user available bytes of any block allocated are set to the value of OSALMEM_ALOC.
14.5.2.3 OSALMEM_REIN
Whenever a block is freed, what had been the user available bytes are set to the value of OSALMEM_REIN.
14.5.2.4 OSALMEM_PROMAX
OSALMEM_PROMAX is the number of different bucket sizes to profile. The bucket sizes are defined by an array:
The bucket sizes profiled should be set according to the application being tuned, but the last bucket must always be
65535 as a catch-all. There are 3 metrics kept for each bucket.
proCur – the current number of allocated blocks that fit in the corresponding bucket size.
proMax – the maximum number of allocated blocks that corresponded to the bucket size at once.
proTot – the total number of times that a block was allocated that corresponded to the bucket size.
In addition, there is a count kept of the total number of times that the part of heap reserved for “small blocks” was
too full to allow a requested small-block allocation: proSmallBlkMiss.
14.5.3 OSALMEM_MIN_BLKSZ
The OSALMEM_MIN_BLKSZ constant is defined locally in OSAL_Memory.c.
OSALMEM_MIN_BLKSZ is the minimum size in bytes of a block that is created by splitting a free block into two
new blocks. The 1st new block is the size that is being requested in a memory allocation and it will be marked as in
use. The 2nd block is whatever size is leftover and it will be marked as free. A larger number may result in
significantly faster overall runtime of an application without necessitating any more or not very much more overall
heap size. For example, if an application made a very large number of inter-mixed, short-lived memory allocations
of 2 & 4 bytes each, the corresponding blocks would be 4 & 6 bytes each with overhead. The memory manager
could spend a lot of time thrashing, as it were, repeatedly splitting and coalescing the same general area of the heap
in order to accommodate the inter-mixed size requests.
14.5.4 OSALMEM_SMALL_BLKSZ
The OSALMEM_SMALL_BLKSZ constant is defined locally in OSAL_Memory.c.
The heap memory use of the Z-Stack was profiled using the GenericApp Sample Application and it was empirically
determined that the best worst-case average combined time for a memory allocation and free, during a heavy OTA
load, can be achieved by splitting the free heap into two sections. The first section is reserved for allocations of
smaller-sized blocks and the second section is used for larger-sized allocations as well as for smaller-sized
allocations if and when the first section is full. OSALMEM_SMALL_BLKSZ is the maximum block size in bytes that
can be allocated from the first section.
14.5.5 OSALMEM_SMALLBLK_BUCKET
The OSALMEM_SMALLBLK_BUCKET constant is locally defined in OSAL_Memory.c.
OSALMEM_SMALLBLK_BUCKET is the number of bytes dedicated to the previously described first section of the
heap which is reserved for smaller-sized blocks.
14.5.6 OSALMEM_NODEBUG
The OSALMEM_NODEBUG constant is locally defined in OSAL_Memory.c to be TRUE by default.
The Z-Stack and Sample Applications do not misuse the heap memory API. The onus to be equally correct is on the
user application: in order to provide the minimum throughput latency possible, there are no run-time checks for
correct use of the API. An application can be shown to be correct by defining the OSALMEM_NODEBUG constant to
FALSE. Such a setting will enable code that traps on the following misuse scenario.
14.5.7 OSALMEM_PROFILER_LL
The OSALMEM_PROFILER_LL constant is defined locally in OSAL_Memory.c to be FALSE by default.
Normally, the allocations that are packed into the Long-Lived bucket by all of the system initialization should not be
counted during “profiling” because they are not iterated over during run-time. But, in order to properly tune the size
of the Long-Lived bucket for any given Application, this constant should be used for one run on the debugger with a
mature implementation. The numbers used in the following example are for the 8051 SOC, GenericApp, with out-
of-the-box settings and thus using this default:
a. ff1 = tmp – 1;
3. Inspect the variable proCur in an IAR ‘Watch’ window and sum the counts of all of the buckets (19 in
this example) and plug it into the formula above – this is the count of long-lived items.
4. Subtract the value of ff1 (0x1095 in one particular run) from the location of theHeap (0x0ECE in that same
run) and then subtract the sub-total of the count of long-lived items multiplied by the OSALMEM_HDRSZ
(19 * 2 = 38 for this example.)
Further memory profiling should now be done with OSALMEM_PROFILER_LL set back to FALSE so as not to
count the long-lived allocations in the statistics.
15.1 Overview
This section provides information and procedures for using compiler options with Texas Instruments Z-Stack™, and
it's recommend that you don't change compile flags that aren't listed in this section.
15.2 Requirements
15.2.1 Target Development System Requirements
Z-Stack is built on top of the IAR Embedded Workbench suite of software development tools (www.iar.com). These
tools support project management, compiling, assembling, linking, downloading, and debugging for various
development platforms. The following are required support for the Z-Stack target development system:
Platform/Target Compiler/Tool
EXP5438 + CC2520 IAR EW430
SmartRF05EB + CC2530 IAR EW8051
SmartRF06EB + CC2538 IAR EWARM
ZigBee Coordinator – This device is configured to start the IEEE 802.15.4 network and will serve as the
PAN Coordinator in that network.
ZigBee Router – This device is configured to associate with a ZigBee Coordinator, then allow other routers
or end devices to associate with it. It will route data packets in the network.
ZigBee End Device – This device is configured to join a pre-existing network and will associate with a
ZigBee Coordinator or ZigBee Router.
Open the project by double-clicking on the GenericApp.eww file, select the CoordinatorEB configuration from the
pull-down list below Workspace, and then open the Tools folder. Several linker control files are located in the
Tools folder. This folder contains various configuration files and executable tools used in Z-Stack projects. Generic
compile options are defined in the f8wConfig.cfg file. This file, for example, specifies the channel(s) and the
PAN ID that will be used when a device starts up. This is the recommended location for a user to establish specific
channel settings for their projects. This allows developers set up “personal” channels to avoid conflict with others.
Device specific compile options are located in the f8wCoord.cfg, f8wEndev.cfg, and f8wRouter.cfg
files:
The GenericApp Coordinator project uses the f8wCoord.cfg file. As shown below, compile options that are
specific to Coordinator devices and options that provide “generic” Z-Stack functions are included in this file:
The f8wCoord.cfg file is used by all projects that build Coordinator devices. Therefore, any change made to this
file will affect all Coordinators. In a similar manner, the f8wRouter.cfg and f8wEnd.cfg files affect all
Router and End-Device projects, respectively.
To add a compile option to all projects of a certain device type, simply add a new line to the appropriate linker
control file. To disable a compile option, comment that option out by placing // at the left edge of the line. You could
also delete the line but this is not recommended since the option might need to be re-enabled at a later time.
The compile options for each of the supported configurations are stored in the GenericApp.ewp file. To modify these
compile options, first select GenericApp – CoordinatorEB. Then select the Options… item from the Project pull-
down menu:
Select the C/C++ Compiler item and click on the Preprocessor tab. The compile options for this configuration are
located in the box labeled Defined symbols: (one per line):
To add a compile option to this configuration, simply add the item on a new line within this box. To disable a
compile option, place an ‘x’ at the left edge of the line. Note that the ZTOOL_P1 option has been disabled in the
example shown above. This option could have been deleted but this is not recommended since it might need to be
re-enabled at a later time.
Compile options are used to select features that are provided in the source files. Most compile options act as on/off
switches for specific sections within source programs. Some options are used to provide a user-defined numerical
value, such as DEFAULT_CHANLIST, to the compiler to override default values.
Each of the Z-Stack sample applications (ex. GenericApp) provide an IAR project file which specifies the compile
options to be used for that specific project. The programmer can add or remove options as needed to include or
exclude portions of the available software functions. Note that changing compile options may require other changes
to the project file (see 15.3.2). For example, adding the MT_NWK_FUNC option requires MT_NWK.c to be in the list
of source files in the configuration of the device you are building.
The next sections of this document provide lists of the supported compile options with a brief description of what
feature they enable or disable. Options that are listed as “do not change” are required for proper operation of the
compiled programs. Options that are listed as “do not use” are not appropriate for use with the board.
The compile options in the following table can be changed or set to select desired features, a lot of these compile
options are set and described in f8wConfig.cfg.
These compile options in the following table should not be changed or used. Not all of them are available in every
platform:
Please read the Z-Stack Monitor and Test API document before changing any of these compile options. You can
enable the following APIs and function associated with the MT_TASK option, but you must include the MT_TASK
option.
By default, the mandatory messages (as defined by the ZigBee spec) are enabled in the ZDO. All other message
processing is controlled by compile flags. You can enable/disable the options by commenting/un-commenting the
compile flags in ZDConfig.h or include/exclude them like other compile flags. There’s an easy way to enable all
the ZDO Function and Management options: You can use MT_ZDO_FUNC to enable all the ZDO Function options,
and MT_ZDO_FUNC and MT_ZDO_MGMT to enable all the ZDO Function plus Management options. Information
about the use of these messages is provided in this guide and Z-Stack API document.