/**
 * This software is subject to the ANT+ Shared Source License
 * www.thisisant.com/swlicenses
 * Copyright (c) Garmin Canada Inc. 2014
 * 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 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 Garmin nor the names of its
 *       contributors may be used to endorse or promote products
 *       derived from this software without specific prior
 *       written permission.
 *
 * The following actions are prohibited:
 *
 *    1) Redistribution of source code containing the ANT+ Network
 *       Key. The ANT+ Network Key is available to ANT+ Adopters.
 *       Please refer to http://thisisant.com to become an ANT+
 *       Adopter and access the key. 
 *
 *    2) Reverse engineering, decompilation, and/or disassembly of
 *       software provided in binary form under this license.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE HEREBY
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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; DAMAGE TO ANY DEVICE, 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. SOME STATES DO NOT ALLOW 
 * THE EXCLUSION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE
 * ABOVE LIMITATIONS MAY NOT APPLY TO YOU.
 *
 */
/**@file
 * @defgroup ant_broadcast_rx_example ANT Broadcast RX Example
 * @{
 * @ingroup nrf_ant_broadcast
 *
 * @brief Example of basic ANT Broadcast RX.
 *
 * Before compiling this example for NRF52, complete the following steps:
 * - Download the S212 SoftDevice from <a href="https://www.thisisant.com/developer/components/nrf52832" target="_blank">thisisant.com</a>.
 * - Extract the downloaded zip file and copy the S212 SoftDevice headers to <tt>\<InstallFolder\>/components/softdevice/s212/headers</tt>.
 * If you are using Keil packs, copy the files into a @c headers folder in your example folder.
 * - Make sure that @ref ANT_LICENSE_KEY in @c nrf_sdm.h is uncommented.
 */

/******************includes**************************/

#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "nrf.h"
#include "bsp.h"
#include "hardfault.h"
#include "app_error.h"
#include "app_timer.h"

#include "nrf_sdh.h"
#include "nrf_sdh_ant.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_drv_gpiote.h"
#include "nrf_fstorage.h"
#include "nrf_fstorage_sd.h"
#include "nrf_delay.h"

#include "ant_interface.h"
#include "ant_parameters.h"
#include "ant_channel_config.h"

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

/******************MACROS**************************/

#define APP_ANT_OBSERVER_PRIO   1    /**< Application's ANT observer priority. You shouldn't need to modify this value. */

#define BUTTON1 14

#define TIME_INRVL1  APP_TIMER_TICKS(50)

APP_TIMER_DEF(m_tick_timer1);

/*******************GLOBAL VARIABLES******************/


uint8_t first_message,send_common_datapage80,channel_periond_cnt,device_paired,tick1_cnt;


uint32_t devnum_addr = 0x2C000;

static void fstorage_evt_handler(nrf_fstorage_evt_t * p_evt);

NRF_FSTORAGE_DEF(nrf_fstorage_t fstorage) =
{
    /* Set a handler for fstorage events. */
    .evt_handler = fstorage_evt_handler,

    /* These below are the boundaries of the flash space assigned to this instance of fstorage.
     * You must set these manually, even at runtime, before nrf_fstorage_init() is called.
     * The function nrf5_flash_end_addr_get() can be used to retrieve the last address on the
     * last page of flash available to write data. */
    .start_addr = 0x2C000,
    .end_addr   = 0x2Cfff,
};

void intflash_init(void);

/*******************FUNCTION DEFINITION**************/

static void fstorage_evt_handler(nrf_fstorage_evt_t * p_evt)
{
    if (p_evt->result != NRF_SUCCESS)
    {
        NRF_LOG_INFO("--> Event received: ERROR while executing an fstorage operation.");
        return;
    }

    switch (p_evt->id)
    {
        case NRF_FSTORAGE_EVT_WRITE_RESULT:
        {
            NRF_LOG_INFO("--> Event received: wrote %d bytes at address 0x%x.",
                         p_evt->len, p_evt->addr);
        } break;

        case NRF_FSTORAGE_EVT_ERASE_RESULT:
        {
            NRF_LOG_INFO("--> Event received: erased %d page from address 0x%x.",
                         p_evt->len, p_evt->addr);
        } break;

        default:
            break;
    }
}
void ant_channel_reinit(void)
{

    ret_code_t err_code = sd_ant_channel_unassign(LEV_CHANNEL_NUMBER);
    APP_ERROR_CHECK(err_code);

    // Set Channel Number.
    err_code = sd_ant_channel_assign(LEV_CHANNEL_NUMBER,
                                     CHANNEL_TYPE_SLAVE,
                                     ANTPLUS_NETWORK_NUM,
                                     0x00);
    APP_ERROR_CHECK(err_code);

// Set Channel ID.
    err_code = sd_ant_channel_id_set(LEV_CHANNEL_NUMBER,
                                     0,
                                     CHAN_ID_DEV_TYPE,
                                     CHAN_ID_TRANS_TYPE);
    APP_ERROR_CHECK(err_code);

    // Open channel.
    err_code = sd_ant_channel_open(LEV_CHANNEL_NUMBER);
    APP_ERROR_CHECK(err_code);
}
/**
 * @brief 2 seconds tick handler for updataing cumulative operating time.
 */
