Skip to content

Commit 8bb9512

Browse files
author
Marc Haber
committed
allow mqtt_topic to be set from the channel config
This backwards-compatible change allows one to set the mqtt topic from the channel configurtation. Currently, the meter values are published via an mqtt topic that is set to the channel number, which changes whenever a new channel is defined or and old deleted. And it's totally not mnemonic. This addresses issue #420 from 2020.
1 parent 9f5805b commit 8bb9512

3 files changed

Lines changed: 10 additions & 1 deletion

File tree

include/Channel.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ class Channel {
7474

7575
const char *name() const { return _name.c_str(); }
7676
std::list<Option> &options() { return _options; }
77+
const char *mqttTopic() const { return _mqttTopic.c_str(); }
7778

7879
ReadingIdentifier::Ptr identifier() {
7980
if (_identifier.use_count() < 1)
@@ -116,6 +117,7 @@ class Channel {
116117
std::string _name; // name of the channel
117118
std::list<Option> _options;
118119

120+
std::string _mqttTopic;
119121
Buffer::Ptr _buffer; // circular queue to buffer readings
120122

121123
ReadingIdentifier::Ptr _identifier; // channel identifier (OBIS, string)

src/Channel.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@ Channel::Channel(const std::list<Option> &pOptions, const std::string apiProtoco
8686
throw;
8787
}
8888

89+
try {
90+
_mqttTopic = optlist.lookup_string(pOptions, "mqtt_topic");
91+
} catch (vz::OptionNotFoundException &e) {
92+
// optional, defaults to empty string
93+
}
8994
pthread_cond_init(&condition, NULL); // initialize thread syncronization helpers
9095
}
9196

src/mqtt.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,9 @@ MqttClient::~MqttClient() {
222222
void MqttClient::ChannelEntry::generateNames(const std::string &prefix, Channel &ch) {
223223
_announceValues.clear();
224224
_fullTopicRaw = prefix;
225-
_fullTopicRaw += ch.name(); // todo this converts from std::string to const char and back...
225+
// Use configured mqtt_topic if set, otherwise fall back to ch.name()
226+
const char *topicSegment = (ch.mqttTopic()[0] != '\0') ? ch.mqttTopic() : ch.name();
227+
_fullTopicRaw += topicSegment;
226228
_fullTopicRaw += '/';
227229
if (ch.identifier()) {
228230
char unparseBuf[200];

0 commit comments

Comments
 (0)