/******************************************************************************
 * @file    main.c
 * @author  Insight SiP
 * @version V2.4.1
 * @date    15-jan-2020
 * @brief   Receiver board project main file.
 *
 * @attention
 *	THIS SOFTWARE IS PROVIDED BY INSIGHT SIP "AS IS" AND ANY EXPRESS
 *	OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 *	OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *	DISCLAIMED. IN NO EVENT SHALL INSIGHT SIP OR CONTRIBUTORS BE
 *	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *	GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 *	OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *****************************************************************************/
 
#include <stdbool.h>
#include <stdint.h>
#include <string.h>

#include "nordic_common.h"
#include "fds.h"
#include "nrf.h"
#include "nrf_soc.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "nrf_delay.h"
#include "nrf_drv_clock.h"
#include "nrf_drv_gpiote.h"
#include "nrf_ble_gatt.h"
#include "nrf_gpio.h"
#include "nrf_serial.h"
#include "app_timer.h"
#include "app_error.h"
#include "app_scheduler.h"
#include "ble_advertising.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_err.h"
#include "ble_srv_common.h"
#include "peer_manager.h"
#include "ble_advdata.h"
#include "ble_conn_params.h"
#include "ble_conn_state.h"

#include "ble_loramngt.h"
#include "ble_env.h"
#include "ble_motion.h"
#include "ble_dis.h"

#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

#include "board.h"
#include "radio.h"
#include "user_config.h"
#include "m_loramngt_flash.h"


#define FW_REVISION "2.4.2"
#define HW_REVISION     "1" 

#define SCHED_MAX_EVENT_DATA_SIZE   MAX(APP_TIMER_SCHED_EVENT_DATA_SIZE, NRF_SDH_BLE_EVT_BUF_SIZE) 	/**< Maximum size of scheduler events. */

#if defined(ISP4520_JP)
#define RF_FREQUENCY                    923000000 // Hz
#define DEVICE_NAME                     "ISP4520-JP-GW"
#elif defined(ISP4520_EU)
#define RF_FREQUENCY                    868000000 // Hz    
#define DEVICE_NAME                     "ISP4520-EU-GW"
#elif defined(ISP4520_US)
#define DEVICE_NAME                     "ISP4520-US-GW"
#define RF_FREQUENCY                    915000000 // Hz                   
#else
    #error "Please define a version of an ISP4520."
#endif

#define LORA_CODINGRATE                 1           // [1: 4/5,
                                                    //  2: 4/6,
                                                    //  3: 4/7,
                                                    //  4: 4/8]
#define LORA_PREAMBLE_LENGTH            8           // Same for Tx and Rx
#define LORA_SYMBOL_TIMEOUT             0           // Symbols
#define LORA_FIX_LENGTH_PAYLOAD_ON      false
#define LORA_IQ_INVERSION_ON            false

#define SERIAL_FIFO_TX_SIZE 100
#define SERIAL_FIFO_RX_SIZE 32
#define SERIAL_BUFF_TX_SIZE 1
#define SERIAL_BUFF_RX_SIZE 1

// Static vars - BLE
NRF_BLE_GATT_DEF(m_gatt);                                                               /**< GATT module instance. */
BLE_ADVERTISING_DEF(m_advertising);                                                     /**< Advertising module instance. */
BLE_LORAMNGT_DEF(m_loramngt);                                                           /**< LoRa management Service instance. */
BLE_ENV_DEF(m_env);                                                                     /**< Environment Service instance. */
BLE_MOTION_DEF(m_motion);                                                               /**< Motion Service instance. */

// Static vars - LoRa
static RadioEvents_t LoRaEvents;                                                        /**< LoRa events */
static ble_loramngt_config_t *m_p_lora_config;                                          /**< Lora configuration pointer. */
static const ble_loramngt_config_t m_lora_default_config = LORAMNGT_CONFIG_DEFAULT; 	/**< Default lora configuration. */

// Static vars - UART
NRF_SERIAL_DRV_UART_CONFIG_DEF( m_uart0_drv_config,
                                PIN_UART_RX, PIN_UART_TX,
                                NRF_UART_PSEL_DISCONNECTED, NRF_UART_PSEL_DISCONNECTED,
                                NRF_UART_HWFC_ENABLED, NRF_UART_PARITY_EXCLUDED,
                                NRF_UART_BAUDRATE_115200,
                                UART_DEFAULT_CONFIG_IRQ_PRIORITY);
