kopia lustrzana https://github.com/tayfunulu/WiFiManager
applied pycharm "reformat file"
fixes: - indentation: tabs -> 4 spaces - spaces around operators - other pep8 issuespull/3/head
rodzic
582cc2acbc
commit
f11fcbf606
137
main.py
137
main.py
|
@ -1,77 +1,76 @@
|
||||||
import network
|
import network
|
||||||
import networkconfig
|
import networkconfig
|
||||||
import time
|
import time
|
||||||
|
|
||||||
wlan_sta = network.WLAN(network.STA_IF)
|
wlan_sta = network.WLAN(network.STA_IF)
|
||||||
|
|
||||||
def do_connect(ntwrk_ssid, netwrk_pass):
|
|
||||||
sta_if = network.WLAN(network.STA_IF)
|
|
||||||
sta_if.active(True)
|
|
||||||
if not sta_if.isconnected():
|
|
||||||
print('try to connect : '+ntwrk_ssid+' network...')
|
|
||||||
sta_if.connect(ntwrk_ssid, netwrk_pass)
|
|
||||||
a=0
|
|
||||||
while not sta_if.isconnected() | (a > 99) :
|
|
||||||
time.sleep(0.1)
|
|
||||||
a+=1
|
|
||||||
print('.', end='')
|
|
||||||
if sta_if.isconnected():
|
|
||||||
print('\nConnected. Network config:', sta_if.ifconfig())
|
|
||||||
return (True)
|
|
||||||
else :
|
|
||||||
print('\nProblem. Not Connected to :'+ntwrk_ssid)
|
|
||||||
return (False)
|
|
||||||
|
|
||||||
def check_connection ():
|
def do_connect(ntwrk_ssid, netwrk_pass):
|
||||||
global wlan_sta
|
sta_if = network.WLAN(network.STA_IF)
|
||||||
# Firstly check is there any connection
|
sta_if.active(True)
|
||||||
if wlan_sta.isconnected():
|
if not sta_if.isconnected():
|
||||||
return (True)
|
print('try to connect : ' + ntwrk_ssid + ' network...')
|
||||||
try:
|
sta_if.connect(ntwrk_ssid, netwrk_pass)
|
||||||
# connection of ESP to WiFi takes time
|
a = 0
|
||||||
# wait 3 sec. and try again.
|
while not sta_if.isconnected() | (a > 99):
|
||||||
time.sleep(3)
|
time.sleep(0.1)
|
||||||
if not wlan_sta.isconnected():
|
a += 1
|
||||||
# inside passwd file. there are list of WiFi network CSV file
|
print('.', end='')
|
||||||
f = open("passwd.dat")
|
if sta_if.isconnected():
|
||||||
data = f.readlines()
|
print('\nConnected. Network config:', sta_if.ifconfig())
|
||||||
f.close()
|
return (True)
|
||||||
# Search WiFi's in range
|
else:
|
||||||
ssids_found = wlan_sta.scan()
|
print('\nProblem. Not Connected to :' + ntwrk_ssid)
|
||||||
|
return (False)
|
||||||
# matching...
|
|
||||||
for ipass in data:
|
|
||||||
ssid_list= ipass.strip("\n").split(";")
|
def check_connection():
|
||||||
|
global wlan_sta
|
||||||
for i in ssids_found:
|
# Firstly check is there any connection
|
||||||
if ssid_list[0] in i[0]:
|
if wlan_sta.isconnected():
|
||||||
print ("OK. WiFi is Founded")
|
return (True)
|
||||||
if do_connect(ssid_list[0],ssid_list[1]):
|
try:
|
||||||
return (True)
|
# connection of ESP to WiFi takes time
|
||||||
|
# wait 3 sec. and try again.
|
||||||
if not wlan_sta.isconnected():
|
time.sleep(3)
|
||||||
if networkconfig.start():
|
if not wlan_sta.isconnected():
|
||||||
return (True)
|
# inside passwd file. there are list of WiFi network CSV file
|
||||||
else:
|
f = open("passwd.dat")
|
||||||
return (True)
|
data = f.readlines()
|
||||||
|
f.close()
|
||||||
except OSError:
|
# Search WiFi's in range
|
||||||
# Web server for connection manager
|
ssids_found = wlan_sta.scan()
|
||||||
if networkconfig.start():
|
|
||||||
return (True)
|
# matching...
|
||||||
|
for ipass in data:
|
||||||
return (False)
|
ssid_list = ipass.strip("\n").split(";")
|
||||||
|
|
||||||
if check_connection ():
|
for i in ssids_found:
|
||||||
|
if ssid_list[0] in i[0]:
|
||||||
# Main Code is here
|
print("OK. WiFi is Founded")
|
||||||
print ("ESP OK")
|
if do_connect(ssid_list[0], ssid_list[1]):
|
||||||
# to import your code;
|
return (True)
|
||||||
# import sample_mqtt.py
|
|
||||||
|
if not wlan_sta.isconnected():
|
||||||
|
if networkconfig.start():
|
||||||
|
return (True)
|
||||||
|
else:
|
||||||
|
return (True)
|
||||||
|
|
||||||
|
except OSError:
|
||||||
|
# Web server for connection manager
|
||||||
|
if networkconfig.start():
|
||||||
|
return (True)
|
||||||
|
|
||||||
|
return (False)
|
||||||
|
|
||||||
|
|
||||||
|
if check_connection():
|
||||||
|
|
||||||
|
# Main Code is here
|
||||||
|
print("ESP OK")
|
||||||
|
# to import your code;
|
||||||
|
# import sample_mqtt.py
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print ("There is something wrong")
|
print("There is something wrong")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
277
networkconfig.py
277
networkconfig.py
|
@ -7,55 +7,58 @@ wlan_ap = network.WLAN(network.AP_IF)
|
||||||
wlan_sta = network.WLAN(network.STA_IF)
|
wlan_sta = network.WLAN(network.STA_IF)
|
||||||
|
|
||||||
# setup for ssid
|
# setup for ssid
|
||||||
ssid_name= "WifiManager"
|
ssid_name = "WifiManager"
|
||||||
ssid_password = "tayfunulu"
|
ssid_password = "tayfunulu"
|
||||||
|
|
||||||
server_socket = None
|
server_socket = None
|
||||||
|
|
||||||
|
|
||||||
def do_connect(ntwrk_ssid, netwrk_pass):
|
def do_connect(ntwrk_ssid, netwrk_pass):
|
||||||
sta_if = network.WLAN(network.STA_IF)
|
sta_if = network.WLAN(network.STA_IF)
|
||||||
sta_if.active(True)
|
sta_if.active(True)
|
||||||
if not sta_if.isconnected():
|
if not sta_if.isconnected():
|
||||||
print('try to connect : '+ntwrk_ssid+' network...')
|
print('try to connect : ' + ntwrk_ssid + ' network...')
|
||||||
sta_if.active(True)
|
sta_if.active(True)
|
||||||
sta_if.connect(ntwrk_ssid, netwrk_pass)
|
sta_if.connect(ntwrk_ssid, netwrk_pass)
|
||||||
a=0
|
a = 0
|
||||||
while not sta_if.isconnected() | (a > 99) :
|
while not sta_if.isconnected() | (a > 99):
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
a+=1
|
a += 1
|
||||||
print('.', end='')
|
print('.', end='')
|
||||||
if sta_if.isconnected():
|
if sta_if.isconnected():
|
||||||
print('\nConnected. Network config:', sta_if.ifconfig())
|
print('\nConnected. Network config:', sta_if.ifconfig())
|
||||||
return (True)
|
return (True)
|
||||||
else :
|
else:
|
||||||
print('\nProblem. Not Connected to :'+ntwrk_ssid)
|
print('\nProblem. Not Connected to :' + ntwrk_ssid)
|
||||||
return (False)
|
return (False)
|
||||||
|
|
||||||
|
|
||||||
def send_response(client, payload, status_code=200):
|
def send_response(client, payload, status_code=200):
|
||||||
client.sendall("HTTP/1.0 {} OK\r\n".format(status_code))
|
client.sendall("HTTP/1.0 {} OK\r\n".format(status_code))
|
||||||
client.sendall("Content-Type: text/html\r\n")
|
client.sendall("Content-Type: text/html\r\n")
|
||||||
client.sendall("Content-Length: {}\r\n".format(len(payload)))
|
client.sendall("Content-Length: {}\r\n".format(len(payload)))
|
||||||
client.sendall("\r\n")
|
client.sendall("\r\n")
|
||||||
|
|
||||||
if len(payload) > 0:
|
if len(payload) > 0:
|
||||||
client.sendall(payload)
|
client.sendall(payload)
|
||||||
|
|
||||||
|
|
||||||
def handle_root(client):
|
def handle_root(client):
|
||||||
global wlan_sta
|
global wlan_sta
|
||||||
response_header = """
|
response_header = """
|
||||||
<html><h1 style="color: #5e9ca0; text-align: center;"><span style="color: #ff0000;">Wi-Fi Client Setup</span></h1>
|
<html><h1 style="color: #5e9ca0; text-align: center;"><span style="color: #ff0000;">Wi-Fi Client Setup</span></h1>
|
||||||
<form action="configure" method="post">
|
<form action="configure" method="post">
|
||||||
<table style="margin-left: auto; margin-right: auto;">
|
<table style="margin-left: auto; margin-right: auto;">
|
||||||
<tbody><tr><td>Wifi Name</td>
|
<tbody><tr><td>Wifi Name</td>
|
||||||
<td style="text-align: center;"><select id="ssid" name="ssid">
|
<td style="text-align: center;"><select id="ssid" name="ssid">
|
||||||
"""
|
"""
|
||||||
wlan_sta.active(True)
|
wlan_sta.active(True)
|
||||||
|
|
||||||
response_variable = ""
|
response_variable = ""
|
||||||
for ssid, *_ in wlan_sta.scan():
|
for ssid, *_ in wlan_sta.scan():
|
||||||
response_variable += '<option value="{0}">{0}</option>'.format(ssid.decode("utf-8"))
|
response_variable += '<option value="{0}">{0}</option>'.format(ssid.decode("utf-8"))
|
||||||
|
|
||||||
response_footer = """
|
response_footer = """
|
||||||
</select></td></tr>
|
</select></td></tr>
|
||||||
<tr><td>Password</td>
|
<tr><td>Password</td>
|
||||||
<td><input name="password" type="password" /></td>
|
<td><input name="password" type="password" /></td>
|
||||||
|
@ -74,130 +77,132 @@ def handle_root(client):
|
||||||
</ul>
|
</ul>
|
||||||
</html>
|
</html>
|
||||||
"""
|
"""
|
||||||
send_response(client, response_header + response_variable + response_footer)
|
send_response(client, response_header + response_variable + response_footer)
|
||||||
|
|
||||||
|
|
||||||
def handle_configure(client, request):
|
def handle_configure(client, request):
|
||||||
match = ure.search("ssid=([^&]*)&password=(.*)", request)
|
match = ure.search("ssid=([^&]*)&password=(.*)", request)
|
||||||
|
|
||||||
if match is None:
|
if match is None:
|
||||||
send_response(client, "Parameters not found", status_code=400)
|
send_response(client, "Parameters not found", status_code=400)
|
||||||
return (False)
|
return (False)
|
||||||
# version 1.9 compatibility
|
# version 1.9 compatibility
|
||||||
try:
|
try:
|
||||||
ssid = match.group(1).decode("utf-8").replace("%3F","?").replace("%21","!")
|
ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace("%21", "!")
|
||||||
password = match.group(2).decode("utf-8").replace("%3F","?").replace("%21","!")
|
password = match.group(2).decode("utf-8").replace("%3F", "?").replace("%21", "!")
|
||||||
except:
|
except:
|
||||||
ssid = match.group(1).replace("%3F","?").replace("%21","!")
|
ssid = match.group(1).replace("%3F", "?").replace("%21", "!")
|
||||||
password = match.group(2).replace("%3F","?").replace("%21","!")
|
password = match.group(2).replace("%3F", "?").replace("%21", "!")
|
||||||
|
|
||||||
|
|
||||||
if len(ssid) == 0:
|
|
||||||
send_response(client, "SSID must be provided", status_code=400)
|
|
||||||
return (False)
|
|
||||||
|
|
||||||
if do_connect(ssid, password):
|
if len(ssid) == 0:
|
||||||
response_footer = """
|
send_response(client, "SSID must be provided", status_code=400)
|
||||||
|
return (False)
|
||||||
|
|
||||||
|
if do_connect(ssid, password):
|
||||||
|
response_footer = """
|
||||||
<html>
|
<html>
|
||||||
<center><br><br>
|
<center><br><br>
|
||||||
<h1 style="color: #5e9ca0; text-align: center;"><span style="color: #ff0000;">:) YES, Wi-Fi Configured to """+ssid+"""</span></h1>
|
<h1 style="color: #5e9ca0; text-align: center;"><span style="color: #ff0000;">:) YES, Wi-Fi Configured to """ + ssid + """</span></h1>
|
||||||
<br><br>"""
|
<br><br>"""
|
||||||
send_response(client, response_footer)
|
send_response(client, response_footer)
|
||||||
try:
|
try:
|
||||||
fo = open("passwd.dat","r")
|
fo = open("passwd.dat", "r")
|
||||||
ex_data = fo.read()
|
ex_data = fo.read()
|
||||||
fo.close()
|
fo.close()
|
||||||
fo = open("passwd.dat","w")
|
fo = open("passwd.dat", "w")
|
||||||
ex_data = ssid+";"+password+"\n"+ex_data
|
ex_data = ssid + ";" + password + "\n" + ex_data
|
||||||
fo.write(ex_data)
|
fo.write(ex_data)
|
||||||
fo.close()
|
fo.close()
|
||||||
except:
|
except:
|
||||||
fo = open("passwd.dat","w")
|
fo = open("passwd.dat", "w")
|
||||||
fo.write(ssid+";"+password+"\n")
|
fo.write(ssid + ";" + password + "\n")
|
||||||
fo.close()
|
fo.close()
|
||||||
|
|
||||||
return (True)
|
return (True)
|
||||||
else:
|
else:
|
||||||
response_footer = """
|
response_footer = """
|
||||||
<html>
|
<html>
|
||||||
<center>
|
<center>
|
||||||
<h1 style="color: #5e9ca0; text-align: center;"><span style="color: #ff0000;">Wi-Fi Not Configured to """+ssid+"""</span></h1>
|
<h1 style="color: #5e9ca0; text-align: center;"><span style="color: #ff0000;">Wi-Fi Not Configured to """ + ssid + """</span></h1>
|
||||||
<br><br>
|
<br><br>
|
||||||
<form>
|
<form>
|
||||||
<input type="button" value="Go back!" onclick="history.back()"></input>
|
<input type="button" value="Go back!" onclick="history.back()"></input>
|
||||||
</form></center></html>
|
</form></center></html>
|
||||||
"""
|
"""
|
||||||
send_response(client, response_footer )
|
send_response(client, response_footer)
|
||||||
return (False)
|
return (False)
|
||||||
|
|
||||||
|
|
||||||
def handle_not_found(client, url):
|
def handle_not_found(client, url):
|
||||||
send_response(client, "Path not found: {}".format(url), status_code=404)
|
send_response(client, "Path not found: {}".format(url), status_code=404)
|
||||||
|
|
||||||
|
|
||||||
def stop():
|
def stop():
|
||||||
global server_socket
|
global server_socket
|
||||||
|
|
||||||
|
if server_socket:
|
||||||
|
server_socket.close()
|
||||||
|
|
||||||
if server_socket:
|
|
||||||
server_socket.close()
|
|
||||||
|
|
||||||
def start(port=80):
|
def start(port=80):
|
||||||
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
|
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
|
||||||
|
|
||||||
global server_socket
|
global server_socket
|
||||||
global wlan_sta
|
global wlan_sta
|
||||||
global wlan_ap
|
global wlan_ap
|
||||||
global ssid_name
|
global ssid_name
|
||||||
global ssid_password
|
global ssid_password
|
||||||
stop()
|
stop()
|
||||||
|
|
||||||
wlan_sta.active(True)
|
|
||||||
wlan_ap.active(True)
|
|
||||||
|
|
||||||
wlan_ap.config(essid=ssid_name,password=ssid_password)
|
|
||||||
|
|
||||||
|
|
||||||
server_socket = socket.socket()
|
|
||||||
server_socket.bind(addr)
|
|
||||||
server_socket.listen(1)
|
|
||||||
|
|
||||||
print('Connect to Wifi ssid :'+ssid_name+' , Default pass: '+ssid_password)
|
|
||||||
print('And connect to esp via your favorite web browser (like 192.168.4.1)')
|
|
||||||
print('listening on', addr)
|
|
||||||
|
|
||||||
while True:
|
|
||||||
|
|
||||||
if wlan_sta.isconnected():
|
|
||||||
client.close
|
|
||||||
return (True)
|
|
||||||
|
|
||||||
client, addr = server_socket.accept()
|
|
||||||
client.settimeout(5.0)
|
|
||||||
|
|
||||||
print('client connected from', addr)
|
|
||||||
|
|
||||||
request = b""
|
wlan_sta.active(True)
|
||||||
try:
|
wlan_ap.active(True)
|
||||||
while not "\r\n\r\n" in request:
|
|
||||||
request += client.recv(512)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
print("Request is: {}".format(request))
|
|
||||||
if "HTTP" not in request:
|
|
||||||
# skip invalid requests
|
|
||||||
client.close()
|
|
||||||
continue
|
|
||||||
|
|
||||||
# version 1.9 compatibility
|
|
||||||
try:
|
|
||||||
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/")
|
|
||||||
except:
|
|
||||||
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).rstrip("/")
|
|
||||||
print("URL is {}".format(url))
|
|
||||||
|
|
||||||
if url == "":
|
wlan_ap.config(essid=ssid_name, password=ssid_password)
|
||||||
handle_root(client)
|
|
||||||
elif url == "configure":
|
server_socket = socket.socket()
|
||||||
handle_configure(client, request)
|
server_socket.bind(addr)
|
||||||
else:
|
server_socket.listen(1)
|
||||||
handle_not_found(client, url)
|
|
||||||
|
print('Connect to Wifi ssid :' + ssid_name + ' , Default pass: ' + ssid_password)
|
||||||
client.close()
|
print('And connect to esp via your favorite web browser (like 192.168.4.1)')
|
||||||
|
print('listening on', addr)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
|
||||||
|
if wlan_sta.isconnected():
|
||||||
|
client.close
|
||||||
|
return (True)
|
||||||
|
|
||||||
|
client, addr = server_socket.accept()
|
||||||
|
client.settimeout(5.0)
|
||||||
|
|
||||||
|
print('client connected from', addr)
|
||||||
|
|
||||||
|
request = b""
|
||||||
|
try:
|
||||||
|
while not "\r\n\r\n" in request:
|
||||||
|
request += client.recv(512)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
print("Request is: {}".format(request))
|
||||||
|
if "HTTP" not in request:
|
||||||
|
# skip invalid requests
|
||||||
|
client.close()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# version 1.9 compatibility
|
||||||
|
try:
|
||||||
|
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/")
|
||||||
|
except:
|
||||||
|
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).rstrip("/")
|
||||||
|
print("URL is {}".format(url))
|
||||||
|
|
||||||
|
if url == "":
|
||||||
|
handle_root(client)
|
||||||
|
elif url == "configure":
|
||||||
|
handle_configure(client, request)
|
||||||
|
else:
|
||||||
|
handle_not_found(client, url)
|
||||||
|
|
||||||
|
client.close()
|
||||||
|
|
Ładowanie…
Reference in New Issue