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;
}