Skip to content

Commit af3eaa3

Browse files
committed
Secrets cleanup
1 parent 34c661e commit af3eaa3

File tree

5 files changed

+194
-58
lines changed

5 files changed

+194
-58
lines changed

adafruit_portalbase/network.py

Lines changed: 59 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import gc
2525
import os
2626
import time
27+
import warnings
2728

2829
from adafruit_fakerequests import Fake_Requests
2930
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
@@ -57,11 +58,18 @@
5758
CONTENT_JSON = const(2)
5859
CONTENT_IMAGE = const(3)
5960

60-
OLD_SETTINGS = {
61+
OLD_SECRETS = {
62+
"ADAFRUIT_AIO_KEY": "aio_key",
63+
"ADAFRUIT_AIO_USERNAME": "aio_username",
64+
"AIO_KEY": "aio_key",
65+
"AIO_USERNAME": "aio_username",
6166
"CIRCUITPY_WIFI_SSID": "ssid",
6267
"CIRCUITPY_WIFI_PASSWORD": "password",
63-
"AIO_USERNAME": "aio_username",
64-
"AIO_KEY": "aio_key",
68+
}
69+
70+
OLD_SETTINGS = {
71+
"ADAFRUIT_AIO_KEY": "AIO_KEY",
72+
"ADAFRUIT_AIO_USERNAME": "AIO_USERNAME",
6573
}
6674

6775

@@ -83,12 +91,11 @@ class NetworkBase:
8391
:param bool extract_values: If true, single-length fetched values are automatically extracted
8492
from lists and tuples. Defaults to ``True``.
8593
:param debug: Turn on debug print outs. Defaults to False.
86-
:param list secrets_data: An optional list in place of the data contained in the secrets.py file
8794
8895
"""
8996

9097
def __init__( # noqa: PLR0912,PLR0913 Too many branches,Too many arguments in function definition
91-
self, wifi_module, *, extract_values=True, debug=False, secrets_data=None
98+
self, wifi_module, *, extract_values=True, debug=False
9299
):
93100
self._wifi = wifi_module
94101
self._debug = debug
@@ -101,11 +108,6 @@ def __init__( # noqa: PLR0912,PLR0913 Too many branches,Too many arguments in f
101108
]
102109

103110
self._settings = {}
104-
if secrets_data is not None:
105-
for key, value in secrets_data.items():
106-
if key in OLD_SETTINGS:
107-
key = OLD_SETTINGS.get(key) # noqa: PLW2901 `for` loop variable `value` overwritten by assignment target
108-
self._settings[key] = value
109111
self._wifi_credentials = None
110112

111113
self.requests = None
@@ -120,31 +122,44 @@ def __init__( # noqa: PLR0912,PLR0913 Too many branches,Too many arguments in f
120122

121123
gc.collect()
122124

123-
def _get_setting(self, setting_name, show_error=True):
125+
def _get_setting(self, setting_name):
126+
# if setting is has already been found, return it
124127
if setting_name in self._settings:
125128
return self._settings[setting_name]
126129

127-
old_setting_name = setting_name
130+
# if setting is in settings.toml return it
131+
env_value = os.getenv(setting_name)
132+
if env_value is not None:
133+
self._settings[setting_name] = env_value
134+
return env_value
135+
136+
# if setting old name is in settings.toml return it
128137
if setting_name in OLD_SETTINGS:
129138
old_setting_name = OLD_SETTINGS.get(setting_name)
130-
if os.getenv(setting_name) is not None:
131-
return os.getenv(setting_name)
139+
env_value = os.getenv(old_setting_name)
140+
if env_value is not None:
141+
self._settings[setting_name] = env_value
142+
return env_value
143+
132144
try:
133145
from secrets import secrets
134146
except ImportError:
135-
secrets = {}
136-
if old_setting_name in secrets.keys():
137-
self._settings[setting_name] = secrets[old_setting_name]
138-
return self._settings[setting_name]
139-
if show_error:
140-
if setting_name in ("CIRCUITPY_WIFI_SSID", "CIRCUITPY_WIFI_PASSWORD"):
141-
print(
142-
"""WiFi settings are kept in settings.toml, please add them there!
143-
the secrets dictionary must contain 'CIRCUITPY_WIFI_SSID' and 'CIRCUITPY_WIFI_PASSWORD'
144-
at a minimum in order to use network related features"""
145-
)
146-
else:
147-
print(f"{setting_name} not found. Please add this setting to settings.toml.")
147+
return None
148+
149+
# if setting is in legacy secrets.py return it
150+
secrets_setting_name = setting_name
151+
if setting_name in OLD_SECRETS:
152+
# translate common names
153+
secrets_setting_name = OLD_SECRETS.get(setting_name)
154+
env_value = secrets.get(secrets_setting_name)
155+
if env_value is not None:
156+
warnings.warn(
157+
"The using of `secrets`, is deprecated. Please put your settings in "
158+
"settings.toml"
159+
)
160+
self._settings[setting_name] = env_value
161+
return env_value
162+
148163
return None
149164

150165
def neo_status(self, value):
@@ -206,17 +221,17 @@ def get_strftime(self, time_format, location=None, max_attempts=10):
206221
api_url = None
207222
reply = None
208223
try:
209-
aio_username = self._get_setting("AIO_USERNAME")
210-
aio_key = self._get_setting("AIO_KEY")
224+
aio_username = self._get_setting("ADAFRUIT_AIO_USERNAME")
225+
aio_key = self._get_setting("ADAFRUIT_AIO_KEY")
211226
except KeyError:
212227
raise KeyError(
213228
"\n\nOur time service requires a login/password to rate-limit. "
214-
"Please register for a free adafruit.io account and place the user/key "
215-
"in your secrets file under 'AIO_USERNAME' and 'AIO_KEY'"
229+
"Please register for a free adafruit.io account and place the user/key in "
230+
"your settings.toml file under 'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY'"
216231
) from KeyError
217232

218233
if location is None:
219-
location = self._get_setting("timezone", False)
234+
location = self._get_setting("timezone")
220235
if location:
221236
print("Getting time for timezone", location)
222237
api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
@@ -242,7 +257,8 @@ def get_strftime(self, time_format, location=None, max_attempts=10):
242257
reply = response.text
243258
except KeyError:
244259
raise KeyError(
245-
"Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones"
260+
"Was unable to lookup the time, try setting 'timezone' in your settings.toml"
261+
"according to http://worldtimeapi.org/timezones"
246262
) from KeyError
247263
# now clean up
248264
response.close()
@@ -346,7 +362,7 @@ def wget(self, url, filename, *, chunk_size=12000, headers=None):
346362

347363
def connect(self, max_attempts=10):
348364
"""
349-
Connect to WiFi using the settings found in secrets.py
365+
Connect to WiFi using the settings found in settings.toml
350366
351367
:param max_attempts: The maximum number of attempts to connect to WiFi before
352368
failing or use None to disable. Defaults to 10.
@@ -361,7 +377,7 @@ def connect(self, max_attempts=10):
361377
}
362378
]
363379