static void app_tick_handler1(void * p_context)
{
   tick1_cnt++;

   if(nrf_gpio_pin_read(BUTTON1) == 1)
   {
    if(tick1_cnt>=20)
    {
        if(device_paired)
        {
         
          NRF_LOG_INFO("Slave disconnected");
  
          bsp_board_led_off(BSP_BOARD_LED_1);

          ret_code_t err_code = sd_ant_channel_close(LEV_CHANNEL_NUMBER);
          APP_ERROR_CHECK(err_code);

          tick1_cnt = 0;
          device_paired = 0;
          app_timer_stop(m_tick_timer1);

          err_code = nrf_fstorage_erase(&fstorage,devnum_addr,1,NULL);
          APP_ERROR_CHECK(err_code);

          NRF_LOG_INFO("erase error code:%d",err_code);
          nrf_delay_ms(500);
          

          NVIC_SystemReset();
        }
    }
    else
    {
      bsp_board_led_off(BSP_BOARD_LED_1);
      app_timer_stop(m_tick_timer1);
    }
    tick1_cnt=0;
   }

}
void in1_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
   // if(!pairing_started)
    {
    bsp_board_led_on(BSP_BOARD_LED_1);

    ret_code_t err_code = app_timer_start(m_tick_timer1, TIME_INRVL1, NULL);
    APP_ERROR_CHECK(err_code);
    }
}


/**@brief Function for handling a ANT stack event.
 *
 * @param[in] p_ant_evt  ANT stack event.
 * @param[in] p_context  Context.
 */
void ant_evt_handler(ant_evt_t * p_ant_evt, void * p_context)
{
    ret_code_t err_code;

    if (p_ant_evt->channel == LEV_CHANNEL_NUMBER)
    {
        switch (p_ant_evt->event)
        {
            case EVENT_RX:
                if (p_ant_evt->message.ANT_MESSAGE_ucMesgID == MESG_BROADCAST_DATA_ID
                 || p_ant_evt->message.ANT_MESSAGE_ucMesgID == MESG_ACKNOWLEDGED_DATA_ID
                 || p_ant_evt->message.ANT_MESSAGE_ucMesgID == MESG_BURST_DATA_ID)
                { 
                    if(!device_paired)
                    {
                      uint32_t m_device_id = uint16_decode(p_ant_evt->message.ANT_MESSAGE_aucExtData);
                      uint32_t *w_add =(uint32_t*) devnum_addr;

                      err_code = nrf_fstorage_write(&fstorage, devnum_addr, &m_device_id, sizeof(m_device_id), NULL);
                      APP_ERROR_CHECK(err_code);
                    
                      // Wait for the erase operation to complete.
                      //while (nrf_fstorage_is_busy(&fstorage));
                      nrf_delay_ms(50);

                      NRF_LOG_INFO("device paired");
                     
                      device_paired = 1;
                     
                    }    
                     err_code = bsp_indication_set(BSP_INDICATE_SENT_OK);
                      APP_ERROR_CHECK(err_code);           
                    //send_common_Datapage();

                    //process_rxmessage(p_ant_evt->message.ANT_MESSAGE_aucPayload);
                    
                }
                break;
            
            case EVENT_RX_SEARCH_TIMEOUT:
                  // Open channel.
                  err_code = sd_ant_channel_open(LEV_CHANNEL_NUMBER);
                  APP_ERROR_CHECK(err_code);

                  break;

            default:
                break;
        }
    }
}

NRF_SDH_ANT_OBSERVER(m_ant_observer, APP_ANT_OBSERVER_PRIO, ant_evt_handler, NULL);

