/*
 * measurand.c
 *
 *  Created on: 07-10-2014
 *      Author: Krzysztof Jakubczyk
 */

#include <math.h>

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

#include "measurand.h"
#include "analog_in.h"

volatile struct measurands_table measurands;

int measurand_initlog(void *arguments, void *logic)
{
	struct measurand_args *args = (struct measurand_args *)arguments;
	struct measurand_logic *log = (struct measurand_logic *)logic;
	u32 *an_params_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;

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

	log->an_params=(struct analog_in_params *)*an_params_ptr;

	measurands.value[measurands.count]=&log->calculated;
	measurands.value_pri[measurands.count]=&log->calculated_pri;
	measurands.value_sec[measurands.count]=&log->calculated_sec;
	measurands.id[measurands.count]=args->params.id;
	measurands.count++;

	return 0;
}

void measurand_100hz(void *arguments, void *logic)
{
	struct measurand_args *args = (struct measurand_args *)arguments;
	struct measurand_logic *log = (struct measurand_logic *)logic;
	float m;

	if(*log->esk_ptr == 32768.0f)
		m=0;
	else if(args->params.bits & MEASURAND_SQRT)
		m=sqrtf(*log->esk_ptr);
	else
		m=*log->esk_ptr;

	log->calculated = m;

//	if(args->params.bits & MEASURAND_LIMITED_OUTPUT)
	{
		if(log->calculated<args->params.minval)
		{
			log->calculated = 0;
			m = 0;
		}
	}

	if(args->params.bits & MEASURAND_NO_PRI_SEC)
	{
		log->calculated_pri=log->calculated;
		log->calculated_sec=log->calculated;
	}
	else
	{
		log->calculated_pri=m * log->an_params->znam_pierw;
		log->calculated_sec=m * log->an_params->znam_wtor;
	}
}
