/**
 * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "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 NORDIC SEMICONDUCTOR ASA 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.
 *
 */
/**
 * @brief BLE LED Button Service central and client application main file.
 *
 * This file contains the source code for a sample client application using the LED Button service.
 */

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "nrf_sdh_soc.h"
#include "nrf_pwr_mgmt.h"
#include "app_timer.h"
#include "boards.h"
#include "bsp.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_advertising.h"
#include "nrf_ble_scan.h"

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


#define CENTRAL_SCANNING_LED            BSP_BOARD_LED_0                     /**< Scanning LED will be on when the device is scanning. */
#define CENTRAL_CONNECTED_LED           BSP_BOARD_LED_1                     /**< Connected LED will be on when the device is connected. */
#define LEDBUTTON_LED                   BSP_BOARD_LED_2                     /**< LED to indicate a change of state of the the Button characteristic on the peer. */

#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 SCAN_DURATION                   0x0000                              /**< Timout when scanning. 0x0000 disables timeout. */

#define APP_BLE_CONN_CFG_TAG            1                                   /**< A tag identifying the SoftDevice BLE configuration. */
#define APP_BLE_OBSERVER_PRIO           3                                   /**< Application's BLE observer priority. You shouldn't need to modify this value. */

NRF_BLE_SCAN_DEF(m_scan);                                       /**< Scanning module instance. */

#define NON_CONNECTABLE_ADV_INTERVAL    MSEC_TO_UNITS(100, UNIT_0_625_MS)  /**< The advertising interval for non-connectable advertisement (100 ms). This value can vary between 100ms to 10.24s). */

#define APP_BEACON_INFO_LENGTH          0x17                               /**< Total length of information advertised by the Beacon. */
#define APP_ADV_DATA_LENGTH             0x15                               /**< Length of manufacturer specific data in the advertisement. */
#define APP_DEVICE_TYPE                 0x02                               /**< 0x02 refers to Beacon. */
#define APP_MEASURED_RSSI               0xC3                               /**< The Beacon's measured RSSI at 1 meter distance in dBm. */
#define APP_COMPANY_IDENTIFIER          0x0627                             /**< Company identifier for Nordic Semiconductor ASA. as per www.bluetooth.org. */
#define APP_MAJOR_VALUE                 0x01, 0x02                         /**< Major value used to identify Beacons. */
#define APP_MINOR_VALUE                 0x03, 0x04                         /**< Minor value used to identify Beacons. */
#define APP_BEACON_UUID                 0x01, 0x12, 0x23, 0x34, \
                                        0x45, 0x56, 0x67, 0x78, \
                                        0x89, 0x9a, 0xab, 0xbc, \
                                        0xcd, 0xde, 0xef, 0xf0            /**< Proprietary UUID for Beacon. */

#define DEAD_BEEF                       0xDEADBEEF                         /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */

#if defined(USE_UICR_FOR_MAJ_MIN_VALUES)
#define MAJ_VAL_OFFSET_IN_BEACON_INFO   18                                 /**< Position of the MSB of the Major Value in m_beacon_info array. */
#define UICR_ADDRESS                    0x10001080                         /**< Address of the UICR register used by this example. The major and minor versions to be encoded into the advertising data will be picked up from this location. */
#endif

static ble_gap_adv_params_t m_adv_params;                                  /**< Parameters to be passed to the stack when starting advertising. */
static uint8_t              m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET; /**< Advertising handle used to identify an advertising set. */
static uint8_t              m_enc_advdata[BLE_GAP_ADV_SET_DATA_SIZE_MAX];  /**< Buffer for storing an encoded advertising set. */

bool newdisp = 1;
int msg = 0;
int cont = 0;
uint8_t endereco[17];
uint8_t enderecoatual[17];
uint8_t advertising[27] = {0};
uint8_t advertising1[27] = {0};
uint8_t advertising2[27] = {0};
uint8_t advertising3[27] = {0};
uint8_t advertising4[27] = {0};

/**@brief Struct that contains pointers to the encoded advertising data. */
static ble_gap_adv_data_t m_adv_data =
{
    .adv_data =
    {
        .p_data = m_enc_advdata,
        .len    = BLE_GAP_ADV_SET_DATA_SIZE_MAX
    },
    .scan_rsp_data =
    {
        .p_data = NULL,
        .len    = 0

    }
};


