From f11fcbf606e3db8c906ece5d0fadf2287fdfebcf Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 14:38:41 +0100 Subject: [PATCH 01/23] applied pycharm "reformat file" fixes: - indentation: tabs -> 4 spaces - spaces around operators - other pep8 issues --- main.py | 137 ++++++++++++----------- networkconfig.py | 277 ++++++++++++++++++++++++----------------------- 2 files changed, 209 insertions(+), 205 deletions(-) diff --git a/main.py b/main.py index ff0711f..9181aa8 100644 --- a/main.py +++ b/main.py @@ -1,77 +1,76 @@ import network import networkconfig import time + 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 (): - global wlan_sta - # Firstly check is there any connection - if wlan_sta.isconnected(): - return (True) - try: - # connection of ESP to WiFi takes time - # wait 3 sec. and try again. - time.sleep(3) - if not wlan_sta.isconnected(): - # inside passwd file. there are list of WiFi network CSV file - f = open("passwd.dat") - data = f.readlines() - f.close() - # Search WiFi's 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]: - print ("OK. WiFi is Founded") - if do_connect(ssid_list[0],ssid_list[1]): - return (True) - - 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 +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(): + global wlan_sta + # Firstly check is there any connection + if wlan_sta.isconnected(): + return (True) + try: + # connection of ESP to WiFi takes time + # wait 3 sec. and try again. + time.sleep(3) + if not wlan_sta.isconnected(): + # inside passwd file. there are list of WiFi network CSV file + f = open("passwd.dat") + data = f.readlines() + f.close() + # Search WiFi's 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]: + print("OK. WiFi is Founded") + if do_connect(ssid_list[0], ssid_list[1]): + return (True) + + 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: - print ("There is something wrong") - - - - - + print("There is something wrong") diff --git a/networkconfig.py b/networkconfig.py index 411d577..34738f2 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -7,55 +7,58 @@ wlan_ap = network.WLAN(network.AP_IF) wlan_sta = network.WLAN(network.STA_IF) # setup for ssid -ssid_name= "WifiManager" +ssid_name = "WifiManager" ssid_password = "tayfunulu" server_socket = None + 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.active(True) - 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) + 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.active(True) + 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 send_response(client, payload, status_code=200): - client.sendall("HTTP/1.0 {} OK\r\n".format(status_code)) - client.sendall("Content-Type: text/html\r\n") - client.sendall("Content-Length: {}\r\n".format(len(payload))) - client.sendall("\r\n") - - if len(payload) > 0: - client.sendall(payload) + client.sendall("HTTP/1.0 {} OK\r\n".format(status_code)) + client.sendall("Content-Type: text/html\r\n") + client.sendall("Content-Length: {}\r\n".format(len(payload))) + client.sendall("\r\n") + + if len(payload) > 0: + client.sendall(payload) + def handle_root(client): - global wlan_sta - response_header = """ + global wlan_sta + response_header = """

Wi-Fi Client Setup

@@ -74,130 +77,132 @@ def handle_root(client): """ - send_response(client, response_header + response_variable + response_footer) + send_response(client, response_header + response_variable + response_footer) + def handle_configure(client, request): - match = ure.search("ssid=([^&]*)&password=(.*)", request) + match = ure.search("ssid=([^&]*)&password=(.*)", request) - if match is None: - send_response(client, "Parameters not found", status_code=400) - return (False) - # version 1.9 compatibility - try: - ssid = match.group(1).decode("utf-8").replace("%3F","?").replace("%21","!") - password = match.group(2).decode("utf-8").replace("%3F","?").replace("%21","!") - except: - ssid = match.group(1).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 match is None: + send_response(client, "Parameters not found", status_code=400) + return (False) + # version 1.9 compatibility + try: + ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace("%21", "!") + password = match.group(2).decode("utf-8").replace("%3F", "?").replace("%21", "!") + except: + ssid = match.group(1).replace("%3F", "?").replace("%21", "!") + password = match.group(2).replace("%3F", "?").replace("%21", "!") - if do_connect(ssid, password): - response_footer = """ + if len(ssid) == 0: + send_response(client, "SSID must be provided", status_code=400) + return (False) + + if do_connect(ssid, password): + response_footer = """


-

:) YES, Wi-Fi Configured to """+ssid+"""

+

:) YES, Wi-Fi Configured to """ + ssid + """



""" - send_response(client, response_footer) - try: - fo = open("passwd.dat","r") - ex_data = fo.read() - fo.close() - fo = open("passwd.dat","w") - ex_data = ssid+";"+password+"\n"+ex_data - fo.write(ex_data) - fo.close() - except: - fo = open("passwd.dat","w") - fo.write(ssid+";"+password+"\n") - fo.close() - - return (True) - else: - response_footer = """ + send_response(client, response_footer) + try: + fo = open("passwd.dat", "r") + ex_data = fo.read() + fo.close() + fo = open("passwd.dat", "w") + ex_data = ssid + ";" + password + "\n" + ex_data + fo.write(ex_data) + fo.close() + except: + fo = open("passwd.dat", "w") + fo.write(ssid + ";" + password + "\n") + fo.close() + + return (True) + else: + response_footer = """
-

