#include "driver.h"
#include <linux/types.h>
#include <stdio.h>
#include <string.h>
#include "com_gpio.h"
#include "hal_interface_api.h"
#include "linux/fcntl.h"
#include "time.h"
#include <unistd.h>

#define DEV_NAME	"/dev/adc1"
/*
channel: 1,2,3,4,5,6,7
*/
int stm32_adc_get_value(uint8_t channel, uint16_t *value)
{
	int fd;
	int ret;
	adc_arg_t adc_arg;
	uint16_t max_val, min_val;
	uint32_t sum = 0;
	int i;
	
	if((channel < 1) || (channel > 7))
	{
		printf("Invalid adc channel %d.\n", channel);
		return -1;
	}
	
	fd = open(DEV_NAME, O_RDWR);
	if(fd == -1)
	{
		printf("Open %s failed!\n", DEV_NAME);
	}
	adc_arg.channel = channel;
	ret = ioctl(fd, ADC_GET_RESULT, &adc_arg);
	if(ret == -1)
	{
		printf("Adc get result failed!\n");
	}
	close(fd);

	//get the max value
	max_val = adc_arg.value[0];
	for(i=1;i<10;i++)
	{
		if(max_val < adc_arg.value[i])
		{
			max_val = adc_arg.value[i];
		}
	}

	//get the min value
	min_val = adc_arg.value[0];
	for(i=1;i<10;i++)
	{
		if(min_val > adc_arg.value[i])
		{
			min_val = adc_arg.value[i];
		}
	}

	//get sum
	sum = 0;
	for(i=0;i<10;i++)
	{
		sum += adc_arg.value[i];
	}

	//remove max_value and min_value
	sum = sum - max_val - min_val;

	*value = sum/8;

	// printf("value: ");
	// for(i=0;i<10;i++)
	// 	printf("%d ", adc_arg.value[i]);
	// printf("\nmax_value: %d, min_value: %d, sum: %d, average: %d\n", max_val, min_val, sum, *value);
	return ret;
}