/*
 * Copyright (c) 2014 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is confidential property of Nordic Semiconductor. The use,
 * copying, transfer or disclosure of such information is prohibited except by express written
 * agreement with Nordic Semiconductor.
 *
 */

/**
 * @brief BLE Heart Rate and Running speed Relay application main file.
 *
 * @detail This application demonstrates a simple "Relay".
 * Meaning we pass on the values that we receive. By combining a collector part on
 * one end and a sensor part on the other, we show that the s130 can function
 * simultaneously as a central and a peripheral device.
 *
 * In the figure below, the sensor ble_app_hrs connects and interacts with the relay
 * in the same manner it would connect to a heart rate collector. In this case, the Relay
 * application acts as a central.
 *
 * On the other side, a collector (such as Master Control panel or ble_app_hrs_c) connects
 * and interacts with the relay the same manner it would connect to a heart rate sensor peripheral.
 *
 * Led layout:
 * LED 1: Central side is scanning       LED 2: Central side is connected to a peripheral
 * LED 3: Peripheral side is advertising LED 4: Peripheral side is connected to a central
 *
 * @note While testing, be careful that the Sensor and Collector are actually connecting to the Relay,
 *       and not directly to each other!
 *
 *    Peripheral                  Relay                    Central
 *    +--------+        +-----------|----------+        +-----------+
 *    | Heart  |        | Heart     |   Heart  |        |           |
 *    | Rate   | -----> | Rate     -|-> Rate   | -----> | Collector |
 *    | Sensor |        | Collector |   Sensor |        |           |
 *    +--------+        +-----------|   and    |        +-----------+
 *                      | Running   |   Running|
 *    +--------+        | Speed    -|-> Speed  |
 *    | Running|------> | Collector |   Sensor |
 *    | Speed  |        +-----------|----------+
 *    | Sensor |
 *    +--------+
 */
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf.h"
#include "app_error.h"
#include "boards.h"
#include "softdevice_handler.h"
#include "app_timer.h"
#include "app_trace.h"
#include "boards.h"
#include "bsp.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "app_uart.h"
#include "ble_srv_common.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_conn_state.h"
#include "ble_db_discovery.h"
#include "ble_hci.h"
#include "nrf_log.h"
#include "our_service.h"
#include "pstorage.h"
#include "fds.h"
#include "device_manager.h"
#include "app_gpiote.h"
#include "nrf_delay.h"
#include "nrf_soc.h"
//#include "nrf_drv_timer.h"
#include "nrf_drv_rtc.h"
#include "nrf_drv_clock.h"
#include "ble_gap.h"
#include "fstorage.h"

#include "sh1.h"
#include "hmac.h"
#include "app_scheduler.h"
#include "app_timer_appsh.h"
//#include "add.h"
#include "nrf_gpio.h"
#include "pca10040.h"

#include <stdarg.h>
#include <cstdint>
#include <cstring>

 
#define APP_FEATURE_NOT_SUPPORTED   BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2

#define CENTRAL_LINK_COUNT          1                                  /**< Number of central links used by the application. When changing this number remember to adjust the RAM settings*/
#define PERIPHERAL_LINK_COUNT       1                                /**< Number of peripheral links used by the application. When changing this number remember to adjust the RAM settings*/

#define APPL_LOG                    app_trace_log                      /**< Macro used to log debug information over UART. */
#define UART_TX_BUF_SIZE            256                                /**< Size of the UART TX buffer, in bytes. Must be a power of two. */
#define UART_RX_BUF_SIZE            1                                  /**< Size of the UART RX buffer, in bytes. Must be a power of two. */

/* Central related. */

#define CENTRAL_SCANNING_LED        BSP_LED_0_MASK
#define CENTRAL_CONNECTED_LED       BSP_LED_1_MASK

#define APP_TIMER_PRESCALER         0                                  /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_MAX_TIMERS        (2+BSP_APP_TIMERS_NUMBER)          /**< Maximum number of timers used by the application. */
#define APP_TIMER_OP_QUEUE_SIZE     2                                  /**< Size of timer operation queues. */

#define SEC_PARAM_BOND              1                                  /**< Perform bonding. */
#define SEC_PARAM_MITM              0                                  /**< Man In The Middle protection not required. */
#define SEC_PARAM_LESC              0                                  /**< LE Secure Connections not enabled. */
#define SEC_PARAM_KEYPRESS          0                                  /**< Keypress notifications not enabled. */
//#define SEC_PARAM_IO_CAPABILITIES    BLE_GAP_IO_CAPS_NONE        /**< No I/O capabilities. */
#define SEC_PARAM_OOB               0                                  /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE      7                                  /**< Minimum encryption key size in octets. */
#define SEC_PARAM_MAX_KEY_SIZE      16                                 /**< Maximum encryption key size in octets. */

#define SCAN_INTERVAL               0x00A0                             /**< Determines scan interval in units of 0.625 millisecond. */
#define SCAN_WINDOW                 0x0050                             /**< Determines scan window in units of 0.625 millisecond. */

#define MIN_CONNECTION_INTERVAL     (uint16_t) MSEC_TO_UNITS(7.5, UNIT_1_25_MS)   /**< Determines minimum connection interval in milliseconds. */
#define MAX_CONNECTION_INTERVAL     (uint16_t) MSEC_TO_UNITS(30, UNIT_1_25_MS)    /**< Determines maximum connection interval in milliseconds. */
#define SLAVE_LATENCY               0                                  /**< Determines slave latency in terms of connection events. */
#define SUPERVISION_TIMEOUT         (uint16_t) MSEC_TO_UNITS(4000, UNIT_10_MS)    /**< Determines supervision time-out in units of 10 milliseconds. */

#define UUID16_SIZE                 2                                  /**< Size of a UUID, in bytes. */
#define APP_GPIOTE_MAX_USERS        3                                           /**< Maximum number of users of the GPIOTE handler. */

//#define BLE_GAP_SEC_STATUS_CONFIRM_VALUE          0x84 

#define COMPARE_COUNTERTIME  (15UL << 2)
#define SCHED_MAX_EVENT_DATA_SIZE       sizeof(app_timer_event_t)                   /**< Maximum size of scheduler events. Note that scheduler BLE stack events do not contain any data, as the events are being pulled from the stack in the event handler. */
#define SCHED_QUEUE_SIZE                10                  

uint32_t   arrt;	
uint32_t  *addr,*addr1,*tamper;
uint32_t   patwr;											
uint32_t   i;
uint32_t   pg_size;
uint32_t   pg_num;
ble_gatts_attr_t    attr_char_value;

/*These structure definitions are for HMAC algorithm*/											
struct shastate {
  uint32_t h0,h1,h2,h3,h4;
#ifdef SHA_BIG_DATA  
  uint32_t count;
#else  
  uint16_t count;
#endif  
};

extern union _digest {
  unsigned char data[20];
  struct shastate state;
} shadigest;

