Skip to content

Commit 3e73a6c

Browse files
authored
Merge pull request #63 from brentru/add-esp32s2-updated-code
Add ESP32-S2 compatibility and example
2 parents ce359f0 + dac995d commit 3e73a6c

File tree

2 files changed

+109
-17
lines changed

2 files changed

+109
-17
lines changed

adafruit_io/adafruit_io.py

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,9 @@ def __init__(self, mqtt_client):
5151
raise TypeError(
5252
"This class requires a MiniMQTT client object, please create one."
5353
)
54-
# MiniMQTT's username kwarg is optional, IO requires a username
54+
# Adafruit IO MQTT API MUST require a username
5555
try:
56-
self._user = self._client.user
56+
self._user = self._client._username
5757
except Exception as err:
5858
raise TypeError(
5959
"Adafruit IO requires a username, please set one in MiniMQTT"
@@ -70,11 +70,6 @@ def __init__(self, mqtt_client):
7070
self._client.on_message = self._on_message_mqtt
7171
self._client.on_subscribe = self._on_subscribe_mqtt
7272
self._client.on_unsubscribe = self._on_unsubscribe_mqtt
73-
self._logger = False
74-
# Write to the MiniMQTT logger, if avaliable.
75-
if self._client.logger is not None:
76-
self._logger = True
77-
self._client.set_logger_level("DEBUG")
7873
self._connected = False
7974

8075
def __enter__(self):
@@ -112,8 +107,6 @@ def is_connected(self):
112107
# pylint: disable=not-callable, unused-argument
113108
def _on_connect_mqtt(self, client, userdata, flags, return_code):
114109
"""Runs when the client calls on_connect."""
115-
if self._logger:
116-
self._client._logger.debug("Client called on_connect.")
117110
if return_code == 0:
118111
self._connected = True
119112
else:
@@ -125,8 +118,6 @@ def _on_connect_mqtt(self, client, userdata, flags, return_code):
125118
# pylint: disable=not-callable, unused-argument
126119
def _on_disconnect_mqtt(self, client, userdata, return_code):
127120
"""Runs when the client calls on_disconnect."""
128-
if self._logger:
129-
self._client._logger.debug("Client called on_disconnect")
130121
self._connected = False
131122
# Call the user-defined on_disconnect callblack if defined
132123
if self.on_disconnect is not None:
@@ -140,8 +131,6 @@ def _on_message_mqtt(self, client, topic, payload):
140131
:param str topic: MQTT topic response from Adafruit IO.
141132
:param str payload: MQTT payload data response from Adafruit IO.
142133
"""
143-
if self._logger:
144-
self._client._logger.debug("Client called on_message.")
145134
if self.on_message is not None:
146135
# Parse the MQTT topic string
147136
topic_name = topic.split("/")
@@ -177,16 +166,12 @@ def _on_message_mqtt(self, client, topic, payload):
177166
# pylint: disable=not-callable
178167
def _on_subscribe_mqtt(self, client, user_data, topic, qos):
179168
"""Runs when the client calls on_subscribe."""
180-
if self._logger:
181-
self._client._logger.debug("Client called on_subscribe")
182169
if self.on_subscribe is not None:
183170
self.on_subscribe(self, user_data, topic, qos)
184171

185172
# pylint: disable=not-callable
186173
def _on_unsubscribe_mqtt(self, client, user_data, topic, pid):
187174
"""Runs when the client calls on_unsubscribe."""
188-
if self._logger:
189-
self._client._logger.debug("Client called on_unsubscribe")
190175
if self.on_unsubscribe is not None:
191176
self.on_unsubscribe(self, user_data, topic, pid)
192177

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
import time
4+
from random import randint
5+
6+
import ssl
7+
import socketpool
8+
import wifi
9+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
10+
from adafruit_io.adafruit_io import IO_MQTT
11+
12+
### WiFi ###
13+
14+
# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
15+
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
16+
# source control.
17+
# pylint: disable=no-name-in-module,wrong-import-order
18+
try:
19+
from secrets import secrets
20+
except ImportError:
21+
print("WiFi secrets are kept in secrets.py, please add them there!")
22+
raise
23+
24+
# Set your Adafruit IO Username and Key in secrets.py
25+
# (visit io.adafruit.com if you need to create an account,
26+
# or if you need your Adafruit IO key.)
27+
aio_username = secrets["aio_username"]
28+
aio_key = secrets["aio_key"]
29+
30+
print("Connecting to %s" % secrets["ssid"])
31+
wifi.radio.connect(secrets["ssid"], secrets["password"])
32+
print("Connected to %s!" % secrets["ssid"])
33+
34+
# Define callback functions which will be called when certain events happen.
35+
# pylint: disable=unused-argument
36+
def connected(client):
37+
# Connected function will be called when the client is connected to Adafruit IO.
38+
# This is a good place to subscribe to feed changes. The client parameter
39+
# passed to this function is the Adafruit IO MQTT client so you can make
40+
# calls against it easily.
41+
print("Connected to Adafruit IO! Listening for DemoFeed changes...")
42+
# Subscribe to changes on a feed named DemoFeed.
43+
client.subscribe("DemoFeed")
44+
45+
46+
def subscribe(client, userdata, topic, granted_qos):
47+
# This method is called when the client subscribes to a new feed.
48+
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
49+
50+
51+
def unsubscribe(client, userdata, topic, pid):
52+
# This method is called when the client unsubscribes from a feed.
53+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
54+
55+
56+
# pylint: disable=unused-argument
57+
def disconnected(client):
58+
# Disconnected function will be called when the client disconnects.
59+
print("Disconnected from Adafruit IO!")
60+
61+
62+
# pylint: disable=unused-argument
63+
def message(client, feed_id, payload):
64+
# Message function will be called when a subscribed feed has a new value.
65+
# The feed_id parameter identifies the feed, and the payload parameter has
66+
# the new value.
67+
print("Feed {0} received new value: {1}".format(feed_id, payload))
68+
69+
70+
# Create a socket pool
71+
pool = socketpool.SocketPool(wifi.radio)
72+
73+
# Initialize a new MQTT Client object
74+
mqtt_client = MQTT.MQTT(
75+
broker="io.adafruit.com",
76+
username=secrets["aio_username"],
77+
password=secrets["aio_key"],
78+
socket_pool=pool,
79+
ssl_context=ssl.create_default_context(),
80+
)
81+
82+
# Initialize an Adafruit IO MQTT Client
83+
io = IO_MQTT(mqtt_client)
84+
85+
# Connect the callback methods defined above to Adafruit IO
86+
io.on_connect = connected
87+
io.on_disconnect = disconnected
88+
io.on_subscribe = subscribe
89+
io.on_unsubscribe = unsubscribe
90+
io.on_message = message
91+
92+
# Connect to Adafruit IO
93+
print("Connecting to Adafruit IO...")
94+
io.connect()
95+
96+
# Below is an example of manually publishing a new value to Adafruit IO.
97+
last = 0
98+
print("Publishing a new message every 10 seconds...")
99+
while True:
100+
# Explicitly pump the message loop.
101+
io.loop()
102+
# Send a new message every 10 seconds.
103+
if (time.monotonic() - last) >= 5:
104+
value = randint(0, 100)
105+
print("Publishing {0} to DemoFeed.".format(value))
106+
io.publish("DemoFeed", value)
107+
last = time.monotonic()

0 commit comments

Comments
 (0)