raspberry pi

Raspberry Pi and Alexa Based Home Automation Project

Description:

Raspberry Pi and Alexa Based Home Automation- In this article, we will be making a home automation system using Raspberry Pi 3 and Alexa. A relay module will be interfaced with the Raspberry Pi which will be controlled with the help of a voice command. In this project we will be controlling a single relay using voice commands, the code can be modified easily to control more relays. The whole system is connected with the WiFi. There is no physical connection between the Raspberry Pi and Alexa device, this makes the Alexa Echo Dot completely portable. You can keep the Alexa device near to you on a table, or somewhere else. Then all you need is to say the desired command and then the Raspberry Pi will do its job. The same concept can be used to control a Robot using Raspberry Pi and Alexa.

Let’s have a look at the component that we will need for making this project.

Material required for Raspberry Pi Alexa home automation:

Amazon Purchase Links:

12v SPDT type 4-channel relay Module:

8 channel Relay Module

Echo Dot or Echo, Alexa

SD Card Module

8GB Micro SD Card

Micro SD Card Adaptor

Micro usb card cable

Micro USB Cable

Raspberry Pi

raspberry pi 4 4gb kit

Wireless Keyboard and Mouse for raspberry pi:

Night vision Camera for Raspberry Pi:

Oled HDMI touch display for raspberry pi:

TOP10 Best Raspberry Pi Kits

Raspberry Pi and Alexa

 

Other Tools and Components:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!


 

Steps for getting started with our home automation:-

  • Download and Install Rasbian on SD card
  • Enable SSH and Wi-Fi without a monitor
  • Download Putty and access pi3 over SSH.
  • Download putty and access pi3 over SSH
  • Download and run IoT program from link in description.
  • Control Pi attached relay with voice command from Alexa.

 Connection of Raspberry PI3 and Relay:

  1. 5v power of pi3 which is pin four on the board is connected to the relay power pin.
  2. GND pin which is pin six on the board to the ground pin of the relay.
  3. GPIO 4 pin which is pin seven on the board to the relay signal pin.
Raspberry Pi and Alexa
Fig#2 Raspberry pie interfacing with relay module

Getting Started with Raspberry pie and Alexa Project:-

  1. Take mini SD card and connect it to your pc to format and flash it with Rasbian. So we will take the SD card and put it in the SD card reader
  2. After putting in the computer go to SD card drive right click on it to format the SD card in the FAT (default) as shown below.
Raspberry Pi and Alexa
Fig#3 Formatting SD card
  1. Now the formatting is successful press ok and now we are good to go for installing Rasbian.
  2. Now we will go to the website and download Rasbian as per your system. The file will be downloaded in the zip file.
Raspberry Pi and Alexa
Fig#4 Raspberry pie Website

 

  1. Next is to install win32 disk imager click on the link and wait for few second then save it locally.
Raspberry Pi and Alexa
Fig#5 Win32 disk imager
  1. Once both files are download go to the windows download folder and unzip the Rasbian folder.
  2. Next is to open the unzip folder and search for the image file with the .img extension.
  3. We will install the win32 disk imager software in our pc.
  4. When successfully installed Click the Disk imager and open the Rasbian img file in it as shown below.
Raspberry Pi and Alexa
Fig#6 Rasbian Image

 

  1. It will take 20-30 minutes and then when the image is extracted in to the sd card then we need to add file named “ssh” and “wpa_supplicant.conf”.
  2. In wpa_supplicant.conf add the password and SSID Wi-Fi name.
  3. Don’t worry the file is in the description you can simply download both files and copy it in the SD card drive and you are good to go.
Raspberry Pi and Alexa
Fig#7 SH and WIFI Password File
  1. Take the SD card out of the adopter insert it in your raspberry pie 3
  2. Now we are going to connect our raspberry pie to the power source. And boot in for 10 second.
  3. In windows go to run and type run or simply press window key + R.
  4. Type cmd and press enter as shown below.
Raspberry Pi and Alexa
Fig#8 Command Prompt



  1. When the command prompt is open type in “arp –a”. This will show up several Ip address on the screen the one physical address that starts with b-28 usually for raspberrypie3 note it down because it is our raspberrypie3 Wi-Fi Ip address on your network and we will need these to login into our pi3.
