File: signalindicator.cpp

package info (click to toggle)
plasma-mobile 6.3.6-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 18,612 kB
  • sloc: xml: 38,470; cpp: 18,437; javascript: 139; sh: 82; makefile: 5
file content (380 lines) | stat: -rw-r--r-- 14,149 bytes parent folder | download | duplicates (2)
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
// SPDX-FileCopyrightText: 2021 Tobias Fella <fella@posteo.de>
// SPDX-FileCopyrightText: 2022-2023 Devin Lin <devin@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "signalindicator.h"

#include <NetworkManagerQt/GsmSetting>
#include <NetworkManagerQt/Manager>
#include <NetworkManagerQt/Settings>
#include <NetworkManagerQt/Utils>
#include <QDBusReply>

#include <KUser>

#include "signalindicator.h"

SignalIndicator::SignalIndicator(QObject *parent)
    : QObject{parent}
    , m_nmModem{nullptr}
    , m_modemDevice{nullptr}
    , m_modem{nullptr}
    , m_3gppModem{nullptr}
{
    connect(ModemManager::notifier(), &ModemManager::Notifier::modemAdded, this, &SignalIndicator::updateModemManagerModem);
    connect(ModemManager::notifier(), &ModemManager::Notifier::modemRemoved, this, &SignalIndicator::updateModemManagerModem);

    connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, this, &SignalIndicator::mobileDataEnabledChanged);
    connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionRemoved, this, &SignalIndicator::mobileDataEnabledChanged);
    connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, this, &SignalIndicator::mobileDataEnabledChanged);
    connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionRemoved, this, &SignalIndicator::mobileDataEnabledChanged);
    connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, this, &SignalIndicator::updateNetworkManagerModem);
    connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, this, &SignalIndicator::updateNetworkManagerModem);

    updateModemManagerModem();
}

int SignalIndicator::strength() const
{
    if (!m_modem) {
        return 0;
    }
    return m_modem->signalQuality().signal;
}

QString SignalIndicator::name() const
{
    return m_3gppModem ? m_3gppModem->operatorName() : QString();
}

bool SignalIndicator::modemAvailable() const
{
    return !m_modem.isNull();
}

bool SignalIndicator::simLocked() const
{
    if (!m_modem) {
        return false;
    }
    return m_modem->unlockRequired() == MM_MODEM_LOCK_SIM_PIN;
}

bool SignalIndicator::simEmpty() const
{
    return !m_modemDevice || !m_modemDevice->sim() || (m_modemDevice->sim()->uni() == QStringLiteral("/"));
}

bool SignalIndicator::mobileDataSupported() const
{
    return m_nmModem && !simEmpty();
}

bool SignalIndicator::mobileDataEnabled() const
{
    // if wwan is globally disabled
    if (!NetworkManager::isWwanEnabled()) {
        return false;
    }

    // no modem -> no mobile data -> report disabled
    if (!m_nmModem) {
        return false;
    }

    // mobile data already activated -> report enabled
    if (m_nmModem->state() == NetworkManager::Device::Activated) {
        return true;
    }

    // autoconnect disabled on the entire modem -> report disabled
    if (!m_nmModem->autoconnect()) {
        return false;
    }

    // at least one connection set to autoconnect -> report enabled
    for (NetworkManager::Connection::Ptr con : m_nmModem->availableConnections()) {
        if (con->settings()->autoconnect()) {
            return true;
        }
    }

    // modem, but no connection, set to autoconnect -> report disabled (#182)
    return false;
}

bool SignalIndicator::needsAPNAdded() const
{
    return m_nmModem && mobileDataSupported() && m_nmModem->availableConnections().count() == 0;
}

void SignalIndicator::setMobileDataEnabled(bool enabled)
{
    // ensure that wwan is on
    if (enabled && !NetworkManager::isWwanEnabled()) {
        NetworkManager::setWwanEnabled(true);
    }

    if (!m_nmModem) {
        return;
    }

    if (enabled) {
        // enable mobile data...

        m_nmModem->setAutoconnect(true);

        // activate the connection that was last used
        QDateTime latestTimestamp;
        NetworkManager::Connection::Ptr latestCon;
        for (NetworkManager::Connection::Ptr con : m_nmModem->availableConnections()) {
            QDateTime timestamp = con->settings()->timestamp();
            // if con was not used yet, skip it, otherwise:
            // if we have no latestTimestamp yet, con is the latest
            // otherwise, compare the timestamps
            // in case of a tie, use the first connection that was found
            if (!timestamp.isNull() && (latestTimestamp.isNull() || timestamp > latestTimestamp)) {
                latestTimestamp = timestamp;
                latestCon = con;
            }
        }

        // if we found the last used connection
        if (!latestCon.isNull()) {
            // set it to autoconnect and connect it immediately
            latestCon->settings()->setAutoconnect(true);
            latestCon->update(latestCon->settings()->toMap());
            NetworkManager::activateConnection(latestCon->path(), m_nmModem->uni(), "");
        }

    } else {
        // disable mobile data...

        // we do not call NetworkManager::setWwanEnabled(false), because it turns off cellular

        // turn off autoconnect
        m_nmModem->setAutoconnect(false);
        // we need to also set all connections to not autoconnect (#182)
        for (NetworkManager::Connection::Ptr con : m_nmModem->availableConnections()) {
            con->settings()->setAutoconnect(false);
            con->update(con->settings()->toMap());
        }

        // disconnect network
        m_nmModem->disconnectInterface();
    }
}

QString SignalIndicator::activeConnectionUni() const
{
    if (m_nmModem && m_nmModem->activeConnection() && m_nmModem->activeConnection()->connection()) {
        return m_nmModem->activeConnection()->connection()->uuid();
    }
    return QString();
}

QList<ProfileSettings *> &SignalIndicator::profileList()
{
    return m_profileList;
}

void SignalIndicator::refreshProfiles()
{
    m_profileList.clear();

    if (!m_nmModem) {
        Q_EMIT profileListChanged();
        qWarning() << "No NetworkManager modem found, cannot refresh profiles.";
        return;
    }

    for (auto connection : m_nmModem->availableConnections()) {
        for (auto setting : connection->settings()->settings()) {
            if (setting.dynamicCast<NetworkManager::GsmSetting>()) {
                m_profileList.append(new ProfileSettings(this, setting.dynamicCast<NetworkManager::GsmSetting>(), connection));
            }
        }
    }
    Q_EMIT profileListChanged();
}

QCoro::Task<void> SignalIndicator::activateProfile(const QString &connectionUni)
{
    if (!m_nmModem) {
        qWarning() << "Cannot activate profile since there is no NetworkManager modem";
        co_return;
    }

    qDebug() << QStringLiteral("Activating profile on modem") << m_nmModem->uni() << QStringLiteral("for connection") << connectionUni << ".";

    NetworkManager::Connection::Ptr con;

    // disable autoconnect for all other connections
    for (auto connection : m_nmModem->availableConnections()) {
        if (connection->uuid() == connectionUni) {
            connection->settings()->setAutoconnect(true);
            con = connection;
        } else {
            connection->settings()->setAutoconnect(false);
        }
    }

    if (!con) {
        qDebug() << QStringLiteral("Connection") << connectionUni << QStringLiteral("not found.");
        co_return;
    }

    // activate connection manually
    // despite the documentation saying otherwise, activateConnection seems to need the DBus path, not uuid of the connection
    QDBusReply<QDBusObjectPath> reply = co_await NetworkManager::activateConnection(con->path(), m_nmModem->uni(), {});
    if (!reply.isValid()) {
        qWarning() << QStringLiteral("Error activating connection:") << reply.error().message();
        co_return;
    }
}

QCoro::Task<void> SignalIndicator::addProfile(const QString &name, const QString &apn, const QString &username, const QString &password, const QString &networkType)
{
    if (!m_nmModem) {
        qWarning() << "Cannot add profile since there is no NetworkManager modem";
        co_return;
    }

    NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Gsm)};
    settings->setId(name);
    settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid());
    settings->setAutoconnect(true);
    settings->addToPermissions(KUser().loginName(), QString());

    NetworkManager::GsmSetting::Ptr gsmSetting = settings->setting(NetworkManager::Setting::Gsm).dynamicCast<NetworkManager::GsmSetting>();
    gsmSetting->setApn(apn);
    gsmSetting->setUsername(username);
    gsmSetting->setPassword(password);
    gsmSetting->setPasswordFlags(password.isEmpty() ? NetworkManager::Setting::NotRequired : NetworkManager::Setting::AgentOwned);
    gsmSetting->setNetworkType(ProfileSettings::networkTypeFlag(networkType));

    gsmSetting->setInitialized(true);

    QDBusReply<QDBusObjectPath> reply = co_await NetworkManager::addAndActivateConnection(settings->toMap(), m_nmModem->uni(), {});
    if (!reply.isValid()) {
        qWarning() << "Error adding connection:" << reply.error().message();
    } else {
        qDebug() << "Successfully added a new connection" << name << "with APN" << apn << ".";
    }
}

QCoro::Task<void> SignalIndicator::removeProfile(const QString &connectionUni)
{
    NetworkManager::Connection::Ptr con = NetworkManager::findConnectionByUuid(connectionUni);
    if (!con) {
        qWarning() << "Could not find connection" << connectionUni << "to update!";
        co_return;
    }

    QDBusPendingReply reply = co_await con->remove();
    if (!reply.isValid()) {
        qWarning() << "Error removing connection" << reply.error().message();
    }
}

