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
3
5
4
6
# Import standard python modules.
5
7
import random
18
20
# (go to https://accounts.adafruit.com to find your username)
19
21
ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME'
20
22
21
- # name of the group to subscribe to changes on
23
+ # Group Name
22
24
group_name = 'grouptest'
23
25
26
+ # Feeds within the group
27
+ group_feed_one = 'one'
28
+ group_feed_two = 'two'
29
+
24
30
# Define callback functions which will be called when certain events happen.
25
31
def connected (client ):
26
32
# 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
28
34
# passed to this function is the Adafruit IO MQTT client so you can make
29
35
# 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`
32
38
client .subscribe_group (group_name )
33
39
34
40
def disconnected (client ):
@@ -40,7 +46,7 @@ def message(client, topic_id, payload):
40
46
# Message function will be called when a subscribed topic has a new value.
41
47
# The topic_id parameter identifies the topic, and the payload parameter has
42
48
# 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 ))
44
50
45
51
46
52
# Create an MQTT client instance.
@@ -54,5 +60,21 @@ def message(client, topic_id, payload):
54
60
# Connect to the Adafruit IO server.
55
61
client .connect ()
56
62
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