Raspberry Pi and Alexa
Fig#9 IP Configuration for Raspberrypie3
  1. Next step is to download the putty software on your system from this link.
Raspberry Pi and Alexa
Fig#10 Putty Software Website
  1. When the software is downloaded open it and install it which will show us this interface.

Raspberry Pi and Alexa

  1. Enter your Ip address in the putty software as shown and press ok.
Raspberry Pi and Alexa
Fig#12 Putty Interface

 

  1. Now in command prompt write down the default username as pi and default password that is raspberry.
  2. Congrats now you are logined in the raspberry pie and form this command prompt you can do whatever you want to do.
Raspberry Pi and Alexa
Fig#13 raspberry pie login
  1. Write down “sudo raspi-config” in the prompt and then move to “Interfacing options” and allow VNC setting as shown in below steps.

 

Raspberry Pi and Alexa

Raspberry Pi and Alexa
Fig#14 Interfacing with VNC


  1. At this point VNC is enabled as shown by command prompt.
  2. Now it is your choice to download and install client VNC which will allow you to have a look at the raspberry pie interface. To download this click here in your system.
  3. Attach VNC client to Raspberry pi3 device by using address copied earlier.
  4. Now Login VNC user pi and password raspberry as used before.
Raspberry Pi and Alexa
Fig#15 VNC Viewer
  1. It will give you a warning but continue and we are in to raspberry pie 3 desktop and we can turn on and off various setting without command prompt.
  2. Now press sudo apt-get update it will ask for permission press y or yes. It will update and upgrade your raspberry pie with latest data using sudo apt-get upgrade  this will take some while so be patient after running these two commands the raspberry pie is at its best to work.
  3. You will need to download the IOT-Pi3-Alexa-Automation-master. you will see that the software will download the zip file and to un zip in press command “unzip nameofile.zip” and press enter.
  4. Next press cd and folder name of the image and press enter “cd IOT-Pi3-Alexa-Automation-master” as the command is completed.
  5. Now enter “sudo pip install virtual env” command prompt to install virtual env on your raspberry pie.
  6. Press in “virtualenv ipaa-env” into your command prompt to make a virtual background for your project
  7. Press in ipaa-env/bin/activate into your command prompt to trigger your project’s virtual environment,
  8. Insert command “sudo python3 RPi_name_port_gpio.py” to execute Pi IOT program. What’s in this python code, I will share it below.

Raspberry Pi and Alexa

Raspberry Pi and Alexa
Fig#15 command execution
  1. Power up the Alexa and give voice command to Alex to discover devices “Alexa discover devices” it will find your system and notice your Raspberry Pi 3 as an IoT device.
  2. “Turn on the office” give this command to turn on the load or simple relay
  3. Turn off the office” give this command to turn off the load or simple relay
Raspberry Pi and Alexa
Fig#15 Raspberry pie with Alexa

IMPORTANT:- You can change the code and say anything for switching relay simply make changes in python code provided in zip file. Below are the files and the codes they have.


CHIP_name_port_gpio.py

""" name_port_gpio.py
 
    This is a demo python file showing how to take paramaters
    from command line for device name, port, and GPIO.
    All credit goes to https://github.com/toddmedema/echo/
    for making the first working versions of this code.
    Usage: chip@chip:~/echo$ sudo python name_port_gpio.py devicename 51000 XIO-P2
    Usage: chip@chip:~/echo$ sudo python name_port_gpio.py coffeebrew 51001 XIO-P3
"""
 
import fauxmo
import logging
import time
import sys
import CHIP_IO.GPIO as GPIO ## Import GPIO library
 
from debounce_handler import debounce_handler
 
logging.basicConfig(level=logging.DEBUG)
 
class device_handler(debounce_handler):
    """Publishes the on/off state requested,
       and the IP address of the Echo making the request.
    """
    #TRIGGERS = {str(sys.argv[1]): int(sys.argv[2])}
    TRIGGERS = {"office": 52000}
 
    def act(self, client_address, state, name):
        print("State", state, "from client @", client_address)
        GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
        GPIO.setup(str(sys.argv[3]), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT
        GPIO.output(str(sys.argv[3]), not state) ## State is true/false
        GPIO.cleanup(str(sys.argv[3]))
        return True
 
if __name__ == "__main__":
    # Startup the fauxmo server
    fauxmo.DEBUG = True
    p = fauxmo.poller()
    u = fauxmo.upnp_broadcast_responder()
    u.init_socket()
    p.add(u)
 
    # Register the device callback as a fauxmo handler
    d = device_handler()
    for trig, port in d.TRIGGERS.items():
        fauxmo.fauxmo(trig, u, p, None, port, d)
 
    # Loop and poll for incoming Echo requests
    logging.debug("Entering fauxmo polling loop")
    while True:
        try:
            # Allow time for a ctrl-c to stop the process
            p.poll(100)
            time.sleep(0.1)
        except Exception as e:
            logging.critical("Critical exception: "+ e.args )
            break


debounce_handler.py

import time




class debounce_handler(object):

    """Use this handler to keep multiple Amazon Echo devices from reacting to

       the same voice command.

    """

    DEBOUNCE_SECONDS = 0.3




    def __init__(self):

        self.lastEcho = time.time()




    def on(self, client_address, name):

        if self.debounce():

            return True

        return self.act(client_address, True, name)




    def off(self, client_address, name):

        if self.debounce():

            return True

        return self.act(client_address, False, name)




    def act(self, client_address, state):

        pass




    def debounce(self):

        """If multiple Echos are present, the one most likely to respond first

           is the one that can best hear the speaker... which is the closest one.

           Adding a refractory period to handlers keeps us from worrying about

           one Echo overhearing a command meant for another one.

        """

        if (time.time() - self.lastEcho) < self.DEBOUNCE_SECONDS:

            return True




        self.lastEcho = time.time()

        return False



example-minimal.py

""" fauxmo_minimal.py - Fabricate.IO




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

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

    "Alexa, device off".




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

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

    those other rooms.




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

    do different things based on which Echo triggered the handler.

"""




import fauxmo

import logging

import time




from debounce_handler import debounce_handler




logging.basicConfig(level=logging.DEBUG)




class device_handler(debounce_handler):

    """Publishes the on/off state requested,

       and the IP address of the Echo making the request.

    """

    TRIGGERS = {"office": 52000}




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

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

        return True




if __name__ == "__main__":

    # Startup the fauxmo server

    fauxmo.DEBUG = True

    p = fauxmo.poller()

    u = fauxmo.upnp_broadcast_responder()

    u.init_socket()

    p.add(u)




    # Register the device callback as a fauxmo handler

    d = device_handler()

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

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




    # Loop and poll for incoming Echo requests

    logging.debug("Entering fauxmo polling loop")

    while True:

        try:

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

            p.poll(100)

            time.sleep(0.1)

        except Exception as e:

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

            break


fauxmo.py

#!/usr/bin/env python




"""

The MIT License (MIT)




Copyright (c) 2015 Maker Musings




Permission is hereby granted, free of charge, to any person obtaining a copy

of this software and associated documentation files (the "Software"), to deal

in the Software without restriction, including without limitation the rights

to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

copies of the Software, and to permit persons to whom the Software is

furnished to do so, subject to the following conditions:




The above copyright notice and this permission notice shall be included in

all copies or substantial portions of the Software.




THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

THE SOFTWARE.

"""




# For a complete discussion, see http://www.makermusings.com

# TODO(semartin): investigate time.sleep usage in here...




import email.utils

import requests

import select

import socket

import struct

import sys

import time

import urllib

import uuid

import logging




# This XML is the minimum needed to define one of our virtual switches

# to the Amazon Echo




SETUP_XML ="""<?xml version=1.0?>

            <root>

             <device>

                <deviceType>urn:Belkin:device:controllee:1</deviceType>

                <friendlyName>%(device_name)s</friendlyName>

                <manufacturer>Belkin International Inc.</manufacturer>

                <modelName>Socket</modelName>

                <modelNumber>3.1415</modelNumber>

                <modelDescription>Belkin Plugin Socket 1.0</modelDescription>\r\n

                <UDN>uuid:Socket-1_0-%(device_serial)s</UDN>

                <serialNumber>221517K0101769</serialNumber>

                <binaryState>0</binaryState>

                <serviceList>

                  <service>

                      <serviceType>urn:Belkin:service:basicevent:1</serviceType>

                      <serviceId>urn:Belkin:serviceId:basicevent1</serviceId>

                      <controlURL>/upnp/control/basicevent1</controlURL>

                      <eventSubURL>/upnp/event/basicevent1</eventSubURL>

                      <SCPDURL>/eventservice.xml</SCPDURL>

                  </service>

              </serviceList>

              </device>

            </root>"""







def dbg(msg):

    logging.debug(msg)







# A simple utility class to wait for incoming data to be

# ready on a socket.




class poller:

    def __init__(self):

        self.poller = select.poll()

        self.targets = {}




    def add(self, target, fileno = None):

        if not fileno:

            fileno = target.fileno()

        self.poller.register(fileno, select.POLLIN)

        self.targets[fileno] = target




    def remove(self, target, fileno = None):

        if not fileno:

            fileno = target.fileno()

        self.poller.unregister(fileno)

        del(self.targets[fileno])




    def poll(self, timeout = 0):

        ready = self.poller.poll(timeout)

        num = len(ready)

        for one_ready in ready:

            target = self.targets.get(one_ready[0], None)

            if target:

                target.do_read(one_ready[0])

        return num







# Base class for a generic UPnP device. This is far from complete

# but it supports either specified or automatic IP address and port

# selection.




class upnp_device(object):

    this_host_ip = None




    @staticmethod

    def local_ip_address():

        if not upnp_device.this_host_ip:

            temp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            try:

                temp_socket.connect(('8.8.8.8', 53))

                upnp_device.this_host_ip = temp_socket.getsockname()[0]

            except:

                upnp_device.this_host_ip = '127.0.0.1'

            del(temp_socket)

            dbg("got local address of %s" % upnp_device.this_host_ip)

        return upnp_device.this_host_ip







    def __init__(self, listener, poller, port, root_url, server_version, persistent_uuid, other_headers = None, ip_address = None):

        self.listener = listener

        self.poller = poller

        self.port = port

        self.root_url = root_url

        self.server_version = server_version

        self.persistent_uuid = persistent_uuid

        self.uuid = uuid.uuid4()

        self.other_headers = other_headers




        if ip_address:

            self.ip_address = ip_address

        else:

            self.ip_address = upnp_device.local_ip_address()




        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.socket.bind((self.ip_address, self.port))

        self.socket.listen(5)

        if self.port == 0:

            self.port = self.socket.getsockname()[1]

        self.poller.add(self)

        self.client_sockets = {}

        self.listener.add_device(self)




    def fileno(self):

        return self.socket.fileno()




    def do_read(self, fileno):

        if fileno == self.socket.fileno():

            (client_socket, client_address) = self.socket.accept()

            self.poller.add(self, client_socket.fileno())

            self.client_sockets[client_socket.fileno()] = (client_socket, client_address)

        else:

            data, sender = self.client_sockets[fileno][0].recvfrom(4096)

            if not data:

                self.poller.remove(self, fileno)

                del(self.client_sockets[fileno])

            else:

                self.handle_request(data, sender, self.client_sockets[fileno][0], self.client_sockets[fileno][1])




    def handle_request(self, data, sender, socket, client_address):

        pass




    def get_name(self):

        return "unknown"




    def respond_to_search(self, destination, search_target):

        dbg("Responding to search for %s" % self.get_name())

        date_str = email.utils.formatdate(timeval=None, localtime=False, usegmt=True)

        location_url = self.root_url % {'ip_address' : self.ip_address, 'port' : self.port}

        message = ("HTTP/1.1 200 OK\r\n"

                  "CACHE-CONTROL: max-age=86400\r\n"

                  "DATE: %s\r\n"

                  "EXT:\r\n"

                  "LOCATION: %s\r\n"

                  "OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n"

                  "01-NLS: %s\r\n"

                  "SERVER: %s\r\n"

                  "ST: %s\r\n"

                  "USN: uuid:%s::%s\r\n" % (date_str, location_url, self.uuid, self.server_version, search_target, self.persistent_uuid, search_target))

        if self.other_headers:

            for header in self.other_headers:

                message += "%s\r\n" % header

        message += "\r\n"

        temp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        temp_socket.sendto(bytes(message, 'UTF-8'), destination)

        #print("Responding to search-->" + message )   




# This subclass does the bulk of the work to mimic a WeMo switch on the network.




class fauxmo(upnp_device):

    @staticmethod

    def make_uuid(name):

        return ''.join(["%x" % sum([ord(c) for c in name])] + ["%x" % ord(c) for c in "%sfauxmo!" % name])[:14]




    def __init__(self, name, listener, poller, ip_address, port, action_handler = None):

        self.serial = self.make_uuid(name)

        self.name = name

        self.switchStatus=0

        self.ip_address = ip_address

        persistent_uuid = "Socket-1_0-" + self.serial

        other_headers = ['X-User-Agent: redsonic']

        upnp_device.__init__(self, listener, poller, port, "http://%(ip_address)s:%(port)s/setup.xml", "Unspecified, UPnP/1.0, Unspecified", persistent_uuid, other_headers=other_headers, ip_address=ip_address)

        if action_handler:

            self.action_handler = action_handler

        else:

            self.action_handler = self

        dbg("FauxMo device '%s' ready on %s:%s" % (self.name, self.ip_address, self.port))




    def get_name(self):

        return self.name




    def handle_request(self, data, sender, socket, client_address):

        print("##################################   handle_reques #######################")

        print(data)

        print("##################################   handle_reques #######################")

        data = data.decode('utf-8')

        success = False

       

        if data.find('GET /setup.xml HTTP/1.1') == 0:

            dbg("Responding to setup.xml for %s" % self.name)

            xml = SETUP_XML % {'device_name' : self.name, 'device_serial' : self.serial}

            date_str = email.utils.formatdate(timeval=None, localtime=False, usegmt=True)

            message = ("HTTP/1.1 200 OK\r\n"

                       "CONTENT-LENGTH: %d\r\n"

                       "CONTENT-TYPE: text/xml\r\n"

                       "DATE: %s\r\n"

                       "LAST-MODIFIED: Sat, 01 Jan 2000 00:01:15 GMT\r\n"

                       "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n"

                       "X-User-Agent: redsonic\r\n"

                       "CONNECTION: close\r\n"

                       "\r\n"

                       "%s" % (len(xml), date_str, xml))

            socket.send(bytes(message, 'UTF-8'))

            #print("responsed to setup-->" + message)

       

        elif data.find('SOAPACTION: "urn:Belkin:service:basicevent:1#SetBinaryState"') != -1:

        #elif data.find('urn:Belkin:service:basicevent:1') != -1:

        #elif data.find("SetBinaryState") != -1:

           

            if data.find('SetBinaryState') != -1:

                if data.find('<BinaryState>1</BinaryState>') != -1:

                    # on

                    dbg("Responding to ON for %s" % self.name)

                    success = self.action_handler.on(client_address[0], self.name)

                    self.switchStatus=1

                elif data.find('<BinaryState>0</BinaryState>') != -1:

                    # off

                    dbg("Responding to OFF for %s" % self.name)

                    success = self.action_handler.off(client_address[0], self.name)

                    self.switchStatus=0

                else:

                    dbg("Unknown Binary State request:")

                    dbg(data)

                               

            if success:

                # The echo is happy with the 200 status code and doesn't

                # appear to care about the SOAP response body

                #dbg("Unknown Binary State request:")

                soap = ""

                date_str = email.utils.formatdate(timeval=None, localtime=False, usegmt=True)

                message = ("HTTP/1.1 200 OK\r\n"

                           "CONTENT-LENGTH: %d\r\n"

                           "CONTENT-TYPE: text/xml charset=\"utf-8\"\r\n"

                           "DATE: %s\r\n"

                           "EXT:\r\n"

                           "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n"

                           "X-User-Agent: redsonic\r\n"

                           "CONNECTION: close\r\n"

                           "\r\n"

                           "%s" % (len(soap), date_str, soap))

                socket.send(bytes(message, 'UTF-8'))

               

        elif data.find('GetBinaryState'):

            #if data.find('<BinaryState>1</BinaryState>') != -1:

            #    switch_sate="1"

            #else:

            #    switch_sate="0"

            soap = """<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

                <s:Body>

                    <u:GetBinaryStateResponse

                    xmlns:u="urn:Belkin:service:basicevent:1">

                    <BinaryState>"""+ str(self.switchStatus) +"""</BinaryState>

                    </u:GetBinaryStateResponse>

                </s:Body></s:Envelope>"""

           

           

            date_str = email.utils.formatdate(timeval=None, localtime=False, usegmt=True)

            message = ("HTTP/1.1 200 OK\r\n"

                       "CONTENT-LENGTH: %d\r\n"

                       "CONTENT-TYPE: text/xml charset=\"utf-8\"\r\n"

                       "DATE: %s\r\n"

                       "EXT:\r\n"

                       "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n"

                       "X-User-Agent: redsonic\r\n"

                       "CONNECTION: close\r\n"

                       "\r\n"

                       "%s" % (len(soap), date_str, soap))

            socket.send(bytes(message, 'UTF-8'))

            print("##################################   response #######################")

            print(data)




        else:

            dbg(data)




    def on(self):

        return False




    def off(self):

        return True







# Since we have a single process managing several virtual UPnP devices,

# we only need a single listener for UPnP broadcasts. When a matching

# search is received, it causes each device instance to respond.

#

# Note that this is currently hard-coded to recognize only the search

# from the Amazon Echo for WeMo devices. In particular, it does not

# support the more common root device general search. The Echo

# doesn't search for root devices.




class upnp_broadcast_responder(object):

    TIMEOUT = 0




    def __init__(self):

        self.devices = []




    def init_socket(self):

        ok = True

        self.ip = '239.255.255.250'

        self.port = 1900

        try:

            #This is needed to join a multicast group

            self.mreq = struct.pack("4sl",socket.inet_aton(self.ip),socket.INADDR_ANY)




            #Set up server socket

            self.ssock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)

            self.ssock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)




            try:

                self.ssock.bind(('',self.port))

            except Exception:

                dbg("WARNING: Failed to bind %s:%d: %s" , (self.ip,self.port))

                ok = False




            try:

                self.ssock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,self.mreq)

            except Exception:

                dbg('WARNING: Failed to join multicast group:')

                ok = False




        except Exception:

            dbg("Failed to initialize UPnP sockets:")

            return False

        if ok:

            dbg("Listening for UPnP broadcasts")




    def fileno(self):

        return self.ssock.fileno()




    def do_read(self, fileno):

        data, sender = self.recvfrom(1024)

        data = data.decode('utf-8')

        if data:

            #if data.find('M-SEARCH') == 0 and data.find('urn:Belkin:device:**') != -1:

            if data.find('M-SEARCH') >= 0 and data.find('urn:Belkin:device:**') >0 or data.find('n:Belkin:device:**') >0 or data.find('upnp:rootdevice') >0:

                for device in self.devices:

                    time.sleep(0.5)

                    device.respond_to_search(sender, 'urn:Belkin:device:**')

            else:

                pass




    #Receive network data

    def recvfrom(self,size):

        if self.TIMEOUT:

            self.ssock.setblocking(0)

            ready = select.select([self.ssock], [], [], self.TIMEOUT)[0]

        else:

            self.ssock.setblocking(1)

            ready = True




        try:

            if ready:

                return self.ssock.recvfrom(size)

            else:

                return False, False

        except Exception:

            print('error')

            return False, False




    def add_device(self, device):

        self.devices.append(device)

        dbg("UPnP broadcast listener: new device registered")







# This is an example handler class. The fauxmo class expects handlers to be

# instances of objects that have on() and off() methods that return True

# on success and False otherwise.

#

# This example class takes two full URLs that should be requested when an on

# and off command are invoked respectively. It ignores any return data.




class dummy_handler(object):

    def __init__(self, name):

        self.name = name




    def on(self):

        print(self.name, "ON")

        return True




    def off(self):

        print(self.name, "OFF")

        return True







class rest_api_handler(object):

    def __init__(self, on_cmd, off_cmd):

        self.on_cmd = on_cmd

        self.off_cmd = off_cmd




    def on(self):

        r = requests.get(self.on_cmd)

        return r.status_code == 200




    def off(self):

        r = requests.get(self.off_cmd)

        return r.status_code == 200




if __name__ == "__main__":

    FAUXMOS = [

        ['office lights', dummy_handler("officelight")],

        ['kitchen lights', dummy_handler("kitchenlight")],

    ]




    if len(sys.argv) > 1 and sys.argv[1] == '-d':

        DEBUG = True




    # Set up our singleton for polling the sockets for data ready

    p = poller()




    # Set up our singleton listener for UPnP broadcasts

    u = upnp_broadcast_responder()

    u.init_socket()




    # Add the UPnP broadcast listener to the poller so we can respond

    # when a broadcast is received.

    p.add(u)




    # Create our FauxMo virtual switch devices

    for one_faux in FAUXMOS:

        switch = fauxmo(one_faux[0], u, p, None, 0, action_handler = one_faux[1])




    dbg("Entering main loop\n")




    while True:

        try:

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

            p.poll(100)

            time.sleep(0.1)

        except Exception:

            print('error1')

            break


RPi_name_port_gpio.py

""" name_port_gpio.py




    This is a demo python file showing how to take paramaters

    from command line for device name, port, and GPIO.

    All credit goes to https://github.com/toddmedema/echo/

    for making the first working versions of this code.

"""




import fauxmo

import logging

import time

import sys

import RPi.GPIO as GPIO ## Import GPIO library




from debounce_handler import debounce_handler




logging.basicConfig(level=logging.DEBUG)




class device_handler(debounce_handler):

    """Publishes the on/off state requested,

       and the IP address of the Echo making the request.

    """

    #TRIGGERS = {str(sys.argv[1]): int(sys.argv[2])}

    #TRIGGERS = {"Light": 52000}

    TRIGGERS = {"LED": 52000,"FAN":51000}




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

        print("State", state, "from client @", client_address)

        # GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

        # GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

        # GPIO.output(int(7), state) ## State is true/false

        if name=="kitchen":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(7), state) ## State is true/false

        elif name =="living room":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(11), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(11), state) ## State is true/false

        else:

            print("Device not found!")













        return True




if __name__ == "__main__":

    # Startup the fauxmo server

    fauxmo.DEBUG = True

    p = fauxmo.poller()

    u = fauxmo.upnp_broadcast_responder()

    u.init_socket()

    p.add(u)




    # Register the device callback as a fauxmo handler

    d = device_handler()

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

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




    # Loop and poll for incoming Echo requests

    logging.debug("Entering fauxmo polling loop")

    while True:

        try:

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

            p.poll(100)

            time.sleep(0.1)

        except Exception as e:

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

            break


RPi_name_port_gpio_8_Relays.py

""" name_port_gpio.py




    This is a demo python file showing how to take paramaters

    from command line for device name, port, and GPIO.

    All credit goes to https://github.com/toddmedema/echo/

    for making the first working versions of this code.

"""




import fauxmo

import logging

import time

import sys

import RPi.GPIO as GPIO ## Import GPIO library




from debounce_handler import debounce_handler




logging.basicConfig(level=logging.DEBUG)




class device_handler(debounce_handler):

    """Publishes the on/off state requested,

       and the IP address of the Echo making the request.

    """

    #TRIGGERS = {str(sys.argv[1]): int(sys.argv[2])}

    #TRIGGERS = {"office": 52000}

    TRIGGERS = {"kitchen": 52000, "living room": 51000, "office": 53000, "room": 52002, "tv": 52003, "pc": 52004,

                "xbox": 52005, "light": 52006}




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

        print("State", state, "from client @", client_address)

        # GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

        # GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

        # GPIO.output(int(7), state) ## State is true/false




        ############# Uncomment this code to revers the relay polarity ############

        # if state==True:

        #     state = False

        # else:

        #     state = True

        ############# Uncomment this code to revers the relay polarity ############




        if name=="kitchen":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(7), state) ## State is true/false

        elif name =="living room":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(11), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(11), state) ## State is true/false

        elif name =="office":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(13), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(13), state) ## State is true/false

        elif name == "room":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(5), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(5), state)  ## State is true/false

        elif name == "tv":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(15), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(15), state)  ## State is true/false

        elif name == "pc":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(8), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(8), state)  ## State is true/false

        elif name == "xbox":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(12), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(12), state)  ## State is true/false

        elif name == "light":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(10), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(10), state)  ## State is true/false

        else:

            print("Device not found!")













        return True




