Add the ability to add mqtt sensors at runtime
This commit is contained in:
parent
36171a221a
commit
25b9f87285
11 changed files with 208 additions and 0 deletions
|
|
@ -31,6 +31,25 @@ void MqttSensorSource::start(std::shared_ptr<MqttClient> client, const QJsonObje
|
|||
}
|
||||
}
|
||||
|
||||
void MqttSensorSource::addSensor(const QString& topic, const QString& name)
|
||||
{
|
||||
if(!client)
|
||||
return;
|
||||
|
||||
SensorSubscription sensor;
|
||||
sensor.topic = topic;
|
||||
sensor.name = name;
|
||||
sensor.id = qHash(client->getBaseTopic() + "/" + topic);
|
||||
sensors.push_back(sensor);
|
||||
|
||||
// Subscribe if already connected
|
||||
if(client->getClient()->state() == QMqttClient::ClientState::Connected)
|
||||
{
|
||||
sensor.subscription = client->subscribe(client->getBaseTopic() + "/" + topic);
|
||||
connect(sensor.subscription->subscription, &QMqttSubscription::messageReceived, this, &MqttSensorSource::onMessageReceived);
|
||||
}
|
||||
}
|
||||
|
||||
MqttSensorSource::SensorSubscription& MqttSensorSource::findSubscription(const QString& topic)
|
||||
{
|
||||
for(SensorSubscription& sensor : sensors)
|
||||
|
|
@ -194,3 +213,16 @@ MqttSensorSource::~MqttSensorSource()
|
|||
client->unsubscribe(client->getBaseTopic() + "/" + sub.topic);
|
||||
}
|
||||
|
||||
void MqttSensorSource::onSensorAdded(Sensor sensor, Sensor::sensor_backend_type_t backend, QJsonObject payload)
|
||||
{
|
||||
if(backend != Sensor::BACKEND_MQTT)
|
||||
return;
|
||||
|
||||
QString topic = payload["Topic"].toString();
|
||||
QString name = payload["Name"].toString();
|
||||
if(topic.isEmpty())
|
||||
return;
|
||||
|
||||
addSensor(topic, name);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,10 +31,14 @@ private slots:
|
|||
void onClientStateChanged(QMqttClient::ClientState state);
|
||||
void onMessageReceived(const QMqttMessage& message);
|
||||
|
||||
public slots:
|
||||
void onSensorAdded(Sensor sensor, Sensor::sensor_backend_type_t backend, QJsonObject payload);
|
||||
|
||||
public:
|
||||
explicit MqttSensorSource(QObject *parent = nullptr);
|
||||
~MqttSensorSource();
|
||||
void start(std::shared_ptr<MqttClient> client, const QJsonObject& settings);
|
||||
void addSensor(const QString& topic, const QString& name);
|
||||
void store(QJsonObject& json);
|
||||
|
||||
signals:
|
||||
|
|
|
|||
|
|
@ -33,6 +33,12 @@ public:
|
|||
TYPE_DUMMY,
|
||||
} sensor_type_t;
|
||||
|
||||
typedef enum {
|
||||
BACKEND_MICROCONTROLLER = 0,
|
||||
BACKEND_MQTT,
|
||||
BACKEND_SUN,
|
||||
} sensor_backend_type_t;
|
||||
|
||||
sensor_type_t type;
|
||||
uint64_t id;
|
||||
float field;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue