Skip to content

Commit 071c95b

Browse files
authored
Merge pull request #3004 from justmobilize/secrets-cleanup-p-part1
Secrets Cleanup: P Part 1
2 parents 389027c + fb932a9 commit 071c95b

File tree

27 files changed

+338
-200
lines changed

27 files changed

+338
-200
lines changed

Pi_In_Stock_Notifier/code.py

+25-18
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#
33
# SPDX-License-Identifier: MIT
44

5+
from os import getenv
56
import time
67
import ssl
78
import wifi
@@ -14,6 +15,21 @@
1415
from digitalio import DigitalInOut, Direction, Pull
1516
from adafruit_debouncer import Debouncer
1617

18+
# Get WiFi details and Adafruit IO keys, ensure these are setup in settings.toml
19+
# (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.)
20+
ssid = getenv("CIRCUITPY_WIFI_SSID")
21+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
22+
aio_username = getenv("ADAFRUIT_AIO_USERNAME")
23+
aio_key = getenv("ADAFRUIT_AIO_KEY")
24+
25+
if None in [ssid, password, aio_username, aio_key]:
26+
raise RuntimeError(
27+
"WiFi and Adafruit IO settings are kept in settings.toml, "
28+
"please add them there. The settings file must contain "
29+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
30+
"'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY' at a minimum."
31+
)
32+
1733
alarm_out = DigitalInOut(board.A1)
1834
alarm_out.direction = Direction.OUTPUT
1935
alarm_out.value = False
@@ -23,37 +39,28 @@
2339
button = Debouncer(button_in)
2440

2541

26-
# Get wifi details and more from a secrets.py file
27-
try:
28-
from secrets import secrets
29-
except ImportError:
30-
print("WiFi secrets are kept in secrets.py, please add them there!")
31-
raise
32-
3342
print("Adafruit Raspberry Pi In Stock Tweet Listener")
3443

3544
# import your bearer token
36-
bear = secrets['bearer_token']
45+
bearer_token = getenv('bearer_token')
3746

3847
# query URL for tweets. looking for hashtag partyparrot sent to a specific username
3948
# disabling line-too-long because queries for tweet_query & TIME_URL cannot have line breaks
4049
# pylint: disable=line-too-long
4150
tweet_query = 'https://api.twitter.com/2/tweets/search/recent?query=In Stock at Adafruit from:rpilocator&tweet.fields=created_at'
4251

43-
headers = {'Authorization': 'Bearer ' + bear}
52+
headers = {'Authorization': 'Bearer ' + bearer_token}
4453

45-
print("Connecting to %s"%secrets["ssid"])
46-
wifi.radio.connect(secrets["ssid"], secrets["password"])
47-
print("Connected to %s!"%secrets["ssid"])
48-
print("My IP address is", wifi.radio.ipv4_address)
54+
print(f"Connecting to {ssid}")
55+
wifi.radio.connect(ssid, password)
56+
print(f"Connected to {ssid}!")
57+
print(f"My IP address is {wifi.radio.ipv4_address}")
4958

5059
pool = socketpool.SocketPool(wifi.radio)
5160
requests = adafruit_requests.Session(pool, ssl.create_default_context())
5261

5362
# gets and formats time from adafruit.io
54-
aio_username = secrets["aio_username"]
55-
aio_key = secrets["aio_key"]
56-
location = secrets.get("timezone", None)
63+
location = getenv("timezone", None)
5764
TIME_URL = "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s" % (aio_username, aio_key)
5865
TIME_URL += "&fmt=%25Y-%25m-%25dT%25H%3A%25M%3A%25S.%25L%25j%25u%25z%25Z"
5966

@@ -132,14 +139,14 @@
132139

