BLE to UART

Dependencies:   BLE_API Buffer mbed nRF51822

Fork of BLE_LoopbackUART by Bluetooth Low Energy

main.cpp

Committer:
yihui
Date:
2015-05-22
Revision:
12:f86bdebbebe8
Parent:
10:633cec718bf4

File content as of revision 12:f86bdebbebe8:

/* 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.
 */

#include "mbed.h"
#include "BLEDevice.h"
#include "UARTService.h"
#include "DFUService.h"
#include "Buffer.h"

#define NEED_CONSOLE_OUTPUT 0 /* Set this if you need debug messages on the console;
                               * it will have an impact on code-size and power consumption. */

#if NEED_CONSOLE_OUTPUT
#define DEBUG(...) { printf(__VA_ARGS__); }
#else
#define DEBUG(...) /* nothing */
#endif /* #if NEED_CONSOLE_OUTPUT */

Buffer <char> uartRxBuffer(0x100);
//Serial uart(p8, p7);
Serial uart(USBTX, USBRX);

BLEDevice  ble;
DigitalOut led1(p28);

UARTService *uartServicePtr;

uint8_t bleIsConnected = 0;
uint8_t bleTxFlag = 0;

bool rxPayloadUpdated = false;
uint8_t rxPayload[20 + 1] = {0,};
uint8_t txPayload[20 + 1] = {0,};

void uart2ble(void)
{
    uint16_t bytesToWrite = 0;
    for (int i = 0; i < 20; i++) {
        if (uartRxBuffer.available()) {
            txPayload[bytesToWrite] = uartRxBuffer;
            bytesToWrite++;
        }
    }

    if (bytesToWrite != 0) {
        bleTxFlag = 1;

        ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), txPayload, bytesToWrite);
    } else {
        bleTxFlag = 0;
    }
}

void resetToRunBootloader()
{
    DEBUG("Reset to run bootloader\r\n");
    NRF_POWER->GPREGRET = 0x02; 
    NVIC_SystemReset();
}

void connectionCallback(Gap::Handle_t, Gap::addr_type_t peerAddrType, const Gap::address_t peerAddr, const Gap::ConnectionParams_t *)
{
    DEBUG("Connected\r\n");
    bleIsConnected = 1;
    bleTxFlag = 0;
}

void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    DEBUG("Disconnected!\n\r");
    DEBUG("Restarting the advertising process\n\r");
    
    bleTxFlag = 0;
    bleIsConnected = 0;
    
    ble.startAdvertising();
}

void onDataWritten(const GattCharacteristicWriteCBParams *params)
{
    if ((uartServicePtr != NULL) && (params->charHandle == uartServicePtr->getTXCharacteristicHandle())) {
        uint16_t bytesRead = params->len;
        DEBUG("received %u bytes\n\r", bytesRead);
        // ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), params->data, bytesRead);
        
        for (int i = 0; i < bytesRead; i++) {
            uart.putc(params->data[i]);
        }
    }
}

void onDataSent(unsigned count)
{
    DEBUG("onDataSent\r\n");

    uart2ble();
}

void periodicCallback(void)
{
    led1 = !led1;
}

int main(void)
{
    led1 = 1;
    Ticker ticker;
    ticker.attach(periodicCallback, 0.01);

    DEBUG("Initialising the nRF51822\n\r");
    ble.init();
    ble.onConnection(connectionCallback);
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(onDataWritten);
    ble.onDataSent(onDataSent);

    /* setup advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                     (const uint8_t *)"BLE UART", sizeof("BLE UART") - 1);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
                                     (const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed));

    ble.setAdvertisingInterval(Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000));
    ble.startAdvertising();

    DFUService dfuService(ble);
    UARTService uartService(ble);
    uartServicePtr = &uartService;

    while (true) {
        uint32_t timeout = 1000;
        while (timeout) {
            timeout--;
            if (uart.readable()) {
                uartRxBuffer.put((char)uart.getc());
                timeout = 1000;
            }
        }
        
        if (bleIsConnected && bleTxFlag == 0 && uartRxBuffer.available()) {
            uart2ble();
            bleTxFlag = 1;
        }
    }
}

extern "C" void HardFault_Handler()
{
    NVIC_SystemReset();
}