/*
 * cacheTestProgram.c
 *
 *  Created on: Feb 2, 2012
 *      Author: bjon
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define __USE_XOPEN
#include <poll.h>

#include <sys/ioctl.h>
#include <sys/poll.h>
#include <sys/mman.h>

#include "cachetest.h"
#include "cachetestcommands.h"

static int fd = -1;
static struct shared_struct *sharedStruct;

void process_data(void)
{
	int ret_val,i;
	struct pollfd pollStruct;
	pollStruct.fd = fd;
	pollStruct.events = POLLIN | POLLRDNORM;
	while (1)
	{
		ret_val = poll(&pollStruct, 1, -1);
		if(ret_val <0)
		{
			printf("poll failed.\n");
			return;
		}
		if(sharedStruct->controlData.readIndex==sharedStruct->controlData.writeIndex){
			printf("No data available.\n");
			continue;
		}
		while(sharedStruct->controlData.readIndex!=sharedStruct->controlData.writeIndex)
		{
			printf("Received packet from kernel with counter %lu\n",sharedStruct->data[sharedStruct->controlData.readIndex].counter);
			for(i=0;i<KRNL_SIZE;i++)
			{
				if(KRNL_VAL != sharedStruct->data[sharedStruct->controlData.readIndex].data[i])
				{
					printf("Value %u of packet %lu is not correct.\n",i, sharedStruct->data[sharedStruct->controlData.readIndex].counter);
				}
			}
			for(i=KRNL_SIZE;i<DATA_SIZE;i++)
			{
				sharedStruct->data[sharedStruct->controlData.readIndex].data[i] = USR_VAL;
			}
			sharedStruct->controlData.readIndex = (sharedStruct->controlData.readIndex + 1)%NR_DATA_BUFFERS;
			ret_val = ioctl(fd, CACHE_TEST_REMOVE_REQUEST, 0);
			if(ret_val < 0)
			{
				printf("ioctl failed.\n");
			}
		}
	}
}

int init_application(void)
{
	unsigned long mmapAddress;
	int ret_val;
	fd = open("/dev/cacheTest", O_RDWR);
	if (fd < 0)
	{
		printf("open() of /dev/xxx failed.\n");
		return -1;
	}
	ret_val = ioctl(fd, CACHE_TEST_GET_MMAP_ADDRESS, &mmapAddress);
	if(ret_val < 0)
	{
		printf("ioctl failed.\n");
		close(fd);
		return -1;
	}
	sharedStruct = (struct shared_struct *) mmap(0, sizeof(struct shared_struct), PROT_READ | PROT_WRITE, MAP_SHARED, fd, mmapAddress);
	if ((void*) -1 == (void*) sharedStruct)
	{
		printf("mmap failed.\n");
		close(fd);
		return -1;
	}
	return 0;
}

int main(int argc, char *argv[])
{
	if(init_application()!=0)
	{
		return 0;
	}
	process_data();
	return 0;
}
