#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};


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

void pwm_3phase_sides(bool hon, bool lon) {
	if (hon && lon) {
		return;
	}
	TIM_DeInit(MOS_PWM_TIMER);
	rcu_apb2_periph_clock_enable(PWM_TIM_CLK);
    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_apb2_periph_clock_enable(PWM_U_P_RCU);
    rcu_apb2_periph_clock_enable(PWM_V_P_RCU);
	rcu_apb2_periph_clock_enable(PWM_W_P_RCU);
    rcu_apb2_periph_clock_enable(PWM_U_N_RCU);
    rcu_apb2_periph_clock_enable(PWM_V_N_RCU);
	rcu_apb2_periph_clock_enable(PWM_W_N_RCU);	
    rcu_apb2_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_apb2_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);
	}
}

static void _init_pwm_timer(bool enable_brk) {
	TIM_TimeBaseInitType TIM1_TimeBaseStructure;
	OCInitType TIM1_OCInitStructure;
	TIM_BDTRInitType TIM1_BDTRInitStructure;
	TIM_Module *TIMx = MOS_PWM_TIMER;
	u32 half_period = FOC_PWM_Half_Period;

	rcu_apb2_periph_clock_enable(PWM_TIM_CLK);

	TIM_DeInit(TIMx);

	TIM_InitTimBaseStruct(&TIM1_TimeBaseStructure);
	TIM1_TimeBaseStructure.Prescaler = 0;
	TIM1_TimeBaseStructure.CntMode = TIM_CNT_MODE_CENTER_ALIGN1;// 01: \,irq flag only counter down
	TIM1_TimeBaseStructure.Period = half_period;
	TIM1_TimeBaseStructure.ClkDiv = TIM_CLK_DIV1;
	TIM1_TimeBaseStructure.RepetCnt = 1;
	TIM_InitTimeBase(TIMx, &TIM1_TimeBaseStructure);
	//Channel 1, 2,3 in PWM mode
	TIM_InitOcStruct(&TIM1_OCInitStructure);
	TIM1_OCInitStructure.OcMode = TIM_OCMODE_PWM1;//Pos logic(when '<' is active,when '>' is inactive)
	TIM1_OCInitStructure.OutputState = TIM_OUTPUT_STATE_ENABLE; 
	TIM1_OCInitStructure.OutputNState = TIM_OUTPUT_NSTATE_ENABLE;                  
	TIM1_OCInitStructure.Pulse = (half_period>>1);
	TIM1_OCInitStructure.OcPolarity = TIM_OC_POLARITY_HIGH;
	TIM1_OCInitStructure.OcNPolarity = TIM_OCN_POLARITY_HIGH; 
	TIM1_OCInitStructure.OcIdleState = TIM_OC_IDLE_STATE_RESET;
	TIM1_OCInitStructure.OcNIdleState = TIM_OC_IDLE_STATE_RESET;          
	TIM_InitOc1(TIMx, &TIM1_OCInitStructure); 
	TIM_InitOc2(TIMx, &TIM1_OCInitStructure);
	TIM_InitOc3(TIMx, &TIM1_OCInitStructure);
	//Channel 4 Configuration in OC 
	TIM1_OCInitStructure.OcMode = TIM_OCMODE_PWM2;
	TIM1_OCInitStructure.OutputState = TIM_OUTPUT_STATE_ENABLE;
	TIM1_OCInitStructure.OutputNState = TIM_OUTPUT_NSTATE_DISABLE;
	TIM1_OCInitStructure.Pulse = half_period - 1;//3400;
	TIM_InitOc4(TIMx, &TIM1_OCInitStructure);
	
	//Enables the TIM1 Preload on CC1,CC2,CC3,CC4 Register
	TIM_ConfigOc1Preload(TIMx, TIM_OC_PRE_LOAD_ENABLE);
	TIM_ConfigOc2Preload(TIMx, TIM_OC_PRE_LOAD_ENABLE);
	TIM_ConfigOc3Preload(TIMx, TIM_OC_PRE_LOAD_ENABLE);

	//Automatic Output enable, Break, dead time and lock configuration
	TIM1_BDTRInitStructure.OssrState = TIM_OSSR_STATE_DISABLE;
	TIM1_BDTRInitStructure.OssiState = TIM_OSSI_STATE_DISABLE;
	TIM1_BDTRInitStructure.LockLevel = TIM_LOCK_LEVEL_OFF; 
	TIM1_BDTRInitStructure.DeadTime = _dead_time(NS_2_TCLK(PWM_DEAD_TIME_NS));
	TIM1_BDTRInitStructure.Break = enable_brk?TIM_BREAK_IN_ENABLE:TIM_BREAK_IN_DISABLE;
	TIM1_BDTRInitStructure.BreakPolarity = TIM_BREAK_POLARITY_LOW;
	TIM1_BDTRInitStructure.AutomaticOutput = TIM_AUTO_OUTPUT_DISABLE;
    TIM1_BDTRInitStructure.IomBreakEn = true;
	TIM_ConfigBkdt(TIMx, &TIM1_BDTRInitStructure);
	
	pwm_enable_channel();

	TIM_ClearFlag(TIMx,TIM_FLAG_UPDATE);
	TIM_ConfigInt(TIMx, TIM_INT_UPDATE, DISABLE);
	nvic_irq_enable(PWM_UP_IRQ, TIMER_UP_IRQ_PRIORITY, 0);
	TIM_ClearFlag(TIMx,TIM_FLAG_BREAK);
	TIM_ConfigInt(TIMx, TIM_INT_BREAK, ENABLE);
	nvic_irq_enable(PWM_BRK_IRQ, EBREAK_IRQ_PRIORITY, 0);
	//TIM1 counter enable
	TIM_Enable(TIMx, ENABLE);
}

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 */
	TIM_ClearFlag(MOS_PWM_TIMER, TIM_FLAG_UPDATE);

	TIM_GenerateEvent(MOS_PWM_TIMER, TIM_EVT_SRC_UPDATE);
	while ( TIM_GetFlagStatus(MOS_PWM_TIMER, TIM_FLAG_UPDATE) == RESET ){}
	/* Clear Update Flag */
	TIM_ClearFlag(MOS_PWM_TIMER, TIM_FLAG_UPDATE);

	TIM_EnableCtrlPwmOutputs(MOS_PWM_TIMER,ENABLE);
}

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

	TIM_ConfigInt(MOS_PWM_TIMER, TIM_INT_UPDATE, DISABLE);
	/* wait for a new PWM period to flush last HF task */
	TIM_ClearFlag(MOS_PWM_TIMER, TIM_FLAG_UPDATE);
	while ( TIM_GetFlagStatus(MOS_PWM_TIMER, TIM_FLAG_UPDATE) == RESET ){}
	/* Clear Update Flag */
	TIM_ClearFlag(MOS_PWM_TIMER, TIM_FLAG_UPDATE);
}

void pwm_enable_output(bool enable) {
	if (enable) {
		TIM_EnableCtrlPwmOutputs(MOS_PWM_TIMER,ENABLE);
	}else {
		TIM_EnableCtrlPwmOutputs(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);
	TIM_ClearFlag(MOS_PWM_TIMER,TIM_FLAG_UPDATE);
	TIM_GenerateEvent(MOS_PWM_TIMER, TIM_EVT_SRC_UPDATE);
  	while (TIM_GetFlagStatus(MOS_PWM_TIMER, TIM_FLAG_UPDATE) == RESET );
  	/* Main PWM Output Enable */
  	TIM_EnableCtrlPwmOutputs(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(TIM_OCMODE_PWM2);
	}else {
		TIMER_CH3CV(MOS_PWM_TIMER) = samp2;
		pwm_change_t3_mode(TIM_OCMODE_PWM1);
	}
	adc_current_sample_config(sector);
}
