Posted on

Smartline的MQTT接口调整说明

为了统一和规范MQTT连接,Smartline对接入MQTT的客户端做了如下要求:

  1. MQTT连接必须使用用户名和密码进行鉴权;
  2. MQTT连接的client_id必须与用户名保持一致;
  3. 客户端在由网络引起掉线后应主动进行重连

这里主要解释一下第2点,在之前的版本中,只对连接MQTT的客户端进行了用户名和密码鉴权,但是没有对client_id进行检查,导致有一定的概率会产生相同的client_id,这样会使客户端无法连接服务,所以为了规范起见,所有的client_id将强制与username保持一致,如果不一致,服务器将直接拒绝连接。

这里以Arduino连接MQTT服务器为例,简要示例一下代码:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "WIFI名";
const char* password = "WIDI密码";
const char* mqtt_server = "mqtt.smartline.cc";

const char* mqtt_username = "MQTT用户名";
const char* mqtt_password = "MQTT密码";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    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();

    // 对payload进行处理,payload中包含了下发的指令数据

}

void reconnect() {
    // Loop until we're reconnected
    while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // 注意!client_id也使用了mqtt_username
        if (client.connect(mqtt_username, mqtt_username, mqtt_password)) {
            Serial.println("connected");
            // ... and resubscribe
            client.subscribe("YOUR_TOPIC");
        } else {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            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();
}

请注意,client.connect(CLIENT_ID, USERNAME, PASSWORD),务必保证CLIENT_IDUSERNAME保持一致。代码中使用了第三方库完成MQTT协议,可以到pubsubclient-master找到。

发表评论

电子邮件地址不会被公开。 必填项已用*标注