在家庭助理更新之前,开关一直运行良好!但是在我无法解决这个问题之后。我用 esp32-dev Kit v1 制作了我的房间灯开关,就像这样 画的
Arduino代码在这里
#include <WiFi.h>
#include <PubSubClient.h>
const char *ssid = "olleh_WiFi_BA83";
const char *password = "0000002583";
const char* ID = "테스트"; // Name of our device, must be unique
const char* TOPIC = "room/light/ahn";
const char* INTOPIC = "room/light/Switch";
const char* mqttUser = "dragon";
const char* mqttPassword = "qazwsxedcrfvtgbyhnujm";
const char* broker = "172.30.1.48";
WiFiClient wclient;
PubSubClient client(wclient);
char messages[50];
int state = 0;
int state1 = 0;
int state2 = 0;
int SW_state = 0;
int light = 4;
// Connect to WiFi network
void setup_wifi() {
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Received messages: ");
Serial.print(INTOPIC);
for(int i=0; i<length; i++){
Serial.println((char) payload[i]);
}
Serial.println();
if ((char)payload[0] == '1') {
state = HIGH;
state1 = LOW;
client.publish(TOPIC, "1");
} else if((char)payload[0] == '0') {
state = LOW;
state1 = HIGH;
client.publish(TOPIC, "0");
}
digitalWrite(4, state);
Serial.print(state);
}
// Reconnect to client
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(ID, mqttUser, mqttPassword)) {
Serial.println("connected");
Serial.print("Publishing to: ");
Serial.println(TOPIC);
Serial.println('\n');
client.subscribe(INTOPIC);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println("\n try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(light, OUTPUT);
pinMode(5, INPUT);
delay(100);
setup_wifi(); // Connect to network
client.setServer(broker, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()){
reconnect();
}
client.loop();
if (digitalRead(5) != SW_state) {
state2 = state;
state = state1;
state1 = state2;
digitalWrite(4, state);
snprintf(messages, 75, "%ld", state);
client.publish(TOPIC, messages);
}
SW_state = digitalRead(5);
}
和家庭助理'configuration.yaml'在这里
#Switch
switch:
- platform: mqtt
name: "불"
command_topic: "room/light/Switch"
state_topic: "room/light/ahn"
payload_on: "1"
payload_off: "0"
state_on: "1"
state_off: "0"
qos: 0
retain: true