API for communicating with XBee devices.

Dependencies:   CircularBuffer FixedLengthList

Dependents:   XBeeApiTest XBeeApiSimpleATCmdsExample XBeeApiBroadcastExample XBeeApiBroadcastExampleRTOS ... more

Overview

XBeeApi is intended to be a library for providing a high-level API interface to the XBee - for example getChannel() and setChannel(2) methods rather than needing to send( "ATCH" ) and send( "ATCH 2" ) - and then de-code the responses.

See the notebook page here for a description of how the API works & some details on the various classes.

Features:

  • Support for transmission & reception of data packets
  • Support for reading & changing settings
  • Support for "Remote AT" interface to access settings & I/O channels on remote XBees
  • XBeeApi should work if you're using mbed-rtos, though it is not currently threadsafe. Take a look at the XBeeApiBroadcastExampleRTOS example if you're including mbed-rtos.

Example Programs

There are also example programs available:

Transmit

Import programXBeeApiSimpleBroadcastExample

Simple example of how to use XBeeApi - set up the XBee, configure P2P networking then transmit a frame.

Import programXBeeApiBroadcastExample

Example for XBeeAPI; a little more involved than XBeeApiSimpleBroadcastExample with report on failure to set up the XBee and on the transmit status of the message.

Import programXBeeApiBroadcastExampleRTOS

Example of using the XBeeApi library to broadcast a message, based on XBeeApiBroadcastExample. This example shows how to use the library when using mbed-rtos. Before compiling you must open "XbeeApi\Config\XBeeApiCfg.hpp" and change the '#if 0' to '#if 1' on the line above the comment reading "Use RTOS features to make XBeeApi threadsafe"

Settings/Status

Import programXBeeApiSimpleATCmdsExample

Simple example of using XBeeApi to send AT-style commands to the XBee

Import programXBeeApiRemoteATCmdsExample

Example of using the XBeeApi library to send AT commands to remote XBee devices in order to read/write settings

Receive

Import programXBeeApiSimpleReceiveExample

Simple example of using XBeeApi to receive data packets via wireless

Import programXBeeApiReceiveCallbackExample

Example of using the XBeeApi library to receive a message via a callback method

Import programXBeeApiReceiveCallbackExampleRTOS

Example of using the XBeeApi library to receive a message via a callback method. This example shows how to use the library when using mbed-rtos. See the comment at the top of main.cpp

Remote I/O

Import programXBeeApiRemoteIOExample

Example of using the XBeeApi library to read inputs on a remote XBee

If you have 2 mbed connected XBees available then you can use XBeeApiSimpleReceiveExample and XBeeApiSimpleBroadcastExample as a pair.

Note that this is still a work in progress! XBeeApiTodoList tracks some of the functionality still to be added.

Utility/XBeeApiCmdAt.cpp

Committer:
johnb
Date:
2014-08-08
Revision:
56:7fe74b03e6b1
Parent:
55:610aa4a2ed3b

File content as of revision 56:7fe74b03e6b1:

/**

Copyright 2014 John Bailey

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

#include "XBeeApiCmdAt.hpp"

/* Set of Frame ID codes for the various commands (see XBEE_CMD_POSN_FRAME_ID) */

#define CMD_RESPONSE_GET_VR  '1'
#define CMD_RESPONSE_GET_HV  '2'
#define CMD_RESPONSE_GET_CH  '3'
#define CMD_RESPONSE_SET_CH  '4'
#define CMD_RESPONSE_SET_CE  '5'
#define CMD_RESPONSE_GET_CE  '6'
#define CMD_RESPONSE_SET_EDA '7'
#define CMD_RESPONSE_GET_EDA '8'
#define CMD_RESPONSE_SET_PID '9'
#define CMD_RESPONSE_GET_PID '0'
#define CMD_RESPONSE_SET_MY  'a'
#define CMD_RESPONSE_GET_MY  'b'
#define CMD_RESPONSE_GET_SH  'c'
#define CMD_RESPONSE_GET_SL  'd'
#define CMD_RESPONSE_SET_RR  'e'
#define CMD_RESPONSE_GET_RR  'f'
#define CMD_RESPONSE_SET_RN  'g'
#define CMD_RESPONSE_GET_RN  'h'
#define CMD_RESPONSE_SET_MM  'i'
#define CMD_RESPONSE_GET_MM  'j'
#define CMD_RESPONSE_GET_D0  'k'
#define CMD_RESPONSE_GET_D1  'l'
#define CMD_RESPONSE_GET_D2  'm'
#define CMD_RESPONSE_GET_D3  'n'
#define CMD_RESPONSE_GET_D4  'o'
#define CMD_RESPONSE_GET_D5  'p'
#define CMD_RESPONSE_GET_D6  'q'
#define CMD_RESPONSE_GET_D7  'r'
#define CMD_RESPONSE_SET_D0  's'
#define CMD_RESPONSE_SET_D1  't'
#define CMD_RESPONSE_SET_D2  'u'
#define CMD_RESPONSE_SET_D3  'v'
#define CMD_RESPONSE_SET_D4  'w'
#define CMD_RESPONSE_SET_D5  'x'
#define CMD_RESPONSE_SET_D6  'y'
#define CMD_RESPONSE_SET_D7  'z'
#define CMD_RESPONSE_SET_IC  'A'
#define CMD_RESPONSE_GET_IC  'B'
#define CMD_RESPONSE_SET_IO  'C'
#define CMD_RESPONSE_SET_IR  'D'
#define CMD_RESPONSE_GET_IR  'E'
#define CMD_RESPONSE_SET_DH  'F'
#define CMD_RESPONSE_GET_DH  'G'
#define CMD_RESPONSE_SET_DL  'H'
#define CMD_RESPONSE_GET_DL  'I'
#define CMD_RESPONSE_SET_WR  'J'
#define CMD_RESPONSE_SET_AC  'K'
#define CMD_RESPONSE_SET_FR  'L'
#define CMD_RESPONSE_SET_IS  'M'
#define CMD_RESPONSE_SET_RE  'N'
#define CMD_RESPONSE_SET_KY  'O'
#define CMD_RESPONSE_GET_EE  'P'
#define CMD_RESPONSE_SET_EE  'Q'

