micropython-WiFiManager/main.py

77 wiersze
2.0 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)
2017-10-22 19:49:26 +00:00
def do_connect(ntwrk_ssid, netwrk_pass):
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
if sta_if.isconnected():
return None
print('Trying to connect to %s...' % ntwrk_ssid)
sta_if.connect(ntwrk_ssid, netwrk_pass)
for retry in range(100):
connected = sta_if.isconnected()
if connected:
break
time.sleep(0.1)
print('.', end='')
if connected:
print('\nConnected. Network config: ', sta_if.ifconfig())
else:
print('\nFailed. Not Connected to: ' + ntwrk_ssid)
return connected
2017-10-22 19:49:26 +00:00
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
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 not wlan_sta.isconnected():
2017-12-11 14:06:47 +00:00
# inside passwd file, there is a list of WiFi networks (CSV format)
f = open("passwd.dat")
data = f.readlines()
f.close()
2017-12-11 14:06:47 +00:00
# Search WiFis in range
ssids_found = wlan_sta.scan()
# matching...
for ipass in data:
ssid_list = ipass.strip("\n").split(";")
for i in ssids_found:
if ssid_list[0] in i[0]:
2017-12-11 14:06:47 +00:00
print("OK. WiFi found.")
if do_connect(ssid_list[0], ssid_list[1]):
2017-12-11 14:12:22 +00:00
return True
2017-10-22 19:49:26 +00:00
if not wlan_sta.isconnected():
if networkconfig.start():
2017-12-11 14:12:22 +00:00
return True
else:
2017-12-11 14:12:22 +00:00
return True
2017-10-22 19:49:26 +00:00
except OSError:
2017-12-11 14:06:47 +00:00
# start web server for connection manager:
if networkconfig.start():
2017-12-11 14:12:22 +00:00
return True
2017-10-22 19:49:26 +00:00
2017-12-11 14:12:22 +00:00
return False
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.")