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.

Base/XBeeDevice.cpp

Committer:
johnb
Date:
2014-08-08
Revision:
56:7fe74b03e6b1
Parent:
51:a7d0d2ef9261

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 "XBeeDevice.hpp"
#include "XBeeApiCfg.hpp"
#include "XBeeApiTxFrame.hpp"

/** Number of bytes we need to 'peek' into the receive buffer in order to retrieve the 
    payload length */
#define INITIAL_PEEK_LEN XBEE_API_FRAME_OVERHEAD_START
    
/** 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' };

#if defined XBEEAPI_CONFIG_USING_RTOS
#if defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER

#if XBEEAPI_CONFIG_RTOS_DISPATCHER_LIST_SIZE < 1
#error Can't deal with XBEEAPI_CONFIG_RTOS_DISPATCHER_LIST_SIZE being less than 1
#endif

/** List of XBeeDevices that will receive RX dispatches from the XBeeRxDispatch thread */
static FixedLengthList<XBeeDevice*, XBEEAPI_CONFIG_RTOS_DISPATCHER_LIST_SIZE> s_XBeeDevices;

/** Serial data is received in the interrupt context which signals this thread to call
    the XBeeDevice classes in order to deal with the data */
void XBeeRxDispatch(void const *args) {
    while (true) {
        // Wait for a signal to that there's data ready to be examined.
        osSignalWait(0x1, osWaitForever);

        /* Loop all devices - TODO: could make this more efficient and skip devices with no data?
           TODO: mutex the list to prevent modification while iterating */
        for( FixedLengthList<XBeeDevice*, XBEEAPI_CONFIG_RTOS_DISPATCHER_LIST_SIZE>::iterator it = s_XBeeDevices.begin();
             it!= s_XBeeDevices.end();
             it++ )
        {
            (*it)->checkRxDecode();
        }
    }
}

osThreadDef(XBeeRxDispatch, osPriorityNormal, XBEEAPI_CONFIG_RTOS_DISPATCHER_TASK_STACK_SIZE);
static osThreadId XBeeRxDispatchTID = NULL;

#endif // defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER
#endif // defined XBEEAPI_CONFIG_USING_RTOS

void XBeeDevice::init()                          
{
    m_model = XBeeDevice::XBEEDEVICE_S1;
    m_inAtCmdMode = false;
    m_rxMsgLastWasEsc = false;
    m_escape = true;
    m_ignoreBadCsum = false;
    m_badCsumCount = 0U;
    m_serialBytesDiscarded = 0U;
}

XBeeDevice::XBeeDevice( PinName p_tx, PinName p_rx, PinName p_rts, PinName p_cts ):  m_serialNeedsDelete( true )
{    
    init();
        
    m_if = new RawSerial( p_tx, p_rx ); 

    /* 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( RawSerial* p_serialIf ): m_if( p_serialIf ),
                                              m_serialNeedsDelete( true )
{    
    init();
}

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();
    }
    if( m_serialNeedsDelete )
    {
        delete( m_if );
    }
#if defined XBEEAPI_CONFIG_USING_RTOS && defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER
    s_XBeeDevices.remove( this );
#endif // defined XBEEAPI_CONFIG_USING_RTOS && defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER

}

XBeeDevice::XBeeDeviceModel_t XBeeDevice::getXBeeModel() const
{
    return m_model;
}
     
void XBeeDevice::setXBeeModel( const XBeeDevice::XBeeDeviceModel_t p_model )
{
    m_model = p_model;
}

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 ) 
    {
        /* Safeguard - if we're in cmd mode, clear out status associated with API mode */
        m_rxMsgLastWasEsc = false;
    } 
    else 
    {
#if defined XBEEAPI_CONFIG_USING_RTOS && defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER
        /* Not going to check for API data here in the interrupt handler - set a signal
           to the handling thread */
        osSignalSet(XBeeRxDispatchTID, 0x1);
#else
        /* Check to see if there's API data to decode */
        checkRxDecode();
#endif
    }
}

