Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active December 5, 2020 06:18
Show Gist options
  • Save todbot/3d1c4a0d0f79442bfe727153bffbc5a6 to your computer and use it in GitHub Desktop.
Save todbot/3d1c4a0d0f79442bfe727153bffbc5a6 to your computer and use it in GitHub Desktop.
Given a list of preferred networks, connect to the one with the strongest signal, for CircuitPython ESP32S2
#
# wifi-preferred-network.py -- Given a list of preferred networks,
# connect to the one with the strongest signal
# for CircuitPython ESP32S2 Metro / MagTag
# 2020 @todbot / todbot.com/blog
import time
import wifi
from secrets import secrets
def find_preferred_network(ssid_prefs, networks=None):
"""Return a preferred Network and password given a list of preferred SSIDs.
:param list ssid_prefs: list of ssid/password pairs in secrets.py format.
:param list networks: list of wifi.Network objects, or None to perform scan.
:returns: (Network,password): The wifi.Network and password most preferred
Example:
.. code-block:: python
ssid_prefs = [ {'ssid':'todbot', 'password':'toomanysecrets'},
{'ssid':'todbot2', 'password':'setecastronomy'}]
(my_network,my_password) = find_preferred_network(ssid_prefs)
"""
if not networks:
networks = []
for network in wifi.radio.start_scanning_networks():
networks.append(network)
wifi.radio.stop_scanning_networks()
# sort by signal strength
networks = sorted(networks, key=lambda net: net.rssi, reverse=True)
# find first preferred network that matches
for network in networks:
for ssid_pref in ssid_prefs:
if ssid_pref['ssid'] == network.ssid:
return(network, ssid_pref['password'])
# Demonstrate how to use "find_preferred_network()"
print("Finding preferred network...")
(my_network, my_password) = find_preferred_network( secrets['ssid_prefs'] )
print("Connecting to %s" % my_network.ssid)
wifi.radio.connect(ssid=my_network.ssid, password=my_password, channel=my_network.channel)
while True:
print(time.monotonic(), "hi there")
time.sleep(5)
# Can also call it with an explicit list of networks, like:
# print("looking for networks:")
# networks = []
# for network in wifi.radio.start_scanning_networks():
# networks.append(network)
# print(" ssid:%s \t\t channel:%d" % (network.ssid,network.channel))
# wifi.radio.stop_scanning_networks()
#
# print("Finding preferred network...")
# (my_network, my_password) = find_preferred_network( secrets['ssid_prefs'], networks )
# print("Connecting to %s" % my_network.ssid)
# wifi.radio.connect(ssid=my_network.ssid, password=my_password, channel=my_network.channel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment