首页 > 解决方案 > 如何使用 Paho MQTT C 客户端发送整数和字符数组

问题描述

我是 MQTT 的新手。我的最后一个项目是发送一个包含基于 UNIX 的时间戳及其时区代码和一些整数值的数组。

在 Paho MQTT C Client - MQTT Client Library Encyclopedia 之后,我想出了它的代码片段:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"

#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "testTopic"
#define PAYLOAD     "220"
#define QOS         0
#define TIMEOUT     10000L

int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    int rc;

    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
    int arr [3] = {1, 2, 3};
    pubmsg.payload = arr; // PAYLOAD;
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;

    // while(1){
            
        MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    // }

    printf("Waiting for up to %d seconds for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
    rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
    printf("Message with delivery token %d delivered\n", token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}

我用一个数组(例如只有 int 值)更改了它的有效负载。但是当我发布味精时,我在订阅者端得到一个未定义的字符:

testClient1@localhost> sub -t testTopic -s
"

有人可以告诉我如何发送该数组吗?

标签: cmqtt

解决方案


strlen(payload)将不起作用,因为arr它不是以空字符结尾的字符串。

有效载荷大小应该是sizeof arr / sizeof int(假设它以后可能会改变长度)

但即使在那之后,你也会从 mosquitto_sub 命令中得到看起来像垃圾的东西,因为默认情况下将所有有效负载视为字符串并且你没有发送字符串,你已经发送了 3 个不映射到可打印字符的 int 值。

您需要在此处查看OUTPUT FORMATmosquitto_sub 手册页的部分


推荐阅读