-
Notifications
You must be signed in to change notification settings - Fork 1
/
TCP.cpp
297 lines (256 loc) · 7.6 KB
/
TCP.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
/**
* @file TCP.cpp
* @Author BeeeOn team
* @date
* @brief
*/
#include <utility>
#include <Poco/AutoPtr.h>
#include <Poco/Event.h>
#include <Poco/Net/SocketAddress.h>
#include "IOcontrol.h"
#include "TCP.h"
#include "XMLTool.h"
using namespace std;
using namespace Poco::Net;
using Poco::AutoPtr;
using Poco::Logger;
using Poco::Mutex;
using Poco::Runnable;
using Poco::Semaphore;
using Poco::Util::IniFileConfiguration;
#define RECONNECT_TIME 5 // seconds
#define RECEIVE_TIMEOUT 3 // seconds
/**
* Thread function for sending data to server (to not to block receiving thread)
*/
void referMessageFromServer(shared_ptr<std::queue<std::string>>send_queue,
std::pair<shared_ptr<Aggregator>, Poco::Logger&> params,
shared_ptr<Semaphore> send_semaphore,
shared_ptr<Mutex>queue_mutex) {
while(!quit_global_flag){
shared_ptr<Aggregator> agg = params.first;
Logger& log = params.second;
std::string msg;
Command cmd;
send_semaphore->wait();
if (quit_global_flag)
break;
queue_mutex->lock();
if (send_queue->empty()) /*Should not happen*/
continue;
msg = send_queue->front();
send_queue->pop();
queue_mutex->unlock();
try {
unique_ptr<XMLTool> xml(new XMLTool());
cmd = (xml->parseXML(msg)).command;
}
catch (Poco::Exception& ex) {
log.error("Exception: " + ex.displayText());
return;
}
agg->parseCmd(cmd);
}
}
IOTReceiver::IOTReceiver(shared_ptr<Aggregator> _agg, string _address, int _port, IOTMessage _msg, long long int _adapter_id) :
agg(_agg),
address(_address),
port(_port),
msg(_msg),
adapter_id(_adapter_id),
log(Poco::Logger::get("Adaapp-TCP"))
{
keepalive = {0,0,0};
input_socket = nullptr;
send_semaphore = nullptr;
send_queue = nullptr;
queue_mutex = nullptr;
AutoPtr<IniFileConfiguration> cfg;
try {
cfg = new IniFileConfiguration(std::string(MODULES_DIR)+std::string(MOD_TCP)+".ini");
}
catch (Poco::Exception& ex) {
log.error("Exception with config file reading:\n" + ex.displayText());
exit (EXIT_FAILURE);
}
}
void IOTReceiver::keepaliveInit(IniFileConfiguration * cfg) {
try{
if ( cfg->getBool("keepalive.enable") == false ) {
keepalive_enable = false;
return;
}
keepalive.time = cfg->getInt("keepalive.time", KEEPALIVE_TIME);
keepalive.interval = cfg->getInt("keepalive.interval", KEEPALIVE_INTERVAL);
keepalive.probes = cfg->getInt("keepalive.probes", KEEPALIVE_PROBES);
keepalive_enable = true;
}
catch (Poco::Exception& exc) {
keepalive_enable = false;
}
}
void IOTReceiver::init() {
SocketAddress srv_address(address, port);
input_socket.reset(new SecureStreamSocket(srv_address));
unique_ptr<XMLTool> xml(new XMLTool(ServerMessage(msg)));
string message = xml->createXML(INIT);
char buffer[2000] = {0};
input_socket->sendBytes(message.c_str(), message.length());
input_socket->receiveBytes(buffer, 1999, 0);
input_socket->setBlocking(true);
if ( keepalive_enable ) {
input_socket->setKeepAlive(true);
input_socket->setOption(SOL_TCP, TCP_KEEPIDLE, keepalive.time);
input_socket->setOption(SOL_TCP, TCP_KEEPINTVL, keepalive.interval);
input_socket->setOption(SOL_TCP, TCP_KEEPCNT, keepalive.probes);
}
}
void IOTReceiver::run() {
log.information("Starting SSL connection thread...");
msg.state = "register";
msg.priority = MSG_PRIO_REG;
send_queue.reset(new std::queue<std::string>());
send_semaphore.reset(new Semaphore(0,10));
queue_mutex.reset(new Mutex());
send_thread.reset (new std::thread(referMessageFromServer, send_queue, std::pair<shared_ptr<Aggregator>, Poco::Logger&>(agg, log), send_semaphore, queue_mutex));
while ( !quit_global_flag ) {
if ( input_socket.get() == nullptr ) {
try {
init();
#ifdef LEDS_ENABLED
LEDControl::blinkLED(LED_LIME);
#endif
if (input_socket.get() != nullptr)
input_socket->setReceiveTimeout(Poco::Timespan(RECEIVE_TIMEOUT,0));
}
catch (Poco::Exception& exc) {
log.error("Exception: " + exc.displayText());
#ifdef LEDS_ENABLED
LEDControl::setLED(LED_LIME, false);
#endif
for (unsigned int i = 0; i < RECONNECT_TIME; i++) {
if (quit_global_flag)
return;
sleep(1);
}
continue;
}
}
try {
MSG_TYPE ret; // variable for the message residue
try {
int n = 0;
// XXX This while should have some maximum message size counter,
// otherwise it will cycle until \0 will be found
while ((n >= 0) && (!quit_global_flag)) {
MSG_TYPE buffer (BUF_SIZE);
try {
n = input_socket->receiveBytes(buffer.data(), buffer.size());
}
catch (Poco::TimeoutException& t_ex) {
n = 0;
}
// Check for timeout expiration for receive bytes
if (n > 0) {
buffer.resize(n);
ret.insert(ret.end(), buffer.begin(), buffer.end()); // Concatenate vector
ret = parseTempMessage(ret);
}
}
if (quit_global_flag)
return;
if ( n <= 0 ) {
input_socket.reset(nullptr);
continue;
}
// It is possible that receiveBytes returned 0 - try to parse message again if there is something
if (ret.size())
parseTempMessage(ret);
} catch (Poco::Exception& exc) {
log.error("Exception: " + exc.displayText());
input_socket.reset(nullptr);
}
if ( input_socket.get() == nullptr )
continue;
} catch (Poco::Exception& ex) {
log.error("Exception: " + ex.displayText());
}
}
}
/**
* Parse temporary buffer from server. Delimiter is found, message is parsed and sent to other parts.
* @param tmp_msg Message which will be parsed
* @param delimiter Delimiter character
* @return residue after parsing
*/
MSG_TYPE IOTReceiver::parseTempMessage(MSG_TYPE tmp_msg, char delimiter) {
MSG_TYPE::iterator it = tmp_msg.end();
while ((it = std::find(tmp_msg.begin(), tmp_msg.end(), delimiter) ) != tmp_msg.end()) { // Try to find delimiter
std::string partial_msg(tmp_msg.begin(), it++);
if (!partial_msg.empty()) { // Partial message might be empty
log.information("Incomming message:\n" + partial_msg);
queue_mutex->lock();
send_queue->push(partial_msg);
queue_mutex->unlock();
send_semaphore->set();
}
tmp_msg.erase(tmp_msg.begin(), it);
}
return tmp_msg;
}
IOTReceiver::~IOTReceiver() {
send_semaphore->set();
send_thread->join();
}
pair<bool, Command> IOTReceiver::sendToServer(IOTMessage _msg) {
Command income_cmd;
if (_msg.state == "")
_msg.state = "data";
unique_ptr<XMLTool> xml(new XMLTool(ServerMessage(_msg)));
string a_to_s = "";
if(_msg.state == "getparameters" || _msg.state == "parameters")
a_to_s = xml->createXML(PARAM);
else
a_to_s = xml->createXML(A_TO_S);
log.information("Try to send this MSG to server:\n" + a_to_s);
#ifdef LEDS_ENABLED
LEDControl::setLED(LED_PAN, true);
#endif
SocketAddress sa(address, port);
try {
SecureStreamSocket str(sa);
str.sendBytes(a_to_s.c_str(), a_to_s.length());
str.setReceiveTimeout(Poco::Timespan(RECEIVE_TIMEOUT,0));
char buffer[BUF_SIZE];
string message = "";
int n = 0;
do {
n = str.receiveBytes(buffer, sizeof(buffer));
message += string(buffer, n);
// XXX Temporary solution to handle case with NULL byte
// at the end of the message
auto pos = message.find('\0');
if (pos != message.npos) {
message.erase(pos);
break;
}
} while (n == BUF_SIZE);
#ifdef LEDS_ENABLED
LEDControl::setLEDAfterTimeout(LED_PAN, false, 200000);
#endif
if (message != "") {
log.information("Received message:\n" + message);
unique_ptr<XMLTool> resp(new XMLTool());
income_cmd = (resp->parseXML(message)).command;
agg->parseCmd(income_cmd);
}
else {
log.information("Received empty message.");
}
}
catch (Poco::Exception& ex) {
return make_pair(false, income_cmd);
}
return make_pair(true, income_cmd);
}