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);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue