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

using namespace board;

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

/**** Public function definitions ****/
board::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) this->max_dc = 100;
	else this->max_dc = max_dc;
	this->disable();
}

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

void board::Hafbridge::write(uint8_t duty)
{
	// Limit duty
	if(duty > this->max_dc) duty = this->max_dc;
	this->last_duty = duty;
	
	if(this->enabled == 0) return;
	
	// Convert percent to 16b duty cycle
	uint16_t dc = util::percent_to_16b(duty);
	// Set PWM
	mcu::pwm_write(this->pwm_ch, dc);
}

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

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

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

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

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