/*
 * virt_in_drv.c
 *
 *  Created on: 15-10-2014
 *      Author: KJ
 */


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

#include "virt_in_drv.h"
#include "virt_in.h"
#include <ti/sysbios/knl/Semaphore.h>

u32 virt_in_states = 0;
u32 virt_in_mask = 0;

u32 virt_in2_states = 0;
u32 virt_in2_mask = 0;

int virt_in_drv_initlog(void *arguments, void *logic)
{
	struct virt_in_drv_logic *log = (struct virt_in_drv_logic *)logic;
	struct virt_in_args *v_args;
	struct virt_in_logic *v_log;

	int i;

	log->virt_in_count=0;

	//Semaphore_post(spi_semaphore);
	//virt_in_states = 0;

	virt_in_mask = 0;
	virt_in2_mask = 0;
	for(i=0;i<MAX_LOG_ELEMENTS;i++)
	{
		if(log_manager.log_element[i].flags & FUNCTION_IS_VIRT_IN)
		{
			if((u8 *)&log->element_num[log->virt_in_count]>(u8 *)(log_manager.buf+sizeof(log_manager.buf)-sizeof(u16)))
				return -1;

			v_args = (struct virt_in_args *)log_manager.log_element[i].fun_args_ptr;
			v_log = (struct virt_in_logic *)log_manager.log_element[i].fun_log_ptr;

			if(v_args->params.in_num<32)
			{
				if(virt_in_states & (1<<v_args->params.in_num))
					*v_log->out_ptr|=(1<<v_log->out_bit_no);

				virt_in_mask|=(1<<v_args->params.in_num);
			}
			else
			{
				if(virt_in2_states & (1<<(v_args->params.in_num-32)))
					*v_log->out_ptr|=(1<<v_log->out_bit_no);

				virt_in2_mask|=(1<<(v_args->params.in_num-32));
			}
			log->element_num[log->virt_in_count]=i;
			log->virt_in_count++;
		}
	}


	return 0;
}

void virt_in_drv_100hz(void *arguments, void *logic)
{
	struct virt_in_drv_logic *log = (struct virt_in_drv_logic *)logic;
	struct virt_in_args *v_args;
	struct virt_in_logic *v_log;
	int i;

	for(i=0;i<log->virt_in_count;i++)
	{
		v_args = (struct virt_in_args *)log_manager.log_element[log->element_num[i]].fun_args_ptr;
		v_log = (struct virt_in_logic *)log_manager.log_element[log->element_num[i]].fun_log_ptr;

		if(v_args->params.in_num<32)
		{
			if(virt_in_states & (1<<v_args->params.in_num))
			{
				*v_log->out_ptr|=(1<<v_log->out_bit_no);
				if(v_args->params.impulse)
				{
					if(v_log->impulse_cnt++>=VIRT_IN_IMPULSE_TIME_100HZ)
					{
						virt_in_states&=~(1<<v_args->params.in_num);
						*v_log->out_ptr&=~(1<<v_log->out_bit_no);
						v_log->impulse_cnt=0;
					}
				}
			}
			else
			{
				*v_log->out_ptr&=~(1<<v_log->out_bit_no);
				v_log->impulse_cnt=0;
			}
		}
		else
		{
			if(virt_in2_states & (1<<(v_args->params.in_num-32)))
			{
				*v_log->out_ptr|=(1<<v_log->out_bit_no);
				if(v_args->params.impulse)
				{
					if(v_log->impulse_cnt++>=VIRT_IN_IMPULSE_TIME_100HZ)
					{
						virt_in2_states&=~(1<<(v_args->params.in_num-32));
						*v_log->out_ptr&=~(1<<v_log->out_bit_no);
						v_log->impulse_cnt=0;
					}
				}
			}
			else
			{
				*v_log->out_ptr&=~(1<<v_log->out_bit_no);
				v_log->impulse_cnt=0;
			}
		}
	}
}
