The Amazon Alexa took the world by a storm when it was launched as a AI voice service with a programmable "SKILL" feature built into it. Developers have since then created awesome SKILLS to control various IoT objects. I have always wondered what it would take to automate my house with Alexa. That's when i got the opportunity to work with RAK Wireless on their WisCore EVK which has built in support for Alexa void service. This project (though loooonggg) explains the end-to-end setup required to automate home appliances using WisCore and OpenHAB2
In this section we will understand briefly what goes behind the scenes when integrating your devices via Openhab with Alexa void service.
Here is a block diagram explaining the flow:
As you can see, the WisCore board talks to the Alexa voice service for all its operation and the Openhab Skill talks to the Amazon Alexa platform via AWS Lambda hosted functions or our very own HTTPS server. The Openhab skill in turn associates its self to the OpenHAB2 cloud connector service called myopenhab.org where it authenticates itself via OAuth to control devices. The cloud connector connects to the openhab instance running on the raspberry pi. The Openhab Alexa skill tries to collect the information about all the devices from the openhab cloud connector and these devices are shown as Special “Smart devices” to Alexa.
So when you say discover devices Alexa will scan from all available skills that expose devices. In our case the Openhab Skill exposes our MQTT enabled devices as potential smart home appliances. When we tell Alexa to switch off a particular device. It sends a command payload to the skill which in turn send the command payload to the Openhab cloud instance. Openhab then converts these commands as mqtt commands as described in the openhab items file (to be explained in detail in the coming sections)
Pre-requisites:This project takes into consideration that you have a little bit of knowledge with the ESP8266 C based development and some complexities involved with working on cloud based home automation services. But don’t worry, I have outlined the complex step with some of the difficulties I and others from the community have faced while setting up such a system. But hey, it’s the struggle that keeps Makers going right ??
Hardware prerequisites1) WisCore board with the latest firmware (firmware @ https://github.com/RAKWireless/WisCore/tree/master/img)
2) Raspberry pi 3 with the latest Jessie release
3) A ESP8266 based relay system like the Sonoff switches or switches from Electrodragon. I will be concentrating on the switches from electrodragon which have the Sonoff Tasmote firmware loaded onto them. For details on how to burn the checkout the Tasmota wiki page here: https://github.com/arendst/Sonoff-Tasmota/wiki
Software Pre-requisites:I have been working on a windows based system but a linux or a mac system would also do.
- ATOM text editor with the Platform.IO plugin enabled: Intructions to install them is here: http://platformio.org/get-started. Make sure that once installed you also install the ESP8266 toolchain from the platform menu in PlatformIO IDE UI as explained here: http://docs.platformio.org/en/latest/platforms/espressif8266.html
- Make sure that the software on the RPi 3 is upto date with the latest kernel updates as well. To setup wifi on the RPi 3 and to connect to the web follow the instructions here: https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md
- The Sonoff or Electrodragon switches do not have a usb to serial interface built in I used a FTDI bases interface for all my uploading needs. I will add a section in this document on how to flash the firmware on the such switches.
I will divide this document into three parts:
- Setting up you switches using the Tasmota firmware and setting up you preferred MQTT settings.
- Setting up OpenHAB on your RPi 3 and connecting the OpenHAB instance to the cloud
- Finally, setting up you WisCorewiscore to find the switches and control them via Alexa
So Lets Get Started……..
Setting up you switchesAs I cited before, I used the Electrodragon switches for this project. They are relatively inexpensive and are of good quality.
The pic above shows the relay board and its ping configuration.
Notes:
1) BTN2 is your GPIO0 pin which you need to press before powering on the board to enter firmware upgrade mode.
2) To connect the board to FTDI board please connect as shown below:
a. TX of board to RX of FTDI board
b. RX of board to TX of FTDI board
c. 5v of board to 5v of FTDI board
d. GND of board to the GND of the FTDI board
Connect the FTDI board to your computer via a USB2.0 port and windows 7 and above should install the necessary drivers.
Once installed, Go to My Computer - > Device Manager and in The COM Ports section you should see your board given a COM Port like so:
As you can see I get COM 3. Note this port down as it will be used for the upload.
Downloading the firmware for the Relay board:I used the Sonoff Tasmota firmware as it the most recommended firmware for this device providing lots of cool functions via a REST and an MQTT based interface. REST is a web services paradigm aiming to provide a state-ful interface to a service. MQTT is a lightweight messaging protocol aimed at machine to machine communication.
Clone the repository @: https://github.com/arendst/Sonoff-Tasmota.git into your system at convenient place.
Now open the Platform IO software and go to File -> Add Project folder and add the recently downloaded git project root folder. This will shows up on the Platform Io Software like so:
Once loaded. Open the user_config.h file and edit these minimal section:
#define STA_SSID1 "xxxx" // [Ssid1] Wifi SSID
#define STA_PASS1 "xxxx" // [Password1] Wifi password
#define STA_SSID2 "xxx" // [Ssid2] Optional alternate AP Wifi SSID
#define STA_PASS2 “xxx”
Where STA SSID1 and STA SSID2 are two wifi access point SSID names at your premises. You can skip STA2 if you want. And STA-PASS1 and PASS2 are the passwords for the two access points.
Now your ready to fire up the upload process. Click on PlatformIO - > Run Other Target and you will see a small window. Scroll till you see the Option PIO Upload (sonoff)
Before clicking this options make sure you relay board in in “firmware flash” mode. In the electrodragon board, this is easy. Just press the BTN2 on the board while powering on to enter firmware upgrade mode. For sonoff switches the process is defdined here in detail: https://github.com/arendst/Sonoff-Tasmota/wiki/Upload
Once you select the menu, the platformIO command line will trigger and upload to your relay board and after 2-3 minutes your relay board should be ready and connected to your STA-SSID1 AP with the correct password.
Notes:1) If your relay board connects to your SSID you can check the IP of the board via apps Like FING available on board Android and iOS app stores. Once you find the IP of the board (They will come up as Espressif endpoints in the FING app), You can open a webbrowser on your phone or on your desktop and go to the IP. It will show you a screen like so:
- Make sure you change the module type by going to Configuration -> Configure module and select “electrodragon relay” if your board is the one I used. Else select the appropriate sonoff module type.
- If your module doesn’t connect to the network, check the configuration of the SSID and PWD and then flash the firmware again.
These relay modules have a very powerful MQTT based configuration option for controlling the relays via simple MQTT messages. To setup MQTT please choose a suitable MQTT broker. You can setup an MQTT broker on your RPi 3 by following the instruction here: http://www.instructables.com/id/Installing-MQTT-BrokerMosquitto-on-Raspberry-Pi/
Or you can use one of the public mqtt brokers list available here:
https://github.com/mqtt/mqtt.github.io/wiki/public_brokers
Once you determine you mqtt broker of choice, note down their IP/Hostname, the port (usually its 1883) and any username or password required. Now with the IP of the relay board in hand open the browser and open the relay configuration page as shown above and go to Configuration - > Configure MQTT.
Here provide the following:
- In the Host section, enter the hostname/IP of the broker
- In the port, enter the MQTT broker port.
- You can leave client ID as it is
- If you have a username and password for accessing the mqtt broker, enter thenm in the User and Password section./
- Finally, provide a topic name for this board. Each board will listen to messages onthis topic and respong accordingly. For eg if topic is “xxx” then to turn on relay 1 on the board you can send the message “ON” to the topic “cmnd/xxx/POWER1”. For more details on the mqtt commands available checkout the tasmota wiki here: https://github.com/arendst/Sonoff-Tasmota/wiki/Commands
Once done click save. This will restart the device and you can again open the boards IP on a browser. Try switching on the “Toggle X” switches on the web gui to here the relay click.
Notes:- Make sure that your able to see the board connect to an MQTT broker successfully and is responding to your MQTT messages like cmnd/xxxx/POWER1 ON (where xxx is the topic you give as explained before.)
- If not connected, make sure the hostname of the mqtt broker and port are correct and that the credentials you gave are also correct.
- A good mqtt test app is the MyMQTT https://play.google.com/store/apps/details?id=at.tripwire.mqtt.client&hl=en. Using the app connect to the same broker as the relay board and send the test command ON to the topic cmnd/xxxx/POWER1 and see if the relay responds
- For connecting the relay board to mains here is a sample pic. ALWAYS BE CAREFUL WHILE PLAYIGN WITH AC MAIN VOLTAGE AS THEY ARE FATAL WHEN YOU COME IN DIRECT CONTACT. ALWAYS WORK UNDER ADULT SUPERVISION AT ALL TIMES AND IF POSSIBLE A HAVE A TECHNICIAN DO THE CONNECTION FOR YOU.
With this your relay is setup. Now lets move on to OpenHAB.
OpenHAB Setup:What is OpenHAB?OpenHAB is a software for integrating different home automation systems and technologies into one single solution that allows over-arching automation rules and that offers uniform user interfaces.
This means that OpenHAB
- · is designed to be absolutely vendor-neutral as well as hardware/protocol-agnostic
- · can run on any device that is capable of running a JVM (Linux, Mac, Windows)
- · lets you integrate an abundance of different home automation technologies into one
- · has a powerful rule engine to fulfill all your automation needs
- · comes with different web-based UIs as well as native UIs for iOS and Android
- · is fully open source
- · is maintained by a passionate and growing community
- · is easily extensible to integrate with new systems and devices
- · provides APIs for being integrated in other systems
One of the coolest things with OpenHAB is the Alexa integration. That is the meat of this project.
TO get started with Open HAB just follow the instructions here: http://docs.OpenHAB.org/installation/rasppi.html
The steps are fairly straightforward and will get you up and running in no time.
Once installed the OpenHAB portal should be available at the address http://raspberrypi.local:8080
OpenHAB has a number of Ui option ranging from BASIC UI, REST API to Paper UI. Paper UI is coming up to be the defacto admin console for OpenHAB and we will be referring to it often in the sections to follow.
OpenHAB cloud integration and enabling mqttNow that you have OpenHAB, its time for your OpenHAB to talk to your switches via Mqtt. According to the OpenHAB documentation. Each device or Item is an entry in the xxx.items file present inside the /etc/OpenHAB2/items folder on the raspberry pi. A typical item entry will be
itemtype itemname ["labeltext"] [<iconname>] [(group1, group2, ...)] [{bindingconfig}]
This line is self explanatory and more details about each part of the string is explained in details @: https://github.com/OpenHAB/OpenHAB1-addons/wiki/Explanation-of-items
Configuring Mqtt in OpenHAB2We are more interested in the item name and the binding config. Bindings are a way for OpenHAB to connect to the item for sending commands. Binding can be HTTP, MQTT, ZWAVE etc.
In our case we will install the mqtt binding in OpenHAB. Keep in mind that mqtt is OpenHAB 1.x binding and once installed will not show up in the OpenHAB Paper UI. Rather Mqtt will get its own conf file in /etc/OpenHAB2/services/ called mqtt.conf.
For example here is a sample mqtt.conf file:
#
# Define your MQTT broker connections here for use in the MQTT Binding or MQTT
# Persistence bundles. Replace <broker> with an ID you choose.
#
# URL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883
ioteclipse.url=tcp://broker.hivemq.com:1883
# Optional. Client id (max 23 chars) to use when connecting to the broker.
# If not provided a default one is generated.
#ioteclipse.clientId=narekriOpenHAB2
# Optional. User id to authenticate with the broker.
#ioteclipse.user=xxxx
# Optional. Password to authenticate with the broker.
#ioteclipse.pwd=t-xxxx
# Optional. Set the quality of service level for sending messages to this broker.
# Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2
# (Deliver exactly once). Defaults to 0.
ioteclipse.qos=1
# Optional. True or false. Defines if the broker should retain the messages sent to
# it. Defaults to false.
#<broker>.retain=<retain>
# Optional. True or false. Defines if messages are published asynchronously or
# synchronously. Defaults to true.
#<broker>.async=<async>
# Optional. Defines the last will and testament that is sent when this client goes offline
# Format: topic:message:qos:retained <br/>
#<broker>.lwt=<last will definition>
You can use this .cfg file content as it is to connect you instance to a public broker as hivemq
Once you put this content in the mqtt.cfg file save it and restart the OpenHAB2 service but typing:
$> Sudo service OpenHAB2 restart
This should restart the service and mqtt service should start along with OpenHAB.
Adding items to controlNow we need to add an item that will connect with this MQTT binding and let us control it from the internet. To add an item to OpenHAB you have to create a xxx.items file in the /etc/OpenHAB2/items folder. Xxx can be any name you give.
For example here is a sample switches.items file. Here the id of the switch is the second string After the word Switch. So Switch1, Switch2, Switch3 are all ID. They will be used in sitemaps so name them carefully and consistently.
/* Groups */
Group Lab_Switches "Lab Switches" [ "Lighting" ]
Switch Switch1 "Computer Lights" <light> [Lighting] {mqtt=">[ioteclipse:cmnd/xxx/Power1:command:ON:1],>[ioteclipse:cmnd/n$
Switch Switch2 "Computer Fan" <light> [Switchable] {mqtt=">[ioteclipse:cmnd/xxx/Power2:command:ON:1],>[ioteclipse:cmnd/na$
Switch Switch3 "Bedroom Lights" <light> [Lighting] {mqtt=">[ioteclipse:cmnd/xxx/Power1:command:ON:1],>[ioteclipse:cmnd/n$
Switch Switch4 "Bedroom fan" <light> [Switchable] {mqtt=">[ioteclipse:cmnd/xxx/Power2:command:ON:1],>[ioteclipse:cmnd/na$
Note here we have four items in a single file. You can create as many items inside a items file and you can have as many items file in the /etc/OpenHAB2/items folder as you wish. OpenHAB2 will load them dynamically.
In this items file few things are worth to note:
- You need to give tags to the items. Tags means the words inside the [] brackets. Only then will Alexa voice service be able to discover the device.
- The name of the broker config..in this case ioteclipse should be the same as the name you gave in the mqtt.cfg file a few steps back.
- Remember we had talked about the topic cmnd/xxx/POWER1 to power a switch on and off on the relay board. That’s the one that is being denoted in the file as the first info in the binding section of the item string.
Exit this sample to make sure the “xxx” string is replaced by topic name you gave to you relay board “MQTT configure menu”
Showing Items on the UIOnce done. You are ready to show this item to the UI. But wait, not so fast. UI in OpenHAB2 need a definition file called Sitemap. A Sitemap tells how to render a UI for an item. It is very very easy to set a sitemap. Here is a sample sitemaps called default.sitemap file for the switches I mentioned in the switches.items
sitemap default label="My Home"
{
Switch item=Switch1 label="Computer Lights"
Switch item=Switch2 label="Computer Fan"
Switch item=Switch3 label="Bedroom Lights"
Switch item=Switch4 label="Bedroom Fan"
Switch item=TestSwitch1 label="Kitchen Switch"
Switch item=TestSwitch2 label="Bathroom Switch"
Text item=Computer_Room_RSSI label="Computer room WiFi strength"
Text item=Bedroom1_Room_RSSI label="Bedroom One WiFi strength"
Text item=Bedroom1_Room_Humidity label="Bedroom One humidity"
Text item=Bedroom1_Room_Temperature label="Bedroom One temperature"
}
So here is a small breakdown of the sitemap file:
- The first line if the display name for this sitemap. Here is it My Home.
- Each line inside the label is a UI item corresponding to the Items ID specified in the item=”xxx” parameter.
- Label is the test that will be shown in the UI.
- Make sure you set the sitemap you created as the default sitemap but going to OpenHAB2 local website at raspberrypi.local:8080 -> click Basic Ui as shown below an then click configure. In the Popup that comes up, make sure you give the same sitemap file name you created for the section that says “Default Sitemap”
Once you have created a items file and a sitemap file. Restart the OpenHAB2 service again:
$> sudo service OpenHAB2 restart
Once it restarts. Go to the OpenHAB2 webpage but now instead of going to Paper UI, Go to Basic UI. You should be able to see the Switched you create in the Items and Sitemap. Toggle the switches. It should toggle the relay in your relay board.
1) Sometimes the toggle switch may not control the relay board. In such cases make sure that the OpenHAB2 MQTT binding is working properly by seeing the logs at /var/log/OpenHAB2/OpenHAB2.log. The log should not show a connection failure when invoking the mqtt binding. If all is well you should be able to send MQTT messages successfully from the Toggle UI in OpenHAB2
Once this is done. Its time for WisCore to show its magic. But before that we need to setup OpenHAB2 to connect itself to the cloud service called MyOpenHAB.org First we need to install the MyOpenHAB cloud connector plugin and configure it as explained here:
http://docs.OpenHAB.org/addons/io/OpenHABcloud/readme.html
Once done. Login @ myOpenHAB.org site with your credential. You should be able to see you local OpenHAB2 instance now connected to the cloud myOpenHAB2.org site like so below:
You can now click the link that says “Click here to access your OpenHABs dashboard” to quickly access your OpenHAB setup on your raspberry pi in the cloud via secure connection. Neat right ???
Setting up you WisCore to discover these devices:Now lets delve into the world of Amazon Alexa and setup your board to control your home. As part of the setup, Make sure your WisCore board is on the latest firmware release. The release firmware can be found here: https://github.com/RAKWireless/WisCore/tree/master/release
Once updated and synced to the amazon account using the WisCore app as explained here: https://github.com/RAKWireless/WisCore/wiki/WisCore Test your board by asking alexa a question and see if she responds.
Installing the Alexa Openhab SkillNow comes the interesting part. The Alexa service support what Amazon calls Skills. Skills extends the functionality of Alexa to take complex requests and process them. One such Skill is the OpenHAB Skill in the Alexa Smart home index.
Items that you wish to expose to Alexa will need to be tagged to identify what type of device Alexa will see them as. See http://docs.openhab.org/addons/io/homekit/readme.html1.3k for more information. Lighting, switchable and thermostat tags are currently supported (although not limited to those types of items). Thermostat control must use the Homekit style grouping to associate temperature, mode and set point, see the Homekit binding ReadMe above.
Some examples of tagged items are:
Switch KitchenLights "Kitchen Lights" <light> (gKitchen) [ "Lighting" ]
Dimmer BedroomLights "Bedroom Lights" <light> (gBedroom) [ "Lighting" ]
Group gDownstairsThermostat "Downstairs Thermostat" (gFF) ["Thermostat","Fahrenheit"]
Number DownstairsThermostatCurrentTemp "Downstairs Thermostat Current Temperature" (gDownstairsThermostat) [ "CurrentTemperature" ]
Number DownstairsThermostatTargetTemperature "Downstairs Thermostat Target Temperature" (gDownstairsThermostat) [ "TargetTemperature" ]
String DownstairsThermostatHeatingCoolingMode "Downstairs Thermostat Heating/Cooling Mode" (gDownstairsThermostat) [ "homekit:HeatingCoolingMode" ]
You can search for and enable skills in the Alexa app or from the Alexa Skills store on the website. To use an Alexa skill, first enable the skill, and then make your request based on the example phrases shown in the app. If you know the exact name of the skill you want, you can say, "Enable [skill name] skill." Some skills may require you to link to an existing account and a separate subscription in order to use the skill.
Note:For information about setting up or using a smart home skill, go to Connect a Smart Home Device to Alexa.
To enable a skill in the Alexa app:From the Menu, select Skills.
Use the search bar to enter keywords “Openhab” or select Categories to browse through skill categories.
When you see the OpenHAB skill you want to use, select Enable Skill.
To enable skills from the Alexa Skills store on the website, go to https://www.amazon.com/skills.
After you enable a skill, you can ask Alexa to open and use it. For example, say, "Open [skill name]." There may be different or additional instructions for using the skill. You can refer to the skill's detail page to learn more, or say, "[Skill name] help." When you no longer want to use a skill say, "Disable [skill name] skill," or select Disable in the Alexa app.
Notes:Some skills may request access to your device’s address or location. This access will be requested during install, and can be approved/revoked at any time via the Manage Settings button on the relevant skill's page on the Alexa app.
Connect The skill to OpenHABOnce you get the OpenHab Skill, click on the button that requests access to the openhab API.
- This will redirect you to the myopenhab.org account that you created in the first section of this tutorial. Enter you credential.
- The next page after login will ask you if you wish to give the OAUTH cred access to the Alexa Skill. Click yes
- Then you should see that ALexa is now a connected app in your openhab dashboard like so:
Before ordering Alexa to dicsover your home devices, Make sure your able to see your items in the myopenhab.org UI. It should look something likle this under the Items Tab:
If you go this far. Then AWESOMEEEEE. Let the Magic begin. Now Say the words With me
Alexa… Discover Devices !!
And Alexa Should Respond that she has found n number of devices. Once she says that, Tell her to control a light with the Name you gave to the light in the items text file while configuring Openhab on the raspberry Pi 3.
Now you can add more devices to your openhab setup and alexa should be able to discover them Automagically !! Look out for more such Tutorials using the Wiscore Module.
Comments