// ----- GPIO ------
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "sdk_common.h"
#include "nrf.h"
#include "nrf_delay.h"
#include "nrf_gpio.h"
#include "nrf_drv_gpiote.h"

#include "UartProcess.h"
#include "GpioProcess.h"
#include "EsbProcess.h"

const uint32_t UICR_ADDR_0x20C    __attribute__((at(0x1000120C))) __attribute__((used)) = 0xFFFFFFFE;				// Chianglin. 11/25/2018. 加上這一行, 會將 NFC pin 切到 GPIO

uint8_t		KeyDebunseTick = 0;
extern	void Action_Key1(void);
void Pin_Trigger_handler_1(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
	int				i;
	uint16_t		CRC;

	if ( KeyDebunseTick == 0 )
	{
		KeyDebunseTick = 2;
		printf(" Start Test\r\n");
		nrf_gpio_pin_toggle(GpioLed0);
		Action_Key1();
	}
}

void Pin_Trigger_handler_2(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
	printf("TX:%d / TX_OK:%d / TX_NG:%d / RX_OK:%d / RX_NG:%d\r\n", PacketSendCnt, PacketSendOKCnt, PacketSentNGCnt, PacketReceiveOKCnt, PacketReceiveNGCnt);
}

void gpio_init( void )
{
	ret_code_t err_code;

	err_code = nrf_drv_gpiote_init();
	APP_ERROR_CHECK(err_code);

	// Config GPIO output
	nrf_gpio_cfg_output(GpioLed0);						// LED-0 Config
	nrf_gpio_cfg_output(GpioLed1);						// LED-1 Config
	nrf_gpio_cfg_output(GpioLed2);						// LED-2 Config
	nrf_gpio_pin_clear(GpioLed0);						// LED-0 On
	nrf_gpio_pin_clear(GpioLed1);						// LED-1 On
	nrf_gpio_pin_clear(GpioLed2);						// LED-2 On
	nrf_gpio_cfg_output(RS485_RW_Control);				// "RS485 RW Control-pin" Config
	nrf_gpio_pin_clear(RS485_RW_Control);				// "RS485 RW Control-pin" Set to Read Mode

	// Config Button interrupt
	nrf_drv_gpiote_in_config_t in_config = GPIOTE_CONFIG_IN_SENSE_LOTOHI(true);
	in_config.pull = NRF_GPIO_PIN_PULLUP;
	err_code = nrf_drv_gpiote_in_init(5, &in_config, Pin_Trigger_handler_1);
	APP_ERROR_CHECK(err_code);
	err_code = nrf_drv_gpiote_in_init(6, &in_config, Pin_Trigger_handler_2);
	APP_ERROR_CHECK(err_code);

	nrf_drv_gpiote_in_event_enable(5, true);
	nrf_drv_gpiote_in_event_enable(6, true);
}
