mqtt C客戶端

Paho MQTT C客戶端是一個使用標準C編寫的流暢的MQTT。 實際上包含了兩個C API,同步的和異步的,分別爲MQTTClient和MQTTAsync。同步的API可以更簡單更使用,執行完操作後,一些調用會被阻攔,編程也更容易;而在異步API沒有調用的阻攔操作,所有API的調用都是通過會調來實現的,這使得API更適合有窗口環境的操作系統,許多應用沒有主線程控制。


linux環境:
在linux環境下建立MQTT C 客戶端:

 git clone https://github.com/eclipse/paho.mqtt.c.git
cd org.eclipse.paho.mqtt.c.git
make

安裝MQTT

sudo make install

在windows環境下

在Windows下使用Visual Studio 或者Visual C++創建

git clone https://github.com/eclipse/paho.mqtt.c.git
cd org.eclipse.paho.mqtt.c.git
msbuild "Windows Build\Paho C MQTT APIs.sln" /p:Configuration=Release

爲了設置msbuild的路徑,可以運行 vcvars32.bat,它的創建如下:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin

以下是一個簡單的同步類型的MQTT C客戶端:

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

#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "MQTT Examples"
#define PAYLOAD     "Hello World!"
#define QOS         1
#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);
    }
    pubmsg.payload = PAYLOAD;
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    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;
}

來源:https://www.eclipse.org/paho/clients/c/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章