#pragma once

#include <zephyr/zephyr.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/sensor.h>


const struct device *dev_bme280;

/*
 * Get a device structure from a devicetree node with compatible
 * "bosch,bme280". (If there are multiple, just pick one.)
 */
void bme280_init(void)
{
	dev_bme280 = DEVICE_DT_GET_ANY(bosch_bme280);

	if (dev_bme280 == NULL) {
		/* No such node, or the node does not have status "okay". */
		printk("\nError: no device found.\n");
		return NULL;
	}

	if (!device_is_ready(dev_bme280)) {
		printk("\nError: Device \"%s\" is not ready; "
		       "check the driver initialization logs for errors.\n",
		       dev_bme280->name);
		return NULL;
	}

	printk("Found device \"%s\", getting sensor data\n", dev_bme280->name);
}


double bme280_measure_pressure(){
	struct sensor_value press;

	sensor_sample_fetch(dev_bme280);
	sensor_channel_get(dev_bme280, SENSOR_CHAN_PRESS, &press);

	//printk("BME280 .. press: %d.%06d\n", press.val1, press.val2);
	double pressure = ((double)press.val1 + (double)press.val2/1000000)*10;
	printk("BME280 .. press: %f hPa\n", pressure);
	return pressure;
}

double bme280_measure_temperature(){
	struct sensor_value temp;

	sensor_sample_fetch(dev_bme280);
	sensor_channel_get(dev_bme280, SENSOR_CHAN_AMBIENT_TEMP, &temp);

	//printk("BME280 .. temp: %d.%06d\n", temp.val1, temp.val2);
	double temperature = (double)temp.val1 + (double)temp.val2/1000000;
	printk("BME280 .. temp: %f °C\n", temperature);
	return temperature;
}

double bme280_measure_humidity(){
	struct sensor_value humidity;

	sensor_sample_fetch(dev_bme280);
	sensor_channel_get(dev_bme280, SENSOR_CHAN_HUMIDITY, &humidity);

	//printk("BME280 .. humidity: %d.%06d\n", humidity.val1, humidity.val2);
	double hum = (double)humidity.val1 + (double)humidity.val2/1000000;
	printk("BME280 .. humidity: %f %\n", hum);
	return hum;
}