Secrets Cleanup: L, M and O

This commit is contained in:
Justin Myers 2025-03-25 07:49:30 -07:00
parent 53234f9932
commit 592b33be07
27 changed files with 341 additions and 191 deletions

View file

@ -22,7 +22,7 @@ from adafruit_macropad import MacroPad
# CONFIGURABLES ------------------------ # CONFIGURABLES ------------------------
# Password information # 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 = "2468"
PASSWORD_LENGTH = len(PASSWORD) PASSWORD_LENGTH = len(PASSWORD)

View file

@ -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)

View file

@ -31,15 +31,11 @@ DISPLAY_TIMEOUT = 60 # screen saver timeout in seconds
DISPLAY_RATE = 1 # screen refresh rate DISPLAY_RATE = 1 # screen refresh rate
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# Get secrets from a secrets.py file # Get totp_keys from a totp_keys.py file
try: try:
from secrets import secrets from totp_keys import totp_keys
totp_keys = secrets["totp_keys"]
except ImportError: except ImportError:
print("Secrets are kept in secrets.py, please add them there!") print("TOTP info not found in totp_keys.py, please add them there!")
raise
except KeyError:
print("TOTP info not found in secrets.py.")
raise raise
# set board to use PCF8523 as its RTC # set board to use PCF8523 as its RTC
@ -80,7 +76,9 @@ rtc_time = label.Label(terminalio.FONT, text="12:34:56 AM")
rtc_time.anchor_point = (0.0, 0.5) rtc_time.anchor_point = (0.0, 0.5)
rtc_time.anchored_position = (0, 59) 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 = displayio.Group()
splash.append(name) splash.append(name)
@ -172,15 +170,15 @@ def generate_otp(int_input, secret_key, digits=6):
int_to_bytestring(int_input)).digest() int_to_bytestring(int_input)).digest()
) )
offset = hmac_hash[-1] & 0xf offset = hmac_hash[-1] & 0xf
code = ((hmac_hash[offset] & 0x7f) << 24 | otp_code = ((hmac_hash[offset] & 0x7f) << 24 |
(hmac_hash[offset + 1] & 0xff) << 16 | (hmac_hash[offset + 1] & 0xff) << 16 |
(hmac_hash[offset + 2] & 0xff) << 8 | (hmac_hash[offset + 2] & 0xff) << 8 |
(hmac_hash[offset + 3] & 0xff)) (hmac_hash[offset + 3] & 0xff))
str_code = str(code % 10 ** digits) str_otp_code = str(otp_code % 10 ** digits)
while len(str_code) < digits: while len(str_otp_code) < digits:
str_code = '0' + str_code 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 # M A C R O P A D S E T U P

View file

@ -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,
]
}

View file

@ -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,
]

View file

