// ==========================================================================
// sensor_analog.c
// (c) 2022, Aurel Dumitru
//
// Description:
// Analog sensor operations - Leaf Wetness supported
// =========================================================================

#include <stdlib.h>
#include <string.h>
#include "sensor_analog.h"
#include "main.h"
#include "devstatus.h"

// Defines
#define SENSOR_ANALOG_STATE_IDLE		0
#define SENSOR_ANALOG_STATE_INIT		1

// Data
char Sensor_Analog_ReturnValues[24];

uint8_t	 Sensor_Analog_State;
uint32_t Sensor_Analog_TimeStamp;


// Public operations
void Sensor_Analog_Init(void)
{
	Sensor_Analog_State = SENSOR_ANALOG_STATE_INIT;
	Sensor_Analog_TimeStamp = HAL_GetTick();
}

void Sensor_Analog_InitServer(void)
{
	ADC_ChannelConfTypeDef AdcChConfig;

	if (Sensor_Analog_State == SENSOR_ANALOG_STATE_INIT)
		if ((HAL_GetTick() - Sensor_Analog_TimeStamp) > 30)
		{
			DevStatus[DEVSTATUS_SENSOR_ANALOG_STATUS_IDX] = SENSOR_ANALOG_NOTPRESENT;

			AdcChConfig.Channel = ADC_CHANNEL_4;
			AdcChConfig.Rank = ADC_REGULAR_RANK_1;
			AdcChConfig.SamplingTime = ADC_SAMPLETIME_64CYCLES_5;
			AdcChConfig.SingleDiff = ADC_SINGLE_ENDED;
			AdcChConfig.OffsetNumber = ADC_OFFSET_NONE;
			AdcChConfig.Offset = 0;
			AdcChConfig.OffsetRightShift = DISABLE;
			AdcChConfig.OffsetSignedSaturation = DISABLE;
			HAL_ADC_ConfigChannel(&hadc2, &AdcChConfig);
			HAL_ADC_Start(&hadc2);
			while ((ADC2->ISR & ADC_FLAG_EOC) == 0);	// wait end of conversion
			uint32_t Value = HAL_ADC_GetValue(&hadc2) & 0xFFFF;
			if (Value > 0x800)
				DevStatus[DEVSTATUS_SENSOR_ANALOG_STATUS_IDX] = SENSOR_ANALOG_PRESENT;
			Sensor_Analog_State = SENSOR_ANALOG_STATE_IDLE;
		}
}

void Sensor_Analog_StartMeasurement(void)
{
	HAL_GPIO_WritePin(EN_3V3S_GPIO_Port, EN_3V3S_Pin, GPIO_PIN_SET);	// Enable the 3V3S power supply
	Sensor_Analog_TimeStamp = HAL_GetTick();
}

uint32_t Sensor_Analog_GetMeasurementStatus(void)
{
	if ((HAL_GetTick() - Sensor_Analog_TimeStamp) > 30)
	{
		ADC_ChannelConfTypeDef AdcChConfig;
		AdcChConfig.Channel = ADC_CHANNEL_4;
		AdcChConfig.Rank = ADC_REGULAR_RANK_1;
		AdcChConfig.SamplingTime = ADC_SAMPLETIME_64CYCLES_5;
		AdcChConfig.SingleDiff = ADC_SINGLE_ENDED;
		AdcChConfig.OffsetNumber = ADC_OFFSET_NONE;
		AdcChConfig.Offset = 0;
		AdcChConfig.OffsetRightShift = DISABLE;
		AdcChConfig.OffsetSignedSaturation = DISABLE;
		HAL_ADC_ConfigChannel(&hadc2, &AdcChConfig);
		HAL_ADC_Start(&hadc2);
		while ((ADC2->ISR & ADC_FLAG_EOC) == 0);	// wait end of conversion
		uint32_t Value = (HAL_ADC_GetValue(&hadc2) & 0xFFFF) >> 4;
		Value = (Value*435)/285;
		strcpy(Sensor_Analog_ReturnValues, "LeafWetness: ");
		itoa(Value, &Sensor_Analog_ReturnValues[13], 10);
		return 1;
	}
	return 0;
}

char* Sensor_Analog_GetValues(void)
{
	return Sensor_Analog_ReturnValues;
}

int32_t Sensor_Analog_GetStatus(void)
{
	return DevStatus[DEVSTATUS_SENSOR_ANALOG_STATUS_IDX];
}
