之前用esp8266做的东西是通过tcp连接来和服务器端通信的,服务器端需要自己管理所有的连接,每个连接要做心跳包,还要考虑通信消息的可靠性。偶然看到了mqtt协议,发现可以拿来用。
安装MQTT客户端
- 下载客户端连接
- 把下载好文件解压缩到 arduinoide安装目录的libraries文件夹下,重启IDE
烧制程序到ESP8266
//注意我这边用的是esp12e模块,淘宝16块左右,所以有16引脚,esp8266也可以烧制以下程序
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "........";
const char* password = "........";
const char* mqttServer = ".....";
const int mqttPort = 9999;
const char* mqttUserName = "...";
const char* mqttPassword = "...";
const char* lightTopic = "...";
const char* willTopic = "...";
const char* onlineTopic = "...";
const char* clientId = "...";
WiFiClient espClient;
PubSubClient client(espClient);
int lightPin = 16;
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.println(topic);
String command = "";
for (int i = 0; i < length; i++) {
command += (char)payload[i];
}
Serial.println(command);
handlePayload(String(topic), command);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
//详细参数说明请查看文档
if (client.connect(clientId,mqttUserName,mqttPassword,willTopic,1,0,clientId)) {
Serial.println("connected");
client.publish(onlineTopic, clientId);
client.subscribe(lightTopic, 1);
} 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() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
//处理命令
String handlePayload(String topic, String payload) {
if (String(lightTopic).equals(topic)) {
//light command
if (String("lightOn").equals(payload)) {
digitalWrite(lightPin, HIGH);
} else if (String("lightOff").equals(payload)) {
digitalWrite(lightPin, LOW);
}
}
}
安装MQTT服务器
服务器列表 中的服务器都是可以支持mqtt的,大家可以根据个人情况选择。我这边用的 activemq
下载activemq
官方地址解压缩,然后进入bin目录 运行以下命令启动
activemq.bat start
3.打开examplesmqttwebsocket目录下的index.html
可以进行测试
4.配置端口和用户名密码
打开config/activemq.xml文件
<!-- 找到一下内容,即是配置不同协议端口 -->
<transportConnectors>
<!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
<transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
</transportConnectors>
<!-- 在broker节点的最后添加 -->
<plugins>
<simpleAuthenticationPlugin>
<users>
<authenticationUser username="admin" password="admin" groups="users,admins"/>
<authenticationUser username="user" password="password" groups="users"/>
</users>
</simpleAuthenticationPlugin>
</plugins>
测试
给esp12e模块的16引脚接个继电器,通电,就可以通过向esp12e模块订阅的主题发送命令控制继电器了。目前我已经可以通过天猫精灵和微信小程序控制我卧室的灯了。