133140
else:
134141
# if it's not new, then the wait continues
135-
no_tweet_text = ("No stock in last hour :( Last stock: %s" % (timestamp))
142+
no_tweet_text = "No stock in last hour :( Last stock: %s" % (timestamp)
136143
text_area.text = "\n".join(wrap_text_to_lines(no_tweet_text, 21))
137144
print("no new in stock notifications :(")
138145
# updates tweet ID
139146
last_value = value
140147
# if the tweet wasn't today
141148
else:
142149
# if it's not new, then the wait continues
143-
no_tweet_text = ("No stock in last hour :( Last stock: %s" % (timestamp))
150+
no_tweet_text = "No stock in last hour :( Last stock: %s" % (timestamp)
144151
text_area.text = "\n".join(wrap_text_to_lines(no_tweet_text, 21))
145152
print("no new in stock notifications :(")

Pico_W_CircuitPython_WiFi_Examples/Pico_W_Basic_WiFi_Test/code.py

+15-3
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,29 @@
22
#
33
# SPDX-License-Identifier: MIT
44

5-
import os
5+
from os import getenv
66
import ipaddress
77
import wifi
88
import socketpool
99

10+
# Get WiFi details, ensure these are setup in settings.toml
11+
ssid = getenv("CIRCUITPY_WIFI_SSID")
12+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
13+
14+
if None in [ssid, password]:
15+
raise RuntimeError(
16+
"WiFi settings are kept in settings.toml, "
17+
"please add them there. The settings file must contain "
18+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
19+
"at a minimum."
20+
)
21+
1022
print()
1123
print("Connecting to WiFi")
1224

1325
# connect to your SSID
1426
try:
15-
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
27+
wifi.radio.connect(ssid, password)
1628
except TypeError:
1729
print("Could not find WiFi info. Check your settings.toml file!")
1830
raise
@@ -25,7 +37,7 @@
2537
print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])
2638

2739
# prints IP address to REPL
28-
print("My IP address is", wifi.radio.ipv4_address)
40+
print(f"My IP address is {wifi.radio.ipv4_address}")
2941

3042
# pings Google
3143
ipv4 = ipaddress.ip_address("8.8.4.4")

Purple_Air_Display/code.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,23 @@
77
# or Matrix Portal
88
# and 64 x 32 RGB LED Matrix
99

10+
from os import getenv
1011
import time
1112
import board
1213
import terminalio
1314
from adafruit_matrixportal.matrixportal import MatrixPortal
1415

15-
# Get wifi details and more from a secrets.py file
16-
try:
17-
from secrets import secrets
18-
except ImportError:
19-
print("WiFi secrets are kept in secrets.py, please add them there!")
20-
raise
16+
# Get WiFi details, ensure these are setup in settings.toml
17+
ssid = getenv("CIRCUITPY_WIFI_SSID")
18+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
19+
20+
if None in [ssid, password]:
21+
raise RuntimeError(
22+
"WiFi settings are kept in settings.toml, "
23+
"please add them there. The settings file must contain "
24+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
25+
"at a minimum."
26+
)
2127

