Sonoff Touch switch and MQTT (ESP) help needed

HI all,

Upfront I apologise if this has totally been covered by someone, I have read so much on this topic but seem to not find a solution.

In short, I have flashed a Sonoff Touch [(https://sonoff.itead.cc/en/products/residential/sonoff-t1)], with my own ESP8266 code. I did NOT use Tasmota. The Touch is connected to the wifi, and I can even publish MQTT topics to it, and it responds. (I can make all three the relays). However, the physical buttons on the touch does not work. So my challenge is not so much OH, but in the ESP8266 code.
When I say my own code, I mean code I have used on other ESP8266’s and ESP32’s I have around the house. Mostly sprinklers, lights via relays and such. The Sonoff touch is the first time I have had to publish MQTT topic from the “thing”.

I have the following setup.

OpenHAB 2.4
MQTT v1 (but have the v2 addon for all my other ESP’s to work)

Here is a copy of my items entries:

Blockquote
Switch kitchenswitch1 “Kitchen Switch1” (grp_kitchen, grp_houselights) [ “Lighting” ] {mqtt=">[broker:openhab/in/kitchen:command:ON:switch1ON],>[broker:openhab/in/kitchen:command:OFF:switch1OFF]"}
Switch kitchenswitch2 “Kitchen Switch2” (grp_kitchen, grp_houselights) [ “Lighting” ] {mqtt=">[broker:openhab/in/kitchen:command:ON:switch2ON],>[broker:openhab/in/kitchen:command:OFF:switch2OFF]"}
Switch kitchenswitch3 “Kitchen Switch3” (grp_kitchen, grp_houselights) [ “Lighting” ] {mqtt=">[broker:openhab/in/kitchen:command:ON:switch3ON],>[broker:openhab/in/kitchen:command:OFF:switch3OFF]"}

Here is my ESP8266 code.

Blockquote
#include <ESP8266WiFi.h>
#include <MQTTClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
/* WIFI Settings /
// Name of wifi network
const char
ssid = “xxxxxx”;

// Password to wifi network
const char* password = "xxxxxx"; 

/* Web Updater Settings */
// Host Name of Device
const char* host = "KitchenSonoffSwitch";

// Path to access firmware update page (Not Neccessary to change)
const char* update_path = "/firmware";

// Username to access the web update page
const char* update_username = "xxxx";

// Password to access the web update page
const char* update_password = "xxxx";

/* MQTT Settings */
// Topic which listens for commands
const char* subscribeTopic = "openhab/in/kitchen"; 

//MQTT Server IP Address
const char* server = "192.168.0.18";

//Unique device ID 
const char* mqttDeviceID = "KitchenSonoffSwitch"; 

int channel1 = 12;  // for the relays, these work!
int channel2 = 5;   // for the relays, these work!
int channel3 = 4;   // for the relays, these work!
int button1 = 0;  // this is for the SONOFF button I think
int button2 = 9;  // this is for the SONOFF button I think
int button3 = 10; // this is for the SONOFF button I think
int buttonState1 = digitalRead(button1);
int buttonState2 = digitalRead(button2);
int buttonState3 = digitalRead(button3);

//webserver 
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

//MQTT
WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

//Connect to WiFI and MQTT
void connect();

//Setup pins, wifi, webserver and MQTT
void setup() {
    Serial.begin(115200);
  delay(10);

  // set pin modes  for the relays, these work!
  pinMode(channel1, OUTPUT);
  digitalWrite(channel1, LOW);

  pinMode(channel2, OUTPUT);
  digitalWrite(channel2, LOW);

  pinMode(channel3, OUTPUT);
  digitalWrite(channel3, LOW);

  // set button modes // this is for the SONOFF buttons
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);


  WiFi.mode(WIFI_STA);
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  client.begin(server, net);
 // client.onMessage(messageReceived);

  connect();
  MDNS.begin(host);
  httpUpdater.setup(&httpServer, update_path, update_username, update_password);
  httpServer.begin();

  MDNS.addService("http", "tcp", 80);
}

//Connect to wifi and MQTT
void connect() 
{
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println(WiFi.localIP());
  
  while (!client.connect(mqttDeviceID)) 
  {
    delay(500);
  }

  client.subscribe(subscribeTopic);
}

void loop() 
{
  // MQTT Loop
  client.loop();
  delay(10);

  // Make sure device is connected
  if(!client.connected()) 
  {
    connect();
  }

  httpServer.handleClient();

//}

// willie button code starts. My effort to get the physical buttons to work
/*
 *
if(buttonState1 == HIGH)
  {  
    client.publish("openhab/in/kitchen", "switch1ON");
    digitalWrite(channel1, HIGH);
    delay(250);
  } 
   else if(buttonState1 = LOW) 
  {
    client.publish("openhab/in/kitchen", "switch1OFF");
//    digitalWrite(channel1, LOW);
    delay(250);
  }
else if(buttonState2 == HIGH)
  {  
    client.publish("openhab/in/kitchen", "switch2ON");
    digitalWrite(channel2, HIGH);
    delay(250);
  } 
   else if(buttonState2 = LOW) 
  {
    client.publish("openhab/in/kitchen", "switch2OFF");
//    digitalWrite(channel2, LOW);
    delay(250);
  }
else if(buttonState3 == HIGH)
  {  
    client.publish("openhab/in/kitchen", "switch3ON");
    digitalWrite(channel3, HIGH);
    delay(250);
  } 
   else if(buttonState3 = LOW) 
  {
    client.publish("openhab/in/kitchen", "switch3OFF");
    digitalWrite(channel3, LOW);
    delay(250);
  }
 }

 */

 //  willie button code stops My effort to get the physical buttons to work stops here

 // everything below this works
  // Change the state of a relay based on the MQTT Message
  void messageReceived(String &topic, String &payload) 
  {
    String msgString = payload;

  if (msgString == "switch1ON")
  {
    digitalWrite(channel1, HIGH);
    delay(250);
  }
  else if (msgString == "switch1OFF")
  {
    digitalWrite(channel1, LOW);
    delay(250);
  }
  else if (msgString == "switch2ON")
  {
    digitalWrite(channel2, HIGH);
    delay(250);
  }
  else if (msgString == "switch2OFF")
  {
    digitalWrite(channel2, LOW);
    delay(250);
  }
  else if (msgString == "switch3ON")
  {
    digitalWrite(channel3, HIGH);
    delay(250);
  }
  else if (msgString == "switch3OFF")
  {
    digitalWrite(channel3, LOW);
    delay(250);
  }
}

You may note the commented part in the middle, it was my attempt to get this to work. BUt that code only made button1 come on and stay on, and the MQTT status was basically looping all the time.

According to this site link the GPIO’s are the way I declared them, but I may be wrong in the interpretation.

I would really appreciate some guidance. My coding skills are near to non-existant. :slight_smile:

THank you in advance.

Given this problem is outside of OH and the fact that the vast majority of users on this forum flash their esps with Tasmota, ESPEasy or one of the other firmwares, I suspect you will have better luck on an ESP or Arduino form than here. We just don’t have the concentration of experience here too have a high likelihood of being able to help.

What I can say is part of the reason for the behavior you see us because you publish a message every time through the loop instead of keeping track of the last publish and only sending a new message when the state changes.

Thanks Rich, appreciate the feedback. I decided to flash with Tasmota also.

i would say, if you can make tasmota work for what you want, use that. I have 7 sonoff t1 switches. 1,2 and 3 gang all working with tasmota

Thanks Christopher,
I loaded Tasmota, configured the type and MQTT and Wifi.
I can get the button to work manually as well as from mosquito_pub, but not from OH items file.

Would you mind a quick squizz?

Here is my config:

My OH Items entry.

Switch kitchenswitch1 "Kitchen Switch1" <light> (grp_kitchen) {mqtt=">.        [broker:openhab/in/kitchen/cmnd/switch/POWER1:ON:ON],>.  [broker:openhab/in/kitchen/cmnd/switch/POWER1:OFF:OFF]"}

from the SOnoff Information page:
MQTT Full Topic openhab/in/kitchen/cmnd/switch/

The OH log

2019-07-01 07:17:18.587 [ome.event.ItemCommandEvent] - Item 'kitchenswitch1' received command ON
2019-07-01 07:17:18.634 [vent.ItemStateChangedEvent] - kitchenswitch1 changed from OFF to ON
2019-07-01 07:17:23.703 [ome.event.ItemCommandEvent] - Item 'kitchenswitch1' received command OFF
2019-07-01 07:17:23.719 [vent.ItemStateChangedEvent] - kitchenswitch1 changed from ON to OFF

However, in MQTT I don’t see anything and of course the SOnoff doesnt change state.Preformatted text

This is a setup for a single switch.
Your MQTT section is laid out all wrong.
Dont put a FULL topic in your MQTT setup in tasmota. Just put something simple like
KitchenWallSwitch
Also i find it easier to call the sonoff device the same name for continuity when trying to find it on your routers dhcp page

the < is the state which is received from topic
stat/topic/POWER, I do this because it seems to eliminate a random issue where the item has a predicted event and will always return back to off when you click it on.
and the command > is
cmnd/topic/power

the * after command: is for it to pass the command exactly, and with a switch its either on or off.
If you wanted to have it pass a specific message for ON you would type :comand:ON:Whateveryourcommandis, and you would have another > for command:OFF:whateveryourcommandis

Switch KitchenLight "Kitchen"	<light>    (IndoorLighting,Lights)  	[ "Lighting" ]   	{ mqtt="<[broker:stat/KitchenWallSwitch/POWER:state:default],>[broker:cmnd/KitchenWallSwitch/power:command:*:default]" }

if you had a two gang you would do something like this

Switch KitchenLight "Kitchen"	<light>    (IndoorLighting,Lights)  	[ "Lighting" ]   	{ mqtt="<[broker:stat/KitchenWallSwitch/POWER1:state:default],>[broker:cmnd/KitchenWallSwitch/power1:command:*:default]" }

Switch KitchenLight 2 "Kitchen 2"	<light>    (IndoorLighting,Lights)  	[ "Lighting" ]   	{ mqtt="<[broker:stat/KitchenWallSwitch/POWER2:state:default],>[broker:cmnd/KitchenWallSwitch/power2:command:*:default]" }

Awesome stuff thank you so much.

Got it all to work! :smile:

Works like a charm :smile: