Skip to content

Commit 4227988

Browse files
authored
Merge pull request #30 from brentru/minimqtt-update
Update examples for MiniMQTT PR
2 parents 0da1d6c + 0027e5d commit 4227988

6 files changed

+172
-46
lines changed

adafruit_io/adafruit_io.py

+10
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,16 @@ def __enter__(self):
9999
def __exit__(self, exception_type, exception_value, traceback):
100100
self.disconnect()
101101

102+
def reconnect(self):
103+
"""Attempts to reconnect to the Adafruit IO MQTT Broker.
104+
105+
"""
106+
try:
107+
self._client.reconnect()
108+
except:
109+
raise AdafruitIO_MQTTError("Unable to reconnect to Adafruit IO.")
110+
111+
102112
def connect(self):
103113
"""Connects to the Adafruit IO MQTT Broker.
104114
Must be called before any other API methods are called.

examples/mqtt/adafruit_io_groups.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
1212
import neopixel
1313
from adafruit_io.adafruit_io import IO_MQTT
14-
from adafruit_minimqtt import MQTT
14+
import adafruit_minimqtt as MQTT
1515

1616
### WiFi ###
1717

@@ -76,18 +76,18 @@ def message(client, feed_id, payload):
7676
# the new value.
7777
print("Feed {0} received new value: {1}".format(feed_id, payload))
7878

79-
8079
# Connect to WiFi
80+
print("Connecting to WiFi...")
8181
wifi.connect()
82+
print("Connected!")
83+
84+
# Initialize MQTT interface with the esp interface
85+
MQTT.set_socket(socket, esp)
8286

8387
# Initialize a new MQTT Client object
84-
mqtt_client = MQTT(
85-
socket=socket,
86-
broker="io.adafruit.com",
87-
username=secrets["aio_user"],
88-
password=secrets["aio_key"],
89-
network_manager=wifi,
90-
)
88+
mqtt_client = MQTT.MQTT(broker="https://io.adafruit.com",
89+
username=secrets["aio_user"],
90+
password=secrets["aio_key"])
9191

9292
# Initialize an Adafruit IO MQTT Client
9393
io = IO_MQTT(mqtt_client)
@@ -105,6 +105,7 @@ def message(client, feed_id, payload):
105105
humid_feed = "weatherstation.humidity"
106106

107107
# Connect to Adafruit IO
108+
print("Connecting to Adafruit IO...")
108109
io.connect()
109110

110111
print("Publishing new messages to group feeds every 5 seconds...")

examples/mqtt/adafruit_io_location.py

+22-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Example of tagging data with location values
22
# and sending it to an Adafruit IO feed.
3-
3+
import time
44
import board
55
import busio
66
from digitalio import DigitalInOut
@@ -10,7 +10,7 @@
1010
import neopixel
1111

1212

13-
from adafruit_minimqtt import MQTT
13+
import adafruit_minimqtt as MQTT
1414
from adafruit_io.adafruit_io import IO_MQTT
1515

1616
### WiFi ###
@@ -75,18 +75,18 @@ def message(client, feed_id, payload):
7575
# the new value.
7676
print("Feed {0} received new value: {1}".format(feed_id, payload))
7777

78-
7978
# Connect to WiFi
79+
print("Connecting to WiFi...")
8080
wifi.connect()
81+
print("Connected!")
82+
83+
# Initialize MQTT interface with the esp interface
84+
MQTT.set_socket(socket, esp)
8185

8286
# Initialize a new MQTT Client object
83-
mqtt_client = MQTT(
84-
socket=socket,
85-
broker="io.adafruit.com",
86-
username=secrets["aio_user"],
87-
password=secrets["aio_key"],
88-
network_manager=wifi,
89-
)
87+
mqtt_client = MQTT.MQTT(broker="https://io.adafruit.com",
88+
username=secrets["aio_user"],
89+
password=secrets["aio_key"])
9090

9191
# Initialize an Adafruit IO MQTT Client
9292
io = IO_MQTT(mqtt_client)
@@ -112,5 +112,15 @@ def message(client, feed_id, payload):
112112
print("Data sent!")
113113

114114

115-
# Listen forever...
116-
io.loop_blocking()
115+
# Start a blocking message loop...
116+
# NOTE: NO code below this loop will execute
117+
# NOTE: Network reconnection is handled within this loop
118+
while True:
119+
try:
120+
io.loop()
121+
except (ValueError, RuntimeError) as e:
122+
print("Failed to get data, retrying\n", e)
123+
wifi.reset()
124+
io.reconnect()
125+
continue
126+
time.sleep(1)

examples/mqtt/adafruit_io_simpletest.py

+11-14
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
1717
import neopixel
1818
from adafruit_io.adafruit_io import IO_MQTT
19-
from adafruit_minimqtt import MQTT
19+
import adafruit_minimqtt as MQTT
2020

2121
### WiFi ###
2222

@@ -89,18 +89,19 @@ def message(client, feed_id, payload):
8989
# the new value.
9090
print("Feed {0} received new value: {1}".format(feed_id, payload))
9191

92-
9392
# Connect to WiFi
93+
print("Connecting to WiFi...")
9494
wifi.connect()
95+
print("Connected!")
96+
97+
# Initialize MQTT interface with the esp interface
98+
MQTT.set_socket(socket, esp)
9599

96100
# Initialize a new MQTT Client object
97-
mqtt_client = MQTT(
98-
socket=socket,
99-
broker="io.adafruit.com",
100-
username=secrets["aio_user"],
101-
password=secrets["aio_key"],
102-
network_manager=wifi,
103-
)
101+
mqtt_client = MQTT.MQTT(broker="https://io.adafruit.com",
102+
username=secrets["aio_user"],
103+
password=secrets["aio_key"])
104+
104105

105106
# Initialize an Adafruit IO MQTT Client
106107
io = IO_MQTT(mqtt_client)
@@ -113,6 +114,7 @@ def message(client, feed_id, payload):
113114
io.on_message = message
114115

115116
# Connect to Adafruit IO
117+
print("Connecting to Adafruit IO...")
116118
io.connect()
117119

118120
# Below is an example of manually publishing a new value to Adafruit IO.
@@ -127,8 +129,3 @@ def message(client, feed_id, payload):
127129
print("Publishing {0} to DemoFeed.".format(value))
128130
io.publish("DemoFeed", value)
129131
last = time.monotonic()
130-
131-
132-
# You can also call loop_blocking if you only want to receive values.
133-
# NOTE: If uncommented, no code below this line will run.
134-
# io.loop_blocking()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Example of using the Adafruit IO CircuitPython MQTT client
2+
# to subscribe to an Adafruit IO feed and publish random data
3+
# to be received by the feed.
4+
#
5+
# Example by Tony DiCola for Adafruit Industries
6+
# Modified by Brent Rubell for Adafruit Industries, 2019
7+
import time
8+
from random import randint
9+
10+
import board
11+
import busio
12+
from digitalio import DigitalInOut
13+
14+
from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K
15+
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
16+
from adafruit_io.adafruit_io import IO_MQTT
17+
import adafruit_minimqtt as MQTT
18+
19+
# Get MQTT details and more from a secrets.py file
20+
try:
21+
from secrets import secrets
22+
except ImportError:
23+
print("MQTT secrets are kept in secrets.py, please add them there!")
24+
raise
25+
26+
cs = DigitalInOut(board.D10)
27+
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
28+
29+
# Initialize ethernet interface with DHCP
30+
eth = WIZNET5K(spi_bus, cs)
31+
32+
# Define callback functions which will be called when certain events happen.
33+
# pylint: disable=unused-argument
34+
def connected(client):
35+
# Connected function will be called when the client is connected to Adafruit IO.
36+
# This is a good place to subscribe to feed changes. The client parameter
37+
# passed to this function is the Adafruit IO MQTT client so you can make
38+
# calls against it easily.
39+
print("Connected to Adafruit IO! Listening for DemoFeed changes...")
40+
# Subscribe to changes on a feed named DemoFeed.
41+
client.subscribe("DemoFeed")
42+
43+
def subscribe(client, userdata, topic, granted_qos):
44+
# This method is called when the client subscribes to a new feed.
45+
print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos))
46+
47+
def unsubscribe(client, userdata, topic, pid):
48+
# This method is called when the client unsubscribes from a feed.
49+
print('Unsubscribed from {0} with PID {1}'.format(topic, pid))
50+
51+
# pylint: disable=unused-argument
52+
def disconnected(client):
53+
# Disconnected function will be called when the client disconnects.
54+
print("Disconnected from Adafruit IO!")
55+
56+
# pylint: disable=unused-argument
57+
def message(client, feed_id, payload):
58+
# Message function will be called when a subscribed feed has a new value.
59+
# The feed_id parameter identifies the feed, and the payload parameter has
60+
# the new value.
61+
print("Feed {0} received new value: {1}".format(feed_id, payload))
62+
63+
# Initialize MQTT interface with the ethernet interface
64+
MQTT.set_socket(socket, eth)
65+
66+
# Initialize a new MQTT Client object
67+
mqtt_client = MQTT.MQTT(broker="http://io.adafruit.com",
68+
username=secrets["aio_user"],
69+
password=secrets["aio_key"])
70+
71+
# Initialize an Adafruit IO MQTT Client
72+
io = IO_MQTT(mqtt_client)
73+
74+
# Connect the callback methods defined above to Adafruit IO
75+
io.on_connect = connected
76+
io.on_disconnect = disconnected
77+
io.on_subscribe = subscribe
78+
io.on_unsubscribe = unsubscribe
79+
io.on_message = message
80+
81+
# Connect to Adafruit IO
82+
print("Connecting to Adafruit IO...")
83+
io.connect()
84+
85+
# Below is an example of manually publishing a new value to Adafruit IO.
86+
last = 0
87+
print("Publishing a new message every 10 seconds...")
88+
while True:
89+
# Explicitly pump the message loop.
90+
io.loop()
91+
# Send a new message every 10 seconds.
92+
if (time.monotonic() - last) >= 5:
93+
value = randint(0, 100)
94+
print("Publishing {0} to DemoFeed.".format(value))
95+
io.publish("DemoFeed", value)
96+
last = time.monotonic()

examples/mqtt/adafruit_io_time.py

+23-11
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Adafruit IO provides some built-in MQTT topics
22
# for obtaining the current server time, if you don't have
33
# access to a RTC module.
4-
4+
import time
55
import board
66
import busio
77
from digitalio import DigitalInOut
@@ -10,7 +10,7 @@
1010
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
1111
import neopixel
1212

13-
from adafruit_minimqtt import MQTT
13+
import adafruit_minimqtt as MQTT
1414
from adafruit_io.adafruit_io import IO_MQTT
1515

1616
### WiFi ###
@@ -91,16 +91,17 @@ def message(client, feed_id, payload):
9191

9292

9393
# Connect to WiFi
94+
print("Connecting to WiFi...")
9495
wifi.connect()
96+
print("Connected!")
97+
98+
# Initialize MQTT interface with the esp interface
99+
MQTT.set_socket(socket, esp)
95100

96101
# Initialize a new MQTT Client object
97-
mqtt_client = MQTT(
98-
socket=socket,
99-
broker="io.adafruit.com",
100-
username=secrets["aio_user"],
101-
password=secrets["aio_key"],
102-
network_manager=wifi,
103-
)
102+
mqtt_client = MQTT.MQTT(broker="https://io.adafruit.com",
103+
username=secrets["aio_user"],
104+
password=secrets["aio_key"])
104105

105106
# Initialize an Adafruit IO MQTT Client
106107
io = IO_MQTT(mqtt_client)
@@ -113,5 +114,16 @@ def message(client, feed_id, payload):
113114
# Connect to Adafruit IO
114115
io.connect()
115116

116-
# Listen forever...
117-
io.loop_blocking()
117+
118+
# Start a blocking message loop...
119+
# NOTE: NO code below this loop will execute
120+
# NOTE: Network reconnection is handled within this loop
121+
while True:
122+
try:
123+
io.loop()
124+
except (ValueError, RuntimeError) as e:
125+
print("Failed to get data, retrying\n", e)
126+
wifi.reset()
127+
io.reconnect()
128+
continue
129+
time.sleep(1)

0 commit comments

Comments
 (0)