Skip to content

Commit 60d11b7

Browse files
author
brentru
committed
add example and 2x methods, black and pylinten
1 parent 2d3de68 commit 60d11b7

File tree

2 files changed

+155
-17
lines changed

2 files changed

+155
-17
lines changed

adafruit_io/adafruit_io.py

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,7 @@ def __exit__(self, exception_type, exception_value, traceback):
100100
self.disconnect()
101101

102102
def reconnect(self):
103-
"""Attempts to reconnect to the Adafruit IO MQTT Broker.
104-
105-
"""
103+
"""Attempts to reconnect to the Adafruit IO MQTT Broker."""
106104
try:
107105
self._client.reconnect()
108106
except Exception as err:
@@ -118,8 +116,7 @@ def connect(self):
118116
raise AdafruitIO_MQTTError("Unable to connect to Adafruit IO.") from err
119117

120118
def disconnect(self):
121-
"""Disconnects from Adafruit IO MQTT Broker.
122-
"""
119+
"""Disconnects from Adafruit IO MQTT Broker."""
123120
if self._connected:
124121
self._client.disconnect()
125122

@@ -130,8 +127,7 @@ def is_connected(self):
130127

131128
# pylint: disable=not-callable, unused-argument
132129
def _on_connect_mqtt(self, client, userdata, flags, return_code):
133-
"""Runs when the client calls on_connect.
134-
"""
130+
"""Runs when the client calls on_connect."""
135131
if self._logger:
136132
self._client._logger.debug("Client called on_connect.")
137133
if return_code == 0:
@@ -144,8 +140,7 @@ def _on_connect_mqtt(self, client, userdata, flags, return_code):
144140

145141
# pylint: disable=not-callable, unused-argument
146142
def _on_disconnect_mqtt(self, client, userdata, return_code):
147-
"""Runs when the client calls on_disconnect.
148-
"""
143+
"""Runs when the client calls on_disconnect."""
149144
if self._logger:
150145
self._client._logger.debug("Client called on_disconnect")
151146
self._connected = False
@@ -195,22 +190,39 @@ def _on_message_mqtt(self, client, topic, payload):
195190

196191
# pylint: disable=not-callable
197192
def _on_subscribe_mqtt(self, client, user_data, topic, qos):
198-
"""Runs when the client calls on_subscribe.
199-
"""
193+
"""Runs when the client calls on_subscribe."""
200194
if self._logger:
201195
self._client._logger.debug("Client called on_subscribe")
202196
if self.on_subscribe is not None:
203197
self.on_subscribe(self, user_data, topic, qos)
204198

205199
# pylint: disable=not-callable
206200
def _on_unsubscribe_mqtt(self, client, user_data, topic, pid):
207-
"""Runs when the client calls on_unsubscribe.
208-
"""
201+
"""Runs when the client calls on_unsubscribe."""
209202
if self._logger:
210203
self._client._logger.debug("Client called on_unsubscribe")
211204
if self.on_unsubscribe is not None:
212205
self.on_unsubscribe(self, user_data, topic, pid)
213206

