/*
 * e_avg.c
 *
 *  Created on: 12-05-2016
 *      Author: Krzysztof Jakubczyk
 */

#include "tdefs.h"
#include "misc.h"
#include "config.h"

#include "e_avg.h"
#include "analog_in.h"
#include <math.h>

int e_avg_initlog(void *arguments, void *logic)
{
	struct e_avg_args *args = (struct e_avg_args *)arguments;
	struct e_avg_logic *log = (struct e_avg_logic *)logic;
	struct analog_in_params *an_params;
	u32 *an_params_ptr;
	u32 *buf_ptr;

	an_params_ptr = (u32 *)(log_manager.nets_data + (args->io.param_an_ptr_in >> 3));
	if((u8*)an_params_ptr > (log_manager.nets_data+sizeof(log_manager.nets_data) - sizeof(void *)))
		return -1;

	if(!*an_params_ptr) // param in not connected or wrong elements order (analog_in should be run before)
		return -1;

	an_params=(struct analog_in_params *)*an_params_ptr;

	buf_ptr = (u32 *)(log_manager.nets_data + (args->io.buf_u16_ptr_in >> 3));
	if((u8*)buf_ptr > (log_manager.nets_data+sizeof(log_manager.nets_data) - sizeof(void *)))
		return -1;

	if(!*buf_ptr) // param in not connected or wrong elements order (analog_in should be run before)
		return -1;

	log->buf_ptr=(u16*)*buf_ptr;

	log->avg_ptr = (float *)(log_manager.nets_data + (args->io.avg_float_out >> 3));
	if((u8 *)log->avg_ptr > (log_manager.nets_data+sizeof(log_manager.nets_data) - sizeof(float)))
		return -1;

	log->savg_ptr = (float *)(log_manager.nets_data + (args->io.savg_float_out >> 3));
	if((u8 *)log->savg_ptr > (log_manager.nets_data+sizeof(log_manager.nets_data) - sizeof(float)))
		return -1;

	log->multiplier = an_params->multiplier; /* (float)1.1107 */;
	log->multiplier /= (SAMPLES_PER_MS*MAIN_FREQ_PERIOD_MS);
	log->offset = 32767 + an_params->offset;

	return 0;
}

void e_avg(void *arguments, void *logic)
{
	struct e_avg_args *args = (struct e_avg_args *)arguments;
	struct e_avg_logic *log = (struct e_avg_logic *)logic;
    short i,i1,i2;
	float skut;
	float pr;

	i2 = bus_an_cur_sample_num;
	skut = 0;

	for (i=0;i<(SAMPLES_PER_MS*MAIN_FREQ_PERIOD_MS);i++/*=2*/)
	{
		i1 = i2 - i;
	    if(i1<0)
	    	i1 += (SAMPLES_PER_MS*MAIN_FREQ_PERIOD_MS*2);
		pr = (float)log->buf_ptr[i1] - log->offset;
		skut+=fabs(pr);
	}

	skut*=log->multiplier;

	if(args->io.avg_float_out)
		*log->avg_ptr=skut;

	if(args->io.savg_float_out)
		*log->savg_ptr=skut*skut;
}