NRF_SERIAL_UART_DEF(serial_uart, 0);
NRF_SERIAL_QUEUES_DEF(serial_queues, SERIAL_FIFO_TX_SIZE, SERIAL_FIFO_RX_SIZE);
NRF_SERIAL_BUFFERS_DEF(serial_buffs, SERIAL_BUFF_TX_SIZE, SERIAL_BUFF_RX_SIZE);
NRF_SERIAL_CONFIG_DEF(serial_config, NRF_SERIAL_MODE_IRQ, &serial_queues, &serial_buffs, NULL, NULL);


/**@brief Callback function for 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] 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(DEAD_BEEF, line_num, p_file_name);
}

/**@brief Function for the Timer initialization.
 *
 * @details Initializes the timer module. This creates and starts application timers.
 */
static uint32_t timers_init (void)
{
    ret_code_t err_code;
	
    APP_SCHED_INIT(SCHED_MAX_EVENT_DATA_SIZE, SCHED_QUEUE_SIZE);

    // Initialize timer module.
    err_code = app_timer_init();
    VERIFY_SUCCESS(err_code);
	
    return NRF_SUCCESS;
}

/**@brief Function to be executed on Radio Tx Done event
 */
void lora_tx_done_evt_handler (void)
{
    Radio.Sleep();
}

/**@brief Function to be executed on Radio Rx Done event
 */
void lora_rx_done_evt_handler (uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr)
{
    uint16_t pressure, humidity, light;
    int16_t temperature;
    int16_t acc[3];
    int16_t mag[3];
    int16_t gyro[3];
    float temperature_f32, humidity_f32, pressure_f32, light_f32;
    float acc_f32[3], mag_f32[3], gyro_f32[3];
    ble_loramngt_rxdiag_t rxdiag;
    char tx_message[100];

    Radio.Sleep();

    if (size == 27)
    {
        // Parse LoRa frame
        pressure_f32    = (float)((uint16_t)(payload[1] << 8) | payload[2]) /  10;
        temperature_f32 = (float)( (int16_t)(payload[3] << 8) | payload[4]) / 100;
        humidity_f32    = (float)((uint16_t)(payload[5] << 8) | payload[6]) / 100;
        light_f32       = (float)((uint16_t)(payload[7] << 8) | payload[8]) / 100;
        acc_f32[0]      = (float)( (int16_t)(payload[9] << 8) | payload[10]) / 100;
        acc_f32[1]      = (float)( (int16_t)(payload[11] << 8) | payload[12]) / 100;
        acc_f32[2]      = (float)( (int16_t)(payload[13] << 8) | payload[14]) / 100;
        mag_f32[0]      = (float)( (int16_t)(payload[15] << 8) | payload[16]) / 100;
        mag_f32[1]      = (float)( (int16_t)(payload[17] << 8) | payload[18]) / 100;
        mag_f32[2]      = (float)( (int16_t)(payload[19] << 8) | payload[20]) / 100;

        rxdiag.frame_number =  payload[0];
        rxdiag.rssi = rssi;
        rxdiag.snr = snr;

        // Update BLE service
        ble_loramngt_rxdiag_set(&m_loramngt, &rxdiag);
        ble_env_temperature_set(&m_env, &temperature_f32);
        ble_env_pressure_set(&m_env, &pressure_f32);
        ble_env_humidity_set(&m_env, &humidity_f32);
        ble_env_light_set(&m_env, &light_f32);
        ble_motion_gravity_set(&m_motion, (ble_motion_gravity_t*)&acc_f32);
        ble_motion_angular_velocity_set(&m_motion, (ble_motion_angular_velocity_t*)&gyro_f32);
        ble_motion_magnetization_set(&m_motion, (ble_motion_magnetization_t*)&mag_f32);

        // Send by UART
        sprintf(tx_message, "%d:%d:%d:%d:%d:%.1f:%.1f:%.1f:%.1f:%.1f:%.1f:%.1f:%.1f:%.1f:%.1f\r\n",             \
            rssi, snr, m_p_lora_config->data_rate, m_p_lora_config->tx_power, payload[0],                       \
            pressure_f32, temperature_f32, humidity_f32, light_f32,                                             \
            acc_f32[0], acc_f32[1], acc_f32[2], mag_f32[0], mag_f32[1], mag_f32[2]);

        nrf_serial_write(&serial_uart, tx_message, strlen(tx_message), NULL, NRF_SERIAL_MAX_TIMEOUT);
    } 

    // Re enable LoRa reception
    Radio.Rx(0);
}

