#include "epwm.h"


int bsp_epwm_init(epwm_t* dev, const char* name)
{
    if (dev)
    {
        uint8_t buff[128];
        dev->ratioA = 0;
        dev->ratioB = 0;
        dev->name = name;
        sprintf(buff, "%s/pwm0", dev->name);
        if (access(buff, F_OK) != 0)
        {
            sprintf(buff, "echo \"0\"> %s/export", name); system(buff);
        }
        sprintf(buff, "%s/pwm1", dev->name);
        if (access(buff, F_OK) != 0)
        {
            sprintf(buff, "echo \"1\"> %s/export", name); system(buff);
        }
        return 0;
    }
    return -1;
}

void bsp_epwm_exit(epwm_t* dev)
{
    if (dev)
    {
        uint8_t buff[128];
        sprintf(buff, "echo \"0\"> %s/unexport", dev->name); system(buff);        
        sprintf(buff, "echo \"1\"> %s/unexport", dev->name); system(buff); 
    }
}

void bsp_epwm_configA(epwm_t* dev, int Hz, int ratio)
{
    if (dev)
    {
        int len;
        uint8_t buff[128];
        dev->ratioA = ratio;
        Hz = 1000;
        uint64_t period_ns = 1000000000UL/Hz;
        uint64_t duty_cycle_ns = 10000000UL*ratio/Hz;

        sprintf(buff, "echo \"0\" > %s/pwm0/enable", dev->name); system(buff);
        sprintf(buff, "echo \"%lld\" > %s/pwm0/period", period_ns, dev->name); system(buff);
        sprintf(buff, "echo \"%lld\" > %s/pwm0/duty_cycle", duty_cycle_ns, dev->name); system(buff);
        sprintf(buff, "echo \"1\" > %s/pwm0/enable", dev->name); system(buff);
    }
}

void bsp_epwm_configB(epwm_t* dev, int Hz, int ratio)
{
    if (dev)
    {
        int len;
        uint8_t buff[128];
        Hz = 1000;
        dev->ratioB = ratio;
        uint64_t period_ns = 1000000000UL/Hz;
        uint64_t duty_cycle_ns = 10000000UL*ratio/Hz;

        sprintf(buff, "echo \"0\" > %s/pwm1/enable", dev->name); system(buff);
        sprintf(buff, "echo \"%lld\" > %s/pwm1/period", period_ns, dev->name); system(buff);
        sprintf(buff, "echo \"%lld\" > %s/pwm1/duty_cycle", duty_cycle_ns, dev->name); system(buff);
        sprintf(buff, "echo \"1\" > %s/pwm1/enable", dev->name); system(buff);
    }
}