Skip to content

Instantly share code, notes, and snippets.

@gallaugher
Created April 5, 2023 15:33
Show Gist options
  • Save gallaugher/79112d3a7d8d80717726d84a5a2ca912 to your computer and use it in GitHub Desktop.
Save gallaugher/79112d3a7d8d80717726d84a5a2ca912 to your computer and use it in GitHub Desktop.
Playback from Adafruit IO - button sound crashes on third interrupted playback
# MQTT With Color Picker - Adafruit I0
import board, time, neopixel
import os, ssl, socketpool, wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
# import lines for audio & mp3 playing
from audiopwmio import PWMAudioOut as AudioOut
from audiomp3 import MP3Decoder
# setup the speaker
audio = AudioOut(board.GP16) # assuming tip of speaker attached to GP16
# folder where sounds can be found on device
path = "sounds/"
# setup the mp3 decoder
filename = "encouragement1.mp3"
mp3_file = open(path + filename, "rb")
decoder = MP3Decoder(mp3_file)
# play an mp3 function - pass in string with extension
def play_mp3(filename):
decoder.file = open(path + filename, "rb")
audio.play(decoder)
while audio.playing:
mqtt_client.loop() # respond to messages while sound plays
# setup neopixel strip
strip = neopixel.NeoPixel(board.GP15, 30)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
strip.fill(BLACK)
strip_color = RED # global value to hold current color
# convert hex to rgb tuple
def hex_to_rgb(hex):
rgb = []
for i in (0, 2, 4):
decimal = int(hex[i:i+2], 16) # converts two digit hex to int
rgb.append(decimal)
return tuple(rgb)
# Get adafruit io username and key from settings.toml
aio_username = os.getenv('AIO_USERNAME')
aio_key = os.getenv('AIO_KEY')
# Setup a feed: This may have a different name than your Dashboard
strip_on_off_feed = aio_username + "/feeds/strip_on_off"
color_feed = aio_username + "/feeds/color_feed"
sounds_feed = aio_username + "/feeds/sounds_feed"
# Setup functions to respond to MQTT events
def connected(client, userdata, flags, rc):
# Connected to broker at adafruit io
print("Connected to Adafruit IO! Listening for topic changes in feeds I've subscribed to")
# Subscribe to all changes on the feed.
client.subscribe(strip_on_off_feed)
client.subscribe(color_feed)
client.subscribe(sounds_feed)
def disconnected(client, userdata, rc):
# Disconnected from the broker at adafruit io
print("Disconnected from Adafruit IO!")
def message(client, topic, message):
# The bulk of your code to respond to MQTT will be here, NOT in while True:
global strip_color # strip_color will be used outside this function
print(f"topic: {topic}, message: {message}")
if topic == strip_on_off_feed: # on/off toggled
if message == "ON":
strip.fill(strip_color)
strip.brightness = 1.0
elif message == "OFF":
strip.fill(BLACK)
strip.brightness = 0.0
elif topic == color_feed: # color picker used
if message[0] == "#": # all colors should start with # for hex
message = message[1:] # removes # value from string
# convert hex value in message to rgb tuple
strip_color = hex_to_rgb(message)
strip.fill(strip_color)
elif topic == sounds_feed: # sound button is pressed
if message != "0": # make sure it's not a button release msg.
if audio.playing:
audio.stop()
play_mp3(message)
# Connect to WiFi
print(f"Connecting to WiFi")
wifi.radio.connect(os.getenv("WIFI_SSID"), os.getenv("WIFI_PASSWORD"))
print("Connected!")
# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)
# Set up a MiniMQTT Client - this is our current program that subscribes or "listens")
mqtt_client = MQTT.MQTT(
broker=os.getenv("BROKER"),
port=os.getenv("PORT"),
username=aio_username,
password=aio_key,
socket_pool=pool,
ssl_context=ssl.create_default_context(),
)
# Setup the "callback" mqtt methods above
mqtt_client.on_connect = connected
mqtt_client.on_disconnect = disconnected
mqtt_client.on_message = message
# Connect to the MQTT broker (adafruit io for us)
print("Connecting to Adafruit IO...")
mqtt_client.connect()
while True:
# keep checking the mqtt message queue
mqtt_client.loop()
# If you had other non mqtt code, you could add it here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment