EEP fORK

Dependencies:   BLE_API mbed nRF51822

Fork of MCS_LRF by Farshad N

main.cpp

Committer:
Farshad
Date:
2015-12-09
Revision:
7:8a23a257b66a
Parent:
6:09cdafc3ffeb
Child:
8:ed66e7ef8243

File content as of revision 7:8a23a257b66a:

/* 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 "Serial.h"
#include "BLE.h"
#include "DeviceInformationService.h"
#include "UARTService.h"
#include "bleHelper.h"
#include "CircularBuffer.h"

#include "laser.h"

#undef BLE_DEBUG_OUTPUT

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

#define NEED_PARSE_TRACE   0        // only used for parsing tag data- will not work if parse function is called from within serial interrupt

Serial  pc(USBTX, USBRX);
#if NEED_CONSOLE_OUTPUT
//Serial  pc(USBTX, USBRX);
#define DEBUG(...) { pc.printf(__VA_ARGS__); }
#else
#define DEBUG(...) /* nothing */
#endif /* #if NEED_CONSOLE_OUTPUT */

#if NEED_PARSE_TRACE
#define TRACE(...) { pc.printf(__VA_ARGS__); }
#else
#define TRACE(...)
#endif /* #if NEED_TRACE */



#define SET_PARAM_CMD_MASK      0x8000  // commands with MSB set to 0 are to get the parameter and MSB of 1 to set the parameter
#define READER_BAUD_RATE        115200


BLEDevice  ble;


#undef NORDIC  // is board nordic DK?

#ifdef NORDIC
DigitalOut connectionLed(p21);
DigitalOut triggerLed(p22);
DigitalOut shutdown(p20);  // for nordic DK
Serial reader(p13, p17);  // tx, rx   === NOTE tx port pin needs to be wired and verified  (for nordic DK)
#else
DigitalOut connectionLed(p23);
Serial serial(p27, p26);  // tx, rx   === for adafruit BLE UART board (small blue board with red BLE module)
Laser laser(serial);
#endif

const static char     DEVICE_NAME[]    = "MCS_LRF";
const static char     MANUFACTURER[]   = "MCS";
const static char     MODEL[]          = "Model 1";
const static char     SERIAL_NO[]      = "SN 1234";
const static char     HARDWARE_REV[]   = "hw-rev 1";
const static char     FIRMWARE_REV[]   = "fw-rev 1";
const static char     SOFTWARE_REV[]   = "soft-rev 1";

UARTService *uartServicePtr;
BLEHelper* bleHelper;
static uint8_t isConnected = 0;

// these values must macth definitions in the XML file accompanying this device
const static uint16_t distanceCmd   = 0x0001;
const static uint16_t triggerCmd    = 0x0002;

void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    DEBUG("Disconnected!\n\r");
    DEBUG("Restarting the advertising process\n\r");
    ble.startAdvertising();
    isConnected = 0;
    connectionLed = isConnected;
}

void connectionCallback(const Gap::ConnectionCallbackParams_t *params)
{
    DEBUG("Connected!\n\r");
    isConnected = 1;
    connectionLed = isConnected;
}


uint16_t idx = 0;
const uint16_t storeSize = 300;
uint8_t store[storeSize];
bool reading = false;
bool sending = false;


static void processData(const GattWriteCallbackParams *params)
{
    if(params->len >= 2) {
        uint16_t command = params->data[0] + (params->data[1] << 8);
        bool isSetCmd = (command & SET_PARAM_CMD_MASK) == SET_PARAM_CMD_MASK;
        DEBUG("command: %d   \r\n", command);

        switch(command & ~SET_PARAM_CMD_MASK) {
            case distanceCmd:
                if(!isSetCmd && params->len == 2) {
                    // form the reply to send
                    DEBUG("CMD is GET distance\n\r");
                    // TODO can do a trigger for a new read before transimiting, For now just send the latest read
                   // laser.Connect();
                 //   laser.SetRedDot(true);
                    float distance = laser.getDistance();
                    uint8_t buf[5];
                    memcpy(&buf[0], &distance, sizeof(distance));
                    bleHelper->sendPacketOverBLE(distanceCmd, buf, sizeof(distance));
                   // laser.SetRedDot(false);
                }
                break;
                
                // TODO not needed really- can just use the distance command
                case triggerCmd:
                if(isSetCmd && params->len == 3) {
                    // form the reply to send
                    DEBUG("CMD is SET trigger\n\r");
                    // TODO can do a trigger for a new read before transimiting, For now just send the latest read
                    // make sure it is active                    
                    float distance = laser.getDistance();
                    uint8_t buf[5];
                    memcpy(&buf[0], &distance, sizeof(distance));
                     bleHelper->sendPacketOverBLE(distanceCmd, buf, sizeof(distance));
                }
                break;

            default:
                break;
        }
    }
}