/**@brief Function to be executed on Radio Tx Timeout event
 */
void lora_tx_timeout_evt_handler (void)
{
    Radio.Sleep();
}

/**@brief Function to be executed on Radio Rx Timeout event
 */
void lora_rx_timeout_evt_handler (void)
{
    Radio.Sleep();
}

/**@brief Function to be executed on Radio Rx Error event
 */
void lora_rx_error_evt_handler (void)
{
    Radio.Sleep();
}

/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void ble_evt_handler (ble_evt_t const * p_ble_evt, void * p_context)
{
    ret_code_t err_code = NRF_SUCCESS;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_DISCONNECTED:
        {
            NRF_LOG_INFO("Disconnected.");
        } break;

        case BLE_GAP_EVT_CONNECTED:
        {
            NRF_LOG_INFO("Connected.");
        } break;

        case BLE_GATTC_EVT_TIMEOUT:
            // Disconnect on GATT Client timeout event.
            NRF_LOG_DEBUG("GATT Client Timeout.");
            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;

        case BLE_GATTS_EVT_TIMEOUT:
            // Disconnect on GATT Server timeout event.
            NRF_LOG_DEBUG("GATT Server Timeout.");
            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;

        case BLE_EVT_USER_MEM_REQUEST:
            err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gattc_evt.conn_handle, NULL);
            APP_ERROR_CHECK(err_code);
            break;

        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

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

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

    err_code = nrf_sdh_enable_request();
    VERIFY_SUCCESS(err_code);

    // Configure the BLE stack using the default settings.
    // Fetch the start address of the application RAM.
    uint32_t ram_start = 0;
    err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
    VERIFY_SUCCESS(err_code);

    // Enable BLE stack.
    err_code = nrf_sdh_ble_enable(&ram_start);
    VERIFY_SUCCESS(err_code);

    // Register a handler for BLE events.
    NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
	
    return NRF_SUCCESS;
}

/**@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 uint32_t gap_params_init (void)
{
    ret_code_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));
    VERIFY_SUCCESS(err_code);

    err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_GENERIC_KEYRING);
    VERIFY_SUCCESS(err_code);

    memset(&gap_conn_params, 0, sizeof(gap_conn_params));
    gap_conn_params.min_conn_interval = MSEC_TO_UNITS(MIN_CONN_INTERVAL_MS, UNIT_1_25_MS);
    gap_conn_params.max_conn_interval = MSEC_TO_UNITS(MAX_CONN_INTERVAL_MS, UNIT_1_25_MS);;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = MSEC_TO_UNITS(CONN_SUP_TIMEOUT_MS, UNIT_10_MS);

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

    err_code = sd_ble_gap_tx_power_set(TX_POWER_LEVEL);
    VERIFY_SUCCESS(err_code);
	
    err_code = sd_power_dcdc_mode_set(NRF_POWER_DCDC_ENABLE);
    VERIFY_SUCCESS(err_code);
	 
    return NRF_SUCCESS;
}

/**@brief Function for initializing the GATT module.
 */
static uint32_t gatt_init (void)
{
    ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
    VERIFY_SUCCESS(err_code);
	
    return NRF_SUCCESS;
}

/**@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 uint32_t conn_params_init (void)
{
    ret_code_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);
    VERIFY_SUCCESS(err_code);
	
    return NRF_SUCCESS;
}

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

        case BLE_ADV_EVT_IDLE:
            NRF_LOG_DEBUG("Idle advertising.");
            break; // BLE_ADV_EVT_IDLE

        default:
            break;
    }
}

/**@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.
 */
