#include "sensor.h"

/**/
int8_t Humidity, Temperature;
uint16_t Pressure;

/**/
static struct bme280_dev SensorDev;
static struct bme280_data SensorData;

/**/
void sensor_Init(void) {
  int8_t rsltSensor;

  Flag.BME280 = 0;
  SensorDev.dev_id = (BME280_I2C_ADDR_PRIM << 1);
  SensorDev.intf = BME280_I2C_INTF;
  SensorDev.read = user_i2c_read;
  SensorDev.write = user_i2c_write;
  SensorDev.delay_ms = tdelay_ms;
  rsltSensor = bme280_init(&SensorDev);

  if (rsltSensor == BME280_OK) {
    Flag.BME280 = 1;

    /* BME280 Recommended mode of operation: Indoor navigation */
    SensorDev.settings.osr_h = BME280_OVERSAMPLING_1X;
    SensorDev.settings.osr_p = BME280_OVERSAMPLING_16X;
    SensorDev.settings.osr_t = BME280_OVERSAMPLING_2X;
    SensorDev.settings.filter = BME280_FILTER_COEFF_16;
    rsltSensor = bme280_set_sensor_settings((BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL | BME280_OSR_HUM_SEL | BME280_FILTER_SEL), &SensorDev);
    RTOS_SetTask(sensor_StartMeasure, 103, 1000);
    RTOS_SetTask(sensor_GetData, 603, 1000);
  }
}

void sensor_StartMeasure(void) {
  bme280_set_sensor_mode(BME280_FORCED_MODE, &SensorDev);
}

void sensor_GetData(void) {
  bme280_get_sensor_data(BME280_ALL, &SensorData, &SensorDev);

  int32_t tmp;

  tmp = SensorData.humidity + 512;
  Humidity = (int8_t)(tmp / 1024);

  tmp = SensorData.temperature + 50;
  Temperature = (int8_t)(tmp / 100);

  /* in 32-bit arithmetics pressure in Pa */
  tmp = SensorData.pressure * 1000;
  tmp += 66661;
  tmp /= 133322;
  /* pressure in mmHg */
  Pressure = (uint16_t)tmp;
}