void button_int_init()
{
    ret_code_t err_code;

    err_code = nrf_drv_gpiote_init();
    APP_ERROR_CHECK(err_code);

    nrf_drv_gpiote_in_config_t in1_config = GPIOTE_CONFIG_IN_SENSE_HITOLO(true);
    in1_config.pull = NRF_GPIO_PIN_PULLUP;

    err_code = nrf_drv_gpiote_in_init(BUTTON1, &in1_config, in1_pin_handler);
    APP_ERROR_CHECK(err_code);

    nrf_drv_gpiote_in_event_enable(BUTTON1, true);

}

/**@brief Function for the Timer and BSP initialization.
 */
static void utils_setup(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);

    err_code = bsp_init(BSP_INIT_LEDS,
                        NULL);
    APP_ERROR_CHECK(err_code);

    button_int_init();
    
    err_code = app_timer_create(&m_tick_timer1,
                                APP_TIMER_MODE_REPEATED,
                                app_tick_handler1);

    err_code = nrf_pwr_mgmt_init();
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for ANT stack initialization.
 */
static void softdevice_setup(void)
{
    ret_code_t err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);

    ASSERT(nrf_sdh_is_enabled());

    err_code = nrf_sdh_ant_enable();
    APP_ERROR_CHECK(err_code);

}

uint16_t check_devnum(void)
{
    uint32_t *p_addr = (uint32_t *)devnum_addr;

    if(*p_addr != 0xffffffff )
    {
      //NRF_LOG_INFO("device id read from the flash : %x", *p_addr);
      device_paired = 1;
      return (uint16_t)*p_addr;
    }
    else
    {
      device_paired = 0;
      return 0;
    }
}

/**@brief Function for setting up the ANT module.
 */
static void ant_plus_lev_slave_setup(void)
{
    uint16_t dev_num = check_devnum();

    NRF_LOG_INFO("device id read from the flash : %d", dev_num);
    ant_channel_config_t ant_plus_lev_channel_config =
    {
        .channel_number    = LEV_CHANNEL_NUMBER,
        .channel_type      = CHANNEL_TYPE_SLAVE,
        .ext_assign        = 0x00,
        .rf_freq           = RF_FREQ,
        .transmission_type = CHAN_ID_TRANS_TYPE,
        .device_type       = CHAN_ID_DEV_TYPE,
        .device_number     = dev_num,
        .channel_period    = CHAN_PERIOD,
        .network_number    = ANTPLUS_NETWORK_NUM,
    };

    ret_code_t err_code = ant_channel_init(&ant_plus_lev_channel_config);
    APP_ERROR_CHECK(err_code);

    // Open channel.
    err_code = sd_ant_channel_open(LEV_CHANNEL_NUMBER);
    APP_ERROR_CHECK(err_code);
}

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

    NRF_LOG_DEFAULT_BACKENDS_INIT();
}

void intflash_init(void)
{
    ret_code_t err_code;

    nrf_fstorage_api_t * p_fs_api; 

    p_fs_api = &nrf_fstorage_sd;

    err_code = nrf_fstorage_init(&fstorage, p_fs_api, NULL);
    APP_ERROR_CHECK(err_code);   

}

/**@brief Function for application main entry. Does not return.
 */
int main(void)
{  
    
    log_init();
    intflash_init();
    utils_setup();
    softdevice_setup();


    //Test code to test fstorage functions after soft device initialization

    uint32_t m_device_id =27077;
    uint32_t *w_addr = (uint32_t *)devnum_addr;

    ret_code_t err_code = nrf_fstorage_erase(&fstorage, devnum_addr, 1, NULL);
    APP_ERROR_CHECK(err_code);

  // Wait for the erase operation to complete.
     while (nrf_fstorage_is_busy(&fstorage));

    err_code = nrf_fstorage_write(&fstorage, devnum_addr, &m_device_id, sizeof(m_device_id), NULL);
    APP_ERROR_CHECK(err_code);

    // Wait for the erase operation to complete.
    while (nrf_fstorage_is_busy(&fstorage));

    NRF_LOG_INFO("DUMMY READ : %x", *w_addr);

    // test code ends   
    
    ant_plus_lev_slave_setup();  
    
    NRF_LOG_INFO("ANT SLAVE LEV started.");

    // Main loop.
    for (;;)
    {
        NRF_LOG_FLUSH();
        nrf_pwr_mgmt_run();
    }
}


/**
 *@}
 **/
