/**** Includes ****/
#include "../utils/utils.h"
#include "out_driver.h"

using namespace hw;

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

/**** Public function definitions ****/
hw::OutDriver::OutDriver(void)
{
	return;
}

hw::OutDriver::~OutDriver(void)
{
	return;
}

void hw::OutDriver::init(bsp::PwmOut* pwm_high, bsp::DigitalOut* dout_low)
{
	this->pwm_high = pwm_high;
	this->dout_low = dout_low;
	
	this->target_duty = 0;
	this->target_low = 0;
	this->disabled = 1;
}

void hw::OutDriver::write(uint16_t numerator)
{	
	this->target_duty = numerator;
	this->target_low = 1;
	
	// Check if enabled
	if(this->disabled)
	{
		return;
	};
	
	// Set low side
	if(this->dout_low->last_writen == 0)
	{
		this->dout_low->write(this->target_low);
	};
	
	// Set PWM
	this->pwm_high->write(this->target_duty);
}

void hw::OutDriver::write(uint8_t percent)
{
	// Convert to numerator/0xFFFF
	this->write(util::percent_to_16b(percent));
}

void hw::OutDriver::write_hiz(void)
{
	this->target_duty = 0;
	this->target_low = 0;
	
	// Check if enabled
	if(this->disabled)
	{
		return;
	};
	
	// Set PWM
	this->pwm_high->write((uint16_t)0);
	
	// Set low side
	this->dout_low->write(0);
}

void hw::OutDriver::enable(void)
{
	if(this->disabled==0) return;
	this->disabled = 0;
	
	if(this->target_low==0) this->write_hiz();
	else this->write(this->target_duty);
}

void hw::OutDriver::disable(void)
{
	if(this->disabled!=0) return;
	
	// Set PWM
	this->pwm_high->write((uint16_t)0);
	
	// Set low side
	this->dout_low->write(0);
	
	this->disabled = 1;
}

uint8_t hw::OutDriver::is_disabled(void)
{
	return this->disabled;
}

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