swift
Loading...
Searching...
No Matches
clientconnection.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2019 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QNetworkDatagram>
7
9#include "misc/logmessage.h"
10
11using namespace swift::config;
12using namespace swift::misc;
13using namespace swift::core::afv::crypto;
14
15namespace swift::core::afv::connection
16{
18 : QObject(parent), m_udpSocket(new QUdpSocket(this)), m_voiceServerTimer(new QTimer(this)),
19 m_apiServerConnection(new CApiServerConnection(apiServer, this))
20 {
21 CLogMessage(this).debug(u"ClientConnection instantiated");
22
23 // connect(&m_apiServerConnection, &ApiServerConnection::authenticationFinished, this,
24 // &ClientConnection::apiConnectionFinished); connect(&m_apiServerConnection,
25 // &ApiServerConnection::addCallsignFinished, this, &ClientConnection::addCallsignFinished);
26 // connect(&m_apiServerConnection, &ApiServerConnection::removeCallsignFinished, this,
27 // &ClientConnection::removeCallsignFinished);
28
29 connect(m_voiceServerTimer, &QTimer::timeout, this,
30 &CClientConnection::voiceServerHeartbeat); // sends heartbeat to server
31 connect(m_udpSocket, &QUdpSocket::readyRead, this, &CClientConnection::readPendingDatagrams);
32 connect(m_udpSocket, &QAbstractSocket::errorOccurred, this, &CClientConnection::handleSocketError);
33 }
34
35 void CClientConnection::connectTo(const QString &userName, const QString &password, const QString &callsign,
36 const QString &client, ConnectionCallback callback)
37 {
38 if (m_connection.isConnected())
39 {
40 CLogMessage(this).debug(u"Client already connected to network");
41 return;
42 }
43
44 m_connection.setUserName(userName);
45 m_connection.setCallsign(callsign);
46
47 QPointer<CClientConnection> myself(this);
48 m_apiServerConnection->connectTo(
49 userName, password, client, m_networkVersion,
50 { // callback called when connected
51 this, [=, this](bool authenticated) {
52 // callback when connection has been established
53 if (!myself)
54 {
55 return;
56 } // cppcheck-suppress knownConditionTrueFalse
57
58 if (authenticated)
59 {
60 const QString cs = m_connection.getCallsign();
61 m_connection.setTokens(m_apiServerConnection->addCallsign(cs));
62 m_connection.setTsAuthenticatedToNow();
63 m_connection.createCryptoChannels();
64 m_connection.setTsHeartbeatToNow();
65 this->connectToVoiceServer();
66 // taskServerConnectionCheck.Start();
67
68 CLogMessage(this).info(u"Connected: '%1' to voice server, socket open: %2")
69 << cs << boolToYesNo(m_udpSocket->isOpen());
70 }
71 else
72 {
73 m_connection.reset();
74 }
75
76 // Make sure crypto channels etc. are created
77 m_connection.setConnected(authenticated);
78
79 // callback of the calling parent
80 if (callback)
81 {
82 callback(authenticated);
83 }
84 } });
85 }
86
88 {
89 if (!m_connection.isConnected())
90 {
91 CLogMessage(this).debug(u"Client not connected");
92 return;
93 }
94
95 m_connection.setConnected(false);
96 // TODO emit disconnected(reason)
97 CLogMessage(this).debug(u"Disconnected client: %1") << reason;
98
99 if (!m_connection.getCallsign().isEmpty())
100 {
101 m_apiServerConnection->removeCallsign(m_connection.getCallsign());
102 }
103
104 // TODO connectionCheckCancelTokenSource.Cancel(); // Stops connection check loop
105 disconnectFromVoiceServer();
106 m_apiServerConnection->forceDisconnect();
107 m_connection.reset();
108
109 CLogMessage(this).debug(u"Disconnection complete");
110 }
111
113 {
114 m_apiServerConnection->updateTransceivers(callsign, transceivers);
115 }
116
118 {
119 return m_apiServerConnection->getAllAliasedStations();
120 }
121
123 {
124 if (!m_apiServerConnection)
125 {
126 return false;
127 }
128 return m_apiServerConnection->setUrl(url);
129 }
130
132 {
133 static const QString e;
134 if (!m_apiServerConnection)
135 {
136 return e;
137 }
138 return m_apiServerConnection->getUrl();
139 }
140
141 void CClientConnection::connectToVoiceServer()
142 {
143 const QHostAddress localAddress(QHostAddress::AnyIPv4);
144 m_udpSocket->bind(localAddress);
145 m_voiceServerTimer->start(3000);
146
147 CLogMessage(this).info(u"Connected to voice server '%1'") << m_connection.getTokens().VoiceServer.addressIpV4;
148 }
149
150 void CClientConnection::disconnectFromVoiceServer()
151 {
152 m_voiceServerTimer->stop();
153 m_udpSocket->disconnectFromHost();
154 CLogMessage(this).info(u"All TaskVoiceServer tasks stopped");
155 }
156
157 void CClientConnection::readPendingDatagrams()
158 {
159 while (m_udpSocket->hasPendingDatagrams())
160 {
161 const QNetworkDatagram datagram = m_udpSocket->receiveDatagram();
162 this->processMessage(datagram.data());
163 }
164 }
165
166 void CClientConnection::processMessage(const QByteArray &messageDdata, bool loopback)
167 {
168 if (!m_connection.m_voiceCryptoChannel)
169 {
170 SWIFT_VERIFY_X(false, Q_FUNC_INFO, "processMessage used without crypto channel");
171 return;
172 }
173
174 CryptoDtoSerializer::Deserializer deserializer =
175 CryptoDtoSerializer::deserialize(*m_connection.m_voiceCryptoChannel, messageDdata, loopback);
176
178 {
179 // qDebug() << "Received audio data";
180 const auto audioOnTransceiverDto = deserializer.getDto<AudioRxOnTransceiversDto>();
181 if (m_connection.isReceivingAudio() && m_connection.isConnected())
182 {
183 emit audioReceived(audioOnTransceiverDto);
184 }
185 }
186 else if (deserializer.m_dtoNameBuffer == HeartbeatAckDto::getShortDtoName())
187 {
188 m_connection.setTsHeartbeatToNow();
190 {
191 CLogMessage(this).debug(u"Received voice server heartbeat");
192 }
193 }
194 else
195 {
196 CLogMessage(this).warning(u"Received unknown data: %1 %2")
197 << QString(deserializer.m_dtoNameBuffer) << deserializer.m_dataLength;
198 }
199 }
200
201 void CClientConnection::handleSocketError(QAbstractSocket::SocketError error)
202 {
203 Q_UNUSED(error)
204 CLogMessage(this).debug(u"UDP socket error: '%1'") << m_udpSocket->errorString();
205 }
206
207 void CClientConnection::voiceServerHeartbeat()
208 {
209 if (!m_connection.m_voiceCryptoChannel || !m_udpSocket)
210 {
211 SWIFT_VERIFY_X(false, Q_FUNC_INFO, "voiceServerHeartbeat used without crypto channel or socket");
212 return;
213 }
214
215 const QUrl voiceServerUrl("udp://" + m_connection.getTokens().VoiceServer.addressIpV4);
217 {
218 CLogMessage(this).debug(u"Sending voice server heartbeat to '%1'") << voiceServerUrl.host();
219 }
220 HeartbeatDto keepAlive;
221 keepAlive.callsign = m_connection.getCallsign().toStdString();
222 const QByteArray dataBytes = CryptoDtoSerializer::serialize(*m_connection.m_voiceCryptoChannel,
223 CryptoDtoMode::AEAD_ChaCha20Poly1305, keepAlive);
224 m_udpSocket->writeDatagram(dataBytes, QHostAddress(voiceServerUrl.host()),
225 static_cast<quint16>(voiceServerUrl.port()));
226 }
227} // namespace swift::core::afv::connection
swift::misc::CSlot< void(bool)> ConnectionCallback
Callback for.
static bool isLocalDeveloperDebugBuild()
Local build for developers.
const PostCallsignResponseDto & getTokens() const
Tokens.
QScopedPointer< crypto::CCryptoDtoChannel > m_voiceCryptoChannel
used crypto channel
void updateTransceivers(const QString &callsign, const QVector< TransceiverDto > &transceivers)
Update transceivers.
CClientConnection(const QString &apiServer, QObject *parent=nullptr)
Ctor.
bool updateVoiceServerUrl(const QString &url)
Update the voice server URL.
void disconnectFrom(const QString &reason={})
Disconnect.
void audioReceived(const AudioRxOnTransceiversDto &dto)
Audio has been received.
QVector< StationDto > getAllAliasedStations()
All aliased stations.
const QString & getVoiceServerUrl() const
Get the voice server URL.
void connectTo(const QString &userName, const QString &password, const QString &callsign, const QString &client, ConnectionCallback callback)
Connect.
static QByteArray serialize(const QString &channelTag, CryptoDtoMode mode, const QByteArray &transmitKey, uint sequenceToBeSent, T dto)
Serialize a DTO.
static Deserializer deserialize(CCryptoDtoChannel &channel, const QByteArray &bytes, bool loopback)
Deserialize.
Class for emitting a log message.
Definition logmessage.h:27
Derived & debug()
Set the severity to debug.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
Free functions in swift::misc.
SWIFT_MISC_EXPORT const QString & boolToYesNo(bool v)
Bool to yes/no.
bool bind(QHostAddress::SpecialAddress addr, quint16 port, QAbstractSocket::BindMode mode)
virtual void disconnectFromHost()
void errorOccurred(QAbstractSocket::SocketError socketError)
void readyRead()
QByteArray data() const const
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QObject * parent() const const
void start()
void stop()
void timeout()
bool hasPendingDatagrams() const const
QNetworkDatagram receiveDatagram(qint64 maxSize)
static QByteArray getShortDtoName()
Names.
Definition dto.h:260
static QByteArray getShortDtoName()
Name.
Definition dto.h:198
std::string callsign
callsign
Definition dto.h:188
VoiceServerConnectionDataDto VoiceServer
Properties.
Definition dto.h:91
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26