亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Manufacturing Technology >> 制造工艺

由 Alexa 激活的 Arduino 家庭控制器

组件和用品

Arduino Yun
× 1
ControlEverything.com 用于 I2C 的 4 通道继电器控制器
× 1
DHT11 温湿度传感器(4 针)
× 1
电阻 10k ohm
× 2
SparkFun RedBot Buzzer
× 1
通用晶体管 NPN
× 1
LM2596 直流到直流降压转换器
× 1
亚马逊 Alexa Echo Dot
× 1
Arduino Proto Shield
× 1
USB 网络摄像头
× 1
白色接线盒 200mmx155mmx80mm
× 1

必要的工具和机器

烙铁(通用)

应用和在线服务

Arduino IDE
亚马逊 Alexa Alexa 技能套件
亚马逊网络服务 AWS Lambda
PubNub 发布/订阅 API

关于这个项目

概览

当亚马逊向市场推出 Alexa 和 Amazon Echo Dot 等设备时,会打开无数选项,以使用自然语言通过语音命令控制出色的智能家居。

该项目制作了一个 Arduino 家庭控制器,可以将许多传感器和设备连接到互联网,您可以使用 Amazon Alexa 技能控制它们。

您可以安装并启用我的技能“Arduino Home Controller " 简单的步骤,或者您可以通过本教程指导您的技能。

现在我们将控制:

  • 房间、车库、厨房和客厅有四盏灯。
  • 温湿度传感器。
  • 蜂鸣器警报。
  • 用于拍摄安全照片并通过电子邮件发送的网络摄像头。

您可以在这个简短的视频演示中看到 Arduino 家庭控制器的运行情况。对于演示和视频建议,我在每个房间的原版板中使用四个 LED 模拟灯泡。

如果你想使用远程模块来激活你的灯,你可以查看我的 Arduino Home Controller Remote Modules 项目在此 URL。

框图

框图图片 我们可以看到这个项目的四个主要组成部分:

1.- 亚马逊回声点 接收语音命令并将其发送到 AWS(亚马逊网络服务)。

2.- 具有亚马逊技能和 Lambda 函数的 AWS 解释所有命令。

技能名称是“Arduino Home Controller "你可以稍后激活它。

3.- MQTT Broker 使用 PubNub(c) 云。

该代理将通过两个通道接收控制消息,一个用于设置值,另一个用于从传感器读取值。

您无需在 PubNub 中创建帐户,您可以使用我的帐户进行演示提案。

4.- 家庭控制器 使用 Arduino Yun。

我们将使用 Arduino Yun,因为它内部有以太网屏蔽,并且有一个小型 linux 机器,我们将在其中执行 python 来处理一些操作。

它控制灯的继电器,读取温度和湿度传感器,打开蜂鸣器报警并操纵网络摄像头拍摄安全照片。

对于远程模块,请参阅我的补充,Arduino 家庭控制器远程模块 项目在此 URL。

安装所有需要的软件

在这一点上,您可以选择两个选项,一是演示建议,使用我的 Alexa 技能安装并使用它,或者选项二可以使您成为个人技能。

使用此 url 浏览 Alexa 应用 , 在菜单中的选择部分技能,搜索 Arduino 在列表中,您会看到名称为“Arduino Home Controller”的技能 ”,点击技能卡,点击“启用”按钮进行安装。

或者您需要使用此链接前往亚马逊技能商店 然后按“启用”按钮

您需要链接您的亚马逊帐户,因为我们将使用您的电子邮件地址作为发送到 Arduino 的所有命令的 ID。请注意,我们不会使用此地址发送电子邮件,只会用作 ID。

Skill 已安装并链接到 Amazon 帐户并连接到我在 AWS 云上的 lambda 函数。

1.- 创建 技能

您需要在网站 https://developer.amazon.com/home.html

上注册并创建一个免费的开发者帐户

1.1.- 一旦登录到 Alexa 菜单选项并在 Alexa Skills Kit 中选择 按钮“开始”

1.2.-接下来点击“添加新技能”按钮来创建一个新技能。

