/*******************************************************************************
** Document: FW_i2c.c
** Copyright (c) 2004 R&D Center, Tailyn Communication Company, Ltd.  
** Created by: Chien Chung Lo
** Date: Nov. 25, 2004
** Description: Firmware interface API.
** Version: 0.1
*******************************************************************************/
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>

#include <FW_i2c/FW_i2c_api.h>

#include <umap_type.h>

//----------------------------------------------------------------------
UMAP_S32 FW_ReadI2c(void* buf, UMAP_U32 slave_addr, UMAP_U32 byte_addr, UMAP_U32 size, UMAP_U32 dev_type)
{
	UMAP_S32 i2c_file;
	UMAP_U32 dev_adr;
	UMAP_S32 result;
	
	dev_adr = ((slave_addr << 16) & 0x00ff0000) + (byte_addr & 0xffff) + ((dev_type << 24) & 0x0f000000);
	
	i2c_file = open(I2C_DEVICE_FILE_NAME, O_RDWR);
	if(i2c_file < 0)
	{
		result = i2c_file;
		return result; // open fail!!
	}
	
	result = lseek(i2c_file, dev_adr, SEEK_SET);
	if(result < 0)
	{
		close(i2c_file);
		return result; // lseek fail!!
	}
	
	result = read(i2c_file, buf, size);	
	if(result < 0)
	{
		close(i2c_file);
		return result; // read fail!!
	}
	
	result = close(i2c_file);
	
	return result; // succes
}

//----------------------------------------------------------------------
UMAP_S32 FW_WriteI2c(void* buf, UMAP_U32 slave_addr, UMAP_U32 byte_addr, UMAP_U32 size, UMAP_U32 dev_type)
{
	UMAP_S32 i2c_file;
	UMAP_U32 dev_adr;
	UMAP_S32 result;
	
	dev_adr = ((slave_addr << 16) & 0x00ff0000) + (byte_addr & 0xffff) + ((dev_type << 24) & 0x0f000000);
	
	i2c_file = open(I2C_DEVICE_FILE_NAME, O_RDWR);
	if(i2c_file < 0)
	{
		result = i2c_file;
		return result; // open fail!!
	}
	
	result = lseek(i2c_file, dev_adr, SEEK_SET);
	if(result < 0)
	{
		close(i2c_file);
		return result; // lseek fail!!
	}
	
	result = write(i2c_file, buf, size);
	if(result < 0)
	{
		close(i2c_file);
		return result; // read fail!!
	}
	
	result = close(i2c_file);
	
	return 0; // succes
}



