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

typedef int		BOOL;
typedef unsigned char	BYTE;
typedef unsigned short	WORD;
typedef unsigned long	DWORD;
#define FALSE 0
#define TRUE 1

#pragma warning(disable:4103)

#include "hei.h"

#define MAX_DEVICES	20

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

class CModule
	{
	public:
		CModule();

		void Init(BYTE Type, BYTE ID, BYTE X, BYTE Y, BYTE WX, BYTE WY);

		void SetXState(BYTE *pX, int Len){ memcpy(X, pX, Len); }
		void SetYState(BYTE *pY, int Len){ memcpy(Y, pY, Len); }
		void SetWXState(WORD *pWX, int Len){ memcpy(WX, pWX, Len*2); }
		void SetWYState(WORD *pWY, int Len){ memcpy(WY, pWY, Len*2); }
		
		BOOL IsIn(){ return XCount || WXCount; }
		BOOL IsOut(){ return YCount || WYCount; }
		BOOL IsDiscrete(){ return XCount || YCount; }
		BOOL IsAnalog(){ return WXCount || WYCount; }
		BOOL GetInBit(int BitNum){ return X[BitNum/8] & (0x01<<(BitNum%8)); }
		void SetInBit(int BitNum, BOOL Val){ X[BitNum/8] = X[BitNum/8] & ~(0x01<<(BitNum%8)) | (Val ? (0x01<<(BitNum%8)) : 0); }
		BOOL GetOutBit(int BitNum){ return Y[BitNum/8] & (0x01<<(BitNum%8)); }
		void SetOutBit(int BitNum, BOOL Val){ Y[BitNum/8] = Y[BitNum/8] & ~(0x01<<(BitNum%8)) | (Val ? (0x01<<(BitNum%8)) : 0); }

		BYTE Type;
		BYTE ID;
		
		BYTE XCount;
		BYTE YCount;
		BYTE WXCount;
		BYTE WYCount;

		BYTE X[8];
		BYTE Y[8];
		WORD WX[8];
		WORD WY[8];
	};

CModule::CModule()
	{
	Type			= 0;
	ID				= 0;

	XCount		= 0;
	YCount		= 0;
	WXCount		= 0;
	WYCount		= 0;

	memset(X, 0, sizeof(X));
	memset(Y, 0, sizeof(Y));
	memset(WX, 0, sizeof(WX));
	memset(WY, 0, sizeof(WY));
	}

void CModule::Init(BYTE iType, BYTE iID, BYTE iX, BYTE iY, BYTE iWX, BYTE iWY)
	{
	Type			= iType;
	ID				= iID;
	XCount		= iX;
	YCount		= iY;
	WXCount		= iWX;
	WYCount		= iWY;
	}

CModule aModules[8];

