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/DoorOpener.cpp

68 lines
1.8 KiB

#include "DoorOpener.h"
#include "log.h"
#include "variables.h"
#include <QFile>
#include <QDebug>
DoorOpener::DoorOpener(QObject* parent)
{
Q_UNUSED(parent);
initializeWithMqtt();
}
void DoorOpener::initializeWithMqtt()
{
_client = new QMqttClient();
_client->setHostname(hdvars::MQTT_HOSTNAME.c_str());
_client->setPort(hdvars::MQTT_PORT);
LOG_DBG("Initializing DoorOpener:");
LOG_DBG("\t - Host: " + _client->hostname().toStdString());
LOG_DBG("\t - Port: " + std::to_string(_client->port()));
// TODO this is bad architecture. it should be safe to know when the connection is established. (see main.qml)
if (_client->state() != QMqttClient::Connected) {
_client->connectToHost();
_client->setAutoKeepAlive(true);
// auto-reconnect
QObject::connect(_client, &QMqttClient::disconnected, [&](){ _client->connectToHost(); });
}
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
_access_token = token.split("\n").first().toStdString();
if (_access_token.empty()) {
LOG_ERR("Unable to read access token.");
}
else {
LOG_INF("Access token read.");
}
}
}
bool DoorOpener::open()
{
if (_client->state() != QMqttClient::Connected) {
LOG_ERR("Connect to MQTT client before calling open() function.");
return false;
}
LOG_DBG("Trying to send MQTT message to server with topic " + hdvars::MQTT_TOPIC + ".");
if (_access_token.empty()) {
LOG_WRN("No access token provided.");
}
qint32 retval { _client->publish(QMqttTopicName(hdvars::MQTT_TOPIC.c_str()), QByteArray(_access_token.c_str())) };
LOG_DBG("publish() returned " + std::to_string(retval) + ".");
return 0 == retval;
}