/*
 * cnt.c
 *
 *  Created on: 10-06-2019
 *      Author: Krzysztof Jakubczyk
 */

#include <math.h>

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

#include "helper.h"
#include "cnt.h"

float cnt_mem[8] = {0,0,0,0,0,0,0,0};

int cnt_initlog(void *arguments, void *logic)
{
	struct cnt_args *args = (struct cnt_args *)arguments;
	struct cnt_logic *log = (struct cnt_logic *)logic;

	if(set_bit_ptr_mask(args->io.Pwe_in,&log->Pwe,&log->Pwe_bit_mask))
		return -1;

	if(set_bit_ptr_mask(args->io.Kas_in,&log->Kas,&log->Kas_bit_mask))
		return -1;

	if(set_bit_ptr_mask(args->io.Pwy_out,&log->Pwy,&log->Pwy_bit_mask))
		return -1;

	if(set_float_ptr(args->io.Licznik_float_out,&log->licznik))
		return -1;

	log->on = args->params.bity & 0x0001;
    log->Wr = args->params.Wr_; // przepisanie wartosci progowej PKW
    log->id = args->params.id & 0x0007;

//	Semaphore_post(spi_semaphore);

	return 0;
}

void cnt(void *arguments, void *logic)
{
	struct cnt_logic *log = (struct cnt_logic *)logic;
	struct cnt_args *args = (struct cnt_args *)arguments;

	if(log->on)   // jesli funkcja przekaznika aktywna
    {
		if (*log->Kas & log->Kas_bit_mask)
			cnt_mem[log->id]=args->params.kas;

		if (*log->Pwe & log->Pwe_bit_mask)
    		cnt_mem[log->id] += 1.0;

		check_and_set_mask(cnt_mem[log->id]>=log->Wr,log->Pwy,log->Pwy_bit_mask);

		*log->licznik = cnt_mem[log->id];
    }
	else
        *log->licznik = 0;
}

