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.hpp

Committer:
johnb
Date:
2014-08-08
Revision:
56:7fe74b03e6b1
Parent:
53:7b65422d7a32

File content as of revision 56:7fe74b03e6b1:

/**
   @file
   @brief Class to abstract the XBee serial interface
      
   @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 XBEEDEVICE_HPP
#define      XBEEDEVICE_HPP

#include "XBeeApiCfg.hpp"

#include "mbed.h" // For serial interface
#if defined  XBEEAPI_CONFIG_USING_RTOS
#include "rtos.h" // Mutex support
#endif

#include "FixedLengthList.hpp"
#include "CircularBuffer.h"

#include "XBeeApiFrame.hpp"

/** Class to represent an XBee device & provide an interface to communicate with it

    Actual communication is performed by:
    tx - using SendFrame to transmit messages to the XBee
    rx - registering one or more decoders (via registerDecoder) to be called when
         a message is received */
class XBeeDevice
{
   public:
     /** Represent the different XBee models */
     typedef enum {
         /* XBee S1 (aka XBee 802.15.4) - see http://www.digi.com/products/wireless-wired-embedded-solutions/zigbee-rf-modules/point-multipoint-rfmodules/xbee-series1-module */
         XBEEDEVICE_S1,
         /* XBee S1 Pro (aka XBee 802.15.4 Pro) */
         XBEEDEVICE_S1_PRO
     } XBeeDeviceModel_t;

   private:
 
     /** Common class initialisation, shared between constructors */
     void init( void );
 
#if defined  XBEEAPI_CONFIG_USING_RTOS

     /** Mutex for accessing the serial interface */
     rtos::Mutex  m_ifMutex;

#if defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER

    friend void XBeeRxDispatch(void const *args);
    
#endif // defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER

#endif // defined XBEEAPI_CONFIG_USING_RTOS
   
     /** The model of XBee that this XBeeDevice is associated with */
     XBeeDeviceModel_t m_model;
   
     /** Track whether the XBee is in CMD mode or API mode */
     bool m_inAtCmdMode;
   
     /** Track whether or not the last byte received from the XBee was an escape (i.e. the 
     next incoming byte needs to be un-escaped) */
     uint16_t m_rxMsgLastWasEsc;
   
     /** Serial interface for the XBee comms
         Use RawSerial rather than Serial so that we're OK if the RTOS is used */
     RawSerial* m_if;
     
     /** Flag to indicate if the Serial object m_if was created by this class and
         hence needs deleting in the destructor */
     bool m_serialNeedsDelete;
     
     /** Call-back function from MBED triggered when data is
         received on the XBee's serial interface */
     void if_rx( void );
     
     /** Helper function to determine whether or not there's a message to decode and to
         offer it round any registered decoders */
     void checkRxDecode( void );

     /** Write a byte to the XBee serial interface, taking care of any
         escaping requirements (see m_escape)
         
         @param p_byte Byte to be written 
         @return Sum of the byte(s) written - to be addded to the checksum 
     */
     uint8_t xbeeWrite( uint8_t p_byte, bool p_doEscape = true );

     /** Flag to indicate whether or not the dataflow is currentl being escaped */
     bool m_escape;
     
     /** Buffer of bytes received from the XBee so far */
     CircularBuffer<XBEEAPI_CONFIG_RX_BUFFER_SIZE> m_rxBuff;
     
     /** List of objects which are registered to de-code received frames */
     FixedLengthList<XBeeApiFrameDecoder*, XBEEAPI_CONFIG_DECODER_LIST_SIZE> m_decoders;
     
     /** Option as to whether bad checksum should be ignored or not */
     bool m_ignoreBadCsum;
     
     /** Rolling counter of the number of messages which failed checksum verification when
         this option is enabled.  See getBadChecksumCount() */
     uint16_t m_badCsumCount;

     /** Rolling counter of the number of received serial data bytes which have been discarded
         See getSerialBytesDiscardedCount() */
     uint16_t m_serialBytesDiscarded;
     
   public:
   
     /** Represent the status of an XBee message exchange */
     typedef enum {
         /** Successful communication */
         XBEEDEVICE_OK                = 0,
         /** No response received from the XBee within the expected time */
         XBEEDEVICE_TIMEOUT           = 1,
         /** Data received from the XBee, but was of the wrong length */
         XBEEDEVICE_UNEXPECTED_LENGTH = 2,
         /** Data received from the XBee was in an unexpected format */
         XBEEDEVICE_UNEXPECTED_DATA   = 3,
         /** XBee is currently in the wrong mode to support this request (e.g. requesting AT ASCII
             communications when in API mode) */
         XBEEDEVICE_WRONG_MODE        = 4,
     } XBeeDeviceReturn_t;
   
     /** Represents the different types of addressing for XBee devices */
     typedef enum {
         /** 16-bit addressing */
         XBEE_API_ADDR_TYPE_16BIT = 0,
         /** 64-bit addressing */
         XBEE_API_ADDR_TYPE_64BIT = 1    
     } XBeeApiAddrType_t;

