Added FunHouse IOT hub stuff

This commit is contained in:
dherrada 2021-05-14 14:30:41 -04:00
parent 9547afedb9
commit c01b9cc574
10 changed files with 1037 additions and 0 deletions

View file

@ -0,0 +1,130 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Adafruit IO connected LiPo charger.
Uses:
* https://www.adafruit.com/product/4712
* Feather board (M4 or RP2040 reccomended)
* https://www.adafruit.com/product/4264
* https://www.adafruit.com/product/2890
* https://www.adafruit.com/product/2900
Either the Feather or the Airlift Featherwing should have stacking headers for the display.
"""
import time
import board
from adafruit_lc709203f import LC709203F
import busio
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
import displayio
import terminalio
from adafruit_display_text import label
import adafruit_displayio_ssd1306
displayio.release_displays()
### WiFi ###
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
client.subscribe("battery")
def subscribe(client, userdata, topic, granted_qos):
# This method is called when the client subscribes to a new feed.
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
def message(client, feed_id, payload):
print("Feed {0} received new value: {1}".format(feed_id, payload))
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
io.on_message = message
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
display_bus = displayio.I2CDisplay(board.I2C(), device_address=0x3C)
WIDTH = 128
HEIGHT = 32
BORDER = 2
display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=WIDTH, height=HEIGHT)
splash = displayio.Group(max_size=10)
display.show(splash)
digital_label = label.Label(
terminalio.FONT, text="Battery Percent: ", color=0xFFFFFF, x=4, y=4
)
splash.append(digital_label)
alarm_label = label.Label(terminalio.FONT, text="Voltage: ", color=0xFFFFFF, x=4, y=14)
splash.append(alarm_label)
sensor = LC709203F(board.I2C())
start = 0
while True:
io.loop()
percent = sensor.cell_percent
if time.time() - start > 60:
io.publish("battery", int(percent))
start = time.time()
splash[0].text = f"Percent: {str(int(percent))}%"
splash[1].text = f"Voltage: {str(sensor.cell_voltage)}"
time.sleep(1)

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

242
FunHouse_IOT_Hub/code.py Normal file
View file

@ -0,0 +1,242 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time
import ssl
import displayio
import board
from digitalio import DigitalInOut, Direction, Pull
from adafruit_display_text.label import Label
import terminalio
import touchio
import socketpool
import wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from adafruit_dash_display import Hub
# Set up navigation buttons
up = DigitalInOut(board.BUTTON_UP)
up.direction = Direction.INPUT
up.pull = Pull.DOWN
select = DigitalInOut(board.BUTTON_SELECT)
select.direction = Direction.INPUT
select.pull = Pull.DOWN
down = DigitalInOut(board.BUTTON_DOWN)
down.direction = Direction.INPUT
down.pull = Pull.DOWN
back = touchio.TouchIn(board.CAP7)
submit = touchio.TouchIn(board.CAP8)
# Check for secrets.py. Note: for this project, your secrets.py needs an adafruit io api key as
# well as the wifi information
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# Make the rgb group for setting rgb hex values for NeoPixels
rgb_group = displayio.Group(max_size=9)
R_label = Label(
terminalio.FONT,
text=" +\nR:\n -",
color=0xFFFFFF,
anchor_point=((0, 0.5)),
anchored_position=((5, 120)),
scale=2,
)
G_label = Label(
terminalio.FONT,
text=" +\nG:\n -",
color=0xFFFFFF,
anchor_point=((0, 0.5)),
anchored_position=((90, 120)),
scale=2,
)
B_label = Label(
terminalio.FONT,
text=" +\nB:\n -",
color=0xFFFFFF,
anchor_point=((0, 0.5)),
anchored_position=((175, 120)),
scale=2,
)
rgb_group.append(R_label)
rgb_group.append(G_label)
rgb_group.append(B_label)
R = Label(
terminalio.FONT,
text="00",
color=0xFFFFFF,
anchor_point=((0, 0.5)),
anchored_position=((35, 120)),
scale=2,
)
G = Label(
terminalio.FONT,
text="00",
color=0xFFFFFF,
anchor_point=((0, 0.5)),
anchored_position=((120, 120)),
scale=2,
)
B = Label(
terminalio.FONT,
text="00",
color=0xFFFFFF,
anchor_point=((0, 0.5)),
anchored_position=((205, 120)),
scale=2,
)
rgb_group.append(R)
rgb_group.append(G)
rgb_group.append(B)
# Set up callbacks
# pylint: disable=unused-argument
def rgb(last):
""" Function for when the rgb screen is active """
display.show(None)
rgb_group[3].text = "00"
rgb_group[4].text = "00"
rgb_group[5].text = "00"
display.show(rgb_group)
time.sleep(0.2)
index = 0
colors = [00, 00, 00]
while True:
if select.value:
index += 1
if index == 3:
index = 0
time.sleep(0.3)
continue
if up.value:
colors[index] += 1
if colors[index] == 256:
colors[index] = 0
rgb_group[index + 3].text = hex(colors[index])[2:]
time.sleep(0.01)
continue
if down.value:
colors[index] -= 1
if colors[index] == -1:
colors[index] = 255
rgb_group[index + 3].text = hex(colors[index])[2:]
time.sleep(0.01)
continue
if submit.value:
color = ["{:02x}".format(colors[i]) for i in range(len(colors))]
color = "#" + "".join(color)
iot.publish("neopixel", color)
break
if back.value:
break
time.sleep(0.1)
display.show(None)
time.sleep(0.1)
def rgb_set_color(message):
""" Sets the color of the rgb label based on the value of the feed """
return int(message[1:], 16)
def door_color(message):
""" Sets the color of the door label based on the value of the feed """
door = bool(int(message))
if door:
return int(0x00FF00)
return int(0xFF0000)
def on_door(client, feed_id, message):
""" Sets the door text based on the value of the feed """
door = bool(int(message))
if door:
return "Door: Closed"
return "Door: Open"
def pub_lamp(lamp):
if isinstance(lamp, str):
lamp = eval(lamp) # pylint: disable=eval-used
iot.publish("lamp", str(not lamp))
# funhouse.set_text(f"Lamp: {not lamp}", 0)
time.sleep(0.3)
display = board.DISPLAY
# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])
# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
socket_pool=pool,
ssl_context=ssl.create_default_context(),
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
iot = Hub(display=display, io=io, nav=(up, select, down, back, submit))
iot.add_device(
feed_key="lamp",
default_text="Lamp: ",
formatted_text="Lamp: {}",
pub_method=pub_lamp,
)
iot.add_device(
feed_key="temperature",
default_text="Temperature: ",
formatted_text="Temperature: {:.1f} C",
)
iot.add_device(
feed_key="humidity", default_text="Humidity: ", formatted_text="Humidity: {:.2f}%"
)
iot.add_device(
feed_key="neopixel",
default_text="LED: ",
formatted_text="LED: {}",
color_callback=rgb_set_color,
pub_method=rgb,
)
iot.add_device(
feed_key="battery",
default_text="Battery: ",
formatted_text="Battery: {}%",
)
iot.add_device(
feed_key="door",
default_text="Door: ",
formatted_text="Door: {}",
color_callback=door_color,
callback=on_door,
)
iot.get()
while True:
iot.loop()
time.sleep(0.01)

View file

@ -0,0 +1,90 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Adafruit IO connected door sensor.
Uses:
* https://www.adafruit.com/product/375
* Feather board
* https://www.adafruit.com/product/2890
* https://www.adafruit.com/product/4264
* https://www.adafruit.com/product/3786
This isn't necessary, but it makes it easier to connect the sensor to the Microcontroller if
either the Feather or the AirLift Featherwing has stacking headers.
"""
import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from digitalio import DigitalInOut, Direction, Pull
from adafruit_debouncer import Debouncer
### WiFi ###
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
switch_pin = DigitalInOut(board.D10)
switch_pin.direction = Direction.INPUT
switch_pin.pull = Pull.UP
switch = Debouncer(switch_pin)
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
while True:
switch.update()
print(switch.state)
if switch.rose:
print("Door is open")
io.publish("door", 0)
print("sent")
if switch.fell:
print("Door is closed")
io.publish("door", 1)
print("sent")

View file

@ -0,0 +1,105 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Sets NeoPixel color based on an Adafruit IO feed.
Uses:
* https://www.adafruit.com/product/3811
* Feather board
* https://www.adafruit.com/product/4264
* https://www.adafruit.com/product/2890
If your Feather board has STEMMA QT, you'll need one of these:
* https://www.adafruit.com/product/4209
But if it doesn't, use stacking headers on either the Feather or the AirLift FeatherWing
"""
import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from digitalio import DigitalInOut
### WiFi ###
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# Change the first number to the pin the data line is plugged in to and the second number
# to the number of pixels
pixels = neopixel.NeoPixel(board.D5, 300)
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
client.subscribe("neopixel")
def subscribe(client, userdata, topic, granted_qos):
# This method is called when the client subscribes to a new feed.
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
def on_neopixel(client, topic, message):
print(message)
colors = [
int(message.split("#")[1][i : i + 2], 16) for i in range(0, len(message) - 1, 2)
]
print(colors)
pixels.fill(colors)
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
io.add_feed_callback("neopixel", on_neopixel)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
io.get("neopixel")
while True:
io.loop()

View file

@ -0,0 +1,147 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
NeoPixel remote control using PyPortal Titano.
Colors used are taken from Adafruit_CircuitPython_LED_Animation library
"""
import time
import math
import board
import busio
from digitalio import DigitalInOut
import displayio
from adafruit_display_shapes.rect import Rect
import adafruit_imageload
import adafruit_touchscreen
# ESP32 SPI
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
# Import NeoPixel Library
import neopixel
# Import Adafruit IO HTTP Client
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
ts = adafruit_touchscreen.Touchscreen(
board.TOUCH_XL,
board.TOUCH_XR,
board.TOUCH_YD,
board.TOUCH_YU,
calibration=((5200, 59000), (5800, 57000)),
size=(480, 320),
)
RED = 0xFF0000
YELLOW = 0xFF9600
ORANGE = 0xFF2800
GREEN = 0x00FF00
TEAL = 0x00FF78
CYAN = 0x00FFFF
BLUE = 0x0000FF
PURPLE = 0xB400FF
MAGENTA = 0xFF0014
WHITE = 0xFFFFFF
BLACK = 0x000000
GOLD = 0xFFDE1E
PINK = 0xF15AFF
AQUA = 0x32FFFF
JADE = 0x00FF28
AMBER = 0xFF6400
colors = [
None,
None,
GREEN,
PURPLE,
GOLD,
AMBER,
None,
None,
ORANGE,
BLUE,
BLACK,
JADE,
None,
None,
YELLOW,
CYAN,
WHITE,
AQUA,
None,
None,
RED,
TEAL,
MAGENTA,
PINK,
]
print(colors)
group = displayio.Group()
# pyportal_setter.xcf has been included so you can edit the colors used in GIMP, just make sure to
# change them here as well
background, palette = adafruit_imageload.load(
"bmps/pyportal_setter.bmp", bitmap=displayio.Bitmap, palette=displayio.Palette
)
tile_grid = displayio.TileGrid(background, pixel_shader=palette)
group.append(tile_grid)
rect = Rect(0, 0, 160, 320, fill=0x000000)
group.append(rect)
print(len(group))
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# PyPortal ESP32 Setup
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
ADAFRUIT_IO_USER = secrets["aio_username"]
ADAFRUIT_IO_KEY = secrets["aio_key"]
# Create an instance of the Adafruit IO HTTP client
io = IO_HTTP(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY, wifi)
try:
# Get the 'temperature' feed from Adafruit IO
neopixel_feed = io.get_feed("neopixel")
except AdafruitIO_RequestError:
neopixel_feed = io.create_new_feed("neopixel")
board.DISPLAY.show(group)
print("ready")
last_color = 257
last_index = 0
while True:
p = ts.touch_point
if p:
x = math.floor(p[0] / 80)
y = math.floor(p[1] / 80)
index = 6 * y + x
# Used to prevent the touchscreen sending incorrect results
if last_index == index:
color = colors[index]
if colors[index]:
group[1].fill = color
if last_color != color:
color_str = "#{:06x}".format(color)
print(color_str)
io.send_data(neopixel_feed["key"], color_str)
last_color = color
last_index = index
time.sleep(0.1)

Binary file not shown.

View file

@ -0,0 +1,98 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Controlling a relay with Adafruit IO
Uses:
* Feather board
* https://www.adafruit.com/product/2890
* https://www.adafruit.com/product/4264
* https://www.adafruit.com/product/3191
OR
* https://www.adafruit.com/product/2935
"""
import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from digitalio import DigitalInOut, Direction
### WiFi ###
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# If you are using a Relay FeatherWing, make sure this pin corresponds to the pin shorted on the
# bottom of the Relay FeatherWing
RELAY = DigitalInOut(board.D10)
RELAY.direction = Direction.OUTPUT
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
client.subscribe("lamp")
def subscribe(client, userdata, topic, granted_qos):
# This method is called when the client subscribes to a new feed.
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
def on_lamp(client, topic, message):
RELAY.value = eval(message) # pylint: disable=eval-used
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
io.add_feed_callback("lamp", on_lamp)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
io.get("lamp")
while True:
io.loop()

View file

@ -0,0 +1,104 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Adafruit IO relay control based on feed that doesn't directly turn the relay on and off
Uses:
* Feather board
* https://www.adafruit.com/product/2890
* https://www.adafruit.com/product/4264
* https://www.adafruit.com/product/3191
OR
* https://www.adafruit.com/product/2935
This example gets a feed which I have set as the calculated heat index (how hot a temperature and
humidity feel) and turns a relay on or off based on that. This relay could have something like
a box fan connected to it.
"""
import board
import busio
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from digitalio import DigitalInOut, Direction
### WiFi ###
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
RELAY = DigitalInOut(board.D10)
RELAY.direction = Direction.OUTPUT
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# Define callback functions which will be called when certain events happen.
# pylint: disable=unused-argument
def connected(client):
client.subscribe("heatindex")
def subscribe(client, userdata, topic, granted_qos):
# This method is called when the client subscribes to a new feed.
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
def on_hi(client, topic, message):
if float(message) > 80.0:
RELAY.value = True
else:
RELAY.value = False
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
io.add_feed_callback("heatindex", on_hi)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
io.get("heatindex")
while True:
io.loop()

