Basic demo that shows how to control a Zumo shield using ST X-NUCLEO-IDB04A1 BlueTooth Low energy shield.

Dependencies:   BLE_API X_NUCLEO_IDB0XA1 ZumoShield mbed

ST BLE shield: https://developer.mbed.org/components/X-NUCLEO-IDB04A1/

/media/uploads/bcostm/nucleo-ble-shield.jpg

Zumo shield: https://www.pololu.com/category/169/zumo-robot-for-arduino

/media/uploads/bcostm/zumo.jpg

Android Application: TBD

SampleService.h

Committer:
bcostm
Date:
2015-10-12
Revision:
1:f9ed96482986
Parent:
0:901651f381c9

File content as of revision 1:f9ed96482986:

/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * 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.
 */

#ifndef __SAMPLE_SERVICE_H__
#define __SAMPLE_SERVICE_H__

#include "mbed.h"
#include "Stream.h"

#include "ble/UUID.h"
#include "ble/BLE.h"
#include "Utils.h"

//extern DigitalOut led1;

extern const uint8_t  SampleServiceUUID[UUID::LENGTH_OF_LONG_UUID];
extern const uint16_t SampleServiceShortUUID;

extern const uint8_t  TXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID];
extern const uint8_t  RXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID];

/**
* @class SampleService
* @brief BLE Service to enable ... over BLE
*/
class SampleService {
public:
    /**< Maximum length of data (in bytes) that can be transmitted by the Sample service module to the peer. */
    static const unsigned BLE_SAMPLE_SERVICE_MAX_DATA_LEN = (BLE_GATT_MTU_SIZE_DEFAULT - 3);

public:

    /**
    * @param[ref] ble
    *               BLE object for the underlying controller.
    */
    SampleService(BLE &_ble, void (*appCbk)(const uint8_t*, uint16_t)) :
        ble(_ble),
        receiveBuffer(),
        sendBuffer(),
        sendBufferIndex(0),
        numBytesReceived(0),
        receiveBufferIndex(0),
        txCharacteristic(TXCharacteristicUUID, sendBuffer, 1, BLE_SAMPLE_SERVICE_MAX_DATA_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
        rxCharacteristic(RXCharacteristicUUID, receiveBuffer, 1, BLE_SAMPLE_SERVICE_MAX_DATA_LEN,
                         GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE) {
        GattCharacteristic *charTable[] = {&txCharacteristic, &rxCharacteristic};
        GattService         sampleService(SampleServiceUUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));

                appCallback = appCbk;
                
        ble.addService(sampleService);
        ble.onDataWritten(this, &SampleService::onDataWritten);
    }

    /**
     * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service.
     */
    uint16_t getTXCharacteristicHandle() {
        return txCharacteristic.getValueAttribute().getHandle();
    }

    /**
     * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service.
     */
    uint16_t getRXCharacteristicHandle() {
        return rxCharacteristic.getValueAttribute().getHandle();
    }

    /**
     * We attempt to collect bytes before pushing them to the UART RX
     * characteristic--writing to the RX characteristic will then generate
     * notifications for the client. Updates made in quick succession to a
     * notification-generating characteristic will result in data being buffered
     * in the bluetooth stack as notifications are sent out. The stack will have
     * its limits for this buffering; typically a small number under 10.
     * Collecting data into the sendBuffer buffer helps mitigate the rate of
     * updates. But we shouldn't buffer a large amount of data before updating
     * the characteristic otherwise the client will need to turn around and make
     * a long read request; this is because notifications include only the first
     * 20 bytes of the updated data.
     *
     * @param  buffer The received update
     * @param  length Amount of characters to be appended.
     * @return        Amount of characters appended to the rxCharacteristic.
     */
    size_t write(const void *_buffer, size_t length) {
        size_t         origLength = length;
        const uint8_t *buffer     = static_cast<const uint8_t *>(_buffer);

        if (ble.getGapState().connected) {
            unsigned bufferIndex = 0;
            while (length) {
                unsigned bytesRemainingInSendBuffer = BLE_SAMPLE_SERVICE_MAX_DATA_LEN - sendBufferIndex;
                unsigned bytesToCopy                = (length < bytesRemainingInSendBuffer) ? length : bytesRemainingInSendBuffer;

                /* copy bytes into sendBuffer */
                memcpy(&sendBuffer[sendBufferIndex], &buffer[bufferIndex], bytesToCopy);
                length          -= bytesToCopy;
                sendBufferIndex += bytesToCopy;
                bufferIndex     += bytesToCopy;

                /* have we collected enough? */
                if ((sendBufferIndex == BLE_SAMPLE_SERVICE_MAX_DATA_LEN) ||
                    // (sendBuffer[sendBufferIndex - 1] == '\r')          ||
                    (sendBuffer[sendBufferIndex - 1] == '\n')) {
                    ble.gattServer().write(getTXCharacteristicHandle(), static_cast<const uint8_t *>(sendBuffer), sendBufferIndex);
                    sendBufferIndex = 0;
                }
            }
        }

        return origLength;
    }

    /**
     * Helper function to write out strings.
     * @param  str The received string.
     * @return     Amount of characters appended to the rxCharacteristic.
     */
    size_t writeString(const char *str) {
        return write(str, strlen(str));
    }

    /**
     * Override for Stream::_putc()
     * @param  c
     *         This function writes the character c, cast to an unsigned char, to stream.
     * @return
     *     The character written as an unsigned char cast to an int or EOF on error.
     */
    int _putc(int c) {
        return (write(&c, 1) == 1) ? 1 : EOF;
    }

    /**
     * Override for Stream::_getc()
     * @return
     *     The character read.
     */
    int _getc() {
        if (receiveBufferIndex == numBytesReceived) {
            return EOF;
        }

        return receiveBuffer[receiveBufferIndex++];
    }

protected:
    /**
     * This callback allows the UART service to receive updates to the
     * txCharacteristic. The application should forward the call to this
     * function from the global onDataWritten() callback handler; or if that's
     * not used, this method can be used as a callback directly.
     */
    void onDataWritten(const GattWriteCallbackParams *params) {
      if (params->handle == getRXCharacteristicHandle()) {
        uint16_t bytesRead = params->len;
        if (bytesRead <= BLE_SAMPLE_SERVICE_MAX_DATA_LEN) {
          numBytesReceived   = bytesRead;
          receiveBufferIndex = 0;
          memcpy(receiveBuffer, params->data, numBytesReceived);
          if(appCallback) {
            appCallback(params->data, params->len);
          }    
        }
      }
    }

protected:
    BLE                &ble;
        void               (*appCallback)(const uint8_t*, uint16_t);

    uint8_t             receiveBuffer[BLE_SAMPLE_SERVICE_MAX_DATA_LEN]; /**< The local buffer into which we receive
                                                                       *   inbound data before forwarding it to the
                                                                       *   application. */

    uint8_t             sendBuffer[BLE_SAMPLE_SERVICE_MAX_DATA_LEN];    /**< The local buffer into which outbound data is
                                                                       *   accumulated before being pushed to the
                                                                       *   rxCharacteristic. */
    uint8_t             sendBufferIndex;
    uint8_t             numBytesReceived;
    uint8_t             receiveBufferIndex;

    GattCharacteristic  txCharacteristic; /**< From the point of view of the external client, this is the characteristic
                                           *   they'd write into in order to communicate with this application. */
    GattCharacteristic  rxCharacteristic; /**< From the point of view of the external client, this is the characteristic
                                           *   they'd read from in order to receive the bytes transmitted by this
                                           *   application. */
};

#endif /* #ifndef __SAMPLE_SERVICE_H__*/