]> git.ipfire.org Git - thirdparty/collectd.git/commitdiff
mqtt plugin: add JSON format to mqtt_write
authorMark Ferry <mark@markferry.net>
Fri, 10 Oct 2025 18:17:24 +0000 (19:17 +0100)
committerMark Ferry <mark@markferry.net>
Mon, 24 Nov 2025 14:11:20 +0000 (14:11 +0000)
src/collectd.conf.pod
src/mqtt.c

index f1ba1eb3f8dfc1684cb0e9858f6ac1e5e4dc02b7..ae7a75967a34d834ac75c0350f23d152b4d404a6 100644 (file)
@@ -5447,7 +5447,7 @@ message's QoS will be downgraded.
 
 =item B<Format> I<Format> (Publish only)
 
-The output format to use. Defaults to C<PLAIN>.
+The output format to use. Can be one of C<PLAIN> or C<JSON>. Defaults to C<PLAIN>.
 
 =item B<Prefix> I<Prefix> (Publish only)
 
index e73440c571c10c40d13a1ad4bf016b37eb3bb292..376687c475a5d685a99b70f5d4805a1b5e7cd066 100644 (file)
@@ -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));