forked from Serial-Studio/Serial-Studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
319 lines (274 loc) · 8.17 KB
/
Server.cpp
File metadata and controls
319 lines (274 loc) · 8.17 KB
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
/*
* Copyright (c) 2020-2023 Alex Spataru <https://github.com/alex-spataru>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <IO/Manager.h>
#include <JSON/Generator.h>
#include <Misc/Utilities.h>
#include <Plugins/Server.h>
#include <Misc/TimerEvents.h>
/**
* Constructor function
*/
Plugins::Server::Server()
: m_enabled(false)
{
// clang-format off
// Send processed data at 1 Hz
connect(&JSON::Generator::instance(), &JSON::Generator::jsonChanged,
this, &Plugins::Server::registerFrame);
connect(&Misc::TimerEvents::instance(), &Misc::TimerEvents::timeout1Hz,
this, &Plugins::Server::sendProcessedData);
// Send I/O "raw" data directly
connect(&IO::Manager::instance(), &IO::Manager::dataReceived,
this, &Plugins::Server::sendRawData);
// Configure TCP server
connect(&m_server, &QTcpServer::newConnection,
this, &Plugins::Server::acceptConnection);
// clang-format on
// Begin listening on TCP port
if (!m_server.listen(QHostAddress::Any, PLUGINS_TCP_PORT))
{
Misc::Utilities::showMessageBox(tr("Unable to start plugin TCP server"),
m_server.errorString());
m_server.close();
}
}
/**
* Destructor function
*/
Plugins::Server::~Server()
{
m_server.close();
}
/**
* Returns a pointer to the only instance of the class
*/
Plugins::Server &Plugins::Server::instance()
{
static Server singleton;
return singleton;
}
/**
* Returns @c true if the plugin sub-system is enabled
*/
bool Plugins::Server::enabled() const
{
return m_enabled;
}
/**
* Disconnects the socket used for communicating with plugins.
*/
void Plugins::Server::removeConnection()
{
// Get caller socket
auto socket = static_cast<QTcpSocket *>(QObject::sender());
// Remove socket from registered sockets
if (socket)
{
for (int i = 0; i < m_sockets.count(); ++i)
{
if (m_sockets.at(i) == socket)
{
m_sockets.removeAt(i);
i = 0;
}
}
// Delete socket handler
socket->deleteLater();
}
}
/**
* Enables/disables the plugin subsystem
*/
void Plugins::Server::setEnabled(const bool enabled)
{
// Change value
m_enabled = enabled;
Q_EMIT enabledChanged();
// If not enabled, remove all connections
if (!enabled)
{
for (int i = 0; i < m_sockets.count(); ++i)
{
auto socket = m_sockets.at(i);
if (socket)
{
socket->abort();
socket->deleteLater();
}
}
m_sockets.clear();
}
// Clear frames array to avoid memory leaks
m_frames.clear();
}
/**
* Process incoming data and writes it directly to the connected I/O device
*/
void Plugins::Server::onDataReceived()
{
// Get caller socket
auto socket = static_cast<QTcpSocket *>(QObject::sender());
// Write incoming data to manager
if (enabled() && socket)
IO::Manager::instance().writeData(socket->readAll());
}
/**
* Configures incoming connection requests
*/
void Plugins::Server::acceptConnection()
{
// Get & validate socket
auto socket = m_server.nextPendingConnection();
if (!socket && enabled())
{
Misc::Utilities::showMessageBox(tr("Plugin server"),
tr("Invalid pending connection"));
return;
}
// Close connection if system is not enabled
if (!enabled())
{
if (socket)
{
socket->close();
socket->deleteLater();
}
return;
}
// Connect socket signals/slots
connect(socket, &QTcpSocket::readyRead, this, &Plugins::Server::onDataReceived);
connect(socket, &QTcpSocket::disconnected, this, &Plugins::Server::removeConnection);
// React to socket errors
// clang-format off
#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(onErrorOccurred(QAbstractSocket::SocketError)));
#else
connect(socket, &QTcpSocket::errorOccurred,
this, &Plugins::Server::onErrorOccurred);
#endif
// clang-format on
// Add socket to sockets list
m_sockets.append(socket);
}
/**
* Sends an array of frames with the following information:
* - Frame ID number
* - RX timestamp
* - Frame JSON data
*/
void Plugins::Server::sendProcessedData()
{
// Stop if system is not enabled
if (!enabled())
return;
// Stop if frame list is empty
if (m_frames.count() <= 0)
return;
// Stop if no sockets are available
if (m_sockets.count() < 1)
return;
// Create JSON array with frame data
QJsonArray array;
for (int i = 0; i < m_frames.count(); ++i)
{
QJsonObject object;
auto frame = m_frames.at(i);
object.insert("data", frame);
array.append(object);
}
// Create JSON document with frame arrays
if (array.count() > 0)
{
// Construct QByteArray with data
QJsonObject object;
object.insert("frames", array);
const QJsonDocument document(object);
auto json = document.toJson(QJsonDocument::Compact) + "\n";
// Send data to each plugin
Q_FOREACH (auto socket, m_sockets)
{
if (!socket)
continue;
if (socket->isWritable())
socket->write(json);
}
}
// Clear frame list
m_frames.clear();
}
/**
* Encodes the given @a data in Base64 and sends it through the TCP socket connected
* to the localhost.
*/
void Plugins::Server::sendRawData(const QByteArray &data)
{
// Stop if system is not enabled
if (!enabled())
return;
// Stop if no sockets are available
if (m_sockets.count() < 1)
return;
// Create JSON structure with incoming data encoded in Base-64
QJsonObject object;
object.insert("data", QString::fromUtf8(data.toBase64()));
// Get JSON string in compact format & send it over the TCP socket
QJsonDocument document(object);
auto json = document.toJson(QJsonDocument::Compact) + "\n";
// Send data to each plugin
Q_FOREACH (auto socket, m_sockets)
{
if (!socket)
continue;
if (socket->isWritable())
socket->write(json);
}
}
/**
* Obtains the latest JSON dataframe & appends it to the JSON list, which is later read
* and sent by the @c sendProcessedData() function.
*/
void Plugins::Server::registerFrame(const QJsonObject &json)
{
if (enabled())
m_frames.append(json);
}
/**
* This function is called whenever a socket error occurs, it disconnects the socket
* from the host and displays the error in a message box.
*/
void Plugins::Server::onErrorOccurred(const QAbstractSocket::SocketError socketError)
{
// Get caller socket
auto socket = static_cast<QTcpSocket *>(QObject::sender());
// Print error
if (socket)
qDebug() << socket->errorString();
else
qDebug() << socketError;
}
#ifdef SERIAL_STUDIO_INCLUDE_MOC
# include "moc_Server.cpp"
#endif