Skip to content

Commit f290b4a

Browse files
authored
Merge pull request #1253 from brentru/add-iot-basics-schedule-trigger
Add IO Basics Scheduled Trigger Guide Code
2 parents ecf5b74 + 63af5e7 commit f290b4a

File tree

1 file changed

+145
-0
lines changed
  • Adafruit_IO_Schedule_Trigger

1 file changed

+145
-0
lines changed

Adafruit_IO_Schedule_Trigger/code.py

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import time
2+
import board
3+
import busio
4+
from digitalio import DigitalInOut
5+
from adafruit_esp32spi import adafruit_esp32spi
6+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
7+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
8+
import neopixel
9+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
10+
from adafruit_io.adafruit_io import IO_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+
# Define callback functions which will be called when certain events happen.
53+
# pylint: disable=unused-argument
54+
def connected(client):
55+
# Connected function will be called when the client is connected to Adafruit IO.
56+
# This is a good place to subscribe to feed changes. The client parameter
57+
# passed to this function is the Adafruit IO MQTT client so you can make
58+
# calls against it easily.
59+
print("Connected to Adafruit IO!")
60+
61+
62+
def subscribe(client, userdata, topic, granted_qos):
63+
# This method is called when the client subscribes to a new feed.
64+
print("Listening for changes on relay feed...")
65+
66+
67+
def unsubscribe(client, userdata, topic, pid):
68+
# This method is called when the client unsubscribes from a feed.
69+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
70+
71+
72+
# pylint: disable=unused-argument
73+
def disconnected(client):
74+
# Disconnected function will be called when the client disconnects.
75+
print("Disconnected from Adafruit IO!")
76+
77+
78+
# pylint: disable=unused-argument
79+
def on_message(client, feed_id, payload):
80+
# Message function will be called when a subscribed feed has a new value.
81+
# The feed_id parameter identifies the feed, and the payload parameter has
82+
# the new value.
83+
print("Feed {0} received new value: {1}".format(feed_id, payload))
84+
85+
86+
def on_relay_msg(client, topic, message):
87+
# Method called whenever user/feeds/relay has a new value
88+
if message == "morning":
89+
print("Morning - turning outlet ON")
90+
power_pin.value = True
91+
elif message == "night":
92+
print("Night - turning outlet OFF")
93+
power_pin.value = False
94+
else:
95+
print("Unexpected value received on relay feed.")
96+
97+
98+
# Connect to WiFi
99+
print("Connecting to WiFi...")
100+
wifi.connect()
101+
print("Connected!")
102+
103+
# Initialize MQTT interface with the esp interface
104+
MQTT.set_socket(socket, esp)
105+
106+
# Initialize a new MQTT Client object
107+
mqtt_client = MQTT.MQTT(
108+
broker="io.adafruit.com",
109+
username=secrets["aio_username"],
110+
password=secrets["aio_key"],
111+
)
112+
113+
# Initialize an Adafruit IO MQTT Client
114+
io = IO_MQTT(mqtt_client)
115+
116+
# Connect the callback methods defined above to Adafruit IO
117+
io.on_connect = connected
118+
io.on_disconnect = disconnected
119+
io.on_subscribe = subscribe
120+
io.on_unsubscribe = unsubscribe
121+
io.on_message = on_message
122+
123+
# Connect to Adafruit IO
124+
print("Connecting to Adafruit IO...")
125+
io.connect()
126+
127+
# Set up a message handler for the relay feed
128+
io.add_feed_callback("relay", on_relay_msg)
129+
130+
# Subscribe to all messages on the relay feed
131+
io.subscribe("relay")
132+
133+
# Get the most recent value on the relay feed
134+
io.get("relay")
135+
136+
# Start a blocking loop to check for new messages
137+
while True:
138+
try:
139+
io.loop()
140+
except (ValueError, RuntimeError) as e:
141+
print("Failed to get data, retrying\n", e)
142+
wifi.reset()
143+
io.reconnect()
144+
continue
145+
time.sleep(0.5)

0 commit comments

Comments
 (0)