-
Notifications
You must be signed in to change notification settings - Fork 155
/
sparrowwifiagent.py
executable file
·2844 lines (2412 loc) · 112 KB
/
sparrowwifiagent.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
#
# Copyright 2017 ghostop14
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import os
import sys
import datetime
import json
import re
import argparse
import configparser
# import subprocess
from socket import *
from time import sleep
from threading import Thread, Lock
from dateutil import parser
from http import server as HTTPServer
from socketserver import ThreadingMixIn
from wirelessengine import WirelessEngine
from sparrowgps import GPSEngine, GPSEngineStatic, GPSStatus, SparrowGPS
try:
from sparrowdrone import SparrowDroneMavlink
hasDroneKit = True
except:
hasDroneKit = False
from sparrowrpi import SparrowRPi
from sparrowbluetooth import SparrowBluetooth, BluetoothDevice
from sparrowhackrf import SparrowHackrf
from sparrowcommon import gzipCompress
try:
from manuf import manuf
hasOUILookup = True
except:
hasOUILookup = False
# ------ Global setup ------------
gpsEngine = None
curTime = datetime.datetime.now()
useMavlink = False
vehicle = None
mavlinkGPSThread = None
hasFalcon = False
hasBluetooth = False
hasUbertooth = False
falconWiFiRemoteAgent = None
bluetooth = None
hackrf = SparrowHackrf()
debugHTTP = False
allowCors = False
# Lock list is a dictionary of thread locks for scanning interfaces
lockList = {}
allowedIPs = []
useRPILeds = False
# runningcfg is created in main
runningcfg = None
recordThread = None
announceThread = None
# ------ Global functions ------------
def stringtobool(instr):
if (instr == 'True' or instr == 'true'):
return True
else:
return False
def TwoDigits(instr):
# Fill in a leading zero for single-digit numbers
while len(instr) < 2:
instr = '0' + instr
return instr
def deleteRecordingFiles(filelist):
dirname, filename = os.path.split(os.path.abspath(__file__))
recordingsDir = dirname + '/recordings'
retVal = ''
for curFilename in filelist:
# This split is simply a safety check to prevent path traversal attacks
dirname, filename = os.path.split(curFilename)
if len(filename) > 0:
fullpath = recordingsDir + '/' + filename
try:
os.remove(fullpath)
except:
if len(retVal) == 0:
retVal = filename
else:
retVal += ',' + filename
return retVal
def getRecordingFiles():
dirname, filename = os.path.split(os.path.abspath(__file__))
recordingsDir = dirname + '/recordings'
if not os.path.exists(recordingsDir):
os.makedirs(recordingsDir)
retVal = []
try:
for filename in os.listdir(recordingsDir):
fullPath = recordingsDir + '/' + filename
if not os.path.isdir(fullPath):
curFile = FileSystemFile()
curFile.filename = filename
curFile.size = os.path.getsize(fullPath)
try:
curFile.timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(fullPath))
except:
curFile.timestamp = None
retVal.append(curFile.toJsondict())
except:
pass
return retVal
def restartAgent():
global bluetooth
if mavlinkGPSThread:
mavlinkGPSThread.signalStop = True
print('Waiting for mavlink GPS thread to terminate...')
while (mavlinkGPSThread.threadRunning):
sleep(0.2)
stopRecord()
stopAnnounceThread()
if bluetooth:
bluetooth.stopScanning()
if runningcfg.useRPiLEDs:
SparrowRPi.greenLED(SparrowRPi.LIGHT_STATE_OFF)
SparrowRPi.redLED(SparrowRPi.LIGHT_STATE_ON)
if hasFalcon:
falconWiFiRemoteAgent.cleanup()
if os.path.isfile('/usr/local/bin/python3.5') or os.path.isfile('/usr/bin/python3.5'):
exefile = 'python3.5'
else:
exefile = 'python3'
# params = [exefile, __file__, '--delaystart=2']
newCommand = exefile + ' ' + __file__ + ' --delaystart=2 &'
os.system(newCommand)
# subprocess.Popen(params, stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
# result = subprocess.run(params, stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
# restartResult = result.stdout.decode('UTF-8')
os.kill(os.getpid(), 9)
def updateRunningConfig(newCfg):
global runningcfg
if runningcfg.ipAllowedList != newCfg.ipAllowedList:
buildAllowedIPs(newCfg.ipAllowedList)
# port we ignore since we're already running
# useRPiLEDs will just update
# Announce
if runningcfg.announce != newCfg.announce:
if not newCfg.announce:
stopAnnounceThread()
else:
# start will check if it's already running
startAnnounceThread()
# mavlinkGPS
# Need to restart to update mavlinkGPS
# So just copy forward
newCfg.mavlinkGPS = runningcfg.mavlinkGPS
# recordInterface
if runningcfg.recordInterface != newCfg.recordInterface:
if len(newCfg.recordInterface) == 0:
stopRecord()
else:
# start will check if it's already running
startRecord(newCfg.recordInterface)
# Finally swap out the config
runningcfg = newCfg
def startRecord(interface):
global recordThread
if recordThread:
return
if len(interface) > 0:
interfaces = WirelessEngine.getInterfaces()
if interface in interfaces:
recordThread = AutoAgentScanThread(interface)
recordThread.start()
else:
print('ERROR: Record was requested on ' + interface + ' but that interface was not found.')
else:
recordThread = None
def stopRecord():
global recordThread
if recordThread:
recordThread.signalStop = True
print('Waiting for record thread to terminate...')
i=0
maxCycles = 2 /0.2
while (recordThread.threadRunning) and (i<maxCycles):
sleep(0.2)
i += 1
def stopAnnounceThread():
global announceThread
if announceThread:
announceThread.signalStop = True
print('Waiting for announce thread to terminate...')
sleep(0.2)
# i=0
# maxCycles = 5 # int(2.0 /0.2)
# while (announceThread.threadRunning) and (i<maxCycles):
# sleep(0.2)
# i += 1
announceThread = None
def startAnnounceThread():
global runningcfg
global announceThread
# Start announce if needed
if announceThread:
# It's already running
return
print('Sending agent announcements on port ' + str(runningcfg.port) + '.')
announceThread = AnnounceThread(runningcfg.port)
announceThread.start()
def buildAllowedIPs(allowedIPstr):
global allowedIPs
allowedIPs = []
if len(allowedIPstr) > 0:
ippattern = re.compile(r'([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})')
if ',' in allowedIPstr:
tmpList = allowedIPstr.split(',')
for curItem in tmpList:
ipStr = curItem.replace(' ', '')
try:
ipValue = ippattern.search(ipStr).group(1)
except:
ipValue = ""
print('ERROR: Unknown IP pattern: ' + ipStr)
exit(3)
if len(ipValue) > 0:
allowedIPs.append(ipValue)
else:
ipStr = allowedIPstr.replace(' ', '')
try:
ipValue = ippattern.search(ipStr).group(1)
except:
ipValue = ""
print('ERROR: Unknown IP pattern: ' + ipStr)
return False
if len(ipValue) > 0:
allowedIPs.append(ipValue)
return True
# ------ OUI lookup functions ------------
def getOUIDB():
ouidb = None
if hasOUILookup:
if os.path.isfile('manuf'):
# We have the file but let's not update it every time we run the app.
# every 90 days should be plenty
last_modified_date = datetime.datetime.fromtimestamp(os.path.getmtime('manuf'))
now = datetime.datetime.now()
age = now - last_modified_date
if age.days > 90:
updateflag = True
else:
updateflag = False
else:
# We don't have the file, let's get it
updateflag = True
try:
ouidb = manuf.MacParser(update=updateflag)
except:
ouidb = None
else:
ouidb = None
return ouidb
# ------------------ File ------------------------------
class FileSystemFile(object):
def __init__(self):
self.filename = ""
self.size = 0
self.timestamp = None
def __str__(self):
retVal = self.filename
return retVal
def toJsondict(self):
jsondict = {}
jsondict['filename'] = self.filename
jsondict['size'] = self.size
jsondict['timestamp'] = str(self.timestamp)
return jsondict
def fromJsondict(self, jsondict):
self.filename = jsondict['filename']
self.size = jsondict['size']
if jsondict['timestamp'] == 'None':
self.timestamp = None
else:
self.timestamp = parser.parse(jsondict['timestamp'])
# ------------------ Config Settings ------------------------------
class AgentConfigSettings(object):
def __init__(self):
self.cancelStart = False
self.port = 8020
self.announce = False
self.useRPiLEDs = False
self.recordInterface=""
self.recordRunning = False
self.mavlinkGPS = ""
self.ipAllowedList = ""
self.allowCors = False
def __str__(self):
retVal = "Cancel Start: " + str(self.cancelStart) + "\n"
retVal += "Port: " + str(self.port) + "\n"
retVal += "Announce Agent: " + str(self.announce) + "\n"
retVal += "Use RPi LEDs: " + str(self.useRPiLEDs) + "\n"
retVal += "Record Interface: " + self.recordInterface + "\n"
retVal += "Record Running (for running configs): " + str(self.recordRunning) + "\n"
retVal += "Mavlink GPS: " + self.mavlinkGPS + "\n"
retVal += "IP Allowed List: " + self.ipAllowedList + "\n"
retVal += "Allow CORS: " + str(self.allowCors) + "\n"
return retVal
def __eq__(self, obj):
# This is equivance.... ==
if not isinstance(obj, AgentConfigSettings):
return False
if self.cancelStart != obj.cancelStart:
return False
if self.port != obj.port:
return False
if self.announce != obj.announce:
return False
if self.useRPiLEDs != obj.useRPiLEDs:
return False
if self.recordInterface != obj.recordInterface:
return False
if self.mavlinkGPS != obj.mavlinkGPS:
return False
if self.ipAllowedList != obj.ipAllowedList:
return False
if self.allowCors != obj.allowCors:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def toJsondict(self):
dictjson = {}
dictjson['cancelstart'] = str(self.cancelStart)
dictjson['port'] = self.port
dictjson['announce'] = str(self.announce)
dictjson['recordrunning'] = str(self.recordRunning)
dictjson['userpileds'] = str(self.useRPiLEDs)
dictjson['recordinterface'] = self.recordInterface
dictjson['mavlinkgps'] = self.mavlinkGPS
dictjson['allowedips'] = self.ipAllowedList
dictjson['allowcors'] = str(self.allowCors)
return dictjson
def toJson(self):
dictjson = self.toJsondict()
return json.dumps(dictjson)
def fromJsondict(self, dictjson):
try:
self.cancelStart = stringtobool(dictjson['cancelstart'])
self.port = int(dictjson['port'])
self.announce = stringtobool(dictjson['announce'])
self.recordRunning = stringtobool(dictjson['recordrunning'])
self.useRPiLEDs = stringtobool(dictjson['userpileds'])
self.recordInterface = dictjson['recordinterface']
self.mavlinkGPS = dictjson['mavlinkgps']
self.ipAllowedList = dictjson['allowedips']
# if 'allowcors' in dictjson.keys():
self.allowCors = stringtobool(dictjson['allowcors'])
# else:
# print("allowCors not set in dictjson!")
except Exception as e:
print(e)
def fromJson(self, jsonstr):
dictjson = json.loads(jsonstr)
self.fromJsondict(dictjson)
def toConfigFile(self, cfgFile):
config = configparser.ConfigParser()
config['agent'] = self.toJsondict()
try:
with open(cfgFile, 'w') as configfile:
config.write(configfile)
return True
except:
return False
def fromConfigFile(self, cfgFile):
if os.path.isfile(cfgFile):
cfgParser = configparser.ConfigParser()
try:
cfgParser.read(cfgFile)
section="agent"
options = cfgParser.options(section)
for option in options:
try:
if option =='cancelstart':
self.cancelStart = stringtobool(cfgParser.get(section, option))
elif option == 'sendannounce':
self.announce = stringtobool(cfgParser.get(section, option))
elif option == 'userpileds':
self.useRPiLEDs = stringtobool(cfgParser.get(section, option))
elif option == 'port':
self.port=int(cfgParser.get(section, option))
elif option == 'recordinterface':
self.recordInterface=cfgParser.get(section, option)
elif option == 'mavlinkgps':
self.mavlinkGPS=cfgParser.get(section, option)
elif option == 'allowedips':
self.ipAllowedList = cfgParser.get(section, option)
elif option == 'allowcors':
self.allowCors = stringtobool(cfgParser.get(section, option))
except:
print("exception on %s!" % option)
settings[option] = None
except:
print("ERROR: Unable to read config file: ", cfgFile)
return False
else:
return False
return True
# ------------------ Agent auto scan thread ------------------------------
class AutoAgentScanThread(Thread):
def __init__(self, interface):
global lockList
global hasBluetooth
super(AutoAgentScanThread, self).__init__()
self.interface = interface
self.signalStop = False
self.scanDelay = 0.5 # seconds
self.threadRunning = False
self.discoveredNetworks = {}
self.discoveredBluetoothDevices = {}
self.daemon = True
try:
self.hostname = os.uname()[1]
except:
self.hostname = 'unknown'
if len(self.hostname) == 0:
self.hostname = 'unknown'
self.ouiLookupEngine = getOUIDB()
if interface not in lockList.keys():
lockList[interface] = Lock()
if not os.path.exists('./recordings'):
os.makedirs('./recordings')
now = datetime.datetime.now()
self.filename = './recordings/' + self.hostname + '_wifi_' + str(now.year) + "-" + TwoDigits(str(now.month)) + "-" + TwoDigits(str(now.day))
self.filename += "_" + TwoDigits(str(now.hour)) + "_" + TwoDigits(str(now.minute)) + "_" + TwoDigits(str(now.second)) + ".csv"
self.btfilename = './recordings/' + self.hostname + '_bt_' + str(now.year) + "-" + TwoDigits(str(now.month)) + "-" + TwoDigits(str(now.day))
self.btfilename += "_" + TwoDigits(str(now.hour)) + "_" + TwoDigits(str(now.minute)) + "_" + TwoDigits(str(now.second)) + ".csv"
if hasBluetooth:
print('Capturing on ' + interface + ' and writing wifi to ' + self.filename)
print('and writing bluetooth to ' + self.btfilename)
else:
print('Capturing on ' + interface + ' and writing wifi to ' + self.filename)
def run(self):
global lockList
global hasBluetooth
self.threadRunning = True
if self.interface not in lockList.keys():
lockList[self.interface] = Lock()
curLock = lockList[self.interface]
if hasBluetooth:
# Start normal discovery
bluetooth.startDiscovery(False)
lastState = -1
while (not self.signalStop):
# Scan all / normal mode
if (curLock):
curLock.acquire()
retCode, errString, wirelessNetworks = WirelessEngine.scanForNetworks(self.interface)
if (curLock):
curLock.release()
if (retCode == 0):
if useMavlink:
gpsCoord = GPSStatus()
gpsCoord.gpsInstalled = True
gpsCoord.gpsRunning = True
gpsCoord.isValid = mavlinkGPSThread.synchronized
gpsCoord.latitude = mavlinkGPSThread.latitude
gpsCoord.longitude = mavlinkGPSThread.longitude
gpsCoord.altitude = mavlinkGPSThread.altitude
gpsCoord.speed = mavlinkGPSThread.vehicle.getAirSpeed()
elif gpsEngine.gpsValid():
gpsCoord = gpsEngine.lastCoord
if useRPILeds and (lastState !=SparrowRPi.LIGHT_STATE_ON):
SparrowRPi.redLED(SparrowRPi.LIGHT_STATE_ON)
lastState = SparrowRPi.LIGHT_STATE_ON
else:
gpsCoord = GPSStatus()
if useRPILeds and (lastState !=SparrowRPi.LIGHT_STATE_HEARTBEAT) :
SparrowRPi.redLED(SparrowRPi.LIGHT_STATE_HEARTBEAT)
lastState = SparrowRPi.LIGHT_STATE_HEARTBEAT
# self.statusBar().showMessage('Scan complete. Found ' + str(len(wirelessNetworks)) + ' networks')
if wirelessNetworks and (len(wirelessNetworks) > 0) and (not self.signalStop):
for netKey in wirelessNetworks.keys():
curNet = wirelessNetworks[netKey]
curNet.gps.copy(gpsCoord)
curNet.strongestgps.copy(gpsCoord)
curKey = curNet.getKey()
if curKey not in self.discoveredNetworks.keys():
self.discoveredNetworks[curKey] = curNet
else:
# Network exists, need to update it.
pastNet = self.discoveredNetworks[curKey]
# Need to save strongest gps and first seen. Everything else can be updated.
# Carry forward firstSeen
curNet.firstSeen = pastNet.firstSeen # This is one field to carry forward
# Check strongest signal
if pastNet.strongestsignal > curNet.signal:
curNet.strongestsignal = pastNet.strongestsignal
curNet.strongestgps.latitude = pastNet.strongestgps.latitude
curNet.strongestgps.longitude = pastNet.strongestgps.longitude
curNet.strongestgps.altitude = pastNet.strongestgps.altitude
curNet.strongestgps.speed = pastNet.strongestgps.speed
curNet.strongestgps.isValid = pastNet.strongestgps.isValid
self.discoveredNetworks[curKey] = curNet
if not self.signalStop:
self.exportNetworks()
# Now if we have bluetooth running export these:
if hasBluetooth and bluetooth.discoveryRunning():
bluetooth.deviceLock.acquire()
# Update GPS
now = datetime.datetime.now()
for curKey in bluetooth.devices.keys():
curDevice = bluetooth.devices[curKey]
elapsedTime = now - curDevice.lastSeen
# This is a little bit of a hack for the BlueHydra side since it can take a while to see devices or have
# them show up in the db. For LE discovery scans this will always be pretty quick.
if elapsedTime.total_seconds() < 120:
curDevice.gps.copy(gpsCoord)
if curDevice.rssi >= curDevice.strongestRssi:
curDevice.strongestRssi = curDevice.rssi
curDevice.strongestgps.copy(gpsCoord)
# export
self.exportBluetoothDevices(bluetooth.devices)
bluetooth.deviceLock.release()
sleep(self.scanDelay)
if hasBluetooth:
# Start normal discovery
bluetooth.stopDiscovery()
self.threadRunning = False
def ouiLookup(self, macAddr):
clientVendor = ""
if hasOUILookup:
try:
if self.ouiLookupEngine:
clientVendor = self.ouiLookupEngine.get_manuf(macAddr)
except:
clientVendor = ""
return clientVendor
def exportBluetoothDevices(self, devices):
try:
btOutputFile = open(self.btfilename, 'w')
except:
print('ERROR: Unable to write to bluetooth file ' + self.filename)
return
btOutputFile.write('uuid,Address,Name,Company,Manufacturer,Type,RSSI,TX Power,Strongest RSSI,Est Range (m),Last Seen,GPS Valid,Latitude,Longitude,Altitude,Speed,Strongest GPS Valid,Strongest Latitude,Strongest Longitude,Strongest Altitude,Strongest Speed\n')
for curKey in devices.keys():
curData = devices[curKey]
btType = ""
if curData.btType == BluetoothDevice.BT_LE:
btType = "BTLE"
else:
btType = "Classic"
if curData.txPowerValid:
txPower = str(curData.txPower)
else:
txPower = 'Unknown'
btOutputFile.write(curData.uuid + ',' + curData.macAddress + ',"' + curData.name + '","' + curData.company + '","' + curData.manufacturer)
btOutputFile.write('","' + btType + '",' + str(curData.rssi) + ',' + str(curData.strongestRssi) + ',' + txPower + ',' + str(curData.iBeaconRange) + ',' +
curData.lastSeen.strftime("%m/%d/%Y %H:%M:%S") + ',' +
str(curData.gps.isValid) + ',' + str(curData.gps.latitude) + ',' + str(curData.gps.longitude) + ',' + str(curData.gps.altitude) + ',' + str(curData.gps.speed) + ',' +
str(curData.strongestgps.isValid) + ',' + str(curData.strongestgps.latitude) + ',' + str(curData.strongestgps.longitude) + ',' + str(curData.strongestgps.altitude) + ',' + str(curData.strongestgps.speed) + '\n')
btOutputFile.close()
def exportNetworks(self):
try:
self.outputFile = open(self.filename, 'w')
except:
print('ERROR: Unable to write to wifi file ' + self.filename)
return
self.outputFile.write('macAddr,vendor,SSID,Security,Privacy,Channel,Frequency,Signal Strength,Strongest Signal Strength,Bandwidth,Last Seen,First Seen,GPS Valid,Latitude,Longitude,Altitude,Speed,Strongest GPS Valid,Strongest Latitude,Strongest Longitude,Strongest Altitude,Strongest Speed\n')
for netKey in self.discoveredNetworks.keys():
curData = self.discoveredNetworks[netKey]
vendor = self.ouiLookup(curData.macAddr)
if vendor is None:
vendor = ''
self.outputFile.write(curData.macAddr + ',' + vendor + ',"' + curData.ssid + '",' + curData.security + ',' + curData.privacy)
self.outputFile.write(',' + curData.getChannelString() + ',' + str(curData.frequency) + ',' + str(curData.signal) + ',' + str(curData.strongestsignal) + ',' + str(curData.bandwidth) + ',' +
curData.lastSeen.strftime("%m/%d/%Y %H:%M:%S") + ',' + curData.firstSeen.strftime("%m/%d/%Y %H:%M:%S") + ',' +
str(curData.gps.isValid) + ',' + str(curData.gps.latitude) + ',' + str(curData.gps.longitude) + ',' + str(curData.gps.altitude) + ',' + str(curData.gps.speed) + ',' +
str(curData.strongestgps.isValid) + ',' + str(curData.strongestgps.latitude) + ',' + str(curData.strongestgps.longitude) + ',' + str(curData.strongestgps.altitude) + ',' + str(curData.strongestgps.speed) + '\n')
self.outputFile.close()
# ------------------ Announce thread ------------------------------
class AnnounceThread(Thread):
def __init__(self, port):
super(AnnounceThread, self).__init__()
self.signalStop = False
self.sendDelay = 4.0 # seconds
self.threadRunning = False
self.daemon = True
self.broadcastSocket = socket(AF_INET, SOCK_DGRAM)
self.broadcastSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.broadcastSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
self.broadcastPort = port
self.broadcastAddr=('255.255.255.255', self.broadcastPort)
def sendAnnounce(self):
try:
self.broadcastSocket.sendto(bytes('sparrowwifiagent', "utf-8"),self.broadcastAddr)
except:
pass
def run(self):
self.threadRunning = True
while (not self.signalStop):
self.sendAnnounce()
# 4 second delay, but check every second for termination signal
i=0
while i<4 and not self.signalStop:
sleep(1.0)
i += 1
self.threadRunning = False
# ------------------ Local network scan thread ------------------------------
class MavlinkGPSThread(Thread):
def __init__(self, vehicle):
super(MavlinkGPSThread, self).__init__()
self.signalStop = False
self.scanDelay = 0.5 # seconds
self.threadRunning = False
self.vehicle = vehicle
self.synchronized = False
self.latitude = 0.0
self.longitude = 0.0
self.altitude = 0.0
self.daemon = True
def run(self):
self.threadRunning = True
lastState = -1
while (not self.signalStop):
self.synchronized, self.latitude, self.longitude, self.altitude = self.vehicle.getGlobalGPS()
if self.synchronized:
# Solid on synchronized
if useRPILeds and (lastState != SparrowRPi.LIGHT_STATE_ON):
SparrowRPi.redLED(SparrowRPi.LIGHT_STATE_ON)
lastState = SparrowRPi.LIGHT_STATE_ON
else:
# heartbeat on unsynchronized
if useRPILeds and (lastState != SparrowRPi.LIGHT_STATE_HEARTBEAT):
SparrowRPi.redLED(SparrowRPi.LIGHT_STATE_HEARTBEAT)
lastState = SparrowRPi.LIGHT_STATE_HEARTBEAT
sleep(self.scanDelay)
self.threadRunning = False
class SparrowWiFiAgent(object):
# See https://docs.python.org/3/library/http.server.html
# For HTTP Server info
def run(self, port):
global useRPILeds
global hackrf
global bluetooth
global falconWiFiRemoteAgent
server_address = ('', port)
try: # httpd = HTTPServer.HTTPServer(server_address, SparrowWiFiAgentRequestHandler)
httpd = MultithreadHTTPServer(server_address, SparrowWiFiAgentRequestHandler)
except OSError as e:
curTime = datetime.datetime.now()
print('[' +curTime.strftime("%m/%d/%Y %H:%M:%S") + "] Unable to bind to port " + str(port) + ". " + e.strerror)
if runningcfg.useRPiLEDs:
SparrowRPi.greenLED(SparrowRPi.LIGHT_STATE_OFF)
SparrowRPi.redLED(SparrowRPi.LIGHT_STATE_ON)
exit(1)
curTime = datetime.datetime.now()
print('[' +curTime.strftime("%m/%d/%Y %H:%M:%S") + "] Starting Sparrow-wifi agent on port " + str(port))
if useRPILeds:
SparrowRPi.greenLED(SparrowRPi.LIGHT_STATE_ON)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
if useRPILeds:
SparrowRPi.greenLED(SparrowRPi.LIGHT_STATE_OFF)
if hasFalcon:
falconWiFiRemoteAgent.cleanup()
if bluetooth:
bluetooth.stopScanning()
if hackrf.scanRunning():
hackrf.stopScanning()
curTime = datetime.datetime.now()
print('[' +curTime.strftime("%m/%d/%Y %H:%M:%S") + "] Sparrow-wifi agent stopped.")
# --------------- Multithreaded HTTP Server ------------------------------------
class MultithreadHTTPServer(ThreadingMixIn, HTTPServer.HTTPServer):
pass
# --------------- HTTP Request Handler --------------------
# Sample handler: https://wiki.python.org/moin/BaseHttpServer
class SparrowWiFiAgentRequestHandler(HTTPServer.BaseHTTPRequestHandler):
def log_message(self, format, *args):
global debugHTTP
if not debugHTTP:
return
else:
HTTPServer.BaseHTTPRequestHandler(format, *args)
def do_HEAD(s):
global allowCors
s.send_response(200)
s.send_header("Content-type", "text/html")
if allowCors:
s.send_header("Access-Control-Allow-Origin", "*")
s.end_headers()
def do_POST(s):
global runningcfg
global falconWiFiRemoteAgent
if len(s.client_address) == 0:
# This should have the connecting client IP. If this isn't at least 1, something is wrong
return
if len(allowedIPs) > 0:
if s.client_address[0] not in allowedIPs:
try:
s.send_response(403)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><body><p>Connections not authorized from your IP address</p>".encode("utf-8"))
s.wfile.write("</body></html>".encode("UTF-8"))
except:
pass
return
if (not s.isValidPostURL()):
try:
s.send_response(404)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><body><p>Page not found.</p>".encode("utf-8"))
s.wfile.write("</body></html>".encode("UTF-8"))
except:
pass
return
# Get the size of the posted data
try:
length = int(s.headers['Content-Length'])
except:
length = 0
if length <= 0:
responsedict = {}
responsedict['errcode'] = 1
responsedict['errmsg'] = 'Agent received a zero-length request.'
try:
s.send_response(400)
s.send_header("Content-type", "application/json")
s.end_headers()
jsonstr = json.dumps(responsedict)
s.wfile.write(jsonstr.encode("UTF-8"))
except:
pass
return
# get the POSTed payload
jsonstr_data = s.rfile.read(length).decode('utf-8')
# Try to convert it to JSON
try:
jsondata = json.loads(jsonstr_data)
except:
responsedict = {}
responsedict['errcode'] = 1
responsedict['errmsg'] = 'bad posted data.'
try:
s.send_response(400)
s.send_header("Content-type", "application/json")
s.end_headers()
jsonstr = json.dumps(responsedict)
s.wfile.write(jsonstr.encode("UTF-8"))
except:
pass
return
if s.path == '/system/config':
# ------------- Update startup config ------------------
try:
scfg = jsondata['startup']
startupCfg = AgentConfigSettings()
startupCfg.fromJsondict(scfg)
dirname, filename = os.path.split(os.path.abspath(__file__))
cfgFile = dirname + '/sparrowwifiagent.cfg'
retVal = startupCfg.toConfigFile(cfgFile)
if not retVal:
# HTML 400 = Bad request
s.send_response(400)
responsedict = {}
responsedict['errcode'] = 2
responsedict['errmsg'] = 'An error occurred saving the startup config.'
try:
s.send_response(400)
s.send_header("Content-type", "application/json")
s.end_headers()
jsonstr = json.dumps(responsedict)
s.wfile.write(jsonstr.encode("UTF-8"))
except:
pass
except:
responsedict = {}
responsedict['errcode'] = 3
responsedict['errmsg'] = 'Bad startup config.'
try:
s.send_response(400)
s.send_header("Content-type", "application/json")
s.end_headers()
jsonstr = json.dumps(responsedict)
s.wfile.write(jsonstr.encode("UTF-8"))
except:
pass
# ------------- Check if we should reboot ------------------
if 'rebootagent' in jsondata:
rebootFlag = jsondata['rebootagent']