/**@brief Macro to unpack 16bit unsigned UUID from an octet stream. */
#define UUID16_EXTRACT(DST, SRC) \
    do                           \
    {                            \
        (*(DST))   = (SRC)[1];   \
        (*(DST)) <<= 8;          \
        (*(DST))  |= (SRC)[0];   \
    } while (0)

/**@brief Variable length data encapsulation in terms of length and pointer to data. */
typedef struct
{
    uint8_t     * p_data;    /**< Pointer to data. */
    uint16_t      data_len;  /**< Length of data. */
} data_t;

static const ble_gap_scan_params_t m_scan_param =
{
    1,              // Active scanning not set.
    0,              // Selective scanning not set.
    NULL,//&whitelist,           // No whitelist provided.
    SCAN_INTERVAL,
    SCAN_WINDOW,
    0x0000          // No timeout.
};
/**@brief Connection parameters requested for connection. */
static const ble_gap_conn_params_t m_connection_param =
{
    (uint16_t)MIN_CONNECTION_INTERVAL,
    (uint16_t)MAX_CONNECTION_INTERVAL,
    0,
    (uint16_t)SUPERVISION_TIMEOUT
};

//const nrf_drv_timer_t TIMER_LED = NRF_DRV_TIMER_INSTANCE(0);
///const nrf_drv_rtc_t rtc = NRF_DRV_RTC_INSTANCE(2);//NRF_DRV_RTC_INSTANCE(0); /**< Declaring an instance of nrf_drv_rtc for RTC0. */
//const uint8_t leds_list[LEDS_NUMBER] = LEDS_LIST;

/* Peripheral related. */

#define PERIPHERAL_ADVERTISING_LED       BSP_LED_2_MASK
#define PERIPHERAL_CONNECTED_LED         BSP_LED_3_MASK
#define IS_SRVC_CHANGED_CHARACT_PRESENT  1                                          /**< Include or not the service_changed characteristic. if not enabled, the server's database cannot be changed for the lifetime of the device*/
#define DEVICE_NAME                      "L5"                                    /**< Name of device used for advertising. */
#define MANUFACTURER_NAME                "NordicSemiconductor"                      /**< Manufacturer. Will be passed to Device Information Service. */
#define APP_ADV_INTERVAL                 300                                        /**< The advertising interval (in units of 0.625 ms). This value corresponds to 25 ms. */
#define APP_ADV_TIMEOUT_IN_SECONDS       30                                       /**< The advertising timeout in units of seconds. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(5000, APP_TIMER_PRESCALER) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY    APP_TIMER_TICKS(30000, APP_TIMER_PRESCALER)/**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT     3                                          /**< Number of attempts before giving up the connection parameter negotiation. */
#define DEAD_BEEF                       0xDEADBEEF                                 /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
#define SEC_PARAM_IO_CAPABILITIES    BLE_GAP_IO_CAPS_DISPLAY_ONLY   

#define PASSKEY_TXT                     "Passkey:"                                  /**< Message to be displayed together with the pass-key. */
#define PASSKEY_TXT_LENGTH              8                                           /**< Length of message to be displayed together with the pass-key. */
#define PASSKEY_LENGTH                  6                                           /**< Length of pass-key received by the stack for display. */
#define STATIC_PASSKEY					        "123456" 	

ble_opt_t					 m_static_pin_option;	
ble_os_t           m_our_service;
static uint8_t static_passkey[] = STATIC_PASSKEY;
static dm_application_instance_t        m_app_handle;    
static uint16_t                         m_conn_handle = BLE_CONN_HANDLE_INVALID;   
	
static app_gpiote_user_id_t             m_gpiote_user_id;
static uint8_t timer_minutes[4];// <--- already defined changed to "static"
const  nrf_drv_rtc_t rtc = NRF_DRV_RTC_INSTANCE(2);
static uint8_t count_timer=0;
static uint8_t instance;

static uint32_t					p_pins;
static uint8_t stored_key[2];
static uint8_t st[2]={0};

const volatile int key_new[2] = {0x62,0x62};
int *key_ptr = (int *)key_new;

const volatile int tampered=0;
int *ptr1 = (int*) &tampered;	

//static ble_gatts_attr_t    attr_char_value;
static ble_db_discovery_t m_ble_db_discovery[CENTRAL_LINK_COUNT + PERIPHERAL_LINK_COUNT]; /**< list of DB structures used by the database discovery module. */

APP_TIMER_DEF(m_our_char_timer_id);
#define OUR_CHAR_TIMER_INTERVAL     APP_TIMER_TICKS(1000, APP_TIMER_PRESCALER)

typedef struct
{
	nrf_ecb_hal_data_t Tampered_packet_form;
  nrf_ecb_hal_data_t Untampered_packet_form;
}form_encrypted_packet;

static bool ARMED;

form_encrypted_packet AES_packet;

/**@brief names which the central applications will scan for, and which will be advertised by the peripherals.
 *  if these are set to empty strings, the UUIDs defined below will be used
 */
static const char m_target_periph_name[] = "Vibe P1";
static const uint8_t name[] = {0x59,0x00,0x77}; 
static const uint8_t name1[]={0x59,0x00,0x01};

/**@brief UUIDs which the central applications will scan for if the name above is set to an empty string,
 * and which will be advertised by the peripherals.
 */
static ble_uuid_t       m_adv_uuids[] = {{BLE_UUID_OUR_SERVICE_UUID, BLE_UUID_TYPE_VENDOR_BEGIN}}; 

volatile uint8_t fs_callback_flag;
static fs_ret_t fs_ret;
fs_config_t fs_config;
uint32_t data;
uint32_t flash_data[4];

bool ARM_MODE = false;
bool DISARM_MODE = false;

/**@brief Function to handle asserts in the SoftDevice.
 *
 * @details This function will be called in case of an assert in the SoftDevice.
 *
 * @warning This handler is an example only and does not fit a final product. You need to analyze
 *          how your product is supposed to react in case of Assert.
 * @warning On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in] line_num     Line number of the failing ASSERT call.
 * @param[in] p_file_name  File name of the failing ASSERT call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(0xDEADBEEF, line_num, p_file_name);
}

/** @brief Function to sleep until a BLE event is received by the application.
 */
static void power_manage(void)
{
    ret_code_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}

void fs_evt_handler(fs_evt_t const * const evt, fs_ret_t result)
{
    if (result != FS_SUCCESS)
    {
       // bsp_indication_set(BSP_INDICATE_FATAL_ERROR);
			APP_ERROR_CHECK(result);
    }
		else
		{
				
				fs_callback_flag = 0;
		}
}

FS_REGISTER_CFG( fs_config_t fs_config) =
{
		.callback  = fs_evt_handler, // Function for event callbacks.
		.num_pages = 1,      // Number of physical flash pages required.
		.priority  = 0xFE            // Priority for flash usage.
};