static uint8_t m_beacon_info[APP_BEACON_INFO_LENGTH] =                    /**< Information advertised by the Beacon. */
{
    APP_DEVICE_TYPE,     // Manufacturer specific information. Specifies the device type in this
                         // implementation.
    APP_ADV_DATA_LENGTH, // Manufacturer specific information. Specifies the length of the
                         // manufacturer specific data in this implementation.
    APP_BEACON_UUID,     // 128 bit UUID value.
    APP_MAJOR_VALUE,     // Major arbitrary value that can be used to distinguish between Beacons.
    APP_MINOR_VALUE,     // Minor arbitrary value that can be used to distinguish between Beacons.
    APP_MEASURED_RSSI    // Manufacturer specific information. The Beacon's measured TX power in
                         // this implementation.
};

/**@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 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 void advertising_init(void)
{
    uint32_t      err_code;
    ble_advdata_t advdata;
    //uint8_t       flags = BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;

    ble_advdata_manuf_data_t manuf_specific_data;

    //manuf_specific_data.company_identifier = APP_COMPANY_IDENTIFIER;

#if defined(USE_UICR_FOR_MAJ_MIN_VALUES)
    // If USE_UICR_FOR_MAJ_MIN_VALUES is defined, the major and minor values will be read from the
    // UICR instead of using the default values. The major and minor values obtained from the UICR
    // are encoded into advertising data in big endian order (MSB First).
    // To set the UICR used by this example to a desired value, write to the address 0x10001080
    // using the nrfjprog tool. The command to be used is as follows.
    // nrfjprog --snr <Segger-chip-Serial-Number> --memwr 0x10001080 --val <your major/minor value>
    // For example, for a major value and minor value of 0xabcd and 0x0102 respectively, the
    // the following command should be used.
    // nrfjprog --snr <Segger-chip-Serial-Number> --memwr 0x10001080 --val 0xabcd0102
    uint16_t major_value = ((*(uint32_t *)UICR_ADDRESS) & 0xFFFF0000) >> 16;
    uint16_t minor_value = ((*(uint32_t *)UICR_ADDRESS) & 0x0000FFFF);

    uint8_t index = MAJ_VAL_OFFSET_IN_BEACON_INFO;

    m_beacon_info[index++] = MSB_16(major_value);
    m_beacon_info[index++] = LSB_16(major_value);

    m_beacon_info[index++] = MSB_16(minor_value);
    m_beacon_info[index++] = LSB_16(minor_value);
#endif

    manuf_specific_data.data.p_data = advertising;
    manuf_specific_data.data.size   = sizeof(advertising);

    // Build and set advertising data.
    memset(&advdata, 0, sizeof(advdata));

    advdata.name_type             = BLE_ADVDATA_NO_NAME;
    //advdata.flags                 = flags;
    advdata.p_manuf_specific_data = &manuf_specific_data;

    // Initialize advertising parameters (used when starting advertising).
    memset(&m_adv_params, 0, sizeof(m_adv_params));

    m_adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED;
    m_adv_params.p_peer_addr     = NULL;    // Undirected advertisement.
    m_adv_params.filter_policy   = BLE_GAP_ADV_FP_ANY;
    m_adv_params.interval        = NON_CONNECTABLE_ADV_INTERVAL;
    m_adv_params.duration        = 0;       // Never time out.

    err_code = ble_advdata_encode(&advdata, m_adv_data.adv_data.p_data, &m_adv_data.adv_data.len);
    APP_ERROR_CHECK(err_code);

    err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &m_adv_params);
    APP_ERROR_CHECK(err_code);

}


/**@brief Function for starting advertising.
 */
static void advertising_start(void)
{
    ret_code_t err_code;

    err_code = sd_ble_gap_adv_start(m_adv_handle, APP_BLE_CONN_CFG_TAG);
    APP_ERROR_CHECK(err_code);

    err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
    APP_ERROR_CHECK(err_code);
}

static void advertising_stop(void) { 	
   ret_code_t err_code;

   err_code = sd_ble_gap_adv_stop(m_adv_handle); 	
   APP_ERROR_CHECK(err_code);

   err_code = bsp_indication_set(BSP_INDICATE_IDLE); 	
   APP_ERROR_CHECK(err_code); 
}

/**@brief Function for the LEDs initialization.
 *
 * @details Initializes all LEDs used by the application.
 */