1.3.- 在 创建新的 Alexa 技能 您必须:

  • 选择:自定义交互模型
  • 语言美国英语
  • 名称 TestSkill 是用于在商店搜索的技能名称。
  • 调用名称​​测试技能 是开始语音命令的名称,例如Alexa Ask,打开警报的测试技能
  • 所有全局字段都设置为无选项
  • 点击“保存”

新技能已创建,您会看到一个新字段 Application Id

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

用于连接skill和lambda函数,后面教程2.5节会用到。

1.4.- 此处的交互模型基于意图、槽和话语的定义定义了您如何与技能交互。

交互模型 菜单选项将此 Json 模式复制并粘贴到 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" } ]} 

在自定义插槽类型中定义一些必要的插槽,例如 State 和 HabRooms。

Sample Utterances中定义所有话语,如对话模型 , 复制并粘贴此列表。

LightIntent 转{which}灯{light}LightIntent 设置{which}灯{light}AlarmIntent 转闹钟{alarm}TakePhotoIntent 拍张照片TakePhotoIntent 拍安全照片GetTemperatureIntent 读取TemperatureGetHumidityIntent 读取HumidityAboutIntent 告诉我AboutIntent 关于 

在继续下一部分之前,配置, 我们需要创建我们的 Lambda 函数,因为我们需要链接技能和 lambda 函数。

2.- 创建一个 Lambda 函数

您需要在 AWS 控制台使用 url https://aws.amazon.com/console/

注册并创建一个帐户

2.1.- 选择服务 顶部 菜单Lambda 在左侧栏菜单中。

2.2.- 在左侧栏中选择功能 然后点击“创建函数”按钮。

2.3.- 设置此数据:

  • 点击 作者 从头开始
  • 姓名: TestSkillLambda
  • 运行时: Node.js.6.10
  • 角色: 创建自定义角色

