File: batterycontroller.cpp

package info (click to toggle)
powerdevil 4%3A6.5.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,680 kB
  • sloc: cpp: 13,284; xml: 1,911; python: 1,204; sh: 19; makefile: 10
file content (235 lines) | stat: -rw-r--r-- 8,385 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
/*  This file is part of the KDE project
    SPDX-FileCopyrightText: 2006 Kevin Ottens <ervin@kde.org>
    SPDX-FileCopyrightText: 2008-2010 Dario Freddi <drf@kde.org>
    SPDX-FileCopyrightText: 2010 Alejandro Fiestas <alex@eyeos.org>
    SPDX-FileCopyrightText: 2010-2013 Lukáš Tinkl <ltinkl@redhat.com>
    SPDX-FileCopyrightText: 2015 Kai Uwe Broulik <kde@privat.broulik.de>

    SPDX-License-Identifier: LGPL-2.0-only

*/

#include "batterycontroller.h"

#include <QDBusConnection>

using namespace Qt::StringLiterals;

inline constexpr QLatin1StringView UPOWER_SERVICE("org.freedesktop.UPower");
inline constexpr QLatin1StringView UPOWER_PATH("/org/freedesktop/UPower");
inline constexpr QLatin1StringView UPOWER_IFACE("org.freedesktop.UPower");
inline constexpr QLatin1StringView UPOWER_IFACE_DEVICE("org.freedesktop.UPower.Device");

BatteryController::BatteryController()
    : QObject()
{
    QDBusConnection::systemBus().connect(UPOWER_SERVICE,
                                         UPOWER_PATH,
                                         u"org.freedesktop.DBus.Properties"_s,
                                         u"PropertiesChanged"_s,
                                         this,
                                         SLOT(onPropertiesChanged(QString, QVariantMap, QStringList)));

    QDBusConnection::systemBus().connect(UPOWER_SERVICE, UPOWER_PATH, UPOWER_IFACE, u"DeviceAdded"_s, this, SLOT(slotDeviceAdded(QDBusObjectPath)));
    QDBusConnection::systemBus().connect(UPOWER_SERVICE, UPOWER_PATH, UPOWER_IFACE, u"DeviceRemoved"_s, this, SLOT(slotDeviceRemoved(QDBusObjectPath)));

    m_upowerInterface = new OrgFreedesktopUPowerInterface(UPOWER_SERVICE, u"/org/freedesktop/UPower"_s, QDBusConnection::systemBus(), this);

    m_onBattery = m_upowerInterface->onBattery();

    QDBusReply<QDBusObjectPath> reply = m_upowerInterface->call(u"GetDisplayDevice"_s);
    if (reply.isValid()) {
        const QString path = reply.value().path();
        if (!path.isEmpty() && path != QStringLiteral("/")) {
            m_displayDevice = std::make_unique<UPowerDevice>(path);
            connect(m_displayDevice.get(), &UPowerDevice::propertiesChanged, this, &BatteryController::updateDeviceProps);
        }
    }

    if (!m_displayDevice) {
        const QList<QDBusObjectPath> deviceList = m_upowerInterface->EnumerateDevices();
        for (const QDBusObjectPath &device : deviceList) {
            if (m_devices.count(device.path())) {
                continue;
            }
            addDevice(device.path());
        }
    }

    updateDeviceProps();

    if (m_onBattery) {
        m_acAdapterState = Unplugged;
    } else {
        m_acAdapterState = Plugged;
    }
    Q_EMIT acAdapterStateChanged(m_acAdapterState);
}

void BatteryController::addDevice(const QString &device)
{
    if (m_displayDevice) {
        return;
    }

    auto upowerDevice = std::make_unique<UPowerDevice>(device);
    connect(upowerDevice.get(), &UPowerDevice::propertiesChanged, this, &BatteryController::updateDeviceProps);

    m_devices[device] = std::move(upowerDevice);
}

void BatteryController::slotDeviceAdded(const QDBusObjectPath &path)
{
    addDevice(path.path());
    updateDeviceProps();
}

void BatteryController::slotDeviceRemoved(const QDBusObjectPath &path)
{
    m_devices.erase(path.path());
    updateDeviceProps();
}

