Hacking the Sonoff Wifi Switch - Part 3 Alexa Smart Home

Controlling Sonoff with Alexa

This post will build our previous work with the Sonoff Wifi Switch. We'll focus on using an Arduino library called fauxmo to allow Alexa to interact with the Sonoff.

Overview

I have been controlling appliances such as lights and aquaponics equipment using MQTT with Node-RED and also Blynk. Both work well. When I recieved an Echo Plus as a gift for Christmas I quickly understood the potential that the Alexa service had. It is simple to use and for those of us that like getting under the hood, functional short comings can be overcome with the creation of Alexa Skills and some type of internet accessible service to handle logic and automation (AWS Lambda, Node-RED, etc). 

Echo Dot can be had a reasonable price currently. You can also keep tabs on the Alexa development pages. They have been giving out Echo Dot's to Skill creators that meet certain criteria.


This guide will use the FauxmoESP library to expose the Sonoff to Alexa on your local network. FauxmoESP is a port of the python fauxmo library and enables ESP8266 to emulate a Belkin WeMo device. The advantage here is that Alexa has an established method that it uses to interact with Belkin WeMo devices. Check out Xose Perez's documentation for details.

Alexa will then be able to control the Sonoff using standard voice commands or through Alexa Routines. This is a simple working example and not an in depth review of Alexa.

Goals

  • Program the Sonoff Wifi Switch with code that will expose it to the Alexa Discovery processes
  • Discover the device and add it to Smart Home
  • Control the Sonoff with voice commands
  • Control the Sonoff with a routine

Prep

Setup Steps

If you did not follow the previous posts in this series you will need to go back and follow the steps to install the ESP8266 libraries in Arduino.
  • Download the current FauxmoESP library at https://bitbucket.org/xoseperez/fauxmoesp/downloads/
  • Open the Arduino IDE > Sketch > Include Library > Add .ZIP Library...
  • Navigate to the downloaded fauxmo library and Click Open
  • Connect your Sonoff to your computer using the Modded USB to Serial UART adapter and prepare your programming settings as shown in Part 2 of this series
  • Program the Sonoff with the following code

Code

This code is a slightly altered version of the example sketch that comes with FauxmoESP. You will need to insert your wifi SSID/PASS and also the name you wish to give your Sonoff, such as, "Desk Light".


#include <arduino.h="">
#include <esp8266wifi.h="">
#include <fauxmoesp.h="">

#define WIFI_SSID "YOUR SSID"
#define WIFI_PASS "YOUR PASS"
#define SERIAL_BAUDRATE 115200
#define RELAY_PIN 12
#define LED_PIN 13

fauxmoESP fauxmo;

void wifiSetup() {

    // Set WIFI module to STA mode
    WiFi.mode(WIFI_STA);

    // Connect
    Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASS);

    // Wait
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(100);
    }

    Serial.println();

    // Connected!
    Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());

}

void callback(uint8_t device_id, const char * device_name, bool state) {
  Serial.print("Device "); Serial.print(device_name); 
  Serial.print(" state: ");

  if (state) {
    Serial.println("ON");
  } else {
    Serial.println("OFF");
  }


  //Switching action on detection of device name
  if ( (strcmp(device_name, "YOUR DEVICE NAME") == 0) ) {
    if (!state){
      digitalWrite(RELAY_PIN, LOW);
    } else {
      digitalWrite(RELAY_PIN, HIGH);
    }
  }
}

void setup() {

    // turn on LED
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW); // low turns LED on
   
    // setup relay pin
    pinMode(RELAY_PIN, OUTPUT);
    digitalWrite(RELAY_PIN, LOW);
   
    // Init serial port and clean garbage
    Serial.begin(SERIAL_BAUDRATE);

    // Wifi
    wifiSetup();

    // Fauxmo
    fauxmo.addDevice("YOUR DEVICE NAME");
    fauxmo.onMessage(callback);
}

void loop() {
  fauxmo.handle();
}

Alexa Steps

  • Verify that the code is working as expected by using the Arduino Serial Monitor
    • The Sonoff should be connecting to wifi and displaying its IP

  • Disconnect the Sonoff from the USB to Serial UART adapter
  • Plug in the Sonoff to a wall outlet and connect an appliance such as a lamp
  • Now we need to discover the Sonoff using the command "Alexa, discover new devices."
    • Alexa will state the device name that was discovered
  • You can now test that things are working by using the commands, "Alexa, turn on <device name>" and "Alexa, turn off <device name>"
  • Devices can be viewed, modified, and removed using the Alexa app > Smart Home
    • Using groups is very helpful in scenarios in which you would like to control many Sonoff's with the same command or routine
 


  • To create a routine use the Alexa app > Routines
    • I primarily use time schedules to control routines.

Result

While this took very little effort... this is pretty awesome. You can control your device via a cloud based service without exposing the device to the internet and without the effort and maintenance of deploying a server or container to handle protocols and automation.

I currently have 12 Sonoff Wifi Switches, all controlled by Alexa. I have had very little issues over the last month of use. I have one Sonoff that occassionally loses its connection to Wifi. The only thing I find lacking at the moment is a more complex routine builder, but I will try to address that in the next post.

Next Time

I have some ideas to utilize AWS Lambda and Alexa Skills to create more advanced time schedules.



Comments

  1. I wonder if you tried flashing ESP Easy there. Quite fun project and AFAIK Sonoff runs on this chip.

    ReplyDelete
    Replies
    1. I have not yet used ESPEasy.

      If you are not aware though, the Sonoff has an extra GPIO through hole on the PCB. It should be possible to connect a sensor. Thoughts of controlling the Sonoff relay based on sensor thresholds comes to mind.

      Delete
    2. I think they use those GPIOs in TH version that can have Humidity and Temperature sensor. So flashing ESP Easy would be even better idea because it would support it out of the box

      Delete
  2. Hi Dan,
    Looks like the new FauxmoESP library does not have the onMessage() function. I got the compilation error:
    error: 'class fauxmoESP' has no member named 'onMessage'
    Could not locate the older version of FauxmoESP.
    Any suggestions?
    Cheers,
    Ben

    ReplyDelete

Post a Comment

Popular posts from this blog

Hacking the Sonoff Wifi Switch - Part 2

Creating Alexa Skills for IoT and Nodemcu - Part 2 AWS IoT