Remotely switch On/Off an LED using PubNub and Raspberry PI

Have you ever wanted to control your electrical devices with just the touch of a screen. This can be done via Internet of Things.

The Internet of things (IoT) is the inter-networking of physical devices, vehicles (also referred to as “connected devices” and “smart devices”), buildings, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data.

In this tutorial you will learn how to control a led bulb using your phone or computer from anywhere. The Internet of things (IoT) is the inter-networking of physical devices, vehicles (also referred to as “connected devices” and “smart devices”), buildings, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data.For setup you will need :

  • Raspberry PI 3 or 2
  • Led
  • Male/Female jumper wires
  • Register (220Ω)
Raspberry PI-3
Raspberry PI-3

 

Step 1:

Setup Raspberry PI circuit for LED. Please refer the image below to complete the circuit.
Circuit
Circuit

Step 2:

We are using the RASPBIAN operating system. You can easily download from here :
We are using the python gpiozero liberary to control the LED. For this you have to install python gpiozero library.
Open terminal and execute following commands:

sudo apt-get update
sudo apt-get install python3-gpiozero (recommended) //Python 3

                OR

sudo apt-get install python-gpiozero                //Python 2

Step 3:

Create a python script file in your RASPBIAN operating system to control the LED. Here we name this file to smart-led.py.

from gpiozero import LED
led = LED(17) (Here 17 is the GPIO pin)

led.on() //On the LED
led.off()// Off the LED

Now open the termincal and execute the python file using

python smart-led.py

Hurray !! Now you can control the LED.

Step 4:

Now we are introducing the Pubnub so that you can control your devices from anywhere. For this you have to install pubnub Libraries and Drivers.
Open terrminal and execute following commands:
Install pip    :

sudo apt-get install python-pip

Install pubnub :

sudo pip install pubnub

Step 5: 

Create a free account in Pubnub so that you can get the subscribe_key and the publish_key.
You can create your Pubnub account from here
Pubnub-Dashboard
Pubnub-Dashboard

Step 6:

Now we are going to integrate Pubnub libraries in your python script


from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()

pnconfig.subscribe_key = <Your PUBNUB subscribe key>
pnconfig.publish_key = <Your PUBNUB publish key>

pubnub = PubNub(pnconfig)

You have to write the pubnub subscriber

def my_publish_callback(envelope, status):
    # Check whether request successfully completed or not
    if not status.is_error():
        pass  # Message successfully published to specified channel.
    else:
        pass  # Handle message publish error. Check 'category' property to find out possible issue
        # because of which request did fail.
        # Request can be resent using: [status retry];

class MySubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass  # handle incoming presence data

    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory:
            pass  # This event happens when radio / connectivity is lost

        elif status.category == PNStatusCategory.PNConnectedCategory:
            # Connect event. You can do stuff like publish, and know you'll get it.
            # Or just use the connected event to confirm you are subscribed for
            # UI / internal notifications, etc
            pubnub.publish().channel("awesomeChannel").message("hello!!").async(my_publish_callback)
        elif status.category == PNStatusCategory.PNReconnectedCategory:
            pass
            # Happens as part of our regular operation. This event happens when
            # radio / connectivity is lost, then regained.
        elif status.category == PNStatusCategory.PNDecryptionErrorCategory:
            pass
            # Handle message decryption error. Probably client configured to
            # encrypt messages and on live data feed it received plain text.

    def message(self, pubnub, message):
#        print(message.message)
        if 'status' in message.message:
            print(message.message['status'])
            whatToDo(message.message['status'])
        pass  # Handle new message stored in message.message

def whatToDo(status):
    if status == 'ON':
        print('Switch ON light')
        # switch on
        led.on()
    else:
        print('Swtich OFF light')
        # switch off
        led.off()

pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels(<Your pubnub channel name>).execute()

Step 7:

We are using pubnub javascript library for publishing the message through web page. Create a simple html file for e.g. Button.html
Setup Pubnub:
<script src=”https://cdn.pubnub.com/pubnub.min.js“></script>

var pubnub = PUBNUB.init({
        publish_key: <Your PUBNUB subscribe key>,
        subscribe_key: <Your PUBNUB publish key>
    });

Create Buttons:

<button type="button" onClick="lightOn()" class="on">ON</button>
<button type="button" onClick="lightOff()" class="off">OFF</button>

Publish messages:
Here we are sending ON/OFF status that can handel by your python script.

function lightOff(){
    pubnub.publish(
     {
        message: {
            status: 'OFF'
        },
        channel: 'awesomeChannel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: {
            "cool": "meta"
        }   // publish extra meta with the request
    },
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken")
        }
    }
  );

}

function lightOn(){
    pubnub.publish(
     {
        message: {
            status: 'ON'
        },
        channel: 'awesomeChannel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: {
            "cool": "meta"
        }   // publish extra meta with the request
    },
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken")
        }
    }
  );
}

Open this file to chrome or any other web browser.
You can host this html file to some cloud server like (AWS, heroku) to access from anywhere.

Step 8:

!!! Enjoy !!!
Hope this tutorial helps you to use Pubnub to control your electrical devices via network.

2 Replies to “Remotely switch On/Off an LED using PubNub and Raspberry PI”

  1. I am trying to do a project for school which essentially would be to turn on and off a gpio on the raspberry pi through the web. However whenever I am trying to run the python code it says the pubnub package does not exist, I have downloaded the package already and it still gives me that error message.

Leave a Reply

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