/* File level history (record changes for this file here.)
 
   v 0.0.0  27 May 2016 by Winson
   Use Interrupt to do something.
*/

#include <stdio.h>
#include <signal.h>
#include "msw.h"
#include "i8048W.h"

void ISRFUN (int slot);
int ch = 0;
int rise = 0, fall = 0;


int main()
{
	int Ret, slot, slotIndex;
	int rising,falling;

	for(slot=1;slot<9;slot++)
	{
		Ret = Open_Slot(slot);

		if (Ret == 0) {
			if(I8048W_Init(slot) == 0) //find I-8048W module out
			{
                                slotIndex=slot;
				break;
			}

			Ret = inb(slot,0);
			if(Ret != 0x48)
				Close_Slot(slot);
		}
	}

	if(slotIndex==-1)
	{
		printf("There is no I-8048W at LP-8x8x !\n\n");
		usleep(10);
		return FAILURE;  // end of program
	}
	else
		printf("There is an I-8048W at slot %d\n\n", slotIndex);

	printf("Select Channel(0~7):");
	scanf("%d",&ch);
	printf("Set rising enable register(0.Disable 1.Enable):");
	scanf("%d",&rising);
	printf("Set falling enable register(0.Disable 1.Enable):");
	scanf("%d",&falling);

	I8048W_Set_RisingReg(slotIndex, ch, rising);	//set rising edge register enable
	I8048W_Set_FallingReg(slotIndex, ch, falling);  //set falling edge register disable
	I8048W_InstallISR(slotIndex, ISRFUN);

	printf("\n\nPress ESC and Enter to go out\n");

	while(1)
	{
		if(getch() == 27)
			break;
	}

	I8048W_UnInstallISR(slotIndex);
	
	printf("channel %d rising edge total count is %d\n",ch, I8048W_Read_RisingEventCount(slotIndex,ch));
	printf("channel %d falling edge total count is %d\n",ch, I8048W_Read_FallingEventCount(slotIndex,ch));

	printf("\nClear channel %d rising and falling edge count\n",ch);
	I8048W_Clear_RisingEventCount(slotIndex,ch);
	I8048W_Clear_FallingEventCount(slotIndex,ch);
	printf("channel %d rising edge total count is %d\n",ch, I8048W_Read_RisingEventCount(slotIndex,ch));
	printf("channel %d falling edge total count is %d\n",ch, I8048W_Read_FallingEventCount(slotIndex,ch));
	

	Close_Slot(slotIndex);
	return 0;
}

void ISRFUN (int slot)
{
	int Ret;

//		printf("channel %d rising edge trigger %d times.\n",ch, ++rise);
//#if 0
	if(I8048W_Read_RisingEvent(slot,ch) != 0)  //rising INT status enable
	{
		printf("channel %d rising edge trigger %d times.\n",ch, ++rise);
	}

	if(I8048W_Read_FallingEvent(slot,ch) != 0)  //falling INT status enable
	{
		printf("channel %d falling edge trigger %d times.\n",ch, ++fall);
	}
	I8048W_UnFreezeINT(slot,ch);
//#endif
}
