#include "bsp/bsp.h"
#include "bsp/bsp_driver.h"
#include "os/os_task.h"
#include "libs/logger.h"
/*
以下主要是在某一相电路无法采集的时候，需要对这相的pwm挖坑处理
timer 分配:
timer0 -> ch0-2 互补pwm
        ch4 event, update event 触发DMA(ch3,4)实现CCR的自更新
timer1 -> 触发ADC采样，GD32不支持多channel 或方式触发输出，通过timer1的 ch0 compara 配置 TRGO触发ADC，但是需要在一个PWM周期内触发2次（单电阻）
timer0 master --> timer1 slave/master 确保timer0，1同步开始，同频同相位

DMA 分配：
DMA0 ch4 -> timer0 update event
    ch3 -> timer0 chan3 CC event

    ch1 -> timer1 update event，需要更新CCR
*/

static void _init_pwm_timer(bool);
static void _pwm_gpio_config(void);
#ifndef PWM_BRAKE_GROUP
static void _gpio_brakein_irq_enable(void);
#endif
u16 timer_update_buffer[6] = {0};

static rcu_periph_enum _rcu_clk(u32 timer) {
    if (timer == TIMER0) {
        return RCU_TIMER0;
    }
    if (timer == TIMER1) {
        return RCU_TIMER1;
    }
    if (timer == TIMER2) {
        return RCU_TIMER2;
    }
    return RCU_TIMER2;      
}

void pwm_3phase_init(void){
	_pwm_gpio_config();
    _init_pwm_timer(true);
}

void pwm_3phase_sides(bool hon, bool lon) {
	if (hon && lon) {
		return;
	}
	timer_deinit(MOS_PWM_TIMER);
	rcu_periph_clock_enable(_rcu_clk(MOS_PWM_TIMER));
    gpio_init(PWM_U_P_GROUP,GPIO_MODE_OUT_PP,GPIO_OSPEED_50MHZ,PWM_U_P_PIN);
    gpio_init(PWM_V_P_GROUP,GPIO_MODE_OUT_PP,GPIO_OSPEED_50MHZ,PWM_V_P_PIN);
    gpio_init(PWM_W_P_GROUP,GPIO_MODE_OUT_PP,GPIO_OSPEED_50MHZ,PWM_W_P_PIN);

    gpio_init(PWM_U_N_GROUP,GPIO_MODE_OUT_PP,GPIO_OSPEED_50MHZ,PWM_U_N_PIN);
    gpio_init(PWM_V_N_GROUP,GPIO_MODE_OUT_PP,GPIO_OSPEED_50MHZ,PWM_V_N_PIN);
    gpio_init(PWM_W_N_GROUP,GPIO_MODE_OUT_PP,GPIO_OSPEED_50MHZ,PWM_W_N_PIN);

	sys_debug("pwm_3phase_sides\n");
	/* 开上桥或者下桥之前先关闭下桥或者上桥 */
	if (hon) {
		_pwm_gpio_config();
		_init_pwm_timer(false);
		delay_us(10);
		pwm_start();
		pwm_update_duty(FOC_PWM_Half_Period-200, FOC_PWM_Half_Period-200, FOC_PWM_Half_Period-200);
	}else if (lon) {
		gpio_bit_write(PWM_U_P_GROUP, PWM_U_P_PIN, RESET);
		gpio_bit_write(PWM_V_P_GROUP, PWM_V_P_PIN, RESET);
		gpio_bit_write(PWM_W_P_GROUP, PWM_W_P_PIN, RESET);

		delay_us(10);
		gpio_bit_write(PWM_U_N_GROUP, PWM_U_N_PIN, SET);
		gpio_bit_write(PWM_V_N_GROUP, PWM_V_N_PIN, SET);
		gpio_bit_write(PWM_W_N_GROUP, PWM_W_N_PIN, SET);
	}else {
#if 0		
		gpio_bit_write(PWM_U_P_GROUP, PWM_U_P_PIN, RESET);
		gpio_bit_write(PWM_V_P_GROUP, PWM_V_P_PIN, RESET);
		gpio_bit_write(PWM_W_P_GROUP, PWM_W_P_PIN, RESET);

		gpio_bit_write(PWM_U_N_GROUP, PWM_U_N_PIN, RESET);
		gpio_bit_write(PWM_V_N_GROUP, PWM_V_N_PIN, RESET);
		gpio_bit_write(PWM_W_N_GROUP, PWM_W_N_PIN, RESET);
#else
		pwm_3phase_init();
#endif
	}
}