void onDataWritten(const GattWriteCallbackParams *params)
{
    if ((uartServicePtr != NULL) && (params->handle == uartServicePtr->getTXCharacteristicHandle())) {
        uint16_t bytesRead = params->len;
        DEBUG("received %u bytes\n\r", bytesRead);
        for(int i = 0; i < bytesRead; i++) {
            DEBUG("0x%X ", params->data[i]);
        }
        DEBUG("\n\r", bytesRead);

        // echo?
        // ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), params->data, bytesRead);

        processData(params);
    }
}

// State machine to parse the tag data received from serial port. It only looks for EPC data in the packet
//static void parsePacket(uint8_t d)
//{
//    TRACE("%02X ", d);
//
//    
//}


uint16_t length;
//uint8_t tempBuf[1000];
void periodicCallback(void)
{
    #ifdef BLE_DEBUG_OUTPUT
    //for( idx = 0; idx < 64; idx++){         // 64 is the limit
//        store[idx] = idx;
//    }
     
    if(reading == false) {
        if(idx > 0) {
            sending = true;
            length = idx;            
            //memcpy(&tempBuf[0], &store[0], idx);                    
            sendPacketOverBLE(tagIdCmd, store, idx);
            idx = 0;        // now that we have sent this, reset the index
        }
    }
#endif

    sending = false;
}

// this is an ISR, so do not spend too much time here and be careful with printing debug info
void readerCallback()
{    
    // Note: Need to actually read from the serial to clear the RX interrupt
   // if(sending == false) {
//        reading = true;
//        while(serial.readable()) {
//            uint8_t c = serial.getc();
//            parsePacket(c);
//            #ifdef BLE_DEBUG_OUTPUT
//            store[idx] = c;
//            if(idx < (storeSize-1)) idx++;
//            #endif
//        }
//        reading = false;
//    }
}

int main(void)
{
    // default state is unknown
    connectionLed = 0;

    DEBUG("Initialising the nRF51822\n\r");
    ble.init();

    ble.onDisconnection(disconnectionCallback);
    ble.onConnection(connectionCallback);
    ble.onDataWritten(onDataWritten);

    /* setup advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME) - 1);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,(const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed));
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS,
                                     (uint8_t *)GattService::UUID_DEVICE_INFORMATION_SERVICE, sizeof(GattService::UUID_DEVICE_INFORMATION_SERVICE));
    ble.setAdvertisingInterval(GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000));
    ble.startAdvertising();

    /* Setup uart service */
    UARTService uartService(ble);
    uartServicePtr = &uartService;

    /* Setup auxiliary service. */
    DeviceInformationService deviceInfo(ble, MANUFACTURER, MODEL, SERIAL_NO,HARDWARE_REV, FIRMWARE_REV, SOFTWARE_REV);

    /* Setup bleHelper */
    BLEHelper helper(&ble, uartServicePtr);
    bleHelper = &helper;
    
    // setup serial port to LRF 
    serial.baud(READER_BAUD_RATE);
 //   serial.attach(&readerCallback);
    
    #ifdef BLE_DEBUG_OUTPUT
    Ticker ticker;
    ticker.attach(periodicCallback, 5);
    #endif
    
    laser.enableMeasurement(true);

    while (true) {
        ble.waitForEvent();
    }
}