/** Lowest channel supported by the XBee S1 */
#define XBEE_CHAN_MIN 0x0b
/** Highest channel supported by the XBee S1 */
#define XBEE_CHAN_MAX 0x1a

/** Lowest channel supported by the XBee S1 Pro */
#define XBEE_PRO_CHAN_MIN 0x0c
/** Highest channel supported by the XBee S1 Pro */
#define XBEE_PRO_CHAN_MAX 0x17

/* Content for the various commands - value of 0 indicates a value to be populated (i.e. variable) */

static const uint8_t cmd_vr[] =       { 'V', 'R' };
static const uint8_t cmd_vr_get_fid = CMD_RESPONSE_GET_VR;

static const uint8_t cmd_hv[] =       { 'H', 'V' };
static const uint8_t cmd_hv_get_fid = CMD_RESPONSE_GET_HV;

static const uint8_t cmd_sh[] =       { 'S', 'H' };
static const uint8_t cmd_sh_get_fid = CMD_RESPONSE_GET_SH;

static const uint8_t cmd_sl[] =       { 'S', 'L' };
static const uint8_t cmd_sl_get_fid = CMD_RESPONSE_GET_SL;

static const uint8_t cmd_ch[] =       { 'C', 'H' };
static const uint8_t cmd_ch_get_fid = CMD_RESPONSE_GET_CH;
static const uint8_t cmd_ch_set[] =   { 'C', 'H', 0 };
static const uint8_t cmd_ch_set_fid = CMD_RESPONSE_SET_CH;

static const uint8_t cmd_ce[] =       { 'C', 'E' };
static const uint8_t cmd_ce_get_fid = CMD_RESPONSE_GET_CE;
static const uint8_t cmd_ce_set[] =   { 'C', 'E', 0 };
static const uint8_t cmd_ce_set_fid = CMD_RESPONSE_SET_CE;

static const uint8_t cmd_eda[] =       { 'A', '1' };
static const uint8_t cmd_eda_get_fid = CMD_RESPONSE_GET_EDA;
static const uint8_t cmd_eda_set[]   = { 'A', '1', 0 };
static const uint8_t cmd_eda_set_fid = CMD_RESPONSE_SET_EDA;

static const uint8_t cmd_pid[] =       { 'I', 'D' };
static const uint8_t cmd_pid_get_fid = CMD_RESPONSE_GET_PID;
static const uint8_t cmd_pid_set[] =   { 'I', 'D', 0, 0 };
static const uint8_t cmd_pid_set_fid = CMD_RESPONSE_SET_PID;

static const uint8_t cmd_my[] =        { 'M', 'Y' };
static const uint8_t cmd_my_get_fid =  CMD_RESPONSE_GET_MY;
static const uint8_t cmd_my_set[] =    { 'M', 'Y', 0, 0 };
static const uint8_t cmd_my_set_fid =  CMD_RESPONSE_SET_MY;

static const uint8_t cmd_rr[] =        { 'R', 'R' };
static const uint8_t cmd_rr_get_fid =  CMD_RESPONSE_GET_RR;
static const uint8_t cmd_rr_set[] =    { 'R', 'R', 0 };
static const uint8_t cmd_rr_set_fid =  CMD_RESPONSE_SET_RR;

static const uint8_t cmd_rn[] =        { 'R', 'N' };
static const uint8_t cmd_rn_get_fid =  CMD_RESPONSE_GET_RN;
static const uint8_t cmd_rn_set[] =    { 'R', 'N', 0 };
static const uint8_t cmd_rn_set_fid =  CMD_RESPONSE_SET_RN;

static const uint8_t cmd_mm[] =        { 'M', 'M' };
static const uint8_t cmd_mm_get_fid =  CMD_RESPONSE_GET_MM;
static const uint8_t cmd_mm_set[] =    { 'M', 'M', 0 };
static const uint8_t cmd_mm_set_fid =  CMD_RESPONSE_SET_MM;

static const uint8_t cmd_ic[] =        { 'I', 'C' };
static const uint8_t cmd_ic_get_fid =  CMD_RESPONSE_GET_IC;
static const uint8_t cmd_ic_set[] =    { 'I', 'C', 0 };
static const uint8_t cmd_ic_set_fid =  CMD_RESPONSE_SET_IC;

static const uint8_t cmd_io_set[] =    { 'I', 'O', 0 };
static const uint8_t cmd_io_set_fid =  CMD_RESPONSE_SET_IO;

