Last active
June 26, 2024 06:44
-
-
Save rbaron/764d6d78b49e4f1572119c899142cc95 to your computer and use it in GitHub Desktop.
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
""" | |
Detection callback w/ scanner | |
-------------- | |
Example showing what is returned using the callback upon detection functionality | |
Updated on 2020-10-11 by bernstern <bernie@allthenticate.net> | |
""" | |
import argparse | |
import asyncio | |
import logging | |
from bleak import BleakScanner | |
from bleak.backends.device import BLEDevice | |
from bleak.backends.scanner import AdvertisementData | |
logger = logging.getLogger(__name__) | |
def simple_callback(device: BLEDevice, advertisement_data: AdvertisementData): | |
if device.address.lower() == "E4:5A:3D:03:C4:18".lower(): | |
# logger.info("%s: %r", device.address, advertisement_data) | |
logger.info("Name: %s", advertisement_data.local_name) | |
for ad_type, ad_data in advertisement_data.service_data.items(): | |
logger.info("Service %s: %s", ad_type, ad_data.hex()) | |
async def main(args: argparse.Namespace): | |
scanner = BleakScanner( | |
simple_callback, args.services, cb=dict(use_bdaddr=args.macos_use_bdaddr) | |
) | |
while True: | |
logger.debug("(re)starting scanner") | |
await scanner.start() | |
await asyncio.sleep(5.0) | |
await scanner.stop() | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"--macos-use-bdaddr", | |
action="store_true", | |
help="when true use Bluetooth address instead of UUID on macOS", | |
) | |
parser.add_argument( | |
"--services", | |
metavar="<uuid>", | |
nargs="*", | |
help="UUIDs of one or more services to filter for", | |
) | |
parser.add_argument( | |
"-d", | |
"--debug", | |
action="store_true", | |
help="sets the logging level to debug", | |
) | |
args = parser.parse_args() | |
log_level = logging.DEBUG if args.debug else logging.INFO | |
logging.basicConfig( | |
level=log_level, | |
format="%(asctime)-15s %(name)-8s %(levelname)s: %(message)s", | |
) | |
asyncio.run(main(args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment