Knowledge Base Nr: 00204 XPort.cpp - http://www.swe-kaiser.de

Downloads:

MFC: Sockets; Lantronix XPort Lesen und Schreiben GPIO Interface

  
//www.lantronix.com
//ACHTUNG: nach CAsyncSocket::Create()/Connect() muss die messageloop ausgeführt werden!

CAsyncSocket* g_pClient = 0;

BOOL CXporttestDlg::OnInitDialog()
{
...
GetDlgItem(IDC_STATUS)->SetWindowText("Init...");

GetDlgItem(IDC_IP)->SetWindowText("192.168.32.123");
g_pClient = new CAsyncSocket();

if (g_pClient->Create() == 0)
{
GetDlgItem(IDC_STATUS)->SetWindowText("Error creating client socket.");
return TRUE;
}

CString strIP;
GetDlgItem(IDC_IP)->GetWindowText(strIP);

const int PORT= 0x77F0;

if (!g_pClient->Connect(strIP, PORT))
{
int nErr = g_pClient->GetLastError();
if(nErr != WSAEWOULDBLOCK)
{
g_pClient->Close();

GetDlgItem(IDC_STATUS)->SetWindowText("Error connecting to server.");
return TRUE;
}
}

GetDlgItem(IDC_STATUS)->SetWindowText("Init OK!");
...
}

void CXporttestDlg::OnGet()
{
GetDlgItem(IDC_STATUS)->SetWindowText("Send...");

unsigned char buffer[] = { 0x13, 0,0,0,0, 0,0,0,0 };

int nSend = g_pClient->Send(buffer, sizeof(buffer));
if (nSend == SOCKET_ERROR)
{
GetDlgItem(IDC_STATUS)->SetWindowText("Error sending to server.");
return;
}

Sleep(50);

unsigned char buffer2[20] = {0};
int nRecv = g_pClient->Receive(buffer2, sizeof(buffer2));
if (nRecv != 5)
{
GetDlgItem(IDC_STATUS)->SetWindowText("Error reading from server.");
return;
}

CheckDlgButton(IDC_GPIO0, (buffer2[1]&0x01) ? 1 : 0);
CheckDlgButton(IDC_GPIO1, (buffer2[1]&0x02) ? 1 : 0);
CheckDlgButton(IDC_GPIO2, (buffer2[1]&0x04) ? 1 : 0);

GetDlgItem(IDC_STATUS)->SetWindowText("OK!");
}

void CXporttestDlg::OnSet()
{
GetDlgItem(IDC_STATUS)->SetWindowText("Send...");

unsigned char nValue = 0;
if (IsDlgButtonChecked(IDC_GPIO0))
nValue |= 0x01;
if (IsDlgButtonChecked(IDC_GPIO1))
nValue |= 0x02;
if (IsDlgButtonChecked(IDC_GPIO2))
nValue |= 0x04;

unsigned char buffer[] = { 0x1b, 0xcc, 0,0,0, 0xcc,0,0,0 };
buffer[1] = 0x07;
buffer[5] = nValue;

int nSend = g_pClient->Send(buffer, sizeof(buffer));
if (nSend == SOCKET_ERROR)
{
GetDlgItem(IDC_STATUS)->SetWindowText("Error sending to server.");
return;
}

Sleep(50);

unsigned char buffer2[20] = {0};
int nRecv = g_pClient->Receive(buffer2, sizeof(buffer2));
if (nRecv != 5)
{
GetDlgItem(IDC_STATUS)->SetWindowText("Error reading from server.");
return;
}

GetDlgItem(IDC_STATUS)->SetWindowText("OK!");
}

void CXporttestDlg::OnClose()
{
g_pClient->Close();

delete g_pClient;
g_pClient = 0;

CDialog::OnClose();
}