#include "bsp/dma.h"

u16 pwm_timer_dma_buf[2];
u16 adc_timer_dma_buf[3];
static void pwm_timer_dma_init(void);
static void adc_timer_dma_init(void);

void dma0_init(void){
	pwm_timer_dma_buf[0] = FOC_PWM_Half_Period;
	pwm_timer_dma_buf[1] = FOC_PWM_Half_Period;

	adc_timer_dma_buf[0] = FOC_PWM_Half_Period;
	adc_timer_dma_buf[1] = FOC_PWM_period - 1;
	adc_timer_dma_buf[0] = FOC_PWM_Half_Period;

	pwm_timer_dma_init();
	adc_timer_dma_init();
}

static void pwm_timer_dma_init(void){
    dma_parameter_struct dma_init_struct;

    /* enable DMA clock */
    rcu_periph_clock_enable(PWM_TIMER_CC3_DMA_CLK);

    /* initialize DMA channel */
    dma_deinit(PWM_TIMER_CC3_DMA_DEV,PWM_TIMER_CC3_DMA_CHAN);

    /* DMA channel5 initialize */
    dma_init_struct.periph_addr = (uint32_t)TIMER_CH0CV(pwm_timer);//changed by foc later
    dma_init_struct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dma_init_struct.memory_addr = (uint32_t)pwm_timer_dma_buf;
    dma_init_struct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dma_init_struct.periph_width = DMA_PERIPHERAL_WIDTH_16BIT;
    dma_init_struct.memory_width = DMA_MEMORY_WIDTH_16BIT;
    dma_init_struct.direction = DMA_MEMORY_TO_PERIPHERAL;
    dma_init_struct.number = 2;
    dma_init_struct.priority = DMA_PRIORITY_ULTRA_HIGH;
    dma_init(PWM_TIMER_CC3_DMA_DEV,PWM_TIMER_CC3_DMA_CHAN,&dma_init_struct);
    
    dma_circulation_enable(PWM_TIMER_CC3_DMA_DEV,PWM_TIMER_CC3_DMA_CHAN);

    /* enable DMA channel */
    dma_channel_enable(PWM_TIMER_CC3_DMA_DEV,PWM_TIMER_CC3_DMA_CHAN);
}

static void adc_timer_dma_init(void){
    dma_parameter_struct dma_init_struct;

    /* enable DMA clock */
    rcu_periph_clock_enable(ADC_TIMER_CC0_DMA_CLK);

    /* initialize DMA channel */
    dma_deinit(ADC_TIMER_CC0_DMA_DEV,ADC_TIMER_CC0_DMA_CHAN);

    /* DMA channel5 initialize */
    dma_init_struct.periph_addr = (uint32_t)TIMER_CH0CV(adc_timer);
    dma_init_struct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dma_init_struct.memory_addr = (uint32_t)adc_timer_dma_buf;
    dma_init_struct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dma_init_struct.periph_width = DMA_PERIPHERAL_WIDTH_16BIT;
    dma_init_struct.memory_width = DMA_MEMORY_WIDTH_16BIT;
    dma_init_struct.direction = DMA_MEMORY_TO_PERIPHERAL;
    dma_init_struct.number = 3;
    dma_init_struct.priority = DMA_PRIORITY_ULTRA_HIGH;
    dma_init(ADC_TIMER_CC0_DMA_DEV,ADC_TIMER_CC0_DMA_CHAN,&dma_init_struct);
    
    dma_circulation_enable(ADC_TIMER_CC0_DMA_DEV,ADC_TIMER_CC0_DMA_CHAN);

    /* enable DMA channel */
    dma_channel_enable(ADC_TIMER_CC0_DMA_DEV,ADC_TIMER_CC0_DMA_CHAN);
}

