#ifndef _PWM_H__
#define _PWM_H__
#include "bsp/bsp.h"
#include "os/os_types.h"

#define TIMxCCER_MASK_CH012        ((uint16_t)  (TIMER_CHCTL2_CH0EN|TIMER_CHCTL2_CH0NEN|\
                                                 TIMER_CHCTL2_CH1EN|TIMER_CHCTL2_CH1NEN|\
                                                 TIMER_CHCTL2_CH2EN|TIMER_CHCTL2_CH2NEN))

#define pwm_enable_channel() {TIMER_CHCTL2(MOS_PWM_TIMER) |= TIMxCCER_MASK_CH012;}
#define pwm_disable_channel() {TIMER_CHCTL2(MOS_PWM_TIMER) &= ~TIMxCCER_MASK_CH012;}


#define ch0_update_duty(duty) 	TIMER_CH0CV(MOS_PWM_TIMER) = (uint32_t)duty
#define ch1_update_duty(duty) 	TIMER_CH1CV(MOS_PWM_TIMER) = (uint32_t)duty
#define ch2_update_duty(duty) 	TIMER_CH2CV(MOS_PWM_TIMER) = (uint32_t)duty
#define update_adc_trigger(time) TIMER_CH3CV(MOS_PWM_TIMER) = (uint32_t)time

#ifdef CONFIG_PWM_UV_SWAP
#define pwm_update_duty(dutyA, dutyB, dutyC) \
	do {\
		ch0_update_duty(dutyC);\
		ch1_update_duty(dutyB);\
		ch2_update_duty(dutyA);\
	}while(0)

#else
#define pwm_update_duty(dutyA, dutyB, dutyC) \
	do {\
		ch0_update_duty(dutyA);\
		ch1_update_duty(dutyB);\
		ch2_update_duty(dutyC);\
	}while(0)

#endif

#define pwm_update_2smaples(samp1, sampl2) \
	do { \
		TIMER_CH3CV(MOS_PWM_TIMER) = (uint32_t)samp1; \
	}while(0)



#define enable_pwm_timer_dma() TIMER_DMAINTEN(MOS_PWM_TIMER) |= (uint32_t) TIMER_DMA_CH3D
#define disable_pwm_timer_dma() TIMER_DMAINTEN(MOS_PWM_TIMER) &= ~((uint32_t) TIMER_DMA_CH3D)


#define pwm_clear_updata() \
	timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP);

#define pwm_wait_and_clear_updata() \
	do { \
		while ( timer_flag_get(MOS_PWM_TIMER, TIMER_FLAG_UP) == RESET ); \
		timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP); \
	}while(0)

#define pwm_change_t3_mode(m) \
	do { \
		if (((TIMER_CHCTL1(MOS_PWM_TIMER) >> 12) & 0x7) != m) { \
			TIMER_CHCTL1(MOS_PWM_TIMER) &= (~(uint32_t)TIMER_CHCTL1_CH3COMCTL); \
        	TIMER_CHCTL1(MOS_PWM_TIMER) |= (uint32_t)((uint32_t)(m) << 8U); \
		} \
	}while(0)

#define pwm_brake_enable(n) \
	do { \
		if (n) { \
			nvic_irq_enable(PWM_BRK_IRQ, EBREAK_IRQ_PRIORITY, 0); \
		}else { \
			nvic_irq_disable(PWM_BRK_IRQ); \
		} \
	}while(0)

#define pwm_up_enable(n) \
	do { \
		if (n) { \
			timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP); \
			timer_interrupt_enable(MOS_PWM_TIMER, TIMER_INT_UP); \
		}else { \
			timer_flag_clear(MOS_PWM_TIMER, TIMER_FLAG_UP); \
			timer_interrupt_disable(MOS_PWM_TIMER, TIMER_INT_UP); \
		} \
	}while(0)

#define get_deadtime() (TIMER_CCHP(MOS_PWM_TIMER) & 0xFF)

#ifdef CONFIG_SENSORLESS_TOW_SAMPLES
#define PWM_Direction_Down() ((TIMER_CTL0(MOS_PWM_TIMER) & TIMER_CTL0_DIR) == 0)
#else
#define PWM_Direction_Down() true
#endif
void pwm_3phase_init(void);
void pwm_3phase_sides(bool hon, bool lon);
void pwm_start(void);
void pwm_stop(void);
void pwm_turn_on_low_side(void);
void pwm_enable_output(bool enable);
void pwm_update_sample(u32 samp1, u32 samp2, u8 sector);

#endif  /*_PWM_H__*/

