Introduction: Home Automation With Amazon Echo Voice Control

Last month, Amazon released the Echo - a small cylinder capable of powerful voice recognition.

The Echo itself is closed source. But once you figure out the Echo's secrets, it becomes an incredibly powerful tool for voice control, enabling you to control anything in your home or apartment via voice without having to worry about the complexities of the human voice. (see: how to do voice control pre-Echo - hint: it's MUCH harder)

In this Instructable, I'll cover how to use the Amazon Echo to control any device via wifi or MQTT.

All you need is:

  1. An Amazon Echo that's set up with Amazon's instructions
  2. A Raspberry Pi or other computer running Linux
  3. The starter code

Difficulty: You'll need to know a little bit of Python programming to understand the examples.

Time required: 10 - 30 minutes from unboxing to Alexa.

Note: This Instructable is currently Linux-only. Let us know if you'd like it on other platforms - if there's enough interest, we'll look into it!

Step 1: Set Up Your Server

With your Echo up and running, let's talk hacking and home automation.

Specifically, we're about to create a server that pretends to be a WeMo device.

The Echo integrates with the WeMo home automation protocol - simply say "Alexa, discover my devices" and it'll search the local network for WeMo devices. So let's give it a device to discover!

1. Install the requirements: Python 2.7, pip and required Python modules

sudo apt-get install python-pip ; sudo pip install requests

2. Download a zip of the code from the GitHub repo

wget "https://github.com/toddmedema/echo/archive/master.zip"

3. Extract the zip file

unzip master.zip -d echo

4. Move to the newly created echo folder

cd echo/echo-master

5. Start the server - you should see some debugging text indicating the server has started polling.

python example-minimal.py

6. Say to your Echo "Alexa: discover my devices". She'll take a few seconds to find the new device. If she doesn't find it the first time, try killing and restarting the process and discovering devices again.

7. Now try it out! Say, "Alexa: turn off device", or "Alexa, device on". You'll see True or False for on/off, along with the Echo's IP address.


Footnote:

The Echo can also send commands via the Amazon cloud, using their new service called Lambda. This is a convenient way to get started with the Echo, but not great for home automation. It requires that every command include the name of the program, ie "Alexa, ask HOME to turn on the lights", and it also involves a network round trip to distant servers, which slows down the response time.

What we really want is to control local devices locally, without the prefix - ie "Alexa, turn on the lights" - which is why I'm using the WeMo protocol.

Step 2: Control EVERYTHING!

That's all there is to it. You now have a server connected to your Amazon Echo. You can now use your voice to:

  • Control the lights, air conditioner, even your TV!
  • Run scripts on your computer
  • Toggle entire home automation modes ("movie mode", "party mode", etc)
  • Prank your roommates
  • Save power by making it easier to turn off devices you aren't using

We've set up our apartment to run an Echo in each room, controlling all of our home automation devices via the maker-friendly MQTT protocol.

Read on to learn about MQTT and how to use multiple Echos.

Step 3: (bonus) Using MQTT to Control Devices

MQTT makes controlling home automation devices a breeze using a "publisher-subscriber" or "pub-sub" framework. With pub-sub, you publish messages to topics, and any devices listening on those topics receive those messages. So, for example, you could have a topic bedroom-lights and publish "1" or "0" to turn the lights on or off.

Here's how to use the code I wrote to connect the Amazon Echo to MQTT:

  1. Use pip to install MQTT by opening up a command window and typing: pip install paho-mqtt
  2. You can now run the test MQTT file with python fauxmo_mqtt_example.py
  3. Open up a web browser and browse to the HiveMQ MQTT Websocket Client
  4. Click "Connect".
  5. Click "Add New Topic Subscription". Type "livingroom" in place of "testtopic/#" and hit Subscribe.
  6. Say "Alexa, turn on the lights"
  7. You should see a "True" message posted to the topic!

I'll leave it as an exercise to discover the other topics the example code uses.

Disclaimer: The example code uses a public MQTT server to get you up and running as fast as possible, so don't go publishing your Social Security Number to a test topic!

Step 4: (bonus) Using Multiple Echos & Dealing With Echoes

If you've fallen in love with your newfound Echo powers, you might be interested in using more than one Echo. You'll run into two issues doing so - and here are the solutions for both:

