Project tutorial
Arduino Home Controller Activated by Alexa

Arduino Home Controller Activated by Alexa © GPL3+

With Arduino Home Controller and Amazon Echo dot with Alexa you can handle internet connected devices at home using your voice.

  • 6,226 views
  • 8 comments
  • 13 respects

Components and supplies

Necessary tools and machines

09507 01
Soldering iron (generic)

Apps and online services

About this project

Overview

When Amazon launch to market Alexa and devices like Amazon Echo Dot open an infinity number of options to make a great Smart Home controlled by voice commands using a natural language.

This project makes an Arduino Home Controller that can connect a lot of sensors and devices to internet and you can control them using an Amazon Alexa skill.

You can install and enable my skill "Arduino Home Controller" the easy step, or you can make your skill guided by this tutorial.

For now we will control :

  • Four lights in room, garage, kitchen and living room.
  • Temperature and Humidity sensor.
  • Buzzer alarm.
  • WebCam to take security photo and send by email.

You can see Arduino Home Controller in action in this short video demo. For demo and video propose I use four leds in prothoboard simulating light bulbs in each house rooms.

If you want use remote modules to activated your lights you can view my Arduino Home Controller Remote Modules project at this URL.

Arduino Home Controller in Action

Block Diagram

In the block diagram picture we can see the four main components of this project:

1.- Amazon Echo Dot to receive voice commands and send it to AWS (Amazon Web Service).

2.- AWS with an Amazon Skill and a Lambda Function to interpret all commands.

The skill name is "Arduino Home Controller" you can activated it later.

3.- An MQTT Broker using PubNub(c) cloud.

This broker will receive the control messages in two channels, one for set values and another to read values from sensors.

You do not need to create an account in PubNub you can use my account for demo proposes.

4.- Home Controller using Arduino Yun.

We will use Arduino Yun because it have ethernet shield inside and have a small linux machine where we will execute python for handle some actions.

It controls relays for lights, read temperature and humidity sensor, turn on buzzer for alarm and manipulate a webcam to take security photo.

For remote modules, see my complementary, Arduino Home Controller Remote Modules project at this URL.

Install all software needed

At this point you can take two options one for demo propose, use my Alexa skill install it and use it or option two you can made you personal skill.

Option One - Using my Skill "Arduino Home Controller"

Browse Alexa app with this url, at that select section Skills in menu, Search Arduino and in list you see the skill with name is "Arduino Home Controller", click in the skill card and click button "Enable" to install.

Or you need to go to Amazon Skill Store using this link and press button "Enable"

You need link your Amazon account because we will use your email address like an ID for all commands sent to Arduino. Note we will not use this address to sent emails, only will use like an ID.

Skill is installed and linked to Amazon account and connected to my lambda function at AWS cloud.

Option two - Creates your own Skill and Lambda Function tutorial

1.- Create a skill

You need register and create a free developer account at site https://developer.amazon.com/home.html

1.1.- Once Login goes to Alexa menu option and select in Alexa Skills Kit the button "Get Started"

1.2.- Next click on "Add a New Skill" button to create a new skill.

1.3.- At Create a New Alexa Skill section you must:

  • Select: Custom Interaction Model
  • Language English US
  • Name TestSkill is the skill name using to search at store.
  • Invocation Name Test Skill is the name to begin voice commands like Alexa Ask, Test Skill to turn alarm on
  • All global fields set all to No option
  • Click "Save"

The new skill was created and you see a new field Application Id

amzn1.ask.skill.6e22e052-c32f-433c-8d39-dc94a77a4adb

It is used for link between skill and lambda function, we use it later in tutorial section 2.5.

1.4.- Interaction Model here define how you interact with the skill based in definition of intents, slots and utterances.

At Interaction Model menu option copy and paste this Json schema in Intent Schema.

{
 "intents": [
   {
     "slots": [
       {
         "name": "light",
         "type": "States"
       },
       {
         "name": "which",
         "type": "HabRooms"
       }
     ],
     "intent": "LightIntent"
   },
   {
     "slots": [
       {
         "name": "alarm",
         "type": "States"
       }
     ],
     "intent": "AlarmIntent"
   },
   {
     "intent": "TakePhotoIntent"
   },
   {
     "intent": "GetTemperatureIntent"
   },
   {
     "intent": "GetHumidityIntent"
   },
   {
     "intent": "AboutIntent"
   },
   {
     "intent": "AMAZON.HelpIntent"
   },
   {
     "intent": "AMAZON.CancelIntent"
   },
   {
     "intent": "AMAZON.StopIntent"
   }
 ]
}

