#include "main.h"
#include "ltc2631.h"

void ltc2631_transmit(ltc2631_handle_t *hdac, uint8_t *data)
{
	HAL_I2C_Master_Transmit(hdac->hi2c, hdac->addr, data, 3, 1);
}

void ltc2631_init(ltc2631_handle_t *hdac, I2C_HandleTypeDef *hi2c, uint8_t addr, ltc2631_res_t res, float ref)
{
	hdac->hi2c = hi2c;
	hdac->addr = addr;
	hdac->resolution = res;
	hdac->ref_voltage_f = ref;
	hdac->ref_voltage_u = ref * 1000U;
}

void ltc2631_setOutputVoltage_f(ltc2631_handle_t *hdac, float volt)
{
	uint16_t value = 0;
	uint8_t data[3] = {0};

	if (volt > hdac->ref_voltage_f)
	{
		volt = hdac->ref_voltage_f;
	}

	if (volt < 0)
	{
		volt = 0;
	}

	value = (volt / hdac->ref_voltage_f + 0.005f) * (hdac->resolution - 1);

	value = value << (16 - hdac->resolution);
	data[0] = LTC_WRTIEUPDATE;
	data[1] = (value >> 8);
	data[2] = value;

	ltc2631_transmit(hdac, data);
}
void ltc2631_setOutputVoltage_u(ltc2631_handle_t *hdac, uint32_t volt_x1000)
{
	uint16_t value = 0;
	uint8_t data[3] = {0};

	if (volt_x1000 > hdac->ref_voltage_u)
	{
		volt_x1000 = hdac->ref_voltage_u;
	}

	if (volt_x1000 < 0)
	{
		volt_x1000 = 0;
	}

	value = (volt_x1000 * (hdac->resolution - 1)) / hdac->ref_voltage_u;

	value = value << (16 - hdac->resolution);
	data[0] = LTC_WRTIEUPDATE;
	data[1] = (value >> 8);
	data[2] = value;

	ltc2631_transmit(hdac, data);
}

void ltc2631_setOutputValue(ltc2631_handle_t *hdac, uint16_t value)
{
	uint8_t data[3] = {0};

	if (value >= (1 << hdac->resolution))
	{
		value = (1 << hdac->resolution) - 1;
	}

	value = value << (16 - hdac->resolution);
	data[0] = LTC_WRTIEUPDATE;
	data[1] = (value >> 8);
	data[2] = value;

	ltc2631_transmit(hdac, data);
}

void ltc2631_sleep(ltc2631_handle_t *hdac)
{
	uint8_t data[3] = {0};
	data[0] = LTC_SLEEP;

	ltc2631_transmit(hdac, data);
}