HTM Demo of BLE with Microbit

Dependencies:   microbit

main.cpp

Committer:
dw02136
Date:
2019-08-10
Revision:
2:7c86dc4b74a8
Parent:
1:7623f55dd990

File content as of revision 2:7c86dc4b74a8:

/*
The MIT License (MIT)

Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

#include "MicroBit.h"

const static char  DEVICE_NAME[] = "MY_MICROBIT";
static volatile bool  triggerSensorPolling = false;

MicroBit uBit;
Ticker ticker;
Serial  pc(USBTX, USBRX);

bool isConnect = false;

/* Health Thermometer Service */ 
float temperature = 25.0;
uint8_t             thermTempPayload[5] = { 0, 0, 0, 0, 0 };

GattCharacteristic  tempChar (GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR,
                                thermTempPayload, 5, 5,
                                GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE);

/* Battery Level Service */
uint8_t            batt = 100;     /* Battery level */
GattCharacteristic battLevel ( GattCharacteristic::UUID_BATTERY_LEVEL_CHAR, 
                                 (uint8_t *)batt, 1, 1,
                                 GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ);

GattCharacteristic *htmChars[] = {&tempChar, };
GattCharacteristic *battChars[] = {&battLevel, };

GattService        htmService(GattService::UUID_HEALTH_THERMOMETER_SERVICE, htmChars, 
                                sizeof(htmChars) / sizeof(GattCharacteristic *));
GattService        battService(GattService::UUID_BATTERY_SERVICE, battChars,
                                sizeof(battChars) / sizeof(GattCharacteristic *));
uint16_t             uuid16_list[] = {GattService::UUID_HEALTH_THERMOMETER_SERVICE,
                                      GattService::UUID_BATTERY_SERVICE};

static Gap::ConnectionParams_t connectionParams;

uint32_t quick_ieee11073_from_float(float temperature);
void updateServiceValues(void);

void onConnectionCallback(const Gap::ConnectionCallbackParams_t *params)
{
    isConnect = true;
    pc.printf("connected. Got handle %u\r\n", params->handle);

    connectionParams.slaveLatency = 1;
    if (uBit.ble->gap().updateConnectionParams(params->handle, &connectionParams) != BLE_ERROR_NONE) {
        pc.printf("failed to update connection paramter\r\n");
    }
}

void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    isConnect = false;
    pc.printf("Disconnected handle %u, reason %u\r\n", params->handle, params->reason);
    pc.printf("Restarting the advertising process\r\n");

    pc.printf("Start Advertising\r\n");
    uBit.ble->gap().startAdvertising();
}

void periodicCallback(void)
{
    triggerSensorPolling = true;
}

int main()
{
    // Initialise the micro:bit runtime.
    pc.printf("Initialising MicroBit\r\n");
    uBit.ble = new BLEDevice();
    uBit.init();    
    uBit.ble->init();
    pc.printf("Init done\r\n");

    uBit.ble->gap().onConnection(onConnectionCallback);
    uBit.ble->gap().onDisconnection(disconnectionCallback);

    /* setup advertising */
    uBit.ble->gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    uBit.ble->gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t*)uuid16_list, sizeof(uuid16_list));
    uBit.ble->gap().accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_THERMOMETER);
    uBit.ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    uBit.ble->gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    uBit.ble->setAdvertisingInterval(160); /* 100ms; in multiples of 0.625ms. */
    uBit.ble->startAdvertising();
    pc.printf("Start Advertising\r\n");
    
    uBit.ble->gattServer().addService(htmService);
    uBit.ble->gattServer().addService(battService);
    pc.printf("Add Service\r\n");
    
    ticker.attach(periodicCallback, 1);

    // Insert your code here!
    while(1)
    {
        if(isConnect)
        {
            uBit.display.printChar('C');
        }
        else
        {
            uBit.display.printChar('A');            
        }   
        
        //uBit.display.scroll("ADV");
        if (triggerSensorPolling) {
            triggerSensorPolling = false;
            updateServiceValues();
        } else {
            uBit.ble->waitForEvent();
        }
    }
    
    // If main exits, there may still be other fibers running or registered event handlers etc.
    // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
    // sit in the idle task forever, in a power efficient sleep.
    //release_fiber();
}

/**************************************************************************/
/*!
    @brief  Ticker callback to switch advertisingStateLed state
*/
/**************************************************************************/
void updateServiceValues(void)
{
    // Decrement the battery level.
    batt <=50 ? batt=100 : batt--;
    pc.printf("Batt is %u\r\n", batt);
    
    /* Update the temperature. Note that we need to convert to an ieee11073 format float. */
    temperature >= 30.0 ? temperature = 20.0 : temperature+=0.2;
    pc.printf("temp:%f\r\n", temperature);
    uint32_t temp_ieee11073 = quick_ieee11073_from_float(temperature);
    memcpy(thermTempPayload+1, &temp_ieee11073, 4);
    uBit.ble->gattServer().write(tempChar.getValueAttribute().getHandle(), thermTempPayload, sizeof(thermTempPayload));  //Mod
    uBit.ble->gattServer().write(battLevel.getValueAttribute().getHandle(), (uint8_t *)&batt, sizeof(batt));             //Mod
}

/**
 * @brief A very quick conversion between a float temperature and 11073-20601 FLOAT-Type.
 * @param temperature The temperature as a float.
 * @return The temperature in 11073-20601 FLOAT-Type format.
 */
uint32_t quick_ieee11073_from_float(float temperature)
{
    uint8_t  exponent = 0xFF; //exponent is -1
    uint32_t mantissa = (uint32_t)(temperature*10);
    
    return ( ((uint32_t)exponent) << 24) | mantissa;
}