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

Seems like it is connected now:
pi@raspberrypi:~ $ mosquitto
1475778954: mosquitto version 1.4.9 (build date 2016-09-26 21:18:47+0200) starting
1475778954: Using default config.
1475778954: Opening ipv4 listen socket on port 1883.
1475778954: Opening ipv6 listen socket on port 1883.
1475778990: New connection from 10.0.0.109 on port 1883.
1475778990: New client connected from 10.0.0.109 as spinac1 (c1, k90, u’user’).

But still not working from home assistant. Is there some way how to test it?

Is it still flashing 4 times after a few minutes? If so it means it’s dropping it’s connection to your broker and resetting so it has nothing to do with WiFi passwords etc. There are so many possibilities. Do you have only 1 switch, is the MQTT_CLIENT id unique across your whole mosquito network, is your network connection solid. I could go on and on but without knowing your exact environment it’s going to be difficult. Download mqtt-spy or send commands to mosquito of “on” or “off” and see if the switch responds. You don’t need HA to operate the switch. If that work then at lest you know it’s not the switch. It wont be the switch though. It will be your setup. Post what you modified in the code here and lets have a look.

I have been playing around with the homie-esp8266 for sometime.

I was able to do the following within 30 mins with a Sonoff:

  1. solder a 5 pin connector ( still learning to solder)
  2. connect the sonoff up to a PC
  3. upload homie up to the sonoff note: there is an sonoff example in the homie sub directories … I changed a few parameters within the code , but should run as it)
  4. reset sonoff , and it jumped in configuration mode ( read homie doco)
  5. connected nexus 7 tablet to sonoff (wireless) and enter configuration mode ( read doco)
  6. strip power cord done and connected up to the sonoff ( in and out power)
  7. power up
  8. used phoa client to test MQTT messages
  9. configure HASS MQTT Switch
  10. has now been in production for about 2 weeks turning my bedside lamps on and off

With homie , start with the basic LED light on and off example , turn the LED on and off on the esp8266-12
and READ THE DOCO (+8 pages)

refer https://github.com/marvinroger/homie-esp8266 and download the sable version not from GITHUB

also refer https://community.openhab.org/t/framework-homie-for-esp8266/8674
for others issues and problems with homie

should have a basic understanding of MQTT too

Just want to give my 2 cents here.

I have over 10 sonoff switches and they all flashed to arendst firmware stright out of the box, it support OTA, included a webserver, etc… so basically arendst firmware is more than we need to integrate it to HASS.

Firmware and instruction on how to flash and change mqtt settings are on the link below. You can even update the mqtt settings via the buildin webserver after you flash the firmware.

After that just put the following in your hass config file. update the the topic with your topic name. (my example below use topic “sonoff4”. restart hass and that’s it. Hope this help.

light:
platform: mqtt
name: “Office light 4”
command_topic: “cmnd/sonoff4/light”
state_topic: “stat/sonoff4/LIGHT”
qos: 2
retain: true
payload_on: “On”
payload_off: “Off”

Thanks kenshin & leeb98

If people are having trouble with my firmware then I’d suggest that more complex firmware that requires more setup, knowledge, additional apps on tablets etc, like the 2 mentioned might be more trouble for beginner users. It’s difficult for first time users to grasp the concepts of HA, mqtt and an Arduino IDE and put it all together.

That’s the reason I wrote this firmware, to simplify it for people just starting off. I appreciate both your comments though, but lets not complicate the thread with more options and try keep it on topic.

Also note how many issues have cropped up on Theos firmware & homie. Again, that’s the point of this firmware, simple but issue free and rock solid :smiley:

@KmanOz here are my configs (single sonoff, rocksolid wifi):

**ARDUINO IDE **

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

#define BUTTON 0 // (Don’t Change for Sonoff)
#define RELAY 12 // (Don’t Change for Sonoff)
#define LED 13 // (Don’t Change for Sonoff)

#define MQTT_CLIENT “spinac1” // mqtt client_id (Must be unique for each Sonoff)
#define MQTT_SERVER “10.0.0.102” // mqtt server
#define MQTT_PORT 1883 // mqtt port
#define MQTT_TOPIC “home/sonoff/living_room/1” // mqtt topic (Must be unique for each Sonoff)
#define MQTT_USER “user” // mqtt user
#define MQTT_PASS “pass” // mqtt password

#define WIFI_SSID “V2” // wifi ssid
#define WIFI_PASS “prasatko001” // wifi password

#define VERSION "\n\n------------------ Sonoff Powerpoint v1.0p -------------------"

**extern “C” { **
** #include “user_interface.h” **
}

bool sendStatus = false;
bool requestRestart = false;

int kUpdFreq = 1;
int kRetries = 10;

unsigned long TTasks;
unsigned long count = 0;

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient, MQTT_SERVER, MQTT_PORT);
Ticker btn_timer;

void callback(const MQTT::Publish& pub) {
** if (pub.payload_string() == “stat”) {**
** }**
** else if (pub.payload_string() == “on”) {**
** digitalWrite(LED, LOW);**
** digitalWrite(RELAY, HIGH);**
** }**
** else if (pub.payload_string() == “off”) {**
** digitalWrite(LED, HIGH);**
** digitalWrite(RELAY, LOW);**
** }**
** else if (pub.payload_string() == “reset”) {**
** requestRestart = true;**
** }**
** sendStatus = true;**
}

