收藏文章 楼主

c 语言mqtt 连接脚本

版块:C/C++语言开发   类型:普通   作者:小绿叶技术博客   查看:458   回复:0   获赞:0   时间:2024-08-13 17:14:56


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

#define MQTT_BROKER "mqtt.ddoss.cn" // MQTT代理服务器地址
#define MQTT_PORT 1883               // MQTT代理的默认端口,如果是TLS连接使用8883
#define MQTT_CLIENT_ID "CClient"     // MQTT客户端ID,建议唯一
#define MQTT_TOPIC "test"            // MQTT主题
#define MQTT_USERNAME "eisc"         // MQTT用户名
#define MQTT_PASSWORD "000000"       // MQTT密码

// 连接成功的回调函数
void on_connect(MQTTClient *c, int result_code) {
    if (result_code == 0) {
        printf("Connected to MQTT Broker successfully.\n");
        // 连接成功后订阅主题
        MQTTString topic = MQTTString_initializer;
        topic.cstring = MQTT_TOPIC;
        MQTTClient_subscribe(c, &topic, 1);
    } else {
        printf("Failed to connect, return code %d\n", result_code);
    }
}

// 消息到达的回调函数
void on_message(MQTTClient *c, char *topicName, int topicLen, MQTTClient_message *message) {
    printf("Received message on topic '%s': ", topicName);
    fwrite(message->payload, 1, message->payloadlen, stdout);
    printf("\n");
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
}

int main(int argc, char *argv[]) {
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    char *payload = "Hello MQTT from C!";
    char *topic = "test";

    MQTTClient_create(&client, MQTT_BROKER, MQTT_CLIENT_ID,
                       MQTTCLIENT_PERSISTENCE_NONE, NULL);
    MQTTClient_setCallbacks(client, NULL, on_connect, on_message);

    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.username = MQTT_USERNAME;
    conn_opts.password = MQTT_PASSWORD;

    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS) {
        printf("Failed to connect to the MQTT server.\n");
        exit(EXIT_FAILURE);
    }

    // 发布消息
    pubmsg.payload = (void *)payload;
    pubmsg.payloadlen = strlen(payload);
    pubmsg.qos = 1;
    pubmsg.retained = 0;
    MQTTClient_publishMessage(client, topic, &pubmsg, &token);
    printf("Message published to topic '%s'\n", topic);

    // 等待消息发布完成
    MQTTClient_waitCompletion(client, token, 1000);

    // 订阅主题接收消息
    MQTTString topic = MQTTString_initializer;
    topic.cstring = topic;
    MQTTClient_subscribe(client, &topic, 1);

    // 循环处理消息
    while (1) {
        MQTTClient_yield(client, 1000);
    }

    MQTTClient_disconnect(client, 1000);
    MQTTClient_destroy(&client);

    return 0;
}





有些梦虽然遥不可及,但并不是不可能实现。 
回复列表
默认   热门   正序   倒序

回复:c 语言mqtt 连接脚本

Powered by ddoss.cn 12.0

©2015 - 2024 ddoss

头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息