Wi-Fi Not Configured to """+ssid+"""

+

Wi-Fi Not Configured to """ + ssid + """



""" - send_response(client, response_footer ) - return (False) + send_response(client, response_footer) + return (False) + 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(): - global server_socket + global server_socket + + if server_socket: + server_socket.close() - if server_socket: - server_socket.close() 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 wlan_sta - global wlan_ap - global ssid_name - global ssid_password - 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) + global server_socket + global wlan_sta + global wlan_ap + global ssid_name + global ssid_password + stop() - 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)) + wlan_sta.active(True) + wlan_ap.active(True) - if url == "": - handle_root(client) - elif url == "configure": - handle_configure(client, request) - else: - handle_not_found(client, url) - - client.close() + 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"" + 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() From d1bae019af223764e2278d661ac825f1dd0e71dd Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 14:43:23 +0100 Subject: [PATCH 02/23] add a .gitignore only entry for now is to exclude pycharm files. --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9f11b75 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea/ From b23e52ec530b2e67d99313072e3d77d25ff02277 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 14:47:33 +0100 Subject: [PATCH 03/23] fix README spacing / grammar --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 247ed11..011ddd5 100644 --- a/README.md +++ b/README.md @@ -5,22 +5,22 @@ Tested : 1.8 and 1.9.2 (updated) Description : WiFi manager for ESP8266 - ESP12 for micropython -Main Features:   +Main Features: - Web based connection manager - Save wifi password in passwd.dat (csv format) - Easy to apply -Usage : +Usage: -Upload main.py and networkconfig.py on esp -Write your code on main.py or import from main.py +Upload main.py and networkconfig.py to ESP. +Write your code into main.py or import it from main.py. -Logic: -1. step : Check passwd.dat file and try saved passwords -2. step : To publish web page to config new wifi -3. step : Saving password on passwd.dat file. -4. step : Run user code +Logic: +1. step: Check passwd.dat file and try saved networks/passwords. +2. step: Publish web page to configure new wifi. +3. step: Save network/password to passwd.dat file. +4. step: Run user code. ![alt text](https://github.com/tayfunulu/WiFiManager/blob/master/WiFi_Manager.png) From 1ea05254a419a59b04e019aeb4fe59a22bb70857 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 15:06:47 +0100 Subject: [PATCH 04/23] code: fix wording / grammar --- main.py | 25 ++++++++++++------------- networkconfig.py | 15 +++++++-------- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/main.py b/main.py index 9181aa8..6c359ac 100644 --- a/main.py +++ b/main.py @@ -9,7 +9,7 @@ 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...') + print('Trying to connect to %s...' % ntwrk_ssid) sta_if.connect(ntwrk_ssid, netwrk_pass) a = 0 while not sta_if.isconnected() | (a > 99): @@ -17,28 +17,27 @@ def do_connect(ntwrk_ssid, netwrk_pass): a += 1 print('.', end='') if sta_if.isconnected(): - print('\nConnected. Network config:', sta_if.ifconfig()) + print('\nConnected. Network config: ', sta_if.ifconfig()) return (True) else: - print('\nProblem. Not Connected to :' + ntwrk_ssid) + print('\nFailed. Not Connected to: ' + ntwrk_ssid) return (False) def check_connection(): global wlan_sta - # Firstly check is there any connection + # First check if there already is any connection: if wlan_sta.isconnected(): return (True) try: - # connection of ESP to WiFi takes time - # wait 3 sec. and try again. + # ESP connecting to WiFi takes time, wait a bit and try again: time.sleep(3) if not wlan_sta.isconnected(): - # inside passwd file. there are list of WiFi network CSV file + # inside passwd file, there is a list of WiFi networks (CSV format) f = open("passwd.dat") data = f.readlines() f.close() - # Search WiFi's in range + # Search WiFis in range ssids_found = wlan_sta.scan() # matching... @@ -47,7 +46,7 @@ def check_connection(): for i in ssids_found: if ssid_list[0] in i[0]: - print("OK. WiFi is Founded") + print("OK. WiFi found.") if do_connect(ssid_list[0], ssid_list[1]): return (True) @@ -58,7 +57,7 @@ def check_connection(): return (True) except OSError: - # Web server for connection manager + # start web server for connection manager: if networkconfig.start(): return (True) @@ -69,8 +68,8 @@ if check_connection(): # Main Code is here print("ESP OK") -# to import your code; -# import sample_mqtt.py + # to import your code; + # import sample_mqtt.py else: - print("There is something wrong") + print("There is something wrong.") diff --git a/networkconfig.py b/networkconfig.py index 34738f2..4b75a33 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -6,7 +6,7 @@ import time wlan_ap = network.WLAN(network.AP_IF) wlan_sta = network.WLAN(network.STA_IF) -# setup for ssid +# SSID/Password for setup ssid_name = "WifiManager" ssid_password = "tayfunulu" @@ -17,7 +17,7 @@ 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...') + print('Trying to connect to %s...' % ntwrk_ssid) sta_if.active(True) sta_if.connect(ntwrk_ssid, netwrk_pass) a = 0 @@ -26,10 +26,10 @@ def do_connect(ntwrk_ssid, netwrk_pass): a += 1 print('.', end='') if sta_if.isconnected(): - print('\nConnected. Network config:', sta_if.ifconfig()) + print('\nConnected. Network config: ', sta_if.ifconfig()) return (True) else: - print('\nProblem. Not Connected to :' + ntwrk_ssid) + print('\nFailed. Not Connected to: ' + ntwrk_ssid) return (False) @@ -117,7 +117,6 @@ def handle_configure(client, request): fo = open("passwd.dat", "w") fo.write(ssid + ";" + password + "\n") fo.close() - return (True) else: response_footer = """ @@ -163,9 +162,9 @@ def start(port=80): 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) + print('Connect to WiFi ssid ' + ssid_name + ', default password: ' + ssid_password) + print('and access the ESP via your favorite web browser at 192.168.4.1.') + print('Listening on:', addr) while True: From 72292a72ab3a72134405ee21ab4ebd8740250560 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 15:12:22 +0100 Subject: [PATCH 05/23] some simple python syntax fixes --- main.py | 16 ++++++++-------- networkconfig.py | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/main.py b/main.py index 6c359ac..d44cb3e 100644 --- a/main.py +++ b/main.py @@ -18,17 +18,17 @@ def do_connect(ntwrk_ssid, netwrk_pass): print('.', end='') if sta_if.isconnected(): print('\nConnected. Network config: ', sta_if.ifconfig()) - return (True) + return True else: print('\nFailed. Not Connected to: ' + ntwrk_ssid) - return (False) + return False def check_connection(): global wlan_sta # First check if there already is any connection: if wlan_sta.isconnected(): - return (True) + return True try: # ESP connecting to WiFi takes time, wait a bit and try again: time.sleep(3) @@ -48,20 +48,20 @@ def check_connection(): if ssid_list[0] in i[0]: print("OK. WiFi found.") if do_connect(ssid_list[0], ssid_list[1]): - return (True) + return True if not wlan_sta.isconnected(): if networkconfig.start(): - return (True) + return True else: - return (True) + return True except OSError: # start web server for connection manager: if networkconfig.start(): - return (True) + return True - return (False) + return False if check_connection(): diff --git a/networkconfig.py b/networkconfig.py index 4b75a33..4e2c90e 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -27,10 +27,10 @@ def do_connect(ntwrk_ssid, netwrk_pass): print('.', end='') if sta_if.isconnected(): print('\nConnected. Network config: ', sta_if.ifconfig()) - return (True) + return True else: print('\nFailed. Not Connected to: ' + ntwrk_ssid) - return (False) + return False def send_response(client, payload, status_code=200): @@ -85,7 +85,7 @@ def handle_configure(client, request): if match is None: send_response(client, "Parameters not found", status_code=400) - return (False) + return False # version 1.9 compatibility try: ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace("%21", "!") @@ -96,7 +96,7 @@ def handle_configure(client, request): if len(ssid) == 0: send_response(client, "SSID must be provided", status_code=400) - return (False) + return False if do_connect(ssid, password): response_footer = """ @@ -117,7 +117,7 @@ def handle_configure(client, request): fo = open("passwd.dat", "w") fo.write(ssid + ";" + password + "\n") fo.close() - return (True) + return True else: response_footer = """ @@ -129,7 +129,7 @@ def handle_configure(client, request):
""" send_response(client, response_footer) - return (False) + return False def handle_not_found(client, url): @@ -170,7 +170,7 @@ def start(port=80): if wlan_sta.isconnected(): client.close - return (True) + return True client, addr = server_socket.accept() client.settimeout(5.0) @@ -179,7 +179,7 @@ def start(port=80): request = b"" try: - while not "\r\n\r\n" in request: + while "\r\n\r\n" not in request: request += client.recv(512) except OSError: pass From 28e2aa500165116fdf1504269dbdcc856841cbc5 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 15:18:39 +0100 Subject: [PATCH 06/23] make connection wait loop more readable | is the bitwise or operator, you rather want a logical operator here. --- main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index d44cb3e..d2665bb 100644 --- a/main.py +++ b/main.py @@ -11,10 +11,10 @@ def do_connect(ntwrk_ssid, netwrk_pass): if not sta_if.isconnected(): print('Trying to connect to %s...' % ntwrk_ssid) sta_if.connect(ntwrk_ssid, netwrk_pass) - a = 0 - while not sta_if.isconnected() | (a > 99): + retry = 0 + while not sta_if.isconnected() and retry < 100: time.sleep(0.1) - a += 1 + retry += 1 print('.', end='') if sta_if.isconnected(): print('\nConnected. Network config: ', sta_if.ifconfig()) From e4cda8a95ab3397b97bf11acc01d6f0bb45243f2 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 15:28:31 +0100 Subject: [PATCH 07/23] simplify do_connect kept the behaviour it had before: returns truish/falsish if it has/has not connected to given network. returns None if it already was connected. --- main.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index d2665bb..3415b3b 100644 --- a/main.py +++ b/main.py @@ -8,20 +8,21 @@ 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('Trying to connect to %s...' % ntwrk_ssid) - sta_if.connect(ntwrk_ssid, netwrk_pass) - retry = 0 - while not sta_if.isconnected() and retry < 100: - time.sleep(0.1) - retry += 1 - print('.', end='') - if sta_if.isconnected(): - print('\nConnected. Network config: ', sta_if.ifconfig()) - return True - else: - print('\nFailed. Not Connected to: ' + ntwrk_ssid) - return False + 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 def check_connection(): From 23af7385b0f11c51f59237496ef3ad1c449f2e4c Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 15:34:53 +0100 Subject: [PATCH 08/23] use with-statement for open() --- main.py | 5 ++--- networkconfig.py | 15 ++++++--------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/main.py b/main.py index 3415b3b..e8f4cc6 100644 --- a/main.py +++ b/main.py @@ -35,9 +35,8 @@ def check_connection(): time.sleep(3) if not wlan_sta.isconnected(): # inside passwd file, there is a list of WiFi networks (CSV format) - f = open("passwd.dat") - data = f.readlines() - f.close() + with open("passwd.dat") as f: + data = f.readlines() # Search WiFis in range ssids_found = wlan_sta.scan() diff --git a/networkconfig.py b/networkconfig.py index 4e2c90e..f70ff06 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -106,17 +106,14 @@ def handle_configure(client, request):

""" send_response(client, response_footer) try: - fo = open("passwd.dat", "r") - ex_data = fo.read() - fo.close() - fo = open("passwd.dat", "w") + with open("passwd.dat", "r") as fo: + ex_data = fo.read() ex_data = ssid + ";" + password + "\n" + ex_data - fo.write(ex_data) - fo.close() + with open("passwd.dat", "w") as fo: + fo.write(ex_data) except: - fo = open("passwd.dat", "w") - fo.write(ssid + ";" + password + "\n") - fo.close() + with open("passwd.dat", "w") as fo: + fo.write(ssid + ";" + password + "\n") return True else: response_footer = """ From 278144a911cf07a3a9abd79adf304a21dce915d1 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 15:43:35 +0100 Subject: [PATCH 09/23] cleanup extending passwd.dat --- networkconfig.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index f70ff06..a8aae76 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -106,14 +106,13 @@ def handle_configure(client, request):

""" send_response(client, response_footer) try: - with open("passwd.dat", "r") as fo: - ex_data = fo.read() - ex_data = ssid + ";" + password + "\n" + ex_data - with open("passwd.dat", "w") as fo: - fo.write(ex_data) + with open("passwd.dat", "r") as f: + ex_data = f.read() except: - with open("passwd.dat", "w") as fo: - fo.write(ssid + ";" + password + "\n") + ex_data = "" + ex_data = "%s;%s\n" % (ssid, password) + ex_data + with open("passwd.dat", "w") as f: + f.write(ex_data) return True else: response_footer = """ From 7d479222c2c20bd3710aa91dc945162bb97ab68c Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 16:01:04 +0100 Subject: [PATCH 10/23] simplify/clean up names --- main.py | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/main.py b/main.py index e8f4cc6..9aca53b 100644 --- a/main.py +++ b/main.py @@ -5,13 +5,13 @@ import time wlan_sta = network.WLAN(network.STA_IF) -def do_connect(ntwrk_ssid, netwrk_pass): +def do_connect(ssid, password): 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) + print('Trying to connect to %s...' % ssid) + sta_if.connect(ssid, password) for retry in range(100): connected = sta_if.isconnected() if connected: @@ -21,7 +21,7 @@ def do_connect(ntwrk_ssid, netwrk_pass): if connected: print('\nConnected. Network config: ', sta_if.ifconfig()) else: - print('\nFailed. Not Connected to: ' + ntwrk_ssid) + print('\nFailed. Not Connected to: ' + ssid) return connected @@ -36,18 +36,17 @@ def check_connection(): if not wlan_sta.isconnected(): # inside passwd file, there is a list of WiFi networks (CSV format) with open("passwd.dat") as f: - data = f.readlines() + lines = f.readlines() # 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]: + for line in lines: + ssid, password = line.strip("\n").split(";") + for ssid_found in ssids_found: + if ssid in ssid_found[0]: print("OK. WiFi found.") - if do_connect(ssid_list[0], ssid_list[1]): + if do_connect(ssid, password): return True if not wlan_sta.isconnected(): From 491ad25172b5d81e45cac6268844e888bc3bb452 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 19:52:14 +0100 Subject: [PATCH 11/23] fixed web UI text (grammar, typos) --- networkconfig.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index a8aae76..45edc0c 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -68,12 +68,12 @@ def handle_root(client):

 


-
!!! your ssid and password information will save "passwd.dat" file inside of your esp module to use next time... be careful for security !!!
+
Your ssid and password information will be saved into the "passwd.dat" file in your ESP module for future usage. Be careful about security!

Some useful infos:

    -
  • Wi-Fi Client for Micropython GitHub from cpopp
  • -
  • My github adress tayfunulu
  • +
  • Wi-Fi Client for MicroPython GitHub from cpopp
  • +
  • My github address tayfunulu
""" @@ -102,7 +102,7 @@ def handle_configure(client, request): response_footer = """


-

:) YES, Wi-Fi Configured to """ + ssid + """

+

ESP successfully connected to Wi-Fi network """ + ssid + """.



""" send_response(client, response_footer) try: From a1b6ae585510381df1a3a00d06004fc3ec308634 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 20:28:21 +0100 Subject: [PATCH 12/23] html source: formatted, fixed some issues --- networkconfig.py | 124 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 84 insertions(+), 40 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index 45edc0c..03b64a9 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -45,38 +45,68 @@ def send_response(client, payload, status_code=200): def handle_root(client): global wlan_sta - response_header = """ -

Wi-Fi Client Setup

-
-
Wifi Name
Password
- - + + + + + + +
Wifi Name + + + + - - - -
+ WiFi Name + +
Password
-

- -

 

-
-
Your ssid and password information will be saved into the "passwd.dat" file in your ESP module for future usage. Be careful about security!
-
-

Some useful infos:

-
    -
  • Wi-Fi Client for MicroPython GitHub from cpopp
  • -
  • My github address tayfunulu
  • -
- - """ + response_footer = """\ + +
Password
+

+ +

+ +

 

+
+
+ + Your ssid and password information will be saved into the + "passwd.dat" file in your ESP module for future usage. + Be careful about security! + +
+
+

+ Some useful infos: +

+ + + """ send_response(client, response_header + response_variable + response_footer) @@ -99,11 +129,19 @@ def handle_configure(client, request): return False if do_connect(ssid, password): - response_footer = """ - -


-

ESP successfully connected to Wi-Fi network """ + ssid + """.

-

""" + response_footer = """\ + +
+

+

+ + ESP successfully connected to WiFi network %(ssid)s. + +

+

+
+ + """ % dict(ssid=ssid) send_response(client, response_footer) try: with open("passwd.dat", "r") as f: @@ -115,15 +153,21 @@ def handle_configure(client, request): f.write(ex_data) return True else: - response_footer = """ - -
-

Wi-Fi Not Configured to """ + ssid + """

-

-
- -
- """ + response_footer = """\ + +
+

+ + ESP could not connect to WiFi network %(ssid)s. + +

+

+
+ +
+
+ + """ % dict(ssid=ssid) send_response(client, response_footer) return False From e20694340f065cf83d558391ae5f3a62a65b4476 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 21:03:54 +0100 Subject: [PATCH 13/23] network selection: sort ssids, use radiobutton just one click on the right button, not 2 clicks as for dropdown menu. --- networkconfig.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index 03b64a9..f2b8bf6 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -45,6 +45,9 @@ def send_response(client, payload, status_code=200): def handle_root(client): global wlan_sta + wlan_sta.active(True) + ssids = sorted(ssid.decode('utf-8') for ssid, *_ in wlan_sta.scan()) + response_header = """\

@@ -55,25 +58,22 @@ def handle_root(client):
- - - + + """.format(ssid)) + response_variable = "\n".join(response_variable) + + response_footer = """\ - + From cbf3c8f57b8a40c907db8d6279469c49380b36d0 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 21:13:01 +0100 Subject: [PATCH 14/23] cleanup response assembly --- networkconfig.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index f2b8bf6..1e702f4 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -48,7 +48,8 @@ def handle_root(client): wlan_sta.active(True) ssids = sorted(ssid.decode('utf-8') for ssid, *_ in wlan_sta.scan()) - response_header = """\ + response = [] + response.append("""\

@@ -58,20 +59,18 @@ def handle_root(client):

- WiFi Name - - + response_variable = [] + for ssid in ssids: + response_variable.append("""\ +
+ {0}
PasswordPassword:
- """ + """) - response_variable = [] for ssid in ssids: - response_variable.append("""\ + response.append("""\ """.format(ssid)) - response_variable = "\n".join(response_variable) - response_footer = """\ + response.append("""\ @@ -106,8 +105,8 @@ def handle_root(client): - """ - send_response(client, response_header + response_variable + response_footer) + """) + send_response(client, "\n".join(response)) def handle_configure(client, request): @@ -129,7 +128,7 @@ def handle_configure(client, request): return False if do_connect(ssid, password): - response_footer = """\ + response = """\


@@ -142,7 +141,7 @@ def handle_configure(client, request):
""" % dict(ssid=ssid) - send_response(client, response_footer) + send_response(client, response) try: with open("passwd.dat", "r") as f: ex_data = f.read() @@ -153,7 +152,7 @@ def handle_configure(client, request): f.write(ex_data) return True else: - response_footer = """\ + response = """\

@@ -167,8 +166,8 @@ def handle_configure(client, request):

- """ % dict(ssid=ssid) - send_response(client, response_footer) + """ % dict(ssid=ssid) + send_response(client, response) return False From f991513ea6829633730b3150094446e9d3e37538 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Mon, 11 Dec 2017 22:11:44 +0100 Subject: [PATCH 15/23] deduplicate do_connect() --- main.py | 22 +--------------------- networkconfig.py | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 37 deletions(-) diff --git a/main.py b/main.py index 9aca53b..8a97cd0 100644 --- a/main.py +++ b/main.py @@ -5,26 +5,6 @@ import time wlan_sta = network.WLAN(network.STA_IF) -def do_connect(ssid, password): - sta_if = network.WLAN(network.STA_IF) - sta_if.active(True) - if sta_if.isconnected(): - return None - print('Trying to connect to %s...' % ssid) - sta_if.connect(ssid, password) - 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: ' + ssid) - return connected - - def check_connection(): global wlan_sta # First check if there already is any connection: @@ -46,7 +26,7 @@ def check_connection(): for ssid_found in ssids_found: if ssid in ssid_found[0]: print("OK. WiFi found.") - if do_connect(ssid, password): + if networkconfig.do_connect(ssid, password): return True if not wlan_sta.isconnected(): diff --git a/networkconfig.py b/networkconfig.py index 1e702f4..65dfbdc 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -13,24 +13,24 @@ ssid_password = "tayfunulu" server_socket = None -def do_connect(ntwrk_ssid, netwrk_pass): +def do_connect(ssid, password): sta_if = network.WLAN(network.STA_IF) sta_if.active(True) - if not sta_if.isconnected(): - print('Trying to connect to %s...' % ntwrk_ssid) - sta_if.active(True) - 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('\nFailed. Not Connected to: ' + ntwrk_ssid) - return False + if sta_if.isconnected(): + return None + print('Trying to connect to %s...' % ssid) + sta_if.connect(ssid, password) + 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: ' + ssid) + return connected def send_response(client, payload, status_code=200): From 8674d7c4da93a84bd49da9d066a0321368794a0e Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 00:34:09 +0100 Subject: [PATCH 16/23] refactor main code, separate profile code also: - go through available wifi networks in sorted order, by rssi - differentiate open from encrypted networks - some debug prints --- main.py | 55 +++++++++++++++++++++++++++--------------------- networkconfig.py | 37 ++++++++++++++++++++++++-------- 2 files changed, 59 insertions(+), 33 deletions(-) diff --git a/main.py b/main.py index 8a97cd0..5074b0d 100644 --- a/main.py +++ b/main.py @@ -10,37 +10,44 @@ def check_connection(): # First check if there already is any connection: if wlan_sta.isconnected(): return True + + connected = False try: # ESP connecting to WiFi takes time, wait a bit and try again: time.sleep(3) - if not wlan_sta.isconnected(): - # inside passwd file, there is a list of WiFi networks (CSV format) - with open("passwd.dat") as f: - lines = f.readlines() - # Search WiFis in range - ssids_found = wlan_sta.scan() - - # matching... - for line in lines: - ssid, password = line.strip("\n").split(";") - for ssid_found in ssids_found: - if ssid in ssid_found[0]: - print("OK. WiFi found.") - if networkconfig.do_connect(ssid, password): - return True - - if not wlan_sta.isconnected(): - if networkconfig.start(): - return True - else: + if wlan_sta.isconnected(): return True + # 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: - # start web server for connection manager: - if networkconfig.start(): - return True + pass - return False + # start web server for connection manager: + if not connected: + connected = networkconfig.start() + + return connected if check_connection(): diff --git a/networkconfig.py b/networkconfig.py index 65dfbdc..816a0cb 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -12,6 +12,27 @@ ssid_password = "tayfunulu" server_socket = None +# list of WiFi networks (CSV format: ssid,password) +NETWORK_PROFILES = 'passwd.dat' + + +def read_profiles(): + with open(NETWORK_PROFILES) as f: + lines = f.readlines() + profiles = {} + for line in lines: + ssid, password = line.strip("\n").split(";") + profiles[ssid] = password + return profiles + + +def write_profiles(profiles): + lines = [] + for ssid, password in profiles.items(): + lines.append("%s;%s\n" % (ssid, password)) + with open(NETWORK_PROFILES, "w") as f: + f.write(''.join(lines)) + def do_connect(ssid, password): sta_if = network.WLAN(network.STA_IF) @@ -86,7 +107,7 @@ def handle_root(client):
Your ssid and password information will be saved into the - "passwd.dat" file in your ESP module for future usage. + "%(filename)s" file in your ESP module for future usage. Be careful about security!
@@ -105,7 +126,7 @@ def handle_root(client): - """) + """ % dict(filename=NETWORK_PROFILES)) send_response(client, "\n".join(response)) @@ -143,13 +164,11 @@ def handle_configure(client, request): """ % dict(ssid=ssid) send_response(client, response) try: - with open("passwd.dat", "r") as f: - ex_data = f.read() - except: - ex_data = "" - ex_data = "%s;%s\n" % (ssid, password) + ex_data - with open("passwd.dat", "w") as f: - f.write(ex_data) + profiles = read_profiles() + except OSError: + profiles = {} + profiles[ssid] = password + write_profiles(profiles) return True else: response = """\ From 6b7e885bb09d341a9bebca585b651a73e59e4fba Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 00:43:01 +0100 Subject: [PATCH 17/23] use WPA2 for the AP, really requires a password now --- networkconfig.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/networkconfig.py b/networkconfig.py index 816a0cb..f8e1a08 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -214,7 +214,7 @@ def start(port=80): wlan_sta.active(True) wlan_ap.active(True) - wlan_ap.config(essid=ssid_name, password=ssid_password) + wlan_ap.config(essid=ssid_name, password=ssid_password, authmode=3) # WPA2 server_socket = socket.socket() server_socket.bind(addr) From ff4ad2524a382863947b2d0ff8a8a46855c567b1 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 01:06:12 +0100 Subject: [PATCH 18/23] cleanup server socket and client close --- networkconfig.py | 58 ++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index f8e1a08..2f7dccb 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -199,6 +199,7 @@ def stop(): if server_socket: server_socket.close() + server_socket = None def start(port=80): @@ -227,39 +228,38 @@ def start(port=80): 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 "\r\n\r\n" not in request: - request += client.recv(512) - except OSError: - pass + client.settimeout(5.0) - print("Request is: {}".format(request)) - if "HTTP" not in request: - # skip invalid requests + request = b"" + try: + while "\r\n\r\n" not in request: + request += client.recv(512) + except OSError: + pass + + print("Request is: {}".format(request)) + if "HTTP" not in request: + # skip invalid requests + 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) + + finally: 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() From 3ae68033e6aea089361a00e8925167f127110fe9 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 04:07:20 +0100 Subject: [PATCH 19/23] move most code to networkconfig module, simplify main also: only initialize 2 WLAN instances (one AP, one STA) --- main.py | 63 +++++--------------------------------------- networkconfig.py | 68 ++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 64 insertions(+), 67 deletions(-) diff --git a/main.py b/main.py index 5074b0d..313472c 100644 --- a/main.py +++ b/main.py @@ -1,61 +1,12 @@ -import network import networkconfig -import time - -wlan_sta = network.WLAN(network.STA_IF) -def check_connection(): - global wlan_sta - # First check if there already is any connection: - if wlan_sta.isconnected(): - return True - - connected = False - try: - # ESP connecting to WiFi takes time, wait a bit and try again: - time.sleep(3) - if wlan_sta.isconnected(): - return True - - # 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() - - return connected +wlan = networkconfig.check_connection() +if wlan is None: + print("Could not initialize the network connection.") + while True: + pass # you shall not pass :D -if check_connection(): - - # Main Code is here - print("ESP OK") - # to import your code; - # import sample_mqtt.py - -else: - print("There is something wrong.") +# Main Code goes here, wlan is a working network.WLAN(STA_IF) instance. +print("ESP OK") diff --git a/networkconfig.py b/networkconfig.py index 2f7dccb..16c3033 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -3,18 +3,64 @@ import socket import ure import time -wlan_ap = network.WLAN(network.AP_IF) -wlan_sta = network.WLAN(network.STA_IF) - # SSID/Password for setup ssid_name = "WifiManager" ssid_password = "tayfunulu" -server_socket = None - # list of WiFi networks (CSV format: ssid,password) NETWORK_PROFILES = 'passwd.dat' +wlan_ap = network.WLAN(network.AP_IF) +wlan_sta = network.WLAN(network.STA_IF) + +server_socket = None + + +def check_connection(): + global wlan_sta + + # 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 + 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 = do_connect(ssid, password) + else: + print("skipping unknown encrypted network") + else: # open + connected = do_connect(ssid, None) + if connected: + break + + except OSError: + pass + + # start web server for connection manager: + if not connected: + connected = start() + + return wlan_sta if connected else None + def read_profiles(): with open(NETWORK_PROFILES) as f: @@ -35,20 +81,20 @@ def write_profiles(profiles): def do_connect(ssid, password): - sta_if = network.WLAN(network.STA_IF) - sta_if.active(True) - if sta_if.isconnected(): + global wlan_sta + wlan_sta.active(True) + if wlan_sta.isconnected(): return None print('Trying to connect to %s...' % ssid) - sta_if.connect(ssid, password) + wlan_sta.connect(ssid, password) for retry in range(100): - connected = sta_if.isconnected() + connected = wlan_sta.isconnected() if connected: break time.sleep(0.1) print('.', end='') if connected: - print('\nConnected. Network config: ', sta_if.ifconfig()) + print('\nConnected. Network config: ', wlan_sta.ifconfig()) else: print('\nFailed. Not Connected to: ' + ssid) return connected From b68f6560b97498a23a706f398596f39866ff5c82 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 02:05:11 +0100 Subject: [PATCH 20/23] rename check_connection -> get_connection --- main.py | 2 +- networkconfig.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 313472c..819aa15 100644 --- a/main.py +++ b/main.py @@ -1,7 +1,7 @@ import networkconfig -wlan = networkconfig.check_connection() +wlan = networkconfig.get_connection() if wlan is None: print("Could not initialize the network connection.") while True: diff --git a/networkconfig.py b/networkconfig.py index 16c3033..22af648 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -16,7 +16,8 @@ wlan_sta = network.WLAN(network.STA_IF) server_socket = None -def check_connection(): +def get_connection(): + """return a working WLAN(STA_IF) instance or None""" global wlan_sta # First check if there already is any connection: From b41777f64ddbbb4ef61bdffa243b04b0ff82e2dc Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 02:18:52 +0100 Subject: [PATCH 21/23] wifi profiles: remove bad comment, rename file to wifi.dat passwd.dat is too unspecific, could be passwords of whatever. also, we maybe could put more in there, not just ssid and password, but more data about the known wifi networks. --- networkconfig.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index 22af648..afe6e8d 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -7,8 +7,7 @@ import time ssid_name = "WifiManager" ssid_password = "tayfunulu" -# list of WiFi networks (CSV format: ssid,password) -NETWORK_PROFILES = 'passwd.dat' +NETWORK_PROFILES = 'wifi.dat' wlan_ap = network.WLAN(network.AP_IF) wlan_sta = network.WLAN(network.STA_IF) From d0b8fadd84583d6310f47e638b3ec514db53e407 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 02:37:11 +0100 Subject: [PATCH 22/23] improve ap related names, remove unneeded "global" --- networkconfig.py | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index afe6e8d..6d97737 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -3,9 +3,9 @@ import socket import ure import time -# SSID/Password for setup -ssid_name = "WifiManager" -ssid_password = "tayfunulu" +ap_ssid = "WifiManager" +ap_password = "tayfunulu" +ap_authmode = 3 # WPA2 NETWORK_PROFILES = 'wifi.dat' @@ -17,7 +17,6 @@ server_socket = None def get_connection(): """return a working WLAN(STA_IF) instance or None""" - global wlan_sta # First check if there already is any connection: if wlan_sta.isconnected(): @@ -81,7 +80,6 @@ def write_profiles(profiles): def do_connect(ssid, password): - global wlan_sta wlan_sta.active(True) if wlan_sta.isconnected(): return None @@ -111,7 +109,6 @@ def send_response(client, payload, status_code=200): def handle_root(client): - global wlan_sta wlan_sta.active(True) ssids = sorted(ssid.decode('utf-8') for ssid, *_ in wlan_sta.scan()) @@ -249,25 +246,22 @@ def stop(): def start(port=80): + global server_socket + addr = socket.getaddrinfo('0.0.0.0', port)[0][-1] - global server_socket - global wlan_sta - global wlan_ap - global ssid_name - global ssid_password stop() wlan_sta.active(True) wlan_ap.active(True) - wlan_ap.config(essid=ssid_name, password=ssid_password, authmode=3) # WPA2 + wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode) server_socket = socket.socket() server_socket.bind(addr) server_socket.listen(1) - print('Connect to WiFi ssid ' + ssid_name + ', default password: ' + ssid_password) + print('Connect to WiFi ssid ' + ap_ssid + ', default password: ' + ap_password) print('and access the ESP via your favorite web browser at 192.168.4.1.') print('Listening on:', addr) From 594570268353f6f5755247b264a1c64a6ff82941 Mon Sep 17 00:00:00 2001 From: Thomas Waldmann Date: Tue, 12 Dec 2017 02:48:03 +0100 Subject: [PATCH 23/23] sta must be active for scanning, print exception --- networkconfig.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/networkconfig.py b/networkconfig.py index 6d97737..93740c7 100644 --- a/networkconfig.py +++ b/networkconfig.py @@ -33,6 +33,7 @@ def get_connection(): 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"} @@ -51,8 +52,8 @@ def get_connection(): if connected: break - except OSError: - pass + except OSError as e: + print("exception", str(e)) # start web server for connection manager: if not connected:
{0}
Password: