Skip to content

Commit 279ea10

Browse files
authored
Merge branch 'master' into master
2 parents 522677b + f290b4a commit 279ea10

File tree

146 files changed

+318863
-237588
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

146 files changed

+318863
-237588
lines changed

Adafruit_IO_Power_Relay/code.py

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
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+
def on_message(client, topic, message):
81+
# Method callled when a client's subscribed feed has a new value.
82+
print("New message on topic {0}: {1}".format(topic, message))
83+
84+
85+
def on_relay_msg(client, topic, value):
86+
# Called when relay feed obtains a new value
87+
print("Turning Relay %s"%value)
88+
if value == "ON":
89+
power_pin.value = True
90+
elif value == "OFF":
91+
power_pin.value = False
92+
else:
93+
print("Unexpected value received on relay feed.")
94+
95+
# Connect to WiFi
96+
print("Connecting to WiFi...")
97+
wifi.connect()
98+
print("Connected!")
99+
100+
MQTT.set_socket(socket, esp)
101+
102+
# Set up a MiniMQTT Client
103+
client = MQTT.MQTT(
104+
broker="io.adafruit.com",
105+
username=secrets["aio_username"],
106+
password=secrets["aio_key"],
107+
)
108+
109+
# Setup the callback methods above
110+
client.on_connect = connected
111+
client.on_disconnect = disconnected
112+
client.on_subscribe = subscribe
113+
client.on_unsubscribe = unsubscribe
114+
client.on_message = on_message
115+
# Add a callback to the relay feed
116+
client.add_topic_callback(feed_relay, on_relay_msg)
117+
118+
# Connect the client to Adafruit IO
119+
print("Connecting to Adafruit IO...")
120+
client.connect()
121+
122+
# Subscribe to all updates on relay feed
123+
client.subscribe(feed_relay)
124+
125+
while True:
126+
try: # Poll for new messages on feed_relay
127+
client.loop()
128+
except (ValueError, RuntimeError) as e:
129+
print("Failed to get data, retrying\n", e)
130+
wifi.reset()
131+
client.reconnect()
132+
continue
133+
time.sleep(0.05)
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
import time
2+
import board
3+
import busio
4+
from digitalio import DigitalInOut
5+
import neopixel
6+
import adafruit_bh1750
7+
from adafruit_esp32spi import adafruit_esp32spi
8+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
9+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
10+
11+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
12+
13+
### Sensor Calibration ###
14+
# Appliance power LED's light level, in Lux
15+
APPLIANCE_ON_LUX = 30.0
16+
# How often the light sensor will be read, in seconds
17+
SENSOR_READ_TIME = 10.0
18+
19+
### WiFi ###
20+
21+
# Get wifi details and more from a secrets.py file
22+
try:
23+
from secrets import secrets
24+
except ImportError:
25+
print("WiFi secrets are kept in secrets.py, please add them there!")
26+
raise
27+
28+
# If you are using a board with pre-defined ESP32 Pins:
29+
esp32_cs = DigitalInOut(board.ESP_CS)
30+
esp32_ready = DigitalInOut(board.ESP_BUSY)
31+
esp32_reset = DigitalInOut(board.ESP_RESET)
32+
33+
# If you have an externally connected ESP32:
34+
# esp32_cs = DigitalInOut(board.D9)
35+
# esp32_ready = DigitalInOut(board.D10)
36+
# esp32_reset = DigitalInOut(board.D5)
37+
38+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
39+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
40+
"""Use below for Most Boards"""
41+
status_light = neopixel.NeoPixel(
42+
board.NEOPIXEL, 1, brightness=0.2
43+
) # Uncomment for Most Boards
44+
"""Uncomment below for ItsyBitsy M4"""
45+
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
46+
# Uncomment below for an externally defined RGB LED
47+
# import adafruit_rgbled
48+
# from adafruit_esp32spi import PWMOut
49+
# RED_LED = PWMOut.PWMOut(esp, 26)
50+
# GREEN_LED = PWMOut.PWMOut(esp, 27)
51+
# BLUE_LED = PWMOut.PWMOut(esp, 25)
52+
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
53+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
54+
55+
# Set up a pin for controlling the relay
56+
power_pin = DigitalInOut(board.D3)
57+
power_pin.switch_to_output()
58+
59+
# Set up the light sensor
60+
i2c = board.I2C()
61+
sensor = adafruit_bh1750.BH1750(i2c)
62+
63+
### Feeds ###
64+
# Set up a feed named Relay for subscribing to the relay feed on Adafruit IO
65+
feed_relay = secrets["aio_username"] + "/feeds/relay"
66+
67+
# Set up a feed named status for subscribing to the status feed on Adafruit IO
68+
feed_status = secrets["aio_username"] + "/feeds/status"
69+
70+
### Code ###
71+
72+
# Define callback methods which are called when events occur
73+
# pylint: disable=unused-argument, redefined-outer-name
74+
def connected(client, userdata, flags, rc):
75+
# This function will be called when the client is connected
76+
# successfully to the broker.
77+
print("Connected to Adafruit IO!")
78+
79+
80+
def disconnected(client, userdata, rc):
81+
# This method is called when the client is disconnected
82+
print("Disconnected from Adafruit IO!")
83+
84+
85+
def subscribe(client, userdata, topic, granted_qos):
86+
# This method is called when the client subscribes to a new feed.
87+
print("Subscribed to {0}".format(topic))
88+
89+
90+
def unsubscribe(client, userdata, topic, pid):
91+
# This method is called when the client unsubscribes from a feed.
92+
print("Unsubscribed from {0} with PID {1}".format(topic, pid))
93+
94+
def on_message(client, topic, message):
95+
# Method callled when a client's subscribed feed has a new value.
96+
print("New message on topic {0}: {1}".format(topic, message))
97+
98+
99+
def on_relay_msg(client, topic, value):
100+
# Called when relay feed obtains a new value
101+
print("Turning Relay %s"%value)
102+
if value == "ON":
103+
power_pin.value = True
104+
elif value == "OFF":
105+
power_pin.value = False
106+
else:
107+
print("Unexpected value received on relay feed.")
108+
109+
# Connect to WiFi
110+
print("Connecting to WiFi...")
111+
wifi.connect()
112+
print("Connected!")
113+
114+
MQTT.set_socket(socket, esp)
115+
116+
# Set up a MiniMQTT Client
117+
client = MQTT.MQTT(
118+
broker="io.adafruit.com",
119+
username=secrets["aio_username"],
120+
password=secrets["aio_key"],
121+
)
122+
123+
# Setup the callback methods above
124+
client.on_connect = connected
125+
client.on_disconnect = disconnected
126+
client.on_subscribe = subscribe
127+
client.on_unsubscribe = unsubscribe
128+
client.on_message = on_message
129+
# Add a callback to the relay feed
130+
client.add_topic_callback(feed_relay, on_relay_msg)
131+
132+
# Connect the client to Adafruit IO
133+
print("Connecting to Adafruit IO...")
134+
client.connect()
135+
136+
# Subscribe to all updates on relay feed
137+
client.subscribe(feed_relay)
138+
139+
# Holds previous state of light sensor
140+
prv_sensor_value = 0
141+
# Time in seconds since start
142+
start_time = time.monotonic()
143+
144+
while True:
145+
try:
146+
# Poll for new messages on feed_relay
147+
client.loop()
148+
now = time.monotonic()
149+
if now - start_time > SENSOR_READ_TIME:
150+
# Read light sensor
151+
print("Reading light sensor")
152+
sensor_value = sensor.lux
153+
print("%.2f Lux" % sensor.lux)
154+
if sensor_value != prv_sensor_value:
155+
# Light sensor value changed between readings
156+
if sensor_value > APPLIANCE_ON_LUX:
157+
# Appliance is ON, publish to feed_status
158+
print("Appliance ON, publishing to IO...")
159+
client.publish(feed_status, 1)
160+
print("Published!")
161+
else:
162+
# Appliance is OFF, publish to feed_status
163+
print("Appliance OFF, publishing to IO...")
164+
client.publish(feed_status, 2)
165+
print("Published!")
166+
prv_sensor_value = sensor_value
167+
start_time = now
168+
except (ValueError, RuntimeError) as e:
169+
print("Failed to get data, retrying\n", e)
170+
wifi.reset()
171+
client.reconnect()
172+
continue
173+
time.sleep(0.5)

0 commit comments

Comments
 (0)