Skip to content

Secrets Cleanup: P Part 1 #3004

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 25 additions & 18 deletions Pi_In_Stock_Notifier/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#
# SPDX-License-Identifier: MIT

from os import getenv
import time
import ssl
import wifi
Expand All @@ -14,6 +15,21 @@
from digitalio import DigitalInOut, Direction, Pull
from adafruit_debouncer import Debouncer

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

alarm_out = DigitalInOut(board.A1)
alarm_out.direction = Direction.OUTPUT
alarm_out.value = False
Expand All @@ -23,37 +39,28 @@
button = Debouncer(button_in)


# 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

print("Adafruit Raspberry Pi In Stock Tweet Listener")

# import your bearer token
bear = secrets['bearer_token']
bearer_token = getenv('bearer_token')

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

headers = {'Authorization': 'Bearer ' + bear}
headers = {'Authorization': 'Bearer ' + bearer_token}

print("Connecting to %s"%secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!"%secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)
print(f"Connecting to {ssid}")
wifi.radio.connect(ssid, password)
print(f"Connected to {ssid}!")
print(f"My IP address is {wifi.radio.ipv4_address}")

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

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

Expand Down Expand Up @@ -132,14 +139,14 @@

else:
# if it's not new, then the wait continues
no_tweet_text = ("No stock in last hour :( Last stock: %s" % (timestamp))
no_tweet_text = "No stock in last hour :( Last stock: %s" % (timestamp)
text_area.text = "\n".join(wrap_text_to_lines(no_tweet_text, 21))
print("no new in stock notifications :(")
# updates tweet ID
last_value = value
# if the tweet wasn't today
else:
# if it's not new, then the wait continues
no_tweet_text = ("No stock in last hour :( Last stock: %s" % (timestamp))
no_tweet_text = "No stock in last hour :( Last stock: %s" % (timestamp)
text_area.text = "\n".join(wrap_text_to_lines(no_tweet_text, 21))
print("no new in stock notifications :(")
18 changes: 15 additions & 3 deletions Pico_W_CircuitPython_WiFi_Examples/Pico_W_Basic_WiFi_Test/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,29 @@
#
# SPDX-License-Identifier: MIT

import os
from os import getenv
import ipaddress
import wifi
import socketpool

# 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()
print("Connecting to WiFi")

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

# prints IP address to REPL
print("My IP address is", wifi.radio.ipv4_address)
print(f"My IP address is {wifi.radio.ipv4_address}")

# pings Google
ipv4 = ipaddress.ip_address("8.8.4.4")
Expand Down
20 changes: 13 additions & 7 deletions Purple_Air_Display/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,23 @@
# or Matrix Portal
# and 64 x 32 RGB LED Matrix

from os import getenv
import time
import board
import terminalio
from adafruit_matrixportal.matrixportal import MatrixPortal

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

def aqi_transform(val):
aqi = pm_to_aqi(val) # derive Air Quality Index from Particulate Matter 2.5 value
Expand Down Expand Up @@ -49,7 +55,7 @@ def message_transform(val): # picks message based on thresholds
status_neopixel=board.NEOPIXEL,
debug=True,
url=DATA_SOURCE,
headers={"X-API-Key": secrets["purple_air_api_key"], # purpleair.com
headers={"X-API-Key": getenv("purple_air_api_key"), # purpleair.com
"Accept": "application/json"
},
json_path=(DATA_LOCATION, DATA_LOCATION),
Expand Down
29 changes: 19 additions & 10 deletions PyPortal/PyPortal_AWS_IOT_Planter/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@

Author: Brent Rubell for Adafruit Industries, 2019
"""
import os

from os import getenv
import time
import json
import board
Expand All @@ -28,10 +29,17 @@
# Time between polling the STEMMA, in minutes
SENSOR_DELAY = 15

secrets = {
"ssid" : os.getenv("CIRCUITPY_WIFI_SSID"),
"password" : os.getenv("CIRCUITPY_WIFI_PASSWORD"),
}
# 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."
)

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

status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
esp, secrets, status_light)
status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.WiFiManager(
esp, ssid, password, status_pixel=status_pixel
)

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

# Set up a new MiniMQTT Client
client = MQTT.MQTT(broker = os.getenv("BROKER"),
client_id = os.getenv("CLIENT_ID"),
client = MQTT.MQTT(broker = getenv("BROKER"),
client_id = getenv("CLIENT_ID"),
socket_pool=pool,
ssl_context=ssl_context)

Expand Down
24 changes: 17 additions & 7 deletions PyPortal/PyPortal_AdafruitIO/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,29 @@
and io plus subscribers... and display it on a screen
If you can find something that spits out JSON data, we can display it!
"""

from os import getenv
import time
import board
from adafruit_pyportal import PyPortal

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

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

Expand Down
34 changes: 19 additions & 15 deletions PyPortal/PyPortal_AdafruitIO_Logger/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
* CircuitPython_AdafruitIO
https://github.com/adafruit/Adafruit_CircuitPython_AdafruitIO
"""

from os import getenv
import time
import board
import busio
Expand All @@ -33,30 +35,32 @@
# Timeout between sending data to Adafruit IO, in seconds
IO_DELAY = 30

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

# PyPortal ESP32 Setup
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
ADAFRUIT_IO_USER = secrets['aio_username']
ADAFRUIT_IO_KEY = secrets['aio_key']
status_pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.WiFiManager(esp, ssid, password, status_pixel=status_pixel)

# Create an instance of the Adafruit IO HTTP client
io = IO_HTTP(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY, wifi)
io = IO_HTTP(aio_username, aio_key, wifi)

try:
# Get the 'temperature' feed from Adafruit IO
Expand Down
22 changes: 17 additions & 5 deletions PyPortal/PyPortal_Alarm_Clock/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
#pylint:disable=no-self-use,too-many-branches,too-many-statements
#pylint:disable=useless-super-delegation, too-many-locals

from os import getenv
import time
import json
from secrets import secrets
import board
from adafruit_pyportal import PyPortal
from adafruit_bitmap_font import bitmap_font
Expand All @@ -32,9 +32,21 @@
import displayio
import adafruit_logging as logging

# 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 = 'http://api.openweathermap.org/data/2.5/weather?id='+secrets['city_id']
DATA_SOURCE += '&appid='+secrets['openweather_token']
DATA_SOURCE = 'http://api.openweathermap.org/data/2.5/weather?id='+getenv('city_id')
DATA_SOURCE += '&appid='+getenv('openweather_token')
# You'll need to get a token from openweather.org, looks like 'b6907d289e10d714a6e88b30761fae22'
DATA_LOCATION = []

Expand Down Expand Up @@ -73,7 +85,7 @@

icon_file = None
icon_sprite = None
celcius = secrets['celcius']
celcius = getenv('celcius')

# display/data refresh timers

Expand Down Expand Up @@ -243,7 +255,7 @@ def tick(self, now):
if (not self.refresh_time) or ((now - self.refresh_time) > 3600):
logger.debug('Fetching time')
try:
pyportal.get_local_time(location=secrets['timezone'])
pyportal.get_local_time(location=getenv('timezone'))
self.refresh_time = now
except RuntimeError as e:
self.refresh_time = now - 3000 # delay 10 minutes before retrying
Expand Down
Loading