micropython-WiFiManager/main.py

62 wiersze
1.7 KiB
Python
Czysty Zwykły widok Historia

2017-10-22 19:49:26 +00:00
import network
import networkconfig
import time
2017-10-22 19:49:26 +00:00
wlan_sta = network.WLAN(network.STA_IF)
def check_connection():
global wlan_sta
2017-12-11 14:06:47 +00:00
# First check if there already is any connection:
if wlan_sta.isconnected():
2017-12-11 14:12:22 +00:00
return True
connected = False
try:
2017-12-11 14:06:47 +00:00
# ESP connecting to WiFi takes time, wait a bit and try again:
time.sleep(3)
if wlan_sta.isconnected():
2017-12-11 14:12:22 +00:00
return True
2017-10-22 19:49:26 +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
except OSError:
pass
# start web server for connection manager:
if not connected:
connected = networkconfig.start()
2017-10-22 19:49:26 +00:00
return connected
2017-10-22 19:49:26 +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
else:
2017-12-11 14:06:47 +00:00
print("There is something wrong.")