static void _pwm_gpio_config(void)
{
    rcu_periph_clock_enable(PWM_U_P_RCU);
    rcu_periph_clock_enable(PWM_V_P_RCU);
	rcu_periph_clock_enable(PWM_W_P_RCU);
    rcu_periph_clock_enable(PWM_U_N_RCU);
    rcu_periph_clock_enable(PWM_V_N_RCU);
	rcu_periph_clock_enable(PWM_W_N_RCU);	
    rcu_periph_clock_enable(RCU_AF);

    /*configure PA8 PA9 PA10(TIMER0 CH0 CH1 CH2) as alternate function*/
    gpio_init(PWM_U_P_GROUP,PWM_U_P_MODE,GPIO_OSPEED_50MHZ,PWM_U_P_PIN);
    gpio_init(PWM_V_P_GROUP,PWM_V_P_MODE,GPIO_OSPEED_50MHZ,PWM_V_P_PIN);
    gpio_init(PWM_W_P_GROUP,PWM_W_P_MODE,GPIO_OSPEED_50MHZ,PWM_W_P_PIN);

    /*configure PB13 PB14 PB15(TIMER0 CH0N CH1N CH2N) as alternate function*/
    gpio_init(PWM_U_N_GROUP,PWM_U_N_MODE,GPIO_OSPEED_50MHZ,PWM_U_N_PIN);
    gpio_init(PWM_V_N_GROUP,PWM_V_N_MODE,GPIO_OSPEED_50MHZ,PWM_V_N_PIN);
    gpio_init(PWM_W_N_GROUP,PWM_W_N_MODE,GPIO_OSPEED_50MHZ,PWM_W_N_PIN);

	/*configure BRAKE IN*/
#ifdef PWM_BRAKE_GROUP
    /* TIMER0 BKIN */
	rcu_periph_clock_enable(PWM_BRAKE_RCU);
    gpio_init(PWM_BRAKE_GROUP, PWM_BRAKE_MODE, GPIO_OSPEED_50MHZ, PWM_BRAKE_PIN);
#endif
}

