imob

Dependencies:   mbedtls mbed BLE_API nRF51822 AccelSensor

RELAYService.h

Committer:
osilvam
Date:
2018-03-20
Revision:
0:5284859bb3e8
Child:
1:471d502617fe

File content as of revision 0:5284859bb3e8:

#ifndef __BLE_RELAY_SERVICE_H__
#define __BLE_RELAY_SERVICE_H__

#include "mbed.h"
#include "ble/BLE.h"
#include "ble/Gap.h"
#include "ImobStateService.h"

#define RELAY_TIME 2000000 // us
#define CTR12V_TIME 100000 // us

class RELAYService {
public:
    const static uint16_t RELAY_SERVICE_UUID = 0xC000;
    const static uint16_t RELAY_STATE_CHARACTERISTIC_UUID = 0xC001;

    RELAYService(BLEDevice &_ble, ImobStateService * imobStateServicePtr) : 
        ble(_ble),
        relayState(0),
        actuatedRelay(P0_10,0),
        Ctr12v(P0_3,0),        
        ISS(imobStateServicePtr),
        RelayCharacteristic(RELAY_STATE_CHARACTERISTIC_UUID, &relayState, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY)
    {
        GattCharacteristic *charTable[] = {&RelayCharacteristic};
        GattService relayService(RELAY_SERVICE_UUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));

        ble.addService(relayService);

        ble.gap().onDisconnection(this, &RELAYService::onDisconnectionFilter);
        ble.gattServer().onDataWritten(this, &RELAYService::onDataWritten);
    }

    GattAttribute::Handle_t getValueHandle() const 
    {
        return RelayCharacteristic.getValueHandle();
    }
    
    void updateRelayState(uint8_t newRelayState) {
        relayState = newRelayState;
        actuatedRelay = newRelayState;
        ble.gattServer().write(RelayCharacteristic.getValueHandle(), &relayState, 1);
    }
    
    void activate()
    {
        Ctr12v = 1;
        wait_us(CTR12V_TIME);
        updateRelayState(1);
        wait_us(RELAY_TIME);//depending of the time switching desired
        updateRelayState(0);
        wait_us(CTR12V_TIME);
        Ctr12v = 0;   
    }

protected:

    void onDisconnectionFilter(const Gap::DisconnectionCallbackParams_t *params)
    {   
        if(authenticated && activated)
        {
            activate();
            //ISS->resetAuthenticationValues();
        }
    }
    
    virtual void onDataWritten(const GattWriteCallbackParams *params)
    {          
        if ((params->handle == RelayCharacteristic.getValueHandle()) && (params->len == 1) && authenticated)
        {
            activate();
            ISS->resetAuthenticationValues();
            
            if(!activated)
                ISS->updateActivationValue(1);
        }
        else
            updateRelayState(0);
    }     

private:
    
    BLEDevice &ble;
    uint8_t relayState;
    DigitalOut actuatedRelay;
    DigitalOut Ctr12v;
    
    ImobStateService * ISS;

    ReadWriteGattCharacteristic<uint8_t> RelayCharacteristic;
};

#endif /* #ifndef __BLE_RELAY_SERVICE_H__ */