-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWebSocketServerConnection.cpp
350 lines (293 loc) · 8.8 KB
/
WebSocketServerConnection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
* @file WebSocketServerConnection.cpp
* @Author BeeeOn team - Richard Wolfert
* @date Q3/2016
* @brief Implementation of communication with BeeeOn ada_server over WebSockets
*/
#include <Poco/Exception.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/NetException.h>
#include <Poco/ScopedLock.h>
#include <Poco/Timespan.h>
#include "WebSocketServerConnection.h"
#include "XMLTool.h"
#define DEFAULT_SOCKET_TIMEOUT 5
#define MAX_WAIT_FOR_RESPONSE_TIME 10
#define RETRY_WAIT_TIME 1
#define RECEIVE_BUFFER_SIZE 4096
#define TIME_TO_ANSWER 1
using namespace std;
using namespace Poco::Net;
using Poco::Mutex;
WebSocketServerConnection::WebSocketServerConnection(shared_ptr<Aggregator> agg, Poco::Util::IniFileConfiguration *cfg, IOTMessage msg) :
m_msg(ServerMessage(msg)),
log(Poco::Logger::get("WebSocketServerConnection")),
m_agg(agg),
m_current_request_id(0)
{
m_socketTimeout = cfg->getInt("server.timeout", DEFAULT_SOCKET_TIMEOUT);
try {
m_host = cfg->getString("server.ip");
m_port = cfg->getInt("server.port");
m_uri = cfg->getString("server.uri");
}
catch (Poco::Exception &ex) {
log.log(ex, __FILE__, __LINE__);
m_initialized = false;
return;
}
m_initialized = true;
}
void WebSocketServerConnection::initConnection()
{
Mutex::ScopedLock lock(m_init_mutex);
if (initSocket()) {
log.debug("connection established");
sendRegisterMessage();
}
else {
log.debug("failed to connect");
}
}
bool WebSocketServerConnection::initSocket()
{
HTTPSClientSession cs(m_host, m_port);
HTTPRequest request(HTTPRequest::HTTP_GET, m_uri, HTTPMessage::HTTP_1_1);
HTTPResponse response;
log.information("Initializing connection to server:");
log.debug("Hostname:" + m_host);
log.debug("Port:" + to_string(m_port));
log.debug("Uri:" + m_uri);
m_socket.reset();
try {
m_socket.reset(new WebSocket(cs, request, response));
}
catch(Poco::Exception &ex) {
log.log(ex, __FILE__, __LINE__);
return false;
}
m_socket->setReceiveTimeout(Poco::Timespan(m_socketTimeout, 0));
m_socket->setBlocking(true);
return true;
}
void WebSocketServerConnection::run()
{
if (m_initialized) {
log.information("Starting server connection thread");
}
else {
log.critical("Connection settings are not initialized, exiting");
return;
}
while (!quit_global_flag) {
if (!connectWithRetry(RETRY_WAIT_TIME))
continue;
receiveMessages();
}
}
bool WebSocketServerConnection::connectWithRetry(int timeout)
{
bool exit_value = true;
initConnection();
while (!isConnected()) {
if (quit_global_flag) {
exit_value = false;
break;
}
log.warning("failed to connect to server, retry in 1 s",
__FILE__, __LINE__);
sleep(timeout);
initConnection();
}
return exit_value;
}
void WebSocketServerConnection::receiveMessages()
{
while (!quit_global_flag) {
try {
vector<string> received_messages;
received_messages = receiveMessagesFromServer();
for (string const& message : received_messages) {
acceptMessage(message);
}
}
catch(Poco::TimeoutException &ex) {
continue;
}
catch(Poco::Net::NetException &ex) {
log.log(ex, __FILE__, __LINE__);
break;
}
}
}
bool WebSocketServerConnection::isConnected()
{
return (m_socket.get() != NULL);
}
void WebSocketServerConnection::sendRegisterMessage()
{
log.information("sending register message to server");
m_msg.iotmessage.state = "register";
m_msg.iotmessage.priority = MSG_PRIO_REG;
XMLTool xml(m_msg);
string message = xml.createXML(INIT);
sendStringToServer(message);
}
bool WebSocketServerConnection::sendStringToServer(string message)
{
Mutex::ScopedLock lock(m_socket_write_mutex);
log.information("Sending message to server: " + message);
if (isConnected()) {
try {
m_socket->sendBytes(message.c_str(), message.length());
}
catch (Poco::Exception &ex) {
log.log(ex, __FILE__, __LINE__);
return false;
}
log.debug("Send successful");
return true;
}
else {
log.error("Send failed: socket is not initialized");
return false;
}
}
vector<string> WebSocketServerConnection::receiveMessagesFromServer()
{
char buffer[RECEIVE_BUFFER_SIZE + 1];
int bytes_received;
vector<string> result_vector;
int last_string = 0;
bytes_received = m_socket->receiveBytes(buffer, RECEIVE_BUFFER_SIZE);
buffer[bytes_received] = '\0';
for (int i = 0; i < bytes_received; i++) {
if (buffer[i] == '\0') {
result_vector.push_back(m_data_leftover +
string(buffer + last_string));
m_data_leftover = "";
last_string = i + 1;
}
}
m_data_leftover = string(buffer + last_string);
if (bytes_received < 1)
throw Poco::Net::NoMessageException("");
log.debug("received packet of " + to_string(bytes_received) + " Bytes, packet content: " + string(buffer));
return result_vector;
}
std::pair<bool, Command> WebSocketServerConnection::sendToServer(IOTMessage msg)
{
std::pair<bool, Command> answer(false, Command());
ServerMessage sMessage = ServerMessage(msg);
request_id_t request_id = generateRequestId();
sMessage.request_id = request_id;
XMLTool xml(sMessage);
string message_to_server;
if(sMessage.iotmessage.state == "getparameters" || sMessage.iotmessage.state == "parameters")
message_to_server = xml.createXML(PARAM);
else
message_to_server = xml.createXML(A_TO_S);
prepareForResponse(request_id);
if (!safeSendToServer(message_to_server)) {
requestDone(request_id);
return answer; //answer is not valid, answer.first means validity, which is set to false
}
int try_count = 0;
while (try_count < MAX_WAIT_FOR_RESPONSE_TIME) {
checkForResponse(request_id, answer);
// We either have answer or adaapp is terminating
if (answer.first || quit_global_flag ) {
requestDone(request_id);
break;
}
// Waiting last time in next iteration,
// we remove request_id from m_pending_requests,
// so the message can be received only if receiving
// thread already received this message, but its
// context was changed right before inserting answer
// to responses map, otherwise this could result
// in memory leak, because socket reading thread
// would insert entry into m_responses map, but none
// would take it away.
if (try_count == (MAX_WAIT_FOR_RESPONSE_TIME-1)) {
requestDone(request_id);
}
sleep(TIME_TO_ANSWER); // wait one more second for an answer
try_count++;
}
if (!answer.first) {
log.error("failed to send message to server");
log.debug("message content: " + message_to_server);
}
return answer;
}
void WebSocketServerConnection::requestDone(request_id_t request_id)
{
Mutex::ScopedLock lock(m_requests_mutex);
m_pending_requests.erase(request_id);
}
request_id_t WebSocketServerConnection::generateRequestId()
{
Mutex::ScopedLock lock(m_current_request_id_mutex);
if (m_current_request_id == 0) // skip zero, invalid ID
return ++m_current_request_id;
return m_current_request_id++;
}
void WebSocketServerConnection::prepareForResponse(request_id_t request_id)
{
Mutex::ScopedLock lock(m_requests_mutex);
m_pending_requests.insert(request_id);
log.debug("inserting pending request number" + to_string(request_id)
+ ", total pending requests: " + to_string(m_pending_requests.size()));
}
bool WebSocketServerConnection::safeSendToServer(std::string message)
{
Mutex::ScopedLock lock(m_init_mutex);
return sendStringToServer(message);
}
void WebSocketServerConnection::checkForResponse(request_id_t request_id, std::pair<bool, Command> &answer)
{
Mutex::ScopedLock lock(m_responses_mutex);
map<request_id_t, ServerCommand>::iterator it;
it = m_responses.find(request_id);
if (it != m_responses.end()) { //response found
answer.second = m_responses[request_id].command;
answer.first = true;
m_responses.erase(it);
}
}
void WebSocketServerConnection::acceptMessage(std::string message)
{
XMLTool xml;
ServerCommand cmd = xml.parseXML(message);
log.trace("acceptMessage, parsed message= response_id:" + to_string(cmd.response_id)+" Request id: " + to_string(cmd.request_id));
if (cmd.response_id != 0) { //This is an answer
Mutex::ScopedLock lock(m_requests_mutex);
if (m_pending_requests.find(cmd.response_id) != m_pending_requests.end()) {
Mutex::ScopedLock lock(m_responses_mutex);
m_responses.insert(pair<request_id_t, ServerCommand>(cmd.response_id, cmd));
log.debug("Inserted response to requests number " + to_string(cmd.response_id)
+ ",total responses = " + to_string(m_responses.size()));
}
}
else {
if (cmd.request_id != 0) {
sendAckToServer(cmd.request_id);
m_agg->parseCmd(cmd.command);
}
else {
log.warning("received message without response_id neither request_id");
}
}
}
void WebSocketServerConnection::sendAckToServer(request_id_t response)
{
log.debug("sending ack message to server");
m_msg.iotmessage.state = "ack";
m_msg.response_id = response;
XMLTool xml(m_msg);
string message = xml.createXML(A_TO_S);
safeSendToServer(message);
}