1# Copyright 2021-2022 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15# ----------------------------------------------------------------------------- 16# Imports 17# ----------------------------------------------------------------------------- 18import asyncio 19import sys 20import os 21import logging 22from bumble.colors import color 23from bumble.hci import Address 24from bumble.device import Device 25from bumble.transport import open_transport_or_link 26 27 28# ----------------------------------------------------------------------------- 29async def main() -> None: 30 if len(sys.argv) < 2: 31 print('Usage: run_scanner.py <transport-spec> [filter]') 32 print('example: run_scanner.py usb:0') 33 return 34 35 print('<<< connecting to HCI...') 36 async with await open_transport_or_link(sys.argv[1]) as hci_transport: 37 print('<<< connected') 38 filter_duplicates = len(sys.argv) == 3 and sys.argv[2] == 'filter' 39 40 device = Device.with_hci( 41 'Bumble', 42 Address('F0:F1:F2:F3:F4:F5'), 43 hci_transport.source, 44 hci_transport.sink, 45 ) 46 47 def on_adv(advertisement): 48 address_type_string = ('PUBLIC', 'RANDOM', 'PUBLIC_ID', 'RANDOM_ID')[ 49 advertisement.address.address_type 50 ] 51 address_color = 'yellow' if advertisement.is_connectable else 'red' 52 address_qualifier = '' 53 if address_type_string.startswith('P'): 54 type_color = 'cyan' 55 else: 56 if advertisement.address.is_static: 57 type_color = 'green' 58 address_qualifier = '(static)' 59 elif advertisement.address.is_resolvable: 60 type_color = 'magenta' 61 address_qualifier = '(resolvable)' 62 else: 63 type_color = 'white' 64 65 separator = '\n ' 66 print( 67 f'>>> {color(advertisement.address, address_color)} ' 68 f'[{color(address_type_string, type_color)}]' 69 f'{address_qualifier}:{separator}RSSI: {advertisement.rssi}' 70 f'{separator}' 71 f'{advertisement.data.to_string(separator)}' 72 ) 73 74 device.on('advertisement', on_adv) 75 await device.power_on() 76 await device.start_scanning(filter_duplicates=filter_duplicates) 77 78 await hci_transport.source.wait_for_termination() 79 80 81# ----------------------------------------------------------------------------- 82logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper()) 83asyncio.run(main()) 84