-
Notifications
You must be signed in to change notification settings - Fork 0
/
wpa_supplicant.py
46 lines (42 loc) · 1.35 KB
/
wpa_supplicant.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import json
import network
from machine import unique_id
from binascii import hexlify
import time
import sys
try:
from hostname import NAME
except Exception:
NAME = f"{sys.platform}-{hexlify(unique_id())}"
def setup_network(timeout=10, hostname=NAME, notify=True):
n = 0
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
scan = network.WLAN(network.STA_IF).scan()
scan_tuples = [(x[0].decode(), x[3]) for x in scan]
# Sort by dBm
scan_tuples.sort(key=lambda x: x[1], reverse=True)
# Set device hostname
wlan.config(dhcp_hostname=hostname)
try:
with open("wpa_supplicant.config", "r") as wpa_conf:
wifi_config = json.load(wpa_conf)
except Exception as e:
sys.print_exception(e, sys.stdout)
return
_APs_in_range = [x[0] for x in scan_tuples if x[0] in wifi_config.keys()]
if _APs_in_range:
_ssid = _APs_in_range[0]
if not wlan.isconnected():
if notify:
print("Connecting to network...")
wlan.connect(_ssid, wifi_config[_ssid])
while not wlan.isconnected():
n += 1
time.sleep(1)
if n > timeout:
return False
if notify:
print(f"Connected to {_ssid}")
print("Network Config:", wlan.ifconfig())
return _ssid