ESP8266 + MQTT
引用库
-
include <ESP8266WiFi.h>
-
include <PubSubClient.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// led 引脚
#define led_one 2
// wifi info
const char *SSID = "wifi-name"; // 你家的wifi名
const char *PASSWORD = "123456a"; // wifi 密码
// MQTT info https://www.emqx.com/zh/mqtt/public-mqtt5-broker
const char *MQTT_SERVER = "broker-cn.emqx.io"; // MQTT 服务器地址
const int MQTT_PROT = 1883; // MQTT 端口
// mqtt 主题
const char *MQTT_TOPIC_LED = "my/home/led";
const char *MQTT_TOPIC_ONLINE = "my/home/online";
const char *CLIENT_ID = "esp8266-457065e5-f063-474e-2saf-cacf5cb52af5";
WiFiClient espClient;
PubSubClient client(espClient);
void init_wifi(); // 初始化wifi
void mqtt_reconnect(); // 重新连接wifi
void mqtt_msg_callback(char *topic, byte *payload, unsigned int length); // mqtt 消息回调
void setup()
{
Serial.begin(115200);
pinMode(led_one, OUTPUT);
init_wifi();
client.setServer(MQTT_SERVER, MQTT_PROT); // 设置mqtt 服务和端口
client.setCallback(mqtt_msg_callback); // 设置mqtt 回调函数
}
void loop()
{
if (!client.connected())
{
mqtt_reconnect();
}
client.loop();
}
void init_wifi()
{
Serial.println("Connecting to");
Serial.println(SSID);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
}
void mqtt_reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// 第一步: 创建连接
if (client.connect(CLIENT_ID))
{
Serial.println("connected");
client.publish(MQTT_TOPIC_ONLINE, "online"); // 发布
client.subscribe(MQTT_TOPIC_LED); // 监听 led 主题
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void mqtt_msg_callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic); // 打印主题信息
Serial.print("] ");
for (unsigned int i = 0; i < length; i++)
{
Serial.print((char)payload[i]); // 打印主题内容
}
String topic_data = String(topic);
// String() 异步
if (topic_data == MQTT_TOPIC_LED)
{
// (char) byte 转 char 类型
if ((char)payload[0] == '1')
{
digitalWrite(led_one, HIGH);
Serial.println("open_led");
}
else
{
digitalWrite(led_one, LOW);
Serial.println("close_led");
}
}
Serial.println();
}