Hi,
I am trying to re-coding a programme which was compiled for VC++ (windows), this included a file winshok2.h!
In Ubuntu winsock.2 is not supported.
When I comment out the (//#include <winsock2.h>) winsock2.h and compilled in G++ then few errors come with the 2nd file (client socket header file)in relation with following section.
<private:
WSAData wsaData;
SOCKET sd; >
I know this is normal as winsock2 is not for Ubuntu.
Is there any one who can help me that how I can re-code the first programme with XML RPC++ (may be I can use XML RPC++ client and socket files;but not sure how to do as i am newbi at C++ and Linux environment).
Please I need this badly.
Thanks in advance.
Regards-Mamun
mail to me: mamunk2@gmail.com
I am giving the 3 codes here and first one is the main cpp
int desSamplingRate = 0;
int desProgram = -1;
unsigned int ui_TCPPort = 50002;
#ifdef _DEBUG
FILE *ErrorLog;
#endif
int SetFrontendData(T_FrontendData *p_FrontendData);
int SetTrigger(int Mode);
int StopLiveImageServer (void);
int StartLiveImageServer (int i_Port, char*pIP);
int Disconnect (void);
int Connect (char *pIP, unsigned int iXMLPort);
void ShowUsageStr(string prog);
int SetProgram(int i_Val);
int GetTCPPort();
int TriggerImage();
int SetMedianFilterStatus(int status);
int SetExponentialFilterStatus(int status);
int SetAdaptiveMeanFilterStatus (int status);
int SetMeanFilterStatus(int status);
int main(int argc, char* argv[])
{
timeb _timestruct;
long StartTime = 0;
long EndTime = 0;
long NowTime = 0;
T_FrontendData data;
int i_ActiveProduct=-1;
int i;
char *str_IP;
int triggerMode = -1;
int i_xmlport = 0;
int i_NumberOfImages = 0;
string FileName;
FILE *DataFile;
int iEnableMedianFilter = 0;
int iEnableExponentialFilter = 0;
int iEnableMeanValueFilter = 0;
int iEnableAdaptiveMeanFilterStatus = 0;
int i_TempIOC = -1;
int i_TempFrontend = -1;
int size = sizeof(float)*64*50;
int i_SampleMode = -1;
char strDataSendCommand[20];; // max 19 images...
int AmountOfImages = 0;
float *sourceBuffer;
T_IMAGEHEADER header;
int headersize = sizeof(T_IMAGEHEADER)/sizeof(float);
double MeanSum;
if (i_NumberOfImages > 0)
{
StartLiveImageServer(ui_TCPPort, str_IP);
DataFile = fopen(FileName.c_str(),"wb");
if (DataFile == NULL)
{
Disconnect();
return -1;
}
// alloc all memory...
pf_ImageBuffer = new float[64*50+sizeof(T_IMAGEHEADER)/sizeof(float)];
pf_finalImageBuffer = new float[64*50+sizeof(T_IMAGEHEADER)/sizeof(float)];
}
else
DataFile = NULL;
int i_commandSize = 0;
long OldImageTimeStamp = 0;
XmlRpcValue args, result;
int WriteFlag;
long Zykluszeit = 1000/data.i_samplingRate;
for (int images = 0; images < i_NumberOfImages; images++)
{
//fetch time stamp
ftime (&_timestruct);
StartTime = _timestruct.time*1000+_timestruct.millitm;
if (triggerMode == 4) // software trigger mode
{
TriggerImage();
}
else
{
// wann kommt das naechste Bild?? Keine Ahnung, deswegen danach ziemlich schnell pollen.
Sleep(1);
}
if (pImageServerClientSocket != NULL )
{
try
{
pImageServerClientSocket->sendData(AmountOfImages+1,strDataSendCommand);
}
catch (SocketClosedException e)
{
#ifdef _DEBUG
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
printf("Error occured SocketClosedException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fprintf(ErrorLog,"Error occured SocketClosedException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fclose(ErrorLog);
#endif
if (WriteFlag)
{
fwrite(&header,sizeof(T_IMAGEHEADER),1,DataFile);
r1 = 0;
r2 = 0;
u1 = (char*)&r1;
u2 = (char*)&r2;
MeanSum = 0;
/* convert the binary/float data to little endian */
for (int p = 0; p < 64*50; p++)
{
r1 = pf_ImageBuffer[p+headersize];
#ifdef _DEBUG
if (pXmlClient->isFault())
{
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
fprintf(ErrorLog,"Error occured MDAXMLConnectCP: at time %s\n",ctime(¤tTime));
fclose(ErrorLog);
}
#endif
}
return CPCOMM3D_NO_ERRORS;
}
/*!
* Transmit the frontend data to the sensor
*/
int SetFrontendData(T_FrontendData *p_FrontendData)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
if (!pXmlClient->execute ("MDAXMLSetTrigger", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
cout << "TriggerMode " << Mode << endl;
return result[0];
}
/*!
* Sets the sensor Program
*/
int SetProgram(int i_Val)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[2] = (int)(i_Val);
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetProgram", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Get the TCP-Data port number
*/
int GetTCPPort()
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue noargs, result;
result [0] = -1;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLGetTCPPortCP", noargs, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
/* send the y values */
ui_TCPPort = (int)(result[1]);
return result[0];
}
/*!
* Enable/Disable the Median Filter
*/
int SetMedianFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetMedianFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
/*!
* Enable/Disable the Adaptive Mean Filter
*/
int SetAdaptiveMeanFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetAdaptiveMeanValueFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
/*!
* Trigger an Image
*/
int TriggerImage()
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue noargs, result;
result [0] = -1;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLTriggerImage", noargs, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Enable/Disable the Mean Filter
*/
int SetMeanFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetMeanFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
/*!
* Enable/Disable the Exponential filter
*/
int SetExponentialFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetExponentialFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
/*!
* @brief Client socket exception.
*/
class SocketException
{
public:
/*!
* @param s
* Descriptive string for the exception.
*/
SocketException ( std::string s, int error ) : m_s ( s ),m_error(error) {};
~SocketException (){};
/*!
* @brief Get description string
* @return Descriptive string of the exception.
*/
std::string description()
{
return m_s;
};
int error()
{
return m_error;
};
private:
std::string m_s;
int m_error;
};
/*!
* @brief Client socket closed exception
*/
class SocketClosedException : public SocketException
{
public:
/*!
* @param s
* Descriptive string for the exception.
*/
SocketClosedException ( std::string s ) : SocketException(s,0) {};
};
/*!
* @brief Client socket
*/
class ClientSocket
{
public:
/*!
* @brief Client socket initialization.
* @param ipaddr
* IP address to connect to.
* @param port
* TCP/IP port to use, e.g. "127.0.0.1"
*/
ClientSocket(const char* addr, int port);
~ClientSocket();
void sendData(int byte_size, const void* data);
/*!
* @brief receive a data frame.
* @param frame_byte_size
* Number of bytes in the frame.
* @param buffer
* Buffer to save frame to.
* @throws SocketException
*/
int ReceiveFrame(int frame_byte_size, char *buffer);
/*! Receive a 4 byte integer.
@throws SocketException
*/
int ReceiveInt(int &toRec);
/*! Receive a 2 byte unsigned short value.
@throws SocketException
*/
int ReceiveU16(unsigned short &toRec);
/*! \return The current state of the socket. */
bool isOK()
{
return _OK;
};
private:
WSAData wsaData;
SOCKET sd;
/*!
* @param nRemoteAddr
* IP address to connet to.
* @param nPort
* TCP/IP port to connect to.
* @return
* On success a descriptor referencing the new socket is return,
* INVALID_SOCKET else.
*
* Connects to a given address, on a given port, both of which must be
* in network byte order. Returns newly-connected socket if we succeed,
* or INVALID_SOCKET if we fail.
*/
SOCKET EstablishConnection(u_long nRemoteAddr, u_short nPort);
/*!
* Startup Windows socket and Establish connection
*/
ClientSocket::ClientSocket(const char* addr, int port)
{
int code = WSAStartup(MAKEWORD(1, 1), &wsaData);
sd = EstablishConnection(inet_addr(addr), htons(port));
_OK = (code == 0) && sd != INVALID_SOCKET;
}
/*!
* Shutdown connection and Windows socket.
*/
ClientSocket::~ClientSocket()
{
if (sd != INVALID_SOCKET) ShutdownConnection(sd);
WSACleanup();
}
/*!
* Send data with byte size.
*/
void ClientSocket::sendData(int byte_size, const void* data)
{
int ret = send(sd, (char*) data, byte_size, 0) ;
if (ret == SOCKET_ERROR)
{
int error = WSAGetLastError();
throw SocketException("send error",error);
}
}
/*!
* Build up a connection to Sensor.
* Create a socket and connect to Sensor.
*/
SOCKET ClientSocket::EstablishConnection(u_long nRemoteAddr, u_short nPort)
{
// Create a stream socket
SOCKET sd = socket(PF_INET, SOCK_STREAM, 0);
if (sd != INVALID_SOCKET)
{
sockaddr_in sinRemote;
sinRemote.sin_family = AF_INET;
sinRemote.sin_addr.s_addr = nRemoteAddr;
sinRemote.sin_port = nPort;
int r = connect(sd, (sockaddr*)&sinRemote, sizeof(sockaddr_in));
if (r == SOCKET_ERROR) sd = INVALID_SOCKET;
}
return sd;
}
/*!
* Gracefully shuts the connection sd down. Returns true if we're
* successful, false otherwise.
*/
bool ClientSocket::ShutdownConnection(SOCKET sd)
{
// Disallow any further data sends. This will tell the other side
// that we want to go away now. If we skip this step, we don't
// shut the connection down nicely.
// This function is only available for winsock2 sockets.
if (shutdown(sd, SD_SEND) == SOCKET_ERROR)
{
return false;
}
// Close the socket.
if (closesocket(sd) == SOCKET_ERROR)
{
return false;
}
return true;
}
/*!
* Receive an integer.
*/
int ClientSocket::ReceiveInt(int &toRec)
{
int res = ReceiveFrame(sizeof(int),(char*) &toRec);
toRec = ntohl(toRec);
return res;
}
/*!
* Receive an unsigned short (u16).
*/
int ClientSocket::ReceiveU16(unsigned short &toRec)
{
int res = ReceiveFrame(sizeof(unsigned short),(char*) &toRec);
toRec = ntohs(toRec);
return res;
}
/*!
* Receive a frame of given length and save it to buffer.
*/
int ClientSocket::ReceiveFrame(int frame_byte_size, char *buffer)
{
int total_bytes = 0;
while (total_bytes < frame_byte_size)
{
int new_bytes = recv(sd, buffer + total_bytes, frame_byte_size - total_bytes, 0);
if (new_bytes == SOCKET_ERROR)
{
int error = WSAGetLastError();
throw SocketException("receive error",error);
}
if (new_bytes == 0) throw SocketClosedException("connection closed by peer");
total_bytes += new_bytes;
}
return total_bytes;
}
/*--- END OF FILE -------------------------------------------------------*/
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
You need to remove or conditionally compile the Windows specific code, and in some places replace it with the equivalent linux code.
For example, replace the lines:
WSAData wsaData;
SOCKET sd;
with:
#if defined(_MSC_VER) // The next lines will only be compiled under MSVC++
WSAData wsaData;
SOCKET sd;
#else // The next lines will not be compiled under MSVC++
int sd; // sockets are represented as int on linux
#endif
Do this for all the lines with WSA... in them, that should get you started.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
The changes I suggested were not for the xmlrpc++ code, that compiles fine on linux (usually).
The changes were intended for his code, which used a mix of xmlrpc++ and winsock calls.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Hi,
I am trying to re-coding a programme which was compiled for VC++ (windows), this included a file winshok2.h!
In Ubuntu winsock.2 is not supported.
When I comment out the (//#include <winsock2.h>) winsock2.h and compilled in G++ then few errors come with the 2nd file (client socket header file)in relation with following section.
<private:
WSAData wsaData;
SOCKET sd; >
I know this is normal as winsock2 is not for Ubuntu.
Is there any one who can help me that how I can re-code the first programme with XML RPC++ (may be I can use XML RPC++ client and socket files;but not sure how to do as i am newbi at C++ and Linux environment).
Please I need this badly.
Thanks in advance.
Regards-Mamun
mail to me: mamunk2@gmail.com
I am giving the 3 codes here and first one is the main cpp
1)
/* $Id: o3dTestClient.cpp 6324 2008-02-07 16:01:54Z deegech $ */
#include <iostream>
#include <string>
#include <winsock2.h>
#include "clientsocket.h"
#include "CPcomm3dErrors.h"
#include "XmlRpc.h"
#include "structs.h"
#include "stdio.h"
#include "time.h"
#include "sys\timeb.h"
#if defined(_MSC_VER)
# pragma warning(disable:4996) // disable warnings
# pragma warning(disable:4244) // disable warnings
#endif
using namespace XmlRpc;
using namespace std;
// Global objects
XmlRpcClient *pXmlClient;
string OwnIpAddress;
ClientSocket* pImageServerClientSocket = NULL;
// data buffers
float *pf_ImageBuffer = NULL;
float *pf_finalImageBuffer = NULL;
int desSamplingRate = 0;
int desProgram = -1;
unsigned int ui_TCPPort = 50002;
#ifdef _DEBUG
FILE *ErrorLog;
#endif
int SetFrontendData(T_FrontendData *p_FrontendData);
int SetTrigger(int Mode);
int StopLiveImageServer (void);
int StartLiveImageServer (int i_Port, char*pIP);
int Disconnect (void);
int Connect (char *pIP, unsigned int iXMLPort);
void ShowUsageStr(string prog);
int SetProgram(int i_Val);
int GetTCPPort();
int TriggerImage();
int SetMedianFilterStatus(int status);
int SetExponentialFilterStatus(int status);
int SetAdaptiveMeanFilterStatus (int status);
int SetMeanFilterStatus(int status);
int main(int argc, char* argv[])
{
timeb _timestruct;
long StartTime = 0;
long EndTime = 0;
long NowTime = 0;
T_FrontendData data;
int i_ActiveProduct=-1;
int i;
char *str_IP;
int triggerMode = -1;
int i_xmlport = 0;
int i_NumberOfImages = 0;
string FileName;
FILE *DataFile;
int iEnableMedianFilter = 0;
int iEnableExponentialFilter = 0;
int iEnableMeanValueFilter = 0;
int iEnableAdaptiveMeanFilterStatus = 0;
int i_TempIOC = -1;
int i_TempFrontend = -1;
int size = sizeof(float)*64*50;
int i_SampleMode = -1;
char strDataSendCommand[20];; // max 19 images...
int AmountOfImages = 0;
float *sourceBuffer;
T_IMAGEHEADER header;
int headersize = sizeof(T_IMAGEHEADER)/sizeof(float);
double MeanSum;
if (argc > 1)
{
if (strcmp(argv[1], "-v") == 0)
{
#ifdef _DEBUG
cout << argv[0] << " Debug " << __DATE__ << " " << __TIME__ << " $Rev: 6324 $" << endl;
#else
cout << argv[0] << " " << __DATE__ << " " << __TIME__ << " $Rev: 6324 $" << endl;
#endif
exit(0);
}
}
#ifdef _DEBUG
cout << "argc " << argc <<endl;
#endif
switch (argc)
{
case 15:
iEnableMedianFilter = (atoi((char*)argv[11]) ? 1 : 0);
iEnableMeanValueFilter = (atoi((char*)argv[12]) ? 1 : 0);
iEnableExponentialFilter = (atoi((char*)argv[13]) ? 1 : 0);
iEnableAdaptiveMeanFilterStatus = (atoi((char*)argv[14]) ? 1 : 0);
case 11:
desProgram = atoi(argv[10]);
// no break;
case 10:
triggerMode = atoi(argv[9]);
// no break!!
case 9:
str_IP = (char*)argv[1];
i_xmlport = 8080;
data.i_samplingMode = (atoi((char*)argv[2]) ? 1 : 0);
data.i_integrationTimeSingle = atoi((char*)argv[3]);
data.i_integrationTimeDouble = atoi((char*)argv[4]);
data.i_samplingRate = atoi((char*)argv[5]);
desSamplingRate = atoi((char*)argv[5]);
i_NumberOfImages = atoi((char*)argv[6]);
for (unsigned i = 0; i < strlen(argv[7]); i++)
{
switch (argv[7][i])
{
case 'i':
case 'd':
case 'x':
case 'y':
case 'z':
case 'n':
case 'e':
case 'f':
case 'g':
case 's':
strDataSendCommand[i] = argv[7][i];
break;
default:
ShowUsageStr(argv[0]);
break;
}
AmountOfImages++;
strDataSendCommand[AmountOfImages] = 0;
}
FileName = string(argv[8]);
break;
default:
ShowUsageStr(argv[0]);
break;
}
if (Connect(str_IP,i_xmlport) != CPCOMM3D_NO_ERRORS)
{
return -1;
}
if (-1 != desProgram)
{
SetProgram(desProgram);
}
GetTCPPort();
SetFrontendData(&data);
if (-1 != triggerMode)
SetTrigger(triggerMode);
SetMedianFilterStatus (iEnableMedianFilter);
SetExponentialFilterStatus (iEnableExponentialFilter);
SetMeanFilterStatus (iEnableMeanValueFilter);
SetAdaptiveMeanFilterStatus (iEnableAdaptiveMeanFilterStatus);
if (i_NumberOfImages > 0)
{
StartLiveImageServer(ui_TCPPort, str_IP);
DataFile = fopen(FileName.c_str(),"wb");
if (DataFile == NULL)
{
Disconnect();
return -1;
}
// alloc all memory...
pf_ImageBuffer = new float[64*50+sizeof(T_IMAGEHEADER)/sizeof(float)];
pf_finalImageBuffer = new float[64*50+sizeof(T_IMAGEHEADER)/sizeof(float)];
}
else
DataFile = NULL;
int i_commandSize = 0;
long OldImageTimeStamp = 0;
XmlRpcValue args, result;
int WriteFlag;
long Zykluszeit = 1000/data.i_samplingRate;
for (int images = 0; images < i_NumberOfImages; images++)
{
//fetch time stamp
ftime (&_timestruct);
StartTime = _timestruct.time*1000+_timestruct.millitm;
if (triggerMode == 4) // software trigger mode
{
TriggerImage();
}
else
{
// wann kommt das naechste Bild?? Keine Ahnung, deswegen danach ziemlich schnell pollen.
Sleep(1);
}
if (pImageServerClientSocket != NULL )
{
try
{
pImageServerClientSocket->sendData(AmountOfImages+1,strDataSendCommand);
}
catch (SocketClosedException e)
{
#ifdef _DEBUG
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
printf("Error occured SocketClosedException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fprintf(ErrorLog,"Error occured SocketClosedException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fclose(ErrorLog);
#endif
// ReleaseMutex(LiveImageMutex);
return CPCOMM3D_SOCKET_LIVE_IMAGE;
}
catch (SocketException e)
{
#ifdef _DEBUG
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
fprintf(ErrorLog,"Error occured SocketException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fclose(ErrorLog);
#endif
// ReleaseMutex(LiveImageMutex);
return CPCOMM3D_GETTING_LIVE_IMAGE;
}
for (i = 0; i < AmountOfImages; i ++)
{
try
{
//get image from sensor
//cout << "Reading image Type " << strDataSendCommand[i] << " No " << images <<endl;
pImageServerClientSocket->ReceiveFrame(size+sizeof(T_IMAGEHEADER),(char*)pf_ImageBuffer);
}
catch (SocketClosedException e)
{
#ifdef _DEBUG
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
printf("Error occured SocketClosedException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fprintf(ErrorLog,"Error occured SocketClosedException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fclose(ErrorLog);
#endif
// ReleaseMutex(LiveImageMutex);
return CPCOMM3D_SOCKET_LIVE_IMAGE;
}
catch (SocketException e)
{
#ifdef _DEBUG
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
fprintf(ErrorLog,"Error occured SocketException: %s %i at time %s\n",e.description().c_str(),e.error(),ctime(¤tTime));
fclose(ErrorLog);
#endif
// ReleaseMutex(LiveImageMutex);
return CPCOMM3D_GETTING_LIVE_IMAGE;
}
float r1 = 0;
float r2 = 0;
char* u1 = (char*)&r1;
char* u2 = (char*)&r2;
// get images
sourceBuffer = pf_ImageBuffer;
for (int p = 0; p < sizeof(T_IMAGEHEADER)/sizeof(float); p++)
{
r1 = sourceBuffer[p];
u2[0] = u1[3];
u2[1] = u1[2];
u2[2] = u1[1];
u2[3] = u1[0];
((float*)&header)[p] = r2;
}
// received the same picture??
if (i == 0)
{
if (((triggerMode == 1) || (triggerMode == 2)) && (OldImageTimeStamp == 0))
{
#ifdef _DEBUG
cout << "First triggered picture" << endl;
#endif
images = -1;
WriteFlag = 0;
}
else if (header.Seconds*1000+header.Useconds == OldImageTimeStamp)
{
// last picture was the same, don't count it
images--;
WriteFlag = 0;
#ifdef _DEBUG
cout << "Same picture" << endl;
#endif
}
else
{
WriteFlag = 1;
// get image from sensor
cout << "Reading image No " << images << " current value " << header.CurrentValue << " error " <<header.ErrorCode <<endl;
#ifdef _DEBUG
cout << NowTime << endl;
#endif
}
}
OldImageTimeStamp = header.Seconds*1000+header.Useconds;
if (WriteFlag)
{
fwrite(&header,sizeof(T_IMAGEHEADER),1,DataFile);
r1 = 0;
r2 = 0;
u1 = (char*)&r1;
u2 = (char*)&r2;
MeanSum = 0;
/* convert the binary/float data to little endian */
for (int p = 0; p < 64*50; p++)
{
r1 = pf_ImageBuffer[p+headersize];
u2[0] = u1[3];
u2[1] = u1[2];
u2[2] = u1[1];
u2[3] = u1[0];
pf_finalImageBuffer[p] = r2;
MeanSum += r2;
}
//cout << "Sent: " << strDataSendCommand << " Got Type: " << header.ImageType << " Mean Value " << (MeanSum / (64*50)) << endl;
//cout << "Sent: " << strDataSendCommand << " Got Type: " << header.ImageType << " current value " << header.CurrentValue << " temp " << header.Temperature << " error " <<header.ErrorCode <<endl;
fwrite(pf_finalImageBuffer,size,1,DataFile);
}
}
}
if (triggerMode == 4)
{
ftime (&_timestruct);
EndTime = _timestruct.time*1000+_timestruct.millitm;
#ifdef _DEBUG
cout << Zykluszeit - EndTime + StartTime << endl;
#endif
if (Zykluszeit - EndTime + StartTime > 0)
Sleep(Zykluszeit - EndTime + StartTime);
}
}
if (i_NumberOfImages > 0)
{
fclose(DataFile);
StopLiveImageServer();
}
Disconnect();
if (pf_ImageBuffer != NULL)
{
delete[] pf_ImageBuffer;
pf_ImageBuffer = NULL;
}
if (pf_finalImageBuffer != NULL)
{
delete[] pf_finalImageBuffer;
pf_finalImageBuffer = NULL;
}
return 0;
}
/*!
* Connect to the sensor
*/
int Connect (char *pIP, unsigned int iXMLPort)
{
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD( 2, 0 );
char str_FWversion[255],str_SensorType[255];
string strIP = string(pIP);
// Restart: delete the old object and create a new one
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
pXmlClient = new XmlRpcClient ( pIP, iXMLPort);
XmlRpc::setVerbosity(0);
if (pXmlClient == NULL)
return CPCOMM3D_ERR_NO_MEM;
/* retrieve IP-Adress of local machine */
if ( WSAStartup(wVersionRequested, &wsaData ) == 0 )
{
if ( gethostname ( name, sizeof(name)) == 0)
{
if ((hostinfo = gethostbyname(name)) != NULL)
{
OwnIpAddress = string(inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list));
}
}
WSACleanup( );
}
XmlRpcValue args, result;
args[0] = OwnIpAddress;
result [0] = -1;
args[1] = 1;
if (!pXmlClient->execute ("MDAXMLConnectCP", args, result))
{
#ifdef _DEBUG
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
fprintf(ErrorLog,"Error occured MDAXMLConnectCP: at time %s\n",ctime(¤tTime));
fclose(ErrorLog);
#endif
return CPCOMM3D_NO_CONNECTION;
}
if ((int) result[0] == CPCOMM3D_NO_ERRORS)
{
string str;
str = static_cast<string>(result[1]);
strcpy (&str_FWversion[0], str.c_str ());
str = static_cast<string>(result[2]);
strcpy (&str_SensorType[0], str.c_str ());
}
return result[0];
}
/*!
* Disconnect from the sensor
*/
int Disconnect (void)
{
XmlRpcValue args, result;
if (pXmlClient != NULL)
{
args[0] = OwnIpAddress;
result [0] = -1;
if (!pXmlClient->execute ("MDAXMLDisconnectCP", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
pXmlClient->close ();
delete pXmlClient;
}
pXmlClient = NULL;
return result[0];
}
/*!
* Start the live image server
*/
int StartLiveImageServer (int i_Port, char *pIP)
{
if (pImageServerClientSocket == NULL)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result[0] = -1;
args[0] = (int)(1);
if (!pXmlClient->execute ("MDAXMLSetWorkingMode", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
if ((int) result[0] == CPCOMM3D_NO_ERRORS)
{
pImageServerClientSocket = new ClientSocket(pIP,i_Port);
if (!pImageServerClientSocket->isOK())
return CPCOMM3D_NO_CONNECTION;
}
else
{
return result[0];
}
#ifdef _DEBUG
if (pXmlClient->isFault())
{
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
fprintf(ErrorLog,"Error occured MDAXMLConnectCP: at time %s\n",ctime(¤tTime));
fclose(ErrorLog);
}
#endif
}
return CPCOMM3D_NO_ERRORS;
}
/*!
* Stop the live image server
*/
int StopLiveImageServer (void)
{
char command[1];
if (pImageServerClientSocket != NULL)
{
command[0] = 'q';
try
{
pImageServerClientSocket->sendData(sizeof(command),command);
Sleep(1000);
}
catch (SocketClosedException e)
{
cout << e.description() <<endl;
// ReleaseMutex(LiveImageMutex);
return CPCOMM3D_SOCKET_LIVE_IMAGE;
}
catch (SocketException e)
{
cout << e.description() <<endl;
return CPCOMM3D_GETTING_LIVE_IMAGE;
}
if (pXmlClient == NULL)
{
return CPCOMM3D_COMM_NOT_WORKING;
}
XmlRpcValue args, result;
result[0] = -1;
args[0] = (int)(0);
if (!pXmlClient->execute ("MDAXMLSetWorkingMode", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
if ((int) result[0] == CPCOMM3D_NO_ERRORS)
{
delete pImageServerClientSocket;
pImageServerClientSocket = NULL;
}
else
{
return result[0];
}
#ifdef _DEBUG
if (pXmlClient->isFault())
{
time_t currentTime;
time(¤tTime);
ErrorLog = fopen("Cpcomm3dErrorLog.txt", "a");
fprintf(ErrorLog,"Error occured MDAXMLConnectCP: at time %s\n",ctime(¤tTime));
fclose(ErrorLog);
}
#endif
}
return CPCOMM3D_NO_ERRORS;
}
/*!
* Transmit the frontend data to the sensor
*/
int SetFrontendData(T_FrontendData *p_FrontendData)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result[0] = -1;
args[0] = (int)0;
args[1] = (int)(0);
args[2] = (int)(p_FrontendData->i_samplingMode);
args[3] = (int)(0);
args[4] = (int)(p_FrontendData->i_integrationTimeSingle);
args[5] = (int)(p_FrontendData->i_integrationTimeDouble);
args[6] = (int)(20);
args[7] = (int)(p_FrontendData->i_samplingRate);
args[8] = (int)(0);
if (!pXmlClient->execute ("MDAXMLSetFrontendData", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
p_FrontendData->i_samplingMode = (int)(result[3]);
p_FrontendData->i_integrationTimeSingle = (int)(result[5]);
p_FrontendData->i_integrationTimeDouble = (int)(result[6]);
p_FrontendData->i_samplingRate = (int)(result[8]);
p_FrontendData->i_recommendedSamplingRate = (int)(result[9]);
cout << "Samplingrate " << p_FrontendData->i_samplingRate <<
" rec. Samplingrate " << p_FrontendData->i_recommendedSamplingRate << endl;
return result[0];
}
/*!
* Sets the trigger mode
*/
int SetTrigger(int Mode)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result[0] = -1;
args[0] = (int)0;
args[1] = (int)(0);
args[2] = (int)(Mode);
if (!pXmlClient->execute ("MDAXMLSetTrigger", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
cout << "TriggerMode " << Mode << endl;
return result[0];
}
/*!
* Sets the sensor Program
*/
int SetProgram(int i_Val)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[2] = (int)(i_Val);
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetProgram", args, result))
{
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Get the TCP-Data port number
*/
int GetTCPPort()
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue noargs, result;
result [0] = -1;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLGetTCPPortCP", noargs, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
/* send the y values */
ui_TCPPort = (int)(result[1]);
return result[0];
}
/*!
* Enable/Disable the Median Filter
*/
int SetMedianFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetMedianFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Enable/Disable the Adaptive Mean Filter
*/
int SetAdaptiveMeanFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetAdaptiveMeanValueFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Trigger an Image
*/
int TriggerImage()
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue noargs, result;
result [0] = -1;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLTriggerImage", noargs, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Enable/Disable the Mean Filter
*/
int SetMeanFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetMeanFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Enable/Disable the Exponential filter
*/
int SetExponentialFilterStatus(int status)
{
if (pXmlClient == NULL)
return CPCOMM3D_COMM_NOT_WORKING;
XmlRpcValue args, result;
result [0] = -1;
args[0] = status;
// Call the function at the far end.
if (!pXmlClient->execute ("MDAXMLSetExponentialFilterStatus", args, result))
{
if (pXmlClient != NULL)
{
pXmlClient->close ();
delete pXmlClient;
pXmlClient = NULL;
}
return CPCOMM3D_NO_CONNECTION;
}
return result[0];
}
/*!
* Print an usage string
*/
void ShowUsageStr(string prog)
{
size_t found;
found=prog.find_last_of("\\");
// Example: 192.168.95.53 1 2000 125 4 3 d c:\temp\imagedata.bin 3 7 1 0 0 0
cout << "Usage:" << endl << prog.substr(found+1) << " IP Mode " <<
"ISingle IDouble Rate # " <<
"IType FName TMode " <<
"Prog Med Mean " <<
"AdapMean Exp" << endl;
cout << "IP: " << endl;
cout << " IP-Adress: xxx.xxx.xxx.xxx " << endl;
cout << "Mode: " << endl;
cout << " 0 = single, 1 = double" << endl;
cout << "ISingle: " << endl;
cout << " Single Integration Time [ms]" << endl;
cout << "IDouble: " << endl;
cout << " Double Integration Time [ms]" << endl;
cout << "Rate: " << endl;
cout << " Sampling Rate [Hz]" << endl;
cout << "#: " << endl;
cout << " Number of images to receive" << endl;
cout << "IType: " << endl;
cout << " Type of image " << endl;
cout << " i : Intensity Image" << endl;
cout << " d : Distance Image" << endl;
cout << " x : X-Component Image" << endl;
cout << " y : Y-Component Image" << endl;
cout << " z : Z-Component Image" << endl;
cout << " n : ???" << endl;
cout << " e : ???" << endl;
cout << " f : ???" << endl;
cout << " g : ???" << endl;
cout << " s : ???" << endl;
cout << "FName: " << endl;
cout << " Output File name" << endl;
cout << "TMode: " << endl;
cout << " Trigger Mode: 3 free run, 1 extern, 4 SW" << endl;
cout << "Prog: " << endl;
cout << " Sensor Programm: 7 server mode" << endl;
cout << "Med:" << endl;
cout << " Median Filter: 0 off 1 on " << endl;
cout << "Mean: " << endl;
cout << " Mean Filter: 0 off 1 on; " << endl;
cout << "AdapMean: " << endl;
cout << " Adaptive Mean Filter: 0 off 1 on " << endl;
cout << "Exp:" << endl;
cout << " Exponential Filter: 0 off 1 on" << endl;
cout << endl;
cout << "Example: 192.168.95.53 1 2000 125 4 3 d c:\\temp\\imagedata.bin 3 7 1 0 0 0" << endl;
exit(0);
}
---------------------------------------------------------------------------------------------------------------------
2)
/* $Id: clientsocket.h 6321 2008-02-07 09:55:40Z deegech $ */
#ifndef CLIENT_SOCKET_H
#define CLIENT_SOCKET_H
#include <iostream>
#include <string>
#include <winsock2.h>
#include "CPcomm3dErrors.h"
#include "XmlRpc.h"
#include "structs.h"
/*!
* @brief Client socket exception.
*/
class SocketException
{
public:
/*!
* @param s
* Descriptive string for the exception.
*/
SocketException ( std::string s, int error ) : m_s ( s ),m_error(error) {};
~SocketException (){};
/*!
* @brief Get description string
* @return Descriptive string of the exception.
*/
std::string description()
{
return m_s;
};
int error()
{
return m_error;
};
private:
std::string m_s;
int m_error;
};
/*!
* @brief Client socket closed exception
*/
class SocketClosedException : public SocketException
{
public:
/*!
* @param s
* Descriptive string for the exception.
*/
SocketClosedException ( std::string s ) : SocketException(s,0) {};
};
/*!
* @brief Client socket
*/
class ClientSocket
{
public:
/*!
* @brief Client socket initialization.
* @param ipaddr
* IP address to connect to.
* @param port
* TCP/IP port to use, e.g. "127.0.0.1"
*/
ClientSocket(const char* addr, int port);
~ClientSocket();
void sendData(int byte_size, const void* data);
/*!
* @brief receive a data frame.
* @param frame_byte_size
* Number of bytes in the frame.
* @param buffer
* Buffer to save frame to.
* @throws SocketException
*/
int ReceiveFrame(int frame_byte_size, char *buffer);
/*! Receive a 4 byte integer.
@throws SocketException
*/
int ReceiveInt(int &toRec);
/*! Receive a 2 byte unsigned short value.
@throws SocketException
*/
int ReceiveU16(unsigned short &toRec);
/*! \return The current state of the socket. */
bool isOK()
{
return _OK;
};
private:
WSAData wsaData;
SOCKET sd;
/*!
* @param nRemoteAddr
* IP address to connet to.
* @param nPort
* TCP/IP port to connect to.
* @return
* On success a descriptor referencing the new socket is return,
* INVALID_SOCKET else.
*
* Connects to a given address, on a given port, both of which must be
* in network byte order. Returns newly-connected socket if we succeed,
* or INVALID_SOCKET if we fail.
*/
SOCKET EstablishConnection(u_long nRemoteAddr, u_short nPort);
/*!
* Gracefully shuts the connection sd down.
* @return Returns true if we're successful, false otherwise.
*/
bool ClientSocket::ShutdownConnection(SOCKET sd);
bool _OK;
};
#endif // CLIENT_SOCKET_H
/*--- END OF FILE -------------------------------------------------------*/
---------------------------------------------------------------------------------------------------------------------
3)
/* $Id: clientsocket.cpp 6321 2008-02-07 09:55:40Z deegech $ */
#include <iostream>
#include <string>
#include <winsock2.h>
#include "clientsocket.h"
#include "CPcomm3dErrors.h"
#include "XmlRpc.h"
#include "structs.h"
/*!
* Startup Windows socket and Establish connection
*/
ClientSocket::ClientSocket(const char* addr, int port)
{
int code = WSAStartup(MAKEWORD(1, 1), &wsaData);
sd = EstablishConnection(inet_addr(addr), htons(port));
_OK = (code == 0) && sd != INVALID_SOCKET;
}
/*!
* Shutdown connection and Windows socket.
*/
ClientSocket::~ClientSocket()
{
if (sd != INVALID_SOCKET) ShutdownConnection(sd);
WSACleanup();
}
/*!
* Send data with byte size.
*/
void ClientSocket::sendData(int byte_size, const void* data)
{
int ret = send(sd, (char*) data, byte_size, 0) ;
if (ret == SOCKET_ERROR)
{
int error = WSAGetLastError();
throw SocketException("send error",error);
}
}
/*!
* Build up a connection to Sensor.
* Create a socket and connect to Sensor.
*/
SOCKET ClientSocket::EstablishConnection(u_long nRemoteAddr, u_short nPort)
{
// Create a stream socket
SOCKET sd = socket(PF_INET, SOCK_STREAM, 0);
if (sd != INVALID_SOCKET)
{
sockaddr_in sinRemote;
sinRemote.sin_family = AF_INET;
sinRemote.sin_addr.s_addr = nRemoteAddr;
sinRemote.sin_port = nPort;
int r = connect(sd, (sockaddr*)&sinRemote, sizeof(sockaddr_in));
if (r == SOCKET_ERROR) sd = INVALID_SOCKET;
}
return sd;
}
/*!
* Gracefully shuts the connection sd down. Returns true if we're
* successful, false otherwise.
*/
bool ClientSocket::ShutdownConnection(SOCKET sd)
{
// Disallow any further data sends. This will tell the other side
// that we want to go away now. If we skip this step, we don't
// shut the connection down nicely.
// This function is only available for winsock2 sockets.
if (shutdown(sd, SD_SEND) == SOCKET_ERROR)
{
return false;
}
// Close the socket.
if (closesocket(sd) == SOCKET_ERROR)
{
return false;
}
return true;
}
/*!
* Receive an integer.
*/
int ClientSocket::ReceiveInt(int &toRec)
{
int res = ReceiveFrame(sizeof(int),(char*) &toRec);
toRec = ntohl(toRec);
return res;
}
/*!
* Receive an unsigned short (u16).
*/
int ClientSocket::ReceiveU16(unsigned short &toRec)
{
int res = ReceiveFrame(sizeof(unsigned short),(char*) &toRec);
toRec = ntohs(toRec);
return res;
}
/*!
* Receive a frame of given length and save it to buffer.
*/
int ClientSocket::ReceiveFrame(int frame_byte_size, char *buffer)
{
int total_bytes = 0;
while (total_bytes < frame_byte_size)
{
int new_bytes = recv(sd, buffer + total_bytes, frame_byte_size - total_bytes, 0);
if (new_bytes == SOCKET_ERROR)
{
int error = WSAGetLastError();
throw SocketException("receive error",error);
}
if (new_bytes == 0) throw SocketClosedException("connection closed by peer");
total_bytes += new_bytes;
}
return total_bytes;
}
/*--- END OF FILE -------------------------------------------------------*/
You need to remove or conditionally compile the Windows specific code, and in some places replace it with the equivalent linux code.
For example, replace the lines:
WSAData wsaData;
SOCKET sd;
with:
#if defined(_MSC_VER) // The next lines will only be compiled under MSVC++
WSAData wsaData;
SOCKET sd;
#else // The next lines will not be compiled under MSVC++
int sd; // sockets are represented as int on linux
#endif
Do this for all the lines with WSA... in them, that should get you started.
Hi,
I compiled xml rpc++ lib in Suse-Linux and Embedded linux, both using g++ and Makefiles. I did any recoding at all.
I do not remember if I even did the changes Chris mention, or just "make all" compiled everything fine
José
The changes I suggested were not for the xmlrpc++ code, that compiles fine on linux (usually).
The changes were intended for his code, which used a mix of xmlrpc++ and winsock calls.