/// © MiroZ 2024
#include <esp_log.h>

#include "Bme68x.h"


static const char *TAG = "Bme68x";


#define MEAS_DUR 	140
#define NEW_GAS_MEAS (BME68X_GASM_VALID_MSK | BME68X_HEAT_STAB_MSK | BME68X_NEW_DATA_MSK)

Bme68x::Bme68x(TwoWire & bus) : m_bus(bus)
{
	m_sensor = new MyLibs::Bme68x();
}

bool Bme68x::init()
{
	m_sensor->begin(0x77, m_bus);
	
	m_sensor->setTPH();

    uint16_t tempProf[10] = { 320, 100, 100, 100, 200, 200, 200, 320, 320, 320 };
    /* Multiplier to the shared heater duration */
    uint16_t mulProf[10] = { 5, 2, 10, 30, 5, 5, 5, 5, 5, 5 };
    /* Shared heating duration in milliseconds */
    uint16_t sharedHeatrDur = MEAS_DUR - (m_sensor->getMeasDur(BME68X_PARALLEL_MODE) / 1000);

	// ESP_LOGI(TAG, "sharedHeatrDur:%d", sharedHeatrDur);

    m_sensor->setHeaterProf(tempProf, mulProf, sharedHeatrDur, 10);
    m_sensor->setOpMode(BME68X_PARALLEL_MODE);

	m_operational = m_sensor->checkStatus() == BME68X_OK;

	return m_operational;
}


void Bme68x::read()
{
	MyLibs::bme68xData bdata;
	uint8_t left;

	if(m_sensor->fetchData() > 0)
	{
		do
		{
			left = m_sensor->getData(bdata);

			if (bdata.status == NEW_GAS_MEAS)
			{
				ESP_LOGI(TAG, "temp: %f", bdata.temperature);
				ESP_LOGI(TAG, " hum: %f", bdata.humidity);
				ESP_LOGI(TAG, "gres: %f", bdata.gas_resistance);
				ESP_LOGI(TAG, "  ix: %d", bdata.gas_index);
			}
		} while(left > 0);
	}
}