static u8 _dead_time(u16 t) {
	if (t < 128) {
		return (u8 )t;
	}else if (t <= (64 + 63) * 2) { //11 1111
		return ((((u8)2<<6) + (t-64)/2));
	}else if (t <= (32 + 31) * 8) {
		return (((u8)3 << 6) + (t - 32)/8);
	}else {
		if ((t-32)/16 > 63) {
			return 0xFF;
		}
		return (((u8)7<<3) + (t - 32)/16);
	}
}
#ifdef CONFIG_SENSORLESS_TOW_SAMPLES
#define PWM_CNT_REPEAT 0
#else
#define PWM_CNT_REPEAT 1
#endif
static void _init_pwm_timer(bool enable_brk) {
	timer_oc_parameter_struct timer_ocintpara;
	timer_parameter_struct timer_initpara;
	
	u32 timer = MOS_PWM_TIMER;
	u32 half_period = FOC_PWM_Half_Period;
	rcu_periph_clock_enable(_rcu_clk(timer));

	timer_deinit(timer);

    /* TIMER0 configuration */
	memset(&timer_initpara, 0, sizeof(timer_initpara));
	memset(&timer_ocintpara, 0, sizeof(timer_ocintpara));
    timer_initpara.prescaler        = 0;
    timer_initpara.alignedmode      = TIMER_COUNTER_CENTER_UP;
	timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period          = half_period;
    timer_initpara.clockdivision    = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = PWM_CNT_REPEAT;
    timer_init(timer,&timer_initpara);
    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(timer);

    /* CH1,CH2 and CH3 configuration in PWM mode */
    timer_ocintpara.outputstate  = TIMER_CCX_ENABLE;
    timer_ocintpara.outputnstate = TIMER_CCXN_ENABLE;
    timer_ocintpara.ocpolarity   = TIMER_OC_POLARITY_HIGH;
    timer_ocintpara.ocnpolarity  = TIMER_OCN_POLARITY_HIGH;
    timer_ocintpara.ocidlestate  = TIMER_OC_IDLE_STATE_LOW;
    timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;

    timer_channel_output_config(timer,TIMER_CH_0,&timer_ocintpara);
    timer_channel_output_pulse_value_config(timer,TIMER_CH_0,half_period/2);
    timer_channel_output_mode_config(timer,TIMER_CH_0,PWM_MODE);
    timer_channel_output_shadow_config(timer,TIMER_CH_0,TIMER_OC_SHADOW_ENABLE);

    timer_channel_output_config(timer,TIMER_CH_1,&timer_ocintpara);
    timer_channel_output_pulse_value_config(timer,TIMER_CH_1,half_period/2);
    timer_channel_output_mode_config(timer,TIMER_CH_1,PWM_MODE);
    timer_channel_output_shadow_config(timer,TIMER_CH_1,TIMER_OC_SHADOW_ENABLE);

    timer_channel_output_config(timer,TIMER_CH_2,&timer_ocintpara);
    timer_channel_output_pulse_value_config(timer,TIMER_CH_2,half_period/2);
    timer_channel_output_mode_config(timer,TIMER_CH_2,PWM_MODE);
    timer_channel_output_shadow_config(timer,TIMER_CH_2,TIMER_OC_SHADOW_ENABLE);
    
    timer_ocintpara.outputstate  = TIMER_CCX_ENABLE;
    timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE;
    timer_ocintpara.ocpolarity   = TIMER_OC_POLARITY_HIGH;
	timer_ocintpara.ocnpolarity  = TIMER_OCN_POLARITY_HIGH;
    timer_ocintpara.ocidlestate  = TIMER_OC_IDLE_STATE_LOW;
    timer_ocintpara.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;

    /* chan3 trigger adc O3CPRE is alwary active high, adc trigger is rising */
    timer_channel_output_config(timer,TIMER_CH_3,&timer_ocintpara);
    timer_channel_output_pulse_value_config(timer,TIMER_CH_3,half_period-5);
    timer_channel_output_mode_config(timer,TIMER_CH_3,TIMER_OC_MODE_PWM1);
    timer_channel_output_shadow_config(timer,TIMER_CH_3,TIMER_OC_SHADOW_ENABLE);

#ifdef PWM_BRAKE_GROUP
	timer_break_parameter_struct timer_breakpara;
    timer_breakpara.runoffstate        = TIMER_ROS_STATE_DISABLE;
    timer_breakpara.ideloffstate       = TIMER_ROS_STATE_DISABLE;
    timer_breakpara.protectmode        = TIMER_CCHP_PROT_OFF; 
    timer_breakpara.deadtime           = _dead_time(NS_2_TCLK(PWM_DEAD_TIME_NS));
    timer_breakpara.breakstate         = enable_brk?TIMER_BREAK_ENABLE:TIMER_BREAK_DISABLE;
    timer_breakpara.breakpolarity      = TIMER_BREAK_POLARITY_LOW;
    timer_breakpara.outputautostate    = TIMER_OUTAUTO_DISABLE;
    timer_break_config(timer,&timer_breakpara);
	timer_interrupt_enable(timer, TIMER_INT_BRK);
	timer_interrupt_flag_clear(timer, TIMER_INT_FLAG_BRK);
	nvic_irq_enable(PWM_BRK_IRQ, EBREAK_IRQ_PRIORITY, 0);		
#else
	_gpio_brakein_irq_enable();
#endif

#ifdef CONFIG_SENSORLESS_TOW_SAMPLES
	timer_master_slave_mode_config(timer,TIMER_MASTER_SLAVE_MODE_ENABLE);
	timer_master_output_trigger_source_select(timer,TIMER_TRI_OUT_SRC_UPDATE);
#else
	timer_master_slave_mode_config(timer,TIMER_MASTER_SLAVE_MODE_DISABLE);
#endif
	pwm_enable_channel();

	timer_interrupt_disable(timer, TIMER_INT_UP);
	timer_interrupt_flag_clear(timer, TIMER_INT_FLAG_UP);
	nvic_irq_enable(PWM_UP_IRQ, TIMER_UP_IRQ_PRIORITY, 0);
    timer_enable(timer);

#ifdef GD32_FOC_DEMO
	/* IR2136S enable */
    gpio_ir2136_enable(true);
#endif

}



