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.

Files at this revision

API Documentation at this revision

Comitter:
johnb
Date:
Wed Jan 29 20:19:59 2014 +0000
Parent:
4:e5e152b3930f
Child:
6:3cb62daace78
Commit message:
Documentation update

Changed in this revision

Base/XBeeApiFrame.cpp Show annotated file Show diff for this revision Revisions of this file
Base/XBeeApiFrame.hpp Show annotated file Show diff for this revision Revisions of this file
Base/XBeeDevice.cpp Show annotated file Show diff for this revision Revisions of this file
Base/XBeeDevice.hpp Show annotated file Show diff for this revision Revisions of this file
Utility/XBeeApiCmdAt.cpp Show annotated file Show diff for this revision Revisions of this file
Utility/XBeeApiCmdAt.hpp Show annotated file Show diff for this revision Revisions of this file
Utility/XBeeApiSetupHelper.cpp Show annotated file Show diff for this revision Revisions of this file
Utility/XBeeApiSetupHelper.hpp Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Base/XBeeApiFrame.cpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,65 @@
+/** 
+
+Copyright 2013 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 "XBeeApiFrame.hpp"
+#include "XBeeDevice.hpp"
+
+#include <stdlib.h>
+
+XBeeApiFrame::XBeeApiFrame( void ) : m_apiId ( XBEE_CMD_INVALID ), m_dataLen( 0 ), m_data( NULL )
+{
+}
+
+uint16_t XBeeApiFrame::getCmdLen( void ) const
+{
+    return m_dataLen + m_cmdHeaderLen;    
+}
+
+
+XBeeApiIdentifier_e XBeeApiFrame::getApiId( void ) const
+{
+    return m_apiId;
+}
+        
+const uint8_t* XBeeApiFrame::getDataPtr( void ) const
+{
+    return m_data;
+}
+
+XBeeApiFrameDecoder::XBeeApiFrameDecoder() : m_device( NULL )
+{
+    
+}
+
+XBeeApiFrameDecoder::~XBeeApiFrameDecoder()
+{
+    if( m_device != NULL )
+    {
+        m_device->unregisterDecoder( this );
+    }    
+}
+
+void XBeeApiFrameDecoder::registerCallback( XBeeDevice* const p_device )
+{
+    m_device = p_device;
+}
+
+void XBeeApiFrameDecoder::unregisterCallback( void )
+{
+    m_device = NULL;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Base/XBeeApiFrame.hpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,124 @@
+/**
+   @file
+   @brief Class to abstract commands send to the XBee API
+   
+   @author John Bailey 
+
+   @copyright Copyright 2013 John Bailey
+
+   @section LICENSE
+   
+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.
+
+*/
+
+#if !defined XBEEAPICMD_HPP
+#define      XBEEAPICMD_HPP
+
+#include <stdint.h>
+#include <stddef.h> // for size_t
+
+/** API identifiers - the first byte in the API-specific structure within an API frame which provides an indication as to the type of data which follows */
+typedef enum
+{
+    XBEE_CMD_TX_64B_ADDR        = 0x00,
+    XBEE_CMD_TX_16B_ADDR        = 0x01,
+    XBEE_CMD_AT_CMD             = 0x08,
+    XBEE_CMD_QUEUE_PARAM_VAL    = 0x09,
+    XBEE_CMD_REMOTE_AT_CMD      = 0x17,
+    XBEE_CMD_RX_64B_ADDR        = 0x80,
+    XBEE_CMD_RX_16B_ADDR        = 0x81,
+    XBEE_CMD_AT_RESPONSE        = 0x88,
+    XBEE_CMD_TX_STATUS          = 0x89,
+    XBEE_CMD_MODEM_STATUS       = 0x8A,
+    XBEE_CMD_REMOTE_AT_RESPONSE = 0x97,
+    XBEE_CMD_INVALID            = 0xFFF   
+} XBeeApiIdentifier_e; 
+
+/** Position of fixed meaning bytes within the API frame, relative to the start of the frame */
+enum
+{
+    /** Start delimiter, should be equal to XBEE_SB_FRAME_DELIMITER */
+    XBEE_CMD_POSN_SDELIM = 0x00,
+    /** High byte of the 16-bit length field */
+    XBEE_CMD_POSN_LEN_HI = 0x01,
+    /** Low byte of the 16-bit length field */
+    XBEE_CMD_POSN_LEN_LO = 0x02,
+    /** API identifier for the data which follows - see XBeeApiIdentifier_e */
+    XBEE_CMD_POSN_API_ID = 0x03
+};
+
+/** Helper macro to retrieve the frame payload length (i.e. excluding overhead - see XBEE_API_FRAME_OVERHEAD) from a buffer.
+
+    \param _b Pointer to a buffer containing a received API frame.
+    \returns Length of the frame payload excluding overhead */
+#define MSG_LEN_IN_BUFFER( _b ) ((((uint16_t)_b[ XBEE_CMD_POSN_LEN_HI ]) << 8U) + _b[XBEE_CMD_POSN_LEN_LO])
+
+/** The number of 'overhead' bytes in an API frame (i.e. those not included in the frame payload, namely the start delimiter, 2 length bytes & checksum */
+#define XBEE_API_FRAME_OVERHEAD 4U
+
+/** Class which represents an API frame, exchanged with the XBee.
+    This class in itself will not create a valid API frame and needs to be sub-classed.
+*/
+class XBeeApiFrame
+{
+    private:
+        static const   uint8_t m_cmdHeaderLen = 1;
+
+    protected:
+        /** API identifier for the data in the frame */
+        XBeeApiIdentifier_e m_apiId;
+        
+        /** API identifier specific data */
+        const uint8_t*      m_data;
+        
+        /** Length of the data pointed to by m_data */
+        uint16_t            m_dataLen;
+
+    public:
+    
+        /** Constructor */
+        XBeeApiFrame( void );
+    
+        /** Return the length of the API-specific structure represented by this frame.  i.e. the API frame without the overhead - see XBEE_API_FRAME_OVERHEAD */
+        uint16_t getCmdLen( void ) const;
+    
+        /** Retrieve the API identifier for this frame */
+        XBeeApiIdentifier_e getApiId( void ) const;
+        
+        /** Return a pointer to the API-specific data (i.e. that which follows the API identifier in the frame */
+        const uint8_t*      getDataPtr( void ) const;
+};
+
+/* Forward declare this as XBeeDevice is dependent upon XBeeApiFrameDecoder */
+class XBeeDevice;
+
+class XBeeApiFrameDecoder
+{
+    protected:
+        XBeeDevice* m_device;
+        
+    public:
+        
+        XBeeApiFrameDecoder();
+        
+        virtual ~XBeeApiFrameDecoder();
+    
+        virtual bool decodeCallback( const uint8_t* const p_data, size_t p_len ) = 0;
+                
+        void registerCallback( XBeeDevice* const p_device );
+
+        void unregisterCallback( void );
+};
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Base/XBeeDevice.cpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,359 @@
+/** 
+
+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 "XBeeDevice.hpp"
+
+/** Number of bytes we need to 'peek' into the receive buffer in order to retrieve the 
+    payload length */
+#define INITIAL_PEEK_LEN (3U)
+    
+/** Enum of bytes with a special meaning when communicating with the XBee in API
+    mode.  In escaped mode, these are the bytes that need to be escaped */
+typedef enum
+{
+    XBEE_SB_XON             = 0x11,
+    XBEE_SB_XOFF            = 0x13,
+    XBEE_SB_FRAME_DELIMITER = 0x7E,
+    XBEE_SB_ESCAPE          = 0x7D
+} XBeeSerialSpecialBytes_e;
+
+/** ASCII command to the XBee to request API mode 2 */
+const char api_mode2_cmd[] = { 'A', 'T', 'A', 'P', ' ', '2', '\r' };
+
+/** ASCII command to the XBee to request that it exit command mode */
+const char exit_cmd_mode_cmd[] = { 'A', 'T', 'C', 'N', '\r' };
+
+XBeeDevice::XBeeDevice( PinName p_tx, PinName p_rx, PinName p_rts, PinName p_cts ): m_if( p_tx, p_rx )
+{
+    m_escape = true;
+    m_inAtCmdMode = false;
+    m_rxMsgLastWasEsc = false;
+    
+    /* Can only do flow control on devices which support it */
+#if defined ( DEVICE_SERIAL_FC )
+    /* TODO: need rts and cts both set? */
+    m_if.set_flow_control( mbed::SerialBase::Flow.RTSCTS, p_rts, p_cts );
+#endif
+
+    /* Attach RX call-back to the serial interface */
+    m_if.attach( this, &XBeeDevice::if_rx, Serial::RxIrq); 
+}
+
+XBeeDevice::~XBeeDevice( void )
+{
+    /* Iterate all of the decoders and un-register them */
+    for( FixedLengthList<XBeeApiFrameDecoder*, XBEEAPI_CONFIG_DECODER_LIST_SIZE>::iterator it = m_decoders.begin() ;
+         it != m_decoders.end();
+         ++it ) {
+        (*it)->unregisterCallback();
+    }
+}
+
+void XBeeDevice::if_rx( void )
+{
+    /* Keep going while there are bytes to be read */
+    while(m_if.readable()) {
+        
+        uint8_t c = m_if.getc();
+        
+        /* Sanity check that if we're starting from an empty buffer the byte that we're
+           receiving is a frame delimiter */
+        if(( m_inAtCmdMode ) ||
+           (( c == XBEE_SB_FRAME_DELIMITER ) ||
+            ( m_rxBuff.getSize() ))) 
+        {
+            /* If it's an escape character we want to de-code the escape, so flag
+               that we have a pending escape but don't modify the rx buffer */
+            if( m_escape &&
+               ( c == XBEE_SB_ESCAPE ))
+            {
+                m_rxMsgLastWasEsc = true;
+            }
+            else
+            {
+                if( m_rxMsgLastWasEsc ) {
+                    c = c ^ 0x20;  
+                    m_rxMsgLastWasEsc = false;
+                }
+                m_rxBuff.write( &c, 1 );
+            }
+        } else {
+            /* TODO */    
+        }
+    }
+    
+    if( m_inAtCmdMode ) 
+    {
+        m_rxMsgLastWasEsc = false;
+    } 
+ 
+    checkRxDecode();
+}
+    
+void XBeeDevice::checkRxDecode( void )
+{
+    /* Get an initial portion of data from the read buffer so that the message length can be determined */
+    uint8_t buff[INITIAL_PEEK_LEN];
+    uint16_t len = m_rxBuff.peek( buff, INITIAL_PEEK_LEN );    
+    
+    if((len >= INITIAL_PEEK_LEN ) &&
+       (buff[ XBEE_CMD_POSN_SDELIM ] == XBEE_SB_FRAME_DELIMITER ))
+    {
+        /* Try and get enough data to cover the whole message */
+        /* TODO: Magic number */
+        const uint16_t cmdLen = MSG_LEN_IN_BUFFER( buff ) + XBEE_API_FRAME_OVERHEAD;
+        uint8_t cmdBuff[cmdLen];
+        uint16_t len = m_rxBuff.peek( cmdBuff, cmdLen );    
+
+        if( len >= cmdLen )
+        {
+            /* TODO: Verify checksum */
+            
+            /* Iterate all of the decoders */
+            for( FixedLengthList<XBeeApiFrameDecoder*, XBEEAPI_CONFIG_DECODER_LIST_SIZE>::iterator it = m_decoders.begin() ;
+                 it != m_decoders.end();
+                 ++it ) {
+
+                bool processed = (*it)->decodeCallback( cmdBuff, cmdLen );
+                if( processed )
+                {
+                    break;
+                }
+            }            
+            /* Remove the data from the receive buffer - either it was decoded (all well and good)
+               or it wasn't, in which case we need to get rid of it to prevent it from jamming
+               up the message queue */
+            m_rxBuff.chomp( cmdLen );
+        }
+    }
+}
+
+bool XBeeDevice::registerDecoder( XBeeApiFrameDecoder* const p_decoder )
+{
+    bool ret_val = false;
+    if( p_decoder != NULL )
+    {
+        if( !m_decoders.inList( p_decoder ) ) {
+            m_decoders.push( p_decoder );   
+            p_decoder->registerCallback( this );
+            ret_val = true;
+        }
+    }
+    return ret_val;
+}
+     
+bool XBeeDevice::unregisterDecoder( XBeeApiFrameDecoder* const p_decoder )
+{
+    bool ret_val = false;
+    if( p_decoder != NULL )
+    {
+        /* Iterate all of the decoders */
+        for( FixedLengthList<XBeeApiFrameDecoder*, XBEEAPI_CONFIG_DECODER_LIST_SIZE>::iterator it = m_decoders.begin() ;
+             it != m_decoders.end();
+             ++it ) {
+            if( *it == p_decoder ) {
+                p_decoder->unregisterCallback();
+                /* TODO: Actually remove the item from m_decoders! */
+                ret_val = true;   
+            }
+        }
+    }
+    return ret_val;
+}
+
+void XBeeDevice::SendFrame( const XBeeApiFrame* const p_cmd )
+{
+    uint8_t sum = 0U;
+    uint16_t len;
+    uint16_t i;
+    const uint8_t* cmdData;
+ 
+#if defined  XBEEAPI_CONFIG_USING_RTOS
+    m_ifMutex.lock();
+#endif
+
+    xbeeWrite( XBEE_SB_FRAME_DELIMITER, false );
+    
+    len = p_cmd->getCmdLen();
+    xbeeWrite((uint8_t)(len >> 8U));
+    xbeeWrite((uint8_t)(len & 0xFF));
+
+    sum += xbeeWrite((uint8_t)p_cmd->getApiId());
+
+    cmdData = p_cmd->getDataPtr();
+
+    for( i = 0;
+         i < (len-1);
+         i++ )
+    {
+        sum += xbeeWrite(cmdData[i]);
+    }
+    
+    /* Checksum is 0xFF - summation of bytes (excluding delimiter and length) */
+    xbeeWrite( (uint8_t)0xFFU - sum );
+    
+    fflush( m_if );
+    
+#if defined  XBEEAPI_CONFIG_USING_RTOS
+    m_ifMutex.unlock();
+#endif
+}
+
+uint8_t XBeeDevice::xbeeWrite( uint8_t p_byte, bool p_doEscape )
+{
+    uint8_t c_sum = 0;
+    
+    if (p_doEscape && m_escape && 
+        ((p_byte == XBEE_SB_FRAME_DELIMITER ) ||
+         (p_byte == XBEE_SB_ESCAPE ) || 
+         (p_byte == XBEE_SB_XON ) || 
+         (p_byte == XBEE_SB_XOFF))) 
+    {
+        #if 0
+        m_if.printf("%02x ",XBEE_SB_ESCAPE);
+        m_if.printf("%02x ",p_byte ^ 0x20);
+        #else
+        m_if.putc(XBEE_SB_ESCAPE);
+        m_if.putc(p_byte ^ 0x20);
+        #endif
+        c_sum += XBEE_SB_ESCAPE;
+        c_sum += p_byte ^ 0x20;
+    } else {
+        #if 0
+        m_if.printf("%02x ",p_byte);
+        #else
+        m_if.putc(p_byte);
+        #endif
+        c_sum += p_byte;
+    }
+    return c_sum;
+}
+
+#define IS_OK( _b ) (( _b[ 0 ] == 'O' ) && ( _b[ 1 ] == 'K' ) && ( _b[ 2 ] == '\r' ))
+#define OK_LEN (3U)
+
+XBeeDevice::XBeeDeviceReturn_t XBeeDevice::SendFrame( const char* const p_dat, size_t p_len, int p_wait_ms )
+{
+    XBeeDeviceReturn_t ret_val;
+
+    if( m_inAtCmdMode )
+    {
+#if defined  XBEEAPI_CONFIG_USING_RTOS
+        m_ifMutex.lock();
+#endif
+        for( size_t i = 0;
+             i < p_len;
+             i++ ) {
+            m_if.putc(p_dat[i]);
+        }
+        
+        fflush( m_if );
+                
+        wait_ms( p_wait_ms );
+                
+        /* Check the response for the OK indicator */
+        if( m_rxBuff.getSize() == OK_LEN )
+        {
+            uint8_t ok_buff[OK_LEN];
+            m_rxBuff.read( ok_buff, OK_LEN );
+                    
+            if( IS_OK( ok_buff ))
+            {
+                ret_val = XBEEDEVICE_OK;
+            } 
+            else 
+            {
+                ret_val = XBEEDEVICE_UNEXPECTED_DATA;                    
+            }
+        }
+        else
+        {
+            ret_val = XBEEDEVICE_UNEXPECTED_LENGTH;
+        }
+#if defined  XBEEAPI_CONFIG_USING_RTOS
+        m_ifMutex.unlock();
+#endif
+    } 
+    else 
+    {
+        ret_val = XBEEDEVICE_WRONG_MODE;            
+    }
+    return ret_val;
+}
+
+XBeeDevice::XBeeDeviceReturn_t XBeeDevice::setUpApi( void )
+{
+    XBeeDeviceReturn_t ret_val;
+    
+    /* Wait for the guard period before transmitting command sequence */
+    wait_ms( XBEEAPI_CONFIG_GUARDPERIOD_MS );
+    
+    m_inAtCmdMode = true;
+    
+    /* Request to enter command mode */
+    /* TODO: Magic number */
+    ret_val = SendFrame("+++", 3, 3000);
+
+    /* Everything OK with last request? */
+    if( ret_val == XBEEDEVICE_OK )
+    {
+        wait_ms( XBEEAPI_CONFIG_GUARDPERIOD_MS );
+        
+        /* API mode 2 please! */
+        ret_val = SendFrame(api_mode2_cmd,sizeof(api_mode2_cmd));
+    }
+
+    /* Everything OK with last request? */
+    if( ret_val == XBEEDEVICE_OK )
+    {
+        /* Exit command mode, back to API mode */
+        ret_val = SendFrame(exit_cmd_mode_cmd,sizeof(exit_cmd_mode_cmd));
+    }
+    
+    m_inAtCmdMode = false;
+    
+    return ret_val;
+}
+
+#if defined XBEEAPI_CONFIG_ENABLE_DEVELOPER
+
+#define PRINTABLE_ASCII_FIRST 32U
+#define PRINTABLE_ASCII_LAST 126U
+
+void XBeeDevice::dumpRxBuffer( Stream* p_buf, const bool p_hexView )
+{
+    uint8_t c;
+    while( m_rxBuff.getSize() ) {
+        if( m_rxBuff.read( &c, 1 ) ) {
+            if( p_hexView ) {
+                uint8_t a = '-';
+                if(( c>=PRINTABLE_ASCII_FIRST ) && (c<=PRINTABLE_ASCII_LAST)) {
+                    a = c;
+                }
+                p_buf->printf("0x%02x (%c) ",c,a);
+            } else {
+                p_buf->printf("%c",c);
+                if( c == '\r' ) {
+                    p_buf->printf("\n");   
+                }
+            }
+        }
+    }
+}
+
+#endif
\ No newline at end of file
--- a/Base/XBeeDevice.hpp	Mon Jan 27 21:34:10 2014 +0000
+++ b/Base/XBeeDevice.hpp	Wed Jan 29 20:19:59 2014 +0000
@@ -115,7 +115,18 @@
 
      virtual ~XBeeDevice( void );  
      