void XBeeDevice::checkRxDecode( void )
{
    uint8_t buff[INITIAL_PEEK_LEN];
    bool cont = false;
    
    /* Ensure that we're delimiter aligned - this should allow recovery in the case that
       we've missed bytes and somehow become unaligned */
    while( m_rxBuff.getSize() &&
          ( m_rxBuff[0] != XBEE_SB_FRAME_DELIMITER ))
    {
        m_rxBuff.chomp( 1 );
        m_serialBytesDiscarded++;
    }
    
    do {
        /* Get an initial portion of data from the read buffer so that the message length can be determined */
        uint16_t len = m_rxBuff.peek( buff, INITIAL_PEEK_LEN );    
        cont = false;

        /* Ensure that sufficient data was received - already know that we should be delimiter aligned based on the above */
        if( len >= INITIAL_PEEK_LEN ) 
        {
            /* Try and get enough data to cover the whole message */
            const uint16_t cmdLen = MSG_LEN_IN_BUFFER( buff ) + XBEE_API_FRAME_OVERHEAD;

            /* Safety check */            
            if( cmdLen <= ( XBEE_API_MAX_TX_PAYLOAD_LEN + XBEE_API_FRAME_OVERHEAD ))
            {
                uint8_t cmdBuff[cmdLen];
                /* TODO: could consider not "peek" ing here, but working on the rxBuff directly!  Would save (stack) memory at 
                   the expense of a little speed, but would need decoder API to change (decodeCallback()) ... */
                uint16_t len = m_rxBuff.peek( cmdBuff, cmdLen );    
        
                /* Check that we've received the entire frame */
                if( len >= cmdLen )
                {
                    bool doProcess = true;
    
                    /* Checksum verification, performed only if it's configured */
                    if( !m_ignoreBadCsum )
                    {
                        if( !verifyFrameChecksum( cmdBuff, cmdLen ))
                        {
                            doProcess = false;
                            m_badCsumCount++;
                        }
                    }
                    
                    if( doProcess )
                    {                        
                        /* 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 );
    
                    /* Successfully decoded 1 message ... there may be more waiting in the buffer! */                
                    cont = true;
                }
            }
        }
    } while( cont );
}

bool XBeeDevice::registerDecoder( XBeeApiFrameDecoder* const p_decoder )
{
    bool ret_val = false;
    if( p_decoder != NULL )
    {
        /* Check if decoder already registered */
        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 )
    {
        if( m_decoders.remove( p_decoder ) )
        {
            p_decoder->unregisterCallback();
            ret_val = true;   
        }
    }
    return ret_val;
}

void XBeeDevice::SendFrame( XBeeApiFrame* const p_cmd )
{
    uint8_t sum = 0U;
    uint16_t len;
    uint16_t i;
    const uint8_t* cmdData;
    uint16_t written = 0;
 
#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());
    len--;

    /* While data still to go out */
    while( written < len ) 
    {
        uint16_t buffer_len;     
        
        /* Get the next chunk of data from the frame object */
        p_cmd->getDataPtr( written, &cmdData, &buffer_len );

        /* Write the buffer to the XBee */
        for( i = 0;
             i < buffer_len;
             ++i,++written )
        {
            sum += xbeeWrite(cmdData[i]);
        }
    }
     
    /* Checksum is 0xFF - summation of bytes (excluding delimiter and length) */
    xbeeWrite( (uint8_t)0xFFU - sum );
    
#if defined XBEE_DEBUG_DEVICE_DUMP_MESSAGE_DECODE
    m_if.printf("\r\n");
#endif
    
#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 defined XBEE_DEBUG_DEVICE_DUMP_MESSAGE_DECODE
        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 defined XBEE_DEBUG_DEVICE_DUMP_MESSAGE_DECODE
        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 = XBEEDEVICE_TIMEOUT;

    if( m_inAtCmdMode )
    {
        Timer t;
#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]);
        }
        
        t.start();
        
        while(( ret_val != XBEEDEVICE_OK ) && 
              ( t.read_ms() < p_wait_ms ))
        {
            wait_ms( 100 );
                
            /* Check the response for the OK indicator */
            while(( ret_val != XBEEDEVICE_OK ) && 
                  ( m_rxBuff.getSize() >= OK_LEN ))
            {
                uint8_t ok_buff[OK_LEN];

                ret_val = XBEEDEVICE_UNEXPECTED_DATA;                    

                m_rxBuff.peek( ok_buff, OK_LEN );
                        
                if( IS_OK( ok_buff ))
                {
                    ret_val = XBEEDEVICE_OK;
                    m_rxBuff.chomp( OK_LEN );
                } 
                else 
                {
                    m_rxBuff.chomp(1);
                }
            }
        }
#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;
}

void XBeeDevice::setIgnoreBadChecksum( const bool p_shouldIgnore )
{
    m_ignoreBadCsum = p_shouldIgnore;
}
     
uint16_t XBeeDevice::getBadChecksumCount( void ) const
{
    return m_badCsumCount;
}

uint16_t XBeeDevice::getSerialBytesDiscardedCount( void ) const
{
    return m_serialBytesDiscarded;
}

bool XBeeDevice::verifyFrameChecksum( const uint8_t* const p_data, size_t p_len )
{
    /* TODO: Could try and be "smarter" and build the checksum as the frame is RX'd */

    /* Don't include bytes that aren't checksummed */
    size_t ctr = p_len - XBEE_API_FRAME_OVERHEAD;
    /* Skip over the start delimiter and length (not included in checksum) */
    const uint8_t* dat = p_data + XBEE_API_FRAME_OVERHEAD_START;
    
    uint8_t sum = 0;

    do
    {
        sum += *dat;
        dat++;
        ctr--;
    } while( ctr > 0 );

    sum = 0xFFU - sum;
    
    return( sum == (*dat));
}


#if defined XBEEAPI_CONFIG_USING_RTOS && defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER
bool XBeeDevice::setupDispatchTask( void )
{
    bool ret_val = false;
    
    /* Ensure the dispatch thread exists */
    if( XBeeRxDispatchTID == NULL )
    {
        XBeeRxDispatchTID = osThreadCreate(osThread(XBeeRxDispatch), NULL);
    }
    
    /* Register this device in the list that need dispatch */
    if( s_XBeeDevices.push( this ) )
    {
        ret_val = true;
    }
    
    return ret_val;
}
#endif // defined XBEEAPI_CONFIG_USING_RTOS && defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER

#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