static uint32_t advertising_init (void)
{
    ret_code_t             err_code;
    ble_advertising_init_t init;
    ble_uuid_t adv_uuid =  {BLE_UUID_LORAMNGT_SERVICE, m_loramngt.uuid_type};

    memset(&init, 0, sizeof(init));
    init.advdata.name_type               	= BLE_ADVDATA_FULL_NAME;
    init.advdata.include_appearance      	= false;
    init.advdata.flags                   	= BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
    init.srdata.uuids_complete.uuid_cnt 	= 1;
    init.srdata.uuids_complete.p_uuids  	= &adv_uuid;
    init.config.ble_adv_fast_enabled  		= true;
    init.config.ble_adv_fast_interval 		= APP_ADV_INTERVAL;
    init.config.ble_adv_fast_timeout  		= APP_ADV_TIMEOUT_IN_SECONDS;
    init.evt_handler = adv_evt_handler;

    err_code = ble_advertising_init(&m_advertising, &init);
    VERIFY_SUCCESS(err_code);

    ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
	
    return NRF_SUCCESS;
}

/**@brief Function for handling Peer Manager events.
 *
 * @param[in] p_evt  Peer Manager event.
 */
static void pm_evt_handler (pm_evt_t const * p_evt)
{
    switch (p_evt->evt_id)
    {
        case PM_EVT_PEERS_DELETE_SUCCEEDED:
            ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
            break;

        default:
            break;
    }
}

/**@brief Function for the Peer Manager initialization.
 */
#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. */
#define SEC_PARAM_MAX_KEY_SIZE              16                                      /**< Maximum encryption key size. */
static uint32_t peer_manager_init(void)
{
    ble_gap_sec_params_t sec_param;
    ret_code_t           err_code;

    err_code = pm_init();
    VERIFY_SUCCESS(err_code);

    // Security parameters to be used for all security procedures.
    memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
    sec_param.bond           = SEC_PARAM_BOND;
    sec_param.mitm           = SEC_PARAM_MITM;
    sec_param.lesc           = SEC_PARAM_LESC;
    sec_param.keypress       = SEC_PARAM_KEYPRESS;
    sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
    sec_param.oob            = SEC_PARAM_OOB;
    sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
    sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
    sec_param.kdist_own.enc  = 1;
    sec_param.kdist_own.id   = 1;
    sec_param.kdist_peer.enc = 1;
    sec_param.kdist_peer.id  = 1;

    err_code = pm_sec_params_set(&sec_param);
    VERIFY_SUCCESS(err_code);

    err_code = pm_register(pm_evt_handler);
    VERIFY_SUCCESS(err_code);

    return NRF_SUCCESS;
}


/**@brief Function for applying the configuration.
 *
 */
static uint32_t lora_config_apply (ble_loramngt_config_t *p_config)
{
    ret_code_t err_code;
    int8_t power;
    uint32_t bw;
    uint32_t sf;
		
    power = 14 - 2*p_config->tx_power;

#if defined(ISP4520_EU) || defined(ISP4520_JP)
    switch(p_config->data_rate)
    {
        case 0:
            bw = 0;
            sf = 12;
            break;
        case 1:
            bw = 0;
            sf = 11;
            break;
        case 2:
            bw = 0;
            sf = 10;
            break;
        case 3:
            bw = 0;
            sf = 9;
            break;
        case 4:
            bw = 0;
            sf = 8;
            break;
        case 5:
            bw = 0;
            sf = 7;
            break;
        case 6:
            bw = 1;
            sf = 7;
            break;
        default:
            bw = 0;
            sf = 12;
            break;
    }
#elif defined(ISP4520_US)
    switch(p_config->data_rate)
    {
        case 0:
            bw = 0;
            sf = 10;
            break;
        case 1:
            bw = 0;
            sf = 9;
            break;
        case 2:
            bw = 0;
            sf = 8;
            break;
        case 3:
            bw = 0;
            sf = 7;
            break;
        default:
            bw = 0;
            sf = 10;
            break;
    }
#endif

    Radio.Sleep();

    Radio.SetTxConfig(  MODEM_LORA, power, bw, sf, 7, LORA_CODINGRATE,
                        LORA_PREAMBLE_LENGTH, LORA_FIX_LENGTH_PAYLOAD_ON,
                        true, 0, 0, LORA_IQ_INVERSION_ON, 3000);

    Radio.SetRxConfig(  MODEM_LORA, bw, sf, LORA_CODINGRATE, 0, LORA_PREAMBLE_LENGTH,
                        LORA_SYMBOL_TIMEOUT, LORA_FIX_LENGTH_PAYLOAD_ON,
                        0, true, 0, 0, LORA_IQ_INVERSION_ON, true);

    Radio.Rx(0);
	
    *m_p_lora_config = *p_config;
		
    return NRF_SUCCESS;
}

/**@brief Function for handling event from the loramngt service.
 *
 * @details This function will process the data received from the loraconfig BLE Service.
 *
 * @param[in] p_loramngt  	loramngt service structure.
 * @param[in] evt_type 		loramngt service event type.
 * @param[in] p_data   		Event data.
 * @param[in] length   		Length of the data.
 */
static void ble_loramngt_evt_handler(   ble_loramngt_t        	*p_loramngt,
                                        ble_loramngt_evt_type_t evt_type,
                                        uint8_t                 *p_data,
                                        uint16_t                length)
{
    switch (evt_type)
    {
	case BLE_LORAMNGT_EVT_CONFIG_RECEIVED:
        {
            NRF_LOG_INFO("BLE_LORAMNGT_EVT_CONFIG_RECEIVED: %d", length);
            APP_ERROR_CHECK_BOOL(length == sizeof(ble_loramngt_config_t));

            (void)m_loramngt_flash_config_store((ble_loramngt_config_t *)p_data);
            (void)lora_config_apply((ble_loramngt_config_t *)p_data);
            break;
        }
	
        default:
            break;
	}		
}

/**@brief Function for handling event from the environment service.
 *
 * @details This function will process the data received from the environment BLE Service.
 *
 * @param[in] p_loraconfig  	environment service structure.
 * @param[in] evt_type 		environment service event type.
 * @param[in] p_data   		Event data.
 * @param[in] length   		Length of the data.
 */
static void ble_env_evt_handler(ble_env_t *p_env, ble_env_evt_type_t evt_type, uint8_t *p_data, uint16_t length)
{
    //Nothing to do here
}

/**@brief Function for handling event from the motion service.
 *
 * @details This function will process the data received from the motion BLE Service.
 *
 * @param[in] p_loraconfig  	motion service structure.
 * @param[in] evt_type 		motion service event type.
 * @param[in] p_data   		Event data.
 * @param[in] length   		Length of the data.
 */
static void ble_motion_evt_handler(ble_motion_t *p_motion, ble_motion_evt_type_t evt_type, uint8_t *p_data, uint16_t length)
{
    //Nothing to do here
}

/**@brief Function for initializing the loramngt Service.
 *
 * @retval NRF_SUCCESS If initialization was successful.
 */
static uint32_t services_init (void)
{
    uint32_t                err_code;
    ble_loramngt_init_t     loramngt_init;
    ble_env_init_t          env_init;
    ble_motion_init_t       motion_init;
    ble_dis_init_t          dis_init;

    ble_loramngt_rxdiag_t   rxdiag_init = {0};
    ble_env_temperature_t   temperature_init = 0.0;
    ble_env_pressure_t      pressure_init = 0.0;
    ble_env_humidity_t      humidity_init = 0.0;
    ble_env_light_t         light_init = 0.0;
    ble_motion_gravity_t            gravityt_init = {0.0};
    ble_motion_magnetization_t      magnetization_init = {0.0};
    ble_motion_angular_velocity_t   angular_velocity_init = {0.0};

    // Load configuration from flash.
    err_code = m_loramngt_flash_init (&m_lora_default_config, &m_p_lora_config);
    VERIFY_SUCCESS(err_code);

    // Verify configuration retreived from flash. 
    //TODO
//    err_code = config_verify(m_p_lora_config);
//    VERIFY_SUCCESS(err_code);

    // Initialize services
    memset(&loramngt_init, 0, sizeof(ble_loramngt_init_t));
    loramngt_init.p_init_config     = m_p_lora_config;
    loramngt_init.p_init_rxdiag     = &rxdiag_init;
    loramngt_init.evt_handler       = ble_loramngt_evt_handler;
    err_code = ble_loramngt_init(&m_loramngt, &loramngt_init);
    VERIFY_SUCCESS(err_code);

    memset(&env_init, 0, sizeof(ble_env_init_t));
    env_init.p_init_temperature = &temperature_init;
    env_init.p_init_pressure    = &pressure_init;
    env_init.p_init_humidity    = &humidity_init;
    env_init.p_init_light       = &light_init;
    env_init.evt_handler        = ble_env_evt_handler;
    err_code = ble_env_init(&m_env, &env_init);
    VERIFY_SUCCESS(err_code);

    memset(&motion_init, 0, sizeof(ble_motion_init_t));
    motion_init.p_init_gravity          = &gravityt_init;
    motion_init.p_init_magnetization    = &magnetization_init;
    motion_init.p_init_angular_velocity = &angular_velocity_init;
    motion_init.evt_handler             = ble_motion_evt_handler; 
    err_code = ble_motion_init(&m_motion, &motion_init);
    VERIFY_SUCCESS(err_code);

    memset (&dis_init, 0, sizeof(ble_dis_init_t));
    ble_srv_ascii_to_utf8 (&dis_init.fw_rev_str, (char*)FW_REVISION);
    ble_srv_ascii_to_utf8 (&dis_init.hw_rev_str, (char*)HW_REVISION);
    BLE_GAP_CONN_SEC_MODE_SET_OPEN (&dis_init.dis_attr_md.read_perm);
    BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS (&dis_init.dis_attr_md.write_perm);
    err_code = ble_dis_init(&dis_init);
    VERIFY_SUCCESS(err_code);

    // Apply configuration retreived from flash.
    lora_config_apply(m_p_lora_config);

    return NRF_SUCCESS;
}