void fstorage_init(void)
{

		fs_ret = fs_init();
		if (fs_ret != FS_SUCCESS)
		{
					APP_ERROR_CHECK(fs_ret);
		}
		
		// Erase one page (page 0).

		fs_callback_flag = 1;
		fs_ret = fs_erase(&fs_config, fs_config.p_start_addr, 1);
		if (fs_ret != FS_SUCCESS)
		{
					APP_ERROR_CHECK(fs_ret);
		}
		
		while(fs_callback_flag == 1) 
    { power_manage(); }
		
		data = 0x62006200;
	
		fs_callback_flag = 1;
		fs_ret = fs_store(&fs_config, fs_config.p_start_addr, &data,1);      //Write data to memory address 0x0003F00. Check it with command: nrfjprog --memrd 0x0003F000 --n 16
		if (fs_ret != FS_SUCCESS)
		{
					APP_ERROR_CHECK(fs_ret);
		}
		while(fs_callback_flag == 1)  { power_manage(); }			
				
		addr1 = (uint32_t *)fs_config.p_start_addr;
}

/**
 * @brief Parses advertisement data, providing length and location of the field in case
 *        matching data is found.
 *
 * @param[in]  Type of data to be looked for in advertisement data.
 * @param[in]  Advertisement report length and pointer to report.
 * @param[out] If data type requested is found in the data report, type data length and
 *             pointer to data will be populated here.
 *
 * @retval NRF_SUCCESS if the data type is found in the report.
 * @retval NRF_ERROR_NOT_FOUND if the data type could not be found.
 */
static uint32_t adv_report_parse(uint8_t type, data_t * p_advdata, data_t * p_typedata)
{
    uint32_t  index = 0;
    uint8_t * p_data;

    p_data = p_advdata->p_data;

    while (index < p_advdata->data_len)
    {
        uint8_t field_length = p_data[index];
        uint8_t field_type   = p_data[index+1];

        if (field_type == type)
        {
            p_typedata->p_data   = &p_data[index+2];
            p_typedata->data_len = field_length-1;
            return NRF_SUCCESS;
        }
        index += field_length + 1;
    }
    return NRF_ERROR_NOT_FOUND;
}
/**@brief Function for initiating scanning.
 */
static void scan_start(void)
{
    ret_code_t err_code;

	/** @brief Scan parameters requested for scanning and connection. */

    (void) sd_ble_gap_scan_stop();
	
   err_code = sd_ble_gap_scan_start(&m_scan_param);
    // It is okay to ignore this error since we are stopping the scan anyway.
    if (err_code != NRF_ERROR_INVALID_STATE)
    {
        APP_ERROR_CHECK(err_code);
    }
}

static void flash_page_erase(uint32_t * page_address)
{
    // Turn on flash erase enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Een << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    // Erase page:
    NRF_NVMC->ERASEPAGE = (uint32_t)page_address;

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    // Turn off flash erase enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }
}

static void flash_word_write(uint32_t * address, uint32_t value)
{
	
    // Turn on flash write enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    *address = value;

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }

    // Turn off flash write enable and wait until the NVMC is ready:
    NRF_NVMC->CONFIG = (NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos);

    while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
    {
        // Do nothing.
    }
}

uint32_t our_char_add(ble_os_t * p_our_service)
{
    // OUR_JOB: Step 2.A, Add a custom characteristic UUID
	uint32_t            err_code;
	ble_uuid_t          char_uuid;
	ble_uuid128_t       base_uuid = BLE_UUID_OUR_BASE_UUID;
	char_uuid.uuid      = BLE_UUID_OUR_CHARACTERISTC_UUID;
	err_code = sd_ble_uuid_vs_add(&base_uuid, &char_uuid.type);
	APP_ERROR_CHECK(err_code);
	
    // OUR_JOB: Step 2.F Add read/write properties to our characteristic
    ble_gatts_char_md_t char_md;
    memset(&char_md, 0, sizeof(char_md));
	char_md.char_props.read = 1;
 char_md.char_props.write = 0;

    // OUR_JOB: Step 3.A, Configuring Client Characteristic Configuration Descriptor metadata and add to char_md structure
    ble_gatts_attr_md_t cccd_md;
    memset(&cccd_md, 0, sizeof(cccd_md));
		BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
		BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);
		cccd_md.vloc                = BLE_GATTS_VLOC_STACK;    
		char_md.p_cccd_md           = &cccd_md;
		char_md.char_props.notify   = 1;
    
    // OUR_JOB: Step 2.B, Configure the attribute metadata
    ble_gatts_attr_md_t attr_md;
    memset(&attr_md, 0, sizeof(attr_md));  
    attr_md.vloc = BLE_GATTS_VLOC_STACK;
    
    // OUR_JOB: Step 2.G, Set read/write security levels to our characteristic
    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm);
	 BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm);
	 BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(&attr_md.read_perm);
    
    // OUR_JOB: Step 2.C, Configure the characteristic value attribute
  ble_gatts_attr_t    attr_char_value;
	memset(&attr_char_value, 0, sizeof(attr_char_value));    
	attr_char_value.p_uuid      = &char_uuid;
	attr_char_value.p_attr_md   = &attr_md;
    
    // OUR_JOB: Step 2.H, Set characteristic length in number of bytes
    attr_char_value.max_len  = 16;
    attr_char_value.init_len    = 16;
		
//		//nrf_ecb_hal_data_t Tampered_packet;
		
		uint8_t num_rand_bytes_available; 
    static uint8_t rand_number[2]= {0x00,0x00};
	  int i;
		while(1)
		{
				uint32_t err_code = sd_rand_application_bytes_available_get(&num_rand_bytes_available);
				APP_ERROR_CHECK(err_code);

				if (num_rand_bytes_available > 0)
				break;	
		}

		sd_rand_application_vector_get(rand_number, 2);
	
//		if((((uint32_t)*(addr1 + 1)) == 0xFFFFFFFF))//&&(((uint32_t)*(fs_config.p_start_addr + 1) >> 24) == 0xFF))
//		{	
//			stored_key[0]= ((uint32_t)*(fs_config.p_start_addr) >> 8);
//			stored_key[1]= ((uint32_t)*(fs_config.p_start_addr) >> 24);
//		}
//		else
//		{
//			stored_key[0]= ((uint32_t)*(addr1 + 1) >> 0);
//			stored_key[1]= ((uint32_t)*(addr1 + 1) >> 8);
//		}
	
		uint8_t key[16]	= {key_ptr[0],key_ptr[1],0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

//	 if((((uint32_t)*(addr1 + 2) == 0x00000054)) )
			if(*ptr1 == 1)
    {

//	  uint8_t form_packet[16]={0x0,0x0,0x0,AES_packet.Tampered_packet_form.cleartext[3],0x4f,0x50,0x45,0x4E,0xa,0xb,0xc,0xd,0xe,0xf,rand_number[0],rand_number[1]};
		 uint8_t form_packet[16]={0x0,0x0,0x0,*ptr1,0x4f,0x50,0x45,0x4E,0xa,0xb,0xc,0xd,0xe,0xf,rand_number[0],rand_number[1]};
			for( i=0;i<16;i++)	
			{
				AES_packet.Tampered_packet_form.cleartext[i] = form_packet[i];
				AES_packet.Tampered_packet_form.key[i] = key[i];
			}
	
    	sd_ecb_block_encrypt(&AES_packet.Tampered_packet_form); 
			attr_char_value.p_value = AES_packet.Tampered_packet_form.ciphertext;
			
		}		
   else 
   {
	 
			uint8_t	untampered_packet[16]={0x0,0x0,0x0,0x0,0x43,0x4c,0x4e,0x53,0x45,0x44,0x55,0x66,0x77,0x88,rand_number[0],rand_number[1]};
			for( i=0;i<16;i++)	
			{
				AES_packet.Untampered_packet_form.cleartext[i] = untampered_packet[i];
				AES_packet.Untampered_packet_form.key[i] = key[i];
			}
	
    	sd_ecb_block_encrypt(&AES_packet.Untampered_packet_form); 
			attr_char_value.p_value = AES_packet.Untampered_packet_form.ciphertext;
		}	 
	
    // OUR_JOB: Step 2.E, Add our new characteristic to the service
			err_code = sd_ble_gatts_characteristic_add(p_our_service->service_handle,
																				 &char_md,
																				 &attr_char_value,
																				 &p_our_service->char_handles);
			APP_ERROR_CHECK(err_code);

    return NRF_SUCCESS;
}

