#include	"stdafx.h"
#include	"Globals.h"
//
int					gDeviceNumber;
int					gDataRate;
int					gTimeouts;
COM20020_CONFIG		gCfg;
SRVR_CONFIG			gSrvrCfg;
CString				gHostname;
int					gHostPort;
bool				gInitialized;
//
int					gNodeID;
struct in_addr		host_ip_address;
//
// Helper functions.
//
// Here to read a register from the USB22.
//
short regRead( unsigned char regNum )
{
	long				lResult;
	COM20020_REGISTER	reg;

	reg.bWrite = 0;
	reg.byRegister = regNum;
	lResult = Com20020Register( &reg );
	if ( lResult == 0 )
		return reg.byValue;
	else
		return -1;
}
//
// Here to write to a USB22 register.
//
short regWrite( unsigned char regNum , unsigned char val )
{
	COM20020_REGISTER	reg;

	reg.bWrite = 1;
	reg.byRegister = regNum;
	reg.byValue = val;
	return Com20020Register( &reg );
}
//
// Here to read from a sub-addressed register.
//
short regSubRead( unsigned char regNum )
{
	// Write to sub-address register.
	regWrite( REG_SUBADR , regNum );
	// Return with value.
	return regRead( REG_SUBVAL );
}
//
// Here to write to one of the sub-addressed registers.
//
short regSubWrite( unsigned char regNum , unsigned char val )
{
	// Write to sub-address register.
	regWrite( REG_SUBADR , regNum );
	// Write value.
	return regWrite( REG_SUBVAL , val );
}
//
// Here to dump packets to a file.
//
void writePacket( FILE *fp , COM20020_RECEIVE_BUFFER *rxb )
{
	int		i;

	fprintf(fp, "Received Packet:\n\n" );
	fprintf(fp, "Source ID: %02x\n", rxb->bySourceNodeID );
	fprintf(fp, "Destination ID: %02x\n",  rxb->byDestinationNodeID );
	fprintf(fp, "Packet Length: %03x", rxb->uiNumberOfBytes );
	for (i=0; i<rxb->uiNumberOfBytes; i++)
	{
		if (!(i % 16) && (i != rxb->uiNumberOfBytes))
			fprintf(fp, "\n[%03X]:", i);
		fprintf(fp, "%02X ", rxb->byDataBuffer[i]);
	}
	fprintf(fp, "\n\n");
}
//
void writePacket( FILE *fp , COM20020_TRANSMIT_BUFFER *txb )
{
	int		i;

	fprintf(fp, "Transmitted Packet:\n\n" );
	fprintf(fp, "Destination ID: %02x\n",  txb->byDestinationNodeID );
	fprintf(fp, "Packet Length: %03x", txb->uiNumberOfBytes );
	for (i=0; i<txb->uiNumberOfBytes; i++)
	{
		if (!(i % 16) && (i != txb->uiNumberOfBytes))
			fprintf(fp, "\n[%03X]:", i);
		fprintf(fp, "%02X ", txb->byDataBuffer[i]);
	}
	fprintf(fp, "\n\n");
}
