-
Notifications
You must be signed in to change notification settings - Fork 0
/
sensorinformation.cpp
95 lines (78 loc) · 2.66 KB
/
sensorinformation.cpp
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
#include "sensorinformation.h"
#include <QtCore/QRandomGenerator>
#include <QtCore/QTimer>
#include <QtCore/QUuid>
#include <QtMqtt/QMqttClient>
//generates sensor data for testing
inline double moveValue(double currentValue, double min, double max, double maxStep)
{
static QRandomGenerator generator;
double result = currentValue + generator.bounded(maxStep * 2.) - maxStep;
if (result < min)
return min;
else if (result > max)
return max;
return result;
}
Ic_MQTT_client::Ic_MQTT_client(QObject *parent) : QObject(parent)
{
fiveSecondTimer_ = new QTimer(this);
fiveSecondTimer_->setInterval(5000);
fiveSecondTimer_->setSingleShot(false);
connect(fiveSecondTimer_, &QTimer::timeout, [this]()
{
// Every five seconds report device still online
if (client_->state() == QMqttClient::Connected)
{
const QString content = QLatin1String(">Online");
client_->publish(QLatin1String("inlevelSensors/active"), content.toUtf8());
}
});
secondTimer_ = new QTimer(this);
secondTimer_->setInterval(1000);
secondTimer_->setSingleShot(false);
connect(secondTimer_, &QTimer::timeout, [this]() {
setDistance(moveValue(distance(), 0., 100., 1));
setDiameter(moveValue(diameter(), 0., 150., 1));
});
client_ = new QMqttClient(this);
client_->setWillTopic(QLatin1String("inlevelSensors/active"));
const QString will = QLatin1String(">Offline");
client_->setWillMessage(will.toUtf8());
client_->setHostname("localhost");
client_->setPort(1883);
connect(client_, &QMqttClient::stateChanged, [](QMqttClient::ClientState s)
{
qDebug() << "Client state changed:" << s;
});
}
void Ic_MQTT_client::start()
{
client_->connectToHost();
fiveSecondTimer_->start();
secondTimer_->start();
}
double Ic_MQTT_client::distance() const
{
return distance_;
}
double Ic_MQTT_client::diameter() const
{
return diameter_;
}
void Ic_MQTT_client::setDistance(double distance)
{
client_->publish(QString::fromLatin1("inlevelSensors/%1/distance"),
QByteArray::number(distance));
distance_ = distance;
//just for testing
qDebug() << "Test data distance: " << Ic_MQTT_client::distance_;
}
void Ic_MQTT_client::setDiameter(double diameter)
{
client_->publish(QString::fromLatin1("inlevelSensors/%1/distance"),
QByteArray::number(diameter));
diameter_ = diameter;
//just for testing
qDebug() << "Test data diameter: " << Ic_MQTT_client::diameter_;
}