https://github.com/tuanpmt/ESP8266MQTTClient
1、打开arduino,然后点击项目--加载库--添加.zip库,找到你下载的zip包,然后选中即可,这里需要更新为V1.0.4版本,在项目--加载库--管理库中,找到你刚刚安装的库,选择类型--已安装,目前下载安装的是V1.0.5版本,有点问题,需要安装V1.0.4版本的
2、解压刚刚的zip文件,找到examples里面的MQTTClient打开里面.ino文件,然后这里需要进行更改一下,添加wifi连接的部分代码,设置为你自己的Wifi,还有最下面的mqtt服务器的ip和port也要更改,参考代码如下:
//https://github.com/tuanpmt/ESP8266MQTTClient
#include
#include
MQTTClient mqtt;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA); //设置esp8266 工作模式
WiFi.begin("WIFI", "PWD");
WiFi.setAutoConnect(true);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//topic, data, data is continuing
mqtt.onData([](String topic, String data, bool cont) {
Serial.printf("Data received, topic: %s, data: %s\r\n", topic.c_str(), data.c_str());
//mqtt.unSubscribe("/qos0");
});
mqtt.onSubscribe([](int sub_id) {
Serial.printf("Subscribe topic id: %d ok\r\n", sub_id);
mqtt.publish("esp32", "GONEPOO", 0, 0);
});
mqtt.onConnect([]() {
Serial.printf("\r\nMQTT: Connected\r\n");
Serial.printf("Subscribe id: %d\r\n", mqtt.subscribe("esp32", 0));
//mqtt.subscribe("esp32", 1);
//mqtt.subscribe("esp32", 2);
});
mqtt.begin("mqtt://175.175.175.175:1883");
// mqtt.begin("mqtt://test.mosquitto.org:1883", {.lwtTopic = "hello", .lwtMsg = "offline", .lwtQos = 0, .lwtRetain = 0});
// mqtt.begin("mqtt://user:[email protected]:1883");
// mqtt.begin("mqtt://user:[email protected]:1883#clientId");
}
void loop() {
mqtt.handle();
}
3、刷入程序后,在工具--串口监视器里面可以看到已经连上了mqtt服务器了,用paho订阅测试一下就好了,paho的下载地址如下http://www.eclipse.org/paho/components/tool/
4、同理,websocket客户端的代码也大同小异,只需要更改一下,刷入即可,需要更改的是下面的websocket的ip和端口号,参考代码如下:
//https://github.com/tuanpmt/ESP8266MQTTClient
#include
#include
MQTTClient mqtt;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA); //设置esp8266 工作模式
WiFi.begin("WIFI", "PWD");
WiFi.setAutoConnect(true);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//topic, data, data is continuing
mqtt.onData([](String topic, String data, bool cont) {
Serial.printf("Data received, topic: %s, data: %s\r\n", topic.c_str(), data.c_str());
//mqtt.unSubscribe("/qos0");
});
mqtt.onSubscribe([](int sub_id) {
Serial.printf("Subscribe topic id: %d ok\r\n", sub_id);
mqtt.publish("esp32", "gaojing", 0, 0);
});
mqtt.onConnect([]() {
Serial.printf("\r\nMQTT: Connected\r\n");
Serial.printf("Subscribe id: %d\r\n", mqtt.subscribe("esp32", 0));
//mqtt.subscribe("esp8266", 1);
//mqtt.subscribe("arduino", 2);
});
mqtt.begin("ws://175.175.175.175:9001");
//mqtt.begin("ws://test.mosquitto.org:8080", {.lwtTopic = "hello", .lwtMsg = "offline", .lwtQos = 0, .lwtRetain = 0});
//mqtt.begin("ws://user:[email protected]:8080");
//mqtt.begin("ws://user:[email protected]:8080#clientId");
}
void loop() {
mqtt.handle();
}
三、最后感言
我只是代码的搬运工,感谢那些分享代码的各位大神