/*
 * sht4x.c
 *
 *  Created on: Jun 8, 2021
 *      Author: user
 */

#include "scd4x.h"
#include "main.h" /* for uart_disable_interrupts() */

int8_t scd4x_send_cmd(scd4x_cmd_t cmd)
{
	uint8_t buffer[32];
	int result;

	// start measurement
	buffer[0] = cmd >> 8;
	buffer[1] = cmd & 0x00ff;
	result = i2c_transmit(SCD4X_I2C_ADDRESS<<1, buffer, 2);
	if (result != I2C_OK) {
		return SCD4X_ERROR;
	}

	return SCD4X_OK;
}

int8_t scd4x_read_data(uint8_t *buffer, int len)
{
	return SCD4X_OK;
}

int8_t scd4x_start_periodic_measurement( void )
{
	return scd4x_send_cmd(SCD4X_START_PERIODIC_MEASUREMENT);
}

int8_t scd4x_stop_periodic_measurement( void )
{
	return scd4x_send_cmd(SCD4X_STOP_PERIODIC_MEASUREMENT);
}

int8_t scd4x_perform_factory_reset( void )
{
	return scd4x_send_cmd(SCD4X_PERFORM_FACTORY_RESET);
}

int8_t scd4x_read_measurement(uint16_t * co2, int16_t *temperature, uint16_t *relative_humidity)
{
	uint8_t buffer[32];
	int8_t result;

	// start measurement
	// TODO: Check for data ready
	/*
	buffer[0] = GET_DATA_READY_STATUS >> 8;
	buffer[1] =  GET_DATA_READY_STATUS & 0x00ff;
	result = i2c_transmit(SCD4X_I2C_ADDRESS<<1, buffer, 2);
	if (result != I2C_OK) {
		return SCD4X_ERROR;
	}
	LL_mDelay(100); // 10 ms should be enough
	// read out
	result = i2c_receive(SCD4X_I2C_ADDRESS<<1, buffer, 6);
	if (result != I2C_OK) {
		return SCD4X_ERROR;
	}*/


	// start measurement
//	tx_buffer[0] = SCD4X_READ_MEASUREMENT >> 8;
//	tx_buffer[1] = SCD4X_READ_MEASUREMENT & 0x00ff;

	/*uart_disable_interrupts();*/
//	result = i2c_transmit(SCD4X_I2C_ADDRESS<<1, buffer, 2);

	// TODO: Proc to vraci NACK? Vyresit.
	/*if (result != I2C_OK) {
		return SCD4X_ERROR;
	}*/

	/*uart_enable_interrupts();*/
//	HAL_Delay(10);

//	uart_disable_interrupts();
	// read out
//	result = i2c_receive(SCD4X_I2C_ADDRESS<<1, buffer, 9);
//	if (result != I2C_OK)
//	{
//		return SCD4X_ERROR;
//	}
	result = i2c_transmit_receive(SCD4X_I2C_ADDRESS<<1, SCD4X_READ_MEASUREMENT, I2C_MEMADD_SIZE_16BIT, buffer, 9);
	if (result != I2C_OK)
	{
		return SCD4X_ERROR;
	}
//	uart_enable_interrupts();

	// TODO checksum
	// Convert to T and RH; taken directly from pseudocode in SHT4x datasheet, page 3
	uint32_t co2_ticks = (buffer[0] << 8) + buffer[1];
	uint32_t t_ticks = (buffer[3] << 8) + buffer[4];
	uint32_t rh_ticks = (buffer[6] << 8) + buffer[7];
	int t_degC = -450 + 10 * 175 * t_ticks / 65535;
	int rh_pRH = 100 * rh_ticks / 65535;
	if (rh_pRH > 100) {
			rh_pRH = 100;
	}
	if (rh_pRH < 0) {
		rh_pRH = 0;
	}
	*co2 = co2_ticks;
	*temperature = t_degC;
	*relative_humidity = rh_pRH;

	return SCD4X_OK;
}
