This is a demonstration of how to create a GATT service and characteristic.

Dependencies:   BLE_API mbed nRF51822

Fork of BLE_EvothingsExample_GATT by Austin Blackstone

Intro

This code demonstrates how to use the BLE_API to create a GATT service and characteristic to toggle a LED on / off.

Overview

This code is a demonstration of how to create a custom service (UUID=0xA0000) with two characteristics, a read only characteristic (UUID=0xA001) and a write characteristic (UUID=0xA002). What is written to the write characteristic will be copied across to the read characteristic and broadcast out. If a single byte is written it will be used to toggle the on board LED, if more than 1 byte is written the data will be written out to the terminal. The default max size is 10bytes.

Video

This is a video of how to use this example. Please note that in this video Android is used to read / write the characteristics. This could just as easily been done with the Evothings App listed below or an equivalent iOS app. Any app that can read/write characteristics could have been used.

Details

characteristic and service UUID's are initialized here

UUID's

uint16_t customServiceUUID  = 0xA000;
uint16_t readCharUUID       = 0xA001;
uint16_t writeCharUUID      = 0xA002;


We set up the list of available UUID's that will be advertised as part of the GAP advertising packet here. (it is good form to make this match the services you are actually advertising, so in this case we should set it to be 0xA000, but we are choosing to set it to 0xFFFF so it is easier to distinguish on the scanning app)

Set_ServiceID's

static const uint16_t uuid16_list[]        = {0xFFFF};
...
ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list)); // UUID's broadcast in advertising packet


Next we set up the characteristics and then put them together into a service. Notice that each characteristic has a maximum of 10Bytes of Value space, this can be expanded up to 512B.

Setup_Service_&_Characteristics

// Set Up custom Characteristics
static uint8_t readValue[10] = {0};
ReadOnlyArrayGattCharacteristic<uint8_t, sizeof(readValue)> readChar(readCharUUID, readValue);
 
static uint8_t writeValue[10] = {0};
WriteOnlyArrayGattCharacteristic<uint8_t, sizeof(writeValue)> writeChar(writeCharUUID, writeValue);
 
// Set up custom service
GattCharacteristic *characteristics[] = {&readChar, &writeChar};
GattService        customService(customServiceUUID, characteristics, sizeof(characteristics) / sizeof(GattCharacteristic *));


Next we setup the writeCharCallback() function that will be called when a BLE onDataWritten event is triggered (when someone writes to a characteristic on the device). This function will check to see what characteristic is being written to and then handle it appropriately. In this case there is only one writable characteristic so its redundant, but good form for more complex service/characteristic combinations.

On_Characteristic_written_to_callback

void writeCharCallback(const GattCharacteristicWriteCBParams *params)
{
    // check to see what characteristic was written, by handle
    if(params->charHandle == writeChar.getValueHandle()) {
        // toggle LED if only 1 byte is written
        if(params->len == 1) {
            led = params->data[0];
            ...}
        // print the data if more than 1 byte is written
        else {
            printf("\n\r Data received: length = %d, data = 0x",params->len); 
            ...}
        // update the readChar with the value of writeChar
        ble.updateCharacteristicValue(readChar.getValueHandle(),params->data,params->len);
    }
}
...
// register callback function
ble.onDataWritten(writeCharCallback);
...


The last thing to do is register the service with the BLE object so it is available.

Add_Service_to_BLE_Object

...
    // add our custom service
    ble.addService(customService);
...

Viewing Data

You can use either the LightBlue app on iOS or the nRF Master Control Panel application on Android to view the advertising data. Alternatively you can use a custom GATT Evothings App to view the data.

Evothings?

Evothings is a rapid prototyping environment that uses cordova to enable you to rapidly develop smartphone applications in Javascript. Please download the Evothings workbench to your computer and the Evothings client to your smartphone. The Evothings workbench will come with a program called "mbed Evothings GATT", this Evothings Smartphone program is meant to be used with the embedded mbed code. For instructions on how to use evothings please see the reference section below.

Reference

CustomService.h

Committer:
mbedAustin
Date:
2015-02-14
Revision:
1:94152e7d8b5c

File content as of revision 1:94152e7d8b5c:

