/*
 * relay_out.c
 *
 *  Created on: 07-04-2014
 *      Author: Krzysztof Jakubczyk
 */

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

#include "relay_out.h"

int relay_out_initlog(void *arguments, void *logic)
{
	struct relay_out_args *args = (struct relay_out_args *)arguments;
	struct relay_out_logic *log = (struct relay_out_logic *)logic;

	log->in_ptr = log_manager.nets_data + (args->io.in  >> 3);
	log->in_bit_mask = args->io.in & 0x07;
	log->in_bit_mask = (1<<log->in_bit_mask);

	log->clr_ptr = log_manager.nets_data + (args->io.clr_in >> 3);
	log->clr_bit_mask = args->io.clr_in & 0x07;
	log->clr_bit_mask = (1<<log->clr_bit_mask);

	log->kob_ptr = log_manager.nets_data + (args->io.kob_out >> 3);
	log->kob_bit_mask = args->io.kob_out & 0x07;
	log->kob_bit_mask = (1<<log->kob_bit_mask);

	if(log->in_ptr >= (log_manager.nets_data+sizeof(log_manager.nets_data)))
		return -1;

	if(log->clr_ptr >= (log_manager.nets_data+sizeof(log_manager.nets_data)))
		return -1;

	if(log->kob_ptr >= (log_manager.nets_data+sizeof(log_manager.nets_data)))
		return -1;

	log->kob_msw_bit_mask=(1<<(args->params.relay_num/3))<<12;

	if(args->params.card_addr>(MAX_OUT_CARDS-1))
		return -1;

	if(args->params.relay_num>15)
		return -1;

	return 0;
}

void relay_out(void *arguments, void *logic)
{
	struct relay_out_args *args = (struct relay_out_args *)arguments;
	struct relay_out_logic *log = (struct relay_out_logic *)logic;

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

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

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