/*
 * p_io.c
 *
 * Created: 8/19/2020 5:18:03 PM
 *  Author: Penguin
 */ 
#include "p_io.h"
#include "p_usart.h"

static volatile p_btn_state_t btn_state = P_BTN_STATE_STOP;
static volatile bool b_new_button_state = false;
static void p_forward_btn_cb(void);
static void p_reverse_btn_cb(void);
static void p_stop_btn_cb(void);
static void _p_io_init(uint32_t eic_pin, uint32_t eic_mux, enum extint_pull pin_pull,
	enum extint_detect det, uint8_t eic_line, const extint_callback_t cb)
{
	struct extint_chan_conf chan_conf;
	extint_chan_get_config_defaults(&chan_conf);
	
	chan_conf.gpio_pin		= eic_pin;
	chan_conf.gpio_pin_mux	= eic_mux;
	chan_conf.gpio_pin_pull = pin_pull;
	chan_conf.detection_criteria = det;
	extint_chan_set_config(eic_line, &chan_conf);
	extint_register_callback(cb, eic_line, EXTINT_CALLBACK_TYPE_DETECT);
}

void p_io_init(void)
{
	_p_io_init(P_IO_FORWARD_BTN_EIC_PIN, P_IO_FORWARD_BTN_EIC_MUX, 
		P_IO_FORWARD_BTN_PULL, P_IO_FORWARD_BTN_DET, P_IO_FORWARD_BTN_EIC_LINE, p_forward_btn_cb);
	_p_io_init(P_IO_REVERSE_BTN_EIC_PIN, P_IO_REVERSE_BTN_EIC_MUX,
		P_IO_REVERSE_BTN_PULL, P_IO_REVERSE_BTN_DET, P_IO_REVERSE_BTN_EIC_LINE, p_reverse_btn_cb);
	_p_io_init(P_IO_STOP_BTN_EIC_PIN, P_IO_STOP_BTN_EIC_MUX,
		P_IO_STOP_BTN_PULL, P_IO_STOP_BTN_DET, P_IO_STOP_BTN_EIC_LINE, p_stop_btn_cb);
		
	p_io_enable(P_IO_FORWARD_BTN_EIC_LINE);
	p_io_enable(P_IO_REVERSE_BTN_EIC_LINE);
	p_io_enable(P_IO_STOP_BTN_EIC_LINE);
}

void p_io_enable(uint8_t eic_line)
{
	extint_chan_enable_callback(eic_line, EXTINT_CALLBACK_TYPE_DETECT);
}


void p_forward_btn_cb(void)
{
	printf("Going forward!\n");
	if(btn_state != P_BTN_STATE_FWD)
	{
		btn_state = P_BTN_STATE_FWD;
		b_new_button_state = true;
	}
}
void p_reverse_btn_cb(void)
{
	printf("Going backwards!\n");
	if(btn_state != P_BTN_STATE_REV)
	{
		btn_state = P_BTN_STATE_REV;
		b_new_button_state = true;
	}

}
void p_stop_btn_cb(void)
{
	printf("Stopping!\n");
	if(btn_state != P_BTN_STATE_STOP)
	{
		btn_state = P_BTN_STATE_STOP;
		b_new_button_state = true;
	}
}

bool p_button_pressed(void)
{
	if(b_new_button_state)
	{
		b_new_button_state = false;
		return true;
	}
	return false;
}

p_btn_state_t p_button_state(void)
{
	return btn_state;
}