Knowing where the Echo is. You don't want the bedroom Echo to turn on the kitchen lights, but these things don't exactly have GPS built in. Instead, you can use the IP address of each Echo to offer it a different set of commands and controls.

Check out fauxmo_mqtt_example.py for one solution to this. I recorded the IP address seen when I ran fauxmo_minimal.py and kept it as a constant. Then whenever I want different echos to have different responses to the same command, I compare the IP against client_address in the handler's act() function.

Echoes from other Echos. The microphones on the Echo are so sensitive that they'll often pick you up from a room away - even with music playing! While incredibly convenient, it also becomes a problem when you have multiple Echos around the house.

To solve this, I added a "debounce" function to the code (see debounce_handler.py) that prevents the same command from being called multiple times in quick succession. So, if the bedroom AND kitchen Echos hear you, only the first one to submit the command will execute. Whichever Echo hears you loudest & is closest to you processes the message faster, submits the network request faster, and has its request processed - while all the Echos that hear quieter echoes take longer to process and get debounced. Voila! The debounce function is built in, so there's actually nothing extra you need to do here - it works out of the box.

Step 5: That's All, Folks!

You now have the skills to control any device in your home with your voice using the Amazon Echo. Go make incredible things!

If you like this Instructable, don't forget to favorite it and follow us on Facebook

Inspired by @MakerMusings' fauxmo control framework.

Comments

author
Honkoponko (author)2017-08-30

Hello

Does your software work with more than 16 devices?(as original fauxmo I think is up to 16 even though on Alexa forum they say you can discover over 100 wemo devices)

