/**** Includes ****/
#include "../utils/utils.h"
#include "mcu/mcu_hal.h"
#include "halfbridge.h"

using namespace bsp;

/**** Private definitions ****/
/**** Private constants ****/
/**** Private variables ****/
/**** Private function declarations ****/

/**** Public function definitions ****/
bsp::Hafbridge::Hafbridge(uint8_t hs_pwm_ch, uint8_t ls_gpio_ch, uint8_t max_dc)
{
	this->pwm_ch  = hs_pwm_ch;	
	this->gpio_ch = ls_gpio_ch;
	
    if(max_dc>100) max_dc = 100;
	
	this->max_dc = util::percent_to_16b(max_dc);

	this->disable();
}

bsp::Hafbridge::~Hafbridge(void)
{
	this->last_duty = 0;
	this->disable();
}

void bsp::Hafbridge::write(uint16_t dividend)
{
	// Limit duty
	if(dividend > this->max_dc) dividend = this->max_dc;
	this->last_duty = dividend;
	
	if(this->enabled == 0) return;
	
	// Set PWM
	mcu::pwm_write(this->pwm_ch, dividend);
}

void bsp::Hafbridge::write(uint8_t percent)
{
	// Convert to dividend/0xFFFF
	this->write(util::percent_to_16b(percent));
}

void bsp::Hafbridge::enable(void)
{
	mcu::gpio_write(this->gpio_ch, mcu::LEVEL_HIGH);
	this->enabled = 1;
	this->write(this->last_duty);
}

void bsp::Hafbridge::disable(void)
{
	mcu::pwm_write(this->pwm_ch, 0);
	mcu::gpio_write(this->gpio_ch, mcu::LEVEL_LOW);
	this->enabled = 0;
}

uint8_t bsp::Hafbridge::get_set_duty(void)
{
	return this->last_duty;
}

uint8_t bsp::Hafbridge::is_enabled(void)
{
	return this->enabled;
}

/**** Private function definitions ****/
