#include "hdc1080.h"

int bsp_hdc1080_init(hdc_1080_t* dev, const char* name)
{
    if (dev)
    {
        uint8_t buff[128];
        dev->name = name;
        sprintf(buff, "%s/in_temp_raw", name);
        dev->fp_in_temp_raw = fopen(buff, "r");
        sprintf(buff, "%s/in_temp_scale", name);
        dev->fp_in_temp_scale = fopen(buff, "r");

        sprintf(buff, "%s/in_humidityrelative_raw", name);
        dev->fp_in_humidityrelative_raw = fopen(buff, "r");
        sprintf(buff, "%s/in_humidityrelative_scale", name);
        dev->fp_in_humidityrelative_scale = fopen(buff, "r");
        return 0;
    }
    return -1;
}

void bsp_hdc1080_exit(hdc_1080_t* dev)
{
    if (dev)
    {
        if (dev->fp_in_temp_raw) fclose(dev->fp_in_temp_raw);
        if (dev->fp_in_temp_scale) fclose(dev->fp_in_temp_scale);
        if (dev->fp_in_humidityrelative_raw) fclose(dev->fp_in_humidityrelative_raw);
        if (dev->fp_in_humidityrelative_scale) fclose(dev->fp_in_humidityrelative_scale);
    }
}

float bsp_hdc1080_getTemp(hdc_1080_t* dev)
{
    if (dev)
    {
        int value;
        float scale;
        fseek(dev->fp_in_temp_raw, 0, SEEK_SET); fscanf(dev->fp_in_temp_raw, "%d", &value);
        fseek(dev->fp_in_temp_scale, 0, SEEK_SET); fscanf(dev->fp_in_temp_scale, "%f", &scale);
        return (float)(value * scale / 1000.0f - 40);
    }
    return 0.0f;
}

float bsp_hdc1080_getHumidityrelative(hdc_1080_t* dev)
{
    if (dev)
    {
        int value;
        float scale;
        fseek(dev->fp_in_humidityrelative_raw, 0, SEEK_SET); fscanf(dev->fp_in_humidityrelative_raw, "%d", &value);
        fseek(dev->fp_in_humidityrelative_scale, 0, SEEK_SET); fscanf(dev->fp_in_humidityrelative_scale, "%f", &scale);
        return (float)(value * scale / 1000);
    }
    return 0.0f;
}