산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Manufacturing Technology >> 제조공정

Alexa에 의해 활성화된 Arduino 홈 컨트롤러

구성품 및 소모품

Arduino 윤
× 1
ControlEverything.com I2C용 4채널 릴레이 컨트롤러
× 1
DHT11 온도 및 습도 센서(4핀)
× 1
저항 10k 옴
× 2
SparkFun RedBot 버저
× 1
범용 트랜지스터 NPN
× 1
LM2596 DC-DC 벅 컨버터
× 1
Amazon Alexa 에코 닷
× 1
Arduino Proto Shield
× 1
USB 웹캠
× 1
흰색 접속 배선함 200mmx155mmx80mm
× 1

필요한 도구 및 기계

납땜 인두(일반)

앱 및 온라인 서비스

Arduino IDE
Amazon Alexa Alexa 기술 키트
Amazon Web Services AWS Lambda
PubNub 게시/구독 API

이 프로젝트 정보

개요

Amazon이 Alexa를 출시하고 Amazon Echo Dot과 같은 장치를 출시하면 자연어를 사용하여 음성 명령으로 제어되는 훌륭한 스마트 홈을 만들기 위한 무한한 옵션이 열립니다.

이 프로젝트는 많은 센서와 장치를 인터넷에 연결할 수 있고 Amazon Alexa 기술을 사용하여 제어할 수 있는 Arduino 홈 컨트롤러를 만듭니다.

내 기술 "Arduino Home Controller를 설치하고 활성화할 수 있습니다. " 쉬운 단계 또는 이 튜토리얼에 따라 기술을 만들 수 있습니다.

지금은 우리가 제어할 것입니다:

