// aducmd.c - access an Ontrak ADU card
// Copyright 2003 by John Homppi
// released under the GPL license

// this is a crude program intended to demonstrate the
// application programming interface of the adutux driver

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

int main (int argc, char *argv[])
{
	int fd;
	int status;
	char sResponse[512]; // big just in case
	char sFilename[256];
	int id;
	
	if (argc != 2)
	{
		printf("usage: aducmd fileid\n"
				"   fileid = [0|1|...]\n");
		return 0;
	} // end if
	id = atoi(argv[1]);
	sprintf(sFilename, "/dev/usb/adutux%d", id);
	
	// the open call gets the file handle for the ocsadu driver 
	fd = open(sFilename, O_RDWR);
	
   	if (fd < 0)
   	{
   		printf("Open failed on %s. errno=%d %s\n", sFilename, errno, 
   				strerror(errno));
   		return 0;
   	}
   	else
   	{
   		printf("Opened %s\n", sFilename);
   	} // end if
   		
	for (;1;)
	{
		char sInput[256];
		int iPipe;
		char cAction;
		char sCommand[256];
		  
		printf("enter <pipe#> <w|r|s> [command] ");
		if (!strlen(gets(sInput))) // generates a warning but this is a demo.
		{
			break;
		} // end 
		cAction = '0';
		sscanf(sInput, "%d %c %s", &iPipe, &cAction, sCommand);
		switch(cAction)
		{
			case('w'):
			{
				char sString[8];
				sprintf(sString, "%c%s", iPipe, sCommand);
				status = write(fd, sString, 8);

				if (status < 0)
				{
					printf("write failed. status=%d errno=%d %s\n", 
							status, errno, strerror(errno));
				} // end if
				break;
			} // end case 'w'
			case('r'):
			{
				char sString[8];
				memset(sString, 0, 8);
				status = read(fd, sString, 8);
				memset(sResponse, 0, 9);
				strncpy(sResponse, sString, 8);
				if (status < 0)
				{
					printf("\nread failed. errno=%d %s\n", errno, strerror(errno));
				}
				else
				{
					printf("response=%02x%02x%02x%02x%02x%02x%02x%02x %s\n",
						sResponse[0], sResponse[1], sResponse[2], sResponse[3], 
						sResponse[4], sResponse[5], sResponse[6], sResponse[7],
						sResponse);
				} // end if
				break;
			} // end case 'r'
			case('s'):
			{
				char sString[8];
				memset(sString, 0, 8);
				sString[0] = 's';
				status = read(fd, sString, 8);
				memset(sResponse, 0, 9);
				strncpy(sResponse, sString, 8);
				if (status < 0)
				{
					printf("\nread failed. errno=%d %s\n", errno, strerror(errno));
				}
				else
				{
					printf("serial number=%02x%02x%02x%02x%02x%02x%02x%02x %s\n",
						sResponse[0], sResponse[1], sResponse[2], sResponse[3], 
						sResponse[4], sResponse[5], sResponse[6], sResponse[7],
						sResponse);
				} // end if
				break;
			} // end case 's'
			default:
			{
				printf("invalid action\n");
			}
		} // end switch
				
	} // end for
	close(fd);
	return 0;
} // end main

// end aducmd.c