这将打开一个新窗口,您应该在其中选择以下值:

  • IAM 角色: Lambda_Basic_Execution
  • 政策名称: “创建新角色策略”,然后编辑策略并粘贴以下内容:
{ "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":[ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource":"arn:aws:logs:*:*:*" }, { "Effect":"Allow", "Action":[ "iot:UpdateThingShadow" ], "Resource" :"*" } ]} 

要保存按“添加”按钮并返回创建函数 页面并选择 lambda_basic_execution 现有角色 领域。

2.4.- TestSkillLambda 函数已创建,您会看到它的设计器页面。

2.5.- 从左侧菜单栏中选择Alexa Skills Kit 并将其添加到添加触发器 定界区域。

点击Alexa 技能工具包 框并向下滚动到配置触发器 选项,选择启用 并在技能 ID 字段复制和粘贴应用程序 ID 稍后保存值,请参阅教程第 1.3 节。

此时,我们正在使用应用程序或技能 ID 将 lambda 函数与技能联系起来。

按“保存”按钮和 Alexa Skills Kit 保存和函数 lambda 已知技能并链接。

2.6.- 向下滚动到功能代码 部分和设置字段:

  • 代码条目类型:上传 .zip 文件
  • 运行时: Node.js 6.10
  • 按下按钮“上传 " 使用文件data.zip上传功能代码 .

代码编辑器将打开,您将看到文件夹和文件上传。

选择文件 index.js 它包含所有函数 lambda 实现。

您必须更改第 23 行,复制并粘贴相同的 Application ID 稍后在教程第 1.3 节中使用。

按下“保存”按钮,lambda 功能被激活以接收技能指令。

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

在“保存”按钮上方的页面顶部,您将看到 ARN(亚马逊资源名称),它是 lambda 函数的 ID,我们将在配置中使用它 技能页面部分。

3.- 返回技能定义

3.1.- 选择配置 部分,在 EndPoint 选择 AWS Lambda ARN, 将上述 ARN 字符串复制并粘贴到 Default 中 场地。这是链接技能和 lambda 函数的最后一个动作,技能已知函数 lambda 和链接。

3.2.- 向下滚动到帐户链接 部分并复制前两个重定向 URL, 您需要它们来配置安全配置文件。

在继续进行技能配置之前,我们需要定义一个安全配置文件,用于在 Alexa 应用程序中链接技能和亚马逊帐户。

4.- 创建安全配置文件

在用于创建技能的同一个开发者控制台中,选择应用和服务登录亚马逊 然后按下按钮“创建 安全 个人资料”

4.1.- 安全配置文件管理 页面可让您创建具有所有 OAuth 2.0 安全性的配置文件,以将技能与您的 Amazon 帐户相关联。

4.2.- 用这些数据填充所有字段:

  • 安全配置文件名称 :TestSkillProfile
  • 安全配置文件描述 :TestSkill 使用的配置文件
  • 同意隐私声明网址 :https://www.amazon.com/gp/help/customer/display.html?nodeId=201809740 这是您必须使用的示例。
  • 点击“保存”按钮。

4.3.- 保存所有数据或编辑安全配置文件时,两个新字段显示重要数据,Client ID 客户端秘密 .你需要它们来配置最终技能。

4.4.- 定义白名单网址,选择标签Web Settings。

  • 允许的来源 :https://layla.amazon.com 和 https://pitangui.amazon.com
  • 允许的返回 URL :添加第 3.2 节中的前两个网址

5.- 完成技能创造

5.1.- 返回技能定义,选择配置 部分并向下滚动到帐户关联 .

  • 您是否允许用户创建帐户 :选择
  • 授权网址https://www.amazon.com/ap/oa/?redirect_url=UUUUUU 如果有“UUUUUU”,您需要将其替换为 重定向 URL 之一 从页面的更下方。该链接最终看起来像这样 https://www.amazon.com/ap/oa/?redirect_url=https://layla.amazon.com/api/skill/link/UUUUUU
  • 客户 ID :复制并粘贴客户 ID 来自第 4.3 节。
  • 范围个人资料 ,请参阅此网址的说明。

5.2.- 继续帐户链接:

  • 授权类型 :授权码授权
  • 访问令牌 URI :https://api.amazon.com/auth/o2/token
  • 客户端机密 :复制并粘贴客户端密码 来自第 4.3 节。
  • 隐私政策网址 :https://www.amazon.com/gp/help/customer/display.html?nodeId=201809740 这是您必须使用的示例。
  • 点击“保存”和“下一步”按钮

5.3.- 全局字段是用于记录技能的部分。

  • 选择获得认证后可在商店中找到技能的类别 ,“智能家居”
  • 测试说明
  • Skill 将在所有国家/地区提供 .
  • 简短说明
  • 完整的技能描述
  • 示例短语
  • 定义技能的一些关键词
  • Png 或 Jpg 图标 108x108 像素
  • Png 或 Jpg 图标 512x512 像素

5.4.- 最后一部分隐私与合规

6.- 在 Alexa 应用程序上安装 TestSkill

6.1- 当您保存技能时,您可以转到 https://alexa.amazon.com/ 上的 Alexa 应用程序,在左侧栏菜单中选择选项 Skills ,点击右侧的按钮“你的技能”和过滤器开发技能 你可以看到TestSkill 卡片。请注意帐户关联所需的消息。

6.2.- 如果您点击卡片,TestSkill 描述页面显示该技能的所有信息,点击“启用”按钮。

6.3.- 由于帐户链接需要定义,您必须重定向到亚马逊登录凭证页面以将技能与您的亚马逊帐户链接。

如果登录信息得到验证,您会看到此页面,表明该技能与您的亚马逊帐户相关联。

6.4.- 技能完成,安装并链接到您的亚马逊帐户并连接到Lambda函数。

你可以测试说Alexa,问测试技能 您会看到欢迎使用 Arduino Home Controller,因为所有对话框都是相同的。

配置 Arduino Yun

如果您是第一次使用 Arduino Yun,您需要在草图上传之前准备它。

我建议参阅 Greg Baugues 指南或教程 Arduino Yun 入门 – 带有 WiFi 的 Arduino。感谢 Hackster 用户 @BenEagen 找到本指南。

为了拍照和发送电子邮件,我们需要安装额外的软件。我们还将测试 USB 摄像头以查看驱动程序是否正常工作。请将USB摄像头连接到Arduino Yun的usb端口。

为此,请使用终端连接到 Arduino Yun:

ssh [email protected] 

默认密码是arduino。

如果连接正常,您将看到 OpenWRT Linux 提示:

安装 图像生成 软件

从包管理器的更新开始:

opkg 更新 

安装 UVC 驱动程序:

opkg install kmod-video-uvc 

安装 python-openssl 包:

opkg install python-openssl 

我们还需要 fswebcam 实用程序,用于从终端拍摄照片:

opkg install fswebcam 

确保SD卡已挂载到Arduino Yun中,您可以执行此命令对其进行测试:

挂载 

如果你在设备列表中看到一个像 /dev/sda1 on /mnt/sda1 type vfat SD卡没问题。

要测试相机并拍照,这真的很容易。只需输入:

cd /mnt/sda1fswebcam test.png 

您应该会看到显示的一些信息以及一些错误,但不要担心它们。重要的是看到这些行:

--- 打开 /dev/video0...正在尝试源模块 v4l2.../dev/video0 打开。 

要检查照片是否正确拍摄,请从 Arduino Yun 中取出 SD 卡并使用您的计算机读取它。您应该会看到出现在 SD 卡根目录下的图片“test.png ”.

只需打开它以确保它被正确拍摄并且没有损坏。

安装 发送电子邮件软件

使用计算机中的 SD 复制 python 文件 AHC_SendEmail.py 并从 gmail 帐户的第 11、12 和 13 行更改您的电子邮件和密码,如果您有其他电子邮件提供商,请在第 36 行更改服务器信息。

从计算机中提取 SD 并插入 Arduino Yun 的 SD 插槽。在连接到 Arduino Yun 的终端,执行命令:

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

如果一切正常,您必须收到一封包含照片的电子邮件。

将所有设备连接到 Arduino Yun

根据电子原理图连接所有设备,特别是DHT11传感器,因为我们需要它读取温湿度和蜂鸣器来测试警报声。

安装 草图 文件 ArduinoHomeMQTT.ino

我创建了一个 libraries.zip 包含此文件所需的所有库的文件,您可以从我的 GitHub 站点下载它并在 Arduino IDE 库目录中解压。

libraries.zip 中包含的库 ArduinoHomeMQTT 文件夹。

ArduinoJson --> 用于操作Json contentDHT_sensor_library --> 用于处理DHT sensorpubsubclient-master --> 用于连接、发布和订阅PubNub(c) 

打开Arduino IDE 1.6.x,在工具中选择“Board:Arduino Yun”。

加载文件 ArduinoHomeMQTT.ino 并在 IDE 中修改第 16 行,使用在启用 Amazon App 技能中的关联帐户时使用的 Amazon 电子邮件。

当 AWS 向代理发送 MQTT 消息时,此选项会识别您的控制器。

将第 50 行更改为您的 uuid 以在 PubNub(c) 中标识您的控制器,您可以访问此站点 并复制粘贴在线生成的 uuid。

现在保存并上传草图,当打开 Arduino IDE 监控窗口时,您可以看到 Arduino Yun 连接到 PubNub(c) 代理和传感器初始化。

测试来自 Alexa Echo Dot 的所有话语

Alexa 技能“Arduino 家庭控制器 " 技能处理这个话语列表 ,您可以在描述部分的 Alexa App 技能中看到它们。您可以测试所有并在 Arduino ID 串行监视器上查看所有收到并发送到 PubNub(c) 代理的消息。

灯光控制:

==> "Alexa,请 arduino home 打开房间灯"==> "Alexa,请 arduino home 关闭房间灯"==> "Alexa,请 arduino home 打开厨房灯"==> "Alexa,让 arduino home 关掉厨房灯"==> "Alexa,让 arduino home 打开车库灯"==> "Alexa,让 arduino home 关掉车库灯"==> " Alexa,请 arduino home 打开客厅灯“==>“Alexa,请 arduino home 关闭客厅灯” 

报警控制:

==> "Alexa,请 arduino home 打开闹钟"==> "Alexa,请 arduino home 关闭闹钟" 

扫描温度和湿度:

==> "Alexa,请 arduino home 读取温度"==> "Alexa,请 arduino home 读取湿度" 

拍摄安全照片:

==> “Alexa,让 arduino 回家拍照” 

关于和帮助

==> "Alexa,向 arduino home 询问"==> "Alexa,向 arduino home 求助" 

软件详情

你可以从我的 Github 站点下载这个项目的所有文件。

文件夹包含说明

ArduinoHomeMQTT --> Arduino Yun 家庭控制器的ino 文件和库

拉姆达 --> Node.js 中的 Lambda 函数将部署在 AWS Lambda 中,包括所有必需的 node_modules,请参阅安装所有软件部分中的选项 2。

蟒蛇 --> python 文件,用于发送附有照片的电子邮件。

示意图 --> Fritzing(c) 电子原理图文件。

Arduino 家庭控制器工作流程 显示 文件如何交互 .

( 1 ) Amazon Echo Dot 发送命令语音,由 Arduino Home Controller 技能接收。

(2)技能调用Lambda函数文件index.js .

( 3 ) Lambda 函数文件是 Node.Js 中的 developer,使用了一些 node 模块 并托管在亚马逊网络服务 (AWS) 上。

( 4 ) lambda 函数解释所有意图并将它们转换为 MQTT Json 消息并发送给 PubNub(c) 代理。 此消息的格式为:

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

主题Topic_xxxx 可能是:

Topic_room --> turn on/off room lightTopic_livingroom --> turn on/off living room lightTopic_kitchen --> turn on/off kitchen lightTopic_garage --> turn on/off garage lightTopic_alarm --> turn on/off alarmTopic_temperature --> read temperatureTopic_humidity --> read humidityTopic_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 sensorPin 8 :activate the buzzer alarm with help of NPN transistor Pin 9 :control room lightPin 10:control kitchen lightPin 11:control garage lightPin 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.

代码

  • ArduinoHomeMQTT.ino
  • AHC_SendEmail.py
  • index.js
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 #include #include #include #include // 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 sensorDHT 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 portint mqtt_server_port =1883;const char* mqtt_server ="mqtt.pndsn.com";// Suscribe topicconst char* topic ="AHC_IOT_01";// Publish topicconst 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;c onst char* clientId ="pub-c-e93def7f-95aa-475a-aa60-cc3cd32ee8a7/sub-c-ec04dbbc-0893-11e8-8e75-cea83f8405bb/YOUR UUID GENERATED";// Define de Yun ethernet clientYunClient ethClient;// Define PubNub pub and sub clientPubSubClient client(ethClient);// Picture processProcess picture;// FilenameString filename;// Path for image fileString path ="/mnt/sda1/";// Create an image file and sent by emailvoid 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 handlevoid callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i =0; i  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 connectionvoid 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();延迟(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 smtplibimport sysimport timefrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfrom email.MIMEBase import MIMEBasefrom email import encoders fromaddr ="[email protected]"toaddr ="[email protected]"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'] =fromaddrmsg['To'] =toaddrmsg['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 channelvar 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/offvar slotStates =['on', 'off'];// App ID for the skillvar APP_ID ='YOUR APP ID FOR THE SKILL';// The AlexaSkill prototype and helper functionsvar AlexaSkill =require('./AlexaSkill');var ArduinoHomeSkill =function() { AlexaSkill.call(this, APP_ID);};//Listener for suscribe and receive temperature and humidityvar mqttListener;var access_token;var url;var https =require("https");function SendMessage(topicname, commandvalue, speechOutput, iresponse) { https.get(url, res => { res.setEnc oding("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 AlexaSkillArduinoHomeSkill.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.');返回; } 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 handlersArduinoHomeSkill.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);返回; }, //*** 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);};
Github
https://github.com/jcruzp/ArduinoHomeController

示意图

Main board with reles, temperature and humidity sensor, buzzer alarm and webcam.

制造工艺

  1. Web 操作的 DMX 控制器
  2. Arduino 数字骰子
  3. Arduino 游戏控制器
  4. 像素追逐游戏
  5. 家庭植物浇水系统
  6. Arduino 排斥电磁悬浮
  7. 真空荧光显示控制器
  8. 自主家庭助理机器人
  9. NeoMatrix Arduino Pong
  10. Arduino DMX-512 测试控制器
  11. LED 轮盘游戏
  12. 家庭监视器