-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.py
401 lines (352 loc) · 20.6 KB
/
index.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
# NOTE: Some sensitive information has been removed such as MAC Addresses and names
# ┏━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓
# ┃ Index ┃ Address ┃ Name ┃ RSSI ┃ TX power ┃ Services ┃ Company ┃ Distance ┃ Last Seen ┃
# ┡━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩
# │ 0 │ 00:00:00:00:00:00 │ Unknown │ -39 │ 0 │ 0 │ Microsoft │ 0.00 │ 2024-09-18 15:11:42 │
# │ 1 │ 00:00:00:00:00:00 │ [TV] Samsung Q90 Series (75) │ -82 │ 0 │ 0 │ Samsung Electronics Co. Ltd. │ 0.00 │ 2024-09-18 15:11:42 │
# │ 2 │ 00:00:00:00:00:00 │ Wyze Lock │ -85 │ 0 │ 0 │ 17497 │ 0.00 │ 2024-09-18 15:11:42 │
# │ 3 │ 00:00:00:00:00:00 │ R33-0405 │ -38 │ 0 │ 0 │ 46517 │ 0.00 │ 2024-09-18 15:11:42 │
# │ 4 │ 00:00:00:00:00:00 │ Unknown │ -80 │ 0 │ 0 │ Samsung Electronics Co. Ltd. │ 0.00 │ 2024-09-18 15:11:42 │
# │ 5 │ 00:00:00:00:00:00 │ Unknown │ -81 │ -17 │ 0 │ Apple, Inc. │ 6.31 │ 2024-09-18 15:11:42 │
# │ 6 │ 00:00:00:00:00:00 │ Unknown │ -34 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:02 │
# │ 7 │ 00:00:00:00:00:00 │ N016Y │ -74 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:32 │
# │ 8 │ 00:00:00:00:00:00 │ Unknown │ -62 │ 0 │ 0 │ Apple, Inc. │ 0.00 │ 2024-09-18 15:11:02 │
# │ 9 │ 00:00:00:00:00:00 │ Unknown │ -37 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:42 │
# │ 10 │ 00:00:00:00:00:00 │ Unknown │ -83 │ -8 │ 0 │ Apple, Inc. │ 8.66 │ 2024-09-18 15:10:02 │
# │ 11 │ 00:00:00:00:00:00 │ Unknown │ -58 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:32 │
# │ 12 │ 00:00:00:00:00:00 │ Z01_665384 │ -78 │ -65 │ 0 │ Swipp ApS │ 1.45 │ 2024-09-18 15:11:42 │
# │ 13 │ 00:00:00:00:00:00 │ LYWSD03MMC │ -82 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:42 │
# │ 14 │ 00:00:00:00:00:00 │ ATC_97A504 │ -82 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:22 │
# │ 15 │ 00:00:00:00:00:00 │ ATC_C2F4FE │ -81 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:10:12 │
# │ 16 │ 00:00:00:00:00:00 │ LYWSD03MMC │ -80 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:42 │
# │ 17 │ 00:00:00:00:00:00 │ Unknown │ -83 │ 0 │ 0 │ Apple, Inc. │ 0.00 │ 2024-09-18 15:10:32 │
# │ 18 │ 00:00:00:00:00:00 │ Unknown │ -55 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:22 │
# │ 19 │ 00:00:00:00:00:00 │ Unknown │ -65 │ 0 │ 0 │ Samsung Electronics Co. Ltd. │ 0.00 │ 2024-09-18 15:11:22 │
# │ 20 │ 00:00:00:00:00:00 │ Unknown │ -39 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:02 │
# │ 21 │ 00:00:00:00:00:00 │ Unknown │ -70 │ -12 │ 0 │ Apple, Inc. │ 5.31 │ 2024-09-18 15:11:42 │
# │ 22 │ 00:00:00:00:00:00 │ ATC_E2930E │ -80 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:10:52 │
# │ 23 │ 00:00:00:00:00:00 │ Unknown │ -69 │ 0 │ 0 │ Apple, Inc. │ 0.00 │ 2024-09-18 15:10:22 │
# │ 24 │ 00:00:00:00:00:00 │ Unknown │ -38 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:02 │
# │ 25 │ 00:00:00:00:00:00 │ Unknown │ -44 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:22 │
# │ 26 │ 00:00:00:00:00:00 │ Unknown │ -54 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:42 │
# │ 27 │ 00:00:00:00:00:00 │ Unknown │ -66 │ 0 │ 0 │ Samsung Electronics Co. Ltd. │ 0.00 │ 2024-09-18 15:11:42 │
# │ 28 │ 00:00:00:00:00:00 │ Unknown │ -58 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:22 │
# │ 29 │ 00:00:00:00:00:00 │ Unknown │ -45 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:32 │
# │ 30 │ 00:00:00:00:00:00 │ Unknown │ -35 │ 0 │ 1 │ │ 0.00 │ 2024-09-18 15:11:32 │
# └───────┴───────────────────┴──────────────────────────────┴──────┴──────────┴──────────┴──────────────────────────────┴──────────┴─────────────────────┘
import os
import sys
import logging
from datetime import datetime, timedelta
import asyncio
import csv
import requests
from rich.progress import track
from rich.text import Text
from rich.live import Live
from rich.table import Table
from rich.console import Console
from ruamel.yaml import YAML
from ruamel.yaml.reader import Reader
from bleak import BleakScanner, AdvertisementData, BLEDevice, BleakClient
from core import (
device_distance_calculation,
bytes_to_hex_string,
bytes_to_int,
bytes_to_string,
)
logging.basicConfig(filename="bluetooth-discovery.log", level=logging.DEBUG)
class BleScannerInteractive:
"""Interactive Bluettooth Scanner"""
def __init__(self, redacted_address=False) -> None:
self._logger = logging.getLogger(__name__)
self._redacted_address = redacted_address
self.ensure_bluetooth_public_information_is_saved()
self._console = Console()
self._company_dict = {}
self._services_dict = {}
self._devices_dict = {}
self._devices_columns = {
"index": "Index",
"address": "Address",
"name": "Name",
"rssi": "RSSI",
"tx_power": "TX Power",
"services": "Services",
"company": "Company",
"distance": "Distance",
"last_seen": "Last Seen",
"first_seen": "First Seen",
}
self.__create_table()
self._discovery_timeout = 10
self._private_resolvable_random_address_timeout = 120
self._signal_propagation_constant = 8
def get_key_index(self, key: str, generic_dict: dict) -> int:
"""Get a key by index"""
keys = list(generic_dict.keys())
try:
return keys.index(key)
except ValueError:
return -1 # Return -1 if key is not found
def ensure_bluetooth_public_information_is_saved(self):
"""Download public bluetooth information"""
def save(filename: str, url: str):
if os.path.isfile(filename) is True:
return
self._logger.info("updating/creation %s from %s", filename, url)
response = requests.get(url, timeout=5000)
response.raise_for_status()
with open(filename, "w", encoding="utf-8") as file:
file.write(response.text.strip())
self._logger.info("saved %s", filename)
# TODO this should be saved in a config file
save(
"service_uuids.yaml",
"https://bitbucket.org/bluetooth-SIG/public/raw/025ac280519f8ad3967f79ee45bd921a76003113/assigned_numbers/uuids/service_uuids.yaml",
)
save(
"company_identifiers.yaml",
"https://bitbucket.org/bluetooth-SIG/public/raw/025ac280519f8ad3967f79ee45bd921a76003113/assigned_numbers/company_identifiers/company_identifiers.yaml",
)
def __create_table(self) -> None:
self._table = Table()
for _, device_value in self._devices_columns.items():
self._table.add_column(device_value)
async def _query_device(self, device_index: int):
mac_address = self._devices_dict[device_index]
client = BleakClient(mac_address, timeout=60)
try:
self._console.log(f"Connecting to {mac_address}")
await client.connect()
self._console.log(f"Connected to {mac_address}")
# Iterate through services and characteristics
for service in client.services:
self._console.log(
f"Service: {service.uuid} {service.description} {service.handle} {self.__get_service_name(service.handle)}"
)
for characteristic in service.characteristics:
self._console.log(f" Characteristic: {characteristic.uuid}")
self._console.log(f" Properties: {characteristic.properties}")
for descriptor in characteristic.descriptors:
# descriptor_value = await client.read_gatt_char(descriptor.uuid)
self._console.log(
f" Descriptor: {descriptor.uuid} Handle: {descriptor.handle}"
)
# pylint: disable=W0703
except Exception as exception:
self._console.log(exception)
self._logger.warning(exception)
finally:
await client.disconnect()
def uuid_to_gatt_handle(self, uuid: str) -> int:
"""Get uuid to int"""
handle_hex = uuid[4:8]
handle_int = int(handle_hex, 16)
return handle_int
def __callback(self, device: BLEDevice, advertisement_data: AdvertisementData):
service_count = (
len(advertisement_data.service_data.items())
if advertisement_data.service_data
else 0
)
company = None
if advertisement_data.manufacturer_data:
for company_id, _ in advertisement_data.manufacturer_data.items():
if company_id and company_id != 0:
company = self.__get_company_name(company_id) or str(company_id)
break
# ensure that rssi and tx power are negative (since that is how it should work!)
rssi = -abs(advertisement_data.rssi or device.rssi or 0)
tx_power = -abs(advertisement_data.tx_power or 0)
distance = device_distance_calculation(
tx_power, rssi, self._signal_propagation_constant
)
last_seen = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# If device has already been seen, use the original first seen value from existing table.
first_seen = last_seen
if self._devices_dict.get(device.address, None) is not None:
first_seen = self._devices_dict[device.address][
self.get_key_index("first_seen", self._devices_columns)
]
# Maintain an ongoing current status list
self._devices_dict[device.address] = [
str(0),
str(device.address),
str(device.name or "Unknown"),
str(rssi),
str(tx_power),
str(service_count),
str(company or ""),
str(f"{distance:.2f}"),
last_seen,
first_seen,
]
# all items in array become parameters
# self._table.add_row(*self._devices_dict[device.address])
# if advertisement_data.manufacturer_data:
# self._console.log("Manufacturer Data:")
# for company_id, data in advertisement_data.manufacturer_data.items():
# self._console.log(f" Manufacturer ID: {company_id}")
# self._console.log(
# f" Hex Data: {BleScannerInteractive.bytes_to_hex_string(data)}")
# self._console.log(
# f" Integer Data: {BleScannerInteractive.bytes_to_int(data)}")
# self._console.log(
# f" String Data: {BleScannerInteractive.bytes_to_string(data)}")
# if advertisement_data.service_uuids:
# service_name = None
# for service_uuid in advertisement_data.service_uuids:
# service_name = self.__get_service_name(self.uuid_to_gatt_handle(service_uuid))
# self._console.log(f'{service_name} {service_uuid}')
# if service_name == 'Battery':
# for service_uuid, data in advertisement_data.service_data.items():
# print(
# f" Hex Data: {bytes_to_hex_string(data)}")
# print(
# f" Integer Data: {bytes_to_int(data)}")
# print(
# f" String Data: {bytes_to_string(data)}")
# if advertisement_data.service_data:
# print("Service Data:")
# for service_uuid, data in advertisement_data.service_data.items():
# print(f" Service UUID: {service_uuid} {data}")
# print(
# f" Hex Data: {bytes_to_hex_string(data)}")
# print(
# f" Integer Data: {bytes_to_int(data)}")
# print(
# f" String Data: {bytes_to_string(data)}")
@staticmethod
def strip_invalid(s):
"""strip invalid yaml markup"""
res = ""
for x in s:
if Reader.NON_PRINTABLE.match(x):
continue
res += x
return res
def __get_service_name(self, value: int):
if len(self._services_dict) == 0:
# https://stackoverflow.com/a/45871921
with open("service_uuids.yaml", "r", encoding="utf-8") as file:
yaml = YAML(typ="safe")
self._services_dict = yaml.load(
BleScannerInteractive.strip_invalid(file.read())
)
for service in self._services_dict["uuids"]:
if service["uuid"] == value:
return service["name"]
return None
def __get_company_name(self, value: int) -> str | None:
if len(self._company_dict) == 0:
# https://stackoverflow.com/a/45871921
with open("company_identifiers.yaml", "r", encoding="utf-8") as file:
yaml = YAML(typ="safe")
self._company_dict = yaml.load(
BleScannerInteractive.strip_invalid(file.read())
)
for company in self._company_dict["company_identifiers"]:
if company["value"] == value:
return company["name"]
return None
def __write_current_device_list_csv(self):
try:
with open("devices.csv", mode="w", newline="", encoding="utf8") as file:
writer = csv.writer(file)
writer.writerow(self._devices_columns.keys())
for _, values in self._devices_dict.items():
writer.writerow([*values])
except Exception as e:
self._logger.warning(e)
async def loading(self):
for _ in track(range(self._discovery_timeout + 1), description="Scanning..."):
await asyncio.sleep(1)
async def __discover_with_data(self):
# Combat "private resolvable random addresses" from filling up the screen.
time_threshold = datetime.now() - timedelta(
seconds=self._private_resolvable_random_address_timeout
)
keys_to_remove = []
for device, value in self._devices_dict.items():
last_seen = datetime.strptime(
value[self.get_key_index("last_seen", self._devices_columns)],
"%Y-%m-%d %H:%M:%S",
)
if last_seen < time_threshold:
keys_to_remove.append(device)
# Remove devices after expire
for device in keys_to_remove:
del self._devices_dict[device]
self._logger.info("removed %s", device)
self._logger.info("bluetooth discovered devices started")
devices_data = await BleakScanner.discover(
timeout=self._discovery_timeout, return_adv=True
)
self._logger.info("bluetooth discovered devices ended")
for device_key in devices_data:
device, adv = devices_data[device_key]
self.__callback(device, adv)
# update all the missing ones in the table
for index, (device_key, device_data) in enumerate(self._devices_dict.items()):
rendered_device_data = []
device_data[0] = str(index)
for index_device_data, text_device_data in enumerate(device_data):
text = text_device_data
# redact addresses
if (
self._redacted_address is True
and index_device_data
== self.get_key_index("address", self._devices_columns)
):
text = text[:3] + "." * (len(text) - 3)
rendered_device_data.append(Text(text=text))
# tx power or services want to be found. highlight them
style = ""
if (
abs(
int(
device_data[
self.get_key_index("tx_power", self._devices_columns)
]
)
)
> 0
or abs(
int(
device_data[
self.get_key_index("services", self._devices_columns)
]
)
)
> 0
):
style = "green"
self._table.add_row(*rendered_device_data, style=style)
async def run_async(self):
"""async method to start app"""
# Dummy loading screening while devices are being discovered
await asyncio.gather(self.__discover_with_data(), self.loading())
self._console.clear()
# Keep a live table going
with Live(self._table, console=self._console) as live:
live.update(self._table)
while True:
self.__create_table()
await self.__discover_with_data()
live.update(self._table)
self.__write_current_device_list_csv()
def run(self):
"""sync method to start app"""
try:
asyncio.run(self.run_async())
except KeyboardInterrupt:
self._console.print("Bye bye")
sys.exit(0)
# while True:
# device_index = int(self._console.input(
# "Pick an index to connect:"))
# await self._query_device(device_index)
if __name__ == "__main__":
scanner = BleScannerInteractive(redacted_address=True)
scanner.run()