View file

@ -0,0 +1,121 @@
# SPDX-FileCopyrightText: 2021 Dylan Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Setting Adafruit IO feeds from a MagTag with a sensor connected over STEMMA QT
Uses:
* https://www.adafruit.com/product/4819
OR
* https://www.adafruit.com/product/4800
* https://www.adafruit.com/product/4236
* https://www.adafruit.com/product/4631
AND
* https://www.adafruit.com/product/4885 (although any sensor should work with a few changes)
* https://www.adafruit.com/product/4399
"""
import ssl
import socketpool
import wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT
from adafruit_magtag.magtag import MagTag
import busio
import board
import adafruit_sht4x
### WiFi ###
# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
# source control.
# pylint: disable=no-name-in-module,wrong-import-order
magtag = MagTag()
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
connected = False
try:
print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])
# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)
# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
broker="io.adafruit.com",
username=secrets["aio_username"],
password=secrets["aio_key"],
socket_pool=pool,
ssl_context=ssl.create_default_context(),
)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
connected = True
except ConnectionError:
pass
i2c = busio.I2C(board.SCL, board.SDA)
sht = adafruit_sht4x.SHT4x(i2c)
print("Found SHT4x with serial number", hex(sht.serial_number))
sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
# Can also set the mode to enable heater
# sht.mode = adafruit_sht4x.Mode.LOWHEAT_100MS
print("Current mode is: ", adafruit_sht4x.Mode.string[sht.mode])
magtag.add_text(
text_position=(50, 128 / 4,), text_scale=2,
)
magtag.add_text(
text_position=(50, (2 * 128) / 4,), text_scale=2,
)
magtag.add_text(
text_position=(50, (3 * 128) / 4,), text_scale=2,
)
temperature, relative_humidity = sht.measurements
magtag.set_text("Temperature: %0.1f C" % temperature, 0, False)
magtag.set_text("Humidity: %0.1f %%" % relative_humidity, 1, False)
T = temperature * 1.8 + 32
humidity = relative_humidity
HI = (
-42.379
+ 2.04901523 * T
+ 10.14333127 * humidity
- 0.22475541 * T * humidity
- 0.00683783 * T * T
- 0.05481717 * humidity ** 2
+ 0.00122874 * T * T * humidity
+ 0.00085282 * T * humidity ** 2
- 0.00000199 * T * T * humidity ** 2
)
magtag.set_text("Feels like: %0.1f F" % HI, 2)
if connected:
io.publish("temperature", temperature)
io.publish("humidity", relative_humidity)
io.publish("heatindex", HI)
magtag.exit_and_deep_sleep(600)