Define some necessary slots like States and HabRooms in Custom Slot Types.

Define all utterances like a conversation model in Sample Utterances, copy and paste this list.

LightIntent Turn {which} light {light}
LightIntent Set  {which} light {light}
AlarmIntent Turn alarm {alarm}
TakePhotoIntent Take a Photo
TakePhotoIntent Take Security Photo
GetTemperatureIntent Read Temperature
GetHumidityIntent Read Humidity
AboutIntent Tell me about
AboutIntent About

Before continues with the next section, Configuration, we need have created our Lambda Function because we need link both the skill and lambda function.

2.- Creates a Lambda Function

You need register and create an account at AWS Console use url https://aws.amazon.com/console/

2.1.- Select Services in top menu and Lambda in the left bar menu.

2.2.- Select in left bar Function and click button "Create function".

2.3.- Set this data :

  • Click Author from Scratch
  • Name: TestSkillLambda
  • Runtime: Node.js.6.10
  • Role: Create Custom Role

This will open a new window where you should select the following values:

  • IAM Role: Lambda_Basic_Execution
  • PolicyName: “Create New Role Policy” then edit the policy and paste in the following:
{
 "Version": "2012-10-17",
 "Statement": [
   {
     "Effect": "Allow",
     "Action": [
       "logs:CreateLogGroup",
       "logs:CreateLogStream",
       "logs:PutLogEvents"
     ],
     "Resource": "arn:aws:logs:*:*:*"
   },
   { "Effect": "Allow",
     "Action": [
        "iot:UpdateThingShadow"
     ], 
     "Resource": "*"
   }
 ]
}

To save press "Add" button and return to Create Function page and select lambda_basic_execution in Existing role field.

2.4.- The TestSkillLambda function was created and you see its designer page.

2.5.- Select from left menu bar Alexa Skills Kit and add it to add triggers delimited area.

Click on Alexa Skills Kit box and scroll down to Configure triggers option, select Enable and in Skill ID field copy and paste Application ID value save later, see tutorial section number 1.3.

At this time we are linking lambda function with the skill using the Application or Skill ID.

Press the button "Save" and Alexa Skills Kit are saved and function lambda knowns skill and are linked.

2.6.- Scroll down to Function code section and set fields:

  • Code entry type: Upload a .zip file
  • Runtime: Node.js 6.10
  • Press button "Upload" to upload function code using the file data.zip.

The code editor will open and you will see the folders and files uploads.

Select the file index.js it contains all function lambda implementation.

You must change the line 23, copy and paste the same Application ID used later in tutorial section number 1.3.

Press button "Save" and lambda function was activated to receive skill commads.

var APP_ID = amzn1.ask.skill.6e22e052-c32f-433c-8d39-dc94a77a4adb

In the top of page above button "Save" you will see the ARN (Amazon Resource Name) it is the ID of lambda function than we will use it at Configuration section at Skill page.

3.- Return to Skill definition

3.1.- Select Configuration section, at EndPoint select AWS Lambda ARN, copy and paste the above ARN string in Default field. This is the last action to link skill and lambda function, skill knowns function lambda and are linked.

3.2.- Scroll down to Account Linking section and copy the two first Redirect URLs, you need them to config security profile.

Before continue with skill Configuration, we need define a security profile used to link the skill and Amazon account in Alexa App.

4.- Create Security Profile

At same developer console used to create a skill, select Apps & Services and Login with Amazon and press button "Create a New Security Profile"

4.1.- Security Profile Management page let you create a profile with all OAuth 2.0 security to link the skill with your Amazon account.

4.2.- Fill all fields with this data:

  • Security Profile Name: TestSkillProfile
  • Security Profile Description: Profile used by TestSkill
  • Click "Save" button.

4.3.- When save all data or edit the security profile two new fields show important data, Client ID and Client Secret. You need them for end skill configuration.