void BatteryController::updateDeviceProps()
{
    double energyTotal = 0.0;
    double energyRateTotal = 0.0; // +: charging, -: discharging (contrary to EnergyRate)
    double energyFullTotal = 0.0;
    qulonglong timestamp = 0;

    if (m_displayDevice) {
        if (!m_displayDevice->isPresent()) {
            // No Battery/Ups, nothing to report
            return;
        }
        const auto state = m_displayDevice->state();
        energyTotal = m_displayDevice->energy();
        energyFullTotal = m_displayDevice->energyFull();
        timestamp = m_displayDevice->updateTime();
        // Workaround for https://gitlab.freedesktop.org/upower/upower/-/issues/252
        if (state == UPowerDevice::State::Charging) {
            energyRateTotal = std::abs(m_displayDevice->energyRate());
        } else if (state == UPowerDevice::State::Discharging) {
            energyRateTotal = -std::abs(m_displayDevice->energyRate());
        }
    } else {
        for (const auto &[key, upowerDevice] : m_devices) {
            if (!upowerDevice->isPowerSupply() || !upowerDevice->isPresent()) {
                continue;
            }
            const auto type = upowerDevice->type();
            if (type == UPowerDevice::Type::Battery || type == UPowerDevice::Type::Ups) {
                const auto state = upowerDevice->state();
                energyFullTotal += upowerDevice->energyFull();
                energyTotal += upowerDevice->energy();

                if (state == UPowerDevice::State::FullyCharged) {
                    continue;
                }

                timestamp = std::max(timestamp, upowerDevice->updateTime());
                // Workaround for https://gitlab.freedesktop.org/upower/upower/-/issues/252
                if (state == UPowerDevice::State::Charging) {
                    energyRateTotal += std::abs(upowerDevice->energyRate());
                } else if (state == UPowerDevice::State::Discharging) {
                    energyRateTotal -= std::abs(upowerDevice->energyRate());
                }
            }
        }
    }

    m_batteryEnergy = energyTotal;
    m_batteryEnergyFull = energyFullTotal;
    setBatteryRate(energyRateTotal, timestamp);
}

void BatteryController::onPropertiesChanged(const QString &ifaceName, const QVariantMap &changedProps, const QStringList &invalidatedProps)
{
    if (ifaceName != UPOWER_IFACE) {
        return;
    }

    bool onBattery = m_onBattery;
    if (changedProps.contains(QStringLiteral("OnBattery"))) {
        onBattery = changedProps[QStringLiteral("OnBattery")].toBool();
    } else if (invalidatedProps.contains(QStringLiteral("OnBattery"))) {
        onBattery = m_upowerInterface->onBattery();
    }
    if (onBattery != m_onBattery) {
        m_acAdapterState = onBattery ? Unplugged : Plugged;
        Q_EMIT acAdapterStateChanged(m_acAdapterState);
        m_onBattery = onBattery;
    }
}

/**
 * Filter data along one dimension using exponential moving average.
 */
double emafilter(const double last, const double update, double weight)
{
    double current = last * (1 - weight) + update * weight;

    return current;
}

void BatteryController::setBatteryRate(const double rate, qulonglong timestamp)
{
    // remaining time in milliseconds
    qulonglong time = 0;

    if (rate > 0) {
        // Energy and rate are in Watt*hours resp. Watt
        time = 3600 * 1000 * (m_batteryEnergyFull - m_batteryEnergy) / rate;
    } else if (rate < 0) {
        time = 3600 * 1000 * (0.0 - m_batteryEnergy) / rate;
    }

    if (m_batteryRemainingTime != time) {
        m_batteryRemainingTime = time;
        Q_EMIT batteryRemainingTimeChanged(time);
    }

    // Charging or full
    if ((rate > 0) || (time == 0)) {
        if (m_smoothedBatteryRemainingTime != time) {
            m_smoothedBatteryRemainingTime = time;
            Q_EMIT smoothedBatteryRemainingTimeChanged(time);
        }
        return;
    }

    double oldRate = m_smoothedBatteryDischargeRate;
    if (oldRate == 0) {
        m_smoothedBatteryDischargeRate = rate;
    } else {
        // To have a time constant independent from the update frequency
        // the weight must be scaled
        double weight = 0.005 * std::min<qulonglong>(60, timestamp - m_lastRateTimestamp);
        m_lastRateTimestamp = timestamp;
        m_smoothedBatteryDischargeRate = emafilter(oldRate, rate, weight);
    }

    time = 3600 * 1000 * (0.0 - m_batteryEnergy) / m_smoothedBatteryDischargeRate;

    if (m_smoothedBatteryRemainingTime != time) {
        m_smoothedBatteryRemainingTime = time;
        Q_EMIT smoothedBatteryRemainingTimeChanged(m_smoothedBatteryRemainingTime);
    }
}

BatteryController::AcAdapterState BatteryController::acAdapterState() const
{
    return m_acAdapterState;
}

qulonglong BatteryController::batteryRemainingTime() const
{
    return m_batteryRemainingTime;
}

qulonglong BatteryController::smoothedBatteryRemainingTime() const
{
    return m_smoothedBatteryRemainingTime;
}

#include "moc_batterycontroller.cpp"