static const uint8_t cmd_ir[] =        { 'I', 'R' };
static const uint8_t cmd_ir_get_fid =  CMD_RESPONSE_GET_IR;
static const uint8_t cmd_ir_set[] =    { 'I', 'R', 0, 0 };
static const uint8_t cmd_ir_set_fid =  CMD_RESPONSE_SET_IR;

static const uint8_t cmd_dh[] =        { 'D', 'H' };
static const uint8_t cmd_dh_get_fid =  CMD_RESPONSE_GET_DH;
static const uint8_t cmd_dh_set[] =    { 'D', 'H', 0, 0, 0, 0 };
static const uint8_t cmd_dh_set_fid =  CMD_RESPONSE_SET_DH;

static const uint8_t cmd_dl[] =        { 'D', 'L' };
static const uint8_t cmd_dl_get_fid =  CMD_RESPONSE_GET_DL;
static const uint8_t cmd_dl_set[] =    { 'D', 'L', 0, 0, 0, 0 };
static const uint8_t cmd_dl_set_fid =  CMD_RESPONSE_SET_DL;

static const uint8_t cmd_wr[] =        { 'W', 'R' };
static const uint8_t cmd_wr_set_fid =  CMD_RESPONSE_SET_WR;

static const uint8_t cmd_ac[] =        { 'A', 'C' };
static const uint8_t cmd_ac_set_fid =  CMD_RESPONSE_SET_AC;

static const uint8_t cmd_fr[] =        { 'F', 'R' };
static const uint8_t cmd_fr_set_fid =  CMD_RESPONSE_SET_FR;

static const uint8_t cmd_is[] =        { 'I', 'S' };
static const uint8_t cmd_is_set_fid =  CMD_RESPONSE_SET_IS;

static const uint8_t cmd_re[] =        { 'R', 'E' };
static const uint8_t cmd_re_set_fid =  CMD_RESPONSE_SET_RE;

static const uint8_t cmd_ky_set[] =    { 'K', 'Y', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static const uint8_t cmd_ky_set_fid =  CMD_RESPONSE_SET_KY;

static const uint8_t cmd_ee[] =        { 'E', 'E' };
static const uint8_t cmd_ee_get_fid =  CMD_RESPONSE_GET_EE;
static const uint8_t cmd_ee_set[] =    { 'E', 'E', 0 };
static const uint8_t cmd_ee_set_fid =  CMD_RESPONSE_SET_EE;


static const uint8_t cmd_d[ XBEE_API_DIO_CHANNEL_COUNT ][2] = {{ 'D', '0' },
                                                               { 'D', '1' },
                                                               { 'D', '2' },
                                                               { 'D', '3' },
                                                               { 'D', '4' },
                                                               { 'D', '5' },
                                                               { 'D', '6' },
                                                               { 'D', '7' }};
static const uint8_t cmd_d_get_fid[ XBEE_API_DIO_CHANNEL_COUNT ] =  { CMD_RESPONSE_GET_D0,
                                                                      CMD_RESPONSE_GET_D1,
                                                                      CMD_RESPONSE_GET_D2,
                                                                      CMD_RESPONSE_GET_D3,
                                                                      CMD_RESPONSE_GET_D4,
                                                                      CMD_RESPONSE_GET_D5,
                                                                      CMD_RESPONSE_GET_D6,
                                                                      CMD_RESPONSE_GET_D7 };

#define XBEE_CMD_POSN_FRAME_ID    (XBEE_CMD_POSN_ID_SPECIFIC_DATA)
#define XBEE_CMD_POSN_STATUS      (7U)
#define XBEE_CMD_POSN_PARAM_START (8U)

#define XBEE_CMD_RESPONS_HAS_DATA( _p_len ) ((_p_len > ( XBEE_CMD_POSN_PARAM_START + 1 ))

/** Class to create an XBeeApiFrame which can be used to read or change
    the value of one of the XBee parameters.  This class is used by the
    requestXXX and setXXX methods in XBeeApiCmdAt */
class XBeeApiCmdAtFrame : public XBeeApiFrame {
    uint8_t m_buffer[ XBEE_API_CMD_SET_HEADER_LEN + XBEE_CMD_MAX_PARAM_LENGTH ];
    public:
        /** Constructor
                   
            \param p_data Pointer to a buffer of length 2 bytes identifying
                          the command, e.g. 'V', 'R' would set up a version
                          request
            \param p_val Pointer to the new value for the parameter, most
                        significant byte (MSB) first 
            \param p_len The length of the data pointed to by p_val 
        */
        XBeeApiCmdAtFrame( const uint8_t        p_frameId,
                           const uint8_t* const p_data,
                           const uint8_t* const p_val,
                           const uint8_t        p_len );
        /** Destructor */
        virtual ~XBeeApiCmdAtFrame();
};

void XBeeApiCmdAt::resetCachedData( void )
{
    uint8_t i;
    
    m_have_hwVer = false;
    m_have_fwVer = false;
    m_have_chan = false;
    m_have_PANId = false;
    m_have_EDA = false;
    m_have_CE = false;
    m_have_sourceAddress = false;
    m_have_retries = false;
    m_have_randomDelaySlots = false;
    m_have_macMode = false;
    m_have_dioChangeDetectMask = false;
    m_have_dioLevels = false;
    m_have_sampleRate = false;
    m_have_destHigh = false;
    m_have_destLow = false;
    m_have_encryptionEnabled = false;
    m_keySet = false;
    
    m_writeCount = 0;
    m_applyCount = 0;
    m_resetCount = 0;
    m_sampleCount = 0;
    m_restoreCount = 0;
    
    /* We DO NOT reset m_have_snLow and m_have_snHigh here as
       these are reset only in the custructor - we assume that if
       we've received them then they can't change
       TODO: Could be wrong - what about if we're re-using remote XBee? */
    
    for( i = 0;
         i < XBEE_API_DIO_CHANNEL_COUNT;
         i++ )
    {
        m_have_d[ i ] = false;
        m_ioDigitalUpdatedTime[ i ] = 0;
    }
    for( i = 0;
         i < XBEE_API_ADC_CHANNEL_COUNT;
         i++ )
    {
        m_ioAnalogueUpdatedTime[ i ] = 0;
    }
}


XBeeApiCmdAt::XBeeApiCmdAt( XBeeDevice* const p_device ) : XBeeApiFrameDecoder( p_device ) , 
    m_have_snLow ( false ),
    m_have_snHigh ( false )
{
    resetCachedData();
}

#define RESPONSE_OK( _data ) (_data[ statusPosn ] == 0)

#define PROCESS_SET_RESPONSE( _type, _var ) \
            case CMD_RESPONSE_SET_ ## _type: \
                if( RESPONSE_OK( p_data )) \
                { \
                    m_ ## _var = m_ ## _var ## Pend; \
                    m_have_ ## _var = true; \
                } \
                else \
                { \
                    /* TODO */ \
                } \
                ret_val = true; \
                break;

#define PROCESS_SET_GET_RESPONSE_GENERIC( _type, _var, _src, _t, _sfx ) \
            case CMD_RESPONSE_SET_ ## _type: \
            case CMD_RESPONSE_GET_ ## _type: \
                if( RESPONSE_OK( p_data )) \
                { \
                    if( CMD_RESPONSE_GET_ ## _type == p_data[ XBEE_CMD_POSN_FRAME_ID ] ) \
                    { \
                        m_ ##_var ##_sfx = (_t) (_src); \
                    } \
                    else \
                    { \
                        m_ ##_var ##_sfx = m_ ## _var ## Pend ## _sfx; \
                    } \
                    m_have_ ##_var ##_sfx = true; \
                } \
                else \
                { \
                    /* TODO */ \
                } \
                ret_val = true; \
                break;

#define PROCESS_GET_RESPONSE_GENERIC( _type, _var, _src ) \
            case CMD_RESPONSE_GET_ ## _type: \
                if( RESPONSE_OK( p_data )) \
                { \
                    m_ ##_var = _src; \
                    m_have_ ## _var = true; \
                } \
                else \
                { \
                    /* TODO */ \
                } \
                ret_val = true; \
                break;

#define PROCESS_SET_GET_RESPONSE_8BIT_WITHCAST( _type, _var, _t, _sfx )  PROCESS_SET_GET_RESPONSE_GENERIC( _type, _var, p_data[ dataPosn ], _t, _sfx )
#define PROCESS_SET_GET_RESPONSE_8BIT( _type, _var )               PROCESS_SET_GET_RESPONSE_GENERIC( _type, _var, p_data[ dataPosn ], uint8_t,  )
#define PROCESS_SET_GET_RESPONSE_16BIT( _type, _var )              PROCESS_SET_GET_RESPONSE_GENERIC( _type, _var, ((uint16_t)p_data[ dataPosn ] << 8) | p_data[ dataPosn + 1 ], uint16_t,  )
#define PROCESS_SET_GET_RESPONSE_32BIT( _type, _var )              PROCESS_SET_GET_RESPONSE_GENERIC( _type, _var, ((uint32_t)p_data[ dataPosn ] << 24) |\
                                                                                             ((uint32_t)p_data[ dataPosn + 1 ] << 16) |\
                                                                                             ((uint32_t)p_data[ dataPosn + 2 ] << 8) |\
                                                                                             ((uint32_t)p_data[ dataPosn + 3 ]), uint32_t,  )

#define PROCESS_GET_RESPONSE_16BIT( _type, _var ) PROCESS_GET_RESPONSE_GENERIC( _type, _var, ((uint16_t)p_data[ dataPosn ] << 8) | p_data[ dataPosn + 1 ] )
#define PROCESS_GET_RESPONSE_32BIT( _type, _var ) PROCESS_GET_RESPONSE_GENERIC( _type, _var, ((uint32_t)p_data[ dataPosn ] << 24) |\
                                                                                             ((uint32_t)p_data[ dataPosn + 1 ] << 16) |\
                                                                                             ((uint32_t)p_data[ dataPosn + 2 ] << 8) |\
                                                                                             ((uint32_t)p_data[ dataPosn + 3 ]))

size_t XBeeApiCmdAt::getResponseStatusPos( void ) const
{
    return XBEE_CMD_POSN_STATUS;
}