@ -1,21 +1,25 @@
# SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries # SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
from os import getenv
from adafruit_oauth2 import OAuth2 from adafruit_oauth2 import OAuth2
from adafruit_display_text.label import Label from adafruit_display_text.label import Label
from adafruit_bitmap_font import bitmap_font from adafruit_bitmap_font import bitmap_font
from adafruit_magtag.magtag import Graphics, Network from adafruit_magtag.magtag import Graphics, Network
from adafruit_display_shapes.rect import Rect from adafruit_display_shapes.rect import Rect
# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and # Get WiFi details, ensure these are setup in settings.toml
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other ssid = getenv("CIRCUITPY_WIFI_SSID")
# source control. password = getenv("CIRCUITPY_WIFI_PASSWORD")
# pylint: disable=no-name-in-module,wrong-import-order
try: if None in [ssid, password]:
from secrets import secrets raise RuntimeError(
except ImportError: "WiFi settings are kept in settings.toml, "
print("Credentials and tokens are kept in secrets.py, please add them there!") "please add them there. The settings file must contain "
raise "'CIRCUITPY_WIFI_SSID', 'CIRCUITPY_WIFI_PASSWORD', "
"at a minimum."
)
network = Network() network = Network()
network.connect() network.connect()
@ -57,8 +61,8 @@ scopes = ["https://www.googleapis.com/auth/calendar.readonly"]
# Initialize an OAuth2 object # Initialize an OAuth2 object
google_auth = OAuth2( google_auth = OAuth2(
network.requests, network.requests,
secrets["google_client_id"], getenv("google_client_id"),
secrets["google_client_secret"], getenv("google_client_secret"),
scopes, scopes,
) )
@ -90,9 +94,9 @@ if not google_auth.wait_for_authorization():
raise RuntimeError("Timed out waiting for browser response!") raise RuntimeError("Timed out waiting for browser response!")
print("Successfully Authenticated with Google!") print("Successfully Authenticated with Google!")
print("Add the following lines to your secrets.py file:") print("Add the following lines to your settings.toml file:")
print("\t'google_access_token' " + ":" + " '%s'," % google_auth.access_token) print(f'google_access_token="{google_auth.access_token}"')
print("\t'google_refresh_token' " + ":" + " '%s'" % google_auth.refresh_token) print(f'google_refresh_token="{google_auth.refresh_token}"')
graphics.splash.pop() graphics.splash.pop()
graphics.splash.pop() graphics.splash.pop()
@ -100,6 +104,6 @@ graphics.splash.pop()
label_overview_text.text = "Successfully Authenticated!" label_overview_text.text = "Successfully Authenticated!"
label_verification_url.text = ( 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() display.refresh()

View file

@ -1,12 +1,26 @@
# SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries # SPDX-FileCopyrightText: 2021 Brent Rubell, written for Adafruit Industries
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
from os import getenv
import time import time
import rtc import rtc
from adafruit_oauth2 import OAuth2 from adafruit_oauth2 import OAuth2
from adafruit_display_shapes.line import Line from adafruit_display_shapes.line import Line
from adafruit_magtag.magtag import MagTag 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
CALENDAR_ID = "YOUR_CALENDAR_ID" CALENDAR_ID = "YOUR_CALENDAR_ID"
@ -42,15 +56,6 @@ WEEKDAYS = {
6: "Sunday", 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 # Create a new MagTag object
magtag = MagTag() magtag = MagTag()
@ -62,18 +67,18 @@ magtag.network.connect()
scopes = ["https://www.googleapis.com/auth/calendar.readonly"] scopes = ["https://www.googleapis.com/auth/calendar.readonly"]
google_auth = OAuth2( google_auth = OAuth2(
magtag.network.requests, magtag.network.requests,
secrets["google_client_id"], getenv("google_client_id"),
secrets["google_client_secret"], getenv("google_client_secret"),
scopes, scopes,
secrets["google_access_token"], getenv("google_access_token"),
secrets["google_refresh_token"], getenv("google_refresh_token"),
) )
def get_current_time(time_max=False): def get_current_time(time_max=False):
"""Gets local time from Adafruit IO and converts to RFC3339 timestamp.""" """Gets local time from Adafruit IO and converts to RFC3339 timestamp."""
# Get local time from Adafruit IO # Get local time from Adafruit IO
magtag.get_local_time(secrets["timezone"]) magtag.get_local_time(getenv("timezone"))
# Format as RFC339 timestamp # Format as RFC339 timestamp
cur_time = r.datetime cur_time = r.datetime
if time_max: # maximum time to fetch events is midnight (4:59:59UTC) if time_max: # maximum time to fetch events is midnight (4:59:59UTC)

View file

@ -11,9 +11,10 @@ MIT license, all text above must be included in any redistribution.
""" """
# pylint: disable=import-error # pylint: disable=import-error
from os import getenv
import gc import gc
import time import time
from secrets import secrets
import displayio import displayio
from rtc import RTC from rtc import RTC
from adafruit_magtag.magtag import Graphics from adafruit_magtag.magtag import Graphics
@ -23,6 +24,17 @@ from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label from adafruit_display_text.label import Label
from nextbus import NextBus 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 ---------------------------------------------------- # CONFIGURABLE SETTINGS ----------------------------------------------------
@ -54,15 +66,12 @@ MINIMUM_TIME = 5 * 60
# not a big problem if this drifts a bit due to infrequent synchronizations. # not a big problem if this drifts a bit due to infrequent synchronizations.
# 6 hour default. # 6 hour default.
CLOCK_SYNC_INTERVAL = 6 * 60 * 60 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 # (http://worldtimeapi.org/api/timezone for list). Again, this is only
# used for the 'Last checked' display, not predictions, so it's not # used for the 'Last checked' display, not predictions, so it's not
# especially disruptive if missing. # especially disruptive if missing.
# pylint: disable=bare-except # pylint: disable=bare-except
try: TIME_ZONE = getenv('timezone') # e.g. 'America/New_York'
TIME_ZONE = secrets['timezone'] # e.g. 'America/New_York'
except:
TIME_ZONE = None # Use IP geolocation
# SOME UTILITY FUNCTIONS --------------------------------------------------- # SOME UTILITY FUNCTIONS ---------------------------------------------------

View file

@ -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",
}

View file

@ -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"

View file

@ -4,11 +4,24 @@
# MagTag Quote Board # MagTag Quote Board
# Displays Quotes from the Adafruit quotes server # 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 import time
from adafruit_magtag.magtag import MagTag 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 # Set up where we'll be fetching data from
DATA_SOURCE = "https://www.adafruit.com/api/quotes.php" DATA_SOURCE = "https://www.adafruit.com/api/quotes.php"
QUOTE_LOCATION = [0, "text"] QUOTE_LOCATION = [0, "text"]

View file

@ -9,14 +9,27 @@ Lists in-season fruits and vegetables for a user's location and season.
""" """
# pylint: disable=import-error, line-too-long # pylint: disable=import-error, line-too-long
from os import getenv
import time import time
from secrets import secrets
import rtc import rtc
from adafruit_display_shapes.rect import Rect from adafruit_display_shapes.rect import Rect
from adafruit_magtag.magtag import MagTag from adafruit_magtag.magtag import MagTag
from produce import Produce 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 ------------------------ # CONFIGURABLE SETTINGS and ONE-TIME INITIALIZATION ------------------------
TWELVE_HOUR = True # If set, show 12-hour vs 24-hour (e.g. 3:00 vs 15:00) TWELVE_HOUR = True # If set, show 12-hour vs 24-hour (e.g. 3:00 vs 15:00)
@ -24,9 +37,9 @@ DD_MM = False # If set, show DD/MM instead of MM/DD dates
# Location of produce data (file:// or http:// or https://): # 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' 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. # 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) PRODUCE = Produce(JSON_URL, LOCATION)
MAGTAG = MagTag(rotation=0) # Portrait (vertical) display MAGTAG = MagTag(rotation=0) # Portrait (vertical) display

View file

@ -3,12 +3,24 @@
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
# MagTag Shower Thoughts # 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 time
import random import random
from adafruit_magtag.magtag import MagTag 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 # Set up where we'll be fetching data from
DATA_SOURCE = "https://www.reddit.com/r/showerthoughts/hot.json?limit=10" DATA_SOURCE = "https://www.reddit.com/r/showerthoughts/hot.json?limit=10"

View file

@ -4,13 +4,26 @@
# MagTag Showtimes Event Viewer # MagTag Showtimes Event Viewer
# Uses the events.json file to display next or current event # 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 time
import json import json
import re import re
from adafruit_magtag.magtag import MagTag 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 # 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) # (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) FAKETIME = False # time.struct_time(2020, 12, 11, 15, 01, 00, 4, 346, -1)

View file

@ -31,7 +31,6 @@ while True:
if HOUR_MODE_24: if HOUR_MODE_24:
timestr = "%d:%02d" % (hour, minute) timestr = "%d:%02d" % (hour, minute)
else: else:
is_pm = (hour >= 12)
hour %= 12 hour %= 12
if hour == 0: if hour == 0:
hour = 12 hour = 12

View file

@ -2,19 +2,31 @@
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
# MagTag Sports Schedule Viewer # 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 D to advance to next game
# Press C to go back one game # Press C to go back one game
# Press B to refresh the schedule (this takes a minute) # Press B to refresh the schedule (this takes a minute)
# Press A to advance to next sport (this takes a minute) # Press A to advance to next sport (this takes a minute)
from os import getenv
import time import time
import json import json
from adafruit_datetime import datetime, timedelta from adafruit_datetime import datetime, timedelta
from adafruit_magtag.magtag import MagTag 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 USE_24HR_TIME = False
TIME_ZONE_OFFSET = -8 # hours ahead or behind Zulu time, e.g. Pacific is -8 TIME_ZONE_OFFSET = -8 # hours ahead or behind Zulu time, e.g. Pacific is -8
TIME_ZONE_NAME = "PST" TIME_ZONE_NAME = "PST"
@ -186,7 +198,7 @@ def update_labels():
def fetch_sports_data(reset_game_number=True): def fetch_sports_data(reset_game_number=True):
# Fetches and parses data for all games for the current sport # Fetches and parses data for all games for the current sport
# pylint: disable=global-statement # pylint: disable=global-statement
global sports_data, current_game, current_sport global current_game
magtag.url = SPORTS[current_sport]["url"] magtag.url = SPORTS[current_sport]["url"]
sports_data.clear() sports_data.clear()
raw_data = json.loads(magtag.fetch(auto_refresh=False)) raw_data = json.loads(magtag.fetch(auto_refresh=False))

View file

@ -2,17 +2,22 @@
# SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries. # SPDX-FileCopyrightText: 2020 Brent Rubell for Adafruit Industries.
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
from os import getenv
import time import time
from adafruit_magtag.magtag import MagTag from adafruit_magtag.magtag import MagTag
try: # Get WiFi details, ensure these are setup in settings.toml
from secrets import secrets ssid = getenv("CIRCUITPY_WIFI_SSID")
except ImportError: password = getenv("CIRCUITPY_WIFI_PASSWORD")
print(
"""WiFi settings are kept in secrets.py, please add them there! if None in [ssid, password]:
the secrets dictionary must contain 'ssid' and 'password' at a minimum""" 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 # Set to the twitter username you'd like to fetch tweets from
TWITTER_USERNAME = "adafruit" TWITTER_USERNAME = "adafruit"
@ -31,7 +36,7 @@ TWEET_HANDLE = [0, "user", "screen_name"]
magtag = MagTag(url=DATA_SOURCE, json_path=(TWEET_FULL_NAME, TWEET_HANDLE, TWEET_TEXT)) magtag = MagTag(url=DATA_SOURCE, json_path=(TWEET_FULL_NAME, TWEET_HANDLE, TWEET_TEXT))
# Set Twitter OAuth2.0 Bearer Token # 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}) magtag.set_headers({"Authorization": "Bearer " + bearer_token})
# Display setup # Display setup

View file

@ -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)

View file

@ -3,13 +3,25 @@
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
# pylint: disable=redefined-outer-name, eval-used, wrong-import-order # pylint: disable=redefined-outer-name, eval-used, wrong-import-order
from os import getenv
import time import time
import terminalio import terminalio
import displayio import displayio
import adafruit_imageload import adafruit_imageload
from adafruit_display_text import label from adafruit_display_text import label
from adafruit_magtag.magtag import MagTag 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 |-------------------------- # --| USER CONFIG |--------------------------
METRIC = False # set to True for metric units 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]) URL += "&lon={}".format(location[1])
else: else:
raise ValueError("Unknown API type: " + api) raise ValueError("Unknown API type: " + api)
return URL + "&appid=" + secrets["openweather_token"] return URL + "&appid=" + getenv("openweather_token")
def get_latlon(city_name): def get_latlon(city_name):
@ -245,18 +257,20 @@ def go_to_sleep(current_time):
# =========== # ===========
# Location # 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 # Get lat/lon using city name
city = secrets["openweather_location"] city = openweather_location
print("Getting lat/lon for city:", city) print("Getting lat/lon for city:", city)
latlon = get_latlon(city) latlon = get_latlon(city)
elif isinstance(secrets["openweather_location"], tuple): elif openweather_location:
# Get city name using lat/lon # Get city name using lat/lon
latlon = secrets["openweather_location"] latlon = openweather_location.split(",")
print("Getting city name for lat/lon:", latlon) print("Getting city name for lat/lon:", latlon)
city = get_city(latlon) city = get_city(latlon)
else: else:
raise ValueError("Unknown location:", secrets["openweather_location"]) raise ValueError(f"Unknown location:{openweather_location}")
print("City =", city) print("City =", city)
print("Lat/Lon = ", latlon) print("Lat/Lon = ", latlon)

View file

@ -3,13 +3,25 @@
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
# pylint: disable=redefined-outer-name, eval-used, wrong-import-order # pylint: disable=redefined-outer-name, eval-used, wrong-import-order
from os import getenv
import time import time
import terminalio import terminalio
import displayio import displayio
import adafruit_imageload import adafruit_imageload
from adafruit_display_text import label from adafruit_display_text import label
from adafruit_magtag.magtag import MagTag 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 |-------------------------- # --| USER CONFIG |--------------------------
METRIC = False # set to True for metric units 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]) URL += "&lon={}".format(location[1])
else: else:
raise ValueError("Unknown API type: " + api) raise ValueError("Unknown API type: " + api)
return URL + "&appid=" + secrets["openweather_token"] return URL + "&appid=" + getenv("openweather_token")
def get_latlon(city_name): def get_latlon(city_name):
@ -183,18 +195,20 @@ def go_to_sleep(current_time):
# =========== # ===========
# Location # 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 # Get lat/lon using city name
city = secrets["openweather_location"] city = openweather_location
print("Getting lat/lon for city:", city) print("Getting lat/lon for city:", city)
latlon = get_latlon(city) latlon = get_latlon(city)
elif isinstance(secrets["openweather_location"], tuple): elif openweather_location:
# Get city name using lat/lon # Get city name using lat/lon
latlon = secrets["openweather_location"] latlon = openweather_location.split(",")
print("Getting city name for lat/lon:", latlon) print("Getting city name for lat/lon:", latlon)
city = get_city(latlon) city = get_city(latlon)
else: else:
raise ValueError("Unknown location:", secrets["openweather_location"]) raise ValueError(f"Unknown location:{openweather_location}")
print("City =", city) print("City =", city)
print("Lat/Lon = ", latlon) print("Lat/Lon = ", latlon)

View file

@ -4,6 +4,8 @@
""" """
MagTag status display for James Webb Telescope MagTag status display for James Webb Telescope
""" """
from os import getenv
import time import time
import json import json
import ssl import ssl
@ -18,11 +20,17 @@ import socketpool
import alarm import alarm
import adafruit_requests import adafruit_requests
try: # Get WiFi details, ensure these are setup in settings.toml
from secrets import secrets ssid = getenv("CIRCUITPY_WIFI_SSID")
except ImportError: password = getenv("CIRCUITPY_WIFI_PASSWORD")
print("WiFi secrets are kept in secrets.py, please add them there!")
raise 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 # Update once per hour
SLEEP_TIME = 60 * 60 # seconds SLEEP_TIME = 60 * 60 # seconds
@ -66,7 +74,7 @@ if not TEST_RUN:
print("Connecting to AP...") print("Connecting to AP...")
try: try:
# wifi connect # wifi connect
wifi.radio.connect(secrets["ssid"], secrets["password"]) wifi.radio.connect(ssid, password)
# Create Socket, initialize requests # Create Socket, initialize requests
socket = socketpool.SocketPool(wifi.radio) socket = socketpool.SocketPool(wifi.radio)

View file

@ -4,6 +4,8 @@
""" """
MagTag status display for James Webb Telescope MagTag status display for James Webb Telescope
""" """
from os import getenv
import time import time
import json import json
import ssl import ssl
@ -18,11 +20,17 @@ import socketpool
import alarm import alarm
import adafruit_requests import adafruit_requests
try: # Get WiFi details, ensure these are setup in settings.toml
from secrets import secrets ssid = getenv("CIRCUITPY_WIFI_SSID")
except ImportError: password = getenv("CIRCUITPY_WIFI_PASSWORD")
print("WiFi secrets are kept in secrets.py, please add them there!")
raise 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 # Update once per hour
SLEEP_TIME = 60 * 60 # seconds SLEEP_TIME = 60 * 60 # seconds
@ -64,7 +72,7 @@ if not TEST_RUN:
print("Connecting to AP...") print("Connecting to AP...")
try: try:
# wifi connect # wifi connect
wifi.radio.connect(secrets["ssid"], secrets["password"]) wifi.radio.connect(ssid, password)
# Create Socket, initialize requests # Create Socket, initialize requests
socket = socketpool.SocketPool(wifi.radio) socket = socketpool.SocketPool(wifi.radio)

View file

@ -5,6 +5,7 @@
# ON AIR sign for YouTube livestreaming # ON AIR sign for YouTube livestreaming
# Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield # Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield
from os import getenv
import time import time
import board import board
import displayio import displayio
@ -15,12 +16,17 @@ from adafruit_bitmap_font import bitmap_font
from adafruit_matrixportal.network import Network from adafruit_matrixportal.network import Network
from adafruit_matrixportal.matrix import Matrix from adafruit_matrixportal.matrix import Matrix
# 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."
)
# Set up where we'll be fetching data from # Set up where we'll be fetching data from
# Adafruit YouTube channel: # Adafruit YouTube channel:
@ -32,7 +38,7 @@ DATA_SOURCE = (
"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="
+ CHANNEL_ID + CHANNEL_ID
+ "&type=video&eventType=live&key=" + "&type=video&eventType=live&key="
+ secrets["youtube_token"] + getenv("youtube_token")
) )
DATA_LOCATION1 = ["items"] DATA_LOCATION1 = ["items"]

