From d9a0fe3905373da95dc8f7d426ab2e7a751ed192 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tim=20He=C3=9F?= <tim.hess@rwth-aachen.de>
Date: Fri, 19 Apr 2024 13:18:47 +0200
Subject: [PATCH] handle unconnected client cleanup, empty root config & use
 json::parse

---
 src/MQTT/Configuration.cpp |  3 +--
 src/MQTT/Publisher.cpp     | 34 +++++++++++++++++++++++++---------
 2 files changed, 26 insertions(+), 11 deletions(-)

diff --git a/src/MQTT/Configuration.cpp b/src/MQTT/Configuration.cpp
index c67f023..658edd1 100644
--- a/src/MQTT/Configuration.cpp
+++ b/src/MQTT/Configuration.cpp
@@ -27,8 +27,7 @@ MQTT::Configuration::Configuration()
 MQTT::Configuration::Configuration(std::string filename)
 {
 	std::ifstream infile(filename);
-	json j;
-	infile >> j;
+	json j = json::parse(infile);
 	host = j.value("host", "127.0.0.1");
 	port = j.value("port", 1883);
 	username = j.value("username", "guest");
diff --git a/src/MQTT/Publisher.cpp b/src/MQTT/Publisher.cpp
index cc2eb0a..2333434 100644
--- a/src/MQTT/Publisher.cpp
+++ b/src/MQTT/Publisher.cpp
@@ -81,8 +81,14 @@ MQTT::Publisher::Publisher(std::string id, unsigned int buffer) : id(id), buffer
 
 MQTT::Publisher::~Publisher()
 {
-	this->disconnect();
-	worker->detach();
+	if (this->is_connected()) 
+	{
+		this->disconnect();
+	}
+	if (worker != nullptr) 
+	{
+		worker->detach();
+	}
 	instances--;
 	if (instances == 0)
 	{
@@ -169,11 +175,14 @@ void MQTT::Publisher::disconnect(unsigned int timeout)
 void MQTT::Publisher::set_root_topic(std::string root_topic)
 {
 	configuration.root = root_topic;
-	std::string::iterator last_character = configuration.root.end() - 1;
-	if ((*last_character) != '/')
+	if (configuration.root.length() > 0) 
 	{
-		configuration.root += "/";
-	}
+		std::string::iterator last_character = configuration.root.end() - 1;
+		if ((*last_character) != '/')
+		{
+			configuration.root += "/";
+		}
+	}	
 }
 
 void MQTT::Publisher::set_buffer(unsigned int buffer)
@@ -183,6 +192,10 @@ void MQTT::Publisher::set_buffer(unsigned int buffer)
 
 bool MQTT::Publisher::is_connected(void)
 {
+	if (this->client == nullptr)
+	{
+		return false;
+	}
 	try
 	{
 		return client->is_connected();
@@ -196,10 +209,13 @@ bool MQTT::Publisher::is_connected(void)
 void MQTT::Publisher::configure(MQTT::Configuration configuration)
 {
 	this->configuration = configuration;
-	std::string::iterator last_character = this->configuration.root.end() - 1;
-	if ((*last_character) != '/')
+	if (configuration.root.length() > 0) 
 	{
-		this->configuration.root += "/";
+		std::string::iterator last_character = configuration.root.end() - 1;
+		if ((*last_character) != '/')
+		{
+			configuration.root += "/";
+		}
 	}
 }
 
-- 
GitLab