2017-10-22 19:49:26 +00:00
|
|
|
import network
|
|
|
|
import networkconfig
|
|
|
|
import time
|
2017-12-11 13:38:41 +00:00
|
|
|
|
2017-10-22 19:49:26 +00:00
|
|
|
wlan_sta = network.WLAN(network.STA_IF)
|
|
|
|
|
2017-12-11 13:38:41 +00:00
|
|
|
|
|
|
|
def check_connection():
|
|
|
|
global wlan_sta
|
2017-12-11 14:06:47 +00:00
|
|
|
# First check if there already is any connection:
|
2017-12-11 13:38:41 +00:00
|
|
|
if wlan_sta.isconnected():
|
2017-12-11 14:12:22 +00:00
|
|
|
return True
|
2017-12-11 23:34:09 +00:00
|
|
|
|
|
|
|
connected = False
|
2017-12-11 13:38:41 +00:00
|
|
|
try:
|
2017-12-11 14:06:47 +00:00
|
|
|
# ESP connecting to WiFi takes time, wait a bit and try again:
|
2017-12-11 13:38:41 +00:00
|
|
|
time.sleep(3)
|
2017-12-11 23:34:09 +00:00
|
|
|
if wlan_sta.isconnected():
|
2017-12-11 14:12:22 +00:00
|
|
|
return True
|
2017-10-22 19:49:26 +00:00
|
|
|
|
2017-12-11 23:34:09 +00:00
|
|
|
# Read known network profiles from file
|
|
|
|
profiles = networkconfig.read_profiles()
|
|
|
|
|
|
|
|
# Search WiFis in range
|
|
|
|
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 encrypted:
|
|
|
|
if ssid in profiles:
|
|
|
|
password = profiles[ssid]
|
|
|
|
connected = networkconfig.do_connect(ssid, password)
|
|
|
|
else:
|
|
|
|
print("skipping unknown encrypted network")
|
|
|
|
else: # open
|
|
|
|
connected = networkconfig.do_connect(ssid, None)
|
|
|
|
if connected:
|
|
|
|
break
|
|
|
|
|
2017-12-11 13:38:41 +00:00
|
|
|
except OSError:
|
2017-12-11 23:34:09 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
# start web server for connection manager:
|
|
|
|
if not connected:
|
|
|
|
connected = networkconfig.start()
|
2017-10-22 19:49:26 +00:00
|
|
|
|
2017-12-11 23:34:09 +00:00
|
|
|
return connected
|
2017-10-22 19:49:26 +00:00
|
|
|
|
2017-12-11 13:38:41 +00:00
|
|
|
|
|
|
|
if check_connection():
|
|
|
|
|
|
|
|
# Main Code is here
|
|
|
|
print("ESP OK")
|
2017-12-11 14:06:47 +00:00
|
|
|
# to import your code;
|
|
|
|
# import sample_mqtt.py
|
2017-12-11 13:38:41 +00:00
|
|
|
|
|
|
|
else:
|
2017-12-11 14:06:47 +00:00
|
|
|
print("There is something wrong.")
|