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

using namespace bsp;

/**** Private definitions ****/
/**** Private constants ****/
/**** Private variables ****/
/**** Private function declarations ****/
/**** Public function definitions ****/
bsp::Board::Board(void)
{
	return;
}

bsp::Board::~Board(void)
{
	return;
}

void bsp::Board::init(boardCfg_t* cfg)
{
	// Calculate settings
	
	// Controller setup
	mcu::startupCfg_t mcu_cfg;
	
	mcu_cfg.adc_clk = mcu::ADC_DIV64; // 8MHz/64=125kHz
	mcu_cfg.pwm_clk = mcu::TIM_DIV1;  // 8MHz/1 = 8MHz
	mcu_cfg.pwm_top = 4000/(uint16_t)cfg->pwm_f_khz;
	mcu_cfg.od_common_is_pwm = cfg->od_common_is_pwm;
	
	mcu::startup(&mcu_cfg);
	
	// Analog inputs
	this->out_voltage.init(mcu::ADC_VOUT);
	this->out_voltage.mul = 20;
	this->out_voltage.div = 1;
	this->out_voltage.offset = 0;
	
	this->out_current.init(mcu::ADC_IOUT);
	this->out_current.mul = 215;
	this->out_current.div = 22;
	this->out_current.offset = 0;
	
	this->battery_voltage.init(mcu::ADC_VBAT);
	this->battery_voltage.mul = 20;
	this->battery_voltage.div = 1;
	this->battery_voltage.offset = 0;
	
	this->battery_current.init(mcu::ADC_IBAT);
	this->battery_current.mul = 235;
	this->battery_current.div = 6;
	this->battery_current.offset = 0;
	
	this->ain1.init(mcu::ADC_AIN1);
	this->ain2.init(mcu::ADC_AIN2);
	
	// Digital inputs
	this->din1.init(mcu::GPIO_DIN1, 0);
	this->din2.init(mcu::GPIO_DIN2, 0);
	this->din3.init(mcu::GPIO_DIN3, 0);
	this->din4.init(mcu::GPIO_DIN4, 0);
	this->hvdin1.init(mcu::GPIO_HVDIN1, 1);
	this->hvdin2.init(mcu::GPIO_HVDIN2, 1);
	this->hvdin3.init(mcu::GPIO_HVDIN3, 1);
	
	this->hvdin3_pull.init(mcu::GPIO_HVDIN3_PULL, 0);
	this->freq_pull.init(mcu::GPIO_FREQ_PULL, 0);
	
	// Open-drain outputs
	this->od1.init(mcu::GPIO_OD1, 1);
	this->od2.init(mcu::GPIO_OD2, 1);
	this->od3.init(mcu::GPIO_OD3, 1);
	this->od4.init(mcu::GPIO_OD4, 1);
	this->od5.init(mcu::GPIO_OD5, 1);
	this->od6.init(mcu::GPIO_OD6, 1);
	this->od_pwm.init(mcu::PWM_OD, 100);
	
	// PWM driver output
	this->out_pwm.init(mcu::PWM_OUT, 95);
	this->out_low.init(mcu::GPIO_OUT_LOW, 0);
}

void bsp::Board::read(void)
{
	// Update all analog inputs
	this->out_voltage.read();
	this->out_current.read();
	this->battery_voltage.read();
	this->battery_current.read();
	this->ain1.read();
	this->ain2.read();
	
	// Update all digital inputs
	this->din1.read();
	this->din2.read();
	this->din3.read();
	this->din4.read();
	this->hvdin1.read();
	this->hvdin2.read();
	this->hvdin3.read();
}

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