void our_service_init(ble_os_t * p_our_service)
{
    uint32_t   err_code; // Variable to hold return codes from library and softdevice functions

    // FROM_SERVICE_TUTORIAL: Declare 16-bit service and 128-bit base UUIDs and add them to the BLE stack
    ble_uuid_t        service_uuid;
    ble_uuid128_t     base_uuid = BLE_UUID_OUR_BASE_UUID;
    service_uuid.uuid = BLE_UUID_OUR_SERVICE_UUID;
    err_code = sd_ble_uuid_vs_add(&base_uuid, &service_uuid.type);
    APP_ERROR_CHECK(err_code);    
    
//    // OUR_JOB: Step 3.B, Set our service connection handle to default value. I.e. an invalid handle since we are not yet in a connection.
//     p_our_service->conn_handle = BLE_CONN_HANDLE_INVALID;
//    // FROM_SERVICE_TUTORIAL: Add our service
//    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
//                                        &service_uuid,
//                                        &p_our_service->service_handle);
//    APP_ERROR_CHECK(err_code);
//    
//    // OUR_JOB: Call the function our_char_add() to add our new characteristic to the service. 
//   our_char_add(p_our_service);
}

void service_status_init(ble_os_t * p_our_service)	
{
	    uint32_t   err_code; // Variable to hold return codes from library and softdevice functions

    // FROM_SERVICE_TUTORIAL: Declare 16-bit service and 128-bit base UUIDs and add them to the BLE stack
    ble_uuid_t        service_uuid;
    ble_uuid128_t     base_uuid = BLE_UUID_OUR_BASE_UUID;
    service_uuid.uuid = BLE_UUID_OUR_SERVICE_UUID;
    err_code = sd_ble_uuid_vs_add(&base_uuid, &service_uuid.type);
    APP_ERROR_CHECK(err_code);    
	
    // OUR_JOB: Step 3.B, Set our service connection handle to default value. I.e. an invalid handle since we are not yet in a connection.
     p_our_service->conn_handle = BLE_CONN_HANDLE_INVALID;
    // FROM_SERVICE_TUTORIAL: Add our service
    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY,
                                        &service_uuid,
                                        &p_our_service->service_handle);
    APP_ERROR_CHECK(err_code);
    
    // OUR_JOB: Call the function our_char_add() to add our new characteristic to the service. 
   our_char_add(p_our_service);
}

void our_tamper_characteristic_update(ble_os_t *p_our_service)
{
	if (p_our_service->conn_handle != BLE_CONN_HANDLE_INVALID)
{

	
uint16_t               len = 16;
ble_gatts_hvx_params_t hvx_params;
memset(&hvx_params, 0, sizeof(hvx_params));
hvx_params.handle = p_our_service->char_handles.value_handle;
hvx_params.type   = BLE_GATT_HVX_NOTIFICATION;
hvx_params.offset = 0;
hvx_params.p_len  = &len;
	
			uint8_t num_rand_bytes_available; 
    static uint8_t rand_number[2]= {0x00,0x00};
	  int i;
		while(1)
		{
				uint32_t err_code = sd_rand_application_bytes_available_get(&num_rand_bytes_available);
				APP_ERROR_CHECK(err_code);

				if (num_rand_bytes_available > 0)
				break;	
		}

		sd_rand_application_vector_get(rand_number, 2);
	
		if((((uint32_t)*(addr1 + 1)) == 0xFFFFFFFF))//&&(((uint32_t)*(fs_config.p_start_addr + 1) >> 24) == 0xFF))
		{	
			stored_key[0]= ((uint32_t)*(fs_config.p_start_addr ) >> 8);
			stored_key[1]= ((uint32_t)*(fs_config.p_start_addr ) >> 24);
		}
		else
		{
			stored_key[0]= ((uint32_t)*(addr1 + 1) >> 0);
			stored_key[1]= ((uint32_t)*(addr1 + 1) >> 8);
		}
	
		uint8_t key[16]	= {stored_key[0],stored_key[1],0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

			
	 if((((uint32_t)*(addr1 + 2) == 0x00000054)) )
    {

	  uint8_t form_packet[16]={0x0,0x0,0x0,AES_packet.Tampered_packet_form.cleartext[3],0x4f,0x50,0x45,0x4E,0xa,0xb,0xc,0xd,0xe,0xf,rand_number[0],rand_number[1]};
		
			for( i=0;i<16;i++)	
			{
				AES_packet.Tampered_packet_form.cleartext[i] = form_packet[i];
				AES_packet.Tampered_packet_form.key[i] = key[i];
			}
	
    	sd_ecb_block_encrypt(&AES_packet.Tampered_packet_form); 
//			attr_char_value.p_value = AES_packet.Tampered_packet_form.ciphertext;
			hvx_params.p_data = AES_packet.Untampered_packet_form.ciphertext;
		}
		
   else 
   {
	 
			uint8_t	untampered_packet[16]={0x0,0x0,0x0,0x0,0x43,0x4c,0x4e,0x53,0x45,0x44,0x55,0x66,0x77,0x88,rand_number[0],rand_number[1]};
			for( i=0;i<16;i++)	
			{
				AES_packet.Untampered_packet_form.cleartext[i] = untampered_packet[i];
				AES_packet.Untampered_packet_form.key[i] = key[i];
			}
	
    	sd_ecb_block_encrypt(&AES_packet.Untampered_packet_form); 
//			attr_char_value.p_value = AES_packet.Untampered_packet_form.ciphertext;
			hvx_params.p_data = AES_packet.Untampered_packet_form.ciphertext;
		}	 
//hvx_params.p_data = (uint8_t*)temperature_value;  
			//nrf_ecb_hal_data_t Tampered_packet;
sd_ble_gatts_hvx(p_our_service->conn_handle, &hvx_params);
}

}

/**@brief Function for initializing services that will be used by the application.
 *
 * @details Initialize the our service
 */
 static void services_init(void)
{
	   our_service_init(&m_our_service);     
}

void gpiote_event_handler(uint32_t event_pins_low_to_high, uint32_t event_pins_high_to_low)
{
	//stop timer
	//take tamper information 0/1
	//make it into packet along with timestamp when tamper happened
	//encrpt it using key and store in RAM
	//if(nrf_gpio_pin_read(20)==1)
	//{ 
		//app_timer_stop;
	  *ptr1=1;
	
if(nrf_gpio_pin_read(21))
{	
  *ptr1=1;
//	LEDS_ON(LED_1);                              
	instance=count_timer;
	AES_packet.Tampered_packet_form.cleartext[3]=instance;

  uint32_t err_code = app_gpiote_user_disable(m_gpiote_user_id); 
	APP_ERROR_CHECK(err_code);
}
}

static void init_gpiote(void)
{
	APP_GPIOTE_INIT(APP_GPIOTE_MAX_USERS);
	
	uint32_t err_code = app_gpiote_user_register(&m_gpiote_user_id, 1 <<21, 1 <<21, gpiote_event_handler);
	APP_ERROR_CHECK(err_code);
}

static void gap_params_init(void)
{
    uint32_t                err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);

   err_code = sd_ble_gap_device_name_set(&sec_mode,
                                         (const uint8_t *)DEVICE_NAME,
                                         strlen(DEVICE_NAME));
   APP_ERROR_CHECK(err_code);

    memset(&gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONNECTION_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONNECTION_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = SUPERVISION_TIMEOUT;

  err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  APP_ERROR_CHECK(err_code);
																										 
	m_static_pin_option.gap_opt.passkey.p_passkey = static_passkey;																 
	err_code =  sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &m_static_pin_option);
	APP_ERROR_CHECK(err_code);

}

