Last active
September 4, 2020 22:09
-
-
Save atharvai/cb30c0d7c6009da40af2de481d2cb458 to your computer and use it in GitHub Desktop.
Scan Bluetooth LE for advertised Eddystone URLs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reads Bluteooth LE Eddystone beacon URL from Microbit | |
# https://github.com/frawau/aioblescan/blob/master/aioblescan/__main__.py#L27 | |
# enable bluetooth without sudo https://www.raspberrypi.org/forums/viewtopic.php?t=108581 | |
import asyncio | |
import aioblescan as aiobs | |
from datetime import datetime | |
from aioblescan.plugins import EddyStone | |
def my_process(data): | |
ev = aiobs.HCI_Event() | |
xx = ev.decode(data) | |
# filter by specific MAC address | |
mac = ev.retrieve("peer") | |
goon = False | |
for x in mac: | |
if x.val == '00:00:00:00:00:00': # replace with your micro:bit's MAC address | |
goon = True | |
break | |
if not goon: | |
return | |
# decode beacon data as Eddystone | |
xx = EddyStone().decode(ev) | |
if xx: | |
# parse the url and get the last 3 parts split by '/' | |
print("{} - {}".format(datetime.utcnow().isoformat(), xx['url'].split('/')[:-3])) | |
# 2020-09-04T22:06:47.161415 - ['878', '254', '248'] | |
event_loop = asyncio.get_event_loop() | |
# First create and configure a raw socket | |
# device hci0 | |
mysocket = aiobs.create_bt_socket(0) | |
# create a connection with the raw socket | |
fac = event_loop._create_connection_transport(mysocket, aiobs.BLEScanRequester, None, None) | |
# Start it | |
conn, btctrl = event_loop.run_until_complete(fac) | |
# Attach your processing | |
btctrl.process = my_process | |
# Probe | |
btctrl.send_scan_request() | |
try: | |
event_loop.run_forever() | |
except KeyboardInterrupt: | |
print('keyboard interrupt') | |
finally: | |
print('closing event loop') | |
btctrl.stop_scan_request() | |
command = aiobs.HCI_Cmd_LE_Advertise(enable=False) | |
btctrl.send_command(command) | |
conn.close() | |
event_loop.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
aioblescan--0.2.6 | |
asyncio==3.4.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment