Secrets Cleanup: C and E

This commit is contained in:
Justin Myers 2025-03-12 14:58:28 -07:00
parent c322fbd036
commit 25db1babaa
11 changed files with 130 additions and 100 deletions

View file

@ -62,18 +62,10 @@ from rps_crypto import bytesPad, strUnpad, generateOTPadKey, \
from rps_display import RPSDisplay, blankScreen from rps_display import RPSDisplay, blankScreen
# Look for our name in secrets.py file if present # Look for our name in settings.toml file if present
ble_name = None ble_name = os.getenv("rps_name", os.getenv("ble_name"))
try: if ble_name is None:
from secrets import secrets print("INFO: No rps_name or ble_name entry found in settings.toml")
ble_name = secrets.get("rps_name")
if ble_name is None:
ble_name = secrets.get("ble_name")
if ble_name is None:
print("INFO: No rps_name or ble_name entry found in secrets dict")
except ImportError:
pass # File is optional, reaching here is not a program error
debug = 1 debug = 1
@ -228,7 +220,7 @@ LAST_ACK_TIME_S = 1.5
# Intro screen with audio # Intro screen with audio
rps_display.introductionScreen() rps_display.introductionScreen()
# Enable the Bluetooth LE radio and set player's name (from secrets.py) # Enable the Bluetooth LE radio and set player's name (from settings.toml)
ble = BLERadio() ble = BLERadio()
if ble_name is not None: if ble_name is not None:
ble.name = ble_name ble.name = ble_name

View file

@ -6,10 +6,9 @@
CHEEKMATE: secret message receiver using WiFi, Adafruit IO and a haptic CHEEKMATE: secret message receiver using WiFi, Adafruit IO and a haptic
buzzer. Periodically polls an Adafruit IO dashboard, converting new messages buzzer. Periodically polls an Adafruit IO dashboard, converting new messages
to Morse code. to Morse code.
secrets.py file must be present and contain WiFi & Adafruit IO credentials.
""" """
from os import getenv
import gc import gc
import time import time
import ssl import ssl
@ -23,11 +22,20 @@ import supervisor
import wifi import wifi
from adafruit_io.adafruit_io import IO_HTTP from adafruit_io.adafruit_io import IO_HTTP
try: # Get WiFi details and Adafruit IO keys, ensure these are setup in settings.toml
from secrets import secrets # (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.)
except ImportError: ssid = getenv("CIRCUITPY_WIFI_SSID")
print("WiFi secrets are kept in secrets.py, please add them there!") password = getenv("CIRCUITPY_WIFI_PASSWORD")
raise aio_username = getenv("ADAFRUIT_AIO_USERNAME")
aio_key = getenv("ADAFRUIT_AIO_KEY")
if None in [ssid, password, aio_username, aio_key]:
raise RuntimeError(
"WiFi and Adafruit IO settings are kept in settings.toml, "
"please add them there. The settings file must contain "
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
"'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY' at a minimum."
)
# CONFIGURABLE GLOBALS ----------------------------------------------------- # CONFIGURABLE GLOBALS -----------------------------------------------------
@ -154,10 +162,10 @@ i2c.unlock()
# WIFI CONNECT ------------------------------------------------------------- # WIFI CONNECT -------------------------------------------------------------
try: try:
print("Connecting to {}...".format(secrets["ssid"]), end="") print(f"Connecting to {ssid}...")
wifi.radio.connect(secrets["ssid"], secrets["password"]) wifi.radio.connect(ssid, password)
print("OK") print("OK")
print("IP:", wifi.radio.ipv4_address) print(f"IP: {wifi.radio.ipv4_address}")
pool = socketpool.SocketPool(wifi.radio) pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context()) requests = adafruit_requests.Session(pool, ssl.create_default_context())
@ -169,8 +177,6 @@ except Exception as error: # pylint: disable=broad-except
# ADAFRUIT IO INITIALIZATION ----------------------------------------------- # ADAFRUIT IO INITIALIZATION -----------------------------------------------
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
io = IO_HTTP(aio_username, aio_key, requests) io = IO_HTTP(aio_username, aio_key, requests)
# SUCCESSFUL STARTUP, PROCEED INTO MAIN LOOP ------------------------------- # SUCCESSFUL STARTUP, PROCEED INTO MAIN LOOP -------------------------------

View file

@ -2,6 +2,7 @@
# #
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
from os import getenv
import time import time
import random import random
import audioio import audioio
@ -20,25 +21,29 @@ print("ESP32 Open Weather API demo")
button = digitalio.DigitalInOut(board.A1) button = digitalio.DigitalInOut(board.A1)
button.switch_to_input(pull=digitalio.Pull.UP) button.switch_to_input(pull=digitalio.Pull.UP)
wave_file = open("sound/Rain.wav", "rb") with open("sound/Rain.wav", "rb") as wave_file:
wave = audiocore.WaveFile(wave_file) wave = audiocore.WaveFile(wave_file)
audio = audioio.AudioOut(board.A0) audio = audioio.AudioOut(board.A0)
# Get WiFi details, ensure these are setup in settings.toml
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")
# Get wifi details and more from a secrets.py file if None in [ssid, password]:
try: raise RuntimeError(
from secrets import secrets "WiFi settings are kept in settings.toml, "
except ImportError: "please add them there. The settings file must contain "
print("WiFi secrets are kept in secrets.py, please add them there!") "'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
raise "at a minimum."
)
# Use cityname, country code where countrycode is ISO3166 format. # Use cityname, country code where countrycode is ISO3166 format.
# E.g. "New York, US" or "London, GB" # E.g. "New York, US" or "London, GB"
LOCATION = secrets['timezone'] LOCATION = getenv('timezone')
# Set up where we'll be fetching data from # Set up where we'll be fetching data from
DATA_SOURCE = "http://api.openweathermap.org/data/2.5/weather?q="+secrets['timezone'] DATA_SOURCE = "http://api.openweathermap.org/data/2.5/weather?q="+LOCATION
DATA_SOURCE += "&appid="+secrets['openweather_token'] DATA_SOURCE += "&appid="+getenv('openweather_token')
# If you are using a board with pre-defined ESP32 Pins: # If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS) esp32_cs = DigitalInOut(board.ESP_CS)
@ -47,8 +52,8 @@ esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
pixels = neopixel.NeoPixel(board.D2, 150, brightness=1.0, auto_write=False) pixels = neopixel.NeoPixel(board.D2, 150, brightness=1.0, auto_write=False)
pixels.fill(0x050505) pixels.fill(0x050505)
pixels.show() pixels.show()
@ -134,18 +139,18 @@ while True:
raining = snowing = thundering = has_sound = False raining = snowing = thundering = has_sound = False
if weather_type == 'Sunny': if weather_type == 'Sunny':
palette = sunny_palette palette = sunny_palette
wave_file = open("sound/Clear.wav", "rb") with open("sound/Clear.wav", "rb") as wave_file:
wave = audiocore.WaveFile(wave_file) wave = audiocore.WaveFile(wave_file)
has_sound = True has_sound = True
if weather_type == 'Clouds': if weather_type == 'Clouds':
palette = cloudy_palette palette = cloudy_palette
wave_file = open("sound/Clouds.wav", "rb") with open("sound/Clouds.wav", "rb") as wave_file:
wave = audiocore.WaveFile(wave_file) wave = audiocore.WaveFile(wave_file)
has_sound = True has_sound = True
if weather_type == 'Rain': if weather_type == 'Rain':
palette = cloudy_palette palette = cloudy_palette
wave_file = open("sound/Rain.wav", "rb") with open("sound/Rain.wav", "rb") as wave_file:
wave = audiocore.WaveFile(wave_file) wave = audiocore.WaveFile(wave_file)
raining = True raining = True
has_sound = True has_sound = True
if weather_type == 'Thunderstorm': if weather_type == 'Thunderstorm':
@ -156,8 +161,8 @@ while True:
next_bolt_time = time.monotonic() + random.randint(1, 5) next_bolt_time = time.monotonic() + random.randint(1, 5)
if weather_type == 'Snow': if weather_type == 'Snow':
palette = cloudy_palette palette = cloudy_palette
wave_file = open("sound/Snow.wav", "rb") with open("sound/Snow.wav", "rb") as wave_file:
wave = audiocore.WaveFile(wave_file) wave = audiocore.WaveFile(wave_file)
snowing = True snowing = True
has_sound = True has_sound = True
weather_refresh = time.monotonic() weather_refresh = time.monotonic()
@ -204,11 +209,13 @@ while True:
# pick next thunderbolt time now # pick next thunderbolt time now
Thunder = random.randint(0, 2) Thunder = random.randint(0, 2)
if Thunder == 0: if Thunder == 0:
wave_file = open("sound/Thunderstorm0.wav", "rb") wave_filename = "sound/Thunderstorm0.wav"
elif Thunder == 1: elif Thunder == 1:
wave_file = open("sound/Thunderstorm1.wav", "rb") wave_filename = "sound/Thunderstorm1.wav"
elif Thunder == 2: elif Thunder == 2:
wave_file = open("sound/Thunderstorm2.wav", "rb") wave_filename = "sound/Thunderstorm2.wav"
wave = audiocore.WaveFile(wave_file) if wave_filename:
audio.play(wave) with open(wave_filename, "rb") as wave_file:
wave = audiocore.WaveFile(wave_file)
audio.play(wave)
next_bolt_time = time.monotonic() + random.randint(5, 15) # between 5 and 15 s next_bolt_time = time.monotonic() + random.randint(5, 15) # between 5 and 15 s

View file

@ -1,13 +0,0 @@
# SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
secrets = {
'ssid' : 'my_ssid',
'password' : 'my_pass',
'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
'openweather_token' : 'putYourOpenWeatherTokenHere',
}

View file

@ -0,0 +1,12 @@
# SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# This file is where you keep private settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
CIRCUITPY_WIFI_SSID="your-wifi-ssid"
CIRCUITPY_WIFI_PASSWORD="your-wifi-password"
timezone="America/New_York" # http://worldtimeapi.org/timezones
openweather_token="putYourOpenWeatherTokenHere"

View file

@ -4,12 +4,12 @@
""" """
This demo is designed for the Kaluga development kit version 1.3 with the This demo is designed for the Kaluga development kit version 1.3 with the
ILI9341 display. Your secrets.py must be populated with your wifi credentials ILI9341 display. Your settings.toml must be populated with your wifi credentials
and your Adafruit IO credentials. and your Adafruit IO credentials.
""" """
from os import getenv
import ssl import ssl
from secrets import secrets
from ulab import numpy as np from ulab import numpy as np
from terminalio import FONT from terminalio import FONT
import board import board
@ -25,6 +25,21 @@ from adafruit_ili9341 import ILI9341
from adafruit_io.adafruit_io import IO_MQTT from adafruit_io.adafruit_io import IO_MQTT
import adafruit_minimqtt.adafruit_minimqtt as MQTT import adafruit_minimqtt.adafruit_minimqtt as MQTT
# Get WiFi details and Adafruit IO keys, ensure these are setup in settings.toml
# (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.)
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")
aio_username = getenv("ADAFRUIT_AIO_USERNAME")
aio_key = getenv("ADAFRUIT_AIO_KEY")
if None in [ssid, password, aio_username, aio_key]:
raise RuntimeError(
"WiFi and Adafruit IO settings are kept in settings.toml, "
"please add them there. The settings file must contain "
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
"'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY' at a minimum."
)
# To change the name of the feed on adafruit_io, just modify this string: # To change the name of the feed on adafruit_io, just modify this string:
feed_name = "qrstring" feed_name = "qrstring"
@ -53,14 +68,14 @@ cam.flip_y = False
cam.colorspace = adafruit_ov2640.OV2640_COLOR_YUV cam.colorspace = adafruit_ov2640.OV2640_COLOR_YUV
print("Connecting to WIFI") print("Connecting to WIFI")
wifi.radio.connect(secrets["ssid"], secrets["password"]) wifi.radio.connect(ssid, password)
pool = socketpool.SocketPool(wifi.radio) pool = socketpool.SocketPool(wifi.radio)
print("Connecting to Adafruit IO") print("Connecting to Adafruit IO")
mqtt_client = MQTT.MQTT( mqtt_client = MQTT.MQTT(
broker="io.adafruit.com", broker="io.adafruit.com",
username=secrets["aio_username"], username=aio_username,
password=secrets["aio_key"], password=aio_key,
socket_pool=pool, socket_pool=pool,
ssl_context=ssl.create_default_context(), ssl_context=ssl.create_default_context(),
) )

View file

