/**************************************************************************//**
 * @file     pwm_common.c
 * @version  V1.0
 * $Date:    19/11/06 17:10 $
 * @brief    Common source file for PWM test.
 *
 * @note
 * Copyright (C) 2019 Panchip Technology Corp. All rights reserved.
 *
 ******************************************************************************/
#include <ctype.h>
#include "pan271x.h"
#include "pwm_common.h"

volatile uint16_t speed_div = 0;

T_PWM_TEST_RESULT (*const PWM_TestCase[])(void) = 
{
    PWM_OperationModesTestCase,
    PWM_PolarityControlTestCase,
};

void PWM_TestFunctionEnter(uint16_t TcIdx)
{
    T_PWM_TEST_RESULT r = PWM_TST_OK;

    if (TcIdx >= sizeof(PWM_TestCase) / sizeof(void*))
    {
        SYS_TEST("Error, cannot find Testcase %d!", TcIdx);
        return;
    }

    r = (PWM_TestCase[TcIdx])();
    if (r != PWM_TST_OK)
    {
        SYS_TEST("PWM Test Fail, Fail case: %d, Error Code: %d\n", TcIdx, r);
    }
    else
    {
        SYS_TEST("PWM Test OK, Success case: %d\n", TcIdx);
    }
}

void PWM_IrqProcess(PWM_T *pwm)
{
    // Period Interrupt
    if(PWM_GetPeriodIntFlag(pwm, TGT_PWM_CH))
    {
        FLAG_PIF_HIGH;
        PWM_ClearPeriodIntFlag(pwm, TGT_PWM_CH);
        SYS_delay_10nop(1);
        FLAG_PIF_LOW;
    }
    // Compare Down Interrupt
    if(PWM_GetCMPDIntFlag(pwm, TGT_PWM_CH))
    {
        FLAG_CMPDIF_HIGH;
        PWM_ClearCMPDIntFlag(pwm, TGT_PWM_CH);
        SYS_delay_10nop(1);
        FLAG_CMPDIF_LOW;
    }
}

void PWM_IRQHandler(void)
{
    PWM_IrqProcess(PWM);
}



void PWM_TestModuleInit(void)
{
    // Enable Clock
    CLK_APB1PeriphClockCmd(CLK_APB1Periph_PWM0_CH01, ENABLE);
    CLK_APB1PeriphClockCmd(CLK_APB1Periph_PWM0_CH23, ENABLE);
    CLK_APB1PeriphClockCmd(CLK_APB1Periph_PWM0_CH45, ENABLE);

    // Config Pinmux
    SYS_SET_MFP(P1, 2, PWM_CH4);
    SYS_SET_MFP(P1, 3, PWM_CH3);
    SYS_SET_MFP(P1, 4, PWM_CH2);
    SYS_SET_MFP(P1, 7, PWM_CH1);

    GPIO_SetMode(P2, BIT0, GPIO_MODE_OUTPUT);   //To indicate PIF signal
    GPIO_SetMode(P2, BIT1, GPIO_MODE_OUTPUT);   //To indicate CMPDIF signal
}

T_PWM_TEST_RESULT PWM_RegisterDefaultValueCheckCase0(void)
{
    uint8_t j,different = 0;
    while(j<16){
        if(((__IO uint32_t *)(&TGT_PWM->PWM_CLKPSC_L))[j] != 0){
            SYS_TEST("addr offset:%x,respect:0,current:%08x \r\n",j*4,((__IO uint32_t *)(&TGT_PWM->PWM_CLKPSC_L))[j]);
            different++;
        }
        j++;
    }
    if(TGT_PWM->PWM_DTCTL    != 0) different++;
    if(TGT_PWM->PWM_CLKPSC_H != 0) different++;  

    if(!different){
       SYS_TEST("pwm default value check ok \r\n"); 
    }

    return PWM_TST_OK;
}

