From 592b33be07992f737e9b9c6141739b26ee8aef88 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Tue, 25 Mar 2025 07:49:30 -0700 Subject: [PATCH] Secrets Cleanup: L, M and O --- MacroPad_Scramble_Lock/code.py | 2 +- Macropad_2FA_TOTP/.circuitpython.skip | 6 ---- Macropad_2FA_TOTP/code.py | 30 ++++++++-------- Macropad_2FA_TOTP/secrets.py | 23 ------------ Macropad_2FA_TOTP/totp_keys.py | 22 ++++++++++++ .../MagTag_Google_Calendar/authenticator.py | 34 ++++++++++-------- MagTag/MagTag_Google_Calendar/code.py | 33 +++++++++-------- MagTag/MagTag_NextBus/code.py | 21 +++++++---- MagTag/MagTag_Project_Selector/secrets.py | 16 --------- MagTag/MagTag_Project_Selector/settings.toml | 14 ++++++++ MagTag/MagTag_Quote_Board/code.py | 15 +++++++- MagTag/MagTag_Seasonal_Produce/code.py | 19 ++++++++-- MagTag/MagTag_Showerthoughts/code.py | 14 +++++++- MagTag/MagTag_Showtimes/code.py | 15 +++++++- MagTag/MagTag_SimpleClock/code.py | 1 - MagTag/MagTag_Sports_Schedule/code.py | 18 ++++++++-- MagTag/MagTag_Twitter/code.py | 21 ++++++----- MagTag/MagTag_Weather/.circuitpython.skip | 2 -- MagTag/MagTag_Weather/forecast/code.py | 28 +++++++++++---- MagTag/MagTag_Weather/onecall/code.py | 28 +++++++++++---- MagTag/MagTag_Webb_Telescope_Status/code.py | 20 +++++++---- .../deprecated_original_version/code.py | 20 +++++++---- Matrix_On_Air/code.py | 20 +++++++---- .../Matrix_Portal_Moon_Clock/code.py | 30 ++++++++++------ Metro_Matrix_Clock/code.py | 21 +++++++---- literary-clock/code.py | 35 +++++++++++-------- oshwa_magtag_display/code.py | 24 ++++++++----- 27 files changed, 341 insertions(+), 191 deletions(-) delete mode 100644 Macropad_2FA_TOTP/.circuitpython.skip delete mode 100755 Macropad_2FA_TOTP/secrets.py create mode 100644 Macropad_2FA_TOTP/totp_keys.py delete mode 100644 MagTag/MagTag_Project_Selector/secrets.py create mode 100644 MagTag/MagTag_Project_Selector/settings.toml delete mode 100644 MagTag/MagTag_Weather/.circuitpython.skip diff --git a/MacroPad_Scramble_Lock/code.py b/MacroPad_Scramble_Lock/code.py index ef21dfc3b..49026ed31 100644 --- a/MacroPad_Scramble_Lock/code.py +++ b/MacroPad_Scramble_Lock/code.py @@ -22,7 +22,7 @@ # CONFIGURABLES ------------------------ # Password information -# For higher security, place password in a separate file like secrets.py +# For higher security, place password in a separate file like settings.toml PASSWORD = "2468" PASSWORD_LENGTH = len(PASSWORD) diff --git a/Macropad_2FA_TOTP/.circuitpython.skip b/Macropad_2FA_TOTP/.circuitpython.skip deleted file mode 100644 index d5b0018ba..000000000 --- a/Macropad_2FA_TOTP/.circuitpython.skip +++ /dev/null @@ -1,6 +0,0 @@ -Macropad_2FA_TOTP/secrets.py 19: Final newline missing (missing-final-newline) -Macropad_2FA_TOTP/secrets.py 19: Unexpected line ending format. There is 'CRLF' while it should be 'LF'. (unexpected-line-ending-format) -Macropad_2FA_TOTP/rtc_setter.py 35: Final newline missing (missing-final-newline) -Macropad_2FA_TOTP/rtc_setter.py 35: Unexpected line ending format. There is 'CRLF' while it should be 'LF'. (unexpected-line-ending-format) -Macropad_2FA_TOTP/macropad_totp.py 77: Line too long (103/100) (line-too-long) -Macropad_2FA_TOTP/macropad_totp.py 169: Redefining name 'code' from outer scope (line 65) (redefined-outer-name) diff --git a/Macropad_2FA_TOTP/code.py b/Macropad_2FA_TOTP/code.py index 4e7546371..64da6b25f 100755 --- a/Macropad_2FA_TOTP/code.py +++ b/Macropad_2FA_TOTP/code.py @@ -31,15 +31,11 @@ DISPLAY_RATE = 1 # screen refresh rate #------------------------------------------------------------------------- -# Get secrets from a secrets.py file +# Get totp_keys from a totp_keys.py file try: - from secrets import secrets - totp_keys = secrets["totp_keys"] + from totp_keys import totp_keys except ImportError: - print("Secrets are kept in secrets.py, please add them there!") - raise -except KeyError: - print("TOTP info not found in secrets.py.") + print("TOTP info not found in totp_keys.py, please add them there!") raise # set board to use PCF8523 as its RTC @@ -80,7 +76,9 @@ rtc_time.anchor_point = (0.0, 0.5) rtc_time.anchored_position = (0, 59) -progress_bar = HorizontalProgressBar((68, 46), (55, 17), bar_color=0xFFFFFF, min_value=0, max_value=30) +progress_bar = HorizontalProgressBar( + (68, 46), (55, 17), bar_color=0xFFFFFF, min_value=0, max_value=30 +) splash = displayio.Group() splash.append(name) @@ -172,15 +170,15 @@ def generate_otp(int_input, secret_key, digits=6): int_to_bytestring(int_input)).digest() ) offset = hmac_hash[-1] & 0xf - code = ((hmac_hash[offset] & 0x7f) << 24 | - (hmac_hash[offset + 1] & 0xff) << 16 | - (hmac_hash[offset + 2] & 0xff) << 8 | - (hmac_hash[offset + 3] & 0xff)) - str_code = str(code % 10 ** digits) - while len(str_code) < digits: - str_code = '0' + str_code + otp_code = ((hmac_hash[offset] & 0x7f) << 24 | + (hmac_hash[offset + 1] & 0xff) << 16 | + (hmac_hash[offset + 2] & 0xff) << 8 | + (hmac_hash[offset + 3] & 0xff)) + str_otp_code = str(otp_code % 10 ** digits) + while len(str_otp_code) < digits: + str_otp_code = '0' + str_otp_code - return str_code + return str_otp_code #------------------------------------------------------------------------- # M A C R O P A D S E T U P diff --git a/Macropad_2FA_TOTP/secrets.py b/Macropad_2FA_TOTP/secrets.py deleted file mode 100755 index 0ed9c2961..000000000 --- a/Macropad_2FA_TOTP/secrets.py +++ /dev/null @@ -1,23 +0,0 @@ -# SPDX-FileCopyrightText: 2021 Carter Nelson 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 = { - # tuples of name, sekret key, color - 'totp_keys' : [("Github", "JBSWY3DPEHPK3PXP", 0x8732A8), - ("Discord", "JBSWY3DPEHPK3PXQ", 0x32A89E), - ("Slack", "JBSWY5DZEHPK3PXR", 0xFC861E), - ("Basecamp", "JBSWY6DZEHPK3PXS", 0x55C24C), - ("Gmail", "JBSWY7DZEHPK3PXT", 0x3029FF), - None, - None, # must have 12 entires - None, # set None for unused keys - None, - ("Hello Kitty", "JBSWY7DZEHPK3PXU", 0xED164F), - None, - None, - ] - } \ No newline at end of file diff --git a/Macropad_2FA_TOTP/totp_keys.py b/Macropad_2FA_TOTP/totp_keys.py new file mode 100644 index 000000000..6e9b5babe --- /dev/null +++ b/Macropad_2FA_TOTP/totp_keys.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2021 Carter Nelson for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +# This file contains totp codes! +# If you put them in the code you risk committing that info or sharing it + +# tuples of name, key, color +totp_keys = [ + ("Github", "JBSWY3DPEHPK3PXP", 0x8732A8), + ("Discord", "JBSWY3DPEHPK3PXQ", 0x32A89E), + ("Slack", "JBSWY5DZEHPK3PXR", 0xFC861E), + ("Basecamp", "JBSWY6DZEHPK3PXS", 0x55C24C), + ("Gmail", "JBSWY7DZEHPK3PXT", 0x3029FF), + None, + None, # must have 12 entires + None, # set None for unused keys + None, + ("Hello Kitty", "JBSWY7DZEHPK3PXU", 0xED164F), + None, + None, +] diff --git a/MagTag/MagTag_Google_Calendar/authenticator.py b/MagTag/MagTag_Google_Calendar/authenticator.py index b008b2da2..b9bae5ced 100755 --- a/MagTag/MagTag_Google_Calendar/authenticator.py +++ b/MagTag/MagTag_Google_Calendar/authenticator.py @@ -1,21 +1,25 @@ # SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries # # SPDX-License-Identifier: Unlicense + +from os import getenv from adafruit_oauth2 import OAuth2 from adafruit_display_text.label import Label from adafruit_bitmap_font import bitmap_font from adafruit_magtag.magtag import Graphics, Network from adafruit_display_shapes.rect import Rect -# 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 -try: - from secrets import secrets -except ImportError: - print("Credentials and tokens are kept in secrets.py, please add them there!") - raise +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) network = Network() network.connect() @@ -57,8 +61,8 @@ # Initialize an OAuth2 object google_auth = OAuth2( network.requests, - secrets["google_client_id"], - secrets["google_client_secret"], + getenv("google_client_id"), + getenv("google_client_secret"), scopes, ) @@ -90,9 +94,9 @@ raise RuntimeError("Timed out waiting for browser response!") print("Successfully Authenticated with Google!") -print("Add the following lines to your secrets.py file:") -print("\t'google_access_token' " + ":" + " '%s'," % google_auth.access_token) -print("\t'google_refresh_token' " + ":" + " '%s'" % google_auth.refresh_token) +print("Add the following lines to your settings.toml file:") +print(f'google_access_token="{google_auth.access_token}"') +print(f'google_refresh_token="{google_auth.refresh_token}"') graphics.splash.pop() graphics.splash.pop() @@ -100,6 +104,6 @@ label_overview_text.text = "Successfully Authenticated!" label_verification_url.text = ( - "Check the REPL for tokens to add\n\tto your secrets.py file" + "Check the REPL for tokens to add\n\tto your settings.toml file" ) display.refresh() diff --git a/MagTag/MagTag_Google_Calendar/code.py b/MagTag/MagTag_Google_Calendar/code.py index 83447e954..b3e5cc0b4 100755 --- a/MagTag/MagTag_Google_Calendar/code.py +++ b/MagTag/MagTag_Google_Calendar/code.py @@ -1,12 +1,26 @@ # SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries # # SPDX-License-Identifier: Unlicense + +from os import getenv import time import rtc from adafruit_oauth2 import OAuth2 from adafruit_display_shapes.line import Line from adafruit_magtag.magtag import MagTag +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) + # Calendar ID CALENDAR_ID = "YOUR_CALENDAR_ID" @@ -42,15 +56,6 @@ 6: "Sunday", } -# 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 -try: - from secrets import secrets -except ImportError: - print("Credentials and tokens are kept in secrets.py, please add them there!") - raise # Create a new MagTag object magtag = MagTag() @@ -62,18 +67,18 @@ scopes = ["https://www.googleapis.com/auth/calendar.readonly"] google_auth = OAuth2( magtag.network.requests, - secrets["google_client_id"], - secrets["google_client_secret"], + getenv("google_client_id"), + getenv("google_client_secret"), scopes, - secrets["google_access_token"], - secrets["google_refresh_token"], + getenv("google_access_token"), + getenv("google_refresh_token"), ) def get_current_time(time_max=False): """Gets local time from Adafruit IO and converts to RFC3339 timestamp.""" # Get local time from Adafruit IO - magtag.get_local_time(secrets["timezone"]) + magtag.get_local_time(getenv("timezone")) # Format as RFC339 timestamp cur_time = r.datetime if time_max: # maximum time to fetch events is midnight (4:59:59UTC) diff --git a/MagTag/MagTag_NextBus/code.py b/MagTag/MagTag_NextBus/code.py index 1b719fc9f..f7b157fc5 100644 --- a/MagTag/MagTag_NextBus/code.py +++ b/MagTag/MagTag_NextBus/code.py @@ -11,9 +11,10 @@ """ # pylint: disable=import-error + +from os import getenv import gc import time -from secrets import secrets import displayio from rtc import RTC from adafruit_magtag.magtag import Graphics @@ -23,6 +24,17 @@ from adafruit_display_text.label import Label from nextbus import NextBus +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # CONFIGURABLE SETTINGS ---------------------------------------------------- @@ -54,15 +66,12 @@ # not a big problem if this drifts a bit due to infrequent synchronizations. # 6 hour default. CLOCK_SYNC_INTERVAL = 6 * 60 * 60 -# Load time zone string from secrets.py, else IP geolocation is used +# Load time zone string from settings.toml, else IP geolocation is used # (http://worldtimeapi.org/api/timezone for list). Again, this is only # used for the 'Last checked' display, not predictions, so it's not # especially disruptive if missing. # pylint: disable=bare-except -try: - TIME_ZONE = secrets['timezone'] # e.g. 'America/New_York' -except: - TIME_ZONE = None # Use IP geolocation +TIME_ZONE = getenv('timezone') # e.g. 'America/New_York' # SOME UTILITY FUNCTIONS --------------------------------------------------- diff --git a/MagTag/MagTag_Project_Selector/secrets.py b/MagTag/MagTag_Project_Selector/secrets.py deleted file mode 100644 index 0f8010a57..000000000 --- a/MagTag/MagTag_Project_Selector/secrets.py +++ /dev/null @@ -1,16 +0,0 @@ -# SPDX-FileCopyrightText: 2020 Eva Herrada 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": "wifi_network", - "password": "wifi_password", - "timezone": "America/New_York", # http://worldtimeapi.org/timezones - "openweather_token": "my_openweather_token", - "openweather_location": "New York City, US", - "aio_username": "my_adafruit_io_username", - "aio_key": "my_adafruit_io_key", -} diff --git a/MagTag/MagTag_Project_Selector/settings.toml b/MagTag/MagTag_Project_Selector/settings.toml new file mode 100644 index 000000000..a01a196a7 --- /dev/null +++ b/MagTag/MagTag_Project_Selector/settings.toml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2020 Eva Herrada 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" +ADAFRUIT_AIO_USERNAME="my_username" +ADAFRUIT_AIO_KEY="my_key" +timezone="America/New_York" # http://worldtimeapi.org/timezones +openweather_token="my_openweather_token" +openweather_location="New York City, US" diff --git a/MagTag/MagTag_Quote_Board/code.py b/MagTag/MagTag_Quote_Board/code.py index 125312c58..da0df4526 100644 --- a/MagTag/MagTag_Quote_Board/code.py +++ b/MagTag/MagTag_Quote_Board/code.py @@ -4,11 +4,24 @@ # MagTag Quote Board # Displays Quotes from the Adafruit quotes server -# Be sure to put WiFi access point info in secrets.py file to connect +# Be sure to put WiFi access point info in settings.toml file to connect +from os import getenv import time from adafruit_magtag.magtag import MagTag +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) + # Set up where we'll be fetching data from DATA_SOURCE = "https://www.adafruit.com/api/quotes.php" QUOTE_LOCATION = [0, "text"] diff --git a/MagTag/MagTag_Seasonal_Produce/code.py b/MagTag/MagTag_Seasonal_Produce/code.py index 7253e5da9..7960589a9 100755 --- a/MagTag/MagTag_Seasonal_Produce/code.py +++ b/MagTag/MagTag_Seasonal_Produce/code.py @@ -9,14 +9,27 @@ """ # pylint: disable=import-error, line-too-long + +from os import getenv import time -from secrets import secrets import rtc from adafruit_display_shapes.rect import Rect from adafruit_magtag.magtag import MagTag from produce import Produce +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) + # CONFIGURABLE SETTINGS and ONE-TIME INITIALIZATION ------------------------ TWELVE_HOUR = True # If set, show 12-hour vs 24-hour (e.g. 3:00 vs 15:00) @@ -24,9 +37,9 @@ # Location of produce data (file:// or http:// or https://): JSON_URL = 'https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/master/MagTag_Seasonal_Produce/produce.json' -# Location is configured in secrets.py. If location is not contained there, +# Location is configured in settings.toml. If location is not contained there, # default value below will be used. -LOCATION = secrets.get('location', 'NY') # default to 'NY' +LOCATION = getenv('location', 'NY') # default to 'NY' PRODUCE = Produce(JSON_URL, LOCATION) MAGTAG = MagTag(rotation=0) # Portrait (vertical) display diff --git a/MagTag/MagTag_Showerthoughts/code.py b/MagTag/MagTag_Showerthoughts/code.py index 3632c4810..99ba6d909 100644 --- a/MagTag/MagTag_Showerthoughts/code.py +++ b/MagTag/MagTag_Showerthoughts/code.py @@ -3,12 +3,24 @@ # SPDX-License-Identifier: MIT # MagTag Shower Thoughts -# Be sure to put WiFi access point info in secrets.py file to connect +# Be sure to put WiFi access point info in settings.toml file to connect +from os import getenv import time import random from adafruit_magtag.magtag import MagTag +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # Set up where we'll be fetching data from DATA_SOURCE = "https://www.reddit.com/r/showerthoughts/hot.json?limit=10" diff --git a/MagTag/MagTag_Showtimes/code.py b/MagTag/MagTag_Showtimes/code.py index 4f8acce4f..c7e9e9376 100644 --- a/MagTag/MagTag_Showtimes/code.py +++ b/MagTag/MagTag_Showtimes/code.py @@ -4,13 +4,26 @@ # MagTag Showtimes Event Viewer # Uses the events.json file to display next or current event -# Be sure to put WiFi access point info in secrets.py file to connect +# Be sure to put WiFi access point info in settings.toml file to connect +from os import getenv import time import json import re from adafruit_magtag.magtag import MagTag +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) + # You can test by setting a time.struct here, to pretend its a different day # (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) FAKETIME = False # time.struct_time(2020, 12, 11, 15, 01, 00, 4, 346, -1) diff --git a/MagTag/MagTag_SimpleClock/code.py b/MagTag/MagTag_SimpleClock/code.py index 33c2e8e12..1b6bedcdc 100644 --- a/MagTag/MagTag_SimpleClock/code.py +++ b/MagTag/MagTag_SimpleClock/code.py @@ -31,7 +31,6 @@ if HOUR_MODE_24: timestr = "%d:%02d" % (hour, minute) else: - is_pm = (hour >= 12) hour %= 12 if hour == 0: hour = 12 diff --git a/MagTag/MagTag_Sports_Schedule/code.py b/MagTag/MagTag_Sports_Schedule/code.py index af1707d51..a7365ecc9 100644 --- a/MagTag/MagTag_Sports_Schedule/code.py +++ b/MagTag/MagTag_Sports_Schedule/code.py @@ -2,19 +2,31 @@ # SPDX-License-Identifier: MIT # MagTag Sports Schedule Viewer -# Be sure to add your wifi credentials to the secrets.py file +# Be sure to add your wifi credentials to the settings.toml file # Press D to advance to next game # Press C to go back one game # Press B to refresh the schedule (this takes a minute) # Press A to advance to next sport (this takes a minute) - +from os import getenv import time import json from adafruit_datetime import datetime, timedelta from adafruit_magtag.magtag import MagTag +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) + USE_24HR_TIME = False TIME_ZONE_OFFSET = -8 # hours ahead or behind Zulu time, e.g. Pacific is -8 TIME_ZONE_NAME = "PST" @@ -186,7 +198,7 @@ def update_labels(): def fetch_sports_data(reset_game_number=True): # Fetches and parses data for all games for the current sport # pylint: disable=global-statement - global sports_data, current_game, current_sport + global current_game magtag.url = SPORTS[current_sport]["url"] sports_data.clear() raw_data = json.loads(magtag.fetch(auto_refresh=False)) diff --git a/MagTag/MagTag_Twitter/code.py b/MagTag/MagTag_Twitter/code.py index 92e02285e..09a4cf8a2 100755 --- a/MagTag/MagTag_Twitter/code.py +++ b/MagTag/MagTag_Twitter/code.py @@ -2,17 +2,22 @@ # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries. # # SPDX-License-Identifier: Unlicense + +from os import getenv import time from adafruit_magtag.magtag import MagTag -try: - from secrets import secrets -except ImportError: - print( - """WiFi settings are kept in secrets.py, please add them there! -the secrets dictionary must contain 'ssid' and 'password' at a minimum""" +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." ) - raise # Set to the twitter username you'd like to fetch tweets from TWITTER_USERNAME = "adafruit" @@ -31,7 +36,7 @@ magtag = MagTag(url=DATA_SOURCE, json_path=(TWEET_FULL_NAME, TWEET_HANDLE, TWEET_TEXT)) # Set Twitter OAuth2.0 Bearer Token -bearer_token = secrets["twitter_bearer_token"] +bearer_token = getenv("twitter_bearer_token") magtag.set_headers({"Authorization": "Bearer " + bearer_token}) # Display setup diff --git a/MagTag/MagTag_Weather/.circuitpython.skip b/MagTag/MagTag_Weather/.circuitpython.skip deleted file mode 100644 index 465e39b2c..000000000 --- a/MagTag/MagTag_Weather/.circuitpython.skip +++ /dev/null @@ -1,2 +0,0 @@ -MagTag_Weather/magtag_weather.py 269: Trailing newlines (trailing-newlines) -MagTag_Weather/magtag_weather.py 7: standard import "from secrets import secrets" should be placed before "import terminalio" (wrong-import-order) diff --git a/MagTag/MagTag_Weather/forecast/code.py b/MagTag/MagTag_Weather/forecast/code.py index a52eabaab..bbc370975 100755 --- a/MagTag/MagTag_Weather/forecast/code.py +++ b/MagTag/MagTag_Weather/forecast/code.py @@ -3,13 +3,25 @@ # SPDX-License-Identifier: MIT # pylint: disable=redefined-outer-name, eval-used, wrong-import-order +from os import getenv import time import terminalio import displayio import adafruit_imageload from adafruit_display_text import label from adafruit_magtag.magtag import MagTag -from secrets import secrets + +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # --| USER CONFIG |-------------------------- METRIC = False # set to True for metric units @@ -74,7 +86,7 @@ def get_data_source_url(api="forecast", location=None): URL += "&lon={}".format(location[1]) else: raise ValueError("Unknown API type: " + api) - return URL + "&appid=" + secrets["openweather_token"] + return URL + "&appid=" + getenv("openweather_token") def get_latlon(city_name): @@ -245,18 +257,20 @@ def go_to_sleep(current_time): # =========== # Location # =========== -if isinstance(secrets["openweather_location"], str): +openweather_location = getenv("openweather_location") +is_lat_long = "," in openweather_location +if openweather_location and not is_lat_long: # Get lat/lon using city name - city = secrets["openweather_location"] + city = openweather_location print("Getting lat/lon for city:", city) latlon = get_latlon(city) -elif isinstance(secrets["openweather_location"], tuple): +elif openweather_location: # Get city name using lat/lon - latlon = secrets["openweather_location"] + latlon = openweather_location.split(",") print("Getting city name for lat/lon:", latlon) city = get_city(latlon) else: - raise ValueError("Unknown location:", secrets["openweather_location"]) + raise ValueError(f"Unknown location:{openweather_location}") print("City =", city) print("Lat/Lon = ", latlon) diff --git a/MagTag/MagTag_Weather/onecall/code.py b/MagTag/MagTag_Weather/onecall/code.py index fb188d2a0..c3a5c89d8 100644 --- a/MagTag/MagTag_Weather/onecall/code.py +++ b/MagTag/MagTag_Weather/onecall/code.py @@ -3,13 +3,25 @@ # SPDX-License-Identifier: MIT # pylint: disable=redefined-outer-name, eval-used, wrong-import-order +from os import getenv import time import terminalio import displayio import adafruit_imageload from adafruit_display_text import label from adafruit_magtag.magtag import MagTag -from secrets import secrets + +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # --| USER CONFIG |-------------------------- METRIC = False # set to True for metric units @@ -68,7 +80,7 @@ def get_data_source_url(api="onecall", location=None): URL += "&lon={}".format(location[1]) else: raise ValueError("Unknown API type: " + api) - return URL + "&appid=" + secrets["openweather_token"] + return URL + "&appid=" + getenv("openweather_token") def get_latlon(city_name): @@ -183,18 +195,20 @@ def go_to_sleep(current_time): # =========== # Location # =========== -if isinstance(secrets["openweather_location"], str): +openweather_location = getenv("openweather_location") +is_lat_long = "," in openweather_location +if openweather_location and not is_lat_long: # Get lat/lon using city name - city = secrets["openweather_location"] + city = openweather_location print("Getting lat/lon for city:", city) latlon = get_latlon(city) -elif isinstance(secrets["openweather_location"], tuple): +elif openweather_location: # Get city name using lat/lon - latlon = secrets["openweather_location"] + latlon = openweather_location.split(",") print("Getting city name for lat/lon:", latlon) city = get_city(latlon) else: - raise ValueError("Unknown location:", secrets["openweather_location"]) + raise ValueError(f"Unknown location:{openweather_location}") print("City =", city) print("Lat/Lon = ", latlon) diff --git a/MagTag/MagTag_Webb_Telescope_Status/code.py b/MagTag/MagTag_Webb_Telescope_Status/code.py index a590beeae..4a66b23a0 100644 --- a/MagTag/MagTag_Webb_Telescope_Status/code.py +++ b/MagTag/MagTag_Webb_Telescope_Status/code.py @@ -4,6 +4,8 @@ """ MagTag status display for James Webb Telescope """ + +from os import getenv import time import json import ssl @@ -18,11 +20,17 @@ import alarm import adafruit_requests -try: - from secrets import secrets -except ImportError: - print("WiFi secrets are kept in secrets.py, please add them there!") - raise +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # Update once per hour SLEEP_TIME = 60 * 60 # seconds @@ -66,7 +74,7 @@ def try_refresh(): print("Connecting to AP...") try: # wifi connect - wifi.radio.connect(secrets["ssid"], secrets["password"]) + wifi.radio.connect(ssid, password) # Create Socket, initialize requests socket = socketpool.SocketPool(wifi.radio) diff --git a/MagTag/MagTag_Webb_Telescope_Status/deprecated_original_version/code.py b/MagTag/MagTag_Webb_Telescope_Status/deprecated_original_version/code.py index 3a2c19409..ae5176661 100644 --- a/MagTag/MagTag_Webb_Telescope_Status/deprecated_original_version/code.py +++ b/MagTag/MagTag_Webb_Telescope_Status/deprecated_original_version/code.py @@ -4,6 +4,8 @@ """ MagTag status display for James Webb Telescope """ + +from os import getenv import time import json import ssl @@ -18,11 +20,17 @@ import alarm import adafruit_requests -try: - from secrets import secrets -except ImportError: - print("WiFi secrets are kept in secrets.py, please add them there!") - raise +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # Update once per hour SLEEP_TIME = 60 * 60 # seconds @@ -64,7 +72,7 @@ def try_refresh(): print("Connecting to AP...") try: # wifi connect - wifi.radio.connect(secrets["ssid"], secrets["password"]) + wifi.radio.connect(ssid, password) # Create Socket, initialize requests socket = socketpool.SocketPool(wifi.radio) diff --git a/Matrix_On_Air/code.py b/Matrix_On_Air/code.py index 05657136d..b323e4d2f 100644 --- a/Matrix_On_Air/code.py +++ b/Matrix_On_Air/code.py @@ -5,6 +5,7 @@ # ON AIR sign for YouTube livestreaming # Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield +from os import getenv import time import board import displayio @@ -15,12 +16,17 @@ from adafruit_matrixportal.network import Network from adafruit_matrixportal.matrix import Matrix -# 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 +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # Set up where we'll be fetching data from # Adafruit YouTube channel: @@ -32,7 +38,7 @@ "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" + CHANNEL_ID + "&type=video&eventType=live&key=" - + secrets["youtube_token"] + + getenv("youtube_token") ) DATA_LOCATION1 = ["items"] diff --git a/Matrix_Portal/Matrix_Portal_Moon_Clock/code.py b/Matrix_Portal/Matrix_Portal_Moon_Clock/code.py index 415e98152..4bbe764d9 100644 --- a/Matrix_Portal/Matrix_Portal_Moon_Clock/code.py +++ b/Matrix_Portal/Matrix_Portal_Moon_Clock/code.py @@ -17,6 +17,8 @@ """ # pylint: disable=import-error + +from os import getenv import gc import time import math @@ -30,11 +32,17 @@ import adafruit_display_text.label import adafruit_lis3dh -try: - from secrets import secrets -except ImportError: - print('WiFi secrets are kept in secrets.py, please add them there!') - raise +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # CONFIGURABLE SETTINGS ---------------------------------------------------- @@ -61,7 +69,7 @@ def update_system_time(): """ Update system clock date/time from Adafruit IO. Credentials and time - zone are in secrets.py. See http://worldtimeapi.org/api/timezone for + zone are in settings.toml. See http://worldtimeapi.org/api/timezone for list of time zones. If missing, will attempt using IP geolocation. Returns present local (not UTC) time as a struct_time and UTC offset as string "sHH:MM". This may throw an exception on get_local_time(), @@ -271,11 +279,11 @@ def __init__(self, datetime_local_struct, days_ahead, utc_offset_string): # LATITUDE, LONGITUDE, TIMEZONE are set up once, constant over app lifetime -# Fetch latitude/longitude from secrets.py. If not present, use +# Fetch latitude/longitude from settings.toml. If not present, use # IP geolocation. This only needs to be done once, at startup! try: - LATITUDE = secrets['latitude'] - LONGITUDE = secrets['longitude'] + LATITUDE = getenv('latitude') + LONGITUDE = getenv('longitude') print('Using stored geolocation: ', LATITUDE, LONGITUDE) except KeyError: LATITUDE, LONGITUDE = ( @@ -285,7 +293,7 @@ def __init__(self, datetime_local_struct, days_ahead, utc_offset_string): print('Using IP geolocation: ', LATITUDE, LONGITUDE) # Set initial clock time, also fetch initial UTC offset while -# here (NOT stored in secrets.py as it may change with DST). +# here (NOT stored in settings.toml as it may change with DST). # pylint: disable=bare-except try: DATETIME_LOCAL_STRUCT, UTC_OFFSET_STRING = update_system_time() @@ -328,7 +336,7 @@ def __init__(self, datetime_local_struct, days_ahead, utc_offset_string): # moon properties are UTC. Convert 'now' to UTC seconds... # UTC_OFFSET_STRING is a string, like +HH:MM. Convert to integer seconds: hhmm = UTC_OFFSET_STRING.split(':') - utc_offset_seconds = ((int(hhmm[0]) * 60 + int(hhmm[1])) * 60) + utc_offset_seconds = (int(hhmm[0]) * 60 + int(hhmm[1])) * 60 NOW_UTC_SECONDS = NOW_LOCAL_SECONDS - utc_offset_seconds # If PERIOD has expired, move data down and fetch new +24-hour data diff --git a/Metro_Matrix_Clock/code.py b/Metro_Matrix_Clock/code.py index acb389a55..5773448c0 100644 --- a/Metro_Matrix_Clock/code.py +++ b/Metro_Matrix_Clock/code.py @@ -5,6 +5,7 @@ # Metro Matrix Clock # Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield +from os import getenv import time import board import displayio @@ -17,14 +18,20 @@ BLINK = True DEBUG = False -# 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 +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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(" Metro Minimal Clock") -print("Time will be set for {}".format(secrets["timezone"])) +print("Time will be set for {}".format(getenv("timezone"))) # --- Display setup --- matrix = Matrix() diff --git a/literary-clock/code.py b/literary-clock/code.py index 57ce1bcde..fcb8baf2f 100644 --- a/literary-clock/code.py +++ b/literary-clock/code.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: 2022 Eva Herrada for Adafruit Industries # SPDX-License-Identifier: MIT +from os import getenv import time import ssl @@ -17,6 +18,21 @@ import displayio from adafruit_display_shapes.rect import Rect +# 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." + ) + UTC_OFFSET = -4 quotes = {} @@ -81,18 +97,9 @@ ) splash.append(author_label) -try: - from secrets import secrets -except ImportError: - print("WiFi secrets are kept in secrets.py, please add them there!") - raise - -aio_username = secrets["aio_username"] -aio_key = secrets["aio_key"] - -print(f"Connecting to {secrets['ssid']}") -wifi.radio.connect(secrets["ssid"], secrets["password"]) -print(f"Connected to {secrets['ssid']}!") +print(f"Connecting to {ssid}") +wifi.radio.connect(ssid, password) +print(f"Connected to {ssid}!") def get_width(font, text): @@ -202,8 +209,8 @@ def message(client, feed_id, payload): # pylint: disable=unused-argument mqtt_client = MQTT.MQTT( broker="io.adafruit.com", port=1883, - username=secrets["aio_username"], - password=secrets["aio_key"], + username=aio_username, + password=aio_key, socket_pool=pool, ssl_context=ssl.create_default_context(), ) diff --git a/oshwa_magtag_display/code.py b/oshwa_magtag_display/code.py index 680fcf588..5ef1bf817 100644 --- a/oshwa_magtag_display/code.py +++ b/oshwa_magtag_display/code.py @@ -2,6 +2,7 @@ # # SPDX-License-Identifier: MIT +from os import getenv import random import ssl import gc @@ -10,12 +11,17 @@ import adafruit_requests from adafruit_magtag.magtag import MagTag -# 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 +# Get WiFi details, ensure these are setup in settings.toml +ssid = getenv("CIRCUITPY_WIFI_SSID") +password = getenv("CIRCUITPY_WIFI_PASSWORD") + +if None in [ssid, password]: + 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." + ) # Initialize magtag object magtag = MagTag() @@ -23,9 +29,9 @@ magtag.set_background("bmps/oshwa_full.bmp") # Set up WiFi -wifi.radio.connect(secrets["ssid"], secrets["password"]) -print(f"Connected to {secrets['ssid']}!") -print("My IP address is", wifi.radio.ipv4_address) +wifi.radio.connect(ssid, password) +print(f"Connected to {ssid}!") +print(f"My IP address is {wifi.radio.ipv4_address}") socket = socketpool.SocketPool(wifi.radio) https = adafruit_requests.Session(socket, ssl.create_default_context())