#include <unistd.h> //Send and recive I2C commands
#include <sys/ioctl.h> //setup i2c devices
#include <linux/i2c-dev.h> //Definitions and structures
#include <i2c/smbus.h> //smbus commands
#include <stdio.h> //To print error

#include "htu21d.h"

//Temperature
int getTemp(int fd, double *temp){
	getReset(fd);
	char buffer[3];
	__s32 res = i2c_smbus_read_i2c_block_data(fd,HTU21D_TEMP, 3, buffer);
	if(res<0){
		perror("ERROR-1: Failed to read Temperature");
		return -1;
	}
	*temp = -46.85+175.72*(buffer[0]*256+buffer[1])/65536.0;
	return 0;
}

//Humidity
int getHum(int fd, double *hum){
	getReset(fd);
	char buffer[3];	
	__s32 res = i2c_smbus_read_i2c_block_data(fd,HTU21D_HUM, 3, buffer);
	if(res<0){
		perror("ERROR -3: Failed to read Humidity");
		return -1;
	}
	*hum = -6+125*(buffer[0]*256+buffer[1])/65536.0;
	return 0;
}


//reset function:
int getReset(int fd){
	if(0>ioctl(fd, I2C_SLAVE, HTU21D_ADDR)){
		perror("ERROR -2: Failed in reset");
		return -2;
	}
	i2c_smbus_write_byte(fd, HTU21D_RESET);
	return 0;

}