364-
networks = self._get_setting("networks", False)
380+
networks = self._get_setting("networks")
365381
if networks is not None:
366382
if isinstance(networks, (list, tuple)):
367383
self._wifi_credentials = networks
@@ -370,14 +386,14 @@ def connect(self, max_attempts=10):
370386
"'networks' must be a list/tuple of dicts of 'ssid' and 'password'"
371387
)
372388

373-
for secret_entry in self._wifi_credentials:
389+
for credentials in self._wifi_credentials:
374390
self._wifi.neo_status(STATUS_CONNECTING)
375391
attempt = 1
376392

377393
while not self._wifi.is_connected:
378-
# secrets dictionary must contain 'ssid' and 'password' at a minimum
379-
print("Connecting to AP", secret_entry["ssid"])
380-
if secret_entry["ssid"] == "CHANGE ME" or secret_entry["password"] == "CHANGE ME":
394+
# credentials must contain 'CIRCUITPY_WIFI_SSID' and 'CIRCUITPY_WIFI_PASSWORD'
395+
print("Connecting to AP", credentials["ssid"])
396+
if credentials["ssid"] == "CHANGE ME" or credentials["password"] == "CHANGE ME":
381397
change_me = "\n" + "*" * 45
382398
change_me += "\nPlease update the 'settings.toml' file on your\n"
383399
change_me += "CIRCUITPY drive to include your local WiFi\n"
@@ -387,7 +403,7 @@ def connect(self, max_attempts=10):
387403
raise OSError(change_me)
388404
self._wifi.neo_status(STATUS_NO_CONNECTION) # red = not connected
389405
try:
390-
self._wifi.connect(secret_entry["ssid"], secret_entry["password"])
406+
self._wifi.connect(credentials["ssid"], credentials["password"])
391407
self.requests = self._wifi.requests
392408
self._wifi.neo_status(STATUS_CONNECTED)
393409
break
@@ -412,11 +428,11 @@ def _get_io_client(self):
412428
self.connect()
413429

