/**
* Relational pipes
* Copyright © 2022 František Kučera (Frantovo.cz, GlobalCode.info)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <locale>
#include <codecvt>
#include <random>
#include <regex>
#include <mosquittopp.h>
#include <relpipe/common/type/typedefs.h>
#include <relpipe/reader/TypeId.h>
#include <relpipe/reader/handlers/RelationalReaderStringHandler.h>
#include <relpipe/reader/handlers/AttributeMetadata.h>
#include "Configuration.h"
#include "Hex.h"
namespace relpipe {
namespace out {
namespace mqtt {
class MQTTHandler : public relpipe::reader::handlers::RelationalReaderStringHandler {
private:
std::wstring_convert<codecvt_utf8<wchar_t>> convertor; // TODO: support also other encodings.
Configuration configuration;
std::shared_ptr<mosqpp::mosquittopp> mq = std::make_shared<mosqpp::mosquittopp>(generateClientID().c_str());
/**
* @return unique (random) client ID for MQTT to allow multiple simultaneous connections
*/
static std::string generateClientID() {
std::stringstream result;
std::string symbols("0123456789abcdef");
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, symbols.size());
for (int i = 0; i < 8; i++) result << symbols[dist(rng)];
return result.str();
}
struct CurrentRelation {
relpipe::common::type::StringX name;
std::vector<relpipe::reader::handlers::AttributeMetadata> attributes;
relpipe::common::type::Integer attributeIndex = 0;
std::string currentValue;
} currentRelation;
static void parseConnectionString(const std::string& connectionString, std::string& hostname, int& port) {
std::regex pattern("mqtt:(//)?([^:]+)(:([0-9]+))?");
std::smatch match;
if (std::regex_match(connectionString, match, pattern)) {
hostname = match[2];
port = stoi(match[4]);
} else {
throw std::invalid_argument("Invalid connection string format. Expecting something like: mqtt://localhost:1883");
}
}
static void check(std::string operation, int result) {
if (result) throw std::logic_error("mosquitto operation failed: " + operation + " = " + std::to_string(result));
}
public:
static MQTTHandler* create(Configuration configuration) {
MQTTHandler* h = new MQTTHandler();
std::string connectionString = h->convertor.to_bytes(configuration.connectionString);
std::string username;
std::string password;
std::string hostname;
int port;
parseConnectionString(connectionString, hostname, port);
for (auto o : configuration.connectionOptions) {
if (o.name == L"username") username = h->convertor.to_bytes(o.value);
else if (o.name == L"password") password = h->convertor.to_bytes(o.value);
else throw std::invalid_argument("Unsupported connection option: " + h->convertor.to_bytes(o.name));
}
if (username.size()) check("set credentials", h->mq->username_pw_set(username.c_str(), password.c_str()));
check("connect", h->mq->connect(hostname.c_str(), port));
return h;
}
void startRelation(relpipe::common::type::StringX name, std::vector<relpipe::reader::handlers::AttributeMetadata> attributes) override {
// TODO: check relation name according to the configuration
currentRelation = CurrentRelation{name, attributes};
}
void attribute(const relpipe::common::type::StringX& value) override {
auto attributeName = currentRelation.attributes[currentRelation.attributeIndex].getAttributeName();
if (attributeName == L"text" && value.size()) currentRelation.currentValue = convertor.to_bytes(value);
else if (attributeName == L"data" && value.size()) currentRelation.currentValue = Hex::fromHex(value).str();
else if (attributeName == L"text"); // keep empty or value from 'data'
else if (attributeName == L"data"); // keep empty or value from 'text'
currentRelation.attributeIndex++;
if (currentRelation.attributeIndex == currentRelation.attributes.size()) {
currentRelation.attributeIndex = 0;
int mid = -1;
check("publish", mq->publish(&mid, convertor.to_bytes(configuration.stream).c_str(), currentRelation.currentValue.size(), currentRelation.currentValue.c_str()));
// std::cerr << "MQTT message enqueued: " << mid << std::endl;
}
}
void endOfPipe() {
check("disconnect", mq->disconnect());
}
};
}
}
}