static void leds_init(void)
{
    bsp_board_init(BSP_INIT_LEDS);
}


/**@brief Function to start scanning.
 */
static void scan_start(void)
{
    ret_code_t err_code;

    err_code = nrf_ble_scan_start(&m_scan);
    APP_ERROR_CHECK(err_code);

    //bsp_board_led_off(CENTRAL_CONNECTED_LED);
    //bsp_board_led_on(CENTRAL_SCANNING_LED);
}


/**@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;

    // For readability.
    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;

    switch (p_ble_evt->header.evt_id)
    {

        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)
            {
                NRF_LOG_DEBUG("Connection request timed out.");
            }
        } break;

    }
}


/**@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;

    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(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);
    APP_ERROR_CHECK(err_code);

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

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


/**@brief Function for handling Scaning events.
 *
 * @param[in]   p_scan_evt   Scanning event.
 */
static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{
    ret_code_t err_code;

    switch(p_scan_evt->scan_evt_id)
    {
        case NRF_BLE_SCAN_EVT_NOT_FOUND:
            if(memcmp(0xac,p_scan_evt->params.p_not_found->peer_addr.addr[3],4) == 0 && 
              (memcmp(0x31,p_scan_evt->params.p_not_found->peer_addr.addr[4],4) == 0) && 
              (memcmp(0x38,p_scan_evt->params.p_not_found->peer_addr.addr[5],4) == 0)){

            NRF_LOG_INFO("Received advertising from: %02x:%02x:%02x:%02x:%02x:%02x", p_scan_evt->params.p_not_found->peer_addr.addr[0], 
                                                                                          p_scan_evt->params.p_not_found->peer_addr.addr[1], 
                                                                                          p_scan_evt->params.p_not_found->peer_addr.addr[2], 
                                                                                          p_scan_evt->params.p_not_found->peer_addr.addr[3], 
                                                                                          p_scan_evt->params.p_not_found->peer_addr.addr[4], 
                                                                                          p_scan_evt->params.p_not_found->peer_addr.addr[5]);

            NRF_LOG_HEXDUMP_INFO(&p_scan_evt->params.p_not_found->data.p_data[0], p_scan_evt->params.p_not_found->data.len);

            sprintf (endereco,"%02x:%02x:%02x:%02x:%02x:%02x", p_scan_evt->params.p_not_found->peer_addr.addr[0], 
                                                                    p_scan_evt->params.p_not_found->peer_addr.addr[1], 
                                                                    p_scan_evt->params.p_not_found->peer_addr.addr[2], 
                                                                    p_scan_evt->params.p_not_found->peer_addr.addr[3], 
                                                                    p_scan_evt->params.p_not_found->peer_addr.addr[4], 
                                                                    p_scan_evt->params.p_not_found->peer_addr.addr[5]);                                                    

            //sprintf(advertising,NRF_LOG_HEXDUMP_INFO(&p_scan_evt->params.p_not_found->data.p_data[0], p_scan_evt->params.p_not_found->data.len));

            NRF_LOG_INFO("%s",endereco);

            memcpy(advertising,&p_scan_evt->params.p_not_found->data.p_data[0],p_scan_evt->params.p_not_found->data.len);

  //          char advertising[p_scan_evt->params.p_not_found->data.len];
            if(newdisp && advertising[7] == 0x01 && advertising[8] != 0x00){

              ble_gap_addr_t my_addr;

              ret_code_t err_code;
              err_code = sd_ble_gap_adv_stop(m_adv_handle);
              memcpy(enderecoatual,endereco,sizeof(endereco));
              newdisp = 0;
              msg = 1;
              err_code = sd_ble_gap_addr_get(&my_addr);
              APP_ERROR_CHECK(err_code);
              my_addr.addr_type = BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE;
              my_addr.addr[0] = p_scan_evt->params.p_not_found->peer_addr.addr[5];
              my_addr.addr[1] = p_scan_evt->params.p_not_found->peer_addr.addr[4];
              my_addr.addr[2] = p_scan_evt->params.p_not_found->peer_addr.addr[3];
              my_addr.addr[3] = p_scan_evt->params.p_not_found->peer_addr.addr[2];
              my_addr.addr[4] = p_scan_evt->params.p_not_found->peer_addr.addr[1];
              my_addr.addr[5] = p_scan_evt->params.p_not_found->peer_addr.addr[0];
              err_code = sd_ble_gap_addr_set(&my_addr);
              NRF_LOG_INFO("Erro: %x", err_code);
              APP_ERROR_CHECK(err_code);

              NRF_LOG_INFO("Novo endereço do dispositivo: %02x:%02x:%02x:%02x:%02x:%02x", my_addr.addr[0], 
                                                                                          my_addr.addr[1], 
                                                                                          my_addr.addr[2], 
                                                                                          my_addr.addr[3], 
                                                                                          my_addr.addr[4], 
                                                                                          my_addr.addr[5]);

             advertising_start();
            }
            
            if(advertising[7] == 0x01 && memcmp(enderecoatual,endereco,sizeof(endereco)) && msg == 1){
            memcpy(advertising1,&p_scan_evt->params.p_not_found->data.p_data[0],p_scan_evt->params.p_not_found->data.len);     
            NRF_LOG_INFO("adv1");
            cont++;
            if (cont >= 3){
              msg = 2;
              cont = 0;
            }
            
            for(int i=0;i<p_scan_evt->params.p_not_found->data.len;i++){
            m_adv_data.adv_data.p_data[i] = advertising1[i];
            }

            }

            else if(advertising[7] == 0x02 && memcmp(enderecoatual,endereco,sizeof(endereco)) && msg == 2){
            memcpy(advertising2,&p_scan_evt->params.p_not_found->data.p_data[0],p_scan_evt->params.p_not_found->data.len);
            NRF_LOG_INFO("adv2");
            cont++;
            if (cont >= 3){
              msg = 3;
              cont = 0;
            }
                        
            for(int i=0;i<p_scan_evt->params.p_not_found->data.len;i++){
            m_adv_data.adv_data.p_data[i] = advertising2[i];
            }

            }

            else if(advertising[7] == 0x03 && memcmp(enderecoatual,endereco,sizeof(endereco)) && msg == 3){
            memcpy(advertising3,&p_scan_evt->params.p_not_found->data.p_data[0],p_scan_evt->params.p_not_found->data.len);
            NRF_LOG_INFO("adv3");
            cont++;
            if (cont >= 3){
              msg = 4;
              cont = 0;
            }

                        
            for(int i=0;i<p_scan_evt->params.p_not_found->data.len;i++){
            m_adv_data.adv_data.p_data[i] = advertising3[i];
            }

            }

            else if(advertising[7] == 0x04 && memcmp(enderecoatual,endereco,sizeof(endereco)) && msg == 4){
            memcpy(advertising4,&p_scan_evt->params.p_not_found->data.p_data[0],p_scan_evt->params.p_not_found->data.len);
            NRF_LOG_INFO("adv4");
            cont++;
            if (cont >= 3){
              msg = 1;
              cont = 0;
              newdisp = 1;
            }

                        
            for(int i=0;i<p_scan_evt->params.p_not_found->data.len;i++){
            m_adv_data.adv_data.p_data[i] = advertising4[i];
            }

            }


            //NRF_LOG_INFO("%s",advertising);

            }

            

            //NRF_LOG_INFO("Advertising: %s",p_scan_evt->params.p_not_found->data.p_data);

            break;
        case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
            break;
        default:
          break;
    }
}

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

    NRF_LOG_DEFAULT_BACKENDS_INIT();
}


/**@brief Function for initializing the timer.
 */
static void timer_init(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the Power manager. */
static void power_management_init(void)
{
    ret_code_t err_code;
    err_code = nrf_pwr_mgmt_init();
    APP_ERROR_CHECK(err_code);
}


static void scan_init(void)
{
    ret_code_t          err_code;
    nrf_ble_scan_init_t init_scan;

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

    init_scan.connect_if_match = false;
    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;

    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling the idle state (main loop).
 *
 * @details Handle any pending log operation(s), then sleep until the next event occurs.
 */
static void idle_state_handle(void)
{
    NRF_LOG_FLUSH();
    nrf_pwr_mgmt_run();
}


int main(void)
{
    // Initialize.
    log_init();
    timer_init();
    leds_init();
    power_management_init();
    ble_stack_init();
    advertising_init();
    advertising_start();
    scan_init();
    // Start execution.
    NRF_LOG_INFO("Beacon scanner+advertiser example started.");
    scan_start();

    // Turn on the LED to signal scanning.
    bsp_board_led_on(CENTRAL_SCANNING_LED);

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