View file

@ -17,6 +17,8 @@ included in derivative projects, thanks. Tall splash images licensed from
""" """
# pylint: disable=import-error # pylint: disable=import-error
from os import getenv
import gc import gc
import time import time
import math import math
@ -30,11 +32,17 @@ from adafruit_bitmap_font import bitmap_font
import adafruit_display_text.label import adafruit_display_text.label
import adafruit_lis3dh import adafruit_lis3dh
try: # Get WiFi details, ensure these are setup in settings.toml
from secrets import secrets ssid = getenv("CIRCUITPY_WIFI_SSID")
except ImportError: password = getenv("CIRCUITPY_WIFI_PASSWORD")
print('WiFi secrets are kept in secrets.py, please add them there!')
raise 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 ---------------------------------------------------- # CONFIGURABLE SETTINGS ----------------------------------------------------
@ -61,7 +69,7 @@ HEADERS = { "User-Agent" : "AdafruitMoonClock/1.1 support@adafruit.com" }
def update_system_time(): def update_system_time():
""" Update system clock date/time from Adafruit IO. Credentials and 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. list of time zones. If missing, will attempt using IP geolocation.
Returns present local (not UTC) time as a struct_time and UTC offset 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(), as string "sHH:MM". This may throw an exception on get_local_time(),
@ -271,11 +279,11 @@ NETWORK.connect()
# LATITUDE, LONGITUDE, TIMEZONE are set up once, constant over app lifetime # 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! # IP geolocation. This only needs to be done once, at startup!
try: try:
LATITUDE = secrets['latitude'] LATITUDE = getenv('latitude')
LONGITUDE = secrets['longitude'] LONGITUDE = getenv('longitude')
print('Using stored geolocation: ', LATITUDE, LONGITUDE) print('Using stored geolocation: ', LATITUDE, LONGITUDE)
except KeyError: except KeyError:
LATITUDE, LONGITUDE = ( LATITUDE, LONGITUDE = (
@ -285,7 +293,7 @@ except KeyError:
print('Using IP geolocation: ', LATITUDE, LONGITUDE) print('Using IP geolocation: ', LATITUDE, LONGITUDE)
# Set initial clock time, also fetch initial UTC offset while # 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 # pylint: disable=bare-except
try: try:
DATETIME_LOCAL_STRUCT, UTC_OFFSET_STRING = update_system_time() DATETIME_LOCAL_STRUCT, UTC_OFFSET_STRING = update_system_time()
@ -328,7 +336,7 @@ while True:
# moon properties are UTC. Convert 'now' to UTC seconds... # moon properties are UTC. Convert 'now' to UTC seconds...
# UTC_OFFSET_STRING is a string, like +HH:MM. Convert to integer seconds: # UTC_OFFSET_STRING is a string, like +HH:MM. Convert to integer seconds:
hhmm = UTC_OFFSET_STRING.split(':') 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 NOW_UTC_SECONDS = NOW_LOCAL_SECONDS - utc_offset_seconds
# If PERIOD has expired, move data down and fetch new +24-hour data # If PERIOD has expired, move data down and fetch new +24-hour data

View file

@ -5,6 +5,7 @@
# Metro Matrix Clock # Metro Matrix Clock
# Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield # Runs on Airlift Metro M4 with 64x32 RGB Matrix display & shield
from os import getenv
import time import time
import board import board
import displayio import displayio
@ -17,14 +18,20 @@ from adafruit_matrixportal.matrix import Matrix
BLINK = True BLINK = True
DEBUG = False DEBUG = False
# 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(" Metro Minimal Clock") print(" Metro Minimal Clock")
print("Time will be set for {}".format(secrets["timezone"])) print("Time will be set for {}".format(getenv("timezone")))
# --- Display setup --- # --- Display setup ---
matrix = Matrix() matrix = Matrix()

View file

@ -1,6 +1,7 @@
# SPDX-FileCopyrightText: 2022 Eva Herrada for Adafruit Industries # SPDX-FileCopyrightText: 2022 Eva Herrada for Adafruit Industries
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
from os import getenv
import time import time
import ssl import ssl
@ -17,6 +18,21 @@ from adafruit_bitmap_font import bitmap_font
import displayio import displayio
from adafruit_display_shapes.rect import Rect 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 UTC_OFFSET = -4
quotes = {} quotes = {}
@ -81,18 +97,9 @@ author_label = label.Label(
) )
splash.append(author_label) splash.append(author_label)
try: print(f"Connecting to {ssid}")
from secrets import secrets wifi.radio.connect(ssid, password)
except ImportError: print(f"Connected to {ssid}!")
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']}!")
def get_width(font, text): def get_width(font, text):
@ -202,8 +209,8 @@ pool = socketpool.SocketPool(wifi.radio)
mqtt_client = MQTT.MQTT( mqtt_client = MQTT.MQTT(
broker="io.adafruit.com", broker="io.adafruit.com",
port=1883, port=1883,
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

@ -2,6 +2,7 @@
# #
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
from os import getenv
import random import random
import ssl import ssl
import gc import gc
@ -10,12 +11,17 @@ import socketpool
import adafruit_requests import adafruit_requests
from adafruit_magtag.magtag import MagTag from adafruit_magtag.magtag import MagTag
# 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."
)
# Initialize magtag object # Initialize magtag object
magtag = MagTag() magtag = MagTag()
@ -23,9 +29,9 @@ magtag = MagTag()
magtag.set_background("bmps/oshwa_full.bmp") magtag.set_background("bmps/oshwa_full.bmp")
# Set up WiFi # Set up WiFi
wifi.radio.connect(secrets["ssid"], secrets["password"]) wifi.radio.connect(ssid, password)
print(f"Connected to {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}")
socket = socketpool.SocketPool(wifi.radio) socket = socketpool.SocketPool(wifi.radio)
https = adafruit_requests.Session(socket, ssl.create_default_context()) https = adafruit_requests.Session(socket, ssl.create_default_context())