#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

static void pwm_gpio_init(gpio_type *gpiox, gpio_mode_type mode, gpio_output_type otype, gpio_pull_type pull, u32 pin) {
	gpio_init_type gpio_init_struct = {0};
	gpio_default_para_init(&gpio_init_struct);
	gpio_init_struct.gpio_mode = mode;
	gpio_init_struct.gpio_out_type = otype;
	gpio_init_struct.gpio_pull = pull;
	gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
	
	/* High-side, Phase A,B,C Config */
	gpio_init_struct.gpio_pins = pin;
	gpio_init(gpiox, &gpio_init_struct);
}

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

void pwm_3phase_sides(bool hon, bool lon) {
	if (hon && lon) {
		return;
	}
	tmr_reset(MOS_PWM_TIMER);
	crm_periph_clock_enable(PWM_CRM_CLK, TRUE);
    pwm_gpio_init(PWM_U_P_GROUP,GPIO_MODE_OUTPUT,GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE, PWM_U_P_PIN);
    pwm_gpio_init(PWM_V_P_GROUP,GPIO_MODE_OUTPUT,GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE,PWM_V_P_PIN);
    pwm_gpio_init(PWM_W_P_GROUP,GPIO_MODE_OUTPUT,GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE,PWM_W_P_PIN);

    pwm_gpio_init(PWM_U_N_GROUP,GPIO_MODE_OUTPUT,GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE,PWM_U_N_PIN);
    pwm_gpio_init(PWM_V_N_GROUP,GPIO_MODE_OUTPUT,GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE,PWM_V_N_PIN);
    pwm_gpio_init(PWM_W_N_GROUP,GPIO_MODE_OUTPUT,GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE,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_bits_write(PWM_U_P_GROUP, PWM_U_P_PIN, FALSE);
		gpio_bits_write(PWM_V_P_GROUP, PWM_V_P_PIN, FALSE);
		gpio_bits_write(PWM_W_P_GROUP, PWM_W_P_PIN, FALSE);

		delay_us(10);
		gpio_bits_write(PWM_U_N_GROUP, PWM_U_N_PIN, TRUE);
		gpio_bits_write(PWM_V_N_GROUP, PWM_V_N_PIN, TRUE);
		gpio_bits_write(PWM_W_N_GROUP, PWM_W_N_PIN, TRUE);
	}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)
{
    crm_periph_clock_enable(PWM_U_P_RCU, TRUE);
    crm_periph_clock_enable(PWM_V_P_RCU, TRUE);
	crm_periph_clock_enable(PWM_W_P_RCU, TRUE);
    crm_periph_clock_enable(PWM_U_N_RCU, TRUE);
    crm_periph_clock_enable(PWM_V_N_RCU, TRUE);
	crm_periph_clock_enable(PWM_W_N_RCU, TRUE);	

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

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

	/*configure BRAKE IN*/
#ifdef PWM_BRAKE_GROUP
    /* TIMER0 BKIN */
	crm_periph_clock_enable(PWM_BRAKE_RCU, TRUE);
    pwm_gpio_init(PWM_BRAKE_GROUP, PWM_BRAKE_MODE, GPIO_OUTPUT_PUSH_PULL,GPIO_PULL_NONE, 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);
	}
}

