/* Copyright (c) 2014 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is property of Nordic Semiconductor ASA.
 * Terms and conditions of usage are described in detail in NORDIC
 * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
 *
 * Licensees are granted free, non-transferable use of the information. NO
 * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
 * the file.
 *
 */
 
/** 
 * @file main.c
 * @brief UWB Application main file.
 * @version 6.0
 * @date 27/06/2017
 */
 
 
 //**********************************************************************************************************/
 //											INCLUDES
 //**********************************************************************************************************/
 
 // Standards
#include <stdint.h>
#include <string.h>

// Nordic
#include "ble_advertising.h"
#include "nordic_common.h"
#include "nrf.h"
#include "nrf_soc.h"
#include "app_error.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_srv_common.h"
#include "ble_advdata.h"
#include "ble_dis.h"
#include "ble_conn_params.h"
#include "softdevice_handler.h"
#include "app_timer.h"
#include "app_util.h"
#include "fds.h"
#include "fstorage.h"
#include "ble_conn_state.h"
#define NRF_LOG_MODULE_NAME "APP"	/**< Name of Log */
#include "nrf_log.h"
#include "nrf_log_ctrl.h"

// Platform
#include "GPIO.h"
#include "sleep.h"
#include "interrupts.h"
#include "spi.h"
#include "adc.h"

// BLE Services
#include "app_uwbrange.h"

// Misc
#include "GlobalDefs.h"
#include "boards.h"
#include "decawave_app.h"


 //**********************************************************************************************************/
 //											DEFINES
 //**********************************************************************************************************/
#if (NRF_SD_BLE_API_VERSION == 3)
#define NRF_BLE_MAX_MTU_SIZE              GATT_MTU_SIZE_DEFAULT   /**< MTU size used in the softdevice enabling and to reply to a BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST event. */
#endif

 //**********************************************************************************************************/
 //											VARIABLES
 //**********************************************************************************************************/

static ble_uuid_t m_adv_uuids[] = {{BLE_UUID_UWBRANGE_SERVICE, BLE_UUID_TYPE_VENDOR_BEGIN}}; 	/**< Universally unique service identifiers. */
static uint16_t  m_conn_handle = BLE_CONN_HANDLE_INVALID;   							/**< Handle of the current connection. */

//adv
static ble_advdata_t 	m_advdata;
static ble_advdata_t sr_data;

uint32 mDeviceNumber = 0;			/**< Serial number used to identify the demo */
												 
//**************************************************************************************************
// DECAWAVE 
//*************************************************************************************************/
												 																							
/** @brief Configuration for DecaRanging Modes (mode 7)
 */
chConfig_t decawaveConfig =
{
	5,              // channel
	DWT_PRF_64M,    // prf
	DWT_BR_6M8,    	// datarate
	9,             	// preambleCode
	DWT_PLEN_128,   // preambleLength
	DWT_PAC8,       // pacSize
	0,       		// non-standard SFD
	(129 + 8 - 8) 	//SFD timeout
};										 
										 
	
/** 
 *  @brief DecaWave Application initialisation function
 *  @param[in] mode Mode of the DecawaveApp
 */
