Sonoff-HomeAssistant (Alternative firmware for Sonoff Switches for use with mqtt/HA)

@namadori @jchasey I am able to use my mac to flash esp8266 without any problem so mac is fine and it’s not the first time I have used it.

How have you guys connected the pin from the sonoff to the USB? Do I have to use both the tx and rx pins on the sonoff ?

I don’t remember which, but on some Sonoffs the labels on TX and RX are inverted. Try to connect straight or crossed, if it makes any difference. And yes, you have to connect both TX and RX.

Ok I will try that when I get home thank you.

right I managed to get something but cannot upload the code whatsoever…been fighting with it tooth and nail…get the following error messages:

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

have done everything I could searched google and this whole thread but no joy !

Are you sure the Sonoff is starting in Bootloading mode?
Other workarounds:

Hello everyone, So i am running into trouble while uploading.
I am able to upload the code. Arduino IDE says: “done uploading” after it counted to 100%.
I see in other videos that the LEDS of the Sonoff s20 flashes after uploading.
Or when you plug it in later. That does not happen for me.
What am I doing wrong?
I am connecting the 3v3 to the sonoff is that correct? Or should I do 5v?

use 3v! My experience with other sonoff devices is that when arduino IDE says its uploaded, it is uploaded. Just close the device and plug it in. If you have configured your mqtt settings and logging (in HA) properly, you should see the device in the logs.

The leds are not even blinking when I plug it in. So I think the uploading was not successfull

Which package do you use? Kmanoz? Tasmota?

Thanks for helping!
I am trying to upload the KmanSonoff
I noticed in this video that the Sonoff led blinks during or after uploading.

But just for testing I also tried::

#define L_1           12
#define LED           13

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(L_1, OUTPUT);
}

void loop() {
  digitalWrite(LED, LOW);
  digitalWrite(L_1, LOW);
  delay(500);
  digitalWrite(LED, HIGH);
  digitalWrite(L_1, HIGH);
  delay(500);
}

If you plug it in and push the button does it switch the load (relais clicks)?
Does it joins the WiFi network? Check the DHCP log of your router.
I have only experience with Tasmota: while and after flashing no blinking leds. When plugged in no blinks, but the led follows the status of the load.

It does nothing when I plug it in, no clicks when I push the button and no light from the LED

That are not good signs. Why don’t you try Tasmota? If it works you know the upload is working and it is a firmware problem. If it doesn’t work it’s the opposite.

Oke solved it.

Apparently the ‘newer’ ones have a different serial flash chip. (credits go to this thread)
Mine Aliexpress cheap version has the “PN25F08B” 1M chip which need to be flashed in “DOUT” mode.
Credit for the chip analysis go to this post.
I had read that somewhere before, but it did not work. I think that was just a problematic try…
Here is where to find that flash chip:

How I wired the FTDI:

mark on pcb is vcc 3v3
from there it is:
Sonoff  -  FTDI
3v3     -  3v3
Rx      -  Tx
Tx      -  Rx
GND     -  GND
Hold down btn before booting, then release after +/- 2sec
    Flash Mode: DOUT
    Flash Frequency: 40MHz
    CPU Frequency: 80MHz
    Flash Size: 1M (64K SPIFFS)
    Debug Port: Disabled
    Debug Level: None
    Reset Method: ck
    Upload Speed: 115200
    Port: COM port connected to Sonoff

Arduino code to test:

#define L_1           12
#define LED           13

void setup() {
 Serial.begin(115200);
  pinMode(LED, OUTPUT);
  pinMode(L_1, OUTPUT);
}

void loop() {
  digitalWrite(LED, LOW);
  digitalWrite(L_1, LOW);
  Serial.println("LOW");
  delay(500);
  digitalWrite(LED, HIGH);
  digitalWrite(L_1, HIGH);
  Serial.println("HIGH");
  delay(500);
}

If you have uploaded then the leds should blink and the relay should click.
The serial monitor (when on 115200 baud) should give HIGH LOW feedback.

3 Likes

@namadori

thank you all for your help @bvansambeek I had to use DOUT thanks for that.

I have successfully uploaded the code i.e. Kmanz.

Can I now connect my mains to the Sonoff and expect it to work flawlessly? or is there anything else I need to connect or do before connecting to the mains?

Thanks again.

Hi @bachoo786

edit: I forgot to answer your question in the excitement of publishing my code :wink:
Yes you can connect the mains and see what happens. You do not need to do any more stuff.
:warning: Always be careful with AC power :warning:

There are a couple of code versions around to get your SONOFF working:

Just upload them and see what works good for you.

I tried KmanOz but it was not stable when wifi or MQTT server is not working.
It would restart the whole thing blinking the relay.

I read good thinks about ESPEasy as you can actually upload without changing the code and then set it up through connecting to it with your phone.

I ended up uploading my own code (forked of some project I cannot find anymore). It is still listening to the button press while Wifi or MQTT is not connected, which increases the WAF. Here it is: (while green light is on then wifi or MQTT is not connected)

//Sonos s20 with:
//- relay - connected to blue led
//- Green LED
//- Momentary button
//
//Home assistant configiguration:
//
//switch:
// - platform: mqtt
//   name: "Woonkamer hoeklamp"
//   state_topic: "home/midden/woonkamer/hoeklamp"
//   command_topic: "home/midden/woonkamer/hoeklamp/set"
//   payload_off: "0"
//   payload_on: "1"
//   qos: 1

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define LED 13
#define RELAY 12       //including blue led
#define buttonPin 0
int buttonState = 0;
int lightstate;