/**@brief Function for handling advertising events.
 *
 * @param[in] ble_adv_evt  Advertising event.
 */
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
    switch (ble_adv_evt)
    {
        case BLE_ADV_EVT_FAST:
            LEDS_OFF(PERIPHERAL_ADVERTISING_LED);
            break;//BLE_ADV_EVT_FAST

        case BLE_ADV_EVT_IDLE:
        {
            ret_code_t err_code;
            err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
            APP_ERROR_CHECK(err_code);
        } break;//BLE_ADV_EVT_IDLE

        default:
            // No implementation needed.
            break;

    }
}

/**@brief Function for initializing the Advertising functionality.
 */

static void advertising_init(void)
{
	
	 uint32_t      err_code;
    ble_advdata_t advdata;

    // Build advertising data struct to pass into @ref ble_advertising_init.
    memset(&advdata, 0, sizeof(advdata));
    advdata.name_type               = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance      = true;
    advdata.flags                   = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
    advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
    advdata.uuids_complete.p_uuids  = m_adv_uuids;

    ble_adv_modes_config_t options = {0};
    options.ble_adv_fast_enabled  = BLE_ADV_FAST_ENABLED;
    options.ble_adv_fast_interval = APP_ADV_INTERVAL;
    options.ble_adv_fast_timeout  = APP_ADV_TIMEOUT_IN_SECONDS;

	
	  ble_advdata_manuf_data_t        manuf_data; // Variable to hold manufacturer specific data
    uint8_t data_response[]             = {'L','2',0,0,0,0,0,0,0,0,0,0,0,0,0,0};
   // manuf_data.company_identifier       = 0x0059; // Nordics company ID
    manuf_data.data.p_data              = data_response;     
    manuf_data.data.size                = sizeof(data_response);

		ble_advdata_t advdata_response;
		memset(&advdata_response,0,sizeof(advdata_response));	
		advdata_response.name_type=BLE_ADVDATA_FULL_NAME;
		advdata_response.p_manuf_specific_data=&manuf_data;		

		err_code=ble_advertising_init(&advdata,&advdata_response,&options,on_adv_evt,NULL);
		APP_ERROR_CHECK(err_code);	
}

static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    uint32_t err_code;

    if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}

/**@brief Function for handling errors from the Connection Parameters module.
 *
 * @param[in] nrf_error  Error code containing information about what went wrong.
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

/**@brief Function for initializing the Connection Parameters module.
 */
static void conn_params_init(void)
{
    uint32_t               err_code;
    ble_conn_params_init_t cp_init;

    memset(&cp_init, 0, sizeof(cp_init));

    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID; // Start upon connection.
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;  // Ignore events.
    cp_init.error_handler                  = conn_params_error_handler;
    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}

void ble_our_service_on_ble_evt(ble_os_t * p_our_service, ble_evt_t * p_ble_evt)
{
    // OUR_JOB: Step 3.D Implement switch case handling BLE events related to our service. 
	switch (p_ble_evt->header.evt_id)
{
    case BLE_GAP_EVT_CONNECTED:
        p_our_service->conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
        break;
    case BLE_GAP_EVT_DISCONNECTED:
        p_our_service->conn_handle = BLE_CONN_HANDLE_INVALID;
        break;
	
    default:
        // No implementation needed.
       break;
}
}

