
#include "driver.h"
#include <linux/types.h>
#include <stdio.h>
#include <string.h>
#include "com_gpio.h"
#include "hal_interface_api.h"
#include "linux/fcntl.h"

/*
bus: 		1,2,3
address: 	8bit
*/
int stm32_gpio_i2c_master_write(int fd, uint8_t address, uint8_t *pBuf, uint16_t size)
{
	int ret = 0;
	gpio_i2c_t i2c_arg;
	
	i2c_arg.DevAddress = address;
	i2c_arg.WriteLen = size;
	memcpy(i2c_arg.Buf, pBuf, size);
	ret = ioctl(fd, GPIO_I2C_MASTER_TRANSFER, &i2c_arg);
	if(ret != 0)
	{
		printf("Write i2c failed! ADDR: %#x\n", address);
	}

	return ret;
}

int stm32_gpio_i2c_master_read(int fd, uint8_t address, uint8_t *pBuf, uint16_t size)
{
	int ret;
	gpio_i2c_t i2c_arg;

	i2c_arg.DevAddress = address;
	i2c_arg.ReadLen = size;
	ret = ioctl(fd, GPIO_I2C_MASTER_RECEIVE, &i2c_arg);
	if(ret != 0)
	{
		printf("Read i2c failed! ADDR: %#x\n", address);
	}
	memcpy(pBuf, i2c_arg.Buf, size);

	return 0;
}


int stm32_gpio_i2c_master_write_read(int fd, uint8_t address, uint8_t *pWrBuf, uint8_t wrsize, uint8_t *pRdBuf, uint16_t rdsize)
{
	int ret;
	gpio_i2c_t i2c_arg;

	i2c_arg.DevAddress = address;
	i2c_arg.WriteLen = wrsize;
	i2c_arg.ReadLen = rdsize;
	memcpy(i2c_arg.Buf, pWrBuf, wrsize);
	ret = ioctl(fd, GPIO_I2C_MASTER_TRANSFER_RECV, &i2c_arg);
	if(ret != 0)
	{
		printf("Read i2c failed! ADDR: %#x\n", address);
		return -1;
	}
	memcpy(pRdBuf, i2c_arg.Buf, rdsize);

	return 0;
}
