// ==========================================================================
// sensor_raing.c
// (c) 2022, Aurel Dumitru
//
// Description:
// Optical rain gauge sensor operations
// =========================================================================

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

// Defines
#define SENSOR_RAING_STATE_IDLE		0
#define SENSOR_RAING_STATE_INIT		1

// Data
const char Sensor_Raing_CmdPooling[] = "P\n";
const char Sensor_Raing_CmdReadAcc[] = "A\n";
char Sensor_Raing_RcvBuffer[24];
char Sensor_Raing_ReturnValues[24];

uint8_t	 Sensor_Raing_State;
uint32_t Sensor_Raing_TimeStamp;


// Public operations
void Sensor_Raing_Init(void)
{
	Sensor_Raing_State = SENSOR_RAING_STATE_INIT;
	Sensor_Raing_TimeStamp = HAL_GetTick();
}


void Sensor_Raing_InitServer(void)
{
	if (Sensor_Raing_State == SENSOR_RAING_STATE_INIT)
		if ((HAL_GetTick() - Sensor_Raing_TimeStamp) > 7000)
		{
			DevStatus[DEVSTATUS_SENSOR_RGAUGE_STATUS_IDX] = SENSOR_RAING_NOTPRESENT;
			HAL_UART_Abort(&huart10);
			HAL_UART_Transmit(&huart10, (uint8_t*)Sensor_Raing_CmdPooling, 2, 50);
			HAL_UART_Abort(&huart10);
			if (HAL_UART_Receive(&huart10, (uint8_t*)Sensor_Raing_RcvBuffer, 3, 100) == HAL_OK)
				if (Sensor_Raing_RcvBuffer[0] == 'p')
					DevStatus[DEVSTATUS_SENSOR_RGAUGE_STATUS_IDX] = SENSOR_RAING_PRESENT;
			Sensor_Raing_State = SENSOR_RAING_STATE_IDLE;
		}
}

void Sensor_Raing_StartMeasurement(void)
{
	Sensor_Raing_TimeStamp = HAL_GetTick();
}

uint32_t Sensor_Raing_GetMeasurementStatus(void)
{
	if ((HAL_GetTick() - Sensor_Raing_TimeStamp) > 7000)
	{
		char* Ptr = Sensor_Raing_RcvBuffer;
		HAL_UART_Transmit(&huart10, (uint8_t*)Sensor_Raing_CmdReadAcc, 2, 100);
		HAL_UART_Abort(&huart10);
		uint32_t TimeStamp = HAL_GetTick();

		Sensor_Raing_ReturnValues[0] = '\0';
		while ((HAL_GetTick() - TimeStamp) < 100)
		{
			if (HAL_UART_Receive(&huart10, (uint8_t*)Ptr, 1, 100) != HAL_OK)
				break;
			if (*Ptr == '\n')
				if ( (Sensor_Raing_RcvBuffer[0] == 'A') && (Sensor_Raing_RcvBuffer[1] == 'c') && (Sensor_Raing_RcvBuffer[2] == 'c'))
				{
					// Return the accumulated rain
					*(Ptr-2) = '\0'; *(Ptr-4) = 'm';
					Ptr = Sensor_Raing_RcvBuffer+4;
					while (*Ptr == ' ')	Ptr++;
					strcpy(Sensor_Raing_ReturnValues, "RainGauge: ");
					strcat(Sensor_Raing_ReturnValues, Ptr);
					break;
				}
			Ptr++;
		}
		return 1;
	}
	return 0;
}

char* Sensor_Raing_GetValues(void)
{
	if (Sensor_Raing_ReturnValues[0] != '\0')
		return Sensor_Raing_ReturnValues;
	return NULL;
}

int32_t Sensor_Raing_GetStatus(void)
{
	return DevStatus[DEVSTATUS_SENSOR_RGAUGE_STATUS_IDX];
}
