static char dmonitor_id[] = "$Header: /u/oreilly/rov/tmacs/RCS/dmonitor.cc,v 1.5 1998/02/23 16:14:03 oreilly Exp $";


/*
$Log: dmonitor.cc,v $
Revision 1.5  1998/02/23 16:14:03  oreilly
*** empty log message ***

Revision 1.4  1997/03/20 12:32:02  oreilly
..

Revision 1.3  96/10/28  09:12:57  09:12:57  oreilly (Thomas C. O'Reilly)
*** empty log message ***

Revision 1.2  96/07/22  10:42:26  10:42:26  oreilly (Thomas C. O'Reilly)
First external release

*/
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include "DmMonitor.h"
#include "DmErrno.h"

#define MASK(f) (1 << (f))
#define dprintf if (debug) fprintf
 
main(int argc, char **argv)
{
  Errno ret;

  if ((ret = dm_init(NULL)) != OK)
  {
    if (ret == EDM_NO_DAEMON)
    {
      fprintf(stderr, "Data Manager daemon isn't running\n");
    }
    else
    {
      fprintf(stderr, "Data Manager daemon initialization error %d\n", ret);
    }

    exit(1);
  }
  
  MBool debug = FALSE;

  if (argc != 4)
  {
    fprintf(stderr, "usage: %s readPipeFd writePipeFd semId\n", argv[0]);
    exit(1);
  }
  
  int readPipe = atoi(argv[1]);
  int writePipe = atoi(argv[2]);
  SEM_ID wakeupSem = atoi(argv[3]);
  
  unsigned flags;

  if ((flags = fcntl(readPipe, F_GETFL, 0)) == -1)
  {
    perror("dmonitor: fcntl()");
    exit(1);
  }

  /* Don't block when reading pipe */
  fcntl(readPipe, F_SETFL, flags | O_NONBLOCK);
  
  int nBytes;
  RequestMessage message;
  char buf[512];

  Int32 timeOutTicks = 1;
  struct timeval sleepTime;
  sleepTime.tv_sec = 0;
  sleepTime.tv_usec = 1000;

  DmMonitor *dmMonitor = new DmMonitor(wakeupSem, writePipe);
  
  while (TRUE)
  {
    /* Wait on semaphore for registration requests or DM item updates */
    dprintf(stderr, "Wait on semaphore\n");
    semTake(wakeupSem, WAIT_FOREVER);

    dprintf(stderr, "Semaphore changed\n");

    // Dispatch data for updated DM items
    if (dmMonitor->handleNewData() == -1)
    {
      fprintf(stderr, "dmonitor: dmMonitor->handleNewData() failed\n");
      exit(1);
    }

    /* Process any monitor requests from application */
    while (TRUE)
    {
      if ((nBytes = read(readPipe, &message, sizeof(RequestMessage))) == EOF)
	/* No requests in pipe */
	break;
      
      else if (nBytes == sizeof(RequestMessage))
      {
	if (dmMonitor->handleRequest(&message) == -1)
	{
	  fprintf(stderr, "dmonitor: dmMonitor->handleRequest() failed\n");
	  exit(1);
	}
      }    
      else
      {
	fprintf(stderr, "Read %d bytes from readPipe - abort\n", nBytes);
	perror("dmonitor: read()");
	exit(1);
      }
    }
  }

  exit(0);
}