static void _init_pwm_timer(bool enable_brk) {
	tmr_output_config_type tmr_output_struct;
	tmr_brkdt_config_type tmr_brkdt_config_struct;

	tmr_reset(MOS_PWM_TIMER);
	crm_periph_clock_enable(PWM_CRM_CLK, TRUE);
	tmr_repetition_counter_set(MOS_PWM_TIMER, 1); 		 /* the pwm cycle isr in underflow (high-side pwm on) */
	tmr_base_init(MOS_PWM_TIMER, FOC_PWM_Half_Period, 0);
	tmr_cnt_dir_set(MOS_PWM_TIMER, TMR_COUNT_TWO_WAY_1);	/* output compare interrupt flags are set only count-down */
	/* set dead time clock */
	tmr_clock_source_div_set(MOS_PWM_TIMER, TMR_CLOCK_DIV1);

	/* channel 1,2,3,1C,2C,3C configuration in output mode */
	tmr_channel_value_set(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_1, FOC_PWM_Half_Period/2);
	tmr_channel_value_set(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_2, FOC_PWM_Half_Period/2);
	tmr_channel_value_set(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_3, FOC_PWM_Half_Period/2);

	tmr_output_default_para_init(&tmr_output_struct);
	tmr_output_struct.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A;
	tmr_output_struct.oc_output_state = TRUE;
	tmr_output_struct.oc_polarity = TMR_OUTPUT_ACTIVE_HIGH;
	tmr_output_struct.oc_idle_state = FALSE;
	tmr_output_struct.occ_output_state = TRUE;
	tmr_output_struct.occ_polarity = TMR_OUTPUT_ACTIVE_HIGH;
	tmr_output_struct.occ_idle_state = FALSE;
	
	/* channel 1, 2, 3 */
	tmr_output_channel_config(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_1, &tmr_output_struct);
	tmr_output_channel_config(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_2, &tmr_output_struct);
	tmr_output_channel_config(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_3, &tmr_output_struct);
	
	tmr_output_channel_buffer_enable(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_1, TRUE);
	tmr_output_channel_buffer_enable(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_2, TRUE);
	tmr_output_channel_buffer_enable(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_3, TRUE);

	tmr_output_struct.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_B;
	tmr_output_channel_config(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_4, &tmr_output_struct);
	tmr_channel_value_set(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_4, FOC_PWM_Half_Period-1);
	tmr_output_channel_buffer_enable(MOS_PWM_TIMER, TMR_SELECT_CHANNEL_4, TRUE);
#ifdef PWM_BRAKE_GROUP
	/* automatic output enable, break, dead time and lock configuration */
	tmr_brkdt_default_para_init(&tmr_brkdt_config_struct);
	tmr_brkdt_config_struct.brk_enable = enable_brk?TRUE:FALSE;
	tmr_brkdt_config_struct.auto_output_enable = FALSE;
	tmr_brkdt_config_struct.deadtime = _dead_time(NS_2_TCLK(PWM_DEAD_TIME_NS));
	tmr_brkdt_config_struct.fcsodis_state = TRUE;
	tmr_brkdt_config_struct.fcsoen_state = FALSE;
	tmr_brkdt_config_struct.brk_polarity = TMR_BRK_INPUT_ACTIVE_LOW;
	tmr_brkdt_config_struct.wp_level = TMR_WP_OFF;
	tmr_brkdt_config(MOS_PWM_TIMER, &tmr_brkdt_config_struct);
#endif
	tmr_primary_mode_select(MOS_PWM_TIMER, TMR_PRIMARY_SEL_OVERFLOW);

	tmr_flag_clear(MOS_PWM_TIMER, TMR_OVF_FLAG | TMR_BRK_FLAG | TMR_C4_INT);
	tmr_interrupt_enable(MOS_PWM_TIMER, TMR_OVF_INT, TRUE);
	tmr_interrupt_enable(MOS_PWM_TIMER, TMR_BRK_INT, TRUE);

	/* disable single pulse mode */
	tmr_one_cycle_mode_enable(MOS_PWM_TIMER, FALSE);

	/* pwm timer output enable */
	tmr_output_enable(MOS_PWM_TIMER, FALSE);

	nvic_irq_enable(TMR1_BRK_TMR9_IRQn, EBREAK_IRQ_PRIORITY, 0);
	nvic_irq_enable(TMR1_OVF_TMR10_IRQn, TIMER_UP_IRQ_PRIORITY, 0);

	/* enable pwm timer */
	tmr_counter_enable(MOS_PWM_TIMER, TRUE);
}


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 */
	tmr_flag_clear(MOS_PWM_TIMER, TMR_OVF_FLAG);

	tmr_event_sw_trigger(MOS_PWM_TIMER, TMR_OVERFLOW_SWTRIG);
	while ( tmr_flag_get(MOS_PWM_TIMER, TMR_OVF_FLAG) == RESET ){}
	/* Clear Update Flag */
	tmr_flag_clear(MOS_PWM_TIMER, TMR_OVF_FLAG);

	tmr_output_enable(MOS_PWM_TIMER, TRUE);
}

void pwm_stop(void){
	tmr_output_enable(MOS_PWM_TIMER, FALSE);

	tmr_interrupt_enable(MOS_PWM_TIMER, TMR_OVF_INT, FALSE);
	/* wait for a new PWM period to flush last HF task */
	tmr_flag_clear(MOS_PWM_TIMER, TMR_OVF_FLAG);
	while ( tmr_flag_get(MOS_PWM_TIMER, TMR_OVF_FLAG) == RESET ){}
	/* Clear Update Flag */
	tmr_flag_clear(MOS_PWM_TIMER, TMR_OVF_FLAG);
}

void pwm_enable_output(bool enable) {
	if (enable) {
		tmr_output_enable(MOS_PWM_TIMER,TRUE);
	}else {
		tmr_output_enable(MOS_PWM_TIMER,FALSE);
	}
}

/*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);
	tmr_flag_clear(MOS_PWM_TIMER, TMR_OVF_FLAG);
	tmr_event_sw_trigger(MOS_PWM_TIMER, TMR_OVERFLOW_SWTRIG);
  	while ( tmr_flag_get(MOS_PWM_TIMER, TMR_OVF_FLAG) == RESET ){}
  	/* Main PWM Output Enable */
  	tmr_output_enable(MOS_PWM_TIMER,TRUE);
}

void pwm_update_sample(u32 samp1, u32 samp2, u8 sector) {
	if (samp1 < FOC_PWM_Half_Period) {
		update_adc_trigger(samp1);
		pwm_change_t3_mode(TMR_OUTPUT_CONTROL_PWM_MODE_B);
	}else {
		update_adc_trigger(samp2);
		pwm_change_t3_mode(TMR_OUTPUT_CONTROL_PWM_MODE_A);
	}
	adc_current_sample_config(sector);
}