4.4.- Define the whitelist urls, select tab Web Settings.

  • Allowed Return URLs: add the two first urls from section 3.2

5.- Finishing skill creation

5.1.- Return to skill definition, select Configuration section and scroll down to Account Linking.

  • Do you allow users to create an account: Select Yes
  • Authorization URL: https://www.amazon.com/ap/oa/?redirect_url=UUUUUU Where there is “UUUUUU” you will need to replace this with one of the Redirect URL’s from further down the page. The link will end up looking something like this https://www.amazon.com/ap/oa/?redirect_url=https://layla.amazon.com/api/skill/link/UUUUUU
  • Client Id: copy and paste Client Id from section 4.3.
  • Scope: profile, see explain at this url.

5.2.- Continue with Account linking:

  • Authorization Grant Type: Auth Code Grant
  • Client Secret: copy and paste Client Secret from section 4.3.
  • Click "Save" and "Next" buttons

5.3.- Global Fields is the section used to document the skill.

  • Select category where find skill in store when certified, "Smart Home"
  • Testing instructions
  • Skill will be available in all countries.
  • Short description
  • Full skill description
  • Example phrases
  • Some keywords that define the skill
  • Png o Jpg Icon 108x108 pixeles
  • Png o Jpg Icon 512x512 pixeles

5.4.- Last section Privacy & Compliance

6.- Install TestSkill at Alexa App

6.1- When you save the skill you can go to Alexa App at https://alexa.amazon.com/ select in left bar menu the option Skills, click on button up right "Your skills" and the filter Dev Skills you can see TestSkill card. Note the account linking required message.

6.2.- If you click the card the TestSkill description page show all information about the skill, click "Enable" button.

6.3.- Because of account linking required definition you have redirect to Amazon login credentials page to link skill with your Amazon account.

If Login info is validated you see this page indicating that skill is linked with your Amazon account.

6.4.- The skill are finished, installed and linked to your Amazon account and connected to Lambda function.

You can test say Alexa, ask Test Skill and you see the welcome to Arduino Home Controller because all dialogs are the same.

Config Arduino Yun

If is the first time that you use Arduino Yun you need prepare it before sketch upload.

I suggest see Greg Baugues guide or tutorial Getting started with the Arduino Yun – the Arduino with WiFi. Thanks to Hackster user @BenEagen for finding this guide.

In order to take photo and send email with it we need install additional software. We are also going to test the USB camera to see if the drivers are working correctly. Please connect the USB webcam in usb port of Arduino Yun.

To do that connect to Arduino Yun with a terminal:

ssh root@yourYunName.local

The default password is arduino.

If connection is ok you will see the OpenWRT Linux prompt:

Install image generating software

Start with an update of the package manager:

opkg update

Install the UVC drivers:

opkg install kmod-video-uvc

Install python-openssl package:

opkg install python-openssl

We also need the fswebcam utility that we will use to take pictures from the terminal:

opkg install fswebcam

Make sure that the SD card is mounted into Arduino Yun, you can test it execute this command:

mount

If you see in device list one like /dev/sda1 on /mnt/sda1 type vfat SD card is Ok.

To test the camera and take a picture, it is really easy. Simply type:

cd /mnt/sda1
fswebcam test.png

You should see some information being displayed, along with some errors, but don't worry about them. The important thing is to see these lines:

--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.

To check that the picture was correctly taken, remove the SD card from the Arduino Yun and read it using your computer. You should see the picture appearing at the root of the SD card "test.png".

Simply open it to make sure it was correctly taken and that it is not corrupted.

Install send email software

With the SD in your computer copy python file AHC_SendEmail.py and change your email and password from a gmail account lines 11, 12 and 13, if you have another email provider change server information at line 36.

Extract SD from computer and insert at SD slot in Arduino Yun. At terminal connected to Arduino Yun, execute the commands :

cd /mnt/sda1
python /mnt/sda1/AHC_SendEmail.py /mnt/sda1/ test.png

If all is ok you must receive an email with your photo.

Connect all devices to Arduino Yun

Based on electronic schematic connect all devices in especial the DHT11 sensor because we need it to read temperature and humidity and buzzer to test alarm sound.

Install the sketch file ArduinoHomeMQTT.ino