     /** Constructor.  Parameters are used to specify the particulars of the connection to the XBee
     
         Objects using this constructor will default to be associated with an XBee S1 (see XBeeDeviceModel_t).  
         This should be altered via setXBeeModel() if required
     
         @param p_tx Serial interface TX pin
         @param p_rx Serial interface RX pin
         @param p_rts Pin to use for RTS (flow control).  Will only be used if supported.  Can specify NC to disable.
         @param p_rts Pin to use for CTS (flow control).  Will only be used if supported.  Can specify NC to disable.
     */
     XBeeDevice( PinName p_tx, PinName p_rx, PinName p_rts, PinName p_cts );  

     /** Constructor.  Parameters are used to specify the particulars of the connection to the XBee
     
         Objects using this constructor will default to be associated with an XBee S1 (see XBeeDeviceModel_t).  
         This should be altered via setXBeeModel() if required
     
         @param p_serialIf Pointer to the serial interface to be used to communicate with the XBee.
                           The referenced object must remain valid for as long as the XBeeDevice object is
                           being used.  Must not be NULL.
     */
     XBeeDevice( RawSerial* p_serialIf );

     /** Destructor */
     virtual ~XBeeDevice( void );  
     
     /** Determine what type of XBee model this object is associated with */
     XBeeDeviceModel_t getXBeeModel() const;
     
     /** Set the type of XBee model this object is associated with */
     void setXBeeModel( const XBeeDeviceModel_t p_model );
     
     /** 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
     */
     void SendFrame( XBeeApiFrame* const p_cmd );
     
     /** Set the XBee up in API mode.  Note that this method needs to know something about the way in which the
         attached XBee is configured (namely the guard time).  This is configured via XBeeApiCmd.hpp, currently */
     XBeeDeviceReturn_t setUpApi( void );
          
     /** Register an object as being interested in decoding messages from the XBee.  Note that each
         decoder MUST only be registered with ONE XBeeDevice.

         \param p_decoder Decoder to be registered
         \returns true in the case that registration was successful, false otherwise (decoder list full, decoder already registered, etc) */
     bool registerDecoder( XBeeApiFrameDecoder* const p_decoder );
     
     /** Remove a previous registration for decoding of messages.  The decoder will be removed from
         the list and no-longer called when XBee data is received
         
         \param p_decoder Decoder to be unregistered
         \returns true in the case that unregistration was successful, false otherwise (decoder not in list) */
     bool unregisterDecoder( XBeeApiFrameDecoder* const p_decoder );
     
     /** Set whether or not the device should ignore checksums on messages that are incorrect.
         By default the class will verify the checksums and discard frames which do not
         pass this test, incrementing a rolling counter which can be retrieved via 
         getBadChecksumCount().  Setting the class to ignore bad checksums will result in all
         frames being processed.
         
         \param p_shouldIgnore If set to true, frames with incorrect checksums will still be processed
                               If set to false, frames with incorrect checksums will not be processed
     */
     void setIgnoreBadChecksum( const bool p_shouldIgnore );
     
     /** Retrieve the number of packets which have failed the checksum test (see setIgnoreBadChecksum() )
         \returns Rolling counter of the number of failed checksum tests 
     */
     uint16_t getBadChecksumCount( void ) const;

     /** Retrieve the number of bytes received from the serial data stream which have been discarded
         Due to the fact that each API frame starts with a specific value, each time an API frame is
         to be read, the first byte should be the frame header.  If it is not then the class will
         keep reading from the stream until the frame header is encountered in order to attempt to
         re-synchronise with the stream.  Reasons for becoming out-of-sync could include not 
         managing to process the data stream fast enough 
         
         \returns A rolling counter of the number of bytes discarded so far */
     uint16_t getSerialBytesDiscardedCount( void ) const;
     
#if defined XBEEAPI_CONFIG_ENABLE_DEVELOPER
     void dumpRxBuffer( Stream* p_buf, const bool p_hexView );
#endif

#if defined XBEEAPI_CONFIG_USING_RTOS && defined XBEEAPI_CONFIG_RTOS_USE_DISPATCHER
     /** Function used (when using the MBED RTOS) to set up a thread to dispatch received data outside 
         of the interrupt context.  Handling received data within the interrupt context is likely to
         result in problems due to limited stack availability.
         Must be called once and once only (even if using multiple XBee devices)
     */
     bool setupDispatchTask();
#endif

  protected:
     /** Send an ASCII frame to the XBee.  This method blocks until a response is received
         or a timeout occurs.
         
         Note that this is a protected method as it is here to support setUpApi() with regard
         to getting the XBee into API mode.  It's not intended to be used for general
         communication with the XBee.
     
         \param p_dat ASCII data to be sent
         \param p_len Length of the data pointed to by p_dat
         \param p_wait_ms Time to wait for a response
     */
     XBeeDeviceReturn_t SendFrame( const char* const p_dat, size_t p_len, int p_wait_ms = 1000 );
     
     /** Verify the checksum of the frame pointed to.
         The referenced frame should be in unescaped form
         
         \param p_data Pointer to a buffer where the first byte is the frame start delimiter
         \param p_len Length of the p_data buffer in bytes
         \returns true in the case that the checksum passed, false in the case that it does not. 
     */
     bool verifyFrameChecksum( const uint8_t* const p_data, size_t p_len );

};

#endif