/************************************************************************/
/*                               TELTALK.C                              */
/*                          written by Dan Kohn                         */
/*                           Ver 1.5b 12/20/03                          */
/* Ver 1.5b                                                             */
/* Updates:     Modified to talk on IO address 0x4fe                    */
/*                                                                      */
/* Ver 1.5                                                              */
/* Updates:     Modified to talk to a PC with an IO card address        */
/*              0x1fe. Also added an additional command:                */
/*                                                                      */
/*              PUT_PORT_A # - will put the number[#] out to output     */
/*                             port.                                    */
/*                                                                      */
/* Ver 1.0                                                              */
/* Description: This program, a modification of Ttalk.C, was written to */
/*              demonstrate how the Flashlite 386EX board can be used   */
/*              to communicate data to/from a remote user (via Telnet   */
/*              or specially developed application) over a TCP/IP       */
/*					 connection.                                             */
/*                                                                      */
/*              It was written using BORLAND C/C++ 4.52 with the        */
/*              WATTCP Network Programming Library.                     */
/*                                                                      */
/*              It will accept 4 message types as follows:              */
/*                                                                      */
/*              GET_ARRAY # - will return the value in number[#] to     */
/*                            the remote user                           */
/*                                                                      */
/*              PUT_ARRAY #,Y - will make number[#] = Y and send a      */
/*                              message to the remote user verifying    */
/*                              the change was made.                    */
/*                                                                      */
/*              GET_PORT_A - will return the value of Hardware Port A   */
/*                           (which is set up for input) to the remote  */
/*                           user.                                      */
/*                                                                      */
/*              DEBUG - Switches on/off debug mode which sends messages */
/*                      to the console.                                 */
/*                                                                      */
/************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <dos.h>
#include <tcp.h>


/* Define Port for TCP/IP Communications - IP address and netmask are */
/* defined by WATTCP.CFG */
#define TALK_PORT 23

/* Define Address for Hardware Port A on Flashlite 386Ex Board */
#define PORT_A				0x4fe	/* address of Port A */
// #define PORT_DIR     	0x63	/* address of port direction register */
// #define PORT_A_DIR_MASK 0x10	/* dir bit is bit 4 (00010000) = 0x10 */

/* Message to indicate Communications established */
void init( void )
{
	printf("%c[40BChannel open:\n\n\n\n",27);
}


/* Shows messages on Console */
void add_msg( char *source, char *msg )
{
	printf("%c%c[2A%s: %s\n\n",13,27,source,msg);
	printf("%60c\n",32);
}

