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.

What is Cross-site Scripting (XSS) and it’s types

If you are into the hacking techniques, you sure must have heard of this popular terminology XSS (Cross-Site Scripting). This is one of the techniques rather a vulnerability in which an attacker/hacker can input something (harmful mostly) which is sent to unsuspecting victims.

What follows below will get you up to speed on the fundamental concept in just a few paragraphs.

What is XSS

Cross-site Scripting (XSS) refers to client-side code injection attack wherein an attacker can execute malicious scripts (also commonly referred to as a malicious payload) into a legitimate website or web application.

XSS is amongst the most rampant of web application vulnerabilities and occurs when a web application makes use of unvalidated or unencoded user input within the output it generates.

In XSS, an attacker does not target a victim directly. Instead, an attacker would exploit a vulnerability within a website or web application that the victim would visit, essentially using the vulnerable website as a vehicle to deliver a malicious script to the victim’s browser.

How XSS works

In order to run malicious JavaScript code in a victim’s browser, an attacker must first find a way to inject a payload into a web page that the victim visits. Of course, an attacker could use social engineering techniques to convince a user to visit a vulnerable page with an injected JavaScript payload.

In order for an XSS attack to take place the vulnerable website needs to directly include user input in its pages. An attacker can then insert a string that will be used within the web page and treated as code by the victim’s browser.

The consequences of malicious JavaScript

  • Cookie theft: The attacker can access the victim’s cookies associated with the website
  • Keylogging: The attacker can register a keyboard event listener using javascript and then send all of the user’s keystrokes to his own server, potentially recording sensitive information such as passwords and credit card numbers.
  • Phishing: The attacker can insert a fake login form into the page using DOM manipulation, set the form’s action attribute to target his own server, and then trick the user into submitting sensitive information.

Types of XSS

While the goal of an XSS attack is always to execute malicious JavaScript in the victim’s browser, there are few fundamentally different ways of achieving that goal. XSS attacks are often divided into three types:

  • Persistent XSS: where the malicious string originates from the website’s database.
  • Reflected XSS: where the malicious string originates from the victim’s request.
  • DOM-based XSS: where the vulnerability is in the client-side code rather than the server-side code.