Knowledge Base Nr: 00205 XPort2.cpp - http://www.swe-kaiser.de
Downloads:
MFC: Socket-Klasse: Lantronix XPort
//www.lantronix.com
//////////////////////////////////////////
//definition
class CXPortSupport : public CAsyncSocket
{
public:
CXPortSupport(const char* lpszIP);
virtual ~CXPortSupport();
int Init(); //<0:error 0:ok
int GetGPIO(); //<0:error >=0:value
int SetGPIO(int nValue); //<0:error 0:ok
protected:
CString m_strIP;
bool m_bConnected;
int DoGPIOCmd(unsigned char* bufferIn, unsigned char* bufferOut);
};
//////////////////////////////////////////
//sample
void CXporttestDlg::OnToggle()
{
CXPortSupport xport("192,168,32,123");
int nErr = xport.Init();
if (nErr)
return;
int nValue = xport.GetGPIO(); //lesen...
if (nValue<0)
return;
nValue = (~nValue)&0x07;
nErr = xport.SetGPIO(nValue); //...alle bits umdrehen...
if (nErr)
return;
nValue = xport.GetGPIO(); //...zurücklesen
if (nValue<0)
return;
CheckDlgButton(IDC_GPIO0, (nValue&0x01) ? 1 : 0);
CheckDlgButton(IDC_GPIO1, (nValue&0x02) ? 1 : 0);
CheckDlgButton(IDC_GPIO2, (nValue&0x04) ? 1 : 0);
}
//////////////////////////////////////////
//implemetierung
#define PORT_GPIO 0x77F0
#define CMDLEN_BUFFERIN 9
#define CMDLEN_BUFFEROUT 5
#define WAITFORANSWER 30
CXPortSupport::CXPortSupport(const char* lpszIP)
{
m_strIP = lpszIP;
}
CXPortSupport::~CXPortSupport()
{
Close();
}
int CXPortSupport::Init()
{
if (Create(PORT_GPIO, SOCK_DGRAM) == 0)
{
TRACE("CXPortSupport: Error creating client socket.\n");
return -1;
}
if (!Connect(m_strIP, PORT_GPIO))
{
int nErr = GetLastError();
if (nErr != WSAEWOULDBLOCK)
{
Close();
TRACE("Error connecting to server.");
return -1;
}
}
return 0;
}
int CXPortSupport::GetGPIO()
{
unsigned char bufferIn[] = { 0x13, 0,0,0,0, 0,0,0,0 };
unsigned char bufferOut[20] = {0};
int nErr = DoGPIOCmd(bufferIn, bufferOut);
if (nErr)
return nErr;
return bufferOut[1];
}
int CXPortSupport::SetGPIO(int nValue)
{
unsigned char bufferIn[] = { 0x1b, 0x07,0,0,0, 0,0,0,0 };
unsigned char bufferOut[20] = {0};
bufferIn[5] = (unsigned char)nValue&0xff;
int nErr = DoGPIOCmd(bufferIn, bufferOut);
if (nErr)
return nErr;
return 0;
}
int CXPortSupport::DoGPIOCmd(unsigned char* bufferIn, unsigned char* bufferOut)
{
int nSend = Send(bufferIn, CMDLEN_BUFFERIN);
if (nSend == SOCKET_ERROR)
{
TRACE("CXPortSupport: Error sending to server.\n");
return -2;
}
Sleep(WAITFORANSWER);
int nRecv = Receive(bufferOut, 2*CMDLEN_BUFFEROUT);
if (nRecv != CMDLEN_BUFFEROUT)
{
TRACE("CXPortSupport: Error reading from server.\n");
return -3;
}
return 0;
}