int main()
{
	char temp[ 80 ],buffer[ 80 ], rbuffer[80]; /* Buffer Space */
	word who_closed = 0;                       /* Define other Variables */

	int status;

	static tcp_Socket s;
	char *user, *remoteuser;

	int number[10];                             /* Test Array */
	int t;
	char *ptr, *ptr1;
	int debug = 1;                              /* Flag for Debug Mode */

//	portA = inportb(PORT_DIR);	/* get current value of direction register */
//	portA |= PORT_A_DIR_MASK;	/* set direction bit for input */
//	outportb(PORT_DIR,portA);	/* write value to direction reg */

	/* Load array with random numbers to start */


	sock_init();                               /* Initialize TCP/IP subsystem */

	puts("TelTalk ver 1.0\n\r");               /* Welcome Message */
	puts("Waiting for an incomming call\n\r");
	printf("(My address is [%s]\n\r", inet_ntoa( buffer, gethostid()));

	printf("\n\nARRAY:\n");
	for (t=0;t<10;t++)
	{
		number[t] = rand() % 100;
		printf ("[%d] is %d\r\n",t,number[t]);
	}

	tcp_listen( &s, TALK_PORT, 0, 0, NULL, 0 ); /* Open a TCP Port for */
															  /* incoming session    */

	sock_mode( &s, TCP_MODE_ASCII );            /* set the socket's mode */
															  /* to ASCII              */

	sock_wait_established( &s, 0, NULL, &status);  /* Wait for TCP connection */

	printf("Connection established\n\r");

	remoteuser = "Receive: ";
	user = "   Send: ";

	init();

	while ( tcp_tick( &s ) )                    /* Loop while connected */
	{
		*temp = 0;                               /* Reset variables      */
		*buffer = 0;
		if (sock_dataready( &s ))                /* Perform if Data present */
		{
			sock_gets( &s, rbuffer, sizeof( rbuffer ));    /* Get Data */

			/* look for 'GET_PORT_A' in input buffer, */
			/* if found transmit value of port A */
			if (strstr(rbuffer,"GET_PORT_A") != NULL)
			{
				itoa((int)inportb(PORT_A),temp,16);      /* Form message to send */
				strcat(buffer,"PORT_A: ");
				strcat(buffer,temp);
				if (debug == 1)                          /* Display to Console */
					add_msg (user,buffer);                /* if debug = 1   */
				sock_puts (&s,buffer);                   /* Send msg via TCP/IP*/
			}

			/* look for "PUT_PORT_A #" in input buffer */
			/* if found put # out to PORT A */
			else if(strstr(rbuffer,"PUT_PORT_A ") != NULL)
			{
				ptr=strchr(rbuffer,' ')+1;                 /* Check and translate */
				if (ptr)
				{
					outportb(PORT_A,atoi(ptr));        /* Update Port       */
					strcat(buffer,"PORT_A -> ");       /* Form response msg */
					strcat(buffer,ptr);
					if (debug == 1)                    /* Display to console */
						add_msg (user,buffer);          /* if debug = 1 */
					sock_puts (&s,buffer);             /* Send msg via tcp/ip */
				}
			}
			/* look for "GET_ARRAY #" in input buffer */
			/* if found transmit value of Array[#] */
			else if(strstr(rbuffer,"GET_ARRAY ") != NULL)
			{
				ptr=strchr(rbuffer,' ')+1;               /* Form message to send */
				if (ptr)
				{
					strcat(buffer,"ARRAY[");
					strcat(buffer,ptr);
					strcat(buffer,"]: ");
					itoa(number[atoi(ptr)],temp,10);
					strcat(buffer,temp);
					if (debug == 1)                       /* Display to console */
						add_msg (user,buffer);             /* if debug = 1 */
					sock_puts (&s,buffer);                /* Send Msg via TCP/IP */
				}
			}
			/* look for "PUT_ARRAY #,y" in input buffer */
			/* if found replace value of ARRAY[#] with y */
			/* Echo back message to conferm new value was recieved */
			else if(strstr(rbuffer,"PUT_ARRAY ") != NULL)
			{
				ptr=strtok(rbuffer," ");                 /* Check and translate */
				ptr=strtok(NULL,",");                    /* value to place into */
				if (ptr)                                 /* array               */
				{
					ptr1=strtok(NULL," ");
					if (ptr1)
					{
						number[atoi(ptr)] = atoi(ptr1);    /* Update value in array */
						strcat(buffer,"ARRAY[");           /* Form response msg */
						strcat(buffer,ptr);
						strcat(buffer,"]: ");
						itoa(number[atoi(ptr)],temp,10);
						strcat(buffer,temp);
						if (debug == 1)                    /* Display to console */
							add_msg (user,buffer);          /* if debug = 1 */
						sock_puts (&s,buffer);             /* Send msg via tcp/ip */
					}
				}
			}
			/* look for "DEBUG" in input buffer */
			/* If found toggle debug mode [on/off] */
			else if(strstr(rbuffer,"DEBUG") != NULL)
			{
				if (debug==1)
				{
					debug = 0;
					strcat(buffer,"DEBUG 0");
				}
				else
				{
					debug = 1;
					strcat(buffer,"DEBUG 1");
				}
				sock_puts(&s,buffer);                   /* Send current status of */
			}                                          /* Debug to remote user   */

			if (debug == 1)
				add_msg( remoteuser, rbuffer );
		}
	}


	/* Connection Lost - Display message, wait for connect to close fully, end */
	if ( who_closed == 1 )
	{
		puts(" *** YOU CLOSED CONNECTION *** ");
		sock_wait_closed(&s, sock_delay, NULL, &status);
	}
	else
		puts(" *** OTHER PERSON CLOSED CONNECTION *** ");

	sleep( 1 );
	exit( 0 );


/* Error Trapping used by WATTCP */
sock_err:
	switch ( status )
	{
		case 1 : puts("Connection closed");
			break;
		case -1: puts("REMOTE HOST CLOSED CONNECTION");
			break;
	}
	exit( 0 );
	return (0);  /* not reached */
}