/**@brief Function for initializing the nrf log module.
 */
static void log_init (void)
{
    ret_code_t err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    NRF_LOG_DEFAULT_BACKENDS_INIT();
}

#define FPU_EXCEPTION_MASK 0x0000009F 
/**@brief Function for the Power manager.
 */
static void power_manage (void)
{
    /* Clear exceptions and PendingIRQ from the FPU unit */
    __set_FPSCR(__get_FPSCR()  & ~(FPU_EXCEPTION_MASK));      
    (void) __get_FPSCR();
    NVIC_ClearPendingIRQ(FPU_IRQn);
	
    ret_code_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for application main entry.
 */
int main (void)
{
    uint32_t err_code;
	
    // Initialize logs.
    log_init();
    NRF_LOG_INFO("ISP4580 LoRa RX side demo started");
	
    // Initialize clocks
    nrf_drv_clock_init();
    nrf_drv_clock_lfclk_request(NULL);
	
    // Initialize Scheduler and timer.
    err_code = timers_init();
    APP_ERROR_CHECK(err_code);
    
     // Initialize Serial.
    err_code = nrf_serial_init(&serial_uart, &m_uart0_drv_config, &serial_config);
    APP_ERROR_CHECK(err_code);

    // Initialize LoRa chip.
    err_code = lora_hardware_init();
    APP_ERROR_CHECK(err_code);

    // Initialize LoRa
    LoRaEvents.TxDone       = lora_tx_done_evt_handler;
    LoRaEvents.RxDone       = lora_rx_done_evt_handler;
    LoRaEvents.TxTimeout    = lora_tx_timeout_evt_handler;
    LoRaEvents.RxTimeout    = lora_rx_timeout_evt_handler;
    LoRaEvents.RxError      = lora_rx_error_evt_handler;
    Radio.Init(&LoRaEvents);
    Radio.SetChannel(RF_FREQUENCY);

    // Initialize BLE
    err_code = ble_stack_init();
    APP_ERROR_CHECK(err_code);

    err_code = gap_params_init();
    APP_ERROR_CHECK(err_code);

    err_code = conn_params_init();
    APP_ERROR_CHECK(err_code);
	
    err_code = services_init();
    APP_ERROR_CHECK(err_code);

    err_code = peer_manager_init();
    APP_ERROR_CHECK(err_code);

    err_code = advertising_init();
    APP_ERROR_CHECK(err_code);
		
    // Start BLE
    ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);

    // Start Lora
    Radio.Rx(0);

    nrf_gpio_pin_write(PIN_RED_LED, 0);
    nrf_gpio_cfg_output(PIN_RED_LED);
	
    // Enter main loop.
    for (;;)
    {
        Radio.IrqProcess();
        app_sched_execute();
        if (NRF_LOG_PROCESS() == false)
        {
            power_manage();
        }
    }
}
