ESP8266 + MQTT
引用库
-
include <ESP8266WiFi.h>
-
include <PubSubClient.h>
-
include <Ticker.h>
#include <Arduino.h>
#include <Ticker.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// 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 = "192.168.110.54"; // MQTT 服务器地址
const int MQTT_PROT = 1883; // MQTT 端口
const char *mqtt_user = "zhangds";
const char *mqtt_password = "zhangds123a";
// mqtt 主题
const char *MQTT_TOPIC_PUB_ONLINE = "my/home/pub_online";
const char *MQTT_TOPIC_PUB_UPDATE = "my/home/pub_update"; // 订阅更新
const char *MQTT_TOPIC_SUB_DATA = "my/home/sub_data"; // 发布
const char *MQTT_TOPIC_HEARTBEAT = "my/home/heartbeat"; // 心跳
const char *CLIENT_ID = "esp8266-457065e5-f063-474e-2saf-cacf5cb52af5";
// ticker.attach(s秒数, 函数名)
Ticker ticker; // 定时调用某一个函数
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 mqtt_heartbeat(); // 心跳
void setup()
{
Serial.begin(115200);
init_wifi();
client.setServer(MQTT_SERVER, MQTT_PROT); // 设置mqtt 服务和端口
client.setCallback(mqtt_msg_callback); // 设置mqtt 回调函数
// 心跳
ticker.attach(1, mqtt_heartbeat);
}
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, mqtt_user, mqtt_password))
{
Serial.println("connected");
client.publish(MQTT_TOPIC_PUB_ONLINE, "online"); // 发布
client.subscribe(MQTT_TOPIC_PUB_UPDATE); // 监听
}
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("] ");
String data = "";
for (unsigned int i = 0; i < length; i++)
{
Serial.print((char)payload[i]); // 打印主题内容
data += (char)payload[i];
}
Serial.println();
// ************** string 转 char * 不能对该变量任何操作 **************
// const char *cstr = data.c_str();
// 如果需要修改 必须使用 strcpy 函数复制 注意!!!!!!!!!!!
char *cstr = new char[data.length() + 1];
strcpy(cstr, data.c_str());
cstr = "改变的数据";
// ************** string 转 float **************
String test_float = "12.024";
float num_float = test_float.toFloat();
Serial.print(num_float);
Serial.println();
// ************** string 转 int **************
String test_int = "1254";
int num_int = test_int.toInt();
Serial.print(num_int);
// ************ 字符串比较 ***************
// strcmp(const char s1, const char s2);
// 当 str1 < str2 时,返回为负数(-1);
// 当 str1 == str2 时,返回值= 0;
// 当 str1 > str2 时,返回正数(1)。
// 主题判断
if (strcmp(MQTT_TOPIC_PUB_UPDATE, topic) == 0)
{
// 发布
client.publish(MQTT_TOPIC_SUB_DATA, cstr);
}
}
void mqtt_heartbeat()
{
if (client.connected())
{
client.publish(MQTT_TOPIC_HEARTBEAT, "1");
}
}