#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wait.h>
#include <pthread.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <errno.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sched.h>

#include "orcd.h"
#include "SSocket.h"
#include "serial.h"
#include "ioutils.h"
#include "logutils.h"
#include "packetbuffer.h"
#include "orcutils.h"


#define LOGCHANNEL "POLLER"

//////////////////// SERIAL READER /////////////////////////////////////

void *asyncPollerThreadProc(void *arg)
{
  orcd_t *orcd=(orcd_t*) arg;
  unsigned char cmd[ORC_MAX_PACKETSIZE];
  memset(cmd, 0, ORC_MAX_PACKETSIZE);

  int pollms=orcd->opt->getOptionInt("pollms");

  unsigned char commerrs[3];
  for (int i=0;i<3;i++)
    commerrs[i]=0;

  while (true)
    {
      //      printf(".");
      //fflush(NULL);

      cmd[0]=237;
      cmd[1]=5;
      cmd[2]=HOSTMASTER;
      cmd[3]='*';
      cmd[4]=checksum(cmd, cmd[1]-1);
      
      doTransaction(orcd, cmd, cmd[1], cmd);

      sched_yield();
      usleep(pollms*1000);

      for (int i=0;i<3;i++)
	{
	  if (cmd[62+i]!=commerrs[i])
	    {
	      if (orcd->opt->getOptionBool("debug"))
		printf("Err count %i: %i\n", i, (cmd[62+i]-commerrs[i])&0x00ff);
	      commerrs[i]=cmd[62+i];
	    }
	}
      int flag=0;
      for (int i=0;i<3;i++)
	{
	  if (cmd[65+i]!=0)
	    flag=1;
	}
      if (flag)
	{
	  if (orcd->opt->getOptionBool("debug"))
	    printf("errs: %02x %02x %02x\n", cmd[65], cmd[66], cmd[67]);
	}
    }
}

void *asyncPollerThreadProc2(void *arg)
{
  orcd_t *orcd=(orcd_t*) arg;
  unsigned char cmd[ORC_MAX_PACKETSIZE];
  memset(cmd, 0, ORC_MAX_PACKETSIZE);

  int pollms=orcd->opt->getOptionInt("pollms");

  while (true)
    {
      //      printf(",");
      //      fflush(NULL);

      cmd[0]=237;
      cmd[1]=5;
      cmd[2]=HOSTSLAVE;
      cmd[3]='*';
      cmd[4]=checksum(cmd, cmd[1]-1);
      
      doTransaction(orcd, cmd, cmd[1], NULL);

      sched_yield();
      usleep(pollms*1000);
    }

  return NULL;
}

