Skip to content

WiFiManager updates #216

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 5 commits into from
Feb 22, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions adafruit_esp32spi/adafruit_esp32spi.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

import struct
import time
import warnings
from micropython import const
from adafruit_bus_device.spi_device import SPIDevice
from digitalio import Direction
Expand Down Expand Up @@ -663,6 +664,10 @@ def connect(self, ssid, password=None, timeout=10):
This upward compatbility will be removed in a future release.
"""
if isinstance(ssid, dict): # secrets
warnings.warn(
"The passing in of `secrets`, is deprecated. Use connect with a `ssid` and "
"`password` instead and fetch values from settings.toml with `os.getenv()`."
)
ssid, password = ssid["ssid"], ssid.get("password")
self.connect_AP(ssid, password, timeout_s=timeout)

Expand Down
88 changes: 74 additions & 14 deletions adafruit_esp32spi/adafruit_esp32spi_wifimanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

# pylint: disable=no-name-in-module

import warnings
from time import sleep
from micropython import const
import adafruit_connection_manager
Expand All @@ -21,7 +22,7 @@


# pylint: disable=too-many-instance-attributes
class ESPSPI_WiFiManager:
class WiFiManager:
"""
A class to help manage the Wifi connection
"""
Expand All @@ -33,17 +34,22 @@ class ESPSPI_WiFiManager:
def __init__(
self,
esp,
secrets,
ssid,
password=None,
*,
enterprise_ident=None,
enterprise_user=None,
status_pixel=None,
attempts=2,
connection_type=NORMAL,
debug=False,
):
"""
:param ESP_SPIcontrol esp: The ESP object we are using
:param dict secrets: The WiFi and Adafruit IO secrets dict (See examples)
The use of secrets.py to populate the secrets dict is depreciated
in favor of using settings.toml.
:param str ssid: the SSID of the created Access Point. Must be less than 32 chars.
:param str password: the password of the created Access Point. Must be 8-63 chars.
:param str enterprise_ident: the ident when connecting to an enterprise Access Point.
:param str enterprise_user: the user when connecting to an enterprise Access Point.
:param status_pixel: (Optional) The pixel device - A NeoPixel, DotStar,
or RGB LED (default=None). The status LED, if given, turns red when
attempting to connect to a Wi-Fi network or create an access point,
Expand All @@ -57,8 +63,8 @@ def __init__(
# Read the settings
self.esp = esp
self.debug = debug
self.ssid = secrets["ssid"]
self.password = secrets.get("password", None)
self.ssid = ssid
self.password = password
self.attempts = attempts
self._connection_type = connection_type
self.statuspix = status_pixel
Expand All @@ -70,11 +76,11 @@ def __init__(
ssl_context = adafruit_connection_manager.get_radio_ssl_context(self.esp)
self._requests = adafruit_requests.Session(pool, ssl_context)

# Check for WPA2 Enterprise keys in the secrets dictionary and load them if they exist
self.ent_ssid = secrets.get("ent_ssid", secrets["ssid"])
self.ent_ident = secrets.get("ent_ident", "")
self.ent_user = secrets.get("ent_user")
self.ent_password = secrets.get("ent_password")
# Check for WPA2 Enterprise values
self.ent_ssid = ssid
self.ent_ident = enterprise_ident
self.ent_user = enterprise_user
self.ent_password = password

# pylint: enable=too-many-arguments

Expand All @@ -97,9 +103,9 @@ def connect(self):
print("MAC addr:", [hex(i) for i in self.esp.MAC_address])
for access_pt in self.esp.scan_networks():
print("\t%s\t\tRSSI: %d" % (access_pt.ssid, access_pt.rssi))
if self._connection_type == ESPSPI_WiFiManager.NORMAL:
if self._connection_type == WiFiManager.NORMAL:
self.connect_normal()
elif self._connection_type == ESPSPI_WiFiManager.ENTERPRISE:
elif self._connection_type == WiFiManager.ENTERPRISE:
self.connect_enterprise()
else:
raise TypeError("Invalid WiFi connection type specified")
Expand Down Expand Up @@ -347,3 +353,57 @@ def signal_strength(self):
if not self.esp.is_connected:
self.connect()
return self.esp.ap_info.rssi


# pylint: disable=too-many-instance-attributes
class ESPSPI_WiFiManager(WiFiManager):
"""
A legacy class to help manage the Wifi connection. Please update to using WiFiManager
"""

# pylint: disable=too-many-arguments
def __init__(
self,
esp,
secrets,
status_pixel=None,
attempts=2,
connection_type=WiFiManager.NORMAL,
debug=False,
):
"""
:param ESP_SPIcontrol esp: The ESP object we are using
:param dict secrets: The WiFi secrets dict
The use of secrets.py to populate the secrets dict is depreciated
in favor of using settings.toml.
:param status_pixel: (Optional) The pixel device - A NeoPixel, DotStar,
or RGB LED (default=None). The status LED, if given, turns red when
attempting to connect to a Wi-Fi network or create an access point,
turning green upon success. Additionally, if given, it will turn blue
when attempting an HTTP method or returning IP address, turning off
upon success.
:type status_pixel: NeoPixel, DotStar, or RGB LED
:param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2)
:param const connection_type: (Optional) Type of WiFi connection: NORMAL or ENTERPRISE
"""

warnings.warn(
"ESP32WiFiManager, which uses `secrets`, is deprecated. Use WifiManager instead and "
"fetch values from settings.toml with `os.getenv()`."
)

ssid = secrets.get("ssid")
password = secrets.get("secrets", None)
enterprise_ident = secrets.get("ent_ident", "")
enterprise_user = secrets.get("ent_user")
super().__init__(
esp=esp,
ssid=ssid,
password=password,
enterprise_ident=enterprise_ident,
enterprise_user=enterprise_user,
status_pixel=status_pixel,
attempts=attempts,
connection_type=connection_type,
debug=debug,
)
28 changes: 9 additions & 19 deletions examples/esp32spi_aio_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,18 @@
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import WiFiManager

print("ESP32 SPI webclient test")

# Get wifi details and more from a settings.toml file
# tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD
# CIRCUITPY_AIO_USERNAME, CIRCUITPY_AIO_KEY
secrets = {}
for token in ["ssid", "password"]:
if getenv("CIRCUITPY_WIFI_" + token.upper()):
secrets[token] = getenv("CIRCUITPY_WIFI_" + token.upper())
for token in ["aio_username", "aio_key"]:
if getenv("CIRCUITPY_" + token.upper()):
secrets[token] = getenv("CIRCUITPY_" + token.upper())
# ADAFRUIT_AIO_USERNAME, ADAFRUIT_AIO_KEY
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")

if not secrets:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
aio_username = getenv("ADAFRUIT_AIO_USERNAME")
aio_key = getenv("ADAFRUIT_AIO_KEY")

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
Expand Down Expand Up @@ -59,7 +49,7 @@
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)

wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
wifi = WiFiManager(esp, ssid, password, status_light=status_light)

counter = 0

Expand All @@ -71,12 +61,12 @@
payload = {"value": data}
response = wifi.post(
"https://io.adafruit.com/api/v2/"
+ secrets["aio_username"]
+ aio_username
+ "/feeds/"
+ feed
+ "/data",
json=payload,
headers={"X-AIO-KEY": secrets["aio_key"]},
headers={"X-AIO-KEY": aio_key},
)
print(response.json())
response.close()
Expand Down
17 changes: 4 additions & 13 deletions examples/esp32spi_cheerlights.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,12 @@
import adafruit_fancyled.adafruit_fancyled as fancy

from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import WiFiManager

# Get wifi details and more from a settings.toml file
# tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD
secrets = {
"ssid": getenv("CIRCUITPY_WIFI_SSID"),
"password": getenv("CIRCUITPY_WIFI_PASSWORD"),
}
if secrets == {"ssid": None, "password": None}:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")

print("ESP32 SPI webclient test")

Expand Down Expand Up @@ -59,7 +50,7 @@
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
wifi = WiFiManager(esp, ssid, password, status_light=status_light)

# neopixels
pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.3)
Expand Down
15 changes: 3 additions & 12 deletions examples/esp32spi_ipconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,8 @@

