#include "bme680.h"
#include "bme680b.h"
#include "esp_log.h"
#include "i2cbrn.h"

bme680_config_t BME680_DEV_CFG = I2C_BME680_CONFIG_DEFAULT;
bme680_handle_t BME680_DEV_HANDLE;

void bme680_print_registers(bme680_handle_t handle)
{
    /* configuration registers */
    bme680_control_measurement_register_t ctrl_meas_reg;
    bme680_control_humidity_register_t ctrl_humi_reg;
    bme680_config_register_t config_reg;
    bme680_control_gas0_register_t ctrl_gas0_reg;
    bme680_control_gas1_register_t ctrl_gas1_reg;

    /* attempt to read control humidity register */
    bme680_get_control_humidity_register(handle, &ctrl_humi_reg);

    /* attempt to read control measurement register */
    bme680_get_control_measurement_register(handle, &ctrl_meas_reg);

    /* attempt to read configuration register */
    bme680_get_configuration_register(handle, &config_reg);

    /* attempt to read control gas 0 register */
    bme680_get_control_gas0_register(handle, &ctrl_gas0_reg);

    /* attempt to read control gas 1 register */
    bme680_get_control_gas1_register(handle, &ctrl_gas1_reg);

    ESP_LOGI(TAG_BME, "Variant Id          (0x%02x): %s", handle->variant_id, uint8_to_binary(handle->variant_id));
    ESP_LOGI(TAG_BME, "Configuration       (0x%02x): %s", config_reg.reg, uint8_to_binary(config_reg.reg));
    ESP_LOGI(TAG_BME, "Control Measurement (0x%02x): %s", ctrl_meas_reg.reg, uint8_to_binary(ctrl_meas_reg.reg));
    ESP_LOGI(TAG_BME, "Control Humidity    (0x%02x): %s", ctrl_humi_reg.reg, uint8_to_binary(ctrl_humi_reg.reg));
    ESP_LOGI(TAG_BME, "Control Gas 0       (0x%02x): %s", ctrl_gas0_reg.reg, uint8_to_binary(ctrl_gas0_reg.reg));
    ESP_LOGI(TAG_BME, "Control Gas 1       (0x%02x): %s", ctrl_gas1_reg.reg, uint8_to_binary(ctrl_gas1_reg.reg));
}

esp_err_t bme680b_init() {
    // init device
    esp_err_t ret = bme680_init(i2c0_bus_hdl, &BME680_DEV_CFG, &BME680_DEV_HANDLE);
    if (BME680_DEV_HANDLE == NULL)
    {
        ESP_LOGE(TAG_BME, "bme680 handle init failed");
    } else {
        bme680_print_registers(BME680_DEV_HANDLE);
    }
    return ret;

}