#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "defs.h"
#include "hei.h"

#define MAX_DEVICES  20

#define QT_NORMAL 0
#define QT_ID    1
#define QT_NAME  2


enum CCMAckCode{ cacWaiting, cacAck, cacNak };

/* We need to supply a timeGetTime function to provide the timeouts
   that windows doesn't provide */
DWORD time_starttime;
DWORD timeGetTime()
{
  /* We will use the gettimeofday function to provide the millisecond
     tick counter.  We will return the timer tick relative to the
     first time the routine is called    */
         struct timeval date;
         struct timezone tz;
         unsigned long now;
         gettimeofday(&date,&tz);
         /* The first time this timer is called, initialize the starttime
   ** variable */
         if (time_starttime==0) {time_starttime = date.tv_sec;};
         now = ((date.tv_sec-time_starttime)*1000)+(date.tv_usec/1000);
         return now;
}



/*
** Note:
** Much of this in here is magic. The non-blocking mechinism isn't
** well defined yet. If you want to do this email and we'll give more
** info. We will get all of this documented as soon as possible.
** rmo
*/
int CCMAck(HEIDevice *pDevice)
{
  // Temp buffers for response
  BYTE Buff[500];
  int BuffSize = sizeof(Buff);

  // Check for a response
  int Error = HEIGetResponse(pDevice, Buff, &BuffSize, TRUE);
  
  // If error, deal with it
  if(Error)
    {
    if(Error == HEIE_NO_RESPONSE)
      return cacWaiting;
    else
      return Error;
    }
  // No error, test response
  else
    {
    if(Buff[PACKET_HEADER_SIZE] == FUN_ACK)
      return cacAck;
    else
      return cacNak;
    }
}

int CCMResponse(HEIDevice *pDevice, BYTE *pData, WORD DataLen)
{
  // Temp buffers for response
  BYTE Buff[500];
  int BuffSize = sizeof(Buff);

  // Check for a response
  int Error = HEIGetResponse(pDevice, Buff, &BuffSize, TRUE);

  // If error, return it
  if(Error)
    return Error;

  // Check for error from device
  Error = (short int) Buff[PACKET_HEADER_SIZE+2]
	+ (short int) (Buff[PACKET_HEADER_SIZE+3] << 8);
  
  // If error, return it
  if(Error)
    return Error;
  // Otherwise copy response data from packet
  else
    memcpy(pData, Buff+PACKET_HEADER_SIZE+4, DataLen);

  return HEIE_NULL;
}

int ParseWriteData(int argc, char *argv[], int Parm, BYTE *pDataBuff)
  {
  int ByteNum = 0;
  WORD DataVal = 0;

  while(Parm < argc)
    {
    char *p = argv[Parm] + (ByteNum ? 0 : 2);

    if(p[0] == '/' || p[0] == '-')
      return ByteNum;

    sscanf(p, "%hx", &DataVal);
    pDataBuff[ByteNum] = (unsigned char)DataVal;

    ByteNum++;
    Parm++;
    }

  return ByteNum;
  }

