|
这里是源码用的是ESP32 Ard IDE 谁帮我看看如何添加第二个开关呢 怎么加都加不上去
#include <WiFi.h> //wifi连接
#include <PubSubClient.h> //mqtt通讯库
WiFiClient espClient;
PubSubClient client(espClient);
const char *wifi_ssid = "qqqq"; //wifi 账号
const char *wifi_password = "123456789"; //wifi密码
const char *mqtt_server = "139.***.***.***"; //MQTT_IP
const char *mqtt_ssid = "****"; //MQTT_账号
const char *mqtt_password = "*****"; //MQTT_密码
const char *mqtt_ID = "测试数据"; //MQTT_客户ID
const int mqtt_Port = 1883; //MQTT端口
int
key_kk = 32; //定义数字2
char resp1[] = R"({
"~": "homeassistant/light/bedroom",
"name": "开关",
"unique_id": "bedroom_light",
"cmd_t": "~/set",
"stat_t": "~/state",
"schema": "json",
"brightness": true})";
void callback(char *topic, byte *payload, unsigned int length) { //回调函数
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String s = "";
for (int i = 0; i < length; i++) {
s = s + (char)payload;
}
Serial.println(s);
if (s == "{\"state\":\"ON\"}") {
digitalWrite(key_kk, HIGH);
client.publish("homeassistant/light/bedroom/state", (char *)s.c_str());
}
if (s == "{\"state\":\"OFF\"}") {
digitalWrite(key_kk, LOW);
client.publish("homeassistant/light/bedroom/state", (char *)s.c_str());
}
}
//WIFI 设置重连
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("链接WIFI账号: ");
Serial.print(wifi_ssid);
Serial.println();
WiFi.mode(WIFI_STA); //wifi 模式
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi 链接成功");
Serial.print("IP 地址: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// 循环直到我们重新连接
while (!client.connected()) //客户端是否链接
{
Serial.println("正在链接MQTT客户端...");
if (client.connect(mqtt_ID, mqtt_ssid, mqtt_password)) //clientID, userName, userPassword
{
client.publish("homeassistant/light/bedroom/config", resp1); //订阅个开关HA主题
client.subscribe("homeassistant/light/bedroom/set"); //开关订阅
Serial.println("链接MQTT网络成功");
} else {
Serial.print("链接MQTT客户端失败");
Serial.print(client.state());
Serial.println(" 五秒后再次尝试");
delay(5000);
}
}
}
void mqtt_cl() //MQTT重连
{
if (!client.connected()) { reconnect(); }
}
void setup() {
Serial.begin(115200);
pinMode(key_kk, OUTPUT); // 初始化IO设置成输出
setup_wifi();
client.setServer(mqtt_server, mqtt_Port); //链接MQTT
client.setCallback(callback); //回调函数
mqtt_cl(); //MQTT重连
}
void loop() {
mqtt_cl(); //MQTT重连
client.loop();
}
|
|