LEONARDO HERNANDEZ
Created February 23, 2018

My Remote Home

Integration of the Arduino Uno to the Alexa Skill platform using the Raspberry Pi to take control of my house

My Remote Home

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Arduino Ethernet Rev. 3
Arduino Ethernet Rev. 3
×1
Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
×1
Temperature Sensor
Temperature Sensor
×1
LED (generic)
LED (generic)
×3
Resistor 10k ohm
Resistor 10k ohm
×3
Relay (generic)
×4
Resistor 1k ohm
Resistor 1k ohm
×4
General Purpose Transistor NPN
General Purpose Transistor NPN
×4
1N4007 – High Voltage, High Current Rated Diode
1N4007 – High Voltage, High Current Rated Diode
×4

Software apps and online services

Arduino IDE
Arduino IDE
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit
Reverb for Amazon Alexa
ngrok
flask-ask
Raspbian
Raspberry Pi Raspbian
HERCULES SETUP UTILITY

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Mastech MS8217 Autorange Digital Multimeter
Digilent Mastech MS8217 Autorange Digital Multimeter

Story

Read more

Schematics

My Remote Home

Code

MyRemoteHome.ino

Arduino
It controls the air conditioning, the light and a feeder of dogs and acquires the temperature, and communicates with the Raspberry Pi via UDP protocol
#include <SPI.h>         // needed for Arduino versions later than 0018
#include <Ethernet.h>
#include <EthernetUdp.h>         // UDP library from: bjoern@cs.stanford.edu 12/30/2008
#include <EEPROM.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(10, 1, 10, 112);

unsigned int localPort = 8888;      // local port to listen on

int sensorReading =0;
int AlarmaReading=0;
int ControlReading = 0;
int Page=1;
int temp=0;
int pos=0;
int temp_min=0;
int temp_max=0;
char temp_var;
int ac=0;
int fan=0;
byte value;
char temperature[3];
String str;
String udp_rx;


// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  //buffer to hold incoming packet,
char  ReplyBuffer[] = "acknowledged";       // a string to send back



// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
  // start the Ethernet and UDP:
  Ethernet.begin(mac, ip);
  Udp.begin(localPort);

  Serial.begin(9600);
  pinMode(6, INPUT);
  pinMode(7, INPUT);
  pinMode(2, OUTPUT);  
  pinMode(3, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(8, OUTPUT);
  value = EEPROM.read(0);
  digitalWrite(2, value);
  value = EEPROM.read(1);
  digitalWrite(3, value);
  temp_min = EEPROM.read(2);
  temp_max = EEPROM.read(3);
  ac=EEPROM.read(4);
  fan=EEPROM.read(5);
  temp= analogRead(A0);
  temp_min=temp;
}

void loop() {

  // if there's data available, read a packet
  int packetSize = Udp.parsePacket();
  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i = 0; i < 4; i++) {
      Serial.print(remote[i], DEC);
      if (i < 3) {
        Serial.print(".");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
    Serial.println("Contents:");
    Serial.println(packetBuffer);
    
    udp_rx=String(packetBuffer);
    
    
    if (udp_rx.indexOf("TEMP_LR?")>=0){
      sensorReading = 0.486*analogRead(A0);
      Serial.print(sensorReading);
      str=String(sensorReading);
      str.toCharArray(ReplyBuffer,3);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write(ReplyBuffer);
      Udp.endPacket();

    }
    
     if (udp_rx.indexOf("TEMP_MIN?")>=0){
      sensorReading = 0.486*temp_min;
      Serial.print(sensorReading);
      str=String(sensorReading);
      str.toCharArray(ReplyBuffer,3);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write(ReplyBuffer);
      Udp.endPacket();

    }
     if (udp_rx.indexOf("TEMP_MAX?")>=0){
      sensorReading = 0.486*temp_max;
      Serial.print(sensorReading);
      str=String(sensorReading);
      str.toCharArray(ReplyBuffer,3);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write(ReplyBuffer);
      Udp.endPacket();

    }
    
   if (udp_rx.indexOf("AC_ON")>=0){
      ac=HIGH;
      Serial.print("AC ON");
      EEPROM.write(4, ac);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("AC ON");
      Udp.endPacket();
   }        
   if (udp_rx.indexOf("AC_OFF")>=0){
      ac=LOW;
      Serial.print("AC OFF");
      EEPROM.write(4, ac);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("AC OFF");
      Udp.endPacket();
   }            
   if (udp_rx.indexOf("FAN_ON")>=0){
      fan=LOW;
      Serial.print("FAN ON");
      EEPROM.write(5, fan);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("FAN ON");
      Udp.endPacket();
   }                      
   if (udp_rx.indexOf("FAN_AUTO")>=0){
      fan=HIGH;
      Serial.print("FAN AUTO");
       EEPROM.write(5, fan);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("FAN AUTO");
      Udp.endPacket();
   }        
   if (udp_rx.indexOf("TEMP_UP")>=0){
      temp_min=temp_min+2;
      temp_max=temp_min+6;
      sensorReading=0.486*temp_min;
      Serial.print(sensorReading);
      EEPROM.write(2, temp_min);
      EEPROM.write(3, temp_max);
      str=String(sensorReading);
      str.toCharArray(ReplyBuffer,3);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write(ReplyBuffer);
      Udp.endPacket();
   }             
   if (udp_rx.indexOf("TEMP_DOWN")>=0){
      temp_min=temp_min-2;
      temp_max=temp_min+6;
      sensorReading=0.486*temp_min;
      Serial.print(sensorReading);
      EEPROM.write(2, temp_min);
      EEPROM.write(3, temp_max);
      str=String(sensorReading);
      str.toCharArray(ReplyBuffer,3);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write(ReplyBuffer);
      Udp.endPacket();
   }             
   if (udp_rx.indexOf("LIGHT_ON")>=0){
      Serial.print("LIGHT ON");
      digitalWrite(2, HIGH);
      EEPROM.write(0, HIGH);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("LIGHT ON");
      Udp.endPacket();
   }
   if (udp_rx.indexOf("LIGHT_OFF")>=0){
      Serial.print("LIGHT OFF");
      digitalWrite(2, LOW);
      EEPROM.write(0, LOW);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("LIGHT OFF");
      Udp.endPacket();
    }
    if (udp_rx.indexOf("FEED_BUDDY")>=0){
      Serial.print("FEED_DOG_OPEN");
      digitalWrite(3, HIGH);
      EEPROM.write(1, HIGH);
      // send a reply to the IP address and port that sent us the packet we received
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      //Udp.write(ReplyBuffer);
      Udp.write("FEEDING BUDDY");
      Udp.endPacket();
      delay(4000);
      Serial.print("FEED_DOG_CLOSE");
      digitalWrite(3, LOW);
      EEPROM.write(1, LOW);
//      // send a reply to the IP address and port that sent us the packet we received
//      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
//      //Udp.write(ReplyBuffer);
//      Udp.write("FEED_DOG_CLOSE");
//      Udp.endPacket();
          
    }
//     if (udp_rx.indexOf("ALARMA")>=0){
//      Serial.print("ALARMA");
//      if (digitalRead(6)==HIGH){
//      
//        //EEPROM.write(0, LOW);
//        // send a reply to the IP address and port that sent us the packet we received
//        Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
//        //Udp.write(ReplyBuffer);
//        Udp.write("ALARMA");
//        Udp.endPacket();
//      }
//    }
   }
  delay(10);
      temp= analogRead(A0);
    //delay(1000);
    if(ac==HIGH){
      
//       Serial.write(char(temp));
//        Serial.write(char( 0.486*temp_min));
//        Serial.write(char( 0.486*temp_max));
        if(temp > temp_max){
          digitalWrite(5, HIGH);  //Compressor  ON
          digitalWrite(8, HIGH);  //FAN  ON
        }
        if(temp< temp_min){
          digitalWrite(5, LOW);  //Compressor  OFF
          if(fan==LOW){
            digitalWrite(8, HIGH);  //FAN  ON
          }
          else{
             digitalWrite(8, LOW);  //FAN  OFF
          }
        }
        
        
           
      
    }
    else{
      
      digitalWrite(5, LOW);  //Compressor  OFF
      digitalWrite(8, LOW);  //FAN  OFF
      
    }
}

MyRemoteHome.py

Python
Run the server Flask-ask and establish the UDP communication with the Arduino Uno
from flask import Flask
from flask_ask import Ask, statement, convert_errors
import RPi.GPIO as GPIO
import logging
import socket
import time
import sys



 




app = Flask(__name__)
ask = Ask(app, '/')

def udp_connection(message):

   # Create a UDP socket
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   server_address = ('10.1.10.112', 8888)
   try:

      # Send data
      # print >>sys.stderr, 'sending "%s"' % message
      sent = sock.sendto(message, server_address)

      # Receive response
      # print >>sys.stderr, 'waiting to receive'

    
      data, server = sock.recvfrom(4096)
      # print >>sys.stderr, 'received "%s"' % data

   finally:
     # print >>sys.stderr, 'closing socket'
      
  
      sock.close()

   return(data)
   

    


logging.getLogger("flask_ask").setLevel(logging.DEBUG)


@ask.intent('EnvironmentIntent', mapping={'device':'device','status':'status','variable':'variable','location':'location','control':'control'})
def ac_control(device,status,variable,location,control):

   if device in ['ac','air conditioner','fan']:
      if device in ['ac','air conditioner']:message = "AC_"
      if device in ['fan']:message = "FAN_"
     
      if status in ['on', 'high']:message = message + "ON"
      if status in ['off', 'low']:message = message + "OFF"
      if status in ['auto']:message = message + "AUTO"
      data=udp_connection(message)
      return statement('Turning {}'.format(data))
      

   if variable in ['temperature','setting',]:
      if location in['living room','sitting room']:
         message = "TEMP_LR?"
         data=udp_connection(message)
         return statement('The temperature of the {} is {} degrees Celsius'.format(location,data))
      if variable in['setting', 'programming']:
         message = "TEMP_MIN?"
         data=udp_connection(message)
         return statement('The temperature set of the {} is {} degrees Celsius'.format(location,data))


   if control in ['up','go up','down','go down']:
      if control in ['up', 'go up']:
         message = "TEMP_UP"
      if control in ['down', 'go down']:
         message = "TEMP_DOWN"
      data=udp_connection(message)
      return statement('The temperature of the air conditioning was set in {} degrees Celsius'.format(data))
   else:
      return statement('Device not valid.')
       


##if __name__ == '__main__':
####    port = 5000  #the custom port you want, 5000 must be open/or port forward from the router
####    app.run(host='0.0.0.0', port=port)
##    app.run(debug=True)


@ask.intent('IluminationIntent', mapping={'status': 'status','device': 'device', 'location': 'location'})
def ilumination_control(status,device,location):

      if device in ['lamp', 'light']:
         if status in ['on', 'high']:message = "LIGHT_ON"
         if status in ['off', 'low']:message = "LIGHT_OFF"
         data=udp_connection(message)
         return statement('Turning {} {}'.format(device,status))
      else:
         return statement('Device not valid.')
   


##if __name__ == '__main__':
##    port = 5000  #the custom port you want, 5000 must be open/or port forward from the router
##    app.run(host='0.0.0.0', port=port)

@ask.intent('MydogIntent', mapping={'food': 'food'})
def mydogfood_control(food):

      if food in ['meal','water','feed']:
         if food in ['meal','feed']:message = "FEED_BUDDY"
         data=udp_connection(message)
         return statement('{}'.format(data))
      else:
         return statement('Device not valid.')
   


if __name__ == '__main__':
##    port = 5000  #the custom port you want, 5000 must be open/or port forward from the router
##    app.run(host='0.0.0.0', port=port)
    app.run(debug=True)
    

Interaction Model

JSON
Alexa Skills: Intents and Slot Types
{
  "languageModel": {
    "types": [
      {
        "name": "CONTROLS",
        "values": [
          {
            "id": null,
            "name": {
              "value": "up",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "down",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "DEVICES",
        "values": [
          {
            "id": null,
            "name": {
              "value": "fan",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "lamp",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "ac",
              "synonyms": [
                "air conditioner",
                "air conditioning"
              ]
            }
          }
        ]
      },
      {
        "name": "FOOD",
        "values": [
          {
            "id": null,
            "name": {
              "value": "water",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "feed",
              "synonyms": [
                "meal"
              ]
            }
          }
        ]
      },
      {
        "name": "LOCATIONS",
        "values": [
          {
            "id": null,
            "name": {
              "value": "living room",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "kitchen",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "balcony",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "STATUS",
        "values": [
          {
            "id": null,
            "name": {
              "value": "on",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "off",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "auto",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "VARIABLES",
        "values": [
          {
            "id": null,
            "name": {
              "value": "temperature",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "humidity",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "setting",
              "synonyms": []
            }
          }
        ]
      }
    ],
    "intents": [
      {
        "name": "AMAZON.CancelIntent",
        "samples": []
      },
      {
        "name": "AMAZON.HelpIntent",
        "samples": []
      },
      {
        "name": "AMAZON.StopIntent",
        "samples": []
      },
      {
        "name": "EnvironmentIntent",
        "samples": [
          "to turn the {device} {status}",
          "what is the {variable} of the {location}",
          "{control} the temperature of the air conditioning",
          "{control} the temperature of the ac",
          "what is the {variable} of the of the ac",
          "which is the {variable} of ac",
          "which is the {variable} of the air conditioning"
        ],
        "slots": [
          {
            "name": "device",
            "type": "DEVICES"
          },
          {
            "name": "status",
            "type": "STATUS"
          },
          {
            "name": "variable",
            "type": "VARIABLES"
          },
          {
            "name": "location",
            "type": "LOCATIONS"
          },
          {
            "name": "control",
            "type": "CONTROLS"
          }
        ]
      },
      {
        "name": "IluminationIntent",
        "samples": [
          "to turn {status}  the {device} in the {location}"
        ],
        "slots": [
          {
            "name": "status",
            "type": "STATUS"
          },
          {
            "name": "device",
            "type": "DEVICES"
          },
          {
            "name": "location",
            "type": "LOCATIONS"
          }
        ]
      },
      {
        "name": "MydogIntent",
        "samples": [
          "to {food} Buddy",
          "to give Buddy {food}"
        ],
        "slots": [
          {
            "name": "food",
            "type": "FOOD"
          }
        ]
      }
    ],
    "invocationName": "my home"
  }
}

Credits

LEONARDO HERNANDEZ

LEONARDO HERNANDEZ

0 projects • 0 followers
I am Electronic Engineer, I work in the Telecommunication Area working with DWDM, Optical Fibers, Antenna, Microwave & Radio Frequency

Comments