bool XBeeApiCmdAt::processResponseFrame( const uint8_t* const p_data, size_t p_len )
{
    bool ret_val = false;
    size_t statusPosn = getResponseStatusPos();
    size_t dataPosn = statusPosn + 1;
    
    switch( p_data[ XBEE_CMD_POSN_FRAME_ID ] ) 
    {
        case CMD_RESPONSE_SET_KY:
            if( RESPONSE_OK( p_data )) 
            {
                m_keySet = true;
            }
            ret_val = true;
            break;
        case CMD_RESPONSE_SET_WR:
            if( RESPONSE_OK( p_data )) 
            {
                m_writeCount++;
            }
            ret_val = true;
            break;
        case CMD_RESPONSE_SET_AC:
            if( RESPONSE_OK( p_data )) 
            {
                m_applyCount++;
            }
            ret_val = true;
            break;
        case CMD_RESPONSE_SET_FR:
            if( RESPONSE_OK( p_data )) 
            {
                m_resetCount++;
            }
            ret_val = true;
            break;
        case CMD_RESPONSE_SET_IS:
            if( RESPONSE_OK( p_data )) 
            {
                m_sampleCount++;
            }
            ret_val = true;
            break;
        case CMD_RESPONSE_SET_RE:
            if( RESPONSE_OK( p_data )) 
            {
                /* If all settings have been reset, clear out any cached 
                   data members in this class */
                resetCachedData();
                m_restoreCount++;
            }
            ret_val = true;
            break;
        PROCESS_GET_RESPONSE_16BIT( HV, hwVer )
        PROCESS_GET_RESPONSE_16BIT( VR, fwVer )
        
        PROCESS_SET_GET_RESPONSE_8BIT( CH, chan )
        PROCESS_SET_GET_RESPONSE_8BIT( CE, CE )
        PROCESS_SET_GET_RESPONSE_16BIT( PID, PANId )
        PROCESS_SET_GET_RESPONSE_8BIT( EDA, EDA )
        PROCESS_SET_GET_RESPONSE_8BIT( RR, retries )
        PROCESS_SET_GET_RESPONSE_16BIT( MY, sourceAddress )
        PROCESS_GET_RESPONSE_32BIT( SH, snHigh )
        PROCESS_GET_RESPONSE_32BIT( SL, snLow )
        PROCESS_SET_GET_RESPONSE_32BIT( DH, destHigh )
        PROCESS_SET_GET_RESPONSE_32BIT( DL, destLow )
        PROCESS_SET_GET_RESPONSE_8BIT( RN, randomDelaySlots )
        PROCESS_SET_GET_RESPONSE_8BIT_WITHCAST( EE, encryptionEnabled, bool,  )
        PROCESS_SET_GET_RESPONSE_8BIT_WITHCAST( MM, macMode, XBeeApiMACMode_e,  )
        /* TODO: Add D0, D1, D2 response handling */
        PROCESS_SET_GET_RESPONSE_8BIT_WITHCAST( D0, d, XBeeApiDioConfig_e, [0] )
        PROCESS_SET_GET_RESPONSE_8BIT( IC, dioChangeDetectMask )
        PROCESS_SET_RESPONSE( IO, dioLevels )
        PROCESS_SET_GET_RESPONSE_16BIT( IR, sampleRate )
    }

    return ret_val;
}

#define DIO_CHANNEL_MASK (0x01FFU)
#define ADC_CHANNEL_MASK (0x7E00U)

bool XBeeApiCmdAt::processIOFrame( const uint8_t* const p_data, size_t p_len, const size_t p_start )
{
#if 0
    /* This is the number of sample sets that are contained in the packet, set using the IT AT command */
    uint8_t sampleCount = p_data[ p_start ];
#endif
    
    const uint16_t channelMask = (((uint16_t)p_data[ p_start + 1 ]) << 8) |
                                 ((uint16_t)p_data[ p_start + 2 ]);
    const uint8_t* dataPtr = &( p_data[ p_start + 3 ] );
    const uint16_t dioMask = channelMask & DIO_CHANNEL_MASK;
    uint16_t adcMask = (channelMask & ADC_CHANNEL_MASK) >> 9U;
    uint8_t adc = 0;

    time_t seconds = time( NULL );

    if( dioMask )
    {
        uint16_t dioData = (((uint16_t)dataPtr[ 0 ]) << 8U) |
                           (uint16_t)dataPtr[ 1 ];
        dataPtr += 2;
        
        for( unsigned i = 0;
             i < XBEE_API_DIO_CHANNEL_COUNT;
             i++ )
        {
            if(( dioMask >> i ) & 0x01 )
            {
                m_ioDigitalState[i] = ( dioData >> i ) & 0x01;
                m_ioDigitalUpdatedTime[i] = seconds;
            }
        }
    }
    
    while( adcMask )
    {
        if( adcMask & 0x01 )
        {
            uint16_t adcData = (((uint16_t)dataPtr[ 0 ]) << 8U) |
                               (uint16_t)dataPtr[ 1 ];
            dataPtr += 2;
            
            m_ioAnalogueVal[adc] = adcData;
            m_ioAnalogueUpdatedTime[adc] = seconds;
        }
        adcMask = adcMask >> 1U;
        adc++;
    }    
    
    return true;                       
}

#define XBEE_IO_PACKET_ADDRESS (XBEE_CMD_POSN_ID_SPECIFIC_DATA)
#define XBEE_IO_PACKET_64BIT_DATA_START (XBEE_IO_PACKET_ADDRESS + sizeof( uint64_t) + 1U + 1U)
#define XBEE_IO_PACKET_16BIT_DATA_START (XBEE_IO_PACKET_ADDRESS + sizeof( uint16_t) + 1U + 1U)

