Update the MQTT and JSON handling slightly.

This commit is contained in:
Jonathan Naylor
2023-07-04 17:08:11 +01:00
parent 893952f024
commit fddabee1b9
3 changed files with 22 additions and 18 deletions

View File

@@ -101,7 +101,7 @@ void WriteJSON(const std::string& topLevel, nlohmann::json& json)
top[topLevel] = json;
m_mqtt->publish("json", top.dump().c_str());
m_mqtt->publish("json", top.dump());
}
}

View File

@@ -84,19 +84,14 @@ bool CMQTTConnection::publish(const char* topic, const char* text)
assert(topic != NULL);
assert(text != NULL);
if (!m_connected)
return false;
return publish(topic, (unsigned char*)text, ::strlen(text));
}
char topicEx[100U];
::sprintf(topicEx, "%s/%s", m_name.c_str(), topic);
bool CMQTTConnection::publish(const char* topic, const std::string& text)
{
assert(topic != NULL);
int rc = ::mosquitto_publish(m_mosq, NULL, topicEx, ::strlen(text), text, static_cast<int>(m_qos), false);
if (rc != MOSQ_ERR_SUCCESS) {
::fprintf(stderr, "MQTT Error publishing: %s\n", ::mosquitto_strerror(rc));
return false;
}
return true;
return publish(topic, (unsigned char*)text.c_str(), text.size());
}
bool CMQTTConnection::publish(const char* topic, const unsigned char* data, unsigned int len)
@@ -107,6 +102,7 @@ bool CMQTTConnection::publish(const char* topic, const unsigned char* data, unsi
if (!m_connected)
return false;
if (::strchr(topic, '/') == NULL) {
char topicEx[100U];
::sprintf(topicEx, "%s/%s", m_name.c_str(), topic);
@@ -115,6 +111,13 @@ bool CMQTTConnection::publish(const char* topic, const unsigned char* data, unsi
::fprintf(stderr, "MQTT Error publishing: %s\n", ::mosquitto_strerror(rc));
return false;
}
} else {
int rc = ::mosquitto_publish(m_mosq, NULL, topic, len, data, static_cast<int>(m_qos), false);
if (rc != MOSQ_ERR_SUCCESS) {
::fprintf(stderr, "MQTT Error publishing: %s\n", ::mosquitto_strerror(rc));
return false;
}
}
return true;
}

View File

@@ -38,6 +38,7 @@ public:
bool open();
bool publish(const char* topic, const char* text);
bool publish(const char* topic, const std::string& text);
bool publish(const char* topic, const unsigned char* data, unsigned int len);
void close();