I create a libraries.zip file with all libraries needed by this file, you can download it from my GitHub site and unzip in Arduino IDE libraries directory.

Libraries included in the libraries.zip inside ArduinoHomeMQTT folder.

ArduinoJson --> used to manipulate Json content
DHT_sensor_library --> used to handle DHT sensor
pubsubclient-master --> used to connect, publish and subscribe to PubNub(c)

Open Arduino IDE 1.6.x, in tools select "Board: Arduino Yun".

Load the file ArduinoHomeMQTT.ino and in the IDE modify line 16 with your Amazon email used when linked account in Amazon App skill enabled.

This option identify your controller when AWS send MQTT message to broker.

Change line 50 with your uuid to identify your controller in PubNub(c), you can go to this site and copy an paste uuid generated online.

Now save and upload the sketch and when open the Arduino IDE monitor window you can see Arduino Yun connected to PubNub(c) broker and sensor initialized.

Test all utterances from Alexa Echo Dot

The Alexa skill "Arduino Home Controller " skill handle this list of utterances, you can see they at Alexa App skill at description section. You can test all and see at Arduino ID serial monitor all messages received and send to PubNub(c) broker.

Lights control:

==> "Alexa, ask arduino home to turn room light on"
==> "Alexa, ask arduino home to turn room light off"
==> "Alexa, ask arduino home to turn kitchen light on"
==> "Alexa, ask arduino home to turn kitchen light off"
==> "Alexa, ask arduino home to turn garage light on"
==> "Alexa, ask arduino home to turn garage light off"
==> "Alexa, ask arduino home to turn living room light on"
==> "Alexa, ask arduino home to turn living room light off"

Alarm control:

==> "Alexa, ask arduino home to turn alarm on"
==> "Alexa, ask arduino home to turn alarm off"

Scan Temperature and Humidity:

==> "Alexa, ask arduino home to read temperature"
==> "Alexa, ask arduino home to read humidity"

Take a security photo:

==> "Alexa, ask arduino home to take a photo"

About and Help

==> "Alexa, ask arduino home about"==> "Alexa, ask arduino home help"

Software details

You can download all files for this project from my Github site.

Folders contains explain

ArduinoHomeMQTT --> ino file and libraries for Arduino Yun Home Controller

lambda --> Lambda function in Node.js to be deployed in AWS Lambda, includes all node_modules necessary, see option 2 in install all software section.

python --> python file for send email with photo attached.

schematic --> Fritzing(c) electronic schematic file.

Arduino Home Controller Workflow show you how files interact.

( 1 ) Amazon Echo Dot send command voice and it is received by Arduino Home Controller skill.

( 2 ) The skill call Lambda function file index.js.

( 3 ) The Lambda function file is developer in Node.Js, uses some node modules and was hosted at Amazon Web Service (AWS).

( 4 ) The lambda function interpret all intents and convert them to MQTT Json message and send it to PubNub(c) broker. This message have the format :

{
    "topic" : Topic_xxxx,
    "command" : on or off,
    "id" : email address
}

The topic Topic_xxxx may be:

Topic_room --> turn on/off room light
Topic_livingroom --> turn on/off living room light
Topic_kitchen --> turn on/off kitchen light
Topic_garage --> turn on/off garage light
Topic_alarm --> turn on/off alarm
Topic_temperature  --> read temperature
Topic_humidity --> read humidity
Topic_photo --> take and send photo by email

The command may be on or off.

( 5 ) The message is send using channel AHC_IOC_01. Channel AHC_IOC_02 is used to receive temperature or humidity values.

( 6 ) The Arduino Yun sketch ArduinoHomeMQTT.ino connect to broker and subscribe or publish to channels and receive or send messages.

( 7 ) Using a bridge the arduino sketch communicate with linux OpenWRT for wan or lan connect and to execute some commands.

( 8 ) If arduino need send an email uses the python file AHC_SendEmail.py, if needs take a photo call fswebcam programs located inside linux OpenWRT.

Hardware details

The heart of hardware is the Arduino Yun.

It uses several digital pins to control each device :

Pin 2 : connected to DHT11 sensor
Pin 8 : activate the buzzer alarm with help of NPN transistor 
Pin 9 : control room light
Pin 10: control kitchen light
Pin 11: control garage light
Pin 12: control living room light

