guowenxue
2019-06-26 57b8d8022cf8444cf59cd20a25cfee491ec88799
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)
{
    mqtt_ctx_t             *ctx = (mqtt_ctx_t *)userdata;
    cJSON                 *root = NULL;
    char                  *out;
    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 ;
}