File indexing completed on 2024-05-05 17:40:02

0001 /*
0002     SPDX-FileCopyrightText: 2019 David Edmundson <davidedmundson@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "SensorObject.h"
0008 
0009 #include "SensorContainer.h"
0010 
0011 using namespace KSysGuard;
0012 
0013 class Q_DECL_HIDDEN SensorObject::Private
0014 {
0015 public:
0016     SensorContainer *parent = nullptr;
0017     QString id;
0018     QString name;
0019     QHash<QString, SensorProperty *> sensors;
0020 };
0021 
0022 SensorObject::SensorObject(const QString &id, SensorContainer *parent)
0023     : SensorObject(id, QString(), parent)
0024 {
0025 }
0026 
0027 SensorObject::SensorObject(const QString &id, const QString &name, SensorContainer *parent)
0028     : QObject(parent)
0029     , d(std::make_unique<Private>())
0030 {
0031     d->parent = parent;
0032     d->id = id;
0033     d->name = name;
0034 
0035     if (parent) {
0036         QMetaObject::invokeMethod(
0037             parent,
0038             [this, parent] {
0039                 parent->addObject(this);
0040             },
0041             Qt::QueuedConnection);
0042     }
0043 }
0044 
0045 SensorObject::~SensorObject() = default;
0046 
0047 QString SensorObject::id() const
0048 {
0049     return d->id;
0050 }
0051 
0052 QString SensorObject::name() const
0053 {
0054     return d->name;
0055 }
0056 
0057 QString SensorObject::path() const
0058 {
0059     if (!d->parent) {
0060         return QString{};
0061     }
0062 
0063     return d->parent->id() % QLatin1Char('/') % d->id;
0064 }
0065 
0066 void SensorObject::setName(const QString &newName)
0067 {
0068     if (newName == d->name) {
0069         return;
0070     }
0071 
0072     d->name = newName;
0073     Q_EMIT nameChanged();
0074 }
0075 
0076 void SensorObject::setParentContainer(SensorContainer *parent)
0077 {
0078     d->parent = parent;
0079 }
0080 
0081 QList<SensorProperty *> SensorObject::sensors() const
0082 {
0083     return d->sensors.values();
0084 }
0085 
0086 SensorProperty *SensorObject::sensor(const QString &sensorId) const
0087 {
0088     return d->sensors.value(sensorId);
0089 }
0090 
0091 void SensorObject::addProperty(SensorProperty *property)
0092 {
0093     d->sensors[property->id()] = property;
0094 
0095     connect(property, &SensorProperty::subscribedChanged, this, [=]() {
0096         uint count = std::count_if(d->sensors.constBegin(), d->sensors.constEnd(), [](const SensorProperty *prop) {
0097             return prop->isSubscribed();
0098         });
0099         if (count == 1) {
0100             Q_EMIT subscribedChanged(true);
0101         } else if (count == 0) {
0102             Q_EMIT subscribedChanged(false);
0103         }
0104     });
0105 }
0106 
0107 bool SensorObject::isSubscribed() const
0108 {
0109     return std::any_of(d->sensors.constBegin(), d->sensors.constEnd(), [](const SensorProperty *prop) {
0110         return prop->isSubscribed();
0111     });
0112 }