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

I agree - i have done the same thing. Though i am not use @KmanOz implementation, I am using arendst, and just modified it to turn the relay on really quickly.

I am hoping that we can get the Xiaomi smart home into HASS soon, and then i will use the wireless buttons as the new switch.

The thing is does not do is check for errors, so if lets say, the probe is not connected, it gives a reading of -127 rather than the appropriate message. Also, if the unit is down, it displays the last reading instead of coming up with a message. Otherwise, as long as all is connected, stable.

I am a bit of minimalist, that’s why I have 2 versions of the firmware. The version that checks temperature expects to have a temp sensor plugged in otherwise use the ver without temp. I could wrap all version into 1 but I guess I like keeping things to bare essential code specific for the application.

Do you have this in github or can you update the format using the </> option

Guys

For anyone interested in the LEDS I’v pushed some updated code to Github for you all to get going. So far after 1 week of using the unit I’m very impressed. Anyway here you go.

https://github.com/KmanOz/SonoffLED-HomeAssistant

Kman

@KmanOz great piece of sketch. thanks.
I’ve changed your code using attachInterrupt instead polling inputs, and add the pin3 (RX) as digital input to handle traditional wall switch.
My plan is to detach the wall switch from 200v power and use it with pin3 (pullup resistor on J1 to J2, switch to ground J4), leaving the sonoff attacched directly to the lamp. With these settings, i think i’ll able to switch the light both with wall switch and with MQTT, and send switch status to MQTT in both case.
Also need 330Ohm resistor on USB-UART tx pin (to sonoff rx pin) to avoid problems when start flashing with pin3 as input.

1 Like

Yep no worries with the sketch. Your idea sounds good. Wiring all that in neatly into the unit could be messy. They were never really designed to have anything attached to them. They don’t really expose any other pins in a nice way to the real world. It’s gonna be a challenge to get to the them I recon although I haven’t studied the board in detail. Not for the average hacker that’s for sure but what your suggesting is more than feasible from a code and h/w perspective.

Good luck. Keep me posted :smiley:

I have made some modifications to the code to allow the the use of wall switches. These are wired in via a 10k ohm resistor to -ve gnd and the other side of the switch to +ve 3v

void light_switch() {
   light_switch_State = digitalRead(light_switch_pin);

   if (light_switch_State != last_light_switch_State ) {  
      digitalWrite(LED, !digitalRead(LED));
      digitalWrite(RELAY, !digitalRead(RELAY));
      sendStatus = true;
   }
     last_light_switch_State = light_switch_State;  // save light switch  state for next comparison:
}

I was also having the issue of the sonoff not connecting to wifi for extended amounts of time and have found that increasing the delay in the connect function from 500ms to 1000ms solved the issue

 mqttClient.set_callback(callback);
  
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.begin(115200);
  Serial.println(VERSION);
  Serial.print("\nESP ChipID: ");
  Serial.print(ESP.getChipId(), HEX);
  Serial.print("\nConnecting to "); Serial.print(WIFI_SSID); Serial.print(" Wifi"); 
  while ((WiFi.status() != WL_CONNECTED) && kRetries --) {
    delay(1000);
    Serial.print(" .");
  }
  if (WiFi.status() == WL_CONNECTED) {  
    Serial.println(" DONE");
    Serial.print("IP Address is: "); Serial.println(WiFi.localIP());
    Serial.print("Connecting to ");Serial.print(MQTT_SERVER);Serial.print(" Broker . .");
    delay(500);
    while (!mqttClient.connect(MQTT::Connect(MQTT_CLIENT).set_keepalive(90).set_auth(MQTT_USER, MQTT_PASS)) && kRetries --) {
      Serial.print(" .");
      delay(1000);
    }
    if(mqttClient.connected()) {
      Serial.println(" DONE");
      Serial.println("\n----------------------------  Logs  ----------------------------");
      Serial.println();
      mqttClient.subscribe(MQTT_TOPIC);
      blinkLED(LED, 40, 8);
      digitalWrite(LED, HIGH);
    }
    else {
      Serial.println(" FAILED!");
      Serial.println("\n----------------------------------------------------------------");
      Serial.println();
    }
  }
  else {
    Serial.println(" WiFi FAILED!");
    Serial.println("\n----------------------------------------------------------------");
    Serial.println();
  }
}