void setup() {
** pinMode(LED, OUTPUT);**
** pinMode(RELAY, OUTPUT);**
** pinMode(BUTTON, INPUT);**

** digitalWrite(LED, HIGH);**
** digitalWrite(RELAY, LOW);**


** btn_timer.attach(0.05, button);**


** 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(500);**
** 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();**
** }**
}

void loop() { **
** mqttClient.loop();

** timedTasks();**
** checkStatus();**
}

void blinkLED(int pin, int duration, int n) { **
** for(int i=0; i<n; i++) { **
** digitalWrite(pin, HIGH); **
** delay(duration);

** digitalWrite(pin, LOW);**
** delay(duration);**
** }**
}

void button() {
** if (!digitalRead(BUTTON)) {**
** count++;**
** } **
** else {**
** if (count > 1 && count <= 40) { **
** digitalWrite(LED, !digitalRead(LED));**
** digitalWrite(RELAY, !digitalRead(RELAY));**
** sendStatus = true;**
** } **
** else if (count >40){**
** Serial.println("\n\nSonoff Rebooting . . . . . . . . Please Wait"); **
** requestRestart = true;**
** } **
** count=0;**
** }**
}

void checkConnection() {
** if (WiFi.status() == WL_CONNECTED) {**
** if (mqttClient.connected()) {**
** Serial.println(“mqtt broker connection . . . . . . . . . . OK”);**
** } **
** else {**
** Serial.println(“mqtt broker connection . . . . . . . . . . LOST”);**
** requestRestart = true;**
** }**
** }**
** else { **
** Serial.println(“WiFi connection . . . . . . . . . . LOST”);**
** requestRestart = true;**
** }**
}

void checkStatus() {
** if (sendStatus) {**
** if(digitalRead(LED) == LOW) {**
** mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/stat", “on”).set_retain().set_qos(1));**
** Serial.println(“Relay . . . . . . . . . . . . . . . . . . ON”);**
** } else {**
** mqttClient.publish(MQTT::Publish(MQTT_TOPIC"/stat", “off”).set_retain().set_qos(1));**
** Serial.println(“Relay . . . . . . . . . . . . . . . . . . OFF”);**
** }**
** sendStatus = false;**
** }**
** if (requestRestart) {**
** blinkLED(LED, 400, 4);**
** ESP.restart();**
** }**
}

void timedTasks() {
** if ((millis() > TTasks + (kUpdFreq*60000)) || (millis() < TTasks)) { **
** TTasks = millis();**
** checkConnection();**
** }**
}

**configuration.yaml **

mqtt:
** broker: 127.0.0.1**
** port: 1883**
** client_id: home-assistant-1**
** username: pi**
** password: raspberry**
** protocol: 3.1.1**

switch:
** platform: mqtt**
** name: “Living Room”**
** state_topic: “home/sonoff/living_room/1/stat”**
** command_topic: “home/sonoff/living_room/1”**
** qos: 1**
** payload_on: “on”**
** payload_off: “off”**
** retain: true**

Notice that you haven’t set the username and password for the switch and left them default of ‘user’ and ‘pass’ but your mqtt broker in your Pi is setup to use

** username: pi**
** password: raspberry**

Enter the same username and password into the Sonoff sketch. (pi & raspberry) Username and password can be the same across all devices. It’s only CLIENT_ID that needs to be different.

Try that :smiley:

SUCCESS it finally runs with manual jessie and mosquitto installation. THANK YOU SO MUCH @KmanOz

Another question. After restart now HASS runs wit this command:
(homeassistant_venv) homeassistant@raspberrypi:/srv/homeassistant $ hass

How should I set systemd autostart with this user (like in the command)?

I tried this without success:

su -c 'cat <> /etc/systemd/system/[email protected]
[Unit]
Description=Home Assistant
After=network.target

[Service]
Type=simple
User=%i
ExecStart=/srv/homeassistant/homeassistant_venv/bin/hass

[Install]
WantedBy=multi-user.target
EOF’

If I try it without sudo it asks me for the password by I don´t know what is homeassistant user password. This user has beem created by HASS installation.

Thank you very much.
I will try.
How about module with power consumtions support?
Is it possible to modify it to MQTT?

I am waiting for the new Sonoff Pow switch to be available. Their Websire says stock will be available by 10th Oct. I will keep you posted because I plan to order one and have a play.

Not sure. I don’t use a Raspberry Pi. There would be other topics in here that would discuss it and I’m sure you’ll get an answer.

Glad it works for you :smiley:

I have just ordered. Sonoff Pow WiFi Switch With Power Consumption Measurement Model: IM160810001
Waiting

@KmanOz do you plan also firmware for https://www.itead.cc/sonoff-led.html ?
I think your firmware is superb - very stable and easy to setup.

1 Like

OK I will place order for both today. I had no idea about the LED but it looks good.

I have not ordered LED.

LOL that was for Jiran :smiley: and myself actually. I could use them in a few areas around the house.

I am using this:
In file /etc/rc.local
add this row:
(sleep 75; sudo -u ha -H /srv/ha/ha_venv/bin/hass)
where:
sleep 75 - time before HA start.
ha - user id
/srv/ha/ha_venv/bin/hass - hass location

Hey! I’ve found this thing too with ESP!

ARILUX™ AL-LC09 super mini LED contrôleur app wifi + rf télécommande rgb LED bande dc9-28v

Yes I’v seen that as well. I think the iTead one works out a little cheaper because you get a bunch of LED strips with it as well. Anyway I am waiting on my order now :smiley: The amount of stuff coming out with ESP on board is awesome. Most of it is crappy firmware but that’s easily fixed :smiley:

1 Like