/* **************************************************************** *
 * Copyright PragmaDev 2003
 * **************************************************************** *
 * This module contains the functions allowing to communicate with
 * the MSC tracer
 * **************************************************************** */

#ifndef __CYGWIN__
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#else
#include <Winsock2.h>
#endif

#include <string.h>

#include "TracerSocketConnection.h"


static int tracerSocket = -1;


/*
 * FUNCTION startTracing:
 * ----------------------
 * Starts the connection to the MSC tracer
 * Parameters:
 * - tracerIPAddress: IP address for the MSC tracer host as a string
 * - portNumber: port number for the tracer
 * Returns: >= 0 if OK; < 0 if KO
 */

int startTracing(char * tracerIPAddress, unsigned short portNumber)
  {
  /* Socket address structure for server */
  struct sockaddr_in serverAddress;

  /* Build socket address structure for server */
  serverAddress.sin_family = AF_INET;
  serverAddress.sin_addr.s_addr = inet_addr(tracerIPAddress);
  serverAddress.sin_port = htons(portNumber);

  /* Create socket */
  tracerSocket = socket(AF_INET, SOCK_STREAM,0);

  /* Connect to socket */
  return connect(tracerSocket, (struct sockaddr *)&serverAddress, sizeof(struct sockaddr_in));
  }


/*
 * FUNCTION sendToTracer:
 * ----------------------
 * Sends a tracing command to the MSC tracer
 * Parameters:
 * - command: the command to send
 * Returns: >= 0 if OK; < 0 if KO
 */

int sendToTracer(char * command)
  {
  if ( tracerSocket == -1 ) return -1;
#ifdef DEBUG
  printf("*** Sending '%s' to tracer...\n", command);
#endif
  send(tracerSocket, command, strlen(command), 0);
  }


/*
 * FUNCTION waitForAck:
 * --------------------
 * Sends a waitForAck command to the MSC tracer and waits for the answer
 * Parameters: none
 * Returns: >= 0 if OK; < 0 if KO
 */

int waitForAck()
  {
  char buffer[4];
  int cr, nbytes;

  if ( tracerSocket == -1 ) return -1;
  cr = sendToTracer("waitingForAck|\n");
  if ( cr < 0 ) return cr;
  nbytes = read(tracerSocket, buffer, 3);
  if (nbytes < 0) return nbytes;
  buffer[nbytes] = '\0';
  if ( strcmp(buffer, "ack") != 0 ) return -1;
  return nbytes;
  }

 
/*
 * FUNCTION endTracing:
 * --------------------
 * Closes the connection to the MSC tracer
 * Parameters: none
 * Returns: >= 0 if OK; < 0 if KO
 */

int endTracing()
  {
  if ( tracerSocket == -1 ) return -1;
  return close(tracerSocket);
  }