2228
def aqi_transform(val):
2329
aqi = pm_to_aqi(val) # derive Air Quality Index from Particulate Matter 2.5 value
@@ -49,7 +55,7 @@ def message_transform(val): # picks message based on thresholds
4955
status_neopixel=board.NEOPIXEL,
5056
debug=True,
5157
url=DATA_SOURCE,
52-
headers={"X-API-Key": secrets["purple_air_api_key"], # purpleair.com
58+
headers={"X-API-Key": getenv("purple_air_api_key"), # purpleair.com
5359
"Accept": "application/json"
5460
},
5561
json_path=(DATA_LOCATION, DATA_LOCATION),

PyPortal/PyPortal_AWS_IOT_Planter/code.py

+19-10
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
1111
Author: Brent Rubell for Adafruit Industries, 2019
1212
"""
13-
import os
13+
14+
from os import getenv
1415
import time
1516
import json
1617
import board
@@ -28,10 +29,17 @@
2829
# Time between polling the STEMMA, in minutes
2930
SENSOR_DELAY = 15
3031

31-
secrets = {
32-
"ssid" : os.getenv("CIRCUITPY_WIFI_SSID"),
33-
"password" : os.getenv("CIRCUITPY_WIFI_PASSWORD"),
34-
}
32+
# Get WiFi details, ensure these are setup in settings.toml
33+
ssid = getenv("CIRCUITPY_WIFI_SSID")
34+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
35+
36+
if None in [ssid, password]:
37+
raise RuntimeError(
38+
"WiFi settings are kept in settings.toml, "
39+
"please add them there. The settings file must contain "
40+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
41+
"at a minimum."
42+
)
3543

3644
# Get device certificate
3745
try:
@@ -65,9 +73,10 @@
6573
# Verify nina-fw version >= 1.4.0
6674
assert int(bytes(esp.firmware_version).decode("utf-8")[2]) >= 4, "Please update nina-fw to >=1.4.0."
6775

68-
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
69-
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
70-
esp, secrets, status_light)
76+
status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
77+
wifi = adafruit_esp32spi_wifimanager.WiFiManager(
78+
esp, ssid, password, status_pixel=status_pixel
79+
)
7180

7281
# Initialize the graphics helper
7382
print("Loading AWS IoT Graphics...")
@@ -126,8 +135,8 @@ def message(client, topic, msg):
126135
print("Message from {}: {}".format(topic, msg))
127136

128137
# Set up a new MiniMQTT Client
129-
client = MQTT.MQTT(broker = os.getenv("BROKER"),
130-
client_id = os.getenv("CLIENT_ID"),
138+
client = MQTT.MQTT(broker = getenv("BROKER"),
139+
client_id = getenv("CLIENT_ID"),
131140
socket_pool=pool,
132141
ssl_context=ssl_context)
133142

PyPortal/PyPortal_AdafruitIO/code.py

+17-7
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,29 @@
77
and io plus subscribers... and display it on a screen
88
If you can find something that spits out JSON data, we can display it!
99
"""
10+
11+
from os import getenv
1012
import time
1113
import board
1214
from adafruit_pyportal import PyPortal
1315

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
16+
# Get WiFi details and Adafruit IO keys, ensure these are setup in settings.toml
17+
# (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.)
18+
ssid = getenv("CIRCUITPY_WIFI_SSID")
19+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
20+
aio_username = getenv("ADAFRUIT_AIO_USERNAME")
21+
aio_key = getenv("ADAFRUIT_AIO_KEY")
22+
23+
if None in [ssid, password, aio_username, aio_key]:
24+
raise RuntimeError(
25+
"WiFi and Adafruit IO settings are kept in settings.toml, "
26+
"please add them there. The settings file must contain "
27+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
28+
"'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY' at a minimum."
29+
)
2030

2131
# Set up where we'll be fetching data from
22-
DATA_SOURCE = "https://io.adafruit.com/api/v2/stats?x-aio-key="+secrets['aio_key']
32+
DATA_SOURCE = f"https://io.adafruit.com/api/v2/stats?x-aio-key={aio_key}"
2333
DATA_LOCATION1 = ["io_plus", "io_plus_subscriptions"]
2434
DATA_LOCATION2 = ["users", "users_active_30_days"]
2535

PyPortal/PyPortal_AdafruitIO_Logger/code.py

+19-15
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
* CircuitPython_AdafruitIO
1313
https://github.com/adafruit/Adafruit_CircuitPython_AdafruitIO
1414
"""
15+
16+
from os import getenv
1517
import time
1618
import board
1719
import busio
@@ -33,30 +35,32 @@
3335
# Timeout between sending data to Adafruit IO, in seconds
3436
IO_DELAY = 30
3537

36-
# Get wifi details and more from a secrets.py file
37-
try:
38-
from secrets import secrets
39-
except ImportError:
40-
print("WiFi secrets are kept in secrets.py, please add them there!")
41-
raise
38+
# Get WiFi details and Adafruit IO keys, ensure these are setup in settings.toml
39+
# (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.)
40+
ssid = getenv("CIRCUITPY_WIFI_SSID")
41+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
42+
aio_username = getenv("ADAFRUIT_AIO_USERNAME")
43+
aio_key = getenv("ADAFRUIT_AIO_KEY")
44+
45+
if None in [ssid, password, aio_username, aio_key]:
46+
raise RuntimeError(
47+
"WiFi and Adafruit IO settings are kept in settings.toml, "
48+
"please add them there. The settings file must contain "
49+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
50+
"'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY' at a minimum."
51+
)
4252

4353
# PyPortal ESP32 Setup
4454
esp32_cs = DigitalInOut(board.ESP_CS)
4555
esp32_ready = DigitalInOut(board.ESP_BUSY)
4656
esp32_reset = DigitalInOut(board.ESP_RESET)
4757
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
4858
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
49-
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
50-
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
51-
52-
# Set your Adafruit IO Username and Key in secrets.py
53-
# (visit io.adafruit.com if you need to create an account,
54-
# or if you need your Adafruit IO key.)
55-
ADAFRUIT_IO_USER = secrets['aio_username']
56-
ADAFRUIT_IO_KEY = secrets['aio_key']
59+
status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
60+
wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)
5761

5862
# Create an instance of the Adafruit IO HTTP client
59-
io = IO_HTTP(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY, wifi)
63+
io = IO_HTTP(aio_username, aio_key, wifi)
6064

6165
try:
6266
# Get the 'temperature' feed from Adafruit IO

PyPortal/PyPortal_Alarm_Clock/code.py

+17-5
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
#pylint:disable=no-self-use,too-many-branches,too-many-statements
2121
#pylint:disable=useless-super-delegation, too-many-locals
2222

23+
from os import getenv
2324
import time
2425
import json
25-
from secrets import secrets
2626
import board
2727
from adafruit_pyportal import PyPortal
2828
from adafruit_bitmap_font import bitmap_font
@@ -32,9 +32,21 @@
3232
import displayio
3333
import adafruit_logging as logging
3434

35+
# Get WiFi details, ensure these are setup in settings.toml
36+
ssid = getenv("CIRCUITPY_WIFI_SSID")
37+
password = getenv("CIRCUITPY_WIFI_PASSWORD")
38+
39+
if None in [ssid, password]:
40+
raise RuntimeError(
41+
"WiFi settings are kept in settings.toml, "
42+
"please add them there. The settings file must contain "
43+
"'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
44+
"at a minimum."
45+
)
46+
3547
# Set up where we'll be fetching data from
36-
DATA_SOURCE = 'http://api.openweathermap.org/data/2.5/weather?id='+secrets['city_id']
37-
DATA_SOURCE += '&appid='+secrets['openweather_token']
48+
DATA_SOURCE = 'http://api.openweathermap.org/data/2.5/weather?id='+getenv('city_id')
49+
DATA_SOURCE += '&appid='+getenv('openweather_token')
3850
# You'll need to get a token from openweather.org, looks like 'b6907d289e10d714a6e88b30761fae22'
3951
DATA_LOCATION = []
4052

@@ -73,7 +85,7 @@
7385

7486
icon_file = None
7587
icon_sprite = None
76-
celcius = secrets['celcius']
88+
celcius = getenv('celcius')
7789

7890
# display/data refresh timers
7991

@@ -243,7 +255,7 @@ def tick(self, now):
243255
if (not self.refresh_time) or ((now - self.refresh_time) > 3600):
244256
logger.debug('Fetching time')
245257
try:
246-
pyportal.get_local_time(location=secrets['timezone'])
258+
pyportal.get_local_time(location=getenv('timezone'))
247259
self.refresh_time = now
248260
except RuntimeError as e:
249261
self.refresh_time = now - 3000 # delay 10 minutes before retrying

0 commit comments

Comments
 (0)