void scheduler_event_handler(void *p_event_data,uint16_t event_size)
{
	uint32_t tampered ='T';
//						if(*ptr1 == 1)
//					{
//					   fs_callback_flag=1;
//						 fs_ret=fs_store(&fs_config,fs_config.p_start_addr + 2,(const uint32_t *)tampered,1);
//						 if(fs_ret!=FS_SUCCESS)
//						{
//							APP_ERROR_CHECK(fs_ret);
//						}
////												while (fs_callback_flag==1) {power_manage();}
//						 nrf_delay_ms(200);
//						 fs_callback_flag=0;
//				}
				
	scan_start();
	
}

											
static void on_adv_report(const ble_evt_t * const p_ble_evt)
{
    uint32_t err_code;
    data_t   adv_data;
    bool     do_connect = false;
	
	  data_t dev_name;
		//int i;
		uint8_t data_received[16];

		uint8_t data_encrypted[16];
		//uint8_t stored_key[2];//={0x0b,0x0b};

		uint8_t old_key[2];
		uint8_t new_key[2];
		unsigned char HMAC_store_1[20];
		unsigned char HMAC_store_2[20];
	
	//sd_softdevice_disable();

    // For readibility.
    const ble_gap_evt_t * const  p_gap_evt  = &p_ble_evt->evt.gap_evt;
 
    const ble_gap_addr_t * const peer_addr  = &p_gap_evt->params.adv_report.peer_addr;
    {    
        // Initialize advertisement report for parsing

        adv_data.p_data     = (uint8_t *)p_gap_evt->params.adv_report.data;
        adv_data.data_len   = p_gap_evt->params.adv_report.dlen;
			
        //search for advertising names
        bool found_name = false;
//				err_code = adv_report_parse(BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA,
//                                    &adv_data,
//                                    &dev_name);
			err_code= adv_report_parse( BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE   ,&adv_data,&dev_name);
          
            if (err_code!= NRF_SUCCESS)
            {
                // If we can't parse the data, then exit
                return;
            }
            else
            {
                found_name = true;
            }
												
						if (p_gap_evt->params.adv_report.data[0]!=0x13)
						{
//							for(int i=7;i<23;i++)
//						{
//							data_received[i-7] = p_gap_evt->params.adv_report.data[i];
//						}
								for(int i=8;i<24;i++)
						{
							data_received[i-8] = p_gap_evt->params.adv_report.data[i];}
						
					}
						else
						{
						for(int i=4;i<20;i++)
						{
							data_received[i-4] = p_gap_evt->params.adv_report.data[i];
						}
					}
										  								 
//						if(((uint32_t)*addr1 != 0x00000031) ) //&addr==0x00
//						{
//							 stored_key[0]= 0x0b;
//							 stored_key[1]= 0x0b;
//						}
//						else
//						{
//							if((((uint32_t)*(fs_config.p_start_addr + 1)) == 0xFFFFFFFF))//&&(((uint32_t)*(fs_config.p_start_addr + 1) >> 24) == 0xFF))
//							{	
//								stored_key[0]= ((uint32_t)*(fs_config.p_start_addr) >> 8);
//								stored_key[1]= ((uint32_t)*(fs_config.p_start_addr) >> 24);
//							}
//							else if((((uint32_t)*(fs_config.p_start_addr + 1)) != 0xFFFFFFFF))
//							{
//								stored_key[0]= ((uint32_t)*(fs_config.p_start_addr + 1) >> 16);
//								stored_key[1]= ((uint32_t)*(fs_config.p_start_addr + 1) >> 24);
//							}
//							if((((uint32_t)*(addr1 + 4)) == 0xFFFFFFFF))//&&(((uint32_t)*(fs_config.p_start_addr + 1) >> 24) == 0xFF))
//							{	
//								stored_key[0]= ((uint32_t)*(fs_config.p_start_addr) >> 8);
//								stored_key[1]= ((uint32_t)*(fs_config.p_start_addr) >> 24);
//							}
//							else
//							{
//								stored_key[0]= ((uint32_t)*(addr1 + 4) >> 0);
//								stored_key[1]= ((uint32_t)*(addr1 + 4) >> 8);
//							}

						stored_key[0] = key_new[0];
						stored_key[1] = key_new[1];

//											
	         	uint8_t key_encrypt[16] = {stored_key[0],stored_key[1],0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};	   //key with which the data was decrypted 
								
						nrf_ecb_hal_data_t data_to_encrypt;

						for(int i=0;i<16;i++)
						data_to_encrypt.key[i] = key_encrypt[i];

						for(int i=0;i<16;i++)
						data_to_encrypt.cleartext[i] = data_received[i];

						sd_ecb_block_encrypt(&data_to_encrypt);

						for(int i=0;i<16;i++)
						data_encrypted[i] = data_to_encrypt.ciphertext[i];
										
        if (found_name)
        {
            if (strlen(m_target_periph_name) != 0)
            {  
						
					switch(data_encrypted[8])
					{	
						
						case 'C': //CONFIG MODE
												// *change=1;
						            sd_ble_gap_scan_stop();
												for(int i=4;i<6; i++)
												old_key[i-4] = data_encrypted[i];

												for(int i=6;i<8; i++)
												new_key[i-6] = data_encrypted[i];

										//// initialize structures with key
												HMACInit(old_key,2);
										// // hash 
												HMACBlock(new_key,2);
										// // make digest
												HMACDone();

											for(int i=0;i<20;i++)						
											HMAC_store_1[i] = shadigest.data[i];
                      
						          for(int i=0;i<2; i++)
											stored_key[i] = old_key[i];
						         // st[i]=old_key[i];
						
											//// initialize structures with key
											HMACInit(stored_key,2);
											// // hash 
											HMACBlock(new_key,2);
											// // make digest
											HMACDone();

											for(int i=0;i<20;i++)						
											HMAC_store_2[i] = shadigest.data[i];

											uint8_t count = 0;
											uint8_t KeyTransfer = 0;
											
											for(int m=0; m<20;m++)
										{
											if(HMAC_store_1[m]==HMAC_store_2[m])
													{
														count++;
														}
													else 
													{ 
														KeyTransfer=0;
														break;
												}
											}

											if (count==20) // Check whether HMAC is Verified?
											KeyTransfer=1;
											if (KeyTransfer==1)
											{
												for(int i=0; i<2; i++)
												{
													//stored_key[i] = new_key[i];
													key_ptr[i] = (int )new_key[i];
                          													
												}	

//												fs_callback_flag = 1;
//												fs_ret = fs_erase(&fs_config, fs_config.p_start_addr, 1);
//												if (fs_ret != FS_SUCCESS)
//												{
//															APP_ERROR_CHECK(fs_ret);
//												}
////												while (fs_callback_flag==1) {power_manage();}
//												
//												
//												nrf_delay_ms(1000);
//												fs_callback_flag = 0;
//												
//												nrf_delay_ms(1000);
//												fs_callback_flag=1;
//												fs_ret=fs_store(&fs_config,fs_config.p_start_addr + 4,(uint32_t *)stored_key,1);
//												if(fs_ret!=FS_SUCCESS)
//												{
//													APP_ERROR_CHECK(fs_ret);
//												}
////												while (fs_callback_flag==1) {power_manage();}
//												nrf_delay_ms(1000);
//												fs_callback_flag = 0;

												
												 advertising_init();
												 err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
												 APP_ERROR_CHECK(err_code);
											
											break;

						case 'A':	//ARM MODE		
				                 		ARM_MODE = 1;
														sd_ble_gap_scan_stop();
//						                services_init();
														advertising_init();
														err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
														APP_ERROR_CHECK(err_code);
                            for(int i=0;i<4;i++)
														{timer_minutes[i]= data_encrypted[i];}													 
														nrf_drv_rtc_enable(&rtc);
									
							break;

			   			case 'S': //STATUS MODE
								          sd_ble_gap_scan_stop();
//												services_init();
													service_status_init(&m_our_service);
//													our_tamper_characteristic_update(&m_our_service);
													advertising_init();
													err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
													APP_ERROR_CHECK(err_code);
						              //nrf_delay_ms(20);
							            //scan_start();
							break;
						
						  case 'D'://DISARM MODE
													DISARM_MODE = 1;
								          sd_ble_gap_scan_stop();
//services_init();
												  advertising_init();
													err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
													APP_ERROR_CHECK(err_code);
										
													 for(int i=0;i<4;i++)
													{ timer_minutes[i]= data_encrypted[i];
													}
													//Power on RTC instance
												    nrf_drv_rtc_enable(&rtc);
														
            	break;

					}
						
				}
			}
		}
	}
}

