#include "tablet_counter.h"
#include "timer.h"
#include "io_port.h"
#include "machineControl.h"

#pragma DATA_ALIGN(TabletCounter, 8);
TTabletCounter TabletCounter;

#pragma DATA_ALIGN(SimpleTabletCounter, 8);
TSimpleTabletCounter SimpleTabletCounter;

struct
{
	int SensorOnCnt;
	int SensorOffCnt;
} SensorSW;


#define CHECKING_INTERVAL		10000		// 10s
unsigned int CheckInterval;
unsigned int IntervalCount;

void SimpleTabletCounter_Reset(void);
void SimpleTabletCounter_Inc(void);

void TabletCounter_Reset(void)
{
	int tableIndex;
	TabletCounter.Counter = 0;	
	TabletCounter.SubCounter[0] = 0;
	TabletCounter.SubCounter[1] = 0;
	TabletCounter.CurrentTableIndex = 0;
	TabletCounter.ElapsedTime = 0;
	for (tableIndex = 0; tableIndex < TC_TABLE_CAPACITY; tableIndex++)
	{
		TabletCounter.IndexTable[tableIndex] = -1;
		TabletCounter.OnInterval[tableIndex] = 0;
		TabletCounter.OffInterval[tableIndex] = 0;
	}
	CheckInterval = 0;
	IntervalCount = 0;
	TabletCounter.CPS = 0;
	TabletCounter.CPM = 0;
}
//----------------------------------------------------------
void TabletCounter_Init(void)
{
	SensorSW.SensorOnCnt = 0;
	SensorSW.SensorOffCnt = 0;


	TabletCounter.CountingMode = COUNTING_MODE_NONE;
	TabletCounter_Reset();
	SimpleTabletCounter_Reset();
}
//----------------------------------------------------------
void TabletCounter_Ready(int mode)
{
	if (mode == 0)
	{
		TabletCounter.CountingMode = COUNTING_MODE_SIMPLE;
	}
	else
	{
		TabletCounter.CountingMode = COUNTING_MODE_COMPLEX;
	}
}
//----------------------------------------------------------
void TabletCounter_Sleep(void)
{
	TabletCounter.CountingMode = COUNTING_MODE_NONE;
}
//----------------------------------------------------------
void SimpleTabletCounter_Reset(void)
{
	SimpleTabletCounter.Counter = 0;
	SimpleTabletCounter.IntervalCounter = 0;
	SimpleTabletCounter.CPM = 0;
	SimpleTabletCounter.ElapsedTimeInterval = 0;
}
//----------------------------------------------------------
void SimpleTabletCounter_Inc(void)
{
	if (SimpleTabletCounter.Counter == 0)
	{
		SimpleTabletCounter.ElapsedTime = 0;
		SimpleTabletCounter.LastCheckingTime = Board1MSTmr;
	}
	else
	{
		SimpleTabletCounter.ElapsedTime += (Board1MSTmr - SimpleTabletCounter.LastCheckingTime);
		SimpleTabletCounter.ElapsedTimeInterval += (Board1MSTmr - SimpleTabletCounter.LastCheckingTime);
		SimpleTabletCounter.LastCheckingTime = Board1MSTmr;
		if (SimpleTabletCounter.ElapsedTimeInterval > CHECKING_INTERVAL)
		{
			SimpleTabletCounter.CPM = SimpleTabletCounter.IntervalCounter * 60 / (CHECKING_INTERVAL / 1000);
			SimpleTabletCounter.ElapsedTimeInterval -= CHECKING_INTERVAL;
			SimpleTabletCounter.IntervalCounter = 0;
		}
	}
	SimpleTabletCounter.IntervalCounter++;
	SimpleTabletCounter.Counter++;
}

