/**
 * @file	   flowmeter.c
 *
 * @copyright  Nehemis SARL reserves all rights even in the event of industrial
 *             property rights. We reserve all rights of disposal such as
 *             copying and passing on to third parties.
 *
 * @brief
 *
 */

/******************************************************************************
 * Include Header Files
 ******************************************************************************/
#include "nms_types.h"
#include "flowmeter.h"
#include "analogMeasurement.h"

/******************************************************************************
 * Type  declarations
 ******************************************************************************/
#define FLOWMETER_GAIN		3.12f
/******************************************************************************
 * Macro Constant Declarations
 ******************************************************************************/

/******************************************************************************
 * Private function Declarations
 ******************************************************************************/
static void FlowmeterReadVoltage(FlowmeterMain_st * flowmeter_pst);
FlowmeterMain_st *flowmeter_gpst;
/******************************************************************************
 * Extern Function Definitions
 ******************************************************************************/
void FlowmeterInit(FlowmeterMain_st *flowmeter_pst)
{
	if (flowmeter_pst == NULL)
	{
		/* ERROR */
	}

	flowmeter_pst->mKu_f32 = 5.0f; // Default value
}


void FlowmeterGetFlow(FlowmeterMain_st *flowmeter_pst)
{
	if (flowmeter_pst == NULL)
	{
		/* ERROR */
	}
	FlowmeterReadVoltage(flowmeter_pst);
	flowmeter_pst->rawQ_f32 = flowmeter_pst->mKu_f32 * flowmeter_pst->voltage_f32;
}


float32 FlowmeterGetKu(FlowmeterMain_st *flowmeter_pst)
{
	if (flowmeter_pst == NULL)
	{
		return 0.0f;
	}

	return flowmeter_pst->mKu_f32;
}


void FlowmeterSetKu(FlowmeterMain_st *flowmeter_pst, float32 ku_f32)
{
	if (flowmeter_pst != NULL)
	{
		flowmeter_pst->mKu_f32 = ku_f32;
	}
}


/******************************************************************************
 * Private function Definitions
 ******************************************************************************/
/**
 * @brief     Function to read ADC voltage data which is directly coming from the sensor.
 *
 * @param	  flowmeter_pst : Pointer to main strucutre of the module.
 *
 * @return	  ADC output voltage based on sensor reading.
 *
 */
static void FlowmeterReadVoltage(FlowmeterMain_st *flowmeter_pst)
{
	/* Convert ADC value to voltage (assuming 12-bit resolution and 3.3V reference) */
	uint32 adcVal_u32 = 0uL;
	AnalogMeasurementReadData(flowmeter_pst->channel_u32, &adcVal_u32);

	flowmeter_pst->voltage_f32 = (float32)adcVal_u32 * (ANALOG_MEAS_ADC_REF_VOLTAGE / ANALOG_MEAS_ADC_RESOLUTION) * FLOWMETER_GAIN;
}