bool XBeeApiCmdAt::decodeCallback( const uint8_t* const p_data, size_t p_len )
{
    bool ret_val = false;

    if( XBEE_CMD_AT_RESPONSE == p_data[ XBEE_CMD_POSN_API_ID ] ) 
    {
        ret_val = processResponseFrame( p_data, p_len );
    } 
    else if( XBEE_CMD_RX_16B_IO == p_data[ XBEE_CMD_POSN_API_ID ] )
    {
        uint16_t src16BitAddr = (((uint16_t)p_data[ XBEE_IO_PACKET_ADDRESS ]) << 8U) | 
                                p_data[ XBEE_IO_PACKET_ADDRESS + 1 ];
        if( m_have_sourceAddress &&
           ( src16BitAddr == m_sourceAddress ))
        {
            ret_val = processIOFrame( p_data, p_len, XBEE_IO_PACKET_16BIT_DATA_START );
        }
    }
    else if( XBEE_CMD_RX_64B_IO == p_data[ XBEE_CMD_POSN_API_ID ] )
    {
        uint32_t srcAddrHigh = (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS ]) << 24U) |
                               (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 1 ]) << 16U) |
                               (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 2 ]) << 8U) |
                               (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 3 ]));
        uint32_t srcAddrLow =  (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 4 ]) << 24U) |
                                (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 5 ]) << 16U) |
                                (((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 6 ]) << 8U) |
                                ((uint64_t)p_data[ XBEE_IO_PACKET_ADDRESS + 7 ]);
        if( m_have_snLow &&
            m_have_snHigh &&
           ( srcAddrHigh == m_snHigh ) &&
           ( srcAddrLow  == m_snLow ))
        {
            ret_val = processIOFrame( p_data, p_len, XBEE_IO_PACKET_64BIT_DATA_START );
        }
    }
    else
    {
    }

    return ret_val;
}

bool XBeeApiCmdAt::setChannel( uint8_t const p_chan )
{
    bool ret_val = false;
    
    if((( m_device->getXBeeModel() == XBeeDevice::XBEEDEVICE_S1 ) && 
        ( p_chan >= XBEE_CHAN_MIN ) &&
        ( p_chan <= XBEE_CHAN_MAX )) ||
       (( m_device->getXBeeModel() == XBeeDevice::XBEEDEVICE_S1_PRO ) && 
        ( p_chan >= XBEE_PRO_CHAN_MIN ) &&
        ( p_chan <= XBEE_PRO_CHAN_MAX )))
    {
        m_chanPend = p_chan;
        SendCmd_uint8_t( cmd_ch_set_fid, cmd_ch_set, p_chan );    
        ret_val = true;
    }
    return ret_val;
}

