|
| 1 | +""" |
| 2 | +'adafruitio_01_subscribe.py' |
| 3 | +========================== |
| 4 | +Subscribes to an Adafruit IO Feed |
| 5 | +
|
| 6 | +Author(s): Brent Rubell, Todd Treece for Adafruit Industries |
| 7 | +""" |
| 8 | +# Import standard python modules. |
| 9 | +import sys |
| 10 | + |
| 11 | +# This example uses the MQTTClient, instead of the REST client |
| 12 | +from Adafruit_IO import MQTTClient |
| 13 | + |
| 14 | +# Set to your Adafruit IO key & username below. |
| 15 | +ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME' |
| 16 | +ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY' |
| 17 | + |
| 18 | +# Set to the ID of the feed to subscribe to for updates. |
| 19 | +FEED_ID = 'counter' |
| 20 | + |
| 21 | +# Define callback functions which will be called when certain events happen. |
| 22 | +def connected(client): |
| 23 | + """Connected function will be called when the client is connected to Adafruit IO. |
| 24 | + This is a good place to subscribe to feed changes. The client parameter |
| 25 | + passed to this function is the Adafruit IO MQTT client so you can make |
| 26 | + calls against it easily. |
| 27 | + """ |
| 28 | + # Subscribe to changes on a feed named Counter. |
| 29 | + print('Subscribing to Feed {0}'.format(FEED_ID)) |
| 30 | + client.subscribe(FEED_ID) |
| 31 | + print('Waiting for feed data...') |
| 32 | + |
| 33 | +def disconnected(client): |
| 34 | + """Disconnected function will be called when the client disconnects.""" |
| 35 | + sys.exit(1) |
| 36 | + |
| 37 | +def message(client, feed_id, payload): |
| 38 | + """Message function will be called when a subscribed feed has a new value. |
| 39 | + The feed_id parameter identifies the feed, and the payload parameter has |
| 40 | + the new value. |
| 41 | + """ |
| 42 | + print('Feed {0} received new value: {1}'.format(feed_id, payload)) |
| 43 | + |
| 44 | + |
| 45 | +# Create an MQTT client instance. |
| 46 | +client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) |
| 47 | + |
| 48 | +# Setup the callback functions defined above. |
| 49 | +client.on_connect = connected |
| 50 | +client.on_disconnect = disconnected |
| 51 | +client.on_message = message |
| 52 | + |
| 53 | +# Connect to the Adafruit IO server. |
| 54 | +client.connect() |
| 55 | + |
| 56 | +# The first option is to run a thread in the background so you can continue |
| 57 | +# doing things in your program. |
| 58 | +client.loop_blocking() |
0 commit comments