/**@brief Function for handling BLE Stack events concerning central applications.
 *
 * @details This function keeps the connection handles of central applications up-to-date. It
 * parses scanning reports, initiating a connection attempt to peripherals when a target UUID
 * is found, and manages connection parameter update requests. Additionally, it updates the status
 * of LEDs used to report central applications activity.
 *
 * @note        Since this function updates connection handles, @ref BLE_GAP_EVT_DISCONNECTED events
 *              should be dispatched to the target application before invoking this function.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 */
static void on_ble_central_evt(const ble_evt_t * const p_ble_evt)
{
    const ble_gap_evt_t   * const p_gap_evt = &p_ble_evt->evt.gap_evt;
    const ble_gap_addr_t * const peer_addr  = &p_gap_evt->params.adv_report.peer_addr;
    switch (p_ble_evt->header.evt_id)
    {
        /** Upon connection, check which peripheral has connected (HR or RSC), initiate DB
         *  discovery, update LEDs status and resume scanning if necessary. */
        case BLE_GAP_EVT_CONNECTED:
        {
						LEDS_ON(CENTRAL_CONNECTED_LED);
            if (ble_conn_state_n_centrals() == CENTRAL_LINK_COUNT)
            {
                LEDS_OFF(CENTRAL_SCANNING_LED);
            }
            else
            {
                // Resume scanning.
                LEDS_ON(CENTRAL_SCANNING_LED);
                scan_start();
            }
        } break; // BLE_GAP_EVT_CONNECTED

        /** Upon disconnection, reset the connection handle of the peer which disconnected, update
         * the LEDs status and start scanning again. */
        case BLE_GAP_EVT_DISCONNECTED:
        {
					//tampered = 0;
          scan_start();
        } break; // BLE_GAP_EVT_DISCONNECTED

        case BLE_GAP_EVT_ADV_REPORT:
        {
         on_adv_report(p_ble_evt);
         }
			  break;  // BLE_GAP_ADV_REPORT

        case BLE_GAP_EVT_TIMEOUT:
        {
            // We have not specified a timeout for scanning, so only connection attemps can timeout.
            if (p_gap_evt->params.timeout.src ==BLE_GAP_TIMEOUT_SRC_CONN)
            {
                APPL_LOG("[APPL]: Connection Request timed out.\r\n");
            }
						
						scan_start();
        } break; // BLE_GAP_EVT_TIMEOUT

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
        {
            // Accept parameters requested by peer.
            ret_code_t err_code;
            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                        &p_gap_evt->params.conn_param_update_request.conn_params);
            APP_ERROR_CHECK(err_code);
        } break; // BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST

        default:
            // No implementation needed.
            break;
    }
}

/**@brief Function for handling BLE Stack events involving peripheral applications. Manages the
 * LEDs used to report the status of the peripheral applications.
 *
 * @param[in] p_ble_evt  Bluetooth stack event.
 */
static void on_ble_peripheral_evt(ble_evt_t * p_ble_evt)
{
    uint32_t err_code;
    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
           // NRF_LOG_PRINTF("Peripheral connected\r\n");
           // LEDS_OFF(PERIPHERAL_ADVERTISING_LED);
           // LEDS_ON(PERIPHERAL_CONNECTED_LED);

//			   err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
//         APP_ERROR_CHECK(err_code);
         m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;

            break; //BLE_GAP_EVT_CONNECTED

        case BLE_GAP_EVT_DISCONNECTED:
            //NRF_LOG_PRINTF("Peripheral disconnected\r\n");
//            LEDS_OFF(PERIPHERAL_CONNECTED_LED); 			
            //  scan_start();
				   //m_conn_handle = BLE_CONN_HANDLE_INVALID;
            break;//BLE_GAP_EVT_DISCONNECTED
                    
        case BLE_EVT_USER_MEM_REQUEST:
            err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gap_evt.conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            break;//BLE_EVT_USER_MEM_REQUEST

        default:
            // No implementation needed.
            break;
    }
}

/**@brief Function for dispatching a BLE stack event to all modules with a BLE stack event handler.
 *
 * @details This function is called from the scheduler in the main loop after a BLE stack event has
 * been received.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 */
static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
    uint16_t conn_handle;
    uint16_t role;

    ble_conn_state_on_ble_evt(p_ble_evt);
    //pm_on_ble_evt(p_ble_evt);

    // The connection handle should really be retrievable for any event type.
    conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
    role        = ble_conn_state_role(conn_handle);

    // Based on the role this device plays in the connection, dispatch to the right applications.
    if (role == BLE_GAP_ROLE_PERIPH)
    {
        // Manages peripheral LEDs.
        dm_ble_evt_handler(p_ble_evt); 
			 ble_conn_params_on_ble_evt(p_ble_evt);
       on_ble_peripheral_evt(p_ble_evt);
       ble_advertising_on_ble_evt(p_ble_evt);
    // OUR_JOB: Step 3.C, Call ble_our_service_on_ble_evt() to do housekeeping of ble connections related to our service and characteristic
    ble_our_service_on_ble_evt(&m_our_service, p_ble_evt);  	
    }
		else if ( (role == BLE_GAP_ROLE_PERIPH) ||((p_ble_evt->header.evt_id == BLE_GAP_EVT_TIMEOUT) && (p_ble_evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_ADVERTISING))  )
		{
			if((ARM_MODE == true) || (DISARM_MODE == true))			
			{
			ARM_MODE = false;
			DISARM_MODE = false;
			}
			else 
			{
				scan_start();
			 *ptr1 = 0;
			}
		}		
    else if ((role == BLE_GAP_ROLE_CENTRAL) || (p_ble_evt->header.evt_id == BLE_GAP_EVT_ADV_REPORT))
    {
        /** on_ble_central_evt will update the connection handles, so we want to execute it
         * after dispatching to the central applications upon disconnection. */
        if (p_ble_evt->header.evt_id != BLE_GAP_EVT_DISCONNECTED)
        {
            on_ble_central_evt(p_ble_evt);
        }

        if (conn_handle < CENTRAL_LINK_COUNT + PERIPHERAL_LINK_COUNT)
        {
            ble_db_discovery_on_ble_evt(&m_ble_db_discovery[conn_handle], p_ble_evt);
        }

        // If the peer disconnected, we update the connection handles last.
        if (p_ble_evt->header.evt_id == BLE_GAP_EVT_DISCONNECTED)
        {
            on_ble_central_evt(p_ble_evt);
        }
    }
}

/**@brief Function for dispatching a system event to interested modules.
 *
 * @details This function is called from the System event interrupt handler after a system
 *          event has been received.
 *
 * @param[in]   sys_evt   System stack event.
 */
static void sys_evt_dispatch(uint32_t sys_evt)
{   
  	pstorage_sys_event_handler(sys_evt);
    //fs_sys_event_handler(sys_evt);
    ble_advertising_on_sys_evt(sys_evt);
}

/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupts.
 */
