#include "SPBTest.h"
#include "common.h"
#include "timer.h"
#include "data_indicator.h"

#define CAPTURE_WIDTH	640
#define CAPTURE_HEIGHT	480
int TestKind = 0;
int TestProc = 0;
unsigned int ImageSendStartTime;
unsigned int ImageSendStartTimePerImage;

THPITestData HPITestData;

THPIProtocolTestData HPIProtocolTestData;

unsigned int HPITestEchoBuffer[1024];

void HPITestProc(void);


void SPB_Test_Init(void)
{
	HPIProtocolTestData.Func = 0;
//	HPIProtocolTestData.CPBIndex = 0x0;
//	TestProc = 1;
}

void SPB_TestProcess(void)
{	
	if (TestProc == 1)
	{
		HPITestProc();
	}

	if (HPIProtocolTestData.Func)
	{
		Request_SendData(IND_ECHO, HPITestEchoBuffer, 1024 * sizeof(unsigned int), HPIProtocolTestData.CPBIndex, NULL);
		Request_ReceiveData(IND_ECHO, HPITestEchoBuffer, 1024 * sizeof(unsigned int), HPIProtocolTestData.CPBIndex, NULL);
	}
}

void SPBTestStop(void)
{
	TestProc = 0;
}

void HPITestStart(int testKind)
{
	TestProc = 1;
	TestKind = testKind;
	HPITestData.ImageSendCount = 0;
	HPITestData.ErrorCount = 0;
	ImageSendStartTime = Board1MSTmr;

	HPITestData.MinTime = 0;
	HPITestData.MaxTime = 0;
	HPITestData.TotalTime = 0;
	HPITestData.AverageTime = 0;
}

void HPITestProc(void)
{
	int cpbIndex;
	int elapsedTime;
	for (cpbIndex = 0; cpbIndex < SYSTEM_CPB_COUNT; cpbIndex++)
	{
		if (IsAvailableCPB(cpbIndex))
        {
			ImageSendStartTimePerImage = Board50usTimer;
			if (TestKind == 0)
			{
				if (!Request_SendImage_Buffer(0, CAPTURE_WIDTH, CAPTURE_HEIGHT, cpbIndex, 0, 0))
				{
					HPITestData.ErrorCount++;
				}
			}
			else
			{
				if (!Request_SendImage_Buffer(0, CAPTURE_WIDTH, CAPTURE_HEIGHT, cpbIndex, 0, 1))
				{
					HPITestData.ErrorCount++;
				}
			}
			elapsedTime = Board50usTimer - ImageSendStartTimePerImage;
			if (HPITestData.ImageSendCount == 0)
			{
				HPITestData.MinTime = elapsedTime;
				HPITestData.MaxTime = elapsedTime;
			}
			else
			{
				if (HPITestData.MinTime > elapsedTime)
				{
					HPITestData.MinTime = elapsedTime;
				}
				if (HPITestData.MaxTime < elapsedTime)
				{
					HPITestData.MaxTime = elapsedTime;
				}
			}
			HPITestData.ImageSendCount++;

			HPITestData.TotalTime += elapsedTime;
			HPITestData.AverageTime = HPITestData.TotalTime / HPITestData.ImageSendCount;
			
			HPITestData.ProcessThroughput = CAPTURE_WIDTH * CAPTURE_HEIGHT * HPITestData.ImageSendCount / (Board1MSTmr - ImageSendStartTime) * 1000 / 1024; // KB/S
		}
	}
}