Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

SONOFF Dual: Control Your Electrical Appliances Remotely

DZone's Guide to

SONOFF Dual: Control Your Electrical Appliances Remotely

Thanks to the SONOFF Dual smart plug, the MQTT protocol, and an Ubidots library, you can easily create a remote switch to control your appliances.

· IoT Zone
Free Resource

Download Red Hat’s blueprint for building an open IoT platform—open source from cloud to gateways to devices.

In this guide, you will learn how to control a couple of 110V appliances over Wi-Fi for $9, using Itead's SONOFF Dual, which can also measure energy consumption. 

Compared with consumer-grade Wi-Fi smart plugs on the market, SONOFF is a great alternative for making smart home and even industrial IoT projects at a larger scale. Moreover, it is based on the popular ESP8266 Wi-Fi chip, making it compatible with the Arduino environment and other resources like our ESP libraries at Ubidots.

Requirements

Hardware Setup

Disassemble the SONOFF Dual device. This is to access the SONOFF TTL pinout, which we'll need to program the onboard ESP8266. The SONOFF comes without two of its pin headers, so you will need to solder them before programming the unit.

After soldering, connect the board to the UartSBee following this table:

UartSBee ---> SONOFF Dual
VCC          ---> VCC
TX             ---> RX
RX             ---> TX
GND          ---> GND

Also, you will need to make a connection between the GND pin of the pin header on the left (the one that contains Button 1 and 0 pins), and the EN_FW pin of the ESP8266, which is shown below:

SONOFF pinout (front facing)

SONOFF Pinout (backward facing)

Arduino IDE Setup

  • In the Arduino IDE, click on Files -> Preferences and enter this URL into the Additional Boards Manager URLs field to be able to access ESP8266's libraries for Arduino:
http://arduino.esp8266.com/stable/package_esp8266com_index.json

 

This field supports multiple URLs. Separate them with commas in case you already have other URLs typed.

  • Open the Boards Manager from Tools -> Board menu and install the ESP8266 platform. 
  • After installation, go to the Tools > Board menu and select the board: Generic ESP8266 Module.
  • Download the UbidotsESPMQTT library as a ZIP file in our GitHub account.
  • Back in your Arduino IDE, click on Sketch -> Include Library -> Add .ZIP Library.
  • Select the ZIP file of UbidotsESPMQTT and then click on “Accept” or “Choose”.
  • Close the Arduino IDE and open it again.

Coding Your SONOFF Dual

This sample code will subscribe to a Ubidots variable that turns on or off both relays at the same time.

Before running the code, go to your Ubidots account, locate the "Devices" tab, and create a Device called "SONOFF Dual" and a variable in it called "Relays". It should look like this:

Make sure the Device API label is "sonoff-dual" and the variable API label is "relays". These are the unique identifiers used by the SONOFF to know to which variable to subscribe in the MQTT broker. You can edit the labels if needed.

You're now ready to flash your device with the following code:

/****************************************
 * Include Libraries
 ****************************************/
#
include "UbidotsESPMQTT.h"

/****************************************
 * Define Constants
 ****************************************/
#
define TOKEN "p4uuxxxxxxxxncTVfoVqxxxxxRQW" // Your Ubidots TOKEN
    #
define WIFINAME "UBIWIFI" //Your SSID
    #
define WIFIPASS "clave123456789ubi" // Your Wifi Pass
    #
define MQTTCLIENTNAME "sonoff15345" // Your MQTT Client Name, it must be unique so we recommend to choose a random ASCCI name

Ubidots client(TOKEN, MQTTCLIENTNAME);

/****************************************
 * Auxiliar Functions
 ****************************************/

void relays_on() {
    Serial.write(0xA0);
    Serial.write(0x04);
    Serial.write(0x03);
    Serial.write(0xA1);
    Serial.flush();
}

void relays_off() {
    Serial.write(0xA0);
    Serial.write(0x04);
    Serial.write(0x00);
    Serial.write(0xA1);
    Serial.flush();
}

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]);
    }
    if ((char) payload[0] == '1') {
        relays_on();
    } else {
        relays_off();
    }
    Serial.println();
}

/****************************************
 * Main Functions
 ****************************************/

void setup() {
    // put your setup code here, to run once:
    Serial.begin(19200);
    Serial.println("Connecting to WiFi...");
    client.wifiConnection(WIFINAME, WIFIPASS);
    client.begin(callback);
    Serial.println("Connected!");
    pinMode(16, OUTPUT);
    client.ubidotsSubscribe("sonoff-dual", "relays"); // Ubidots device and Variable's API Labels
    Serial.println("Subscribed!");
}

void loop() {
    // put your main code here, to run repeatedly:
    if (!client.connected()) {
        client.reconnect();
        client.ubidotsSubscribe("sonoff-dual", "relays"); //Insert the dataSource and Variable's Labels
    }
    client.loop();
}


You can do more elaborate actions by tinkering with the SONOFF Dual internal commands. Here's a quick reference we found in their forums:

Serial:

  19230,8,N,1

Bytes to be sent to the unit:

  0xA0

  0x04

  0xxx

  0xA1

where 0xxx seems to be:

  0x00 both off

  0x01 relay one on

  0x02 relay two on

  0x03 both relays on


After flashing your devices, open up the serial monitor of the Arduino IDE. You should see something like this, meaning the Wi-Fi connection and MQTT subscription were successful:

 

Results

Now go to the "Dashboards" tab and add a new Widget of the type "Control"--> "Switch":

This switch will send a "1" or a "0" to the "Relays" variable, which is then read in the SONOFF's callback function to turn the relays on or off. You can now control your SONOFF Dual remotely from your dashboard!

Build an open IoT platform with Red Hat—keep it flexible with open source software.

Topics:
wi-fi ,mqtt ,home automation ,iot ,tutorial

Published at DZone with permission of Maria Hernandez, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}