Skip to content

Commit af60b40

Browse files
Deomid Ryabkovcesantabot
authored andcommitted
Add mgos_mqtt_pubf - a helper to pub JSON messages
CL: Add mgos_mqtt_pubf - a helper to pub JSON messages PUBLISHED_FROM=1c45b950d47bf8836427689af37c9fdf93df4a74
1 parent 85e47b6 commit af60b40

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

include/mgos_mqtt.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#ifndef CS_FW_SRC_MGOS_MQTT_H_
2626
#define CS_FW_SRC_MGOS_MQTT_H_
2727

28+
#include <stdarg.h>
2829
#include <stdbool.h>
2930

3031
#include "mgos_features.h"
@@ -86,6 +87,12 @@ bool mgos_mqtt_global_connect(void);
8687
bool mgos_mqtt_pub(const char *topic, const void *message, size_t len, int qos,
8788
bool retain);
8889

90+
/* Variant of mgos_mqtt_pub for publishing a JSON-formatted string */
91+
bool mgos_mqtt_pubf(const char *topic, int qos, bool retain,
92+
const char *json_fmt, ...);
93+
bool mgos_mqtt_pubv(const char *topic, int qos, bool retain,
94+
const char *json_fmt, va_list ap);
95+
8996
/*
9097
* Callback signature for `mgos_mqtt_sub()` below.
9198
*/

src/mgos_mqtt.c

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,16 @@
1515
* limitations under the License.
1616
*/
1717

18+
#include "mgos_mqtt.h"
19+
1820
#include <stdbool.h>
1921
#include <stdlib.h>
2022

21-
#include "mgos_mqtt.h"
22-
2323
#include "common/cs_dbg.h"
2424
#include "common/mg_str.h"
2525
#include "common/platform.h"
2626
#include "common/queue.h"
27+
#include "frozen.h"
2728
#include "mgos_debug.h"
2829
#include "mgos_event.h"
2930
#include "mgos_mongoose.h"
@@ -436,6 +437,27 @@ bool mgos_mqtt_pub(const char *topic, const void *message, size_t len, int qos,
436437
return true;
437438
}
438439

440+
bool mgos_mqtt_pubf(const char *topic, int qos, bool retain,
441+
const char *json_fmt, ...) {
442+
bool res;
443+
va_list ap;
444+
va_start(ap, json_fmt);
445+
res = mgos_mqtt_pubv(topic, qos, retain, json_fmt, ap);
446+
va_end(ap);
447+
return res;
448+
}
449+
450+
bool mgos_mqtt_pubv(const char *topic, int qos, bool retain,
451+
const char *json_fmt, va_list ap) {
452+
bool res = false;
453+
char *msg = json_vasprintf(json_fmt, ap);
454+
if (msg != NULL) {
455+
res = mgos_mqtt_pub(topic, msg, strlen(msg), qos, retain);
456+
free(msg);
457+
}
458+
return res;
459+
}
460+
439461
struct sub_data {
440462
sub_handler_t handler;
441463
void *user_data;

0 commit comments

Comments
 (0)