A simple and practical example of the mqtt protocol

The following is a simple example of implementing the MQTT protocol in an embedded system using C language programming:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mosquitto.h>

void on_connect(struct mosquitto *mqtt, void *userdata, int result) {
    if (result == 0) {
        printf("Connected to MQTT broker successfully!\n");
        mosquitto_subscribe(mqtt, NULL, "topic/example", 0); //订阅主题
    } else {
        printf("Failed to connect to MQTT broker\n");
    }
}

void on_message(struct mosquitto *mqtt, void *userdata, const struct mosquitto_message *message) {
    if (message->payloadlen) {
        printf("Received message: %s from topic: %s\n", (char *) message->payload, message->topic);
    } else {
        printf("Empty message received\n");
    }
}

int main() {
    struct mosquitto *mqtt;
    char client_id[] = "sample-client";
    char broker_address[] = "localhost";
    int port = 1883; //默认MQTT端口

    mosquitto_lib_init(); //初始化Mosquitto库

    mqtt = mosquitto_new(client_id, true, NULL);
    if (mqtt) {
        mosquitto_connect_callback_set(mqtt, on_connect);
        mosquitto_message_callback_set(mqtt, on_message);

        if (mosquitto_connect(mqtt, broker_address, port, 0) != MOSQ_ERR_SUCCESS) {
            printf("Unable to connect to the MQTT broker\n");
            return -1;
        }

        mosquitto_loop_start(mqtt); //启动MQTT循环

        //发送消息
        char message[] = "Hello, MQTT!";
        mosquitto_publish(mqtt, NULL, "topic/example", strlen(message), message, 0, false);

        //等待退出
        mosquitto_loop_stop(mqtt, true);

        mosquitto_destroy(mqtt);
    }

    mosquitto_lib_cleanup(); //清理Mosquitto库

    return 0;
}

In this example, we use the mosquitto library to implement the functionality of the MQTT protocol. First, we initialize the library and create an MQTT client instance. Then, we set the connection callback function and the message callback function, so that when the connection is established and the message is received, the corresponding processing will be carried out. Next, we try to connect to the MQTT broker and subscribe to the topic named "topic/example". After a successful connection, we start an MQTT loop to maintain communication with the broker. With mosquitto_publishthe function, we send a message to the "topic/example" topic. Finally, we wait for the loop to stop, clean up and destroy the MQTT client instance.

Please note that the above code is just a simple example, and it is assumed that there is a local MQTT broker named "localhost" running on the default port 1883. You may need to make appropriate modifications and configurations based on actual conditions. At the same time, make sure that the Mosquitto library has been installed in the system, and link the correct library file when compiling.

Guess you like

Origin blog.csdn.net/FLM19990626/article/details/131409211