/*
 * out_drv.c
 *
 *  Created on: 02-12-2019
 *      Author: KJ
 */


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

#include <ti/ipc/Notify.h>
#include <string.h>
#include "out_drv.h"
#include "relay_out.h"
#include "comm.h"
#include <ti/sysbios/knl/Swi.h>

int out_drv_initlog(void *arguments, void *logic)
{
//	struct events_reg_args *args = (struct events_reg_args *)arguments;
	struct out_drv_logic *log = (struct out_drv_logic *)logic;
	int i;

	log->out_count=0;

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

			log->element_num[log->out_count]=i;
			log->out_count++;
		}
	}

	return 0;
}

void out_drv(void *arguments, void *logic)
{
	//struct events_reg_args *args = (struct events_reg_args *)arguments;
	struct out_drv_logic *log = (struct out_drv_logic *)logic;

	struct relay_out_args *rel_args;
	struct relay_out_logic *rel_log;

	int i;

	for(i=0;i<log->out_count;i++)
	{
		rel_args = (struct relay_out_args *)log_manager.log_element[log->element_num[i]].fun_args_ptr;
		rel_log = (struct relay_out_logic *)log_manager.log_element[log->element_num[i]].fun_log_ptr;

		if(*rel_log->in_ptr & rel_log->in_bit_mask)
			bus_out_data[rel_args->params.card_addr]|=(1<<rel_args->params.relay_num);
		else if(!(rel_args->params.bits & RELAY_OUT_UNTIL_CLR))
			bus_out_data[rel_args->params.card_addr]&=~(1<<rel_args->params.relay_num);

		if(!(*rel_log->in_ptr & rel_log->in_bit_mask) && (*rel_log->clr_ptr & rel_log->clr_bit_mask))
			bus_out_data[rel_args->params.card_addr]&=~(1<<rel_args->params.relay_num);

		if(rel_args->params.bits & RELAY_OUT_VIA_MSW)
		{
			if((ic->kob_out & (1<<rel_args->params.card_addr)) && (ic->out_set[rel_args->params.card_addr] & rel_log->kob_msw_bit_mask))
				*rel_log->kob_ptr|=rel_log->kob_bit_mask;
			else
				*rel_log->kob_ptr&=~rel_log->kob_bit_mask;
		}
		else
		{
			if(ic->kob_out & (1<<rel_args->params.card_addr))
				*rel_log->kob_ptr|=rel_log->kob_bit_mask;
			else
				*rel_log->kob_ptr&=~rel_log->kob_bit_mask;
		}
	}
}
