/*
 *  timeout_int.c
 *
 *  v 0.0 2021.6.10
 *    test the timeout interrupt.
 */

#include <signal.h>
#include "msw.h"
#include "armplat.h"

#define MYSLOT SLOT10	//TIMEOUT INT

static unsigned sig_counter;

void sig_handler(int sig)
{
	printf("\rGot single %d for %u times", sig, ++sig_counter);
}

int main()
{
	slot_signal_t sig;

	static struct sigaction act, act_old;

	/* open device file */
	if(Open_Slot(MYSLOT)){
		printf("open Slot %d failed!\n",MYSLOT);
		return FAILURE;
	}
	if(Open_Slot(SLOT9)){
		printf("open Slot %d failed!\n",SLOT9);
		return FAILURE;
	}

	/* set action for signal */
	act.sa_handler = sig_handler;
	sigemptyset(&act.sa_mask);
	sigaddset(&act.sa_mask, SIGALRM);
	if (sigaction(SIGALRM, &act, &act_old)) {
		puts("Failure of signal action.");
		return FAILURE;
	}

	/* signal condiction */
	if(setSignal(MYSLOT,SIGALRM,getpid())){
		Close_Slot(MYSLOT);
		sigaction(SIGALRM, &act_old, NULL);
		puts("Failure of signal condiction.");
		return FAILURE;
	}

	//printf("ENABLE Timeout INT\n");
	outb( 9, 17, 10);
	outb( 9, 19, 10);
	outb( 9, 16, 10);
	outb( 9, 18, 10);

	int irqa, irqb, v9003a, v9003b;

	/* wait for exit */
	//puts("press <Enter> to exit\n");
	//while (getchar() != 10);
	while(1)
	{
		if(MYSLOT != SLOT10)
		{
			outb(MYSLOT, 1, 2);
        		inb(9, 9);
	        	outb(MYSLOT, 1, 0);
	        	inb(9, 9);
			usleep(500);
		}

		if(sig_counter >= 500)	//break when get 500 signal.
			break;
	}

	//printf("DISABLE Timeout INT\n");
	outb( 9, 17, 0);
	outb( 9, 19, 0);
	outb( 9, 16, 0);
	outb( 9, 18, 0);
	outb( 9, 34, 0);

	Close_Slot(MYSLOT);
	Close_Slot(SLOT9);
	sigaction(SIGALRM, &act_old, NULL);
	puts("\nEnd of program.");
	return sig_counter % 500;
}
