Dependencies:   BLE_API mbed nRF51822

Fork of SensorModulePIR by ModoSmart

main.cpp

Committer:
MisterGiet
Date:
2016-11-22
Revision:
1:839f9cac1eca
Parent:
0:eb280529b0ef
Child:
3:53db6c57bb61

File content as of revision 1:839f9cac1eca:

#include "mbed.h"
//#include "HDC1000.h"
#include "BLE.h"
#include "HealthThermometerService.h"
//#include "SetTemperatureService.h"
//#include "SetModeService.h"
//#include "UARTService.h"
#include "PresenceDetectionService.h"
#include "TemperatureMeasureService.h"

#include "ble_gatt.h"
#include "Si7020.h"

Serial pc(p22, p23);
//Serial pc(USBTX, USBRX); 
//I2C i2c(PIN_SDA,PIN_SCL);
I2C i2c(p12, p13);
Si7020 tempsensor(&i2c);

InterruptIn motion(p11);
//InterruptIn motion(p8);
//InterruptIn motion(p23);

DigitalOut led(p21, 1);
//DigitalOut led(LED2, 0);

BLE ble;

const static char     DEVICE_NAME[]        = "SensorModulePIR";
//static const uint16_t uuid16_list[]        = {GattService::UUID_HEALTH_THERMOMETER_SERVICE, SetTemperatureService::SET_TEMPERATURE_SERVICE_UUID};
static const uint16_t uuid16_list[]        = {GattService::UUID_HEALTH_THERMOMETER_SERVICE};

static volatile bool  triggerSensorPolling = false;
uint8_t presence_now = 0;
uint8_t presence_before = 0;
float currentTemperature;

PresenceDetectionService *presenceService = NULL;
TemperatureMeasureService *temperatureService = NULL;

void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    //led = !led;
    pc.printf("Disconnected\r\n");
    ble.gap().startAdvertising();
}

/**
 * This function is called when the ble initialization process has failed
 */
void onBleInitError(BLE &ble, ble_error_t error)
{
    /* Initialization error handling should go here */
}

float getTemperature(void)
{
    /*
    float t = hdc1000.temperature();
    t = t/0x10000*165-40;
    pc.printf("Temperature: %f \n", t);
    
    return t;
    */

    //float t = 26.8;
    //return t;
    
    float temp;
    if(tempsensor.getTemperature(&temp) != 0) {
        //pc.printf("Error getting temperature");
        temp = -1;
    } 
    pc.printf("Temperature = %fC\n", temp);
    
    return temp;  
}

void onDataWrittenCallback(const GattWriteCallbackParams *params) 
{
   pc.printf("Resetting presence\n");
   presence_before = 0;
}

/**
 * Callback triggered when the ble initialization process has finished
 */
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    pc.printf("Init \n");
    
    BLE &ble = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE) {
        /* In case of error, forward the error handling to onBleInitError */
        onBleInitError(ble, error);
        return;
    }

    /* Ensure that it is the default instance of BLE */
    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }
    
    //ble.gap().onConnection(connectionCallback);
    //ble.gap().onDisconnection(disconnectionCallback);
    ble.onDisconnection(disconnectionCallback);

    ble.gap().setScanParams(500, 400);
    //ble.gap().startScan(advertisementCallback);
      
    //BLE server setup
    //ble.init();
    //ble_server.gap().onDisconnection(disconnectionCallbackServer); check why gives error
    ble.gattServer().onDataWritten(onDataWrittenCallback);
    
    //Setup primary services
    presenceService = new PresenceDetectionService(ble, presence_before);
    temperatureService = new TemperatureMeasureService(ble, getTemperature());
    
    //setup advertising
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
    //ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::THERMOMETER_EAR);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.gap().setAdvertisingInterval(1000);  //1000ms 
    ble.gap().startAdvertising(); 
}

/**
*Server functions
*/

/* Restart Advertising on disconnection*/
//void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
//{
//    ble_server.gap().startAdvertising();
//}

void periodicCallbackSensor(void)
{
    //led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */

    /* Note that the periodicCallback() executes in interrupt context, so it is safer to do
     * heavy-weight sensor polling from the main thread. */
    triggerSensorPolling = true;
    pc.printf("Periodic sensor \n");
}

void periodicCallbackPresence(void)
{
    pc.printf("Periodic presence \n");
    //presence_before = 0;
}

void irq_handler(void)
{
    presence_now = 1;
    presence_before = 1;
    pc.printf("Presence detected \n");
}

int main(void)
{   
    pc.printf("Start \n");
    
    Ticker ticker_sensor;
    ticker_sensor.attach(periodicCallbackSensor, 5);
    
    Ticker ticker_presence;
    ticker_presence.attach(periodicCallbackPresence, 300);
    
    motion.rise(&irq_handler);
    
    //BLE instance setup
    BLE &bleptr = BLE::Instance();
    bleptr.init(bleInitComplete);
    
    //float initialDesiredTemperature = 20;
    
    while (true) {
        if (triggerSensorPolling && ble.getGapState().connected) {
            triggerSensorPolling = false;

            //Do blocking calls or whatever is necessary for sensor polling.
            // error = sensor.readData();
            // if (!error) {
            //     thermometerService.updateTemperature(c);
            // }

            temperatureService->updateTemperature(getTemperature());
            presenceService->updatePresence(presence_before);
        } 
        ble.waitForEvent();
        
        if(presence_now) {
            led = 0;
            //cnt++;
            presence_now = 0;
            //pc.printf("Presence detected \n", cnt);
            wait(2);
            led = 1;
        }
    }
}