-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwifi_database.py
92 lines (81 loc) · 2.24 KB
/
wifi_database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import network
import time
active_wifi = None
database_file = "wifi-database"
def get_wifi(essid):
try:
myfile = open(database_file, "r")
except OSError:
return None
line = myfile.readline()
password = None
while line != '':
if line.strip() == essid:
password = myfile.readline().strip()
break
myfile.readline()
line = myfile.readline()
myfile.close()
return password
def add_wifi(essid, password):
try:
myfile = open(database_file, "r+")
except OSError:
myfile = open(database_file, "w+")
line = myfile.readline()
content = None
while line != '':
if line.strip() == essid:
position = myfile.tell()
content = myfile.readlines()
content[0] = password + '\n'
myfile.seek(position)
myfile.writelines(content)
break
myfile.readline()
line = myfile.readline()
if content == None:
myfile.write(essid + '\n' + password + '\n')
myfile.close()
def remove_wifi(essid):
try:
myfile = open(database_file, "r+")
except OSError:
return
line = myfile.readline()
while line != '':
if line.strip() == essid:
position = myfile.tell() - len(line)
myfile.readline()
content = myfile.readlines()
myfile.seek(position)
myfile.writelines(content)
myfile.truncate()
break
myfile.readline()
line = myfile.readline()
if content == None:
myfile.write(essid + '\n' + password + '\n')
myfile.close()
def iter_wifis():
try:
myfile = open(database_file, "r")
except OSError:
return None
line = myfile.readline()
while line != '':
yield (line.strip(), myfile.readline().strip())
line = myfile.readline()
myfile.close()
def connect_and_add_wifi(essid, password):
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect(essid, password)
for i in range(50):
time.sleep_ms(100)
if sta.isconnected():
add_wifi(essid, password)
active_wifi = essid
return True
sta.active(False)
return False