414430
try:
415-
aio_username = self._get_setting("AIO_USERNAME")
416-
aio_key = self._get_setting("AIO_KEY")
431+
aio_username = self._get_setting("ADAFRUIT_AIO_USERNAME")
432+
aio_key = self._get_setting("ADAFRUIT_AIO_KEY")
417433
except KeyError:
418434
raise KeyError(
419-
"Adafruit IO secrets are kept in secrets.py, please add them there!\n\n"
435+
"Adafruit IO settings are kept in settings.toml, please add them there!\n\n"
420436
) from KeyError
421437

422438
self._io_client = IO_HTTP(aio_username, aio_key, self._wifi.requests)

adafruit_portalbase/wifi_coprocessor.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ def __init__(self, *, status_led=None, esp=None, external_spi=None):
7070

7171
if self.esp.is_connected:
7272
self._set_requests()
73-
self._manager = None
7473

7574
gc.collect()
7675

@@ -81,9 +80,9 @@ def _set_requests(self):
8180

8281
def connect(self, ssid, password):
8382
"""
84-
Connect to WiFi using the settings found in secrets.py
83+
Connect to WiFi using the settings found in settings.toml
8584
"""
86-
self.esp.connect({"ssid": ssid, "password": password})
85+
self.esp.connect(ssid, password)
8786
self._set_requests()
8887

8988
def neo_status(self, value):
@@ -95,14 +94,6 @@ def neo_status(self, value):
9594
if self.neopix:
9695
self.neopix.fill(value)
9796

98-
def manager(self, secrets):
99-
"""Initialize the WiFi Manager if it hasn't been cached and return it"""
100-
if self._manager is None:
101-
self._manager = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
102-
self.esp, secrets, None
103-
)
104-
return self._manager
105-
10697
@property
10798
def is_connected(self):
10899
"""Return whether we are connected."""

examples/portalbase_simpletest.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
used directly by end users. This example shows one such usage with the PyPortal library.
77
See MatrixPortal, MagTag, and PyPortal libraries for more examples.
88
"""
9-
# NOTE: Make sure you've created your secrets.py file before running this example
10-
# https://learn.adafruit.com/adafruit-pyportal/internet-connect#whats-a-secrets-file-17-2
9+
# NOTE: Make sure you've created your settings.toml file before running this example
10+
# https://learn.adafruit.com/adafruit-pyportal/create-your-settings-toml-file
1111

1212
import board
13-
import displayio
1413
from adafruit_pyportal import PyPortal
14+
from displayio import CIRCUITPYTHON_TERMINAL
1515

1616
# Set a data source URL
1717
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
@@ -20,7 +20,7 @@
2020
pyportal = PyPortal(url=TEXT_URL, status_neopixel=board.NEOPIXEL)
2121

2222
# Set display to show REPL
23-
board.DISPLAY.root_group = displayio.CIRCUITPYTHON_TERMINAL
23+
board.DISPLAY.root_group = CIRCUITPYTHON_TERMINAL
2424

2525
# Go get that data
2626
print("Fetching text from", TEXT_URL)

optional_requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries
22
#
33
# SPDX-License-Identifier: Unlicense
4+
5+
pytest

0 commit comments

Comments
 (0)