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

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
#-------------------------------------------------------------------------
# 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 = label.Label(terminalio.FONT, text="12:34:56 AM")
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

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-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 @@ scopes = ["https://www.googleapis.com/auth/calendar.readonly"]
# 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 @@ if not google_auth.wait_for_authorization():
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 @@ graphics.splash.pop()
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()

View file

@ -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 @@ WEEKDAYS = {
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 @@ magtag.network.connect()
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)

View file

@ -11,9 +11,10 @@ MIT license, all text above must be included in any redistribution.
"""
# 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_bitmap_font import bitmap_font
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 @@ MINIMUM_TIME = 5 * 60
# 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 ---------------------------------------------------

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
# 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"]

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
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 @@ DD_MM = False # If set, show DD/MM instead of MM/DD dates
# 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

View file

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

View file

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

View file

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

View file

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

View file

@ -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 @@ TWEET_HANDLE = [0, "user", "screen_name"]
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

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

View file

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

View file

@ -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 socketpool
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 @@ if not TEST_RUN:
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)

View file

@ -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 socketpool
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 @@ if not TEST_RUN:
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)

View file

@ -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_bitmap_font import bitmap_font
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 @@ DATA_SOURCE = (
"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"]

View file

@ -17,6 +17,8 @@ included in derivative projects, thanks. Tall splash images licensed from
"""
# pylint: disable=import-error
from os import getenv
import gc
import time
import math
@ -30,11 +32,17 @@ from adafruit_bitmap_font import bitmap_font
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 @@ HEADERS = { "User-Agent" : "AdafruitMoonClock/1.1 support@adafruit.com" }
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 @@ NETWORK.connect()
# 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 @@ except KeyError:
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 @@ while True:
# 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

View file

@ -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 @@ from adafruit_matrixportal.matrix import Matrix
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()

View file

@ -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 @@ from adafruit_bitmap_font import bitmap_font
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 @@ author_label = label.Label(
)
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 @@ pool = socketpool.SocketPool(wifi.radio)
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(),
)

View file

@ -2,6 +2,7 @@
#
# SPDX-License-Identifier: MIT
from os import getenv
import random
import ssl
import gc
@ -10,12 +11,17 @@ import socketpool
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 = MagTag()
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())