The webcam is connected to usb port.

To power all devices the controller use 12 volts Dc power and convert to 5 volts using an Dc to Dc power converter.

I make an arduino shield using the Arduino Proto Shield with all connectors and interface electronic to sensor, buzzer alarm and power supply. It have space for new sensors to extending the controller.

Put the Arduino Yun, Proto shield, Relays and power regulator inside a plastic box with alarm, webcam and sensor outside, and make all connections like mention in electronic schematic.

For demo and video propose I use four leds in prothoboard simulating light bulbs in each house rooms.

Thanks for read this guide, I appreciate your time, If you have any suggestions please contact me.

I make this project in memory of my Dad, he dieds last year, R.I.P Dad.

Code

ArduinoHomeMQTT.inoArduino
Arduino Yun software for Home Controller
//
// ArduinoHomeMQTT
// v2.1
//
// Copyright (C)2018 Jose Cruz. All right reserved
// web: https://sites.google.com/view/raeiot/home
//
#include <YunClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DHT.h>
#include <Process.h>

// Your Amazon email linked skill
#define MyID "YOUR AMAZON EMAIL LINKED IN ALEXA APP"

// DHT11 sensor data pin
#define DHTPIN 2
// DHT 11 sensor type
#define DHTTYPE DHT11
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);

// Alarm control pin
#define alarm 8

// Light control pins
#define room_light 9
#define kitchen_light 10
#define garage_light 11
#define livingroom_light 12

// PubNub MQTT Server address and port
int mqtt_server_port = 1883;
const char* mqtt_server = "mqtt.pndsn.com";
// Suscribe topic
const char* topic = "AHC_IOT_01";
// Publish topic
const char* topic2 = "AHC_IOT_02";

// PubNub publisher ID
//  pub-c-e93def7f-95aa-475a-aa60-cc3cd32ee8a7/
// PubNub suscriber ID
//  sub-c-ec04dbbc-0893-11e8-8e75-cea83f8405bb/
// UUID generated onlyne https://www.uuidgenerator.net/
//  
// PubNub Client ID
//  clientId = pubID + subID + uuid;
const char* clientId = "pub-c-e93def7f-95aa-475a-aa60-cc3cd32ee8a7/sub-c-ec04dbbc-0893-11e8-8e75-cea83f8405bb/YOUR UUID GENERATED";


// Define de Yun ethernet client
YunClient ethClient;
// Define PubNub pub and sub client
PubSubClient client(ethClient);

// Picture process
Process picture;

// Filename
String filename;
// Path for image file
String path = "/mnt/sda1/";

// Create an image file and sent by email
void TakePhoto() {
  // Generate filename with timestamp
  filename = "";
  picture.runShellCommand("date +%s");
  while (picture.running());

  while (picture.available() > 0) {
    char c = picture.read();
    filename += c;
  }
  filename.trim();
  filename += ".jpg";

  // Take picture
  picture.runShellCommand("/usr/bin/fswebcam  -i 0 --jpeg 95 --no-banner --fps 1 -S 1 -r 352x288 --save " + path + filename);
  while (picture.running());

  //Send it by email
  picture.runShellCommand("python /mnt/sda1/AHC_SendEmail.py " + path + " " + filename);
  while (picture.running());
}

//***********************
// Send temperature
//***********************
void SendTemperature()
{
  char cstr[16];
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  //  Serial.print("Temperature: ");
  //  Serial.print(t);
  //  Serial.println(" *C");

  client.publish(topic2, itoa(t, cstr, 10));
  //Serial.print("Temperature sent...");
  //Serial.println(cstr);
}

//***********************
// Send humidity
//***********************
void SendHumidity()
{
  char cstr[16];
  float h = dht.readHumidity();
  //Serial.print("Humidity: ");
  //Serial.print((int)h);
  //Serial.print(" %\t");

  client.publish(topic2, itoa(h, cstr, 10));
  //Serial.print("Humidity sent...");
  //Serial.println(cstr);
}

