ESP8266学习记录4——连接(各种服务器商的)MQTT服务器(Arduino)

一.安装库

在Arduino的环境下使用MQTT在,我们需要下载一个库:PubSubClient 在git里面可以下载https://github.com/knolleary/pubsubclient

二.使用

1.说明

里面的代码其实是非常简洁明了的,基于C++。若是还是有不懂的,这有一个大佬有对pubsubclient进行过翻译:https://github.com/zy19970/Pubsubclient_API_document

2.连接

 

首先将我们的库与代码放在同一级的目录下,然后引入头文件 

#include "PubSubClient.h"

创建两个类,但主要还是用PubSubClient的类

WiFiClient espClient;
PubSubClient client(espClient);

在初始化函数里写入我们的MQTT初始化代码:当然你还得自己写一个回调函数callback

client.setServer("MQTT server address", 1883);
client.setCallback(callback);

编写我们的连接/重连

判断是否连接成功使用:

client.connected()

而连接的话,我们一般使用以下两种代码,connect被重写过。

client.connect(clientname,username,userkey) #如果mqtt服务器有域名的话,就使用这个
client.connect(clientname)

重连函数优化一下就是这样
 

void reconnect() 
{
    while (!client.connected())
    {
        Serial.print("Attempting MQTT connection...");
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        if (client.connect(clientId.c_str(),username,key)) 
        {
            Serial.println("connected");
            client.publish("fire", "hello world");
            client.subscribe("fire");
        } 
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
         }
    }
}

CallBack函数的编写

void callback(char* topic, byte* payload, unsigned int length) {
//以下代码是将返回的消息用串口打印出来
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();
//这里是收到消息的处理函数
    if ((char)payload[0] == 'K') 
    {
        Serial.println("yes");
    } 
    else
    {
        Serial.println("no");
    }
}

主函数的编写

if (!client.connected())
{
    reconnect();
}
client.loop();

3.发送消息

client.publish("topic", "text");

三.编译可用代码

#include 
#include "PubSubClient.h"
#include 

const char* ssid = "1";
const char* password = "2";
const char* mqtt_server = "like xxxxx.mqtt.iot.gz.baidubce.com or ip";
const char* username = "4";
const char* key = "5";

long lastMsg = 0;
char msg[50];
int value = 0;

WiFiClient espClient;
PubSubClient client(espClient);


void setup_wifi()
{
    delay(10);
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    for (int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println();
    if ((char)payload[0] == 'K') //这里是收到消息的处理函数
    {
        Serial.println("yes");
    } 
    else
    {
        Serial.println("no");
    }
}

void reconnect() 
{
    while (!client.connected())
    {
        Serial.print("Attempting MQTT connection...");
        String clientId = "ESP8266Client-";
        clientId += String(random(0xffff), HEX);
        if (client.connect(clientId.c_str(),username,key)) 
        {
            Serial.println("connected");
            client.publish("fire", "hello world");
            client.subscribe("fire");
        } 
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
         }
    }
}

void setup()
{
    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
}

void loop() 
{
    if (!client.connected())
    {
        reconnect();
    }
    client.loop();
    long now = millis();
    if (now - lastMsg > 2000)
    {
        lastMsg = now;
        ++value;
    }
}

 

你可能感兴趣的:(ESP8266学习记录)