Hi all,
I am trying to make a mqtt momentary/timed switch to control a relay, press the button relay is active for 2 seconds then goes off.
I am using a simple code see below.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "B*********";
const char* password = "R**********";
const char* mqtt_server = "192.********";
#define mqtt_user "mqtt" //enter your MQTT username
#define mqtt_password "******" //enter your password
WiFiClient espClient;
PubSubClient client(espClient);
int SwitchedPin = 5, LEDPin = 2, Override = 14, OverrideMem = 0;
bool HassSwitch = false;
String switch1;
String strTopic;
String strPayload;
void setup_wifi() {
Serial.begin(115200);
delay(2000);
Serial.println();
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());
pinMode(LEDPin,OUTPUT);
digitalWrite(LEDPin, HIGH);
}
void callback(char* topic, byte* payload, unsigned int length) {
payload[length] = '\0';
strTopic = String((char*)topic);
if(strTopic == "ha/switch1")
{
switch1 = String((char*)payload);
if(switch1 == "ON")
{
Serial.println("ON");
digitalWrite(SwitchedPin, HIGH);
digitalWrite(LEDPin, LOW);
HassSwitch = true;
delay(2000);
Serial.println("OFF");
digitalWrite(SwitchedPin, LOW);
digitalWrite(LEDPin, HIGH);
HassSwitch = false;
}
else
{
Serial.println("OFF");
digitalWrite(SwitchedPin, LOW);
digitalWrite(LEDPin, HIGH);
HassSwitch = false;
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient", mqtt_user, mqtt_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.subscribe("ha/#");
}
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()
{
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(SwitchedPin, OUTPUT);
digitalWrite(SwitchedPin, LOW);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
if(digitalRead(Override) != OverrideMem && !HassSwitch)
{
if(digitalRead(Override))
{
Serial.println("ON");
digitalWrite(SwitchedPin, HIGH);
digitalWrite(LEDPin, LOW);
OverrideMem = 1;
}
else
{
Serial.println("OFF");
digitalWrite(SwitchedPin, LOW);
digitalWrite(LEDPin, HIGH);
OverrideMem = 0;
}
}
The code works but what isn’t working is the switch state doesn’t update in home assistant when the relay switches off.
My .yaml code is
switch:
- platform: mqtt
mqtt name: "Switch1"
state_topic: "ha/switch1"
command_topic: "ha/switch1"
qos: 2
payload_on: "ON"
payload_off: "OFF"
false retain: true
Can anyone help with this issue,
Thanks