void ParseBaseDefPacket(BYTE *pBaseDef)
	{
	BOOL Done = FALSE;
	int Slot = -1;

	// Determine slot contents
	for(int idx = 0; !Done; idx++)
		{
		switch(pBaseDef[idx] & 0xF0)
			{
			// Select slot
			case 0x00:
				Slot = pBaseDef[idx] & 0x0F;
				break;

			// Module def
			case 0x10:
				// Type 1 is normal I/O
				if(pBaseDef[idx+1] == 1)
					aModules[Slot].Init(pBaseDef[idx+1], pBaseDef[idx+2], pBaseDef[idx+3], 
														pBaseDef[idx+4], pBaseDef[idx+5], pBaseDef[idx+6]);
				else
					aModules[Slot].Init(pBaseDef[idx+1], pBaseDef[idx+2], 0,0,0,0);

				idx += 2 + pBaseDef[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0x20:
				idx += pBaseDef[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0x30:
			case 0x40:
				idx += pBaseDef[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0x50:
			case 0x60:
				idx += (pBaseDef[idx] & 0x0F)*2;
				break;

			// Unexpected, but parse anyway
			case 0x70:
			case 0x80:
			case 0x90:
			case 0xA0:
			case 0xB0:
			case 0xC0:
			case 0xD0:
				idx += pBaseDef[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0xE0:
				idx += 2 + pBaseDef[idx+2];
				break;

			// Finished
			case 0xF0:
				Done = TRUE;
				break;
			}
		}
	}

void ParseReadIOPacket(BYTE *pInBuff)
	{
	BOOL Done = FALSE;
	int Slot = -1;

	// Parse input data
	for(int idx = 0; !Done; idx++)
		{
		switch(pInBuff[idx] & 0xF0)
			{
			// Select slot
			case 0x00:
				Slot = pInBuff[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0x10:
				idx += 2 + pInBuff[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0x20:
				idx += pInBuff[idx] & 0x0F;
				break;

			// Discrete in
			case 0x30:
				if(Slot != -1)
					aModules[Slot].SetXState(pInBuff+idx+1, pInBuff[idx] & 0x0F);

				idx += pInBuff[idx] & 0x0F;
				break;

			// Discrete out
			case 0x40:
				if(Slot != -1)
					aModules[Slot].SetYState(pInBuff+idx+1, pInBuff[idx] & 0x0F);

				idx += pInBuff[idx] & 0x0F;
				break;

			// Word in
			case 0x50:
				if(Slot != -1)
					aModules[Slot].SetWXState((WORD *)(pInBuff+idx+1), pInBuff[idx] & 0x0F);

				idx += (pInBuff[idx] & 0x0F)*2;
				break;

			// Word out
			case 0x60:
				if(Slot != -1)
					aModules[Slot].SetWYState((WORD *)(pInBuff+idx+1), pInBuff[idx] & 0x0F);

				idx += (pInBuff[idx] & 0x0F)*2;
				break;

			// Unexpected, but parse anyway
			case 0x70:
			case 0x80:
			case 0x90:
			case 0xA0:
			case 0xB0:
			case 0xC0:
			case 0xD0:
				idx += pInBuff[idx] & 0x0F;
				break;

			// Unexpected, but parse anyway
			case 0xE0:
				idx += 2 + pInBuff[idx+2];
				break;

			// Complete
			case 0xF0:
				Done = TRUE;
				break;
			}
		}
	}

void PrintBaseState()
{
	for(int Slot = 0; Slot < 8; Slot++)
		{
		CModule *pMod = &aModules[Slot];
		printf("\nSlot = %d\n", Slot);
		printf("Module type = %d\n", pMod->Type);
		printf("Module ID = %02X\n", pMod->ID);

		if(pMod->XCount)
			{
			printf("X Status = ");
			for(int idx = 0; idx < pMod->XCount; idx++)
				printf("%d", (int)pMod->GetInBit(idx));
			printf("\n");
			}

		if(pMod->YCount)
			{
			printf("Y Status = ");
			for(int idx = 0; idx < pMod->YCount; idx++)
				printf("%d", (int)pMod->GetOutBit(idx));
			printf("\n");
			}

		if(pMod->WXCount)
			{
			printf("WX Status = ");
			for(int idx = 0; idx < pMod->WXCount; idx++)
				printf("%04X ", (DWORD)pMod->WX[idx]);
			printf("\n");
			}

		if(pMod->WYCount)
			{
			printf("WY Status = ");
			for(int idx = 0; idx < pMod->WYCount; idx++)
				printf("%04X ", (DWORD)pMod->WY[idx]);
			printf("\n");
			}
		}
}

int main(int argc, char *argv[])
	{
	WORD Protocol = HEIP_IP;
	DWORD ID = 0;
	char Name[256] = "";
	int QueryType = QT_ID;

	printf("EtherIO - Copyright(C) 1997, Host Engineering, Inc.\n");
	printf("Executes IO transaction on specified Hx-EBC device\n\n");

	/*
	** Parse command line
	*/
	for(int 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 'h':
				case 'H':
				case '?':
					printf("Usage - EtherIO [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("  /?   This screen\n");
					return(0);

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

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

	HEIDevice aDevices[MAX_DEVICES];
	memset(aDevices, 0, sizeof(aDevices));

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

	/*
	** Step 2, initialize the transport
	*/
	TP.Transport = HEIT_UNIX; // Under Win32 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. We'll use only the first device and
			** ignore the others.
			*/
			if(!HEIOpenDevice(&TP, &aDevices[0], HEIAPIVERSION, 25, 3, FALSE))
				{
				/*
				** Step 5, confirm that it is an Hx-EBC. A more correct way to do this
				** would be to read the module caps (HEIReadSupportInfo) and test 
				** for the functions we wish to use; I'm lazy.
				*/
				DeviceDef DD;
				memset(&DD, 0, sizeof(DD));
				if(!HEIReadDeviceDef(&aDevices[0], (BYTE *)&DD, sizeof(DD)))
					{
					if(DD.ModuleType != 0)
						{
						if(QueryType == QT_ID)
							printf("Module number %u is not an Hx-EBC. Cannot continue...\n", ID);
						else
							printf("Module %s is not an Hx-EBC. Cannot continue...\n", Name);
						}
					else
						{
						// 2K is plenty enough
						BYTE Data[2000];
						WORD SizeofData = sizeof(Data);

						/*
						** Step 6, optional. Sometime during configuration you can use this 
						** operation to automatically determine whats in the base. This is not a
						** requirement, but it adds a nice capability that many I/O systems
						** don't have.
						*/
						if(!HEIReadBaseDef(&aDevices[0], Data, &SizeofData))
							{
							// Parse the base def response
							ParseBaseDefPacket(Data);

							/*
							** Step 7, do the IO transactions. You'll do this one about
							** 10^zillionth times. You can use HEIReadIO and HEIWriteIO separately
							** if your system dictates that. You can also use HEIWriteIO alone; it
							** returns the input state (HEIReadIO) in the response packet.
							*/
							SizeofData = sizeof(Data);
							if(!HEIReadIO(&aDevices[0], Data, &SizeofData))
								{
								// Parse the read IO response
								ParseReadIOPacket(Data);

								// Print the base state
								PrintBaseState();
								}
							else
								{
								printf("Error! Unable to read IO.\n");
								}
							}
						else
							{
							printf("Error! Unable to read base def.\n");
							}
						}
					}
				else
					{
					printf("Error! Unable to read device def.\n");
					}
				
				/*
				** Step 8, 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 9, terminate the transport
		*/
		HEICloseTransport(&TP);
		}
	else
		{
		printf("Error! Unable to initialize Transport\n");
		}

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