207+
def add_feed_callback(self, feed_key, callback_method):
208+
"""Executes callback_method whenever a message is
209+
received on feed_key.
210+
:param str feed_key: Adafruit IO feed key.
211+
:param str callback_method: Name of callback method.
212+
213+
"""
214+
self._client.add_topic_callback(
215+
"{0}/feeds/{1}".format(self._user, feed_key), callback_method
216+
)
217+
218+
def remove_feed_callback(self, feed_key):
219+
"""Removes a previously registered callback method
220+
from executing whenever feed_key receives new data.
221+
:param str feed_key: Adafruit IO feed key.
222+
223+
"""
224+
self._client.remove_topic_callback("{0}/feeds/{1}".format(self._user, feed_key))
225+
214226
def loop(self):
215227
"""Manually process messages from Adafruit IO.
216228
Call this method to check incoming subscription messages.
@@ -464,16 +476,14 @@ def __init__(self, adafruit_io_username, adafruit_io_key, wifi_manager):
464476

465477
@staticmethod
466478
def _create_headers(io_headers):
467-
"""Creates http request headers.
468-
"""
479+
"""Creates http request headers."""
469480
headers = CLIENT_HEADERS.copy()
470481
headers.update(io_headers)
471482
return headers
472483

473484
@staticmethod
474485
def _create_data(data, metadata):
475-
"""Creates JSON data payload
476-
"""
486+
"""Creates JSON data payload"""
477487
if metadata is not None:
478488
return {
479489
"value": data,
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import time
2+
3+
import board
4+
import busio
5+
from digitalio import DigitalInOut
6+
from adafruit_esp32spi import adafruit_esp32spi
7+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
8+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
9+
import neopixel
10+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
11+
from adafruit_io.adafruit_io import IO_MQTT
12+
13+
### WiFi ###
14+
15+
# Get wifi details and more from a secrets.py file
16+
try:
17+
from secrets import secrets
18+
except ImportError:
19+
print("WiFi secrets are kept in secrets.py, please add them there!")
20+
raise
21+
22+
# If you are using a board with pre-defined ESP32 Pins:
23+
esp32_cs = DigitalInOut(board.ESP_CS)
24+
esp32_ready = DigitalInOut(board.ESP_BUSY)
25+
esp32_reset = DigitalInOut(board.ESP_RESET)
26+
27+
# If you have an externally connected ESP32:
28+
# esp32_cs = DigitalInOut(board.D9)
29+
# esp32_ready = DigitalInOut(board.D10)
30+
# esp32_reset = DigitalInOut(board.D5)
31+
32+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
33+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
34+
"""Use below for Most Boards"""
35+
status_light = neopixel.NeoPixel(
36+
board.NEOPIXEL, 1, brightness=0.2
37+
) # Uncomment for Most Boards
38+
"""Uncomment below for ItsyBitsy M4"""
39+
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
40+
# Uncomment below for an externally defined RGB LED
41+
# import adafruit_rgbled
42+
# from adafruit_esp32spi import PWMOut
43+
# RED_LED = PWMOut.PWMOut(esp, 26)
44+
# GREEN_LED = PWMOut.PWMOut(esp, 27)
45+
# BLUE_LED = PWMOut.PWMOut(esp, 25)
46+
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
47+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
48+
49+
# Define callback functions which will be called when certain events happen.
50+
# pylint: disable=unused-argument
51+
def connected(client):
52+
# Connected function will be called when the client is connected to Adafruit IO.
53+
# This is a good place to subscribe to feed changes. The client parameter
54+
# passed to this function is the Adafruit IO MQTT client so you can make
55+
# calls against it easily.
56+
print("Connected to Adafruit IO! Listening for DemoFeed changes...")
57+
58+
def subscribe(client, userdata, topic, granted_qos):
59+
# This method is called when the client subscribes to a new feed.
60+
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
61+
62+
63+
def unsubscribe(client, userdata, topic, pid):
64+
# This method is called when the client unsubscribes from a feed.
65+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
66+
67+
68+
# pylint: disable=unused-argument
69+
def disconnected(client):
70+
# Disconnected function will be called when the client disconnects.
71+
print("Disconnected from Adafruit IO!")
72+
73+
74+
# pylint: disable=unused-argument
75+
def message(client, feed_id, payload):
76+
# Message function will be called when a subscribed feed has a new value.
77+
# The feed_id parameter identifies the feed, and the payload parameter has
78+
# the new value.
79+
print("Feed {0} received new value: {1}".format(feed_id, payload))
80+
81+
82+
def on_battery_msg(client, topic, message):
83+
# Method called whenever user/feeds/battery has a new value
84+
print("Battery level: {}v".format(message))
85+
86+
# Connect to WiFi
87+
print("Connecting to WiFi...")
88+
wifi.connect()
89+
print("Connected!")
90+
91+
# Initialize MQTT interface with the esp interface
92+
MQTT.set_socket(socket, esp)
93+
94+
# Initialize a new MQTT Client object
95+
mqtt_client = MQTT.MQTT(
96+
broker="io.adafruit.com", username=secrets["aio_username"], password=secrets["aio_key"],
97+
)
98+
99+
# Initialize an Adafruit IO MQTT Client
100+
io = IO_MQTT(mqtt_client)
101+
102+
# Connect the callback methods defined above to Adafruit IO
103+
io.on_connect = connected
104+
io.on_disconnect = disconnected
105+
io.on_subscribe = subscribe
106+
io.on_unsubscribe = unsubscribe
107+
io.on_message = message
108+
109+
# Connect to Adafruit IO
110+
print("Connecting to Adafruit IO...")
111+
io.connect()
112+
113+
# Set up a message handler for the battery feed
114+
io.add_feed_callback("battery", on_battery_msg)
115+
116+
# Subscribe to all messages on the battery feed
117+
io.subscribe("battery")
118+
119+
# Start a blocking loop to check for new messages
120+
while True:
121+
try:
122+
io.loop()
123+
except (ValueError, RuntimeError) as e:
124+
print("Failed to get data, retrying\n", e)
125+
wifi.reset()
126+
io.reconnect()
127+
continue
128+
time.sleep(0.5)

0 commit comments

Comments
 (0)