/*
 * Test for fasync
 */

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

#include <linux/h3600_ts.h>

int gotit=0;
void sighandler(int signo)
{
    signal(SIGIO, &sighandler);
    if (signo==SIGIO)
    {
	printf("SIGIO received\n");
        gotit++;
    }
    return;
}

/* should work for all h3600 events ts tsraw and key */
#define DEV_NODE "/dev/h3600_key"
#if 0
#define DEV_NODE "/dev/ts"
#define DEV_NODE "/dev/tsraw"
#endif

int main(int argc, char **argv)
{
    int counter=0;
    int fd,err;
#if 1
    unsigned char key;
#else
    TS_EVENT event;
#endif

    signal(SIGIO, &sighandler);

    fd = open(DEV_NODE,O_RDONLY);
    if( fd < 0 )
    {
	printf("\nUnable to read from %s\n",DEV_NODE);
	exit(0);
    }

    fcntl(fd, F_SETOWN, getpid());
    fcntl(fd, F_SETFL, fcntl(0, F_GETFL) | FASYNC);


    while(counter++ < 10 )
    {
        /* this only returns if a signal arrives */
        printf("[%d a]Sleeping ....\n",counter);
        sleep(300);	/* sleep for 5mins unless woken by a SIGIO */
        printf("[%d b]Awake ....\n",counter);
        if (!gotit)
            continue;
	printf("[%d c]Reading...\n",counter);
#if 1
	err = read(fd,(char *)&key,1);
	printf("[%d e] Key=%02x\n\n",counter,key);
#else
	err = read(fd,(char *)&event,sizeof(TS_EVENT));
#endif
	if( err < 0 )
	{
		perror("pp_read:bad read");
		close(fd);
		exit(1);
	}       
        gotit=0;
    }

    printf("\n\nEXITING LOOP COUNT (%d) EXCEEDED\n",counter);
    close (fd);

}
