#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "cJSON.h"
#define ADDRESS "tcp://192.168.50.10:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "down"
#define PAYLOAD "Hello"
#define QOS 1
#define TIMEOUT 10000L
volatile MQTTClient_deliveryToken deliveredtoken;
void delivered(void *context, MQTTClient_deliveryToken dt)
{
//printf("Message with token value %d delivery confirmed\n", dt);
deliveredtoken = dt;
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
int i;
char *payloadptr;
payloadptr = message->payload;
cJSON *root = cJSON_Parse(payloadptr);
root = cJSON_Parse(payloadptr);
if (root == NULL)
{
printf("Failed to parse JSON.\n");
return 1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
cJSON *age = cJSON_GetObjectItem(root, "age");
cJSON *msg = cJSON_GetObjectItem(root, "msg");
printf("name: %s\n", name->valuestring);
printf("age: %d\n", age->valueint);
printf("msg: %s\n", msg->valuestring);
putchar('\n');
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause)
{
printf("\nConnection lost\n");
printf(" cause: %s\n", cause);
}
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;
int ch;
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
"Press Q<Enter> to quit\n\n",
TOPIC, CLIENTID, QOS);
MQTTClient_subscribe(client, TOPIC, QOS);
do
{
cJSON *json = cJSON_CreateObject();
//在对象上添加键值对
cJSON_AddItemToObject(json, "name", cJSON_CreateString("zhangsan"));
cJSON_AddItemToObject(json, "age", cJSON_CreateNumber(16));
cJSON_AddItemToObject(json, "msg", cJSON_CreateString("hello world"));
char *buf=cJSON_Print(json);
pubmsg.payload = buf;
pubmsg.payloadlen = (int)strlen(buf);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "up", &pubmsg, &token);
ch = getchar();
} while (ch != 'Q' && ch != 'q');
MQTTClient_unsubscribe(client, TOPIC);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
利用mqtt.fx软件实现聊天功能,fx订阅“up“主题,程序订阅“down“主题。使用如下的json通信协议。
最新推荐文章于 2024-03-06 22:30:24 发布