linux使用C语言,通过MQTT发送以下JSON字符:"ts": "2023-3-27 19:50:0", "d": [ { "tag": "MSTM", "value": "2023-3-27 19:50:0" }, { "tag": "VT", " value": 12.34 }, { "tag": "SPPRWL11", "value": 102.29 },
时间: 2023-07-05 17:24:02 浏览: 156
好的,您可以使用 Eclipse Paho MQTT C 客户端库来实现在 Linux 下通过 C 语言发送 MQTT 消息。以下是一个简单的示例代码,用于创建 JSON 字符串并将其发布到 MQTT 主题中:
```c
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"
#include "cJSON.h"
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "test"
#define QOS 1
#define TIMEOUT 10000L
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
char* payload = NULL;
int rc;
cJSON *root = cJSON_CreateObject();
cJSON *data = cJSON_CreateArray();
cJSON *item1 = cJSON_CreateObject();
cJSON *item2 = cJSON_CreateObject();
cJSON *item3 = cJSON_CreateObject();
cJSON_AddStringToObject(root, "ts", "2023-3-27 19:50:0");
cJSON_AddItemToArray(data, item1);
cJSON_AddItemToArray(data, item2);
cJSON_AddItemToArray(data, item3);
cJSON_AddStringToObject(item1, "tag", "MSTM");
cJSON_AddStringToObject(item1, "value", "2023-3-27 19:50:0");
cJSON_AddStringToObject(item2, "tag", "VT");
cJSON_AddNumberToObject(item2, "value", 12.34);
cJSON_AddStringToObject(item3, "tag", "SPPRWL11");
cJSON_AddNumberToObject(item3, "value", 102.29);
payload = cJSON_PrintUnformatted(root);
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);
}
MQTTClient_message pubmsg = MQTTClient_message_initializer;
pubmsg.payload = payload;
pubmsg.payloadlen = strlen(payload);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_deliveryToken token;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Waiting for publication of %s\n"
"on topic %s for client with ClientID: %s\n",
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);
cJSON_Delete(root);
free(payload);
return rc;
}
```
这个程序使用 cJSON 库来创建 JSON 字符串,并使用 Eclipse Paho MQTT C 客户端库来连接到 MQTT 代理服务器并将消息发布到主题中。您需要在代码中更改 `ADDRESS`、`CLIENTID` 和 `TOPIC` 来适应您的实际情况。当您运行程序时,它将在终端输出消息发布的结果。
阅读全文