<울>
  • 방, 차고, 주방, 거실의 조명 4개
  • <울>
  • 온도 및 습도 센서.
  • <울>
  • 부저 알람.
  • <울>
  • 보안 사진을 찍어 이메일로 보내는 웹캠
  • 이 짧은 비디오 데모에서 Arduino 홈 컨트롤러가 작동하는 것을 볼 수 있습니다. 데모 및 비디오 제안을 위해 각 방의 전구를 시뮬레이션하는 프로토보드에 4개의 LED를 사용합니다.

    원격 모듈을 사용하여 조명을 활성화하려면 내 Arduino 홈 컨트롤러 원격 모듈을 볼 수 있습니다. 이 URL에서 프로젝트를 진행하세요.

    블록 다이어그램

    블록 다이어그램 그림에서 이 프로젝트의 네 가지 주요 구성 요소를 볼 수 있습니다.

    1.- Amazon Echo Dot 음성 명령을 수신하여 AWS(Amazon Web Service)로 보냅니다.

    2.- Amazon 기술과 Lambda 함수가 있는 AWS 모든 명령을 해석합니다.

    기술 이름은 "Arduino 홈 컨트롤러 " 나중에 활성화할 수 있습니다.

    3.- MQTT 브로커 PubNub(c) 클라우드 사용

    이 브로커는 두 개의 채널에서 제어 메시지를 수신합니다. 하나는 설정 값을 위한 것이고 다른 하나는 센서에서 값을 읽는 것입니다.

    PubNub에서 계정을 만들 필요가 없습니다. 데모 제안에 내 계정을 사용할 수 있습니다.

    4.- 홈 컨트롤러 Arduino Yun을 사용하여.

    내부에 이더넷 실드가 있고 일부 작업을 처리하기 위해 Python을 실행할 작은 Linux 머신이 있기 때문에 Arduino Yun을 사용할 것입니다.

    조명 릴레이를 제어하고, 온도 및 습도 센서를 읽고, 알람을 위해 부저를 켜고, 보안 사진을 찍기 위해 웹캠을 조작합니다.

    원격 모듈의 경우 보완적인 Arduino 홈 컨트롤러 원격 모듈을 참조하세요. 이 URL에서 프로젝트를 진행하세요.

    필요한 모든 소프트웨어 설치

    이 시점에서 데모 제안, 내 Alexa 기술을 사용하여 설치 및 사용 또는 개인 기술로 만들 수 있는 두 가지 옵션을 선택할 수 있습니다.

    url을 사용하여 Alexa 앱 탐색 , 메뉴의 스킬 섹션에서 Arduino 검색 목록에서 이름이 "Arduino Home Controller인 기술을 볼 수 있습니다. ", 스킬 카드를 클릭하고 "사용" 버튼을 클릭하여 설치합니다.

    또는 이 링크를 사용하여 Amazon Skill Store로 이동해야 합니다. "활성화" 버튼을 누르세요.

    Arduino로 전송되는 모든 명령에 대한 ID와 같은 이메일 주소를 사용하므로 Amazon 계정을 연결해야 합니다. 이 주소는 이메일 전송에 사용되지 않으며 ID로만 사용됩니다.

    Skill이 설치되어 Amazon 계정에 연결되고 AWS 클라우드에서 내 람다 함수에 연결됩니다.

    1.- 만들기 스킬

    https://developer.amazon.com/home.html

    사이트에서 무료 개발자 계정을 등록하고 생성해야 합니다.

    1.1.- 로그인 후 Alexa로 이동 메뉴 옵션을 선택하고 Alexa Skills Kit에서 선택 "시작하기" 버튼

    1.2.- 다음으로 "새 기술 추가" 버튼을 클릭하여 새 기술을 만듭니다.

    1.3.- 새 Alexa 기술 만들기에서 섹션:

    <울>
  • 선택:맞춤형 상호작용 모델
  • <울>
  • 언어 영어 미국
  • <울>
  • 이름 TestSkill 상점에서 검색하는 데 사용하는 기술 이름입니다.
  • <울>
  • 호출 이름 테스트 기술 Alexa Ask, 알람 켜기 테스트 스킬과 같은 음성 명령을 시작하는 이름입니다.
  • <울>
  • 모든 전역 필드가 모두 옵션 없음으로 설정됨
  • <울>
  • '저장' 클릭
  • 새 기술이 생성되고 새 필드가 표시됩니다. 응용 프로그램 ID

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

    스킬과 람다 함수를 연결하는 데 사용되며 나중에 자습서 섹션 2.5에서 사용합니다.

    1.4.- 여기서 상호 작용 모델은 의도, 슬롯 및 발언의 정의를 기반으로 기술과 상호 작용하는 방법을 정의합니다.

    상호작용 모델에서 메뉴 옵션 이 Json 스키마를 복사하여 인텐트 스키마에 붙여넣습니다.

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

    사용자 정의 슬롯 유형에서 상태 및 HabRoom과 같은 몇 가지 필요한 슬롯을 정의합니다.

    샘플 발화에서 대화 모델과 같은 모든 발화 정의 , 이 목록을 복사하여 붙여넣습니다.

    LightIntent Turn { which} light {light}LightIntent 설정 { which} light {light}AlarmIntent 설정 알람 {alarm}TakePhotoIntent PhotoTakePhotoIntent 가져오기 보안 PhotoGetTemperatureIntent 읽기 TemperatureGetHumidityIntent 읽기 HumidityAboutIntent 정보에 대해 알려주세요 

    다음 섹션인 구성으로 계속 진행하기 전에 스킬과 람다 함수를 모두 연결해야 하므로 Lambda 함수를 생성해야 합니다.

    2.- Lambda 함수 생성

    AWS 콘솔 사용 URL https://aws.amazon.com/console/

    에서 계정을 등록하고 생성해야 합니다.

    2.1.- 서비스 선택 안에 상단 메뉴람다 왼쪽 막대 메뉴에서.

    2.2.- 왼쪽 막대에서 선택 기능 "기능 생성" 버튼을 클릭합니다.

    2.3.- 이 데이터 설정:

    <울>
  • 클릭 저자 처음부터
  • <울>
  • 이름: TestSkillLambda
  • <울>
  • 런타임: Node.js.6.10
  • <울>
  • 역할: 사용자 정의 역할 생성
  • 그러면 다음 값을 선택해야 하는 새 창이 열립니다.

    <울>
  • IAM 역할: Lambda_Basic_Execution
  • <울>
  • 정책 이름: "Create New Role Policy(새 역할 정책 만들기)"를 클릭한 다음 정책을 수정하고 다음을 붙여넣습니다.
  • { "버전":"2012-10-17", "문":[ { "효과":"허용", "작업":[ "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 Skill Kit를 클릭합니다. 상자를 누르고 아래로 스크롤하여 트리거 구성 옵션에서 활성화를 선택합니다. 스킬 ID에서 필드 복사 및 붙여넣기 응용 프로그램 ID 나중에 값을 저장하려면 자습서 섹션 번호 1.3을 참조하세요.

    현재 애플리케이션 또는 스킬 ID를 사용하여 람다 함수를 스킬과 연결하고 있습니다.

    "저장" 버튼을 누르고 Alexa Skills Kit를 누릅니다. 저장되고 기능 람다 알려진 기술과 연결됩니다.

    2.6.- 기능 코드 까지 아래로 스크롤 섹션 및 세트 필드:

    <울>
  • 코드 입력 유형:.zip 파일 업로드
  • <울>
  • 런타임: Node.js 6.10
  • <울>
  • 버튼 "업로드 누르기 " data.zip 파일을 사용하여 기능 코드를 업로드하려면 .
  • 코드 편집기가 열리고 폴더와 파일 업로드가 표시됩니다.

    index.js 파일을 선택합니다. 여기에는 모든 기능 람다 구현이 포함됩니다.

    23행을 변경하고 동일한 응용 프로그램 ID를 복사하여 붙여넣어야 합니다. 튜토리얼 섹션 번호 1.3의 뒷부분에서 사용됩니다.

    "저장" 버튼을 누르면 람다 기능이 활성화되어 스킬 코마드를 받습니다.

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

    페이지 상단의 "저장" 버튼에 ARN(Amazon 리소스 이름)이 표시되며 이는 구성에서 사용할 람다 함수의 ID입니다. 스킬 페이지 섹션

    3.- 스킬 정의로 돌아가기

    3.1.- 구성 선택 섹션, EndPoint AWS Lambda ARN을 선택합니다. 위의 ARN 문자열을 복사하여 기본값에 붙여넣습니다. 들. 이것은 스킬과 람다 함수를 연결하는 마지막 액션이며, 스킬은 함수 람다와 연결되어 있습니다.

    3.2.- 아래로 스크롤하여 계정 연결 섹션을 열고 첫 번째 두 개의 리디렉션 URL을 복사합니다. 보안 프로필을 구성하는 데 필요합니다.

    스킬 구성을 계속하기 전에 Alexa App에서 스킬과 Amazon 계정을 연결하는 데 사용되는 보안 프로필을 정의해야 합니다.

    4.- 보안 프로필 만들기

    기술을 생성하는 데 사용된 동일한 개발자 콘솔에서 앱 및 서비스를 선택합니다. 및 Amazon으로 로그인 "만들기 버튼을 누릅니다. 신규 보안 프로필"

    4.1.- 보안 프로필 관리 페이지에서 모든 OAuth 2.0 보안이 적용된 프로필을 생성하여 기술을 Amazon 계정과 연결할 수 있습니다.

    4.2.- 이 데이터로 모든 필드를 채우십시오:

    <울>
  • 보안 프로필 이름 :TestSkillProfile
  • <울>
  • 보안 프로필 설명 :TestSkill에서 사용하는 프로필
  • <울>
  • 동의 개인정보 보호정책 URL :https://www.amazon.com/gp/help/customer/display.html?nodeId=201809740 이것은 귀하가 사용해야 하는 예입니다.
  • <울>
  • '저장' 버튼을 클릭합니다.
  • 4.3.- 모든 데이터를 저장하거나 보안 프로필을 편집할 때 두 개의 새 필드에 중요한 데이터가 표시됩니다. 클라이언트 ID 클라이언트 비밀번호 . 엔드 스킬 구성에 필요합니다.

    4.4.- 허용 목록 URL을 정의하고 웹 설정 탭을 선택합니다.

    <울>
  • 허용된 출처 :https://layla.amazon.com 및 https://pitangui.amazon.com
  • <울>
  • 허용된 반환 URL :섹션 3.2의 첫 번째 두 URL 추가
  • 5.- 스킬 생성 완료

    5.1.- 기술 정의로 돌아가서 구성 선택 섹션에서 아래로 스크롤하여 계정 연결 .

    <울>
  • 사용자가 계정을 만들도록 허용합니까 : 선택
  • <울>
  • 승인 URL :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에서.
  • <울>
  • 범위 :프로필 , 이 URL에서 설명을 참조하세요.
  • 5.2.- 계정 연결 계속:

    <울>
  • 승인 부여 유형 :인증 코드 부여
  • <울>
  • 액세스 토큰 URI :https://api.amazon.com/auth/o2/token
  • <울>
  • 클라이언트 비밀번호 :클라이언트 비밀번호 복사 및 붙여넣기 섹션 4.3에서.
  • <울>
  • 개인정보취급방침 URL :https://www.amazon.com/gp/help/customer/display.html?nodeId=201809740 이것은 귀하가 사용해야 하는 예입니다.
  • <울>
  • '저장' 및 '다음' 버튼 클릭
  • 5.3.- 글로벌 필드는 기술을 문서화하는 데 사용되는 섹션입니다.

    <울>
  • 인증을 받았을 때 매장에서 기술을 찾을 수 있는 카테고리 선택 , "스마트 홈"
  • <울>
  • 테스트 지침
  • <울>
  • 기술은 모든 국가에서 사용할 수 있습니다. .
  • <울>
  • 간단한 설명
  • <울>
  • 전체 기술 설명
  • <울>
  • 예시 문구
  • <울>
  • 기술을 정의하는 몇 가지 키워드
  • <울>
  • Png o Jpg 아이콘 108x108픽셀
  • <울>
  • Png o Jpg 아이콘 512x512픽셀
  • 5.4.- 마지막 섹션 개인정보 보호 및 규정 준수

    6.- Alexa 앱에서 TestSkill 설치

    6.1- 기술을 저장하면 https://alexa.amazon.com/에서 Alexa 앱으로 이동할 수 있습니다. 왼쪽 막대 메뉴에서 기술 옵션을 선택합니다. , "귀하의 기술" 오른쪽 위 버튼을 클릭하고 개발자 기술 필터를 클릭하십시오. TestSkill을 볼 수 있습니다. 카드. 계정 연결 필수 메시지를 확인하세요.

    6.2.- TestSkill 카드를 클릭하면 설명 페이지에 기술에 대한 모든 정보가 표시됩니다. "활성화" 버튼을 클릭하세요.

    6.3.- 계정 연결 필수 정의 때문에 Amazon 계정과 스킬을 연결하기 위해 Amazon 로그인 자격 증명 페이지로 리디렉션해야 합니다.

    로그인 정보가 확인되면 해당 기술이 Amazon 계정과 연결되었음을 나타내는 이 페이지가 표시됩니다.

    6.4.- 스킬이 완료되고 설치되어 Amazon 계정에 연결되고 Lambda 함수에 연결됩니다.

    Alexa, Test Skill에 질문이라고 테스트할 수 있습니다. 모든 대화 상자가 동일하기 때문에 Arduino 홈 컨트롤러에 오신 것을 환영합니다.

    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 설치 python-openssl 

    터미널에서 사진을 찍는 데 사용할 fswebcam 유틸리티도 필요합니다.

    opkg 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 콘텐츠 조작에 사용DHT_sensor_library --> DHT sensorpubsubclient-master 처리에 사용 --> 연결, 게시 및 PubNub(c) 구독에 사용 

    Arduino IDE 1.6.x를 열고 도구에서 "보드:Arduino Yun"을 선택합니다.

    ArduinoHomeMQTT.ino 파일 로드 그리고 IDE에서 Amazon App 기술의 연결 계정이 활성화된 경우 사용된 Amazon 이메일로 16행을 수정합니다.

    이 옵션은 AWS가 브로커에 MQTT 메시지를 보낼 때 컨트롤러를 식별합니다.

    PubNub(c)에서 컨트롤러를 식별하기 위해 uuid로 라인 50을 변경합니다. 이 사이트로 이동할 수 있습니다. 온라인에서 생성된 붙여넣기 uuid를 복사합니다.

    이제 스케치를 저장하고 업로드하고 Arduino IDE 모니터 창을 열면 PubNub(c) 브로커에 연결된 Arduino Yun과 초기화된 센서를 볼 수 있습니다.

    Alexa Echo Dot의 모든 발화 테스트

    Alexa 기술 "Arduino 홈 컨트롤러 " 스킬은 이 발화 목록을 처리합니다. , 설명 섹션의 Alexa App 기술에서 확인할 수 있습니다. PubNub(c) 브로커에게 수신 및 전송되는 모든 메시지를 테스트하고 Arduino ID 직렬 모니터에서 확인할 수 있습니다.

    조명 제어:

    ==> "Alexa, arduino home에 방 조명 켜달라고 요청"==> "Alexa, arduino home에 방 조명 끄기 요청"==> "Alexa, arduino home에 주방 조명 켜달라고 요청 "==> "Alexa, arduino 집에 주방 조명을 끄라고 요청"==> "Alexa, arduino 집에 차고 조명 켜달라고 요청"==> "Alexa, arduino 집에 차고 조명 끄기 요청"==> " Alexa, arduino 집에 거실 조명을 켜달라고 요청"==> "Alexa, arduino 집에 거실 조명을 끄도록 요청" 

    알람 제어:

    ==> "Alexa, arduino 홈에 알람 켜기"==> "Alexa, arduino 홈에 알람 끄기 요청" 

    스캔 온도 및 습도:

    ==> "Alexa, arduino 집에 온도 읽도록 요청"==> "Alexa, arduino 집에 습도 읽도록 요청" 

    보안 사진을 찍습니다:

    ==> "Alexa, arduino에게 집에 사진을 찍어달라고 요청하세요" 

    정보 및 도움말

    ==> "Alexa, arduino 홈에 대해 문의"==> "Alexa, arduino 홈 도움말에 문의" 

    소프트웨어 세부정보

    내 Github 사이트에서 이 프로젝트의 모든 파일을 다운로드할 수 있습니다.

    설명이 포함된 폴더

    ArduinoHomeMQTT --> Arduino Yun 홈 컨트롤러용 ino 파일 및 라이브러리

    람다 --> AWS Lambda에 배포할 Node.js의 Lambda 함수에는 필요한 모든 node_modules가 포함됩니다. 모든 소프트웨어 설치 섹션의 옵션 2를 참조하십시오.

    파이썬 --> 사진이 첨부된 이메일을 보내기 위한 python 파일

    도식 --> Fritzing(c) 전자 회로도 파일.

    Arduino 홈 컨트롤러 워크플로 보여줘 당신 파일 상호작용 방식 .

    ( 1 ) Amazon Echo Dot이 명령 음성을 전송하고 Arduino Home Controller 기술에 수신됩니다.

    ( 2 ) 스킬 호출 Lambda 함수 파일 index.js .

    ( 3 ) Lambda 함수 파일은 Node.Js의 개발자이며 일부 노드 모듈을 사용합니다. Amazon Web Service(AWS)에서 호스팅되었습니다.

    ( 4 ) 람다 함수는 모든 인텐트를 해석하고 MQTT Json 메시지로 변환하여 PubNub(c) 브로커로 보냅니다. 이 메시지의 형식은 다음과 같습니다.

    { "topic" :Topic_xxxx, "command" :켜짐 또는 꺼짐, "id" :이메일 주소} 

    주제 Topic_xxxx 다음과 같을 수 있습니다.

    Topic_room --> 방 조명 켜기/끄기Topic_livingroom --> 거실 조명 켜기/끄기Topic_kitchen --> 부엌 조명 켜기/끄기Topic_garage --> 차고 조명 켜기/끄기Topic_alarm --> 켜기/ off 알람 주제_온도 --> 온도 주제_습도 읽기 --> 습도 주제_사진 읽기 --> 사진을 찍고 이메일로 보내기 

    명령이 켜져 있을 수 있습니다. 또는 꺼짐 .

    ( 5 ) 메시지는 AHC_IOC_01. 채널을 사용하여 전송됩니다. 채널 AHC_IOC_02 온도 또는 습도 값을 수신하는 데 사용됩니다.

    ( 6 ) Arduino Yun 스케치 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.

    <섹션 클래스="섹션 컨테이너 섹션 축소 가능" id="코드">

    코드

    <울>
  • 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. 판권 소유. 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);};
    깃허브
    https://github.com/jcruzp/ArduinoHomeController

    회로도

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

    제조공정

    1. 웹 운영 DMX 컨트롤러
    2. Arduino 디지털 주사위
    3. Arduino 게임 컨트롤러
    4. 픽셀 체이서 게임
    5. 가정용 식물 관수 시스템
    6. Arduino 반발 전자기 부상
    7. 진공 형광 디스플레이 컨트롤러
    8. 자율 홈 어시스턴트 로봇
    9. NeoMatrix Arduino Pong
    10. Arduino DMX-512 테스터 컨트롤러