-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwifiSetup.py
299 lines (250 loc) · 11.1 KB
/
wifiSetup.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import os
import subprocess
import socket
import requests as r
from time import sleep
from threading import Thread
import re #Regex
import winwifi #Used for ww.scan(), nothing else
from access_modifiers import privatemethod
class DroneConnector():
defaultWifi = "eduroam" #Wifi'et man er forbundet til lige nu
telloWIfiContains = "TELLO"
telloWIfiPassword = "gruppe154"
wifi_profile_folder = "wifi_profiles" #Mappen hvor vores wifi-profiler er gemt
hotspotSSID = "Bear" #
hotspotPASS = "joinTheNet" #Navnet og pass på dit hotspot som du laver
connectedDrones = []
def __init__(self, callback):
#Save your current wifi to connect back to later
self.defaultWifi = self.getCurrentWifi()
#Constantly update connectedDrones[] with the currently online drones
T = Thread(target=self.getConnectedDrones, args=(callback, ))
T.daemon = True
T.start()
@privatemethod
def getCurrentWifi(self):
"""Returns your currently connected Wifi"""
wifi = subprocess.check_output("netsh wlan show interfaces")
wifi = wifi.decode('utf-8').replace(" \r","")
currentWifi = re.findall(r"(?:Profile *: )(.*)\n", wifi)
if len(currentWifi) > 0:
return currentWifi[0] #Return e.g. "eduroam"
else:
return None
#@privatemethod
def connectWifi(self, SSID):
"""Connect to a wifi, which you already have a wifi-profile for"""
name = SSID
command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi"
resp = subprocess.run(command, capture_output=True)
#@privatemethod
def waitForConnection(self):
"""Waits until a connection to www.google.com is established"""
#print("[!] Searching for connection", end="")
for i in range(10):
try:
r.get("https://www.google.com")
#print(" --> Ok!")
return True
except:
#print(".", end="")
pass
sleep(1)
print("")
print(" --> Error?")
return False
@privatemethod
def generateWifiProfile(self, ssid, key=None):
"""Generates a Wifi profile with or without a password. Stores it in the wifi_profiles folder"""
hex = ssid.encode("utf-8").hex()
if key == None:
print("Generating profile for open network (no key)")
profile = """<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>""" + ssid + """</name>
<SSIDConfig>
<SSID>
<hex>""" + hex + """</hex>
<name>""" + ssid + """</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>manual</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>open</authentication>
<encryption>none</encryption>
<useOneX>false</useOneX>
</authEncryption>
</security>
</MSM>
<MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
<enableRandomization>false</enableRandomization>
</MacRandomization>
</WLANProfile>
"""
else:
print("Generating profile for closed network (with key)")
profile = """<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>""" + ssid + """</name>
<SSIDConfig>
<SSID>
<hex>""" + hex + """</hex>
<name>""" + ssid + """</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>""" + key + """</keyMaterial>
</sharedKey>
</security>
</MSM>
<MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
<enableRandomization>false</enableRandomization>
</MacRandomization>
</WLANProfile>
"""
return profile
@privatemethod
def connectToNewWifi(self, ssid, key=None):
"""Connect to a new wifi"""
if not os.path.exists(self.wifi_profile_folder):
os.makedirs(self.wifi_profile_folder)
fileName = self.wifi_profile_folder + "\\" + ssid + ".xml"
# fileName = "wifi_profiles\\TELLO-ABCDEF.xml"
if not os.path.isfile(fileName): #If there is NO wifi profile already, make a new one
profile = self.generateWifiProfile(ssid, key)
with open(fileName, "w") as f:
f.write(profile)
f.close()
command = r"netsh wlan add profile filename=" + fileName
resp = subprocess.run(command, capture_output=True)
self.connectWifi(ssid)
#Bliver lavet en thread af denne
def getConnectedDrones(self, callback):
while True:
# Hotspot is always on 192.168.137.0/24
arp_a_regex = r"""(192\.168\.137\.[0-9]{0,3}) *([0-9a-z-]*) """
arping = subprocess.check_output("arp -a")
arping = arping.decode('utf-8').replace(" \r","")
macsHotspot = re.findall(arp_a_regex, arping)
# macsHotspot = [(192.168.137.36, 34-d2-62-f2-51-f6), (ip, mac)]
# Remove the subnet entry
# macsHotspot.remove(('192.168.137.255', 'ff-ff-ff-ff-ff-ff'))
for m in macsHotspot[:]: #Lav en ny kopi for ikke at slette i macsHotspot mens vi itererer i den. Spørg Bjørn hvis forvirret
pingCommand = f"ping -w 500 {m[0]}"
#print(pingCommand)
pinging = subprocess.run(pingCommand, capture_output=True)
pinging = pinging.stdout.decode('utf-8').replace(" \r","")
if "Received = 0" in pinging:
macsHotspot.remove(m)
# Call GUI
#if self.connectedDrones != macsHotspot: # If the list has changed, we want to update it in our GUI by calling callback
callback(macsHotspot)
#Update so other modules knows what methods are connected
self.connectedDrones = macsHotspot
sleep(0.1)
########################################################################
# #
# NEDENFOR ER PUBLIC FUNKTIONERNE MENT til AT BLIVE KALDT I GUI-en #
# #
########################################################################
def findDrones(self):
"""Finds nearby drones"""
#Sometimes if will only find 1 network. Keep trying until it works
for i in range(5):
print("Scanning for nearby networks... ", end="")
ww = winwifi.WinWiFi()
wNetworks = ww.scan()
#print([i.ssid for i in wNetworks])
print(f"({len(wNetworks)} networks found)")
if len(wNetworks) > 1:
break
drones = []
for w in wNetworks:
if self.telloWIfiContains in w.ssid:
drones.append(w)
return drones
def calibrateDrone(self, droneMAC):
"""Opretter forbindelse, sætter i SDK mode og forbinder dronen til hotspottet"""
droneMAC = droneMAC.replace('-', '')[-6:]
droneSSID = "TELLO-" + droneMAC
self.connectToNewWifi(droneSSID)
#Wait until wifi is connected
print("Connecting to drone wifi", end="")
isWifiConnected = False
for i in range(10):
if self.getCurrentWifi() == droneSSID:
print(" --> Connected | ", end="")
isWifiConnected = True
break
else:
print(".", end="")
sleep(0.5)
if isWifiConnected == False: return False
# ---------------------------------------------
# VI ER PÅ DRONENS WIFI NU
#SOCKET SETUP
locaddr = ('', 1889) #HOST and PORT ME
tello_address = ('192.168.10.1', 8889) #HOST AND PORT FOR TELLO
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(3)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #FRA STACKOVERFLOW. https://stackoverflow.com/questions/41208720/python-sockets-not-really-closing
s.bind(locaddr)
#KEEPING TRACK OF DRONE CONNECTION
conEstablished = False
# First make it enter SDK command mode
print("Sending <command>", end="")
for i in range(5):
try:
s.sendto('command'.encode('utf-8'), tello_address)
response, ip = s.recvfrom(1024)
response = response.decode("utf-8")
if response == "ok":
conEstablished = True
print(" --> ok. ", end="")
break
elif response == "error":
print(" --> error. ", end="")
except Exception as e:
pass
#print("Error", str(e))
if conEstablished == True: # If drone actually is connected
# Make it connect to the hotspot
apCommand = f"ap {self.hotspotSSID} {self.hotspotPASS}" # The (ap ssid pass) command
#apCOmmand = "ap Bear joinTheNet"
print(f"Sending <{apCommand}> --> ", end="")
for i in range(5):
s.sendto(apCommand.encode('utf-8'), tello_address)
try:
response, ip = s.recvfrom(1024)
response = response.decode("utf-8")
if response == "error":
conEstablished = False
print("error", end="")
except Exception as e:
print("assumed to be <ok>", end="")
break
s.close()
return conEstablished #True eller False
def blackhole(*args): #Once entered this function it will never leave
pass
if __name__ == "__main__":
DC = DroneConnector(blackhole)
print([i.ssid for i in DC.findDrones()])
#print("Drone connected =", DC.calibrateDrone("F251F6"))
print("Connected =", DC.calibrateDrone("F250C6"))
DC.connectWifi(DC.defaultWifi)