@ -4,8 +4,7 @@
""" """
This demo is designed for the Kaluga development kit version 1.3 with the This demo is designed for the Kaluga development kit version 1.3 with the
ILI9341 display. Your secrets.py must be populated with your wifi credentials ILI9341 display.
and your Adafruit IO credentials.
""" """
from ulab import numpy as np from ulab import numpy as np

View file

@ -2,6 +2,7 @@
# #
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
from os import getenv
import time import time
import board import board
from digitalio import DigitalInOut from digitalio import DigitalInOut
@ -14,12 +15,17 @@ import displayio
minitft = minitft_featherwing.MiniTFTFeatherWing() minitft = minitft_featherwing.MiniTFTFeatherWing()
# Get wifi details and more from a secrets.py file # Get WiFi details, ensure these are setup in settings.toml
try: ssid = getenv("CIRCUITPY_WIFI_SSID")
from secrets import secrets password = getenv("CIRCUITPY_WIFI_PASSWORD")
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!") if None in [ssid, password]:
raise raise RuntimeError(
"WiFi settings are kept in settings.toml, "
"please add them there. The settings file must contain "
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
"at a minimum."
)
# If you are using a board with pre-defined ESP32 Pins: # If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.D13) esp32_cs = DigitalInOut(board.D13)
@ -27,11 +33,11 @@ esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12) esp32_reset = DigitalInOut(board.D12)
spi = board.SPI() spi = board.SPI()
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets) wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password)
# Symbol "INX" for S&P500, "DJIA" for Dow # Symbol "INX" for S&P500, "DJIA" for Dow
DATA_SOURCE = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&apikey=" DATA_SOURCE = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&apikey="
DATA_SOURCE += secrets['alphavantage_key'] DATA_SOURCE += getenv('alphavantage_key')
symbols = ["DJIA", "INX", "AAPL", "TSLA", "MSFT"] symbols = ["DJIA", "INX", "AAPL", "TSLA", "MSFT"]
# Set text, font, and color # Set text, font, and color

View file

@ -1,11 +0,0 @@
# SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT
secrets = {
'ssid' : 'myssid',
'password' : 'mypassword',
'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
'alphavantage_key' : 'GRABAFREEKEYONLINE'
}

View file

@ -0,0 +1,11 @@
# SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# This file is where you keep private settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
CIRCUITPY_WIFI_SSID="your-wifi-ssid"
CIRCUITPY_WIFI_PASSWORD="your-wifi-password"
timezone="America/New_York" # http://worldtimeapi.org/timezones
alphavantage_key="GRABAFREEKEYONLINE"

View file

@ -2,6 +2,7 @@
# #
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
from os import getenv
import ipaddress import ipaddress
import ssl import ssl
import wifi import wifi
@ -13,12 +14,17 @@ TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_QUOTES_URL = "https://www.adafruit.com/api/quotes.php" JSON_QUOTES_URL = "https://www.adafruit.com/api/quotes.php"
JSON_STARS_URL = "https://api.github.com/repos/adafruit/circuitpython" JSON_STARS_URL = "https://api.github.com/repos/adafruit/circuitpython"
# Get wifi details and more from a secrets.py file # Get WiFi details, ensure these are setup in settings.toml
try: ssid = getenv("CIRCUITPY_WIFI_SSID")
from secrets import secrets password = getenv("CIRCUITPY_WIFI_PASSWORD")
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!") if None in [ssid, password]:
raise raise RuntimeError(
"WiFi settings are kept in settings.toml, "
"please add them there. The settings file must contain "
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
"at a minimum."
)
print("ESP32-S2 WebClient Test") print("ESP32-S2 WebClient Test")
@ -30,10 +36,10 @@ for network in wifi.radio.start_scanning_networks():
network.rssi, network.channel)) network.rssi, network.channel))
wifi.radio.stop_scanning_networks() wifi.radio.stop_scanning_networks()
print("Connecting to %s"%secrets["ssid"]) print(f"Connecting to {ssid}")
wifi.radio.connect(secrets["ssid"], secrets["password"]) wifi.radio.connect(ssid, password)
print("Connected to %s!"%secrets["ssid"]) print(f"Connected to {ssid}!")
print("My IP address is", wifi.radio.ipv4_address) print(f"My IP address is {wifi.radio.ipv4_address}")
ipv4 = ipaddress.ip_address("8.8.4.4") ipv4 = ipaddress.ip_address("8.8.4.4")
print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000)) print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000))