#include <cstdio>

#include "main.h"

#include "FreeRTOS.h"
#include "task.h"

#include "bme_task.h"
#include "bme280.h"
#include "i2c.h"

static constexpr uint16_t delay_ms = 5000U;
static constexpr uint16_t timeout_ms = 1000U;

enum class DeviceOnBus { PRESENT, NOT_PRESENT };

void THPX_Init(void);
DeviceOnBus THPX_GetDeviceID(void);
void THPX_GetDeviceStatus(void);

void bmeTaskStart(void* argument)
{
	UNUSED(argument);

	vTaskDelay(pdMS_TO_TICKS(1000U));
	THPX_Init();

	while (1)
	{
		vTaskDelay(pdMS_TO_TICKS(delay_ms));

		if (THPX_GetDeviceID() == DeviceOnBus::PRESENT)
		{
			THPX_GetDeviceStatus();
		}
	}
}

//------------------------------------------------------------------------------

void THPX_GetDeviceStatus(void)
{
	uint8_t out = BME280_REG_status;
	HAL_I2C_Master_Transmit(&hi2c1, (0x77 << 1U), &out, 1, timeout_ms);
	uint8_t in;
	HAL_I2C_Master_Receive(&hi2c1, (0x77 << 1U), &in, 1, timeout_ms);
	//printf("BME280 status: 0x%02X\n", in);
}

//------------------------------------------------------------------------------

DeviceOnBus THPX_GetDeviceID(void)
{
	uint8_t out = BME280_REG_id;
	//TWI_MasterWriteRead(&twiMaster, SLAVE_ADDRESS, &sendBuffer[0], 1, 1);
	HAL_I2C_Master_Transmit(&hi2c1, (0x77 << 1U), &out, 1, timeout_ms);
	uint8_t in;
	HAL_I2C_Master_Receive(&hi2c1, (0x77 << 1U), &in, 1, timeout_ms);
	if (in == 0x60) return DeviceOnBus::PRESENT;
	return DeviceOnBus::NOT_PRESENT;
}

//------------------------------------------------------------------------------

void THPX_Init(void)
{
	// Everything was initialized in MX_I2C1_Init, generated by CubeMX
}
