Skip to content

Commit b6bbeeb

Browse files
author
brentru
committed
add mqtt aio code
1 parent 659a8f8 commit b6bbeeb

File tree

1 file changed

+136
-0
lines changed

1 file changed

+136
-0
lines changed

Adafruit_IO_Power_Relay/code.py

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
import time
2+
import board
3+
import busio
4+
from digitalio import DigitalInOut
5+
import neopixel
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+
10+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
11+
12+
### WiFi ###
13+
14+
# Get wifi details and more from a secrets.py file
15+
try:
16+
from secrets import secrets
17+
except ImportError:
18+
print("WiFi secrets are kept in secrets.py, please add them there!")
19+
raise
20+
21+
# If you are using a board with pre-defined ESP32 Pins:
22+
esp32_cs = DigitalInOut(board.ESP_CS)
23+
esp32_ready = DigitalInOut(board.ESP_BUSY)
24+
esp32_reset = DigitalInOut(board.ESP_RESET)
25+
26+
# If you have an externally connected ESP32:
27+
# esp32_cs = DigitalInOut(board.D9)
28+
# esp32_ready = DigitalInOut(board.D10)
29+
# esp32_reset = DigitalInOut(board.D5)
30+
31+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
32+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
33+
"""Use below for Most Boards"""
34+
status_light = neopixel.NeoPixel(
35+
board.NEOPIXEL, 1, brightness=0.2
36+
) # Uncomment for Most Boards
37+
"""Uncomment below for ItsyBitsy M4"""
38+
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
39+
# Uncomment below for an externally defined RGB LED
40+
# import adafruit_rgbled
41+
# from adafruit_esp32spi import PWMOut
42+
# RED_LED = PWMOut.PWMOut(esp, 26)
43+
# GREEN_LED = PWMOut.PWMOut(esp, 27)
44+
# BLUE_LED = PWMOut.PWMOut(esp, 25)
45+
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
46+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
47+
48+
# Set up a pin for controlling the relay
49+
power_pin = DigitalInOut(board.D3)
50+
power_pin.switch_to_output()
51+
52+
### Feeds ###
53+
# Set up a feed named Relay for subscribing to the relay feed on Adafruit IO
54+
feed_relay = secrets["aio_username"] + "/feeds/relay"
55+
56+
### Code ###
57+
58+
# Define callback methods which are called when events occur
59+
# pylint: disable=unused-argument, redefined-outer-name
60+
def connected(client, userdata, flags, rc):
61+
# This function will be called when the client is connected
62+
# successfully to the broker.
63+
print("Connected to Adafruit IO!")
64+
65+
66+
def disconnected(client, userdata, rc):
67+
# This method is called when the client is disconnected
68+
print("Disconnected from Adafruit IO!")
69+
70+
71+
def subscribe(client, userdata, topic, granted_qos):
72+
# This method is called when the client subscribes to a new feed.
73+
print("Subscribed to {0}".format(topic))
74+
75+
76+
def unsubscribe(client, userdata, topic, pid):
77+
# This method is called when the client unsubscribes from a feed.
78+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
79+
80+
81+
def on_relay_msg(client, topic, message):
82+
# Called when feeds/relay has a new value
83+
print("Received relay value: ", message)
84+
if message == "ON":
85+
power_pin.value = True
86+
elif message == "OFF":
87+
power_pin.value = False
88+
else:
89+
print("Unexpected message received on /feeds/relay.")
90+
91+
def on_message(client, topic, message):
92+
# Method callled when a client's subscribed feed has a new value.
93+
print("New message on topic {0}: {1}".format(topic, message))
94+
95+
96+
# Connect to WiFi
97+
print("Connecting to WiFi...")
98+
wifi.connect()
99+
print("Connected!")
100+
101+
MQTT.set_socket(socket, esp)
102+
103+
# Set up a MiniMQTT Client
104+
client = MQTT.MQTT(
105+
broker="io.adafruit.com",
106+
username=secrets["aio_username"],
107+
password=secrets["aio_key"],
108+
)
109+
110+
# Setup the callback methods above
111+
client.on_connect = connected
112+
client.on_disconnect = disconnected
113+
client.on_subscribe = subscribe
114+
client.on_unsubscribe = unsubscribe
115+
client.on_message = on_message
116+
# Add a callback to the relay feed
117+
client.add_topic_callback(feed_relay, on_relay_msg)
118+
119+
# Connect the client to Adafruit IO
120+
print("Connecting to Adafruit IO...")
121+
client.connect()
122+
123+
# Subscribe to all updates on relay feed
124+
client.subscribe(feed_relay)
125+
126+
# Start a blocking message loop...
127+
# NOTE: NO code below this loop will execute
128+
while True:
129+
try:
130+
client.loop()
131+
except (ValueError, RuntimeError) as e:
132+
print("Failed to get data, retrying\n", e)
133+
wifi.reset()
134+
client.reconnect()
135+
continue
136+
time.sleep(0.5)

0 commit comments

Comments
 (0)