See "heimdall"; Android Qt/C++ client for the private doorbell project heimdall. Uses MQTT to communicate.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 
heimdall-client/QmlMqttClient.cpp

67 lines
1.7 KiB

#include "QmlMqttClient.h"
#include "log.h"
#include "variables.h"
#include <QSound>
QmlMqttClient::QmlMqttClient(QObject *parent)
: QMqttClient(parent)
{
setHostname(hdvars::MQTT_HOSTNAME.c_str());
setPort(hdvars::MQTT_PORT);
}
QmlMqttSubscription* QmlMqttClient::subscribe()
{
LOG_INF("Initializing subscription with topic " + hdvars::MQTT_TOPIC + ".");
QMqttSubscription* sub { QMqttClient::subscribe(QMqttTopicFilter(hdvars::MQTT_TOPIC.c_str()), 0) };
QmlMqttSubscription* result { new QmlMqttSubscription(sub, this) };
return result;
}
QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
: sub(s)
, client(c)
{
connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
connect(sub, &QMqttSubscription::messageReceived, [](QMqttMessage msg) {
Q_UNUSED(msg);
LOG_INF("Ding dong!");
QSound::play("qrc:/res/bell.wav");
});
m_topic = sub->topic();
}
QmlMqttSubscription::~QmlMqttSubscription()
{
}
void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
bool isTokenValid { false };
if (QFile atFile { "access_token" }; atFile.open(QIODevice::ReadOnly)) {
LOG_DBG("Reading access token.");
QString token { atFile.readAll() };
// we only care about the first line of the "access_token" file
token = token.split("_").first();
if (token.isEmpty()) {
LOG_ERR("Unable to read access token.");
}
else {
isTokenValid = qmsg.payload().startsWith(token.toStdString().c_str());
std::string isValidStr = isTokenValid ? "valid" : "invalid";
LOG_INF("Access token read. Token is " + isValidStr + ".");
}
}
if (isTokenValid) {
emit messageReceived(qmsg.payload());
}
}