if __name__ == "__main__":

    # Startup the fauxmo server

    fauxmo.DEBUG = True

    p = fauxmo.poller()

    u = fauxmo.upnp_broadcast_responder()

    u.init_socket()

    p.add(u)




    # Register the device callback as a fauxmo handler

    d = device_handler()

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

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




    # Loop and poll for incoming Echo requests

    logging.debug("Entering fauxmo polling loop")

    while True:

        try:

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

            p.poll(100)

            time.sleep(0.1)

        except Exception as e:

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

            break



RPi_name_port_gpio_8_Relays2.py

""" name_port_gpio.py




    This is a demo python file showing how to take paramaters

    from command line for device name, port, and GPIO.

    All credit goes to https://github.com/toddmedema/echo/

    for making the first working versions of this code.

"""




import fauxmo

import logging

import time

import sys

import RPi.GPIO as GPIO ## Import GPIO library




from debounce_handler import debounce_handler




logging.basicConfig(level=logging.DEBUG)




class device_handler(debounce_handler):

    """Publishes the on/off state requested,

       and the IP address of the Echo making the request.

    """

    #TRIGGERS = {str(sys.argv[1]): int(sys.argv[2])}

    #TRIGGERS = {"office": 52000}

    TRIGGERS = {"kitchen": 52000, "living room": 51000, "office": 53000, "room": 52002, "tv": 52003, "pc": 52004,

                "xbox": 52005, "light": 52006}




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

        print("State", state, "from client @", client_address)

        # GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

        # GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

        # GPIO.output(int(7), state) ## State is true/false




        ############# Uncomment this code to revers the relay polarity ############

        if state==True:

            state = False

        else:

            state = True

        ############# Uncomment this code to revers the relay polarity ############




        if name=="kitchen":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(7), state) ## State is true/false

        elif name =="living room":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(11), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(11), state) ## State is true/false

        elif name =="office":

            GPIO.setmode(GPIO.BOARD) ## Use board pin numbering

            GPIO.setup(int(13), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(13), state) ## State is true/false

        elif name == "room":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(5), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(5), state)  ## State is true/false

        elif name == "tv":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(16), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(16), state)  ## State is true/false

        elif name == "pc":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(8), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(8), state)  ## State is true/false

        elif name == "xbox":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(12), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(12), state)  ## State is true/false

        elif name == "light":

            GPIO.setmode(GPIO.BOARD)  ## Use board pin numbering

            GPIO.setup(int(10), GPIO.OUT)  ## Setup GPIO Pin to OUTPUT

            GPIO.output(int(10), state)  ## State is true/false

        else:

            print("Device not found!")













        return True




if __name__ == "__main__":

    # Startup the fauxmo server

    fauxmo.DEBUG = True

    p = fauxmo.poller()

    u = fauxmo.upnp_broadcast_responder()

    u.init_socket()

    p.add(u)




    # Register the device callback as a fauxmo handler

    d = device_handler()

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

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




    # Loop and poll for incoming Echo requests

    logging.debug("Entering fauxmo polling loop")

    while True:

        try:

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

            p.poll(100)

            time.sleep(0.1)

        except Exception as e:

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

            break

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button