#include <stdio.h>
#include "mini58series.h"
#include "SHTC3.h"
#include "i2c_software_gpio.h"





static s16 SHTC3_CalcTemperature(u16 rawValue);
static u16 SHTC3_CalcHumidity(u16 rawValue);





u8 _SHTC3_Addr = 0 ;
void SHTC3_Init(u8 i2cAddress)
{
	_SHTC3_Addr = i2cAddress;
	I2C_SW_Open(300000);
	CLK_SysTickDelay(5000);      //delay 5ms
}

//-----------------------------------------------------------------------------
static u32 SHTC3_WriteCommand(etCommands command)
{
	u32 error = 0; // error code
	u8 cmd_buf[2] = {0};
	cmd_buf[0] = command >> 8;
	cmd_buf[1] = command & 0xFF;

	I2C_SW_Send(_SHTC3_Addr, cmd_buf, 2);

	return error;
}

//-----------------------------------------------------------------------------
static u32 SHTC3_ReadBytes(u8* data, u8 length)
{
  u32 error = 0;    // error code

  I2C_SW_Get(_SHTC3_Addr, data, length);

  return error;
}


//u32 SHTC3_ReadID(u16* id)
//{
//	u32 error = 0; // error code
//	u8 data[2] = {0};

//	// write "read serial number" command
//	error |= SHTC3_WriteCommand(READ_ID);
//	// if no error, start read access
//	// if no error, read first serial number word
//	error |= SHTC3_ReadBytes(data, 2);

//	// if no error, calc serial number as 32-bit integer
//	*id = (data[0] << 8) | data[1];
//	
//	return error;
//}

u32 SHTC3_GetTempAndHumi(s16* temperature, u16* humidity, bool lowPowerEnable)
{
	u32 error = 0;
	u8 data[6] = {0,0,0,0,0,0};
	u16 rawValueTemp; // temperature raw value from sensor
	u16 rawValueHumi; // humidity raw value from sensor

	// measure, read temperature first, clock streching enabled
	if (lowPowerEnable){
		error |= SHTC3_WriteCommand(MEAS_T_RH_CLOCKSTR_LPM);
	}else{
		error |= SHTC3_WriteCommand(MEAS_T_RH_CLOCKSTR);
	}
	
	error |= SHTC3_ReadBytes(data, 6);

	rawValueTemp = (data[0] << 8) | data[1];
	rawValueHumi = (data[3] << 8) | data[4];

	*temperature = SHTC3_CalcTemperature(rawValueTemp);
	*humidity 	 = SHTC3_CalcHumidity(rawValueHumi);

	return error;

}

u32 SHTC3_GetTemp(s16* temperature)
{
	u32 error = 0;
	u8 data[6] = {0,0,0,0,0,0};
	u16 rawValueTemp; // temperature raw value from sensor

	// measure, read temperature first, clock streching enabled

	error |= SHTC3_WriteCommand(MEAS_T_RH_CLOCKSTR);
	
	
	error |= SHTC3_ReadBytes(data, 2);

	rawValueTemp = (data[0] << 8) | data[1];

	*temperature = SHTC3_CalcTemperature(rawValueTemp);

	return error;

}
static s16 SHTC3_CalcTemperature(u16 rawValue)
{
    u32 value = 0;
    value = ((int32_t)1750 * (int32_t)rawValue / 65536) - 450;
    return (int16_t)(value);
}

//-----------------------------------------------------------------------------
static u16 SHTC3_CalcHumidity(u16 rawValue)
{
    return (u16)((u32)rawValue * 1000 / 65536);
}

//------------------------------------------------------------------------------
u32 SHTC3_SoftReset(void)
{
	u32 error = 0;

	error |= SHTC3_WriteCommand(SOFT_RESET);

	return error;
}


