/
scanner.py
executable file
·307 lines (277 loc) · 12.1 KB
/
scanner.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
import bluetooth
import lightblue
import httplib
import re
import time
import threading
import copy
import basics
import devices
class Sighting:
devices = []
reportId = 0
beginTime = ""
def __init__(self, devices=[], reportId=1, beginTime=""):
self.devices = copy.deepcopy(devices)
self.reportId = reportId
self.beginTime = beginTime
def serialize(self):
rootText = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"urn:Mynamespace\""
serial = "<?xml version=\"1.0\"?>"
serial += "<sightings %s>" % rootText
serial += "<clientReportId>%s</clientReportId>" % self.reportId
serial += "<scanningBeginTime>%s</scanningBeginTime>" % basics.Clock().getIsoTime()
serial += "<clientReportTime>%s</clientReportTime>" % basics.Clock().getIsoTime()
serial += "<sightingItemsList>"
for device in self.devices:
serial += device.serialize(tagname='sightingItem')
serial += "</sightingItemsList>"
serial += "</sightings>"
return serial
def getNumDevices(self):
return self.devices.__len__()
def __repr__(self):
st = "sighting("
st += "reportId:%s," % self.reportId
st += "beginTime:%s" % self.beginTime
st += "devices:"
for device in self.devices:
st += str(device)
st += " "
st += ")"
return st
def __str__(self):
return self.__repr__()
# -------------------------------------------------
class NameGetter(threading.Thread):
def __init__(self, knownDevices, intrf):
threading.Thread.__init__(self)
self.cv = threading.Condition()
self.kill_received = False
self.knownDevices = knownDevices
self.intrf = intrf
self.addresses = {} # list of addresses to get name - {address:None}
def run(self):
self.cv.acquire()
self.cv.wait()
self.cv.release()
while not self.kill_received:
if self.addresses:
devid = self.intrf.request(bandwidth=1)
print "[SCN] getting names of %d devices using hci%s..." % (len(self.addresses), devid)
try:
doneAddresses = {}
for addr in self.addresses:
#name = bluetooth.lookup_name(addr, device_id=devid)
name = bluetooth.lookup_name(addr)
self.knownDevices.setInfo(address=addr, name=name)
doneAddresses[addr] = name
self.cv.acquire()
for addr in doneAddresses:
if self.addresses.has_key(addr): self.addresses.pop(addr)
self.cv.release()
print "[SCN] inquiry ended. got the names of %d devices" % len(doneAddresses), doneAddresses
except bluetooth.btcommon.BluetoothError:
#raise bluetooth.btcommon.BluetoothError
print "[SCN] bluetooth error"
time.sleep(1)
self.intrf.release(interface=devid, bandwidth=1)
else:
#print "[SCN] there are no devices to get its names"
self.cv.acquire()
self.cv.wait()
self.cv.release()
#print "[SCN] NameGetter thread ended"
def kill(self):
#print "[SCN] killing NameGetter thread..."
if(self.isAlive):
self.kill_received = True
self.cv.acquire()
self.cv.notify()
self.cv.release()
def addAddresses(self, addresses=[]):
self.cv.acquire()
for addr in addresses:
self.addresses[addr] = None
self.cv.notify()
self.cv.release()
# -------------------------------------------------
class ServiceGetter(threading.Thread):
def __init__(self, knownDevices, intrf):
threading.Thread.__init__(self)
self.cv = threading.Condition()
self.kill_received = False
self.knownDevices = knownDevices
self.intrf = intrf
self.addresses = {} # list of addresses to get name - {address:None}
def run(self):
self.cv.acquire()
self.cv.wait()
self.cv.release()
while not self.kill_received:
if self.addresses:
devid = self.intrf.request(bandwidth=1)
print "[SCN] getting services of %d devices using hci%s..." % (len(self.addresses), devid)
try:
doneAddresses = {}
for addr in self.addresses:
services = lightblue.findservices(addr)
services2 = {}
for serv in services:
services2[serv[1]] = serv[2]
self.knownDevices.setInfo(address=addr, services=services2)
doneAddresses[addr] = services2
self.cv.acquire()
for addr in doneAddresses:
if self.addresses.has_key(addr): self.addresses.pop(addr)
self.cv.release()
print "[SCN] inquiry ended. got the services of %d devices" % len(doneAddresses), doneAddresses
except bluetooth.btcommon.BluetoothError:
#raise bluetooth.btcommon.BluetoothError
print "[SCN] bluetooth error"
time.sleep(1)
self.intrf.release(interface=devid, bandwidth=1)
else:
#print "there are no devices to get its services"
self.cv.acquire()
self.cv.wait()
self.cv.release()
#print "[SCN] ServiceGetter thread ended"
def kill(self):
#print "[SCN] killing ServiceGetter thread..."
if(self.isAlive):
self.kill_received = True
self.cv.acquire()
self.cv.notify()
self.cv.release()
def addAddresses(self, addresses=[]):
self.cv.acquire()
for addr in addresses:
self.addresses[addr] = None
self.cv.notify()
self.cv.release()
# -------------------------------------------------
class Scanner(threading.Thread):
def __init__(self, sched, intrf):
threading.Thread.__init__(self)
self.cv = threading.Condition()
self.kill_received = False
self.sched = sched
self.intrf = intrf
self.scannerOn = False
self.knownDevices = devices.ListOfDevices()
self.numErrors = 0
self.numErrorsUntilReset = 15 # workaround for OpenWrt's bug :(
self.lastScanTimestamp = 0
self.scaninterval=30
self.getnames=False
#self.namechache=None
self.getservices=False
#self.scantimeout=None
#self.nametimeout=None
#self.servicetimeout=None
def run(self):
print "[SCN] Scanner thread running"
namegetter = NameGetter(self.knownDevices, self.intrf)
servicegetter = ServiceGetter(self.knownDevices, self.intrf)
namegetter.start()
servicegetter.start()
while not self.kill_received:
if self.scannerOn:
devid = self.intrf.request(bandwidth=8)
(status,seenaddresses) = self._doScan(devid=devid)
addressesToGetName = []
addressesToGetServices = []
for addr in seenaddresses:
self.knownDevices.add(addr)
dev = self.knownDevices.getDeviceByAddress(addr)
# run the getter threads:
if self.namechache and self.namechache > 0:
timeWithNameInCache = self.namechache
else:
timeWithNameInCache = 0
if self.getnames and dev and (not dev.name or dev.lastNameUpdate < basics.Clock().getTimestamp() - timeWithNameInCache):
addressesToGetName.append(addr)
if self.getservices and dev and not dev.services:
addressesToGetServices.append(addr)
self.intrf.release(interface=devid, bandwidth=8)
# create the sighting structure and register event
seendevices2 = []
for addr in seenaddresses:
seendevices2.append(self.knownDevices.getDeviceByAddress(addr))
sighting = Sighting(seendevices2)
if(status>0): self.sched.pushEvent("newscan",sighting)
namegetter.addAddresses(addressesToGetName)
#namegetter.join()
servicegetter.addAddresses(addressesToGetServices)
#servicegetter.join()
wait = self.scaninterval - (time.time() - self.lastScanTimestamp)
if wait < -100000 or wait > self.scaninterval:
wait = self.scaninterval
if wait>0:
wait = int(round(wait))
print "[SCN] waiting %d seconds until scanning again (scaninterval=%s)" % (wait, self.scaninterval)
for i in range(wait):
if self.kill_received: break
time.sleep(1)
else:
self.cv.acquire()
self.cv.wait()
self.cv.release()
namegetter.kill()
servicegetter.kill()
print "[SCN] Scanner thread ended"
def kill(self):
if self.scannerOn: text = "scannings are still being performed! please wait..."
else: text = ""
print "[SCN] killing Scanner thread...", text
if(self.isAlive):
self.kill_received = True
self.cv.acquire()
self.cv.notify()
self.cv.release()
def _doScan(self, devid=-1):
status = 0
seenaddresses = []
try:
if self.lastScanTimestamp: print "[SCN] last scan was performed %.2f seconds ago" % round(time.time() - self.lastScanTimestamp, 2)
self.lastScanTimestamp = time.time()
try: # try to use a specific Bluetooth interface:
print "[SCN] address scanning using hci%s..." % devid
seenaddresses = bluetooth.discover_devices(device_id=devid)
except TypeError: # if there is no support for multiple interfaces, use the default one:
print "[SCN] address scanning using default interface (no support for multiple interfaces)"
seenaddresses = bluetooth.discover_devices()
status = seenaddresses.__len__()
print "[SCN] done. took %.2f sec. seen addresses:" % (round(time.time() - self.lastScanTimestamp, 2)), seenaddresses
self.numErrors = 0
except bluetooth.btcommon.BluetoothError: # if an error occurs, try to recover
status = -1
self.numErrors += 1
print "[SCN] bluetooth error (%d of %d tolerated)" % (self.numErrors, self.numErrorsUntilReset)
if self.numErrors == self.numErrorsUntilReset+1:
print "[SCN] BT ERROR: Resetting interface hci%d" % devid
basics.Exec().execlp('hciconfig', ['hci'+str(devid), 'down'], wait=True)
elif self.numErrors == self.numErrorsUntilReset+3:
print "[SCN] BT ERROR: Critical, restarting hotspot :("
#basics.Exec().execlp('reboot')
return (status, seenaddresses)
def startScanning(self, scaninterval=30, getnames=False, namechache=None, getservices=False, scantimeout=None, nametimeout=None, servicetimeout=None):
self.cv.acquire()
self.scaninterval = scaninterval
self.getnames = getnames
self.namechache = namechache
self.getservices = getservices
self.scantimeout = scantimeout
self.nametimeout = nametimeout
self.servicetimeout = servicetimeout
self.scannerOn = True
self.cv.notify()
self.cv.release()
pass
def stopScanning(self):
self.cv.acquire()
self.scannerOn = False
self.cv.notify()
self.cv.release()
pass