//Callback function for msg receive handle
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]);
  }
  Serial.println();

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject((char[])payload);

  String alexa_topic  = root["topic"];
  String alexa_command = root["command"];
  String alexa_id = root["id"];

  //Serial.println(alexa_topic);
  //Serial.println(alexa_command);

   if (alexa_id.equals(MyID)) {
    //Handle all received msgs topic from MQTT
    if (alexa_topic.endsWith("Topic_room")) {
      digitalWrite(room_light, (alexa_command.endsWith("on") ? LOW : HIGH));
    } else if (alexa_topic.endsWith("Topic_kitchen")) {
      digitalWrite(kitchen_light, (alexa_command.endsWith("on") ? LOW : HIGH));
    } else if (alexa_topic.endsWith("Topic_garage")) {
      digitalWrite(garage_light, (alexa_command.endsWith("on") ? LOW : HIGH ));
    } else if (alexa_topic.endsWith("Topic_living room")) {
      digitalWrite(livingroom_light, (alexa_command.endsWith("on") ? LOW : HIGH));
    } else if (alexa_topic.endsWith("Topic_temperature")) {
      SendTemperature();
    } else if (alexa_topic.endsWith("Topic_humidity")) {
      SendHumidity();
    } else if (alexa_topic.endsWith("Topic_alarm")) {
      digitalWrite(alarm, (alexa_command.endsWith("on") ? HIGH : LOW));
    } else if (alexa_topic.endsWith("Topic_photo")) {
      TakePhoto();
    }
  }
}

//Reconnect to MQTT broker if lost connection
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientId)) {
      Serial.println("MQTT broker connected");
      client.subscribe(topic);
    } else {
      Serial.print("Failed, rc = ");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup()
{
  Bridge.begin();
  delay(2000);
  
  Serial.begin(115200);
  Serial.println("Init Arduino Home Controller v2.1...");
  
  pinMode(alarm, OUTPUT);
  pinMode(room_light, OUTPUT);
  pinMode(kitchen_light, OUTPUT);
  pinMode(garage_light, OUTPUT);
  pinMode(livingroom_light, OUTPUT);

  digitalWrite(room_light, HIGH);
  digitalWrite(kitchen_light, HIGH);
  digitalWrite(garage_light, HIGH );
  digitalWrite(livingroom_light, HIGH);

  // Define PubNub MQTT broker
  client.setServer(mqtt_server, mqtt_server_port);
  client.setCallback(callback);
  client.connect(clientId);
  Serial.println("Connected to PubNub MQTT broker OK ...");
  client.subscribe(topic);
  Serial.println("Suscribe to topic at MQTT broker Ok ...");

  dht.begin();
  //Wait for sensor initialize
  delay(4000);
  Serial.println("DHT sensor Ok ...");
}

void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
AHC_SendEmail.pyPython
File to be installed in Arduino Yun OpenWRT linux to help send email with attached photo
import smtplib
import sys
import time

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
 
fromaddr = "joseacruzp@gmail.com"
toaddr = "joseacruzp@gmail.com"
emailpassword = "YOUR PASSWORD"
subject = "Arduino Home Controller by Alexa Skill"
body = "Photo taken in " + time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)')
filedir =sys.argv[1]
filename = sys.argv[2]

msg = MIMEMultipart()
 
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject
 
msg.attach(MIMEText(body, 'plain'))
 
attachment = open(filedir + filename, "rb")
 
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
 
msg.attach(part)
 
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, emailpassword)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
index.jsJavaScript
AWS Lambda Function if you select option 2, build your own skill
// Alexa SDK for Arduino Home Controller
// Copyright (c) 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. Use is subject to license terms.
// Jose Cruz https://sites.google.com/view/jriot 

// Define connection to PubNub 
var PubNub = require("pubnub");
var pubnub = new PubNub({
    ssl: true,
    publish_key: "pub-c-e93def7f-95aa-475a-aa60-cc3cd32ee8a7",
    subscribe_key: "sub-c-ec04dbbc-0893-11e8-8e75-cea83f8405bb",
    uuid: "YOUR UUID"
});

// Define the PubNub channel
var channel = 'AHC_IOT_01';
// Used to receive some values (temperature, humidity)
var channel2 = 'AHC_IOT_02';

// Define slot states for light and alarm turn on/off
var slotStates = ['on', 'off'];

// App ID for the skill
var APP_ID = 'YOUR APP ID FOR THE SKILL';

