

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "sdk_common.h"
//	#include "nrf_esb.h"
#include "nrf.h"
#include "nrf_error.h"
#include "nrf_esb_error_codes.h"
#include "nrf_delay.h"
#include "nrf_gpio.h"
#include "EsbProcess.h"
#include "boards.h"
#include "app_util.h"

char	gEsbModeStatus;						// 0 for ESB_PTX, 1 for ESB_PRX
nrf_esb_payload_t my_tx_payload = NRF_ESB_CREATE_PAYLOAD(0, 0x01, 0x00);
nrf_esb_payload_t my_rx_payload;

uint32_t esb_init( void )
{
    uint32_t err_code;
    uint8_t base_addr_0[4] = {0xE7, 0xE7, 0xE7, 0xE7};
    uint8_t base_addr_1[4] = {0xC2, 0xC2, 0xC2, 0xC2};
    uint8_t addr_prefix[8] = {0xE7, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8 };

    nrf_esb_config_t nrf_esb_config         = NRF_ESB_DEFAULT_CONFIG;
    nrf_esb_config.retransmit_count         = 6;
    nrf_esb_config.selective_auto_ack       = false;
    nrf_esb_config.protocol                 = NRF_ESB_PROTOCOL_ESB_DPL;
    nrf_esb_config.bitrate                  = NRF_ESB_BITRATE_2MBPS;
    nrf_esb_config.event_handler            = nrf_esb_event_handler;
    nrf_esb_config.mode                     = NRF_ESB_MODE_PTX;

    err_code = nrf_esb_init(&nrf_esb_config);
    VERIFY_SUCCESS(err_code);

    err_code = nrf_esb_set_base_address_0(base_addr_0);
    VERIFY_SUCCESS(err_code);

    err_code = nrf_esb_set_base_address_1(base_addr_1);
    VERIFY_SUCCESS(err_code);

    err_code = nrf_esb_set_prefixes(addr_prefix, 8);
    VERIFY_SUCCESS(err_code);

    my_tx_payload.length  = 3;
    my_tx_payload.noack = false;
    my_tx_payload.pipe    = 0;
    my_tx_payload.length  = 3;
    my_tx_payload.data[0] = 0x00;

    return NRF_SUCCESS;
}

void nrf_esb_event_handler(nrf_esb_evt_t const * p_event)
{
    switch (p_event->evt_id)
    {
        case NRF_ESB_EVENT_TX_SUCCESS:
            printf(" ---> TX SUCCESS EVENT\r\n");
            //	nrf_esb_read_rx_payload(&my_rx_payload);
            //	if (nrf_esb_read_rx_payload(&my_rx_payload) == NRF_SUCCESS)
            //	gReceivedPacketFlag = 1;
            break;
        case NRF_ESB_EVENT_TX_FAILED:
            //xx	 printf(" ***  TX FAILED EVENT\r\n");
            (void) nrf_esb_flush_tx();
            //	(void) nrf_esb_start_tx();
            break;
        case NRF_ESB_EVENT_RX_RECEIVED:
            printf(" ---> RX RECEIVED EVENT\r\n");
            while (nrf_esb_read_rx_payload(&my_rx_payload) == NRF_SUCCESS);
            printf("ReceiveData: %.2X\r\n", my_rx_payload.data[0]);
        	if ( gEsbModeStatus == 1 )
        	{
            	memcpy((void *)&my_tx_payload, (void *)&my_rx_payload, sizeof(nrf_esb_payload_t));
            	(void) nrf_esb_write_payload(&my_tx_payload);
        	}
            //	gReceivedPacketFlag = 1;

            break;
    }
}