QCoro::Task<void> SignalIndicator::updateProfile(const QString &connectionUni,
                                                 const QString &name,
                                                 const QString &apn,
                                                 const QString &username,
                                                 const QString &password,
                                                 const QString &networkType)
{
    NetworkManager::Connection::Ptr con = NetworkManager::findConnectionByUuid(connectionUni);
    if (!con) {
        qWarning() << "Could not find connection" << connectionUni << "to update!";
        co_return;
    }

    NetworkManager::ConnectionSettings::Ptr conSettings = con->settings();
    if (!conSettings) {
        qWarning() << "Could not find connection settings for" << connectionUni << "to update!";
        co_return;
    }

    conSettings->setId(name);

    NetworkManager::GsmSetting::Ptr gsmSetting = conSettings->setting(NetworkManager::Setting::Gsm).dynamicCast<NetworkManager::GsmSetting>();
    gsmSetting->setApn(apn);
    gsmSetting->setUsername(username);
    gsmSetting->setPassword(password);
    gsmSetting->setPasswordFlags(password.isEmpty() ? NetworkManager::Setting::NotRequired : NetworkManager::Setting::AgentOwned);
    gsmSetting->setNetworkType(ProfileSettings::networkTypeFlag(networkType));

    gsmSetting->setInitialized(true);

    QDBusPendingReply reply = co_await con->update(conSettings->toMap());
    if (!reply.isValid()) {
        qWarning() << "Error updating connection settings for" << connectionUni << ":" << reply.error().message() << ".";
    } else {
        qDebug() << "Successfully updated connection settings" << connectionUni << ".";
    }
}

void SignalIndicator::updateModemManagerModem()
{
    m_modemDevice = nullptr;
    m_modem = nullptr;
    m_3gppModem = nullptr;

    if (ModemManager::modemDevices().isEmpty()) {
        qWarning() << "No modems available";
        return;
    }

    // TODO: we assume that there is a single modem for the time being
    m_modemDevice = ModemManager::modemDevices()[0];
    m_modem = m_modemDevice->modemInterface();
    m_3gppModem = m_modemDevice->interface(ModemManager::ModemDevice::GsmInterface).objectCast<ModemManager::Modem3gpp>();

    connect(m_modemDevice->sim().get(), &ModemManager::Sim::simIdentifierChanged, this, &SignalIndicator::simEmptyChanged);

    if (m_modem) {
        connect(m_modem.get(), &ModemManager::Modem::signalQualityChanged, this, &SignalIndicator::strengthChanged);
        connect(m_modem.get(), &ModemManager::Modem::unlockRequiredChanged, this, &SignalIndicator::simLockedChanged);
    }
    if (m_3gppModem) {
        connect(m_3gppModem.get(), &ModemManager::Modem3gpp::operatorNameChanged, this, &SignalIndicator::nameChanged);
    }

    updateNetworkManagerModem();

    Q_EMIT nameChanged();
    Q_EMIT strengthChanged();
    Q_EMIT modemAvailableChanged();
}

void SignalIndicator::updateNetworkManagerModem()
{
    m_nmModem = nullptr;
    if (!m_modemDevice) {
        return;
    }

    // find networkmanager modem
    for (NetworkManager::Device::Ptr nmDevice : NetworkManager::networkInterfaces()) {
        if (nmDevice->udi() == m_modemDevice->uni()) {
            m_nmModem = nmDevice.objectCast<NetworkManager::ModemDevice>();

            connect(m_nmModem.get(), &NetworkManager::Device::autoconnectChanged, this, &SignalIndicator::mobileDataEnabledChanged);
            connect(m_nmModem.get(), &NetworkManager::Device::stateChanged, this, &SignalIndicator::mobileDataEnabledChanged);
            connect(m_nmModem.get(), &NetworkManager::Device::availableConnectionAppeared, this, &SignalIndicator::mobileDataEnabledChanged);
            connect(m_nmModem.get(), &NetworkManager::Device::availableConnectionDisappeared, this, &SignalIndicator::mobileDataEnabledChanged);

            connect(m_nmModem.data(), &NetworkManager::ModemDevice::availableConnectionChanged, this, &SignalIndicator::refreshProfiles);
            connect(m_nmModem.data(), &NetworkManager::ModemDevice::activeConnectionChanged, this, [this]() -> void {
                refreshProfiles();
                Q_EMIT activeConnectionUniChanged();
            });

            refreshProfiles();
        }
    }

    Q_EMIT mobileDataSupportedChanged();
    Q_EMIT mobileDataEnabledChanged();
}