Using mg_str

This commit is contained in:
cpq
2025-12-06 18:59:45 +00:00
parent 80ed81583e
commit 2acbb0ad62
+18 -17
View File
@@ -18,24 +18,25 @@ static const char *s_pub_topic = "mg/123/tx"; // Publish topic
static int s_qos = 1; // MQTT QoS
static struct mg_connection *s_mqtt_conn; // Client connection
static void subscribe(struct mg_connection *c, const char *topic) {
static void subscribe(struct mg_connection *c, struct mg_str topic) {
struct mg_mqtt_opts opts = {};
memset(&opts, 0, sizeof(opts));
opts.topic = mg_str(topic);
opts.topic = topic;
opts.qos = s_qos;
mg_mqtt_sub(c, &opts);
MG_INFO(("%lu SUBSCRIBED to %s", c->id, topic));
MG_INFO(("%lu SUBSCRIBED to %.*s", c->id, topic.len, topic.buf));
}
static void publish(struct mg_connection *c, const char *topic,
const char *message) {
static void publish(struct mg_connection *c, struct mg_str topic,
struct mg_str message) {
struct mg_mqtt_opts opts = {};
memset(&opts, 0, sizeof(opts));
opts.topic = mg_str(topic);
opts.message = mg_str(message);
opts.topic = topic;
opts.message = message;
opts.qos = s_qos;
mg_mqtt_pub(c, &opts);
MG_INFO(("%lu PUBLISHED %s -> %s", c->id, topic, message));
MG_INFO(("%lu PUBLISHED %.*s -> %.*s", c->id, topic.len, topic.buf,
message.len, message.buf));
}
static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
@@ -54,14 +55,14 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
} else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connect is successful
MG_INFO(("%lu CONNECTED to %s", c->id, s_url));
subscribe(c, s_sub_topic);
subscribe(c, mg_str(s_sub_topic));
} else if (ev == MG_EV_MQTT_MSG) {
// When we get echo response, print it
char response[100];
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
mg_snprintf(response, sizeof(response), "Got %.*s -> %.*s", mm->topic.len,
mm->topic.buf, mm->data.len, mm->data.buf);
publish(c, s_pub_topic, response);
publish(c, mg_str(s_pub_topic), mg_str(response));
} else if (ev == MG_EV_MQTT_CMD) {
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
if (mm->cmd == MQTT_CMD_PINGREQ) mg_mqtt_pong(c);
@@ -73,14 +74,14 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
// Timer function - recreate client connection if it is closed
static void timer_fn(void *arg) {
struct mg_mgr *mgr = (struct mg_mgr *) arg;
struct mg_mqtt_opts opts = {.clean = true,
.qos = s_qos,
.topic = mg_str(s_pub_topic),
.keepalive = 5,
.version = 4,
.message = mg_str("bye")};
if (s_mqtt_conn == NULL) {
struct mg_mgr *mgr = (struct mg_mgr *) arg;
struct mg_mqtt_opts opts = {.clean = true,
.qos = s_qos,
.topic = mg_str(s_pub_topic),
.keepalive = 5,
.version = 4,
.message = mg_str("bye")};
s_mqtt_conn = mg_mqtt_connect(mgr, s_url, &opts, mqtt_ev_handler, NULL);
} else {
mg_mqtt_ping(s_mqtt_conn);