Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031 #ifdef ROS
00032 #include "simple_message/socket/udp_client.h"
00033 #include "simple_message/log_wrapper.h"
00034 #endif
00035
00036 #ifdef MOTOPLUS
00037 #include "udp_client.h"
00038 #include "log_wrapper.h"
00039 #endif
00040
00041
00042 using namespace industrial::byte_array;
00043 using namespace industrial::shared_types;
00044
00045 namespace industrial
00046 {
00047 namespace udp_client
00048 {
00049
00050 UdpClient::UdpClient()
00051 {
00052 }
00053
00054 UdpClient::~UdpClient()
00055 {
00056 }
00057
00058 bool UdpClient::init(char *buff, int port_num)
00059 {
00060
00061 int rc;
00062 bool rtn;
00063
00064
00065
00066
00067
00068
00069 rc = SOCKET(AF_INET, SOCK_DGRAM, 0);
00070 if (this->SOCKET_FAIL != rc)
00071 {
00072 this->setSockHandle(rc);
00073
00074
00075 memset(&this->sockaddr_, 0, sizeof(this->sockaddr_));
00076 this->sockaddr_.sin_family = AF_INET;
00077 this->sockaddr_.sin_addr.s_addr = INET_ADDR(buff);
00078 this->sockaddr_.sin_port = HTONS(port_num);
00079
00080 rtn = true;
00081
00082 }
00083 else
00084 {
00085 LOG_ERROR("Failed to create socket, rc: %d", rc);
00086 rtn = false;
00087 }
00088 return rtn;
00089 }
00090
00091
00092 bool UdpClient::makeConnect()
00093 {
00094 ByteArray send;
00095 char sendHS = this->CONNECT_HANDSHAKE;
00096 char recvHS = 0;
00097 bool rtn = false;
00098 const int timeout = 1000;
00099 int bytesRcvd = 0;
00100
00101 if (!this->isConnected())
00102 {
00103 this->setConnected(false);
00104 send.load((void*)&sendHS, sizeof(sendHS));
00105
00106 do
00107 {
00108 ByteArray recv;
00109 recvHS = 0;
00110 LOG_DEBUG("UDP client sending handshake");
00111 this->rawSendBytes(send.getRawDataPtr(), send.getBufferSize());
00112 if (this->isReadyReceive(timeout))
00113 {
00114 bytesRcvd = this->rawReceiveBytes(this->buffer_, 0);
00115 LOG_DEBUG("UDP client received possible handshake");
00116 recv.init(&this->buffer_[0], bytesRcvd);
00117 recv.unload((void*)&recvHS, sizeof(recvHS));
00118 }
00119 }
00120 while(recvHS != sendHS);
00121 LOG_INFO("UDP client connected");
00122 rtn = true;
00123 this->setConnected(true);
00124
00125 }
00126 else
00127 {
00128 rtn = true;
00129 LOG_WARN("Tried to connect when socket already in connected state");
00130 }
00131
00132 return rtn;
00133 }
00134 }
00135 }
00136