-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathwifiman.py
67 lines (55 loc) · 1.75 KB
/
wifiman.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import network
import time
def read_profiles():
with open("wifiman.conf") as f:
lines = f.readlines()
profiles = {}
for line in lines:
if line.find(":")>=0:
ssid, password = line.strip("\n").split(":")
profiles[ssid] = password
return profiles
wlan_sta = network.WLAN(network.STA_IF)
def get_connection():
"""return a working WLAN(STA_IF) instance or None"""
# First check if there already is any connection:
if wlan_sta.isconnected():
return wlan_sta
connected = False
try:
# ESP connecting to WiFi takes time, wait a bit and try again:
time.sleep(3)
if wlan_sta.isconnected():
return wlan_sta
# Read known network profiles from file
profiles = read_profiles()
# Search WiFis in range
wlan_sta.active(True)
networks = wlan_sta.scan()
AUTHMODE = {0: "open", 1: "WEP", 2: "WPA-PSK", 3: "WPA2-PSK", 4: "WPA/WPA2-PSK"}
for ssid, bssid, channel, rssi, authmode, hidden in sorted(networks, key=lambda x: x[3], reverse=True):
ssid = ssid.decode('utf-8')
encrypted = authmode > 0
print("ssid: %s chan: %d rssi: %d authmode: %s" % (ssid, channel, rssi, AUTHMODE.get(authmode, '?')))
if ssid in profiles: # connect only to configured ssids
if encrypted:
connected = do_connect(ssid, profiles[ssid])
else:
connected = do_connect(ssid, None)
if connected:
break
except OSError as e:
print("exception", str(e))
return wlan_sta
def do_connect(ssid, password):
wlan_sta.active(True)
if wlan_sta.isconnected():
return None
wlan_sta.connect(ssid, password)
for retry in range(100):
connected = wlan_sta.isconnected()
if connected:
break
time.sleep(0.1)
return connected
get_connection()