static int32 decawave_init (uint8 mode)
{
    uint32 devID;
    instanceConfig_t instConfig;
    int result;
	int instance_mode = ANCHOR;
	uint32 cpt = 0;

	// Decrease SPI speed to 1MHz (less than 3MHz)
	SPI_SetLowRate (); 
	
	// Wake up decawave!
	GPIO_SetPinValue (PIN_DECA_WAKEUP, GPIO_HIGH);
	Sleep(1);
	GPIO_SetPinValue (PIN_DECA_WAKEUP, GPIO_LOW);
	
	// try reading Decawave ID register
    devID = DecawaveApp_ReadRevId ();	
	while(devID != DWT_DEVICE_ID)
	{
		devID = DecawaveApp_ReadRevId();
		cpt++;
		if(cpt>200)
		{
			// SPI not working or Unsupported Device ID
			if(DWT_DEVICE_ID != devID)
			{
				return(-1) ;
			}			
		}
	}
	
	// initialize app instance and load data from OTP
	result = DecawaveApp_InitInstance(mDeviceNumber) ;
    if (0 > result) 
	{
		// Some failure has occurred
		return(-1) ;
	}

	//increase SPI speed to max (8MHz)
    SPI_SetHighRate (); 
	
	// retry reading Decawave register
    devID = DecawaveApp_ReadRevId() ;

    if (DWT_DEVICE_ID != devID)   // Means it is NOT MP device
    {
        // SPI not working or Unsupported Device ID
        return(-1) ;
    }

	// SPI still working. Now set this instance role
    if(mode)
    {
        instance_mode = ANCHOR;
    }
    else
    {
        instance_mode = TAG;
    }
    DecawaveApp_SetRole (instance_mode) ;     
	
	// Init interrupt, set Decawave callbacks
    DecawaveApp_InitInterrupts (instance_mode);

	// Set default operating channel etc
    instConfig.channelNumber = 	decawaveConfig.channel ;
    instConfig.preambleCode = 	decawaveConfig.preambleCode ;
    instConfig.pulseRepFreq = 	decawaveConfig.prf ;
    instConfig.pacSize = 		decawaveConfig.pacSize ;
    instConfig.nsSFD = 			decawaveConfig.nsSFD ;
    instConfig.sfdTO = 			decawaveConfig.sfdTO ;
    instConfig.dataRate = 		decawaveConfig.datarate ;
    instConfig.preambleLen = 	decawaveConfig.preambleLength ;
    DecawaveApp_ConfigInstance (&instConfig) ;                 

	// Set the Tag sleep time
    DecawaveApp_SetTagSleepDelay (POLL_SLEEP_DELAY, BLINK_SLEEP_DELAY); 

	// set timings
    DecawaveApp_InitTimings ();
	
	// Set report functions
	DecawaveApp_SetReportDistanceMeasurementFunction (uwbrange_measurement_update);
	DecawaveApp_SetGoToRangingModeFunction (GoToRangingMode);
	
	// Configure the on wake parameters (upload the IC config settings)
#if (DEEP_SLEEP == 1)
	int sleepmode = 0;
	sleepmode = (DWT_LOADUCODE|DWT_PRESRV_SLEEP|DWT_CONFIG|DWT_TANDV);
	//if we need to use LDO tune value from OTP kick it after sleep
	if((dwt_getldotune() != 0)) 
	{
		sleepmode |= DWT_LOADLDO;
	}
	
	//if using 64 length preamble then use the corresponding OPSet
	if(instance_data[0].configData.txPreambLength == DWT_PLEN_64) 
	{
		sleepmode |= DWT_LOADOPSET;
	}
		
	//configure the on wake parameters (upload the IC config settings)
	dwt_configuresleep(sleepmode, DWT_WAKE_WK|DWT_SLP_EN); 
#endif 	
	
	// if CONFIG_AS_TAG or CONFIG_AS_ANCHOR is set, go to discovery mode and start Blinking immediatly
#if CONFIG_AS_TAG
	// Prepare Decawave for exchange
	DecawaveApp_InitExchange();
	
	// Switch to UWB discovery mode
	GoToDiscoveryMode();
#elif CONFIG_AS_ANCHOR
	// Prepare Decawave for exchange
	DecawaveApp_InitExchange();
	
	// Switch to UWB discovery mode
	GoToDiscoveryMode();
#else
	// Else go to sleep
#if (DEEP_SLEEP == 1)
	// go to sleep
	dwt_entersleep();
#endif
#endif
	
    return devID;
}									 								 		


//**********************************************************************************************************/
//											SOFTDEVICE
//**********************************************************************************************************/

/**@brief Function for handling the Application's BLE Stack events.
 *
 * @param[in] p_ble_evt  Bluetooth stack event.
 */
static void on_ble_evt(ble_evt_t * p_ble_evt)
{
    uint32_t err_code = NRF_SUCCESS;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_DISCONNECTED:
			NRF_LOG_INFO("Disonnected\r\n");
            m_conn_handle = BLE_CONN_HANDLE_INVALID;

			break;

        case BLE_GAP_EVT_CONNECTED:
        {
			NRF_LOG_INFO("Connected\r\n");
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
        } 
		break; // BLE_GAP_EVT_CONNECTED

     
        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
			NRF_LOG_DEBUG("GATT Client Timeout.\r\n");
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break; // BLE_GATTC_EVT_TIMEOUT

        case BLE_GATTS_EVT_TIMEOUT:
            // Disconnect on GATT Server timeout event.
            NRF_LOG_DEBUG("GATT Server Timeout.\r\n");
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
            break; // BLE_GATTS_EVT_TIMEOUT

        case BLE_EVT_USER_MEM_REQUEST:
            err_code = sd_ble_user_mem_reply(m_conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            break; // BLE_EVT_USER_MEM_REQUEST

        case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
        {
            ble_gatts_evt_rw_authorize_request_t  req;
            ble_gatts_rw_authorize_reply_params_t auth_reply;

            req = p_ble_evt->evt.gatts_evt.params.authorize_request;

            if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
            {
                if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ)     ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
                    (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
                {
                    if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
                    }
                    else
                    {
                        auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
                    }
                    auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
                    err_code = sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gatts_evt.conn_handle,
                                                               &auth_reply);
                    APP_ERROR_CHECK(err_code);
                }
            }
        } break; // BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST

