/*
 * i2c.c
 *
 *  Created on: Jun 8, 2021
 *      Author: user
 */

#include "i2c.h"


I2C_HandleTypeDef *i2c_context;
uint16_t timeout;

int8_t i2c_init(I2C_HandleTypeDef *context, uint16_t i2c_timeout)
{
	if (context == NULL) {
		return I2C_ERROR;
	}
	i2c_context = context;
	timeout = i2c_timeout;
	return I2C_OK;
}

int8_t i2c_transmit(uint8_t address, uint8_t *buffer, uint16_t len)
{
	if (HAL_I2C_Master_Transmit(i2c_context, address, buffer, len, timeout) == HAL_OK)
	{
		return I2C_OK;
	} else {
		return I2C_ERROR;
	}
}

int8_t i2c_receive(uint8_t address, uint8_t *buffer, uint16_t len)
{
	if (HAL_I2C_Master_Receive(i2c_context, address, buffer, len, timeout) == HAL_OK)
	{
		return I2C_OK;
	} else
	{
		return I2C_ERROR;
	}
}

int8_t i2c_transmit_receive(uint8_t address, uint16_t tx_buffer, uint16_t tx_len, uint8_t *rx_buffer, uint16_t rx_len)
{
	if(HAL_I2C_Mem_Read(i2c_context, address, tx_buffer, tx_len, rx_buffer, rx_len, timeout) == HAL_OK)
	{
		return I2C_OK;
	} else
	{
		return I2C_ERROR;
	}
}