// The AlexaSkill prototype and helper functions
var AlexaSkill = require('./AlexaSkill');

var ArduinoHomeSkill = function() {
    AlexaSkill.call(this, APP_ID);
};

//Listener for suscribe and receive temperature and humidity
var mqttListener;

var access_token;
var url;
var https = require("https");


function SendMessage(topicname, commandvalue, speechOutput, iresponse) {
    https.get(url, res => {
        res.setEncoding("utf8");
        let body = "";
        res.on("data", data => {
            body += data;
        });
        res.on("end", () => {
            pubnub.publish({ //Publishes the turn message to my PubHub Device.
                channel: channel,
                message: {
                    "topic": topicname,
                    "command": commandvalue,
                    "id": JSON.parse(body).email
                }
            }).then((response) => {
                console.log("message Published w/ timetoken", response.timetoken);
                if (speechOutput) iresponse.tell(speechOutput);
            }).catch((error) => {
                console.log("publishing failed w/ status: ", error);
                iresponse.ask("Sorry, I didn't catch what you said");
            });

        });
    });
}


/// Extend AlexaSkill
ArduinoHomeSkill.prototype = Object.create(AlexaSkill.prototype);
ArduinoHomeSkill.prototype.constructor = ArduinoHomeSkill;

ArduinoHomeSkill.prototype.eventHandlers.onSessionStarted = function(sessionStartedRequest, session) {

    //    SetUserID();

    console.log("ArduinoHomeSkill onSessionStarted requestId: " + sessionStartedRequest.requestId +
        ", sessionId: " + session.sessionId);
    //    console.log("Init...");

    //Delete all listeners and suscribes defined 
    pubnub.removeListener(mqttListener);
    pubnub.unsubscribeAll();

    //    console.log("Init...Ok");

};