I`m looking for a solution that depending on alexa voice command will run a script on Raspberry Pi. However I need way more commands then 16. Could you recommend something for this?

If possible I prefer option without going through alexa learning skills (to avoid longer command like : allexa tell device to turn 'script' on...)

author
RudiRatlos63 (author)2017-08-28

Hi,

got it working. Is it possible to use more options/args than turnoff of turnon?

author
gary.reardon2 (author)2017-08-02

This is cool and all but is this different than just using a smart plug or the Harmony Hub?

author
GavinG5 (author)2017-06-20

I have gotten the script to work but I want it to exacted a script I made that will send power on packets to my Xbox one. How can I make this happen? I've tried putting in the script name after it prints the echos ip, but this returns errors. Executing the power on script by itself works and turns the Xbox one on. I just need this to exabyte after telling echo to turn it on. Thanks in advance!

author
GeorgeS182 (author)2017-05-29

Has anyone found the "python fauxmo_mqtt_example.py" script ?

author
kevstone122 (author)2017-04-21

Hello!
In step 3 is written we should start "python fauxmo_mqtt_example.py", but where is the script? After this i should start the HiveMQ MQTT Websocket Client page, but this page has some weblink, how should this site connect to my raspberry. I don't know what i need to do, to get more Alexa's working!

The step1 one is totally working i also can switch on around 10 devices, but the ip address isn't everytime correct. I don't know. Sometimes from this User and sometimes from the other!

LG

Please can you help me.

author
lazerdave (author)2017-03-11

Hi, Kevin! I'm also looking to execute an existing python script. The response to Geomi doesn't seem to specifically answer this question.

My specific need is that I have a ceiling fan that has 4 settings, each controlled by a separate .py script. If I say "fan low" it should run fanlow.py. If I say "fan off" it should run fanoff.py. Et cetera.

Any tips on that?

author
kevstone122 (author)lazerdave2017-04-21

Hello. Sorry for my late response, but i was busy. Is the problem still actual?

author
5teeler (author)2017-04-09

First off, thanks for the code. Got it installed and working... well mostly. I have 4 echoes (2 full size and 2 dots) and the problem is that the identified client address seems to randomly be one of the 4 IP echo addresses (in my home network). I am not consistently getting a specific IP address for a given echo. Also, this is not an issue with multiple echoes picking up the voice command - they are all acoustically separated. I have a feeling that when a command is received by one echo via voice, it gets processed in the could and the response from the cloud is sent back to one of the echoes within the same LAN which then forwards the command to the fauxmo. If that is the case I guess nothing can be done within the fauxmo code to fix this problem.

author
kevstone122 (author)5teeler2017-04-21

I have exactly the same problem. I used the starter code and extend it with tip address in the functions. So i want to say "Alexa, turn the light on" and if i am in the living room i mean this light and if i am in the bedroom i mean this light. But the ip address isn't correct. sometimes from this dot and sometimes from the other dot. If i disconnect once of both, the ip adress will be correct....Sure only one device is online!

author
kevstone122 (author)kevstone1222017-04-21

Any ideas for this problem?

author
Goemi (author)2017-02-28

exactly what I searched for!

I just want to execute a sudo command to execute a python script "device-on.py" or "device-off.py".

How can I acchieve that? I really dont know.

author
kevstone122 (author)Goemi2017-03-04

Please read the comments below!

I write it her "kevstone122 -->NathanG99"
Total instruction!

Best regards

Kevin

author
hihionio (author)kevstone1222017-03-21

Kannst du mir bitte ein Skript erstellen mit dem ich mehrere GPIO Pins über Alexa steuern kann denn der den du an Nathan geschrieben hast funktioniert irgendwie nicht und ausserdem versteh ich ih nicht xD danke LG Nico

PS: Wenn du willst kannst du mich über Eamil anschreiben: hihionio.mail@gmail.com

author
kevstone122 (author)hihionio2017-04-21

Hallo. Tut mir leid für die späte Antwort. Hatte kaum Zeit mehr dafür.
Ist das Problem noch aktuell?
Ich werde beides machen. Dir eine email schreiben, damit du direkt das Python file hast und ebenso hier posten, damit andere Leute etwas davon haben die sich noch dafür interessieren:

""" fauxmo_minimal.py - Fabricate.IO

This is a demo python file showing what can be done with the debounce_handler.

The handler prints True when you say "Alexa, device on" and False when you say

"Alexa, device off".

If you have two or more Echos, it only handles the one that hears you more clearly.

You can have an Echo per room and not worry about your handlers triggering for

those other rooms.

The IP of the triggering Echo is also passed into the act() function, so you can

do different things based on which Echo triggered the handler.

"""

########################################################################################

"""KESJI-HOME-AUTOMATISATION script!

Das ist ein script von Kevin Steindl und mehrere Lampen auf einem einzigen Raspberry

simulieren zu koennen. Software Funktionen wie Trigger, ON und OFF wurden ebenfalls

ergaenzt.

Es koennen unbeschraenkt Geraete definiert werden die alexa nachher auch findet und

schalten kann.

"""

########################################################################################

import fauxmo

import logging

import time

import RPi.GPIO as GPIO

import urllib

import sys #Eventuell fuer Logfile notwendig

#Log File Pfad

logfile = '/home/kevin/Spracherkennung-Logfile.log'

hilfe = 0

Clientname = {"leer"}

zaehler = 0

#Weblinks:

ArduinoON = 'http://10.0.1.12/?1=EIN'

ArduinoOFF = 'http://10.0.1.12/?1=AUS'

#GPIO warnings deaktivieren!

GPIO.setwarnings(False)

#GPIO's zuerst alle einmal als Ausgang definieren

GPIO.setmode(GPIO.BCM)

GPIO.setup(2,GPIO.OUT)

GPIO.setup(3,GPIO.OUT)

GPIO.setup(4,GPIO.OUT)

GPIO.setup(5,GPIO.OUT)

GPIO.setup(6,GPIO.OUT)

GPIO.setup(7,GPIO.OUT)

GPIO.setup(8,GPIO.OUT)

GPIO.setup(9,GPIO.OUT)

GPIO.setup(10,GPIO.OUT)

GPIO.setup(11,GPIO.OUT)

GPIO.setup(12,GPIO.OUT)

GPIO.setup(13,GPIO.OUT)

GPIO.setup(14,GPIO.OUT)

GPIO.setup(15,GPIO.OUT)

GPIO.setup(16,GPIO.OUT)

GPIO.setup(17,GPIO.OUT)

GPIO.setup(18,GPIO.OUT)

GPIO.setup(19,GPIO.OUT)

GPIO.setup(20,GPIO.OUT)

GPIO.setup(21,GPIO.OUT)

GPIO.setup(22,GPIO.OUT)

GPIO.setup(23,GPIO.OUT)

GPIO.setup(24,GPIO.OUT)

GPIO.setup(25,GPIO.OUT)

GPIO.setup(26,GPIO.OUT)

GPIO.setup(27,GPIO.OUT)

#GPIO Ausgange zuerst alle einmal ausschalten (True beddeutet bei der Relais Platine OFF)

GPIO.output(2,True)

GPIO.output(3,True)

GPIO.output(4,True)

GPIO.output(5,True)

GPIO.output(6,True)

GPIO.output(7,True)

GPIO.output(8,True)

GPIO.output(9,True)

GPIO.output(10,True)

GPIO.output(11,True)

GPIO.output(12,True)

GPIO.output(13,True)

GPIO.output(14,True)

GPIO.output(15,True)

GPIO.output(16,True)

GPIO.output(17,True)

GPIO.output(18,True)

GPIO.output(19,True)

GPIO.output(20,True)

GPIO.output(21,True)

GPIO.output(22,True)

GPIO.output(23,True)

GPIO.output(24,True)

GPIO.output(25,True)

GPIO.output(26,True)

GPIO.output(27,True)

#######################################################################

###################Unterprogramme definieren hier######################

#######################################################################

#Trigger Funktion um eine gewisse Zeit eine 1 zu senden!

def Trigger(Portnumber,Triggertime):

GPIO.output(Portnumber,False)

print "Output", Portnumber,"eingeschalten"

time.sleep(Triggertime)

print "Output", Portnumber,"ausgeschalten"

GPIO.output(Portnumber,True)

#Einmaliges Einschalten

def ON(Portnumber):

GPIO.output(Portnumber,False)

print "Output",Portnumber,"eingeschalten"

#Einmaliges Ausschalten

def OFF(Portnumber):

GPIO.output(Portnumber,True)

print "Output", Portnumber, "ausgeschalten"

# function to save log messages to specified log file

def log(msg):

# open the specified log file

file = open(logfile,"a")

# write log message with timestamp to log file

file.write("%s: %s\n" % (time.strftime("%d.%m.%Y %H:%M:%S"), msg))

# close log file

file.close

#############Hauptprogramm start#########################################

log("#######################Raspberry mit Wemo Client Software wurde gestartet##############################")

from debounce_handler import debounce_handler

logging.basicConfig(level=logging.DEBUG)

class device_handler(debounce_handler):

"""Publishes the on/off state requested,

and the IP address of the Echo making the request.

"""

#Alle verfuegbaren Geraete hier definieren

TRIGGERS = {"Licht": 52000,

"Jalousine": 52001,

"Romantik": 52002,

"Normal": 52003,

"Party": 52004,

"Vorgarten": 52005,

"Kueche Licht": 52006}

log("Alle Geraete initialisiert")

#Diese 4 Dinge werden nach der Erkennung zurueckgemeldet:

#self: Als ich es mit print getestet habe bekam ich diesen Text hinaus: <__main__.device_handler object at 0x76516bf0>

#client_adress: IP Adresse von dem ECHO oder ECHODOT der es gesendet hat

#State: Erkannter Status der von der Stimme erkannt wurde. True oder False

#Name: Der name der erkannt wurde. Muss ein Name von der "TRIGGERS" Liste sein!

def act(self, client_address, state, name):

#Erzeuge Client Name

if client_address == "10.0.1.184":

client_address = "1"

Clientname = "Amazon Dot - Wohnzimmer"

elif client_address == "10.0.1.43":

client_address = "2"

Clientname = "Amazon Echo - Schlafzimmer"

#Schalte Funktion je nach erkanntem Wort

#Geraet 1

if client_address == "1" #Amazon Dot - Wohnzimmer

if name == "Licht":

print "Das Licht im Wohnzimmer ist:", state, "-->Gesendet von", Clientname, ":", client_address

# create new log message

log("Licht im Wohnzimmer Trigger gesendet")

hilfe=1

Trigger(14,0.5)

if name == "Jalousine":

print "Jalousine im Wohnzimmer ist:", state, "-->Gesendet von", Clientname, ":", client_address

log("Jalousine im Wohnzimmer Trigger gesendet")

hilfe=1

Trigger(15,0.5)

#Geraet 2

if client_address == "2" #Amazon Dot - Wohnzimmer

if name == "Licht":

print "Das Licht im Schlafzimmer ist:", state, "-->Gesendet von", Clientname, ":", client_address

# create new log message

log("Licht im Schlafzimmer Trigger gesendet")

hilfe=1

Trigger(2,0.5)

if name == "Jalousine":

print "Jalousine im Schlafzimmer ist:", state, "-->Gesendet von", Clientname, ":", client_address

log("Jalousine im Schlafzimmer Trigger gesendet")

hilfe=1

Trigger(3,0.5)

if name == "Vorgarten":

print "Der Vorgarten ist:", state, "-->Gesendet von", Clientname, ":", client_address

if state == 1:

log("Vorgarten wurde eingeschalten")

content = urllib.urlopen(ArduinoON).read()

elif state == 0:

log("Vorgarten wurde ausgeschalten")

content = urllib.urlopen(ArduinoOFF).read()

hilfe=1

if name == "Kueche Licht":

print "Die Kueche ist:", state, "-->Gesendet von", Clientname, ":", client_address

hilfe=1

if GPIO.input(18) == 1:

ON(18)

log("Kueche wurde eingeschalten")

else:

OFF(18)

log("Kueche wurde ausgeschalten")

if hilfe == 0:

print "Fehler nicht verstanden"

hilfe = 0

return True

if __name__ == "__main__":

# Startup the fauxmo server

fauxmo.DEBUG = True

p = fauxmo.poller()

u = fauxmo.upnp_broadcast_responder()

u.init_socket()

p.add(u)

# Register the device callback as a fauxmo handler

d = device_handler()

for trig, port in d.TRIGGERS.items():

fauxmo.fauxmo(trig, u, p, None, port, d)

# Loop and poll for incoming Echo requests

logging.debug("Entering fauxmo polling loop")

while True:

try: # Allow time for a ctrl-c to stop the process

if (zaehler <= 100):

zaehler = zaehler + 1

else:

zaehler = 0

p.poll(50) #Standard lWert liegt bei 100

time.sleep(0.05) #Standard Wert liegt bei 0.1

print "Warte auf Spracheingabe: ", zaehler

except Exception, e:

logging.critical("Critical exception: " + str(e))

break

author
DosK (author)2017-04-17

Thank you for your ideas!
With a little change it is working. I only use 1 Echo, and I use a local mqtt on the pi, so i had to change the ip. in line 32 there ist the mqtt publishing for different devices.

#!/usr/bin/env python

import subprocess

import paho.mqtt.client as mqtt

import fauxmo

from debounce_handler import debounce_handler

import threading

import logging

import time

logging.basicConfig(level=logging.DEBUG)

# ---------- Network constants -----------

ECHO_LIVINGROOM = "192.168.1.53"

ECHO_KITCHEN = "192.168.1.243"

MQTT_HOST = "localhost" #jarvis

MQTT_PORT = 1883

# ---------- Device callback functions ----------

class light_handler(debounce_handler):

"""Publishes state to two different lighting MQTT topics

depending on which Echo the request came from.

"""

#TRIGGERS = {"device": 52000}

#{"lights": 52002, "lamp": 52003}

def __init__(self, mqtt):

debounce_handler.__init__(self)

self.mqtt = mqtt

"""Publishes the on/off state requested,

and the IP address of the Echo making the request.

"""

TRIGGERS = {"device": 52000,"lights": 52002, "lamp": 52003}

def act(self, client_address, state, name):

print "State", state, "on ", name, "from client @", client_address

if name == "device":

self.mqtt.publish("device", state)

else:

self.mqtt.publish("whatever", state)

return True

if __name__ == "__main__":

# Startup the MQTT client in a separate thread

client = mqtt.Client()

client.connect(MQTT_HOST, MQTT_PORT, 60)

ct = threading.Thread(target=client.loop_forever)

ct.daemon = True

ct.start()

# Startup the fauxmo server

fauxmo.DEBUG = True

p = fauxmo.poller()

u = fauxmo.upnp_broadcast_responder()

u.init_socket()

p.add(u)

# Register each device callback as a fauxmo handler

h = light_handler(client)

for trig, port in h.TRIGGERS.items():

fauxmo.fauxmo(trig, u, p, None, port, h)

# Loop and poll for incoming Echo requests

logging.debug("Entering fauxmo polling loop")

while True:

try:

# Allow time for a ctrl-c to stop the process

p.poll(100)

time.sleep(0.1)

except Exception, e:

logging.critical("Critical exception: " + str(e))

break

author
mtneco48 (author)2017-04-10

Thank you for your code and this article, both were very helpful! I have the first part working with my Alexa Echo Dot turning on my Raspberry Pi device, but now I want to move onto using Alexa with MQTT control as your Step 3(bonus) outlines. I have installed paho-mqtt on my RPi, but can not find the file fauxmo_mqtt_example.py to execute the MQTT test file. Where is this file? I try to execute "python fauxmo_mqtt_example.py" and I get an error telling me the file does not exist? Did I neglect to do something , or load the paho-mqtt improperly?

I would appreciate any help someone could give me on this to resolve this issue.

Thanks,

Matt

author
benni1 (author)2017-04-03

Nice!

Thank you so much!

You really Helped me!!!

It works so well!!

me!!!

author
MichaelB989 (author)2017-03-27

Fantastic stuff, exactly what I've been looking for but I would also like to "know" how lamda works. Wouldnt happen to have any tutorials for dummies would you?

Thanks much!

author
TinP4 (author)2017-03-27

When I ask Alexa to discover devices I immediately get following response: "Discovery is complete. I couldn't find any smarthome devices."

Is this because I am running Alexa on a Raspberry Pi 2? Or maybe due to the fact that I live in Austria?

author
RIchardHP (author)2017-03-15

Many thanks for this - I found it excellent. As a newbie to both the Pi and to Python I managed to get it working relatively and executing a separate Python script for switching lights on and off.

What I'm struggling with is how I can add a level of granularity to turn specific lights or rooms on or off (similar challenge to LazerDave below). My light control program takes arguments for which room and what action. Any pointers or examples you can give that would help undestand how to get commands or arguments from Alex to become arguments to my executing Python program, would be much appreciated,

Many thanks

author
lazerdave (author)RIchardHP2017-03-16

Would you be willing to share your code, please, RichardHP?

author
RIchardHP (author)lazerdave2017-03-16

Sent you details LazerDave

author
JonathanW180 (author)2017-03-03

he tanks for this tutorial!!

But how can i start now an python programm on my raspi via voice control?

and how can i make that my rpi makes pin 22 on , when i say for example " make device on" ??

kind regards

author
kevstone122 (author)JonathanW1802017-03-04

Please read the comments below!
I write it her "kevstone122 -->NathanG99"
Total instruction!

Best regards

Kevin

author
PradeepK151 (author)2017-03-01

I got my new echo and installed windows linux bash on ubuntu on windows. And followed all the steps. It is Responding to search for tv when i ask alexa to discover devices and there after alexa is not able to find the virtual device. There are no exceptions in the debug.

Configuration:

Amazon Echo Dot 2nd Generation

Linux on ubuntu on windows

wifi

author
GaryG16 (author)2016-08-21

Very well done. I am new to Pi and Python - but have made good use of this. It is possible to add more than one device in the TRIGGERS list. Echo sees the devices and responds to the commands (unique port number) Only issue is that the response, act(self, client_address, state) does not return the port. Not sure where the code for this is? Would it be possible add the port number in the response? I am using the response to send data to an Arduino port to control X10, etc. Thank you - and well done.

author
breagan22 (author)GaryG162016-12-04

bump....

author
breagan22 (author)breagan222016-12-04

I find this very interesting. I have two Echo Dots. One has the microphones muted. When I run this script, the "client_address" for both Dots is returned.

192.168.11.25 is muted and in another part of the house.

DEBUG:root:Responding to ON for lamp
DEBUG:root:client_address 192.168.11.25
Published to kitchen
DEBUG:root:Responding to ON for lights
DEBUG:root:client_address 192.168.11.11
Published to kitchen
DEBUG:root:Respondings to OFF for lights
DEBUG:root:client_address 192.168.11.11
Published to kitchen
DEBUG:root:Respondings to OFF for lamp
DEBUG:root:client_address 192.168.11.25
Published to kitchen

author
kevstone122 (author)breagan222017-02-22

Hello!

I have the same problem. I post it now again on the top. Do you find an solution already?

It doesn't matter with which i speak, i get sometimes this ip adress as feedback from the function and sometimes the other ip adress.
This function does not correctly work!

Thank you for your help!

Best regards

Kevin

author
breagan22 (author)breagan222016-12-04

I did manage to get it to return the 'name' or 'port' by changing lines 226 and 230 in fauxmo.py to:
success = self.action_handler.off(self.name)

or

success = self.action_handler.off(self.port)

Now example-mqtt.py returns the name or port as 'client_address' in the act()

Off to the races!

author
Ian Davies (author)breagan222016-12-28

Many thanks breagan22, this was just what I needed as well - thanks very much for solving and sharing this.

author
Ian Davies (author)Ian Davies2017-01-17

Hi breagan22, looks like the author has updated the code, and now your nice little mod isn't needed anymore, as the code now includes the 'name' parameter which returns the name of the device being turned on/off. But I still thank you for your mod - it helped me at the time !

author

Thank you so much. I registered to reply just for you!

author
kevstone122 (author)2017-02-22

Hello all together!

I have an important question:

After the line "def act(self, client_address, state, name):" i should get back the client_adress (ip adress) of the Echo which hears the sound.
So now i buy the Echo and also the Echo dot. Both of them have different IP adress, but the client_adress is sometimes this and sometimes the other one.

The two Echos are in different levels in the house and so they don't here each other. The feedback of the client adress is not always correct.
Has somebody the same problem?
I want to add some general functions like "light", "Szene" and "Sound" and automatically with the command "light on" the light in the room where the Echo is placed goes on. If i go in another room and say "light on" it will also switch on the correct room because i know the IP adress of this room/echo.

But this doesn't work. Has somebody an idea why this feedback is not working correct? If I switch off one off both immediatelly it will work correct and the room for this IP adress get controlled.
If both are online it is sometimes this ip adress and somethimes the other adress when i always speak with the same Echo.

Thank you!
Best regards
Kevin

author
Ian Davies (author)2017-01-17

Hi, I have this working - and really appreciate you sharing this. But I want to make sure the python code gets started after a reboot of the Pi, so I tried adding to crontab with the @boot command, but the python script fails. The same script work fine at the command line, and if I put it to background, but fails when invoked from cron:

crontab entry

@reboot /usr/bin/python /home/pi/data/sunset/echo-master/alexa1.py >> /home/pi/data/sunset/cronlog.txt 2>&1

error from cronlog.txt:

Traceback (most recent call last):
File "/home/pi/data/sunset/echo-master/alexa1.py", line 68, in <module>
u.init_socket()
File "/home/pi/data/sunset/echo-master/fauxmo.py", line 300, in init_socket
dbg("Failed to initialize UPnP sockets:",e)
TypeError: dbg() takes exactly 1 argument (2 given)

Any ideas?

author
kevstone122 (author)Ian Davies2017-02-22

I do it in an easy way and it is working without any problems. Immediatelly after booting the relais are ready to switch on or off:

I just add this script here with: (USERNAME change to you user=

nano /home/USERNAMER/.config/autostart/Echo.desktop

Then copy this lines inside:
[Desktop Entry]

Type=Application

Name=Run-echo-script

Exec=./Run-echo-script

StartupNotify=false

Save it with STRG+O
Close it with STRG+X

The file Run-echo-script is in the folder /home/USERNAME/

Inside I do the python script:

#!/bin/sh

#Rim-echo-script

#Startet das ECHO script

sudo python /home/kevin/echo/echo-master/example-minimal.py

I do it this way because now i am able to write an # before this start command and after the next reboot it will not start automatically.

Best regards
Kevin

author
bruster999 (author)Ian Davies2017-01-24

I had the same problem and ended up putting the startup script in /etc/rc.local but I had to put a short sleep in before launching it for some reason. It would not launch without the sleep:

sleep 5

/home/pi/scripts/launch_example-minimal.py &

author
Ian Davies (author)bruster9992017-01-25

Success ! I didn't need to move it to rc.local, but your idea of the sleep seemed to help ! I am using an older Pi Model B, so I went for 25 seconds sleep, and I am sure if I tested, I could find a lower interval, but I will probably leave it at 25. The other change I made was to go back to launching the wemo launcher script from cron which then calls the python script:

cron entry:

@reboot /home/pi/data/sunset/wemo_launcher.sh >> /home/pi/data/sunset/cronlog.txt 2>&1 &

wemo_launcher.sh

#!/bin/sh
# wemo_launcher.sh
# navigate to home directory, then to this directory, then execute python script, then back home
sleep 25
cd /
cd /home/pi/data/sunset/echo-master
python alexa1.py &
cd /

I don't know if the navigating back and forth is required, but it was in the original wemo script, and it works, so I will probably leave it alone now ;-)

Thanks for the help bruster999

author
bruster999 (author)Ian Davies2017-01-26

Probably using an absolute path would do the same as changing dirs but whatever works right? LOL. I'm glad you got it working. :-)

author
mayhemxtc (author)Ian Davies2017-01-18

Try this:

@reboot nohup /usr/bin/python /home/pi/data/sunset/echo-master/alexa1.py >> /home/pi/data/sunset/cronlog.txt 2>&1 &

author
Ian Davies (author)mayhemxtc2017-01-18

Thanks for the suggestion, but it still failed exactly the same way. Any other ideas ?

author
thomasfromla (author)2017-02-03

I don't know Linux. Can you translate this to Windows 7?

author
kevstone122 (author)thomasfromla2017-02-22

Hello. I think this software is special for Linux. Best way is raspberry.

What you want to do with windows. After you get the command, how you want to switch on some lights? You habe no digital outputs!?

Raspberry costs around 60€ with all stuff you need and that's it!


Best regards

Kevin

author
NathanG99 (author)2017-02-18

hello, how do you get GPIO working?

author
kevstone122 (author)NathanG992017-02-22

Hello NathanG99!

you need to change the file "echo/echo-master/example-minimal.py"

On the top add:
import RPi.GPIO as GPIO

Then set the Pin to the Output mode: Output numbers you find in google
GPIO.setmode(GPIO.BCM)

GPIO.setup(2,GPIO.OUT)

GPIO.setup(3,GPIO.OUT)

GPIO.setup(4,GPIO.OUT) and so on!

Then set all Outputs to off (I have the amazon 8-Relais board and there is the logic opposite. So true is off:
GPIO.output(2,True)

GPIO.output(3,True)

GPIO.output(4,True) and so on

After this i add 3 Funktions:
1) Trigger

def Trigger(Portnumber,Triggertime):

GPIO.output(Portnumber,False)

print "Output", Portnumber,"eingeschalten"

time.sleep(Triggertime)

print "Output", Portnumber,"ausgeschalten"

GPIO.output(Portnumber,True)

2) Switch on once

def ON(Portnumber):

GPIO.output(Portnumber,False)

print "Output",Portnumber,"eingeschalten"

3) Switch off once

def OFF(Portnumber):

GPIO.output(Portnumber,True)

print "Output", Portnumber, "ausgeschalten"

after this line:

def act(self, client_address, state, name):

you get back the name of your device. Start Trigger with this:

if name == "YOUR DEVICE":

print "Das YOUR DEVICE ist:", state, "-->Gesendet von Amazon Echo Dot", Clientname, ":", client_address

Trigger(2,0.5)

Here the Pin two switch on for 0,5 seconds and after this off again!

Best regards
Kevin

(sorry I am from austria and so some text is german!)

author
bruster999 (author)2017-02-10

Thanks so much for this great instructible. I have used your knowledge to create several ESP8266/mqtt based control nodes around my house based off one PiZero. One of the nodes is a motorized blinds control. The command to turn a light on is "Alexa, turn _____ lights on/off" but that's not intuitive for controlling blinds. For the blinds control I have to say "Alexa, turn _____ blinds on/off". Not very natural sounding. Is there a way to change/add control wording so that I can give the command "Alexa, open/close _____ blinds".

Thanks again.

author
moonchaser (author)2017-01-20

how can i change devise on to some other name

author
bruster999 (author)moonchaser2017-01-24

Edit ~/echo/echo-master/example-minimal.py

Change the text in quotes:

TRIGGERS = {"device": 52000}

to whatever you want. I used the following and it worked great

TRIGGERS = {"living room lights": 52000}

author
RevJ1 (author)2017-01-05

ok. I have alexa-pi running fine on my pi-3.

seemed to get the code here running fine. But alexa fails to find any devices.

there are no errors. I can only assume scanning for devices fails to scan localhost :)

any clues?

ta

About This Instructable

144,269views

482favorites

License:

More by FabricateIO:Home Automation with Amazon Echo voice controlCheap Arduino Controlled Light Sockets - Reverse Engineering RFEye-Glowing Robotic Skull
Add instructable to: