c - 如何使用 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
"
有人可以告诉我如何发送该数组吗?
解决方案
strlen(payload)
将不起作用,因为arr
它不是以空字符结尾的字符串。
有效载荷大小应该是sizeof arr / sizeof int
(假设它以后可能会改变长度)
但即使在那之后,你也会从 mosquitto_sub 命令中得到看起来像垃圾的东西,因为默认情况下将所有有效负载视为字符串并且你没有发送字符串,你已经发送了 3 个不映射到可打印字符的 int 值。
您需要在此处查看OUTPUT FORMAT
mosquitto_sub 手册页的部分
推荐阅读
- python-3.x - django .update() 一个外键
- python-3.x - 尝试将 Swagger 与 Flask 应用程序集成时出现 KeyError:“view_class”
- azure-sql-database - 如何捕获或打印导致存储过程失败的数据值(基本上是整行)
- php - Wordpress the_category() 到 php 字符串
- android - 如何使用 JNI(Java Native 接口)在 android 原生 NDK 中使用 sqlcipher
- scala - akka actor 的 ask 模式中的阻塞
- scala - 如何合并两个文件并在 spark 中添加相应的值?
- c - 在预处理中计算其评估可能导致副作用的 2 个操作数的最大值
- typescript - 在我的情况下,如何使打字稿正确推断类型?
- flutter - 使用传感器锁定/解锁屏幕(如普通电话或信使电话)