Sunday 25 June 2017

How to receive data from MQTT Cloud to Raspberry Pi

How to receive data from MQTT Cloud to Raspberry Pi


# Open https://accounts.adafruit.com
# Import standard python modules.
import RPi.GPIO as GPIO

import sys

# Import Adafruit IO MQTT client.
from Adafruit_IO import MQTTClient

GPIO.setmode(GPIO.BCM)

# Set to your Adafruit IO key & username below.
ADAFRUIT_IO_USERNAME      = 'Your Adafruit IO user name'# to find your username
ADAFRUIT_IO_KEY           = 'Your Adafruit IO Key'  # to find in io.adafruit
                                                 

# Set to the ID of the feed to subscribe to for updates.
FEED_ID1 = 'output1'
FEED_ID2 = 'output2'

GPIO.setup(23, GPIO.OUT)
GPIO.output(23, GPIO.LOW)
GPIO.setup(2, GPIO.OUT)
GPIO.output(2, GPIO.LOW)



# Define callback functions which will be called when certain events happen.
def connected(client):
 
    print 'Connected to Adafruit IO!  Listening for {0} changes...'.format(FEED_ID1)
    print 'Connected to Adafruit IO!  Listening for {0} changes...'.format(FEED_ID2)

     # Subscribe to changes on a feed named DemoFeed.
    client.subscribe(FEED_ID1)
    client.subscribe(FEED_ID2)


def disconnected(client):
    # Disconnected function will be called when the client disconnects.
    print 'Disconnected from Adafruit IO!'
    sys.exit(1)

def message(client, feed_id, payload):
    # Message function will be called when a subscribed feed has a new value.
    # The feed_id parameter identifies the feed, and the payload parameter has
    # the new value.
    print 'Feed {0} received new value: {1}'.format(feed_id, payload)
    if feed_id=="output1" and payload=="1":
           GPIO.output(23, GPIO.HIGH)
    if feed_id=="output1" and payload=="0":
        GPIO.output(23, GPIO.LOW)
    if feed_id=="output2" and payload=="1":
        GPIO.output(2, GPIO.HIGH)
    if feed_id=="output2" and payload=="0":
        GPIO.output(2, GPIO.LOW)



    #print 'Feed {0} received new value: {1}'.format(feed_id, payload)


# Create an MQTT client instance.
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

# Setup the callback functions defined above.
client.on_connect    = connected
client.on_disconnect = disconnected
client.on_message    = message

# Connect to the Adafruit IO server.
client.connect()

client.loop_blocking()




Circuit Diagram:



0 comments:

Post a Comment

if you have any doubt please let me know