/* **************************************************************** *
 * Copyright PragmaDev 2003
 * **************************************************************** *
 * This an example client program to send information to the
 * PragmaDev MSC tracer. It sends a few predefined commands to the
 * tracer.
 * You may use it safely with MSC tracer's GUI
 * **************************************************************** */

#include <stdio.h>
#include <string.h>

#include "TracerSocketConnection.h"


#define T_SIZE 22

int main(int argc, char ** argv)
  {
  /* List of tracer commands */
  char *tabMsg[T_SIZE] =
    {
    "taskCreated| -t90| -npPing| 0x01|\n",
    "messageSent| -t100| -npPing| 0x01| 12| Ping|\n",
    "messageReceived| -t110| -npPong| 0x02| 12| Ping|\n",
    "taskChangedState| -t120| -npPong| 0x02| PingReceived|\n",
    "semaphoreCreated| -ssem| 0x03|\n",
    "takeAttempt| -t130| -npPong| -ssem| 0x02| 0x03|\n",
    "takeSucceeded| -t140| -npPong| -ssem| 0x02| 0x03|\n",
    "information| -t145| -npPong| 0x02| My informal message here|\n",
    "timerStarted| -t150| -npPong| -TWait| 0x02| 0x04| 100|\n",
    "timerTimedOut| -t160| -zrer| -npPong| 0x02| 0x04|\n",
    "taskCreated| -t170| -c0x02| -nnewTask| 0x05|\n",
	  "dummy| -t170| -c0x02| -nnewTask| 0x05|\n",
  	"giveSem| -t180| -npPong| -ssem| 0x02| 0x03|\n",
    "takeAttempt| -t190|  0x05| 0x03|\n",
    "takeSucceeded| -t200|  0x05| 0x03|\n",
    "takeAttempt| -t210|  0x01| 0x03|\n",
    "timerStarted| -t220| -TWait2| 0x05| 0x06| 100|\n",
    "timerTimedOut| -t230| 0x05| 0x06|\n",
    "giveSem| -t240| 0x05| 0x03|\n",
    "takeSucceeded| -t250|  0x01| 0x03|\n",
    "taskDeleted| -t260| 0x05|\n",
    "waitingForAck|\n"
    };

  /* IP address and port number for server */
  char ipAddress[16];
  unsigned short portNumber;
  /* Loop variable to browse commands to send */
  int i, cr;

  /* Decode command line arguments */
  if ( argc < 2 || argc > 3 )
	{
    printf("Usage: %s [<ip address>] <port number>\n", argv[0]);
    exit(0);
	}
  else if (argc<3)
	{
    strcpy(ipAddress, "127.0.0.1");
	portNumber = atoi(argv[1]);
	}
  else
	{
    strcpy(ipAddress, argv[1]);
	portNumber = atoi(argv[2]);
	}
  
  /* Connect to tracer */
  if ( startTracing(ipAddress, portNumber) < 0 )
    {
    fprintf(stderr, "Connection error! Exiting...\n");
    exit(0);
    }
  printf("Connection OK.\n");

  /* Send all messages to tracer */
  for( i = 0; i < T_SIZE; i++ )
	{
	/* Send appropriate message depending on command */
	if (strcmp(tabMsg[i], "waitingForAck|\n") == 0)
      cr = waitForAck();
    else
      cr = sendToTracer(tabMsg[i]);
    if ( cr < 0 ) printf("Error while reading socket\n");
	}
  /* Close socket */
  printf("Closing socket: %d\n", endTracing());
  }

