#include "bsp/mc_hall_gpio.h"
#include "bsp/timer_count32.h"
#include "os/os_task.h"

static void _gpio_irq_enable(void);

static hall_io_t g_hall;

void mc_hall_init(void){
	gpio_init(HALL_1_GROUP,  GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, HALL_1_PIN);
	gpio_init(HALL_2_GROUP,  GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, HALL_2_PIN);
	gpio_init(HALL_3_GROUP,  GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, HALL_3_PIN);
	g_hall.is_edged = 0;
	g_hall.hall_time = 0;
	_gpio_irq_enable();
}

#if 1
int get_hall_stat(int samples) {
	int h1 = 0, h2 = 0, h3 = 0;
	int tres = (samples + 1) / 2;

	while (samples--) {
		h1 += READ_HALL1();
		h2 += READ_HALL2();
		h3 += READ_HALL3();
		task_udelay(5);
	}
#if HALL_PLACE==DEGREES_60	
	return (((h2>tres)^1) << 2) | ((h3 > tres) << 1) | (h2 > tres);
#else
	return (h1 > tres) | ((h2 > tres) << 1) | ((h3 > tres) << 2);
#endif
}
#else
int get_hall_stat(int samples) {
#if HALL_PLACE==DEGREES_60	
	return (((READ_HALL2())^1) << 2) | ((READ_HALL3()) << 1) | (READ_HALL1());
#else
	return (READ_HALL1()) | ((READ_HALL2()) << 1) | ((READ_HALL3()) << 2);
#endif
}
#endif


u32 hall_get_hwcount(u8 *hall) {
	hall[0] = 1;//READ_HALL1();
	hall[1] = 0;//READ_HALL2();
	hall[2] = 1;//READ_HALL3();
	if (g_hall.is_edged) {
		g_hall.is_edged = 0;
		return g_hall.hall_time;
	}
	return timer_count32_get();
}


void hall_sensor_handler(void){

}



#ifdef GD32_FOC_DEMO
static void _gpio_irq_enable(void){
	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOA, GPIO_PIN_SOURCE_6);
	exti_init(EXTI_6, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	exti_interrupt_flag_clear(EXTI_6);
	exti_interrupt_enable(EXTI_6);

	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOA, GPIO_PIN_SOURCE_7);
	exti_init(EXTI_7, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	exti_interrupt_flag_clear(EXTI_7);
	exti_interrupt_enable(EXTI_7);

	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_0);
	exti_init(EXTI_0, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	exti_interrupt_flag_clear(EXTI_0);
	exti_interrupt_enable(EXTI_0);

	nvic_irq_enable(EXTI5_9_IRQn, HALL_IRQ_PRIORITY, 0U);
	nvic_irq_enable(EXTI0_IRQn, HALL_IRQ_PRIORITY, 0U);
}

#else
static void _gpio_irq_enable(void){
	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_6);
	exti_init(EXTI_6, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	exti_interrupt_flag_clear(EXTI_6);
	exti_interrupt_enable(EXTI_6);

	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_7);
	exti_init(EXTI_7, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	exti_interrupt_flag_clear(EXTI_7);
	exti_interrupt_enable(EXTI_7);

	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_8);
	exti_init(EXTI_8, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	exti_interrupt_flag_clear(EXTI_8);
	exti_interrupt_enable(EXTI_8);

	nvic_irq_enable(EXTI5_9_IRQn, HALL_IRQ_PRIORITY, 0U);
}
#endif