#define MAKE_REQUEST( _name, _mnemonic, _cmd ) \
bool XBeeApiCmdAt::request ## _name( void ) \
{\
    m_have_ ## _mnemonic = false;   \
    SendCmd( _cmd ## _get_fid, _cmd, NULL, 0 ); \
    return true;\
}

MAKE_REQUEST( HardwareVersion,             hwVer,               cmd_hv )
MAKE_REQUEST( FirmwareVersion,             fwVer,               cmd_vr )
MAKE_REQUEST( Channel,                     chan,                cmd_ch )
MAKE_REQUEST( PanId,                       PANId,               cmd_pid )
MAKE_REQUEST( CoordinatorEnabled,          CE,                  cmd_ce )
MAKE_REQUEST( EndDeviceAssociationEnabled, EDA,                 cmd_eda )
MAKE_REQUEST( SourceAddress,               sourceAddress,       cmd_my )
MAKE_REQUEST( Retries,                     retries,             cmd_rr )
MAKE_REQUEST( RandomDelaySlots,            randomDelaySlots,    cmd_rn )
MAKE_REQUEST( MacMode,                     macMode,             cmd_mm )
MAKE_REQUEST( SerialNumberHigh,            snHigh,              cmd_sh )
MAKE_REQUEST( SerialNumberLow,             snLow,               cmd_sl )
MAKE_REQUEST( DioChangeDetectMask,         dioChangeDetectMask, cmd_ic )
MAKE_REQUEST( SampleRate,                  sampleRate,          cmd_ir )
MAKE_REQUEST( DestinationAddressHigh,      destHigh,            cmd_dh )
MAKE_REQUEST( DestinationAddressLow,       destLow,             cmd_dl )
MAKE_REQUEST( EncryptionEnabled,           encryptionEnabled,   cmd_ee )

bool XBeeApiCmdAt::requestWriteSettings( void )
{
    SendCmd( cmd_wr_set_fid, cmd_wr, NULL, 0 );
    return true;
}

bool XBeeApiCmdAt::requestApplyChanges( void )
{
    SendCmd( cmd_ac_set_fid, cmd_ac, NULL, 0 );
    return true;
}

bool XBeeApiCmdAt::requestReset( void )
{
    SendCmd( cmd_fr_set_fid, cmd_fr, NULL, 0 );
    return true;
}

bool XBeeApiCmdAt::requestForceSample( void )
{
    SendCmd( cmd_is_set_fid, cmd_is, NULL, 0 );
    return true;
}

bool XBeeApiCmdAt::requestRestoreDefaults( void )
{
    SendCmd( cmd_re_set_fid, cmd_re, NULL, 0 );
    return true;
}

bool XBeeApiCmdAt::requestSerialNumber( void )
{
    requestSerialNumberHigh();
    requestSerialNumberLow();
    return true;
}

bool XBeeApiCmdAt::requestDestinationAddress( void )
{
    requestDestinationAddressHigh();
    requestDestinationAddressLow();
    return true;
}

bool XBeeApiCmdAt::requestDioConfig( const uint8_t p_chanNo )
{
    bool ret_val = false;
    if( p_chanNo < XBEE_API_DIO_CHANNEL_COUNT )
    {
        m_have_d[ p_chanNo ] = false;   
        SendCmd( cmd_d_get_fid[ p_chanNo ], cmd_d[ p_chanNo ], NULL, 0 );
        ret_val = true;
    }
    return ret_val;
}

time_t XBeeApiCmdAt::getDigitalState( const uint8_t p_chanNo, bool& p_state )
{
    time_t ret_val = 0;
    if( p_chanNo < XBEE_API_DIO_CHANNEL_COUNT )
    {
        p_state = m_ioDigitalState[ p_chanNo ];
        ret_val = m_ioDigitalUpdatedTime[ p_chanNo ];
    }    
    return ret_val;
}

time_t XBeeApiCmdAt::getAnalogueValue( const uint8_t p_chanNo, uint16_t& p_val )
{
    time_t ret_val = 0;
    if( p_chanNo < XBEE_API_ADC_CHANNEL_COUNT )
    {
        p_val = m_ioAnalogueVal[ p_chanNo ];
        ret_val = m_ioAnalogueUpdatedTime[ p_chanNo ];
    }        
    return ret_val;
}

#define MAKE_GET(_name, _mnemonic, _type ) \
bool XBeeApiCmdAt::get ## _name( _type* const p_param ) \
{\
    if( m_have_ ## _mnemonic ) {\
        *p_param = m_ ## _mnemonic;\
    } \
    return m_have_ ## _mnemonic; \
}

MAKE_GET( FirmwareVersion,             fwVer,               uint16_t )
MAKE_GET( HardwareVersion,             hwVer,               uint16_t )
MAKE_GET( Channel,                     chan,                uint8_t )
MAKE_GET( CoordinatorEnabled,          CE,                  bool )
MAKE_GET( EndDeviceAssociationEnabled, EDA,                 bool )
MAKE_GET( PanId,                       PANId,               panId_t )
MAKE_GET( SourceAddress,               sourceAddress,       uint16_t )
MAKE_GET( Retries,                     retries,             uint8_t )
MAKE_GET( RandomDelaySlots,            randomDelaySlots,    uint8_t )
MAKE_GET( MacMode,                     macMode,             XBeeApiMACMode_e )
MAKE_GET( DioChangeDetectMask,         dioChangeDetectMask, uint8_t )
MAKE_GET( DioLevels,                   dioLevels,           uint8_t )
MAKE_GET( SampleRate,                  sampleRate,          uint16_t )
MAKE_GET( DestinationAddressHigh,      destHigh,            uint32_t )
MAKE_GET( DestinationAddressLow,       destLow,             uint32_t )
MAKE_GET( EncryptionEnabled,           encryptionEnabled,   bool )

bool XBeeApiCmdAt::getSerialNumber( uint64_t* const p_sn )
{
    /* Need both halves to have the complete serial number */
    bool have_sn = m_have_snLow && m_have_snHigh;
    if( have_sn )
    {
        *p_sn = m_snHigh;
        *p_sn = *p_sn << 32U;
        *p_sn |= m_snLow;
    }
    return( have_sn );
}

bool XBeeApiCmdAt::getDestinationAddress( uint64_t* const p_addr )
{
    bool have_da = m_have_destLow && m_have_destHigh;
    if( have_da )
    {
        *p_addr = m_destHigh;
        *p_addr = *p_addr << 32U;
        *p_addr |= m_destLow;
    }
    return( have_da );
   
}

bool XBeeApiCmdAt::getDioConfig( const uint8_t p_chanNo, XBeeApiDioConfig_e* const p_conf )
{
    bool ret_val = false;
    if( p_chanNo < XBEE_API_DIO_CHANNEL_COUNT )
    {
        if( m_have_d[ p_chanNo ] )
        {
            *p_conf = m_d[ p_chanNo ];
            ret_val = true;
        }
    }
    return ret_val;   
}

bool XBeeApiCmdAt::getEncryptionKeySet( void )
{
    return m_keySet;
}

#define MAKE_SET( _name, _mnemonic, _cmd, _type, _transmit_type ) \
bool XBeeApiCmdAt::set ## _name( const _type p_param ) \
{\
    m_have_ ## _mnemonic = false;\
    m_## _mnemonic ## Pend = p_param;\
    SendCmd_ ## _transmit_type ( _cmd ## _fid, _cmd, p_param ); \
    return true;\
}

MAKE_SET( CoordinatorEnabled,          CE,                  cmd_ce_set,  bool,             uint8_t )
MAKE_SET( EndDeviceAssociationEnabled, EDA,                 cmd_eda_set, bool,             uint8_t )
MAKE_SET( PanId,                       PANId,               cmd_pid_set, uint16_t,         uint16_t )
MAKE_SET( SourceAddress,               sourceAddress,       cmd_my_set,  uint16_t,         uint16_t )
MAKE_SET( Retries,                     retries,             cmd_rr_set,  uint8_t,          uint16_t )
MAKE_SET( RandomDelaySlots,            randomDelaySlots,    cmd_rn_set,  uint8_t,          uint16_t )
MAKE_SET( MacMode,                     macMode,             cmd_mm_set,  XBeeApiMACMode_e, uint8_t )
MAKE_SET( DioChangeDetectMask,         dioChangeDetectMask, cmd_ic_set,  uint8_t,          uint8_t )
MAKE_SET( DioLevels,                   dioLevels,           cmd_io_set,  uint8_t,          uint8_t )
MAKE_SET( SampleRate,                  sampleRate,          cmd_ir_set,  uint16_t,         uint16_t )
MAKE_SET( DestinationAddressHigh,      destHigh,            cmd_dh_set,  uint32_t,         uint32_t )
MAKE_SET( DestinationAddressLow,       destLow,             cmd_dl_set,  uint32_t,         uint32_t )
MAKE_SET( EncryptionEnabled,           encryptionEnabled,   cmd_ee_set,  bool,             uint8_t )

#define XBEE_ENCRYPTION_KEY_LEN 16U

bool XBeeApiCmdAt::setEncryptionKey( const uint8_t* p_key )
{
    m_keySet = false;
    SendCmd( cmd_ky_set_fid, cmd_ky_set, p_key, XBEE_ENCRYPTION_KEY_LEN );
    
    return true;
}

bool XBeeApiCmdAt::setDioConfig( const uint8_t p_chanNo, const XBeeApiDioConfig_e p_conf )
{
    bool ret_val = false;
    if( p_chanNo < XBEE_API_DIO_CHANNEL_COUNT )
    {
        /* TODO: Add check that p_conf is valid for this channel */
        m_have_d[ p_chanNo ] = false;
        m_dPend[ p_chanNo ] = p_conf;
        SendCmd_uint8_t( cmd_d_get_fid[ p_chanNo ], cmd_d[ p_chanNo ], p_conf );
    }
    return ret_val;   
}

bool XBeeApiCmdAt::setDestinationAddress( const uint64_t p_addr )
{
    m_have_destHigh = m_have_destLow = false;
    
    setDestinationAddressHigh( p_addr >> 32U );
    setDestinationAddressLow( p_addr );

    return true;
}

void XBeeApiCmdAt::SendCmd_uint8_t( const uint8_t        p_frameId,
                                    const uint8_t* const p_data,
                                    const uint8_t&       p_val )
{
    SendCmd( p_frameId, p_data, &p_val, sizeof( uint8_t ));
}

void XBeeApiCmdAt::SendCmd_uint16_t( const uint8_t        p_frameId,
                                     const uint8_t* const p_data,
                                     const uint16_t&       p_val )
{
    uint8_t buffer[ sizeof( uint16_t )];
    
    buffer[0] = (uint8_t)((p_val >> 8U) & 0xFF);
    buffer[1] = (uint8_t)((p_val >> 0U) & 0xFF);
     
    SendCmd( p_frameId, p_data, buffer, sizeof( uint16_t ));
}

void XBeeApiCmdAt::SendCmd_uint32_t( const uint8_t        p_frameId,
                                     const uint8_t* const p_data,
                                     const uint32_t&       p_val )
{
    uint8_t buffer[ sizeof( uint32_t )];
    
    buffer[0] = (uint8_t)((p_val >> 24U) & 0xFF);
    buffer[1] = (uint8_t)((p_val >> 16U) & 0xFF);
    buffer[2] = (uint8_t)((p_val >> 8U) & 0xFF);
    buffer[3] = (uint8_t)((p_val >> 0U) & 0xFF);
     
    SendCmd( p_frameId, p_data, buffer, sizeof( uint32_t ));
}

void XBeeApiCmdAt::SendCmd( const uint8_t        p_frameId,
                            const uint8_t* const p_data,
                            const uint8_t* const p_val,
                            const uint8_t        p_len )
{
    XBeeApiCmdAtFrame req( p_frameId, p_data, p_val, p_len );
    m_device->SendFrame( &req );    
}

XBeeApiCmdAtFrame::XBeeApiCmdAtFrame( const uint8_t        p_frameId,   
                                      const uint8_t* const p_data,
                                      const uint8_t* const p_val,
                                      const uint8_t        p_len ) : XBeeApiFrame( )
{
    
    m_apiId = XBEE_CMD_AT_CMD;
    
    m_buffer[0] = p_frameId;
    m_buffer[1] = p_data[0];
    m_buffer[2] = p_data[1];

    m_data = m_buffer;        
    m_dataLen = XBEE_API_CMD_SET_HEADER_LEN;
        
    if(( p_val != NULL ) &&
       ( p_len <= XBEE_CMD_MAX_PARAM_LENGTH ))
    {
        size_t s = 0;
        uint8_t* dest = &( m_buffer[ XBEE_API_CMD_SET_HEADER_LEN ] );
        const uint8_t* src = p_val;
        
        for( s = 0;
             s < p_len;
             s++, dest++, src++ ) {
             *dest = *src;         
        }
        m_dataLen += p_len;
    }

#if 0
    /* Debugging code */
    extern Serial pc;
    size_t x = 0;
    pc.printf("\r\n[%02X][%02X][%02X]",(m_dataLen>>8U)&0xFF,m_dataLen&0xFF,XBEE_CMD_AT_CMD);
    for( x  = 0; x < m_dataLen; x++ )
    {
        if( x < 3 ) 
        { 
            pc.printf("%c",m_data[x]); 
        }
        pc.printf("[%02X]",m_data[x]);
    }
    pc.printf("\r\n");
#endif
}

XBeeApiCmdAtFrame::~XBeeApiCmdAtFrame()
{
}