Recent Posts

#17 Raspberry Pi: Publish - Subscribe IoT Architecture Demo using PubNub server (Python Program)

IoT Tutorial #17 [ Raspberry Pi Tutorials #5 ]
In previous post, we have seen demo for Node-Gateway IoT Architecture using Raspberry Pi 3 and NodeMCU.
Here, We will work on another IoT Architecture: Publish-Subscribe IoT Architecture.

Publish - Subscribe IoT Architecture has multiple benefits over Node-Gateway IoT Architecture:
    1. Faster
    2. Low power Consumption
Publish - Subscribe IoT Architecture consist of one Broker (Server) and multiple clients (Nodes).

Client can either be publisher or subscriber or both.

In this demonstration, https://www.pubnub.com is acting as Broker and python scripts on Raspberry Pi will be acting as client (publisher and Subscriber)

Getting familiar with PubNub Server:

       1.       Open a free account on https://www.pubnub.com/
a.       Click on "Create New App" > Enter <Name for the App> > Click on "Create"
b.      Click on the Newly created app
c.       You can see that, Public Key and Subscribe Key

       2.       Open Console for Debugging purpose
a.       Go to  https://www.pubnub.com/docs/console
b.      Copy and paste Public Key and Subscribe Key from step 1.c. to console window
c.       Change the Name of the Channel to "Raspberry"
d.      Click on the "SUBSCRIBE" > Conncection status will change to "CONNECTED"
e.      Scroll down to (white) "message" window and write following in json format:
{"text":"Hi Guys"}

Click on "Send" button

you will see the same message in black colored message console.

That means, it is working fine




Install pubnub libraries on Raspberry Pi 3:

       3.       Install punnub python library on your RPi3:
a.       Open terminal on RPi3
b.      type following command:
sudo pip install pubnub


Test pubnub connection using python scrips:

       4.       Place python script "ps_01.py" and "ps_02.py" on RPi3
       Change Following 3 things in both the scripts:
a.       pubnub publish_key  (from step 1.c)
b.      pubnub subscibe_key (from step 1.c)
c.       pubnub channel_name (from step 2.c)

       5.       Run these Scripts on RPi3 using "Python2" IDE or in Terminal
       6.       In this script, we are publishing and subscribed to the same borker.channel
       NOTE:
a.       ps_01.py and ps_02.py are exactly same python scripts with just different messages which will be sent to the broker
b.      channel_name is same as topic_name

In python script ps_01.py and ps_02.py,
·         we are connecting/subscribing to the Borker.channel
·         then publishing the data once to the server/Broker.channel
·         And then reading the received msgs in infinite loop.


Debugging using pubnub console:

       7.       We can debug this program using pubnub console (https://www.pubnub.com/docs/console),
a.       Run this script on RPi3 (as shown in step 5)
b.      Set publish_key, subscribe_key and channel_name in pubnub console as same as it is in the script
c.       Publish the data from pubnub console (as shown in step 2.e)

You can observer same messages (as published in step 7.c.) received on 
RPi3 Terminal (where script is running)




For Better understanding you can watch demonstration video given below:

Downloads:

Download link is given in the Description of the YouTube video shown below.

Demonstration:




ps_01.py:

# importing pubnub libraries
from pubnub.pubnub import PubNub, SubscribeListener, SubscribeCallback, PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.exceptions import PubNubException
import pubnub

pnconf = PNConfiguration()                                              # create pubnub_configuration_object
pnconf.publish_key = 'pub-c-873125f5-af8c-436c-b506-669fcfff8c5a'       # set pubnub publish_key
pnconf.subscribe_key = 'sub-c-7bd72574-f2c3-11e7-b8a6-46d99af2bb8c'     # set pubnub subscibe_key
pubnub = PubNub(pnconf)                     # create pubnub_object using pubnub_configuration_object

channel='Raspberry'                         # provide pubnub channel_name

data = {                                    # data to be published
    'username': 'Akshay: ps_01',
    'message' : 'This is my 1st msg... '
}

class MyListener(SubscribeCallback):        # Not need for working of this program
    def status(self, pubnub, status):
        if status.category == PNStatusCategory.PNConnectedCategory:
            pubnub.publish().channel(channel).message({'fieldA': 'awesome', 'fieldB': 10}).sync()

    def message(self, pubnub, message):
        print(message)

    def presence(self, pubnub, presence):
        pass

my_listener = SubscribeListener()                   # create listner_object to read the msg from the Broker/Server
pubnub.add_listener(my_listener)                    # add listner_object to pubnub_object to subscribe it
pubnub.subscribe().channels(channel).execute()      # subscribe the channel (Runs in background)

my_listener.wait_for_connect()                      # wait for the listner_obj to connect to the Broker.Channel
print('connected')                                  # print confirmation msg

pubnub.publish().channel(channel).message(data).sync()      # publish the data to the mentioned channel

while True:                                                 # Infinite loop
    result = my_listener.wait_for_message_on(channel)       # Read the new msg on the channel
    print(result.message)                                   # print the new msg

ps_02.py:

# importing pubnub libraries
from pubnub.pubnub import PubNub, SubscribeListener, SubscribeCallback, PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.exceptions import PubNubException
import pubnub


pnconf = PNConfiguration()                                           # create pubnub_configuration_object
pnconf.publish_key = 'pub-c-873125f5-af8c-436c-b506-669fcfff8c5a'    # set pubnub publish_key
pnconf.subscribe_key = 'sub-c-7bd72574-f2c3-11e7-b8a6-46d99af2bb8c'  # set pubnub subscibe_key
pubnub = PubNub(pnconf)                                              # create pubnub_object using pubnub_configuration_object

channel='Raspberry'                                                  # provide pubnub channel_name

data = {                                                             # data to be published
         'message': 'This is Akshay Daga... ps_02'
       }

my_listener = SubscribeListener()                           # create listner_object to read the msg from the Broker/Server
pubnub.add_listener(my_listener)                            # add listner_object to pubnub_object to subscribe it

pubnub.subscribe().channels(channel).execute()              # subscribe the channel (Runs in background) 

my_listener.wait_for_connect()                              # wait for the listner_obj to connect to the Broker.Channel 
print('connected')                                          # print confirmation msg

pubnub.publish().channel(channel).message(data).sync()      # publish the data to the mentioned channel

while True:                                                 # Infinite loop
    result = my_listener.wait_for_message_on(channel)       # Read the new msg on the channel
    print(result.message)                                   # print the new msg



Click here to see more codes for Raspberry Pi 3 and similar Family.
&
Click here to see more codes for NodeMCU ESP8266 and similar Family.
&
Click here to see more codes for Arduino Mega (ATMega 2560) and similar Family.

Feel free to ask doubts in the comment section. I will try my best to solve it.
If you find this helpful by any mean like, comment and share the post.
This is the simplest way to encourage me to keep doing such work.

Thanks and Regards,
-Akshay P. Daga





No comments