// Update these with values suitable for your network.
const char* ssid      = "SSID";
const char* password  = "password";
const char* mqtt_server = "192.168.0.5";
int mqttport            = 1883;
#define CLIENT_ID         "woonkamer.hoeklamp"
#define MQTT_TOPIC        "home/midden/woonkamer/hoeklamp"

WiFiClient espClient;
PubSubClient client(espClient);
 
void setup(){
  Serial.begin(9600);
  Serial.println("setup begin");
  pinMode(LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(RELAY, LOW);            // Start with lights off
  lightstate = 0;
  Serial.println("setup end");
}

void loop(){
  Serial.println("Loop begin");

  // Connect to Wifi if not connected
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("wifi connect in loop - start");
    setup_wifi();
    Serial.println("wifi connect in loop - wifi connected");
    reconnect();
    client.setServer(mqtt_server, mqttport);
    client.setCallback(callback);
    Serial.println("wifi connect in loop - wifi and MQTT connected");
  } else {
    Serial.println("wifi connect in loop - already connected");
  }

  // reconnect when MQTT is not connected
  if (!client.connected()) {
    Serial.println("MQTT reconnect - start");
    reconnect();

    //publish state here (in case wifi is not connected then lightstate might changed before connecting MQTT)
    if (lightstate == 1){
      client.publish(MQTT_TOPIC, "1", true);
    } else {
      client.publish(MQTT_TOPIC, "0", true);
    }
    
    Serial.println("MQTT reconnect - end");
  } else {
    Serial.println("MQTT reconnect - already connected");
  }
  client.loop();

    // read button press
        buttonState = digitalRead(buttonPin); 
        if (buttonState == 0) {
          if (lightstate == 0){
            lightstate = 1;
            digitalWrite(RELAY, HIGH);   //Light on
            if (client.connected()) {client.publish(MQTT_TOPIC, "1", true);}
          } else {
            lightstate = 0;
            digitalWrite(RELAY, LOW);  //Light off
            if (client.connected()) {client.publish(MQTT_TOPIC, "0", true);}
          }
          delay(150); // delay after button press to prevent double click
        }
        Serial.print("lightstate = ");
        Serial.print(lightstate);
        Serial.print(" - buttonState = ");
        Serial.println(buttonState);   

  Serial.println("Loop ended");
}

void checkbtnpress(){
  buttonState = digitalRead(buttonPin);
  if (buttonState == 0) {
          if (lightstate == 0){
            lightstate = 1;
            digitalWrite(RELAY, HIGH);  //Light on
          } else {
            lightstate = 0;
            digitalWrite(RELAY, LOW);  //Light off
          }
          delay(150);
        } 
   delay(10);    
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid); 
  WiFi.mode(WIFI_STA); //ESP in connect to network mode
  WiFi.begin(ssid, password); 

  while (WiFi.status() != WL_CONNECTED) {
    // wait 50 * 10 ms = 500 ms to give ESP some time to connect (need to give delay else you get soft WDT reset)
      for (int i=0; i <= 50; i++){
      checkbtnpress(); // this takes ~10ms
        if (i == 50) { 
          Serial.println(".");
        } else {
          Serial.print(".");
        }     
      }
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the relay if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(RELAY, HIGH);
    client.publish(MQTT_TOPIC, "1", true);
    lightstate = 1;
    Serial.print("lightstate = ");
    Serial.println(lightstate);
  } else {
    digitalWrite(RELAY, LOW);
    client.publish(MQTT_TOPIC, "0", true);
    lightstate = 0;
    Serial.print("lightstate = ");
    Serial.println(lightstate);
  }
}

void reconnect() {
  // Loop until we're reconnected
  digitalWrite(LED, LOW);           //LED on
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(CLIENT_ID)) {
      Serial.println("connected");
      client.subscribe(MQTT_TOPIC"/set");    //subscribe light to MQTT server, you can set your name here
      digitalWrite(LED, HIGH);       //LED off
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");

      // Wait (500 * 10ms = 5000ms) 5 seconds before retrying, but read button press meanwhile
      for (int i=0; i <= 500; i++){
      checkbtnpress(); // this takes ~10ms
        if (i == 500) { 
          Serial.println(".");
        } else {
          Serial.print(".");
        }     
      }     
    }
  }
}
2 Likes

Hi @bvansambeek

Thanks for the info.

Can you confirm the following again please:

1). With Kmaz’s code are you saying if the Sonoff looses wifi or mqtt connection it wont work?
2). Are you saying your code would still work if the Sonoff looses wifi and mqtt?
3). Finally I have a Sonoff TH16, does your code work with a temperature and humidity sensor?

Thanks.

Anyone played with these switches yet? According to the internal photographs it looks like the ESP chipset. I don’t see an easy to use header for flashing but I bet they can be flashed with a little digging. Friend of mine picked them up on sale a while back, I’ll have to keep an eye on them and pick some up when they go on sale.

1 Like

Hi @bachoo786

  1. The code I used from his GitHub made the relay go on and off if it lost Wifi or MQTT server connection, without looking into it (as the code looked complicated to my eyes) I flashed my code.
  2. With my code: While (trying to connect to Wifi or MQTT) it will { listen to the button press and switch the relay).
  3. My code does not work for the temperature humidity sensor.

You should buy a Wemos on ali for 3 bugs and start doing some basic arduino tutorials to boost your skill. Copy pasting together your own code is fun :wink:

FYI, Have you tried the code of KMaz? is it working for you? If not have you tried uploading the other alternatives and played with it?

Right I see well I have a sonoff with temperature sensor and Kmaz’'s code works for me.

I will try and play with arduino thanks.