#include "i2c_driver.h"

#include <cstdio>
#include <ostream>
#include <iostream>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>


#define PORT_I2C "/dev/i2c-1"

// some curious things https://www.john.geek.nz/2012/12/update-reading-data-from-a-bosch-bmp085-with-a-raspberry-pi/


I2C_Driver::I2C_Driver(const uint8_t& channel, const uint8_t& mode)
{ 
	char filename[20];
	snprintf(filename, 19, "/dev/i2c-%d", channel);
	
	deviceDescriptor = open(filename, O_RDWR);
	if (deviceDescriptor < 0) {
		std::cout << "unable to open : "<< deviceDescriptor << " ! quiting" << std::endl;
		exit(1);
	}
}

uint8_t I2C_Driver::writeByte(const uint8_t& address, const uint8_t& data)   // retuns 0 when a sucsessful transation ocures 
{
	if (ioctl(deviceDescriptor, I2C_SLAVE, address) < 0) 
	{
		std::cout << "Unable to reach device : "<< address << " ! quiting" << std::endl;
		exit(1);
	}
	
	send_buffer[0] = data; 

	if ((write(deviceDescriptor, send_buffer, 1)) != 1)
	{	
		std::cout << "Unable to write quiting" << std::endl;
		exit(0); 
	}
	return 0; 
}

uint8_t I2C_Driver::readByte(const uint8_t& address, const uint8_t& reg)
{
	if (ioctl(deviceDescriptor, I2C_SLAVE, address) < 0) 
	{
		std::cout << "Unable to reach device : "<< address << " ! quiting" << std::endl;
		exit(1);
	}
	
	writeByte(address,reg); //Initiate a write to indicate the desired register to read

	if (read(deviceDescriptor, recieve_buffer, 1) != 1)  // An then initare a read request of 1 byte
	{
		std::cout << "Unable to read quiting" << std::endl;
		exit(1); 
	} 
	return recieve_buffer[0] ;
}


uint8_t I2C_Driver::writeWord(const uint8_t& address, const uint8_t& reg, const uint16_t& data) 	// retuns 0 when a sucsessful transation ocures	
{

	if (ioctl(deviceDescriptor, I2C_SLAVE, address) < 0) 
	{
		std::cout << "Unable to reach device : "<< address << " ! quiting" << std::endl;
		exit(1);
	}
	
	send_buffer[0] = reg; 
	send_buffer[1] = data;

	if ((write(deviceDescriptor, send_buffer, 2)) != 2)
	{	
		std::cout << "Unable to write quiting" << std::endl;
		exit(0); 
	}
	return 0; 
}

uint16_t I2C_Driver::readWord(const uint8_t& address, const uint8_t& reg)
{
	uint16_t result = 0 ;
	if (ioctl(deviceDescriptor, I2C_SLAVE, address) < 0) 
	{
		std::cout << "Unable to reach device : "<< address << " ! quiting" << std::endl;
		exit(1);
	}

	writeByte(address,reg); //Initiate a write to indicate the desired register to read
	
	if (read(deviceDescriptor, recieve_buffer, 2) != 2)  // An then initare a read request of 2 bytes
	{
		std::cout << "Unable to read quiting" << std::endl;
		exit(1); 
	} 
	result = (recieve_buffer[0] << 8) + recieve_buffer[1] ;
	return result ; 
}
