1- # Example of using the MQTT client class to subscribe to and publish feed values.
2- # Author: Tony DiCola
1+ # Example of subscribing to an Adafruit IO group
2+ # and publishing to the feeds within it
3+
4+ # Author: Brent Rubell for Adafruit Industries, 2018
35
46# Import standard python modules.
57import random
1820# (go to https://accounts.adafruit.com to find your username)
1921ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME'
2022
21- # name of the group to subscribe to changes on
23+ # Group Name
2224group_name = 'grouptest'
2325
26+ # Feeds within the group
27+ group_feed_one = 'one'
28+ group_feed_two = 'two'
29+
2430# Define callback functions which will be called when certain events happen.
2531def connected (client ):
2632 # Connected function will be called when the client is connected to Adafruit IO.
27- # This is a good place to subscribe to feed changes. The client parameter
33+ # This is a good place to subscribe to topic changes. The client parameter
2834 # passed to this function is the Adafruit IO MQTT client so you can make
2935 # calls against it easily.
30- # Subscribe to changes on a group_id.
31- print ( 'Subscribing to ' , group_name )
36+ print ( 'Listening for changes on ' , group_name )
37+ # Subscribe to changes on a group, ` group_name`
3238 client .subscribe_group (group_name )
3339
3440def disconnected (client ):
@@ -40,7 +46,7 @@ def message(client, topic_id, payload):
4046 # Message function will be called when a subscribed topic has a new value.
4147 # The topic_id parameter identifies the topic, and the payload parameter has
4248 # the new value.
43- print ('{0} received new value: {1}' .format (topic_id , payload ))
49+ print ('Topic {0} received new value: {1}' .format (topic_id , payload ))
4450
4551
4652# Create an MQTT client instance.
@@ -54,5 +60,21 @@ def message(client, topic_id, payload):
5460# Connect to the Adafruit IO server.
5561client .connect ()
5662
57- # Run a message loop forever to listen
58- client .loop_blocking ()
63+ # Now the program needs to use a client loop function to ensure messages are
64+ # sent and received. There are a few options for driving the message loop,
65+ # depending on what your program needs to do.
66+
67+ # The first option is to run a thread in the background so you can continue
68+ # doing things in your program.
69+ client .loop_background ()
70+ # Now send new values every 5 seconds.
71+ print ('Publishing a new message every 5 seconds (press Ctrl-C to quit)...' )
72+ while True :
73+ value = random .randint (0 , 100 )
74+ print ('Publishing {0} to {1}.{2}.' .format (value , group_name , group_feed_one ))
75+ client .publish ('one' , value , group_name )
76+
77+ value = random .randint (0 ,100 )
78+ print ('Publishing {0} to {1}.{2}.' .format (value , group_name , group_feed_two ))
79+ client .publish ('two' , value , group_name )
80+ time .sleep (5 )
0 commit comments