//-------->This is invoked by invocation word "Arduino Home"
ArduinoHomeSkill.prototype.eventHandlers.onLaunch = function(launchRequest, session, response) {
    console.log("ArduinoHomeSkill onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    //if no amazon token, return a LinkAccount card

    if (session.user.accessToken == undefined) {

        response.tellWithCardLink('To start using this skill, please use the companion app to authenticate on Amazon.');

        return;

    }

    var speechOutput = "Welcome to Arduino Home Controller.   What would you like to do?";
    var repromptText = "I am ready";
    response.ask(speechOutput, repromptText);
};

ArduinoHomeSkill.prototype.eventHandlers.onSessionEnded = function(sessionEndedRequest, session) {
    console.log("ArduinoHomeSkill onSessionEnded requestId: " + sessionEndedRequest.requestId +
        ", sessionId: " + session.sessionId);

    console.log("End...");

};



//*** Define all intent handlers
ArduinoHomeSkill.prototype.intentHandlers = {
    //*** AboutIntent handler
    "AboutIntent": function(intent, session, response) {
        var myText;
        console.log("in about");
        myText = "Arduino Home Controller skil let you control internet connected devices. It controls  Lights at room, kitchen, garage or living room), read a temperature sensor to scan home temperature, read Humidity sensor to scan home humidity, uses webcam to take a home security photo and sent it by email and activate an alarm to alert some events. It uses PubNub site to manipulate all messages send by Alexa with Lambda function. Please check information at skill page for more details.   What would you like to do?";
        response.ask(myText);
        return;
    },

    //*** LightIntent handler
    "LightIntent": function(intent, session, response) {
        var slotHabRooms = ['room', 'kitchen', 'garage', 'living room'];

        var lightSlot = intent.slots.light;
        var lightSlotValue = lightSlot ? lightSlot.value : "";

        var whichSlot = intent.slots.which;
        var whichSlotValue = whichSlot ? whichSlot.value : "";
        if (lightSlotValue && whichSlotValue && slotStates.indexOf(lightSlotValue.toLowerCase()) > -1 && slotHabRooms.indexOf(whichSlotValue.toLowerCase()) > -1) {

            SendMessage('Topic_' + whichSlotValue, lightSlotValue, "The light is now " + lightSlotValue, response);

        }
        else {
            response.ask("Sorry, I didn't catch what you said");
        }
    },

    //*** AlarmIntent handler
    "AlarmIntent": function(intent, session, response) {
        var alarmSlot = intent.slots.alarm;
        var alarmSlotValue = alarmSlot ? alarmSlot.value : "";
        if (alarmSlotValue && slotStates.indexOf(alarmSlotValue.toLowerCase()) > -1) {
            SendMessage('Topic_alarm', alarmSlotValue, "The alarm is now " + alarmSlotValue, response);
        }
        else {
            response.ask("Sorry, I didn't catch what you said");
        }
    },

    //*** TakePhotoIntent handler
    "TakePhotoIntent": function(intent, session, response) {

        SendMessage('Topic_photo', 'take', "Taken home photo ", response);

    },
    //*** GetTemperatureIntent handler
    "GetTemperatureIntent": function(intent, session, response) {

        mqttListener = {
            status: function(statusEvent) {},
            message: function(message) {
                // handle message
                console.log("Receive=", message);
                var myText = "Inside Temperature is " + message.message + " degrees C";
                response.tell(myText);
            },
            presence: function(presenceEvent) {
                // handle presence
            }
        };
        pubnub.addListener(mqttListener);
        pubnub.subscribe({
            channels: [channel2]
        });
        SendMessage('Topic_temperature', 'Ok', null, response)
    },


    //*** GetTemperatureIntent handler
    "GetHumidityIntent": function(intent, session, response) {
        mqttListener = {
            status: function(statusEvent) {},
            message: function(message) {
                // handle message
                console.log("Receive=", message);
                var myText = "Inside Humidity is " + message.message + " %";
                response.tell(myText);
            },
            presence: function(presenceEvent) {
                // handle presence
            }
        };

        pubnub.addListener(mqttListener);

        pubnub.subscribe({
            channels: [channel2]
        });

        SendMessage('Topic_humidity', 'Ok', null, response)
    },

    //*** HelpIntent handler
    "AMAZON.HelpIntent": function(intent, session, response) {
        response.ask("With Arduino Home Controller skill and Alexa you can control internet connected devices using an Arduino Yun or Arduino with Ethernet Shield. Please check information at skill page for more details.    What would you like to do?");
    },
    //*** StopIntent handler
    "AMAZON.StopIntent": function(intent, session, response) {
        response.tell("Thanks for using Arduino Home Controller. Bye see you later");
    },
    //*** StopIntent handler
    "AMAZON.CancelIntent": function(intent, session, response) {
        response.tell("Thanks for using Arduino Home Controller. Bye see you later");
    },
    default: function(intent, session, response) {
        response.ask("Try again");
    },

};


// Create the handler that responds to the Alexa Request.
exports.handler = function(event, context) {

    try {
        access_token = event['context']['System']['user']['accessToken'];
        url = 'https://api.amazon.com/user/profile?access_token=' + access_token;
        //console.log("Access Token:", access_token);
    }
    catch (error) {
        console.log(error);
    }

    // Create an instance of Arduino Home Skill
    var ArduinoHomeControl = new ArduinoHomeSkill();
    ArduinoHomeControl.execute(event, context);
    //console.log('AWSrequestID =', context.awsRequestId);
};

Schematics

Arduino Yun Home Controller
Main board with reles, temperature and humidity sensor, buzzer alarm and webcam.
Arduinohome xwm2u7cqej

Comments

Similar projects you might like

Alexa Based Smart Home Monitoring

Project tutorial by Adithya TG

  • 16,639 views
  • 19 comments
  • 47 respects

Hygge Home - Alexa Smart Bath

Project tutorial by J Howard

  • 5,367 views
  • 2 comments
  • 18 respects

Secure Package Delivery Trunk for Your Front Porch

Project tutorial by Team Castle Locker

  • 2,515 views
  • 1 comment
  • 15 respects

Alexa BBQ/Kitchen Thermometer with IoT Arduino and e-Paper

Project tutorial by Roger Theriault

  • 2,386 views
  • 0 comments
  • 9 respects

Dooreo - The Alexa Powered Automatic Door Opener

Project tutorial by Keith Caskey

  • 2,745 views
  • 0 comments
  • 12 respects

Wise Shower Driven by Alexa Skill

Project in progress by Virgilio Enrique Aray Arteaga

  • 2,196 views
  • 0 comments
  • 3 respects
Add projectSign up / Login