我正在使用Paho客户端库来编写一个客户端,该客户端向mosquitto代理发布一个整数。当我将有效负载设置为字符串时,它会毫无问题地发布,但是当我将有效负载设置为整数时,发布者会崩溃并显示以下消息,如图所示。
我的客户端代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "MQTT Examples"
#define QOS 1
#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, ch;
int i = 4;
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.username = "user";
conn_opts.password = "hello";
conn_opts.keepAliveInterval = 65000;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(-1);
}
pubmsg.payload = i;
pubmsg.payloadlen = sizeof(i); //strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %d\n"
"on topic %s for client with ClientID: %s\n",
(int)(TIMEOUT / 1000), i, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message with delivery token %d delivered\n", token);
do
{
ch = getchar();
} while (ch != 'Q' && ch != 'q');
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
有谁能告诉我我做错了什么?
答案 0 :(得分:1)
payload
的类型为char *
typedef struct {
char * topic;
char * payload;
unsigned int length;
boolean retained;
} MQTTMessage;
这意味着它只接受字符串。
答案 1 :(得分:0)
如果有人遇到这篇文章,这对我有用:
发布为:
uint32_t mmsg = (2<<31)-1;
mosquitto_publish(mosq, NULL, "topic\0", 4, &mmsg, 2, false);
读为
LOGD("Message topic and load are %s and %lu\n ", msg->topic, *((uint32_t *) (msg->payload)));
LOGD只是fprintf(stdout,....)
周围的一个宏答案 2 :(得分:0)
Select tf4hid,tf4iid,date,product,planqty
from tf4i
group by date,product
的{{1}}字段是payload
,如果要发送整数,则需要使用一个指针并将其正确地强制转换:
MQTTClient_message