static void ble_stack_init(void)
{
    ret_code_t err_code;
    
    // Initialize the SoftDevice handler module.
    nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;
    SOFTDEVICE_HANDLER_INIT(&clock_lf_cfg, NULL);

    ble_enable_params_t ble_enable_params;
    err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT,
                                                    PERIPHERAL_LINK_COUNT,
                                                    &ble_enable_params);
    APP_ERROR_CHECK(err_code);

    //Check the ram settings against the used number of links
    CHECK_RAM_START_ADDR(CENTRAL_LINK_COUNT,PERIPHERAL_LINK_COUNT);

    // Enable BLE stack.
	   ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT;
    err_code = softdevice_enable(&ble_enable_params);
    APP_ERROR_CHECK(err_code);

    // Register with the SoftDevice handler module for BLE events.
    err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
    APP_ERROR_CHECK(err_code);

    // Register with the SoftDevice handler module for System events.
    err_code = softdevice_sys_evt_handler_set(sys_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}

static void scheduler_init(void)
{
    APP_SCHED_INIT(SCHED_MAX_EVENT_DATA_SIZE, SCHED_QUEUE_SIZE);
}

static uint32_t device_manager_evt_handler(dm_handle_t const * p_handle,
                                           dm_event_t const  * p_event,
                                           ret_code_t        event_result)
{
    APP_ERROR_CHECK(event_result);

#ifdef BLE_DFU_APP_SUPPORT
    if (p_event->event_id == DM_EVT_LINK_SECURED)
    {
        app_context_load(p_handle);
    }
#endif // BLE_DFU_APP_SUPPORT

    return NRF_SUCCESS;
}

/**@brief Function for the Peer Manager initialization.
 *
 * @param[in] erase_bonds  Indicates whether bonding information should be cleared from
 *                         persistent storage during initialization of the Peer Manager.
 */
static void device_manager_init(bool erase_bonds)
{
    uint32_t               err_code;
    dm_init_param_t        init_param = {.clear_persistent_data = erase_bonds};
    dm_application_param_t register_param;

    // Initialize persistent storage module.
    err_code = pstorage_init();
    APP_ERROR_CHECK(err_code);

    err_code = dm_init(&init_param);
    APP_ERROR_CHECK(err_code);

    memset(&register_param.sec_param, 0, sizeof(ble_gap_sec_params_t));

    register_param.sec_param.bond         = SEC_PARAM_BOND;
    register_param.sec_param.mitm         = SEC_PARAM_MITM;
    register_param.sec_param.io_caps      = SEC_PARAM_IO_CAPABILITIES;
    register_param.sec_param.oob          = SEC_PARAM_OOB;
    register_param.sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE;
    register_param.sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE;
    register_param.evt_handler            = device_manager_evt_handler;
    register_param.service_type           = DM_PROTOCOL_CNTXT_GATT_SRVR_ID;

    err_code = dm_register(&m_app_handle, &register_param);
    APP_ERROR_CHECK(err_code);
}

///**@brief Function for initializing buttons and leds.
// *
// * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to
//  *                            wake the application up.
// */
//static void buttons_leds_init(bool * p_erase_bonds)
//{
//    bsp_event_t startup_event;

//    ret_code_t err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS,
//                                 APP_TIMER_TICKS(100, APP_TIMER_PRESCALER),
//                                 NULL);
//    APP_ERROR_CHECK(err_code);

//    err_code = bsp_btn_ble_init(NULL, &startup_event);
//    APP_ERROR_CHECK(err_code);

//    *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
//}

		

/**@brief Function for the GAP initialization.
 *
 * @details This function sets up all the necessary GAP (Generic Access Profile) parameters of the
 *          device including the device name, appearance, and the preferred connection parameters.
 */

void leds_config(void)
{
    //Configure all leds on board.
    LEDS_CONFIGURE(LEDS_MASK);
    LEDS_OFF(LEDS_MASK);	
}

static void timers_init(void)
{
  // Initialize timer module.
    APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, false);

    // OUR_JOB: Step 3.H, Initiate our timer
//	app_timer_create(&m_our_char_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
}

static void appRTCHandler(nrf_drv_rtc_int_type_t int_type)
{     
	
    if (int_type == NRF_DRV_RTC_INT_COMPARE0)
    {
       	 count_timer++;
			
				if(count_timer== (timer_minutes[3]-0x30))
				{
					nrf_drv_rtc_disable(&rtc);			
//				 *ptr1=1;	
					app_sched_event_put(&p_pins,sizeof(p_pins),scheduler_event_handler);				
				}
				else
				{
					nrf_drv_rtc_counter_clear(&rtc);
					nrf_drv_rtc_int_enable(&rtc, NRF_RTC_INT_COMPARE0_MASK);
				}
				
    }
}

void appRTCInit(void)
	
{
    uint32_t err_code;
		
		nrf_drv_rtc_config_t rtc_config;
		rtc_config.prescaler = 4095;
    //Initialize RTC instance
    err_code = nrf_drv_rtc_init(&rtc, &rtc_config, appRTCHandler);
    APP_ERROR_CHECK(err_code);

    //Enable tick event & interrupt
    nrf_drv_rtc_tick_enable(&rtc, true);
	
		//Set compare channel to trigger interrupt after COMPARE_COUNTERTIME seconds
    err_code = nrf_drv_rtc_cc_set(&rtc,0,COMPARE_COUNTERTIME * 8,true);
    APP_ERROR_CHECK(err_code);
	
}

int main(void)
{  
		pg_size = NRF_FICR->CODEPAGESIZE;
		pg_num  = NRF_FICR->CODESIZE - 1;
		addr    = (uint32_t *)(pg_size *pg_num);
		//addr1   = addr + 32;
	  tamper = addr + 16;
  	ret_code_t err_code;
    bool  erase_bonds;
   // nrf_gpio_cfg_input(21,NRF_GPIO_PIN_PULLDOWN);
	  init_gpiote();
		err_code = app_gpiote_user_enable(m_gpiote_user_id); // put in ARM switch case statement
  	APP_ERROR_CHECK(err_code);
		NRF_POWER->RAMON = (POWER_RAMON_ONRAM0_RAM0On   << POWER_RAMON_ONRAM0_Pos)
                    | (POWER_RAMON_ONRAM1_RAM1On   << POWER_RAMON_ONRAM1_Pos)
										| (POWER_RAMON_OFFRAM0_RAM0Off << POWER_RAMON_OFFRAM0_Pos)
                    | (POWER_RAMON_OFFRAM1_RAM1Off << POWER_RAMON_OFFRAM1_Pos);
	   //timers_init();
		 APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, NULL);
	  
	   ble_stack_init();
//	sd_nvic_SystemReset();
		 scheduler_init();
		 device_manager_init(erase_bonds);
    //buttons_leds_init(&erase_bonds);
     gap_params_init();
	   conn_params_init();
		 services_init();
		 
     appRTCInit();
		 //fstorage_init();	 
		 scan_start();

	for (;;)
    {    
  			app_sched_execute();
        // Wait for BLE events.
        power_manage();
			  
    }
}