/* In this code a characteristic keeps the value of "int key_value" and an android device reads this value and then put it '0' */

#include <Arduino.h>
#include <SPI.h>
#include <BLEPeripheral.h>
#include "nrf_soc.h"
#include "ble_gap.h"
#include "nrf_nvic.h"
 //#define APP_ADV_INTERVAL 4000
#define ADVERTISING_INTERVAL 4000
#define KEY 16
 //#define NON_CONNECTABLE_ADV_INTERVAL    MSEC_TO_UNITS(900, UNIT_0_625_MS)                            

 //void characteristicWrittenCallback(BLECentral&, BLECharacteristic&);
int reconnect = 0;
int key_pushed = 0;
int key_value = 0;
int i = 0;
int j = 0;

//---------------------------------------------------------------------------------------------------------------------

BLEPeripheral blePeripheral = BLEPeripheral();

BLEService ledService = BLEService("19b10000e8f2537e4f6cd104768a1214");
BLECharCharacteristic ledCharacteristic = BLECharCharacteristic("19b10001e8f2537e4f6cd104768a1214", BLERead | BLEWrite);

void setup() 
{
  pinMode(KEY,INPUT);
  sd_ble_gap_tx_power_set (-20);
 
  blePeripheral.setAdvertisedServiceUuid(ledService.uuid());
  blePeripheral.addAttribute(ledService);
  blePeripheral.addAttribute(ledCharacteristic);
  sd_ble_gap_appearance_set(20);
  blePeripheral.setLocalName("nRF51-BLE");
  
  blePeripheral.setConnectionInterval(0x03e8, 0x00c8); 
  blePeripheral.setAdvertisingInterval(ADVERTISING_INTERVAL);
  
  //ledCharacteristic.setEventHandler(BLEWritten, characteristicWrittenCallback);
  //chek.setEventHandler(BLEWritten, characteristicWrittenCallback);

  blePeripheral.begin();

  /* enable low power mode without interrupt */
  sd_power_mode_set(NRF_POWER_MODE_LOWPWR);
}

//-----------------------------------------------------------------------------------------------------------------

void loop() 
{ 
  /* poll peripheral */
  blePeripheral.poll();
  //sd_app_evt_wait();
  //sd_nvic_ClearPendingIRQ(SD_EVT_IRQn);  /*  or SWI2_IRQn */

  BLECentral central = blePeripheral.central();
  
 if(central)
 {
    reconnect = 1;
    if(digitalRead(KEY)== LOW && i == 0)   i = 1;
    if(digitalRead(KEY) == HIGH && i == 1) 
    {
      key_pushed = 1; 
      key_value ++;
      i = 0;
    } 
  
     if(key_pushed == 1)
     {   
        if(ledCharacteristic.written())
        { 
            key_value = ledCharacteristic.value(); 
            key_pushed = ledCharacteristic.value();
            
        }
        ledCharacteristic.setValue(key_value);
     }
 }
  
  else
  {   
    if(reconnect == 1)
    { 
      blePeripheral.end();  
      delay(100);   
      blePeripheral.begin(); 
      reconnect = 0; 
    }
    
    if(digitalRead(KEY)==LOW && j == 0)     j = 1;
    if(digitalRead(KEY)==HIGH && j == 1)
    { 
      key_pushed = 1; 
      key_value ++;
      j = 0;
    }

  }
}


   
  
