RT-Thread OneNET通过方式3上传多组数据

RT-Thread提供的OneNET包,只能同时上传单个数据。参考官方文档,实际上协议可以将多组数据一起上传。
RT-Thread OneNET通过方式3上传多组数据_第1张图片
以下只是一个实例,用于实现多组数据的推送。

static rt_err_t onenet_mqtt_get_diy_data(char **out_buff, size_t *length)
{
    rt_err_t result = RT_EOK;
    cJSON *root = RT_NULL;
    char *msg_str = RT_NULL;

    RT_ASSERT(out_buff);
    RT_ASSERT(length);

    root = cJSON_CreateObject();
    if (!root)
    {
        LOG_E("MQTT publish digit data failed! cJSON create object error return NULL!");
        return -RT_ENOMEM;
    }
    cJSON_AddNumberToObject(root, "lat", 12.3);
    cJSON_AddNumberToObject(root, "lon", 45.6);
    cJSON_AddNumberToObject(root, "elv", 78.9);
    /* render a cJSON structure to buffer */
    msg_str = cJSON_PrintUnformatted(root);
    if (!msg_str)
    {
        LOG_E("MQTT publish digit data failed! cJSON print unformatted error return NULL!");
        result = -RT_ENOMEM;
        goto __exit;
    }

    *out_buff = ONENET_MALLOC(strlen(msg_str) + 3);
    if (!(*out_buff))
    {
        LOG_E("ONENET mqtt upload digit data failed! No memory for send buffer!");
        return -RT_ENOMEM;
    }

    strncpy(&(*out_buff)[3], msg_str, strlen(msg_str));
    *length = strlen(&(*out_buff)[3]);

    /* mqtt head and json length */
    (*out_buff)[0] = 0x03;
    (*out_buff)[1] = (*length & 0xff00) >> 8;
    (*out_buff)[2] = *length & 0xff;
    *length += 3;

    LOG_HEX("out_buff", 16, *out_buff, *length);
    __exit: if (root)
    {
        cJSON_Delete(root);
    }
    if (msg_str)
    {
        cJSON_free(msg_str);
    }

    return result;
}

rt_err_t onenet_mqtt_upload_diy(void)
{
    char *send_buffer = RT_NULL;
    rt_err_t result = RT_EOK;
    size_t length = 0;


    result = onenet_mqtt_get_diy_data(&send_buffer, &length);
    if (result < 0)
    {
        goto __exit;
    }

    result = onenet_mqtt_publish(ONENET_TOPIC_DP, (uint8_t *) send_buffer, length);
    if (result < 0)
    {
        LOG_E("onenet publish failed (%d)!", result);
        goto __exit;
    }

    __exit: if (send_buffer)
    {
        ONENET_FREE(send_buffer);
    }

    return result;
}

上传时的payload数据如下:

D/HEX out_buff: 0000-000F: 03 00 33 7B 22 6C 61 74  22 3A 31 32 2E 33 30 30    ..3{"lat":12.300
                0010-001F: 30 30 30 2C 22 6C 6F 6E  22 3A 34 35 2E 36 30 30    000,"lon":45.600
                0020-002F: 30 30 30 2C 22 65 6C 76  22 3A 37 38 2E 39 30 30    000,"elv":78.900
                0030-003F: 30 30 30 7D A0 1E                                   000}..

可以看到,三组数据是同时收到的。
RT-Thread OneNET通过方式3上传多组数据_第2张图片

你可能感兴趣的:(rt-thread)