You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

149 lines
2.7 KiB

/////////////////////////////////////////////////////////////////////////////////
//
// nwthread.cc is part of TestModbus-Client.
//
/////////////////////////////////////////////////////////////////////////////////
#include <errno.h>
#include <glib.h>
#include <sys/time.h>
#include <string>
#include <string.h>
#if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#else
#include <unistd.h> /* close() */
#endif
#include "tcp.h"
#include "nwthread.h"
#include "client.h"
extern NetworkThread netthread;
// c / C++ wrapper
gpointer _Thread (gpointer data) {
netthread.Thread ();
return NULL;
};
NetworkThread::NetworkThread() {
g_mutex_init (&mutex);
thread = NULL;
state = 0;
host = "";
port = "";
};
NetworkThread::~NetworkThread() {
Disconnect();
g_mutex_clear(&mutex);
};
void NetworkThread::Lock() {
g_mutex_lock(&mutex);
};
void NetworkThread::UnLock() {
g_mutex_unlock(&mutex);
};
/*
* start network thread and connect
*/
int NetworkThread::Connect(std::string dest_host, std::string dest_port) {
printf ("%s:%d NetworkThread::Connect to %s:%s\n", __FILE__, __LINE__, dest_host.c_str(), dest_port.c_str());
//
// if there is an open connection close this one first
if (GetState() != NWT_nothing) Disconnect();
host = dest_host;
port = dest_port;
thread = g_thread_new("network thread", _Thread, NULL);
return -1;
};
/*
* stop network connection
*/
int NetworkThread::Disconnect() {
printf ("%s:%d NetworkThread::Disconnect\n", __FILE__, __LINE__);
Lock();
if (state != NWT_nothing) state = NWT_close;
UnLock();
while (GetState() != NWT_nothing) { usleep(1000); };
if (thread != NULL) g_thread_unref(thread);
thread = NULL;
return 0;
};
void NetworkThread::SetState(int s) {
Lock();
state = s;
UnLock();
};
int NetworkThread::GetState() {
int s;
Lock();
s = state;
UnLock();
return s;
};
void NetworkThread::ClientSendStatustext(char *txt) {
char *msg = NULL;
if (txt) {
int l = strlen (txt)+1;
msg = (char*) malloc(l+1);
memset (msg, 0x0, l+1);
strncpy (msg, txt, strlen (txt));
}
gdk_threads_add_idle(mbcli_thread_cb_status, msg);
}
void NetworkThread::Thread() {
printf ("%s:%d NetworkThread::Thread Started\n", __FILE__, __LINE__);
TCP tcp;
ClientSendStatustext((char*)"connecting");
SetState (NWT_connect);
if (tcp.Connect(host, port) != 1) {
ClientSendStatustext(strerror(errno));
}
else {
//
// destination host and port should be set already
SetState(NWT_running);
while (GetState() == NWT_running) {
ClientSendStatustext((char*)"connected");
usleep (1000);
}
if(GetState() == NWT_close) {
ClientSendStatustext((char*)"");
}
}
SetState(NWT_nothing);
ClientSendStatustext(NULL);
printf ("%s:%d NetworkThread::Thread Finished\n", __FILE__, __LINE__);
};