int main(int argc, char *argv[])
  {
  WORD Protocol = HEIP_IP;
  DWORD ID = 0;
  char Name[256] = "";
  int QueryType = QT_ID;
  BYTE DataType = 0x31;
  unsigned DataAddress = 0x401;
  unsigned DataLen = 2;
  BYTE DataBuff[256];
  BOOL Writing = FALSE;
  int Parm;
  HEITransport TP;
  HEIDevice aDevices[MAX_DEVICES];
  WORD DeviceCount;
  DWORD StartTime;
  BOOL Done, Acked;
  int Error;
  unsigned idx;

  printf("EtherCCM 1.0 - Copyright(C) 1997, Host Engineering, Inc.\n");
  printf("Executes CCM transaction on specified Hx-ENET device\n\n");

  /*
  ** Parse command line
  */
  for(Parm = 1; Parm < argc; Parm++)
    {
    if(argv[Parm][0] == '/' || argv[Parm][0] == '-')
      {
      switch(argv[Parm][1])
        {
        case 'P':
        case 'p':
          switch(argv[Parm][2])
            {
            case 'I':
            case 'i':
              Protocol = HEIP_IP;
              break;

            case 'X':
            case 'x':
              Protocol = HEIP_IPX;
              break;

            default:
              printf("%s - Unknown parameter\n", argv[Parm]);
              break;
            }
          break;

        case 'N':
        case 'n':
          QueryType = QT_NAME;
          memset(Name, 0, 256);
          strcpy(Name, argv[Parm]+2);
          break;

        case 'I':
        case 'i':
          QueryType = QT_ID;
          ID = atoi(argv[Parm]+2);
          break;

        case 'T':
         case 't':
          switch(argv[Parm][2])
            {
            case '1': DataType = 0x31; DataLen = 2; break;
            case '2': DataType = 0x32; DataLen = 1; break;
            case '3': DataType = 0x33; DataLen = 1; break;
            case '6': DataType = 0x36; DataLen = 1; break;
            case '7': DataType = 0x37; DataLen = 3; break;
            default:
              printf("%s - Unknown parameter\n", argv[Parm]);
              break;
            }

        case 'A':
        case 'a':
          if(!sscanf(argv[Parm]+2, "%x", &DataAddress))
            printf("%s - Unknown parameter\n", argv[Parm]);
          break;

        case 'L':
        case 'l':
          if(Writing)
            printf("/L not valid with /W, ignoring...\n", argv[Parm]);
          else if(!sscanf(argv[Parm]+2, "%d", &DataLen))
            printf("%s - Unknown parameter\n", argv[Parm]);
          break;

        case 'W':
        case 'w':
          DataLen = ParseWriteData(argc, argv, Parm, DataBuff);
          if(DataLen)
            Writing = TRUE;
          else
            printf("%s - Unknown parameter\n", argv[Parm]);
          break;

        case 'h':
        case 'H':
        case '?':
          printf("Usage - EtherCCM [Options]\n");
          printf("Options:\n");
          printf("  /Pn  Set protocol\n");
          printf("       n = I for IP\n");
          printf("           X for IPX\n");
          printf("  /Nv  Connect to device named v\n");
          printf("  /Iv  Connect to device number v\n");
          printf("  /Tt  CCM data type t (1, 2, 3, 6, 7)\n");
          printf("  /Aa  CCM data address a\n");
          printf("  /Wb1 [b2 [... [bn]]] Write data\n");
          printf("  /Ln  Read n bytes of data, not valid with /W\n");
          printf("  /?   This screen\n");
          return;

        default:
          printf("%s - Unknown parameter\n", argv[Parm]);
          break;
        }
      }
    }

  /*
  ** Initialize required data structures
  */
  memset(&TP, 0, sizeof(TP));
  memset(aDevices, 0, sizeof(aDevices));

  /*
  ** Step 1, initialize the driver
  ** Called once by app at startup
  */
  HEIOpen(HEIAPIVERSION);

  /*
  ** Step 2, initialize the transport
  */
  TP.Transport = HEIT_UNIX; // Under Unix this is the only valid transport
  TP.Protocol = Protocol;
  if(!HEIOpenTransport(&TP, HEIAPIVERSION, 0))
    {
    /*
    ** Step 3, resolve the logical address to a device
    ** This uses a data query to find all matching devices. There may
    ** be more than 1 match.
    */
    DeviceCount = MAX_DEVICES;

    switch(QueryType)
      {
      case QT_ID:
        HEIQueryDeviceData(&TP, aDevices, &DeviceCount, HEIAPIVERSION, DT_NODE_NUMBER, (BYTE *)&ID, 4);
        break;

      case QT_NAME:
        HEIQueryDeviceData(&TP, aDevices, &DeviceCount, HEIAPIVERSION, DT_NODE_NAME, (BYTE *)Name, 256);
        break;
      }

    // DeviceCount now contains number of devices found
    if(DeviceCount)
      {
      /*
      ** Step 4, open the device
      */
      if(!HEIOpenDevice(&TP, &aDevices[0], HEIAPIVERSION, 25, 3, FALSE))
        {
        /*
        ** Step 5, confirm that it is an Hx-ENET
        */
        DeviceDef DD;
        memset(&DD, 0, sizeof(DD));
        if(!HEIReadDeviceDef(&aDevices[0], (BYTE *)&DD, sizeof(DD)))
          {
          if(DD.ModuleType != 1)
            {
            if(QueryType == QT_ID)
              printf("Module number %u is not an Hx-ENET. Cannot continue...\n", ID);
            else
              printf("Module %s is not an Hx-ENET. Cannot continue...\n", Name);
            }
          else
            {
            /*
            ** Step 6, do the CCM transaction(s)
            **
            ** There are two different ways to execute CCM and KSeq transactions, blocking
            ** and non-blocking. In blocking mode, you make a single call to HEICCMRequest
            ** to perform the operation. All timeouts and retries are handled by the driver.
            ** Unfortunately, you are limited to one transaction at a time using blocking
            ** mode. In non-blocking mode, the call to HEICCMRequest starts the process and returns
            ** immediately. The user must then call HEIGetResponse to get the ack and the response
            ** or until timing out. The user may call HEICCMRequest on many different devices
            ** while waiting for responses. This provides much higher throughput in systems
            ** with many Hx-ENET devices. This demo uses the non-blocking mode. This code doesn't
            ** fully implement all of the nuances of non-blocking mode. We will be creating a more
            ** elaborate demo to fully illustrate the technique.
            */

            // Set to non-blocking mode
            aDevices[0].ParallelPackets = TRUE;            

            // Send CCM request
            StartTime = timeGetTime();
            Done = FALSE;
	    Acked = FALSE;
            Error = HEICCMRequest(&aDevices[0], Writing, DataType, DataAddress, DataLen, DataBuff);

            /*
            ** If you intended to talk to other devices you could send more requests here...
            */

            if(Error == HEIE_NO_RESPONSE)
              {
              // Get CCM ack first. Timeout can be short.
              do
                {
                switch(CCMAck(&aDevices[0]))
                  {
                  case cacWaiting:
                    // Keep waiting...
                    break;

                  case cacNak:
                    // Nak can occur when the module queues are full
                    // Ideally you would want to try back a few times.
                    // For this demo we're just bailing out.
                    printf("Error! CCM request was NAKed.\n");
                    Done = TRUE;
                    break;

                  case cacAck:
                    // Got the ack. Get the actual response now.
                    // Timeout is an app level timeout and mus allow
                    // the PLC to do its thing.
                    StartTime = timeGetTime();
                    Done = TRUE;
                    Acked = TRUE;
                    break;

                  default:
                    Done = TRUE;
                    printf("Error! Unable to get CCM response.\n");
                    break;
                  }

                // Timeout should accomodate network load and master
                // system performance
                } while(!Done && (timeGetTime() - StartTime < 25));

              /*
              ** You could send additional requests to the current device here.
              ** Always wait for the Ack before doing more though.
              */
              
              Done = FALSE;

              // If we got acked, get the actual response
              if(Acked)
                {
                do
                  {
                  switch(CCMResponse(&aDevices[0], DataBuff, DataLen))
                    {
                    case HEIE_NO_RESPONSE:
                      // Keep waiting...
                      break;

                    case HEIE_NULL:
                      {
                      if(Writing)
                        {
                        if(QueryType == QT_ID)
                          printf("Wrote %d bytes to device number %u, type 0x%02x, address 0x%04X", (int)DataLen, ID, (int)DataType, (unsigned)DataAddress);
                        else
                          printf("Wrote %d bytes to device %s, type 0x02%x, address 0x%04X", (int)DataLen, Name, (int)DataType, (unsigned)DataAddress);
                        }
                      else
                        {
                        if(QueryType == QT_ID)
                          printf("Read %d bytes from device number %u, type 0x%02x, address 0x%04X --> ", (int)DataLen, ID, (int)DataType, (unsigned)DataAddress);
                        else
                          printf("Read %d bytes from device %s, type 0x02%x, address 0x%04X --> ", (int)DataLen, Name, (int)DataType, (unsigned)DataAddress);
    
                        for(idx = 0; idx < DataLen; idx++)
                          printf("%02X ", DataBuff[idx]);
                        }

                      printf("\n");
                      Done = TRUE;
                      }
                      break;
                    
                    default:
                      Done = TRUE;
                      printf("Error! Unable to get CCM response.\n");
                      break;
                    }

                  // This implements a 250 ms timeout. The actual timeout should be
                  // long enough to accomodate the maximum PLC scan time * 2 + 5 to 10 ms
                  } while(!Done && (timeGetTime() - StartTime < 250));

                if (!Done)
                  printf("Timeout waiting for response!\n");
                }
              }
            else
              printf("Error! Unable to send CCM request.\n");
            }
          }
        else
          {
          printf("Error! Unable to read device def.\n");
          }
        
        /*
        ** Step 7, close the device
        */
        HEICloseDevice(&aDevices[0]);
        }
      else
        {
        printf("Error! Unable to open device %02X%02X%02X%02X%02X%02X\n", 
          aDevices[0].ENetAddress[0], aDevices[0].ENetAddress[1], aDevices[0].ENetAddress[2], 
          aDevices[0].ENetAddress[3], aDevices[0].ENetAddress[4], aDevices[0].ENetAddress[5]);
        }
      }
    else
      {
      printf("Sorry! No ethernet devices found\n");
      }

    /*
    ** Step 8, terminate the transport
    */
    HEICloseTransport(&TP);
    }
  else
    {
    printf("Error! Unable to initialize Transport\n");
    }

  /*
  ** Step 9, terminate the driver
  ** Called once by app at shutdown
  */
  HEIClose();
  }