Hope these modifications help. One issue that is currently happening is that when the relay is toggled via the home assistant web interface is that it will toggle but switch back immediately to previous state has anyone else had this issue and any possible solutions??

I have been pondering how to use the sonoff with a normal light switch. Wiring in parallel is simple, but HA never knows the true state of the light, because the manual switch can override.

Also I don’t think everyone in my house will want to use HA, it is pretty simple to be able to walk in a room and hit a switch…

I see some of you have tried to remedy this, @mudman I am confused by your wiring, can you draw a picture for a simple guy like me?

My tentative idea was to use pin 14, which is exposed on the board, and a momentary switch (ie replacing my on off light switch with a “bell press” switch). The firmware would just have to monitor for the flick of the switch, either interrupt or polling. It then toggles the state of the light, and informs mqtt of the change of state.

Either that or it could be wired (as suggested further up the thread) across the existing button.

Hi KmanOz

I see you have sorted the Sonoff LED firmware.
Well done.

Are you still considering modified firmware for the Sonoff POW.
If you need one to play with more than happy to send you one.
We are both in Australia so it is just local postage.

Thanks again for the Sonoff TH16 code it works like a charm in Home Assistant.
Had my first one fail today only switched a box fan on about 2 times before it became unresponsive.
Checked the fuse but no it was definitely not going to work again.
Typically the quality has been really good, the TH16 will switch my compressor on !!

Cheers
RAWB

1 Like

The switch is wired in the same manner as below (diagram borrowed from online otherwise you would be seeing a monkeys impression of a picasso) except that gpio pin 14 is used for input although you could use any other of the easily exposed programmable pins for this. And that the +5ve is actually +3ve. The code I have written allows the use of normal toggle switches as found in the home to switch the light on / off no matter the means of how it was turned on and also to broadcast this via MQTT to keep HASS updated

1 Like

Hey dude. A fellow Aussie :smiley:

I actually have one here and is next on the list but thanks for the offer. LOL I use the basic Sonoff to switch off my compressor in the garage. I had to install it cause I would forget to switch it off and my bedroom is at the front of the house close to the Garage. Due to hose leakge compressor would go off in the middle of the night and scare the crap out of me. Fixed that I did :smiley:

I had a power surge here a couple of weeks back. Took out a Sonoff. I tried programming it and it would take code but just not connect to Wifi. Called it dead. Left it for 2 weeks and thought lemme see if I can get it going again. Did nothing different used the same code and it sprang back to life. Had me stumped but it works so what the hell. :smiley:

It’s not the Sonoff. There is something else going on there. I’ve been playing with HA since I think v0.16 and have seen that heaps of times but it’s always either comms to your mqtt broker, or Browser has somehow lost connectivity to HA or something. I’d be checking your network and in particular mqtt connectivity. To be honest I’m not a big fan of HA and mqtt broker working on 1 device. I use a separate broker because I want mqtt (which runs everything in my house) to be on irrespective of what HA is doing or how busy it is. Next time that happens refresh your browser and see if it fixes the issue unless of course that happens with every Sonoff every time. Again though it’s not the Sonoff or the code because there too many of them out there running the code successfully. Start looking else where is what I’m saying.

Also you could have just changed this:

int kRetries = 10;

and made it:

int kRetries = 20;

but either or will work. I will make sure I comment that line so people know to change that figure if they have connection issues. BTW your light switch add on is simple and easy. I wish the pns on the ESP were exposed a little better on the circuit board. I guess they weren’t thinking of future expansion to the point that some people want to take these things to.

Midnight compressor (a tune so often played), hehe
Mostly blame advancing age or maybe just too keen to knock off !!!

