src/MQTTCommand.cpp
author František Kučera <franta-hg@frantovo.cz>
Sun, 05 Jun 2022 22:51:45 +0200
branchv_0
changeset 3 610783d70ae9
parent 2 0799eaf338b9
permissions -rw-r--r--
parse connection string, credentials, check return values

/**
 * 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/>.
 */
#include <cstdlib>
#include <vector>
#include <memory>
#include <locale>
#include <regex>
#include <algorithm>
#include <unistd.h>
#include <sstream>
#include <iomanip>
#include <random>
#include <regex>

#include <mosquittopp.h>

#include <relpipe/writer/RelationalWriter.h>
#include <relpipe/writer/RelpipeWriterException.h>
#include <relpipe/writer/AttributeMetadata.h>
#include <relpipe/writer/Factory.h>
#include <relpipe/writer/TypeId.h>

#include <relpipe/cli/CLI.h>

#include "MQTTCommand.h"
#include "Hex.h"

using namespace relpipe::cli;
using namespace relpipe::writer;

namespace relpipe {
namespace in {
namespace mqtt {

class MQTTClient : public mosqpp::mosquittopp {
private:
	std::shared_ptr<writer::RelationalWriter> writer;
	Configuration& configuration;
	int messageCount = 0;
	std::string clientId;

	/**
	 * @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();
	}
public:

	MQTTClient(std::shared_ptr<writer::RelationalWriter> writer, Configuration& configuration) : mosqpp::mosquittopp((generateClientID()).c_str()), writer(writer), configuration(configuration) {
	}

	void on_message(const mosquitto_message* message) override {
		// std::cerr << "got MQTT message: length=" << message->payloadlen << std::endl;
		std::string payload = std::string((const char*) message->payload, message->payloadlen);
		writer->writeAttribute(configuration.stream);
		writer->writeAttribute(Hex::toTxt(payload));
		writer->writeAttribute(Hex::toHex(payload));
		messageCount++;
	}

	int popMessageCount() {
		int count = messageCount;
		messageCount = 0;
		return count;
	}

};

void MQTTCommand::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");
	}
}

void MQTTCommand::check(std::string operation, int result) {
	if (result) throw std::logic_error("mosquitto operation failed: " + operation + " = " + std::to_string(result));
}

void MQTTCommand::process(std::shared_ptr<writer::RelationalWriter> writer, Configuration& configuration) {
	std::shared_ptr<MQTTClient> mq = std::make_shared<MQTTClient>(writer, configuration);

	writer->startRelation(configuration.relation,{
		{L"stream", TypeId::STRING},
		{L"text", TypeId::STRING},
		{L"data", TypeId::STRING}
	}, true);

	std::string connectionString = 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 = convertor.to_bytes(o.value);
		else if (o.name == L"password") password = convertor.to_bytes(o.value);
		else throw std::invalid_argument("Unsupported connection option: " + convertor.to_bytes(o.name));
	}

	if (username.size()) check("set credentials", mq->username_pw_set(username.c_str(), password.c_str()));

	check("set maximum inflight messages", mq->max_inflight_messages_set(1));
	check("connect", mq->connect(hostname.c_str(), port));
	int mid;
	check("substcribe", mq->subscribe(&mid, convertor.to_bytes(configuration.stream).c_str()));

	//for (int i = configuration.messageCount; continueProcessing && i > 0; i--) {
	for (int i = configuration.messageCount; continueProcessing && i > 0; i = i - mq->popMessageCount()) {
		// std::cerr << "loop(): i=" << i << std::endl;

		//mq->loop();
		check("loop", mq->loop(1000, 1));
		//mq->loop(1000, -1);
		//mq->loop_forever();
		//mq->loop_write();
	}

	// FIXME: move do destructor
	mq->disconnect();
}

MQTTCommand::~MQTTCommand() {
}

}
}
}