From 57b8d8022cf8444cf59cd20a25cfee491ec88799 Mon Sep 17 00:00:00 2001 From: guowenxue <guowenxue@gmail.com> Date: Wed, 26 Jun 2019 13:16:27 +0800 Subject: [PATCH] update mqttd, add ID match support --- mqttd/main.c | 31 ++++++++++++++++++++++++++----- 1 files changed, 26 insertions(+), 5 deletions(-) diff --git a/mqttd/main.c b/mqttd/main.c index 8808585..48e6e85 100644 --- a/mqttd/main.c +++ b/mqttd/main.c @@ -202,9 +202,9 @@ memset(msg, 0, sizeof(msg)); if( ds18b20_get_temperature(&temp) < 0 ) - strncpy(msg, "{ \"temp\":\"error\" }", sizeof(msg)); + snprintf(msg, sizeof(msg), "{ \"id\":%s, \"temp\":\"error\" }", ctx->id); else - snprintf(msg, sizeof(msg), "{ \"temp\":\"%.2f\" }", temp); + snprintf(msg, sizeof(msg), "{ \"id\":%s, \"temp\":\"%.2f\" }", ctx->id, temp); rv = mosquitto_publish(mosq, NULL, ctx->pubTopic, strlen(msg)+1, msg, ctx->pubQos, retain); if( rv ) @@ -388,8 +388,11 @@ void sub_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { - cJSON *root = NULL; - char *out; + mqtt_ctx_t *ctx = (mqtt_ctx_t *)userdata; + + cJSON *root = NULL; + cJSON *item; + char *value; if ( !message->payloadlen ) @@ -398,7 +401,7 @@ return ; } - log_nrml("Subscriber receive message: '%s'\n", message->payload); + log_dbg("Subscriber receive message: '%s'\n", message->payload); root = cJSON_Parse(message->payload); if( !root ) @@ -407,8 +410,26 @@ return ; } + item = cJSON_GetObjectItem(root, "id"); + if( !item ) + { + log_err("cJSON_Parse get ID failure: %s\n", cJSON_GetErrorPtr()); + goto OUT; + } + + value = cJSON_PrintUnformatted(item); + if( strcasecmp(value, ctx->id) ) + { + free(value); + goto OUT; + } + + free(value); + log_nrml("Subscriber receive message: '%s'\n", message->payload); + proc_json_items(root); +OUT: cJSON_Delete(root); /* must delete it, or it will result memory leak */ return ; } -- Gitblit v1.9.1