/* 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 __BLE_HEART_RATE_SERVICE_H__
#define __BLE_HEART_RATE_SERVICE_H__
 
#include "BLEDevice.h"
 
/**
* @class HeartRateService
* @brief BLE Service for HeartRate. This BLE Service contains the location of the sensor, the heartrate in beats per minute. <br>
* Service:  https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.heart_rate.xml <br>
* HRM Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml <br>
* Location: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.body_sensor_location.xml
*/
class HeartRateService {
public:
    /**
    * @enum SensorLocation
    * @brief Location of HeartRate sensor on body.
    */
    enum {
        LOCATION_OTHER = 0, /*!< Other Location */
        LOCATION_CHEST,     /*!< Chest */
        LOCATION_WRIST,     /*!< Wrist */
        LOCATION_FINGER,    /*!< Finger */
        LOCATION_HAND,      /*!< Hand */
        LOCATION_EAR_LOBE,  /*!< Earlobe */
        LOCATION_FOOT,      /*!< Foot */
    };
 
public:
    /**
     * @brief Constructor with 8bit HRM Counter value.
     *
     * @param[ref] _ble
     *               Reference to the underlying BLEDevice.
     * @param[in] hrmCounter (8-bit)
     *               initial value for the hrm counter.
     * @param[in] location
     *               Sensor's location.
     */
    HeartRateService(BLEDevice &_ble, uint8_t hrmCounter, uint8_t location) :
        ble(_ble),
        valueBytes(hrmCounter),
        hrmRate(GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, valueBytes.getPointer(),
                valueBytes.getNumValueBytes(), HeartRateValueBytes::MAX_VALUE_BYTES,
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
        hrmLocation(GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR, &location),
        controlPoint(GattCharacteristic::UUID_HEART_RATE_CONTROL_POINT_CHAR, &controlPointValue) {
        setupService();
    }
 
    /**
     * @brief Constructor with a 16-bit HRM Counter value.
     *
     * @param[in] _ble
     *               Reference to the underlying BLEDevice.
     * @param[in] hrmCounter (8-bit)
     *               initial value for the hrm counter.
     * @param[in] location
     *               Sensor's location.
     */
    HeartRateService(BLEDevice &_ble, uint16_t hrmCounter, uint8_t location) :
        ble(_ble),
        valueBytes(hrmCounter),
        hrmRate(GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, valueBytes.getPointer(),
                valueBytes.getNumValueBytes(), HeartRateValueBytes::MAX_VALUE_BYTES,
                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
        hrmLocation(GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR, &location),
        controlPoint(GattCharacteristic::UUID_HEART_RATE_CONTROL_POINT_CHAR, &controlPointValue) {
        setupService();
    }
 
    /**
     * @brief Set a new 8-bit value for heart rate.
     *
     * @param[in] hrmCounter
     *                  HeartRate in bpm.
     */
    void updateHeartRate(uint8_t hrmCounter) {
        valueBytes.updateHeartRate(hrmCounter);
        ble.updateCharacteristicValue(hrmRate.getValueAttribute().getHandle(), valueBytes.getPointer(), valueBytes.getNumValueBytes());
    }
 
    /**
     * Set a new 16-bit value for heart rate.
     *
     * @param[in] hrmCounter
     *                  HeartRate in bpm.
     */
    void updateHeartRate(uint16_t hrmCounter) {
        valueBytes.updateHeartRate(hrmCounter);
        ble.updateCharacteristicValue(hrmRate.getValueAttribute().getHandle(), valueBytes.getPointer(), valueBytes.getNumValueBytes());
    }
 
    /**
     * This callback allows the HeartRateService to receive updates to the
     * controlPoint Characteristic.
     *
     * @param[in] params
     *     Information about the characterisitc being updated.
     */
    virtual void onDataWritten(const GattCharacteristicWriteCBParams *params) {
        if (params->charHandle == controlPoint.getValueAttribute().getHandle()) {
            /* Do something here if the new value is 1; else you can override this method by
             * extending this class.
             * @NOTE: if you are extending this class, be sure to also call
             * ble.onDataWritten(this, &ExtendedHRService::onDataWritten); in
             * your constructor.
             */
        }
    }
 
private:
    void setupService(void) {
        static bool serviceAdded = false; /* We should only ever need to add the heart rate service once. */
        if (serviceAdded) {
            return;
        }
 
        GattCharacteristic *charTable[] = {&hrmRate, &hrmLocation, &controlPoint};
        GattService         hrmService(GattService::UUID_HEART_RATE_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));
 
        ble.addService(hrmService);
        serviceAdded = true;
 
        ble.onDataWritten(this, &HeartRateService::onDataWritten);
    }
 
private:
    /* Private internal representation for the bytes used to work with the vaulue of the heart-rate characteristic. */
    struct HeartRateValueBytes {
        static const unsigned MAX_VALUE_BYTES  = 3; /* FLAGS + up to two bytes for heart-rate */
        static const unsigned FLAGS_BYTE_INDEX = 0;
 
        static const unsigned VALUE_FORMAT_BITNUM = 0;
        static const uint8_t  VALUE_FORMAT_FLAG   = (1 << VALUE_FORMAT_BITNUM);
 
        HeartRateValueBytes(uint8_t hrmCounter) : valueBytes() {
            updateHeartRate(hrmCounter);
        }
 
        HeartRateValueBytes(uint16_t hrmCounter) : valueBytes() {
            updateHeartRate(hrmCounter);
        }
 
        void updateHeartRate(uint8_t hrmCounter) {
            valueBytes[FLAGS_BYTE_INDEX]    &= ~VALUE_FORMAT_FLAG;
            valueBytes[FLAGS_BYTE_INDEX + 1] = hrmCounter;
        }
 
        void updateHeartRate(uint16_t hrmCounter) {
            valueBytes[FLAGS_BYTE_INDEX]    |= VALUE_FORMAT_FLAG;
            valueBytes[FLAGS_BYTE_INDEX + 1] = (uint8_t)(hrmCounter & 0xFF);
            valueBytes[FLAGS_BYTE_INDEX + 2] = (uint8_t)(hrmCounter >> 8);
        }
 
        uint8_t       *getPointer(void) {
            return valueBytes;
        }
 
        const uint8_t *getPointer(void) const {
            return valueBytes;
        }
 
        unsigned       getNumValueBytes(void) const {
            return 1 + ((valueBytes[FLAGS_BYTE_INDEX] & VALUE_FORMAT_FLAG) ? sizeof(uint16_t) : sizeof(uint8_t));
        }
 
private:
        /* First byte = 8-bit values, no extra info, Second byte = uint8_t HRM value */
        /* See --> https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml */
        uint8_t valueBytes[MAX_VALUE_BYTES];
    };
 
private:
    BLEDevice           &ble;
 
    HeartRateValueBytes  valueBytes;
    uint8_t              controlPointValue;
 
    GattCharacteristic                   hrmRate;
    ReadOnlyGattCharacteristic<uint8_t>  hrmLocation;
    WriteOnlyGattCharacteristic<uint8_t> controlPoint;
};
 
#endif /* #ifndef __BLE_HEART_RATE_SERVICE_H__*/