From: Mark Ferry Date: Fri, 10 Oct 2025 18:17:24 +0000 (+0100) Subject: mqtt plugin: add JSON format to mqtt_write X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=9b9faf90c71f84b9ae19722a6016e40aff88cb4a;p=thirdparty%2Fcollectd.git mqtt plugin: add JSON format to mqtt_write --- diff --git a/src/collectd.conf.pod b/src/collectd.conf.pod index f1ba1eb3f..ae7a75967 100644 --- a/src/collectd.conf.pod +++ b/src/collectd.conf.pod @@ -5447,7 +5447,7 @@ message's QoS will be downgraded. =item B I (Publish only) -The output format to use. Defaults to C. +The output format to use. Can be one of C or C. Defaults to C. =item B I (Publish only) diff --git a/src/mqtt.c b/src/mqtt.c index e73440c57..376687c47 100644 --- a/src/mqtt.c +++ b/src/mqtt.c @@ -520,6 +520,8 @@ static int mqtt_write(const data_set_t *ds, const value_list_t *vl, mqtt_client_conf_t *conf; char topic[MQTT_MAX_TOPIC_SIZE]; char payload[MQTT_MAX_MESSAGE_SIZE]; + size_t offset = 0; + size_t bfree = sizeof(payload); int status = 0; if ((user_data == NULL) || (user_data->data == NULL)) @@ -532,10 +534,21 @@ static int mqtt_write(const data_set_t *ds, const value_list_t *vl, return status; } - status = format_values(payload, sizeof(payload), ds, vl, conf->store_rates); - if (status != 0) { - ERROR("mqtt plugin: format_values failed with status %d.", status); - return status; + if (conf->format == MQTT_FORMAT_JSON) { + format_json_initialize(payload, &offset, &bfree); + format_json_value_list(payload, &offset, &bfree, ds, vl, conf->store_rates); + status = format_json_finalize(payload, &offset, &bfree); + + if (status != 0) { + ERROR("mqtt plugin: format_json_finalize failed with status %d.", status); + return status; + } + } else { /* MQTT_FORMAT_PLAIN */ + status = format_values(payload, sizeof(payload), ds, vl, conf->store_rates); + if (status != 0) { + ERROR("mqtt plugin: format_values failed with status %d.", status); + return status; + } } status = publish(conf, topic, payload, strlen(payload));