def message(client, feed_id, payload):
print("Feed {0} received new value: {1}".format(feed_id, payload))
if feed_id == "neopixel":
pixel.fill(int(payload[1:], 16))
You create a socket pool, use that to initialise the new MQTT Client object, and use
that to initialise the Adafruit IO MQTT "helper".
pool = socketpool.SocketPool(wifi.radio)
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
socket_pool=pool,
ssl_context=ssl.create_default_context(),
)
io = IO_MQTT(mqtt_client)
You set up the callback methods mentioned above.
io.on_connect = connected
io.on_message = message
Next, you attempt to connect the client to the MQTT broker. If connection is
successful, the code continues on to the timestamp .
try:
io.connect()
If the MQTT broker connection is not successful, the error is printed to the serial
console, and the board will hard reset after 30 seconds.
except Exception as e:
print("Failed to connect to Adafruit IO. Error:", e, "\nBoard will hard reset
in 30 seconds.")
time.sleep(30)
microcontroller.reset()
Once the broker is connected, you set the timestamp to 0 immediately before the
loop.
timestamp = 0
Inside the loop, you attempt to do two things. You first explicitly poll the message
loop. Check out this guide() for more details on that.
©Adafruit Industries Page 156 of 263