#pragma once

#include <zephyr/drivers/i2c.h>

#define TRIGGER_TEMP_MEASURE_HOLD  		0xE3
#define TRIGGER_HUM_MEASURE_HOLD  		0xE5
#define TRIGGER_TEMP_MEASURE_NOHOLD  	0xF3    // Mereni teploty - snimac nedrzi master po dobu mereni
#define TRIGGER_HUM_MEASURE_NOHOLD  	0xF5    // Mereni vlhkosti - snimac nedrzi master po dobu mereni
#define READ_USER_REG                   0xE7
#define WRITE_USER_REG                  0xE6
#define SOFT_RESET                      0xFE

#define I2C0_HTU21D DT_NODELABEL(htu21d)

static const struct i2c_dt_spec dev_htu21d = I2C_DT_SPEC_GET(I2C0_HTU21D);

uint8_t htu21d_regs[2] ={0xE3,0xE5};


double htu21d_measure_temperature(){
	uint8_t temp_reading[3]= {0};

    int ret = i2c_write_read_dt(&dev_htu21d,&htu21d_regs[0],1,&temp_reading,3);

	uint16_t raw_value = ((uint16_t) temp_reading[0] << 8) | (uint16_t) temp_reading[1];
	double temperature = ((raw_value & 0xFFFC) * 175.72 / 65536.0) - 46.85;

	if(ret != 0){
		printk("Failed to read I2C device address %x at Reg. %x \n", dev_htu21d.addr,htu21d_regs[0]);
	}else{
		printk("Temperature: %.2f °C\n", temperature);
	}

	return temperature;
}

double htu21d_measure_humidity(){
	uint8_t temp_reading[3]= {0};

	int ret = i2c_write_read_dt(&dev_htu21d,&htu21d_regs[1],1,&temp_reading,3);

	uint16_t raw_value = ((uint16_t) temp_reading[0] << 8) | (uint16_t) temp_reading[1];
	double humidity = ((raw_value & 0xFFFC) * 125.0 / 65536.0) - 6.0;

	if(ret != 0){
		printk("Failed to read I2C device address %x at Reg. %x \n", dev_htu21d.addr,htu21d_regs[1]);
	}else{
		printk("Humidity: %.2f % \n", humidity);
	}

	return humidity;

}