-     /** Transmit the specified frame to the XBee.  This method does not block waiting for a response, but 
+     /** Transmit the specified frame to the XBee.  This method does not block waiting for a response, but returns and
+         expects that any response will be dealt with by an appropriately registered decoder
+     
+         The XBee represents frames as:
+    
+         --------------------------------------------------------------------------
+        | Start Delimiter | Length  | API identifier | ID specific data | Checksum |
+        |  1 byte         | 2 bytes | 1 byte         | x bytes          | 1 byte   |
+        |      0x7e       | MSB LSB | APIID          | ... ... ...      | CKSUM    |
+         --------------------------------------------------------------------------
+    
+         The method uses the XBeeApiFrame class methods to fill in the length, API ID & data.
      
          \param p_cmd Frame to be transmitted
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utility/XBeeApiCmdAt.cpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,172 @@
+/** 
+
+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'
+
+/* Content for the various commands - value of 0 indicates a value to be populated (i.e. variable) */
+
+const uint8_t cmd_vr[] = { CMD_RESPONSE_GET_VR, 'V', 'R' }; 
+const uint8_t cmd_hv[] = { CMD_RESPONSE_GET_HV, 'H', 'V' }; 
+const uint8_t cmd_ch[] = { CMD_RESPONSE_GET_CH, 'C', 'H' }; 
+const uint8_t cmd_set_ch[] = { CMD_RESPONSE_SET_CH, 'C', 'H', 0 }; 
+
+#define XBEE_CMD_POSN_FRAME_ID (4U)
+#define XBEE_CMD_POSN_PARAM_START (8U)
+
+XBeeApiCmdAt::XBeeApiCmdAt() : XBeeApiFrameDecoder( ) , m_haveHwVer( false ),
+                                                        m_haveFwVer( false ),
+                                                        m_haveChan( false )
+{
+}
+
+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 ] )
+    {
+    
+        switch( p_data[ XBEE_CMD_POSN_FRAME_ID ] )
+        {
+            case CMD_RESPONSE_GET_HV:
+                m_haveHwVer = true;
+                // TODO: Is this right?
+                m_hwVer = ((uint16_t)p_data[ XBEE_CMD_POSN_PARAM_START ] << 8) + p_data[ XBEE_CMD_POSN_PARAM_START + 1 ];
+                ret_val = true;
+                break;
+    
+            case CMD_RESPONSE_GET_VR:
+                m_haveFwVer = true;
+                // TODO: Is this right?
+                m_fwVer = ((uint16_t)p_data[ XBEE_CMD_POSN_PARAM_START ] << 8) + p_data[ XBEE_CMD_POSN_PARAM_START + 1 ];
+                ret_val = true;
+                break;
+                
+            case CMD_RESPONSE_GET_CH:
+                m_haveChan = true;
+                m_chan = p_data[ XBEE_CMD_POSN_PARAM_START ];
+                ret_val = true;
+                break;
+    
+            case CMD_RESPONSE_SET_CH:
+                m_chan = m_chanPend;
+                m_haveChan = true;
+                ret_val = true;    
+                break;
+        }
+    }
+    return ret_val;
+}
+
+bool XBeeApiCmdAt::setChannel( uint8_t const p_chan )
+{
+    XBeeApiCmdAt::XBeeApiCmdAtChannelSet req( p_chan );
+    m_chanPend = p_chan;
+    m_device->SendFrame( &req );
+    
+    return true;
+}
+
+void XBeeApiCmdAt::requestHardwareVersion( void )
+{
+    XBeeApiCmdAt::XBeeApiCmdAtHardwareVersionRequest req;
+    m_haveHwVer = false;    
+    m_device->SendFrame( &req );
+}
+    
+void XBeeApiCmdAt::requestFirmwareVersion( void )
+{
+    XBeeApiCmdAt::XBeeApiCmdAtFirmwareVersionRequest req;
+    m_haveFwVer = false;
+    m_device->SendFrame( &req );       
+}
+
+void XBeeApiCmdAt::requestChannel( void )
+{
+    XBeeApiCmdAt::XBeeApiCmdAtChannelRequest req;
+    m_haveChan = false;
+    m_device->SendFrame( &req );
+}
+
+bool XBeeApiCmdAt::getFirmwareVersion( uint16_t* const p_ver ) const
+{
+    if( m_haveFwVer )
+    {
+        *p_ver = m_fwVer;
+    }
+    return m_haveFwVer;
+    
+}
+
+bool XBeeApiCmdAt::getHardwareVersion( uint16_t* const p_ver ) const
+{
+    if( m_haveHwVer )
+    {
+        *p_ver = m_hwVer;
+    }
+    return m_haveHwVer;
+}
+
+bool XBeeApiCmdAt::getChannel( uint8_t* const p_chan ) const
+{
+    if( m_haveChan )
+    {
+        *p_chan = m_chan;
+    }
+    return m_haveChan;
+}
+
+
+XBeeApiCmdAt::XBeeApiCmdAtFirmwareVersionRequest::XBeeApiCmdAtFirmwareVersionRequest( void ) : XBeeApiFrame( )
+{
+     m_apiId = XBEE_CMD_AT_CMD;
+     m_data = cmd_vr;
+     m_dataLen = sizeof( cmd_vr );
+}
+
+XBeeApiCmdAt::XBeeApiCmdAtHardwareVersionRequest::XBeeApiCmdAtHardwareVersionRequest( void ) : XBeeApiFrame( )
+{
+     m_apiId = XBEE_CMD_AT_CMD;
+     m_data = cmd_hv;
+     m_dataLen = sizeof( cmd_hv );
+}
+
+XBeeApiCmdAt::XBeeApiCmdAtChannelRequest::XBeeApiCmdAtChannelRequest( void ) : XBeeApiFrame( )
+{
+     m_apiId = XBEE_CMD_AT_CMD;
+     m_data = cmd_ch;
+     m_dataLen = sizeof( cmd_ch );
+}
+
+XBeeApiCmdAt::XBeeApiCmdAtChannelSet::XBeeApiCmdAtChannelSet( const uint8_t p_chan ) : XBeeApiFrame( )
+{
+     m_apiId = XBEE_CMD_AT_CMD;
+     m_buffer[0] = cmd_set_ch[0];
+     m_buffer[1] = cmd_set_ch[1];
+     m_buffer[2] = cmd_set_ch[2];
+     m_buffer[3] = p_chan;
+     m_data = m_buffer;
+     m_dataLen = sizeof( cmd_set_ch );
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utility/XBeeApiCmdAt.hpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,98 @@
+/**
+   @file
+   @brief Class to abstract AT commands send to the XBee API
+   
+   AT commands have the payload:
+   
+     Byte 1     : Frame ID
+     Byte 2 & 3 : AT command
+     Byte 4-n   : Parameter Value 
+   
+   @author John Bailey 
+
+   @copyright Copyright 2014 John Bailey
+
+   @section LICENSE
+   
+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.
+
+*/
+
+#if !defined XBEEAPICMDAT_HPP
+#define      XBEEAPICMDAT_HPP
+
+#include "XBeeApiFrame.hpp"
+#include "XBeeDevice.hpp"
+
+#include <stdint.h>
+
+class XBeeApiCmdAt : public XBeeApiFrameDecoder
+{
+    protected:
+        bool m_haveHwVer;
+        bool m_haveFwVer;
+        bool m_haveChan;
+        uint16_t m_hwVer;
+        uint16_t m_fwVer;
+        uint8_t m_chan;
+        uint8_t m_chanPend;
+    
+        class XBeeApiCmdAtFirmwareVersionRequest : public XBeeApiFrame
+        {
+            public:
+                XBeeApiCmdAtFirmwareVersionRequest( void );
+        };
+
+        class XBeeApiCmdAtHardwareVersionRequest : public XBeeApiFrame
+        {
+            public:
+                XBeeApiCmdAtHardwareVersionRequest( void );
+        };
+
+        class XBeeApiCmdAtChannelRequest : public XBeeApiFrame
+        {
+            public:
+                XBeeApiCmdAtChannelRequest( void );
+        };
+
+        class XBeeApiCmdAtChannelSet : public XBeeApiFrame
+        {
+            uint8_t m_buffer[ 10 ];
+            public:
+                XBeeApiCmdAtChannelSet( const uint8_t p_chan );
+        };
+
+    public:
+       XBeeApiCmdAt( );
+       
+       void requestHardwareVersion( void );
+       void requestFirmwareVersion( void );
+       void requestChannel( void );
+
+       bool getHardwareVersion( uint16_t* const p_ver ) const;
+       bool getFirmwareVersion( uint16_t* const p_ver ) const;
+       bool getChannel( uint8_t* const p_chan ) const;
+       
+       bool setChannel( uint8_t const p_chan );
+       
+       /* Implement XBeeApiCmdDecoder interface */
+       
+       virtual bool decodeCallback( const uint8_t* const p_data, size_t p_len );
+       virtual uint8_t getCmdType( void ) const;
+
+       typedef uint16_t panId_t;
+       typedef uint8_t  channel_t;
+};
+
+
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utility/XBeeApiSetupHelper.cpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,35 @@
+/** 
+
+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 "XBeeApiSetupHelper.hpp"
+
+XBeeDevice::XBeeDeviceReturn_t xbeeSetNetworkType( XBeeApiCmdAt* const p_xbeeCmd,
+                                                   const XBeeNetworkType_e p_type,
+                                                   const XBeeApiCmdAt::panId_t p_id,
+                                                   const XBeeApiCmdAt::channel_t p_chan )
+{
+    XBeeDevice::XBeeDeviceReturn_t ret_val = XBeeDevice::XBEEDEVICE_OK;
+    
+    p_xbeeCmd->setCoordinatorEnable( false );
+    p_xbeeCmd->disableEndDeviceAssociation();
+    p_xbeeCmd->setChannel( p_chan );
+    p_xbeeCmd->setPanId( p_id );
+    
+    return ret_val;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utility/XBeeApiSetupHelper.hpp	Wed Jan 29 20:19:59 2014 +0000
@@ -0,0 +1,55 @@
+/**
+   @file
+   @brief Functions to help with XBee configuration
+      
+   @author John Bailey 
+
+   @copyright Copyright 2014 John Bailey
+
+   @section LICENSE
+   
+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.
+
+*/
+
+#if !defined XBEEAPISETUPHELPER_HPP
+#define      XBEEAPISETUPHELPER_HPP
+
+#include "XBeeDevice.hpp"
+#include "XBeeApiCmdAt.hpp"
+
+typedef enum {
+    XBEE_NETWORK_TYPE_P2P,
+    XBEE_NETWORK_TYPE_NON_BEACON,
+    XBEE_NETWORK_TYPE_UNKNOWN
+} XBeeNetworkType_e;
+
+/** Set the XBee to use the specified networking model.  Thie helper function
+    assumes that the XBee device and the passed XBeeApiCmdAt-type object have already
+    been configured.
+
+    This function will block until the settings have been successfully applied or a failure
+    has been encountered.
+
+    \param p_xbeeCmd Pointer to an XBeeApiCmdAt object which has already been registered
+                     as a decoder with an XBee device.
+    \param p_type Type of network to set up - must not be XBEE_NETWORK_TYPE_UNKNOWN
+    \param p_id Network ID to use
+    \param p_chan Channel to use
+*/      
+extern XBeeDevice::XBeeDeviceReturn_t xbeeSetNetworkType( XBeeApiCmdAt* const p_xbeeCmd,
+                                                          const XBeeNetworkType_e p_type,
+                                                          const XBeeApiCmdAt::panId_t p_id,
+                                                          const XBeeApiCmdAt::channel_t p_chan );
+
+#endif /* !defined( XBEEAPISETUPHELPER_HPP ) */
\ No newline at end of file