The Sonoff POW uses the Ewelink software and part of the reason I was asking about your progress is the app itself.
It immediately wanted to update outside of the Google Play Store requesting the use of “unknown sources” on Andriod.
The permissions are excessive too, wanting access to photos and phone contacts !!.
As any of you who have the device know, it does not want to shut down either.

cheers
RAWB

******* A NOTE TO ALL *******

Don’t be in a rush to work on the Sonoff’s. Iv been playing with electronics and electricity for 40 years. Remember to disconnect the Sonoff from mains before you plug in your FTDI adapter. Yesterday I has some free time so I thought I would finish off the code to the Sonoff POW. In my rush I forgot to unplug mains power and when I plugged in the FTDI, Sonoff literally went POW !!!

Lost Computer, Sonoff, FTDI adaptor and USB HUB. Basically everything in line. Not a great day. I laugh but thought I would post this to say BE CAREFUL, take your time and unplug. I never thought it would happen to me but there you go.

Anyway, back to spare (OLD) computer. Should have POW up this weekend. EDIT: No I won’t. I don’t have one to test with. Should be soon.

Take care !!

7 Likes

What should be the expected boot up time with this firmware? from power applied to connected to wifi and subscribed ready for commands.

I know the wifi may vary but just wonder.

On my WiFi it takes up to 8 seconds sometimes but is mostly less to connect and be ready for commands

You kinda answered your own question. The answer is. it varies. Mine take 2 - 3 seconds. If it doesn’t happen in that time, I have found that it won’t happen at all. Then I have to wait for the checking routing I have created in the software to kick in (every minute) to reboot the switch and try again or I can turn it off and try again myself and wait for connection. In reality, when the switch is installed in the wall or ceiling, you don;t have the opportunity to manually restart and have to rely on the firmware doing it’s job and connecting for you. Anyway connect time is only an issue if you turn the power on and off to the Sonoff with the wall switch. I don’t. They stay on all the time. I really don’t care how long they take to connect at boot up because it only happens once for me, and know within a couple of minutes they’re connected and will stay connected as long as you have a stable WiFi environment. For someone who turns them on and off with the wall switch every time, connect time is definitely an issue but I really don’t like that method at all. ESP’s are notorious at sometimes not connecting for whatever reason.

I can tell you this. The brand of router plays a more important roll than the code in my firmware. I (like all others) use a WiFi library that uses a simple call “WiFi.begin(WIFI_SSID, WIFI_PASS)” to connect to the router. I don’t know of anyone using lower level routines to do that. The negotiation, handshake etc is handled by the router and ESP directly at a much lower level. This is where delays can happen because not all routers handle that negotiation the same way. I had an Apple Airport Extreme here for a long time. I had so many issues with that it wasn’t funny and it’s meant to be a premium product. I swapped to a Thompson Gateway supplied by my ISP and all issues vanished. In fact this router is so stable it’s ridiculous. In 12 months of it being connected, I have never had to reboot it and I have 40+ wireless devices connecting to it,

I keep all Sonoff switches on 2.4Ghz and all computers, phones, peripherals on 5Ghz. I try and create that separation even though it’s probably not necessary. My router has the ability to set a different SSID for 2.4 & 5Ghz and all Home Automation stuff stays on 2.4Ghz. The traffic is minimal for HA stuff anyway.

Hope that helps :smiley:

1 Like

I have seen this warning on other posts about sonoff, but thanks for the reminder. Shame about your gear, what a bummer.

It’s not just Sonoff’s, it’s nearly all modern electronics. There is no isolation transformer any more. In the old days that transformer would isolate mains voltage from low level DC voltage. There was never an electrical path between them. Now with new switch mode supplies that is no longer the case. On a positive side power supplies have shrunk to the point where they can make a device like a Sonoff so small. It was a silly mistake because I was rushing, that’s all. When developing software it seems like you have uploaded firmware 1000 times. The only thing that actually bothers me about ESP modules is how slow they are to upload compared to Arduino’s but if your just send code 1 or twice it’s not big deal.

I don’t want people to be put off working on the them because they are awesome units for the price, JUST BE CAREFUL :smiley:

2 Likes