forked from Serial-Studio/Serial-Studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork.cpp
More file actions
541 lines (476 loc) · 14.3 KB
/
Network.cpp
File metadata and controls
541 lines (476 loc) · 14.3 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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/*
* 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 <IO/Manager.h>
#include <IO/Drivers/Network.h>
#include <Misc/Utilities.h>
//----------------------------------------------------------------------------------------
// Constructor & singleton access functions
//----------------------------------------------------------------------------------------
/**
* Constructor function
*/
IO::Drivers::Network::Network()
: m_hostExists(false)
, m_udpMulticast(false)
, m_lookupActive(false)
, m_udpIgnoreFrameSequences(false)
{
// Set initial configuration
setRemoteAddress("");
setTcpPort(defaultTcpPort());
setUdpLocalPort(defaultUdpLocalPort());
setUdpRemotePort(defaultUdpRemotePort());
setSocketType(QAbstractSocket::TcpSocket);
// clang-format off
// Update connect button status when the configuration is changed
connect(this, &IO::Drivers::Network::addressChanged,
this, &IO::Drivers::Network::configurationChanged);
connect(this, &IO::Drivers::Network::socketTypeChanged,
this, &IO::Drivers::Network::configurationChanged);
connect(this, &IO::Drivers::Network::portChanged,
this, &IO::Drivers::Network::configurationChanged);
// Report socket errors
#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
connect(&m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(onErrorOccurred(QAbstractSocket::SocketError)));
connect(&m_udpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(onErrorOccurred(QAbstractSocket::SocketError)));
#else
connect(&m_tcpSocket, &QTcpSocket::errorOccurred,
this, &IO::Drivers::Network::onErrorOccurred);
connect(&m_udpSocket, &QUdpSocket::errorOccurred,
this, &IO::Drivers::Network::onErrorOccurred);
#endif
// clang-format on
}
/**
* Returns the only instance of this class
*/
IO::Drivers::Network &IO::Drivers::Network::instance()
{
static Network singleton;
return singleton;
}
//----------------------------------------------------------------------------------------
// HAL driver implementation
//----------------------------------------------------------------------------------------
/**
* Closes the current network connection and discards signals/slots with the TCP/UDP
* socket in use by the network module.
*/
void IO::Drivers::Network::close()
{
// Abort network connections
m_tcpSocket.abort();
m_udpSocket.abort();
m_tcpSocket.disconnectFromHost();
m_udpSocket.disconnectFromHost();
// Disconnect signals/slots
if (socketType() == QAbstractSocket::TcpSocket)
disconnect(&m_tcpSocket, &QTcpSocket::readyRead, this,
&IO::Drivers::Network::onReadyRead);
else if (socketType() == QAbstractSocket::UdpSocket)
disconnect(&m_udpSocket, &QUdpSocket::readyRead, this,
&IO::Drivers::Network::onReadyRead);
}
/**
* Returns @c true if a network connection is currently open
*/
bool IO::Drivers::Network::isOpen() const
{
if (socketType() == QAbstractSocket::UdpSocket)
return m_udpSocket.isOpen();
else if (socketType() == QAbstractSocket::TcpSocket)
return m_tcpSocket.isOpen();
return false;
}
/**
* Returns @c true if the current network device is readable
*/
bool IO::Drivers::Network::isReadable() const
{
if (socketType() == QAbstractSocket::UdpSocket)
return m_udpSocket.isReadable();
else if (socketType() == QAbstractSocket::TcpSocket)
return m_tcpSocket.isReadable();
return false;
}
/**
* Returns @c true if the current network device is writable
*/
bool IO::Drivers::Network::isWritable() const
{
if (socketType() == QAbstractSocket::UdpSocket)
return m_udpSocket.isWritable();
else if (socketType() == QAbstractSocket::TcpSocket)
return m_tcpSocket.isWritable();
return false;
}
/**
* Returns @c true if the port is greater than 0 and the host address is valid.
*/
bool IO::Drivers::Network::configurationOk() const
{
return tcpPort() > 0 && m_hostExists;
}
/**
* Writes the given @a data to the network device and returns the number of bytes written
*/
quint64 IO::Drivers::Network::write(const QByteArray &data)
{
if (isWritable())
{
if (socketType() == QAbstractSocket::UdpSocket)
return m_udpSocket.write(data);
else if (socketType() == QAbstractSocket::TcpSocket)
return m_tcpSocket.write(data);
}
return -1;
}
/**
* Attempts to make a connection to the given host, port and TCP/UDP socket type.
* Returns @c true on success, @c false on failure
*/
bool IO::Drivers::Network::open(const QIODevice::OpenMode mode)
{
// Disconnect all sockets
close();
// Get host & port
auto hostAddr = remoteAddress();
if (hostAddr.isEmpty())
hostAddr = defaultAddress();
// Init socket pointer
QIODevice *socket = Q_NULLPTR;
// TCP connection, assign socket pointer & connect to host
if (socketType() == QAbstractSocket::TcpSocket)
{
socket = static_cast<QIODevice *>(&m_tcpSocket);
m_tcpSocket.connectToHost(hostAddr, tcpPort());
}
// UDP connection, assign socket pointer & bind to host
else if (socketType() == QAbstractSocket::UdpSocket)
{
// Bind the UDP socket
// clang-format off
m_udpSocket.bind(udpLocalPort(),
QAbstractSocket::ShareAddress |
QAbstractSocket::ReuseAddressHint);
// clang-format on
// Join the multicast group (if required)
if (udpMulticast())
m_udpSocket.joinMulticastGroup(QHostAddress(m_address));
// Set socket pointer
socket = static_cast<QIODevice *>(&m_udpSocket);
}
// Open network socket
if (socket)
{
if (socket->open(mode))
{
connect(socket, &QIODevice::readyRead, this,
&IO::Drivers::Network::onReadyRead);
return true;
}
}
// Open failure, abort connection
close();
return false;
}
//----------------------------------------------------------------------------------------
// Driver specifics
//----------------------------------------------------------------------------------------
/**
* Returns the host address
*/
QString IO::Drivers::Network::remoteAddress() const
{
return m_address;
}
/**
* Returns the TCP port number
*/
quint16 IO::Drivers::Network::tcpPort() const
{
return m_tcpPort;
}
/**
* Returns the UDP local port number
*/
quint16 IO::Drivers::Network::udpLocalPort() const
{
return m_udpLocalPort;
}
/**
* Returns the UDP remote port number
*/
quint16 IO::Drivers::Network::udpRemotePort() const
{
return m_udpRemotePort;
}
/**
* Returns @c true if the UDP socket is managing a multicasted
* connection.
*/
bool IO::Drivers::Network::udpMulticast() const
{
return m_udpMulticast;
}
/**
* Returns @c true if we are currently performing a DNS lookup
*/
bool IO::Drivers::Network::lookupActive() const
{
return m_lookupActive;
}
/**
* Returns the current socket type as an index of the list returned by the @c socketType
* function.
*/
int IO::Drivers::Network::socketTypeIndex() const
{
switch (socketType())
{
case QAbstractSocket::TcpSocket:
return 0;
break;
case QAbstractSocket::UdpSocket:
return 1;
break;
default:
return -1;
break;
}
}
/**
* Returns a list with the available socket types
*/
StringList IO::Drivers::Network::socketTypes() const
{
return StringList { "TCP", "UDP" };
}
/**
* Returns @c true if the @c IO::Manager should not check for start/end
* frame sequences when an UDP datagram is received.
*/
bool IO::Drivers::Network::udpIgnoreFrameSequences() const
{
return m_udpIgnoreFrameSequences;
}
/**
* Returns the socket type. Valid return values are:
*
* @c QAbstractSocket::TcpSocket
* @c QAbstractSocket::UdpSocket
* @c QAbstractSocket::SctpSocket
* @c QAbstractSocket::UnknownSocketType
*/
QAbstractSocket::SocketType IO::Drivers::Network::socketType() const
{
return m_socketType;
}
/**
* Instructs the module to communicate via a TCP socket.
*/
void IO::Drivers::Network::setTcpSocket()
{
setSocketType(QAbstractSocket::TcpSocket);
}
/**
* Instructs the module to communicate via an UDP socket.
*/
void IO::Drivers::Network::setUdpSocket()
{
setSocketType(QAbstractSocket::UdpSocket);
}
/**
* Changes the TCP socket's @c port number
*/
void IO::Drivers::Network::setTcpPort(const quint16 port)
{
m_tcpPort = port;
Q_EMIT portChanged();
}
/**
* Changes the UDP socket's local @c port number
*/
void IO::Drivers::Network::setUdpLocalPort(const quint16 port)
{
m_udpLocalPort = port;
Q_EMIT portChanged();
}
/**
* Changes the UDP socket's remote @c port number
*/
void IO::Drivers::Network::setUdpRemotePort(const quint16 port)
{
m_udpRemotePort = port;
Q_EMIT portChanged();
}
/**
* Sets the IPv4 or IPv6 address specified by the input string representation
*/
void IO::Drivers::Network::setRemoteAddress(const QString &address)
{
// Check if host name exists
if (QHostAddress(address).isNull())
{
m_hostExists = false;
lookup(address);
}
// Host is an IP address, host should exist
else
m_hostExists = true;
// Change host
m_address = address;
Q_EMIT addressChanged();
}
/**
* If @a ignore is set to @c true, then the @c IO::Manager should not check
* for start/end frame sequences when an UDP datagram is received.
*
* Otherwise, the @c IO::Manager shall check for start/end sequences to identify
* incoming frames.
*/
void IO::Drivers::Network::setUdpIgnoreFrameSequences(const bool ignore)
{
m_udpIgnoreFrameSequences = ignore;
Q_EMIT udpIgnoreFrameSequencesChanged();
}
/**
* Performs a DNS lookup for the given @a host name
*/
void IO::Drivers::Network::lookup(const QString &host)
{
m_lookupActive = true;
Q_EMIT lookupActiveChanged();
QHostInfo::lookupHost(host.simplified(), this, &IO::Drivers::Network::lookupFinished);
}
/**
* Enables/Disables multicast connections with the UDP socket.
*/
void IO::Drivers::Network::setUdpMulticast(const bool enabled)
{
m_udpMulticast = enabled;
Q_EMIT udpMulticastChanged();
}
/**
* Changes the current socket type given an index of the list returned by the
* @c socketType() function.
*/
void IO::Drivers::Network::setSocketTypeIndex(const int index)
{
switch (index)
{
case 0:
setTcpSocket();
break;
case 1:
setUdpSocket();
break;
default:
break;
}
}
/**
* Changes the socket type. Valid input values are:
*
* @c QAbstractSocket::TcpSocket
* @c QAbstractSocket::UdpSocket
* @c QAbstractSocket::UnknownSocketType
*/
void IO::Drivers::Network::setSocketType(const QAbstractSocket::SocketType type)
{
m_socketType = type;
Q_EMIT socketTypeChanged();
}
/**
* Reads incoming data from the UDP/TCP ports
*/
void IO::Drivers::Network::onReadyRead()
{
// Initialize byte array
QByteArray data;
// Check if we need to use UDP socket functions
if (socketType() == QAbstractSocket::UdpSocket)
{
while (udpSocket()->hasPendingDatagrams())
{
// Read datagram data
QByteArray datagram;
datagram.resize(int(udpSocket()->pendingDatagramSize()));
udpSocket()->readDatagram(datagram.data(), datagram.size());
// Add datagram to data buffer
if (!udpIgnoreFrameSequences())
{
data.append(datagram);
Q_EMIT dataReceived(data);
}
// Ingore start/end sequences & process frame directly
else
IO::Manager::instance().processPayload(datagram);
}
}
// We are using the TCP socket...
else if (socketType() == QAbstractSocket::TcpSocket)
{
data = tcpSocket()->readAll();
Q_EMIT dataReceived(data);
}
}
/**
* Sets the host IP address when the lookup finishes.
* If the lookup fails, the error code/string shall be shown to the user in a messagebox.
*/
void IO::Drivers::Network::lookupFinished(const QHostInfo &info)
{
m_lookupActive = false;
if (info.error() == QHostInfo::NoError)
{
auto addresses = info.addresses();
if (addresses.count() >= 1)
{
m_hostExists = true;
Q_EMIT addressChanged();
return;
}
}
Q_EMIT lookupActiveChanged();
}
/**
* 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 IO::Drivers::Network::onErrorOccurred(const QAbstractSocket::SocketError socketError)
{
QString error;
if (socketType() == QAbstractSocket::TcpSocket)
error = m_tcpSocket.errorString();
else if (socketType() == QAbstractSocket::UdpSocket)
error = m_udpSocket.errorString();
else
error = QString::number(socketError);
Manager::instance().disconnectDriver();
Misc::Utilities::showMessageBox(tr("Network socket error"), error);
}
#ifdef SERIAL_STUDIO_INCLUDE_MOC
# include "moc_Network.cpp"
#endif