#if (NRF_SD_BLE_API_VERSION == 3)
        case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
            err_code = sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle,
                                                       NRF_BLE_MAX_MTU_SIZE);
            APP_ERROR_CHECK(err_code);
            break; // BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST
#endif
		
		case BLE_GAP_EVT_AUTH_KEY_REQUEST:
            NRF_LOG_DEBUG("BLE_GAP_EVT_AUTH_KEY_REQUEST\r\n");     
            break; // BLE_GAP_EVT_AUTH_KEY_REQUEST
		
		case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
            NRF_LOG_DEBUG("BLE_GAP_EVT_LESC_DHKEY_REQUEST\r\n");
            break; // BLE_GAP_EVT_AUTH_KEY_REQUEST
		
		case BLE_GATTS_EVT_SYS_ATTR_MISSING:
			err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, NULL);
			APP_ERROR_CHECK(err_code);
        break;

        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 BLE Stack event interrupt handler 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)
{
    ble_conn_state_on_ble_evt(p_ble_evt);
    ble_conn_params_on_ble_evt(p_ble_evt);
    on_ble_evt(p_ble_evt);
    ble_advertising_on_ble_evt(p_ble_evt);
	
	set_ble_bas_on_ble_evt(p_ble_evt);
	
	// custom service events
	set_ble_uwbrange_on_ble_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)
{
    // Dispatch the system event to the fstorage module, where it will be
    // dispatched to the Flash Data Storage (FDS) module.
    fs_sys_event_handler(sys_evt);

    // Dispatch to the Advertising module last, since it will check if there are any
    // pending flash operations in fstorage. Let fstorage process system events first,
    // so that it can report correctly to the Advertising module.
    ble_advertising_on_sys_evt(sys_evt);
}


/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupt.
 */
static void ble_stack_init(void)
{
    uint32_t err_code;

    nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;

    // Initialize the SoftDevice handler module.
    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.
#if (NRF_SD_BLE_API_VERSION == 3)
    ble_enable_params.gatt_enable_params.att_mtu = NRF_BLE_MAX_MTU_SIZE;
#endif
    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 BLE events.
    err_code = softdevice_sys_evt_handler_set(sys_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}

 //**********************************************************************************************************/
 //											GAP
 //**********************************************************************************************************/

/**@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.
 */
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);
	
	// construct device name based on number read in UICR
	char deviceName[20];
	char temp[3];
	strcpy(deviceName, DEVICE_NAME);
	strcat(deviceName, "_SN");
	sprintf(temp, "%03d", mDeviceNumber);
	strcat(deviceName, temp);

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

    err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_GENERIC_KEYRING);
    APP_ERROR_CHECK(err_code);

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

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;

    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);

    err_code = sd_ble_gap_tx_power_set(TX_POWER_LEVEL);
    APP_ERROR_CHECK(err_code);
										  
	// Added R2 : Compatibility mode 2 for samsung J3 (need softdevice 3.1)
	ble_opt_t ble_options;
	ble_gap_opt_compat_mode_2_t mode_2;
	mode_2.mode_2_enable = 1;
	ble_options.gap_opt.compat_mode_2 = mode_2;
	err_code = sd_ble_opt_set(BLE_GAP_OPT_COMPAT_MODE_2, &ble_options) ;									  
	APP_ERROR_CHECK(err_code);								  
}

/**@brief Function for putting the chip into sleep mode.
 *
 * @note This function will not return.
 */
static void sleep_mode_enter(void)
{
    uint32_t err_code;
	
    // Go to system-off mode (this function will not return; wakeup will cause a reset).
    err_code = sd_power_system_off();
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for handling the Application's BLE Stack events.
 *
 * @details This function will be called for advertising events which are passed to the application.
 *
 * @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:
            break; // BLE_ADV_EVT_FAST

        case BLE_ADV_EVT_IDLE:
            sleep_mode_enter();
            break; // BLE_ADV_EVT_IDLE

        default:
            break;
    }
}

/**@brief Function for handling a Connection Parameters error.
 *
 * @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;
    cp_init.disconnect_on_fail             = true;
    cp_init.evt_handler                    = NULL;
    cp_init.error_handler                  = conn_params_error_handler;

    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}

//**************************************************************************************************
//											ADVERTISING
//*************************************************************************************************/	

/**@brief Function for initializing the Advertising functionality.
 *
 * @details Encodes the required advertising data and passes it to the stack.
 *          Also builds a structure to be passed to the stack when starting advertising.
 */
