/*! ----------------------------------------------------------------------------
 * @file	interrupts.c
 * @brief	Interrupts access function implementations
 * @version 5.0
 * @date 18/05/2017
 */

#include "nrf.h"
#include "nrf_drv_gpiote.h"
#include "interrupts.h"


// interrupt function
InterruptType ptr_InterruptFunction;

/*********************************************************************/
/********************* Hardware Interrupt ****************************/
/*********************************************************************/

/**@brief Pin interruption handler - Should call the decawave callback function !
 *
 * @param[in] pin		pin number
 * @param[in] action	polarity
 *
 */
void in_pin_handler (nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
	// Call decawave callback function
	(*ptr_InterruptFunction)();
}

/**@brief Set an interruption on a pin change
 *
 * @param[in] pin	pin number
 * @retvalue  err_code
 *
 */
ret_code_t GPIO_INT_init(uint32_t pin, InterruptType addr) 
{
    ret_code_t err_code;
	
    err_code = nrf_drv_gpiote_init();
    APP_ERROR_CHECK(err_code); 
	
	// Sense rising edge
    nrf_drv_gpiote_in_config_t in_config = GPIOTE_CONFIG_IN_SENSE_LOTOHI(true); //MPW3 IRQ polarity is high by default
    in_config.pull = NRF_GPIO_PIN_PULLDOWN; //IRQ pin should be Pull Down to prevent unnecessary EXT IRQ while DW1000 goes to sleep mode

	// configure interrupt
    err_code = nrf_drv_gpiote_in_init(pin, &in_config, in_pin_handler);
    APP_ERROR_CHECK(err_code);
	
	// Set interrupt function
	ptr_InterruptFunction = addr;
	
	return err_code;
}

/**@brief Enable interruption on a pin change
 *
 * @param[in] pin	pin number
 *
 */
void GPIO_INT_enable (uint32_t pin)
{
	nrf_drv_gpiote_in_event_enable(pin, true);
}

/**@brief Disable interruption on a pin change
 *
 * @param[in] pin	pin number
 *
 */
void GPIO_INT_disable (uint32_t pin)
{
	nrf_drv_gpiote_in_event_disable(pin);
}