#ifndef PWM_BRAKE_GROUP
static void _gpio_brakein_irq_enable(void){
#ifndef GD32_FOC_DEMO
	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_4);
	exti_init(EXTI_4, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	nvic_irq_enable(EXTI4_IRQn, EBREAK_IRQ_PRIORITY, 0U);
	exti_interrupt_flag_clear(EXTI_4);
	exti_interrupt_enable(EXTI_4);

	gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOB, GPIO_PIN_SOURCE_5);
	exti_init(EXTI_5, EXTI_INTERRUPT, EXTI_TRIG_BOTH);
	nvic_irq_enable(EXTI5_9_IRQn, EBREAK_IRQ_PRIORITY, 0U);
	exti_interrupt_flag_clear(EXTI_5);
	exti_interrupt_enable(EXTI_5);
#endif	
}
#endif

void pwm_start(void){
	pwm_update_duty(FOC_PWM_Half_Period/2, FOC_PWM_Half_Period/2, FOC_PWM_Half_Period/2);
	pwm_update_2smaples(FOC_PWM_Half_Period-1, FOC_PWM_Half_Period + 1);
	/* wait for a new PWM period to flush last HF task */
	timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP);

	timer_event_software_generate(MOS_PWM_TIMER, TIMER_EVENT_SRC_UPG);
	while ( timer_flag_get(MOS_PWM_TIMER, TIMER_FLAG_UP) == RESET ){}
	/* Clear Update Flag */
	timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP);

	timer_primary_output_config(MOS_PWM_TIMER,ENABLE);
}

void pwm_stop(void){
	timer_primary_output_config(MOS_PWM_TIMER,DISABLE);

	timer_interrupt_disable(MOS_PWM_TIMER, TIMER_INT_UP);
	/* wait for a new PWM period to flush last HF task */
	timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP);
	while ( timer_flag_get(MOS_PWM_TIMER, TIMER_FLAG_UP) == RESET ){}
	/* Clear Update Flag */
	timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP);
}

void pwm_enable_output(bool enable) {
	if (enable) {
		timer_primary_output_config(MOS_PWM_TIMER,ENABLE);
	}else {
		timer_primary_output_config(MOS_PWM_TIMER,DISABLE);
	}
}

/*open low side of the mosfet*/
void pwm_turn_on_low_side(void)
{
	pwm_update_duty(0, 0, 0);
	pwm_update_2smaples(FOC_PWM_Half_Period-1, FOC_PWM_Half_Period + 1);
	timer_flag_clear(MOS_PWM_TIMER,TIMER_FLAG_UP);
	timer_event_software_generate(MOS_PWM_TIMER, TIMER_EVENT_SRC_UPG);
  	while (timer_flag_get(MOS_PWM_TIMER,TIMER_FLAG_UP) == RESET );
  	/* Main PWM Output Enable */
  	timer_primary_output_config(MOS_PWM_TIMER, ENABLE);
}

void pwm_update_sample(u32 samp1, u32 samp2, u8 sector) {
	if (samp1 < FOC_PWM_Half_Period) {
		TIMER_CH3CV(MOS_PWM_TIMER) = samp1;
		pwm_change_t3_mode(TIMER_OC_MODE_PWM1);
	}else {
		TIMER_CH3CV(MOS_PWM_TIMER) = samp2;
		pwm_change_t3_mode(TIMER_OC_MODE_PWM0);
	}
	adc_current_sample_config(sector);
}
