aidanReceiver

Dependencies:   mbed BLE_API nRF51822

receiver_main.cpp

Committer:
khyein8154
Date:
2019-04-19
Revision:
6:55c87c9bc90e
Parent:
5:45c48a82f202
Child:
7:435abd25362e

File content as of revision 6:55c87c9bc90e:

#include "mbed.h"
#include "ble/BLE.h"
#include <string>

using namespace std;

Serial pc(USBTX, USBRX);

#define LED_RED     p21
#define LED_GREEN   p22
#define LED_BLUE    p23
#define BUTTON_PIN  p17
#define BATTERY_PIN p1

DigitalOut redLed(LED_RED);
DigitalOut blueLed(LED_BLUE);

const uint8_t TRANSMITTER_MAC_ADDRESS = 0xF34F887FED4E;

const static char DEVICE_NAME[] = "Receiver";

int latestSeqNum;

struct Data {
  uint32_t seqNum;
};

// void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)

void scanCallback(const Gap::AdvertisementCallbackParams_t *params)
{
    if (*(params->peerAddr) == (uint8_t) TRANSMITTER_MAC_ADDRESS) {
        
        // BREDR_NOT_SUPPORTED                = 0x04
        // LE_GENERAL_DISCOVERABLE            = 0x02
        // COMPLETE_LOCAL_NAME                = 0x09
        // MANUFACTURER_SPECIFIC_DATA         = 0xFF
        
        // Data received: 02 ff (MANUFACTURER_SPECIFIC_DATA) 0  (Sequence Number)
        
        const uint8_t * data = params->advertisingData;
        
        //only print when new packet received!
        if (latestSeqNum < (int)data[2]) {
            pc.printf("%d bytes data received from transmitter\n", params->advertisingDataLen);
            
            for (int i = 0; i < params->advertisingDataLen; i++) {
                if ( i >= params->advertisingDataLen-2 && data[i] == 'n' ) {
                   blueLed = 0;
                }
                pc.printf("%x ", data[i]);
            }
            pc.printf("Seq num: %d", (int)data[2]);
            pc.printf("\n");
            latestSeqNum = (int)data[2];
        }
        
        redLed = 0;
    }
    return;
}


void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE &localBle          = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        return;
    }
    
    redLed = 1;
    blueLed = 1;
    
    /* Set up scanning prodedure */
    localBle.gap().setScanParams(GapScanningParams::SCAN_INTERVAL_MAX, GapScanningParams::SCAN_WINDOW_MAX, 0, false);
    latestSeqNum = 0;
    localBle.gap().startScan(scanCallback);
    
    pc.printf("Init Completed\n");
}


int main(void)
{
    BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
    ble.init(bleInitComplete);
    
    /* SpinWait for initialization to complete. This is necessary because the
     * BLE object is used in the main loop below. */
    while (ble.hasInitialized() == false) {
        pc.printf("Intiailizing BLE\n");
    }
    
    while (1) {
        ble.waitForEvent(); // low power wait for event
    }
}