
#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_i2c_master_write(int fd, uint8_t address, uint8_t *pBuf, uint16_t size)
{
	int ret = 0;
	i2c_arg_t i2c_arg;
	
	i2c_arg.DevAddress = address;
	i2c_arg.WriteLen = size;
	memcpy(i2c_arg.Buf, pBuf, size);
	ret = ioctl(fd, I2C_MASTER_TRANSFER, &i2c_arg);
	// if(ret == -1)
	// {
	// 	printf("Write i2c failed! addr %#02x\n", address);
	// }

	return ret;
}

int stm32_i2c_master_read(int fd, uint8_t address, uint8_t *pBuf, uint16_t size)
{
	int ret;
	i2c_arg_t i2c_arg;

	i2c_arg.DevAddress = address;
	i2c_arg.ReadLen = size;
	ret = ioctl(fd, I2C_MASTER_RECEIVE, &i2c_arg);
	// if(ret == -1)
	// {
	// 	//printf("Read i2c failed!\n");
	// 	;
	// }
	memcpy(pBuf, i2c_arg.Buf, size);

	return ret;
}


int stm32_i2c_set_addr(int fd, uint8_t OwnAddress)
{
	int ret;
	i2c_arg_t i2c_arg;

	i2c_arg.OwnAddress1 = OwnAddress;
	ret = ioctl(fd, SET_I2C_ADDR, &i2c_arg);
	if(ret == -1)
	{
		printf("Set i2c address failed!\n");
	}

	return 0;
}

//return receive size
int stm32_i2c_slave_recv(int fd, uint8_t *pBuf)
{
	int ret = 0;
	i2c_arg_t i2c_arg;
	ret = ioctl(fd, I2C_SLAVE_RECEIVE_IT, &i2c_arg);
	if(ret == -1)
	{
		printf("I2c slave receive failed!\n");
		return -1;
	}
	memcpy(pBuf, i2c_arg.Buf, i2c_arg.ReadLen);

	// int i;
	// printf("i2c recv: ");
	// for(i=0;i<i2c_arg.Size;i++)
	// 	printf("%#x ", pBuf[i]);
	// printf("\n");
	return i2c_arg.ReadLen;
}

int stm32_i2c_master_write_read(int fd, uint8_t address, uint8_t *pWrBuf, uint8_t writeLen, uint8_t *pRdBuf, uint8_t readLen)
{
	int ret = 0;
	i2c_arg_t i2c_arg;
	i2c_arg.DevAddress = address;
	i2c_arg.WriteLen = writeLen;
	i2c_arg.ReadLen = readLen;
	memcpy(i2c_arg.Buf, pWrBuf, writeLen);

	ret = ioctl(fd, I2C_MASTER_TRANSFER_RECEIVE, &i2c_arg);
	if(ret == -1)
	{
		printf("i2c master write read failed!\n");
		return -1;
	}
	
	memcpy(pRdBuf, i2c_arg.Buf, readLen);
	return ret;
}