/**@brief Function for initializing the Advertising functionality.
 */
static void advertising_init(void)
{
    // Build advertising data struct to pass into @ref ble_advertising_init.
    memset(&m_advdata, 0, sizeof(m_advdata));
    // Only set up adv_data. Options will be set depending on if advertising will be enabled or not.
    m_advdata.name_type               = BLE_ADVDATA_FULL_NAME;
    m_advdata.include_appearance      = false;
    m_advdata.flags                   = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
    m_advdata.uuids_complete.uuid_cnt = 0;
	
	//Scan response data
    memset(&sr_data, 0, sizeof(sr_data));
    sr_data.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
    sr_data.uuids_complete.p_uuids = m_adv_uuids;
}

/**@brief Function for re-initializing the Advertising module with fast advertising mode enabled.
 */
static void advertising_enable(void)
{
    uint32_t err_code;

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

    err_code = ble_advertising_init(&m_advdata, &sr_data, &options, on_adv_evt, NULL);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for re-initializing the Advertising module with all advertising modes disabled.
 */
static void advertising_disable(void)
{
    uint32_t err_code;

    ble_adv_modes_config_t options    = {0};
    options.ble_adv_directed_enabled  = false;
    options.ble_adv_fast_enabled      = false;
    options.ble_adv_slow_enabled      = false;
    options.ble_adv_whitelist_enabled = false;

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

 //**********************************************************************************************************/
 //											BLE SERVICES
 //**********************************************************************************************************/

/**@brief Function for initializing the Device Information Service.
 */
static void dis_init(void)
{
    uint32_t       err_code;
    ble_dis_init_t dis_init_obj;

    memset (&dis_init_obj, 0, sizeof(ble_dis_init_t));

    ble_srv_ascii_to_utf8 (&dis_init_obj.manufact_name_str, (char *)MANUFACTURER_NAME);
	ble_srv_ascii_to_utf8 (&dis_init_obj.fw_rev_str, (char*)FW_REVISION);	
	
    BLE_GAP_CONN_SEC_MODE_SET_OPEN		(&dis_init_obj.dis_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS	(&dis_init_obj.dis_attr_md.write_perm);

    err_code = ble_dis_init (&dis_init_obj);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for initializing the services that will be used by the application.
 */
static void services_init(void)
{
	// Initialize Device Information Service.
    dis_init();
	
	// Initialize Battery Service.	
	bas_init();
	
	// Initialize Distance Service.
	uwbrange_service_init(decawaveConfig);
}
 
 //**********************************************************************************************************/
 //											MAIN
 //**********************************************************************************************************/

/**@brief Function for the Power manager.
 */
static void power_manage(void)
{
    uint32_t err_code = sd_app_evt_wait();

    APP_ERROR_CHECK(err_code);
}

/**@brief Function for application main entry.
 */
int main(void)
{
	bool erase_bonds = true;
	int defaultRole = 1;
	
	// Read UICR->CUSTOMER[0] of nRF52, this is where we store the serial number
	mDeviceNumber = NRF_UICR->CUSTOMER[0];
	if (mDeviceNumber == 0xFFFFFFFF)
		mDeviceNumber = 0;
	
	// Init Hardware && peripherals
	GPIO_init();
	// Configure SPI to commmunicate with Decawave
	SPI_init();	
	// Configure the GPIO connected to the Decawave IRQ pin, make it call dwt_isr() on interrupts 
	GPIO_INT_init (PIN_DECA_INT, dwt_isr);
	// Configure ADC for battery measurement
	ADC_init (NRF_SAADC_INPUT_AIN3, battery_level_update);
	// Init timers
	timers_init();
	
	// Init SoftDevice & BLE
    ble_stack_init();
	gap_params_init();
	advertising_init();
	services_init();
	conn_params_init();
		
	// Configure Decawave
	// Default role : TAG = 0, ANCHOR = 1
#if CONFIG_AS_TAG
	defaultRole = 0;
#elif CONFIG_AS_ANCHOR
	defaultRole = 1;
#else
	defaultRole = 1;
#endif
    if (decawave_init(defaultRole) == -1)
	{
		GPIO_SetPinValue(LED_2,GPIO_LOW);
		Sleep(3000);
		GPIO_SetPinValue(LED_2,GPIO_HIGH);
		
		return -1; // Error with decawave -> no need to go on
	}

    // Start execution/advertising.
	advertising_enable();
	ble_advertising_start (BLE_ADV_MODE_FAST);

    // Enter main loop.
    for (;;)
    {
        power_manage();
    }
}