# Get wifi details and more from a settings.toml file
# tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD
secrets = {
"ssid": getenv("CIRCUITPY_WIFI_SSID"),
"password": getenv("CIRCUITPY_WIFI_PASSWORD"),
}
if secrets == {"ssid": None, "password": None}:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")

HOSTNAME = "esp32-spi-hostname-test"

Expand Down Expand Up @@ -66,7 +57,7 @@
print("Connecting to AP...")
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
esp.connect_AP(ssid, password)
except OSError as e:
print("could not connect to AP, retrying: ", e)
continue
Expand Down
17 changes: 4 additions & 13 deletions examples/esp32spi_localtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,12 @@
import neopixel
import rtc
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
from adafruit_esp32spi.adafruit_esp32spi_wifimanager import WiFiManager

# Get wifi details and more from a settings.toml file
# tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD
secrets = {
"ssid": getenv("CIRCUITPY_WIFI_SSID"),
"password": getenv("CIRCUITPY_WIFI_PASSWORD"),
}
if secrets == {"ssid": None, "password": None}:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")

print("ESP32 local time")

Expand Down Expand Up @@ -58,7 +49,7 @@
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)

wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
wifi = WiFiManager(esp, ssid, password, status_light=status_light)

the_rtc = rtc.RTC()

Expand Down
4 changes: 2 additions & 2 deletions examples/esp32spi_settings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
CIRCUITPY_WIFI_SSID="yourssid"
CIRCUITPY_WIFI_PASSWORD="yourpassword"
CIRCUITPY_TIMEZONE="America/New_York"
CIRCUITPY_AIO_USERNAME="youraiousername"
CIRCUITPY_AIO_KEY="youraiokey"
ADAFRUIT_AIO_USERNAME="youraiousername"
ADAFRUIT_AIO_KEY="youraiokey"
15 changes: 3 additions & 12 deletions examples/esp32spi_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,8 @@

# Get wifi details and more from a settings.toml file
# tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD
secrets = {
"ssid": getenv("CIRCUITPY_WIFI_SSID"),
"password": getenv("CIRCUITPY_WIFI_PASSWORD"),
}
if secrets == {"ssid": None, "password": None}:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")

print("ESP32 SPI webclient test")

Expand Down Expand Up @@ -72,7 +63,7 @@
print("Connecting to AP...")
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
esp.connect_AP(ssid, password)
except OSError as e:
print("could not connect to AP, retrying: ", e)
continue
Expand Down
15 changes: 3 additions & 12 deletions examples/esp32spi_simpletest_rp2040.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,8 @@

# Get wifi details and more from a settings.toml file
# tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD
secrets = {
"ssid": getenv("CIRCUITPY_WIFI_SSID"),
"password": getenv("CIRCUITPY_WIFI_PASSWORD"),
}
if secrets == {"ssid": None, "password": None}:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
ssid = getenv("CIRCUITPY_WIFI_SSID")
password = getenv("CIRCUITPY_WIFI_PASSWORD")

print("Raspberry Pi RP2040 - ESP32 SPI webclient test")

Expand Down Expand Up @@ -51,7 +42,7 @@
print("Connecting to AP...")
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
esp.connect_AP(ssid, password)
except OSError as e:
print("could not connect to AP, retrying: ", e)
continue
Expand Down
Loading