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 logging 20import sys 21import os 22import struct 23 24from bumble.core import AdvertisingData 25from bumble.device import AdvertisingType, Device 26from bumble.hci import Address 27from bumble.transport import open_transport_or_link 28 29 30# ----------------------------------------------------------------------------- 31async def main() -> None: 32 if len(sys.argv) < 3: 33 print( 34 'Usage: run_advertiser.py <config-file> <transport-spec> [type] [address]' 35 ) 36 print('example: run_advertiser.py device1.json usb:0') 37 return 38 39 if len(sys.argv) >= 4: 40 advertising_type = AdvertisingType(int(sys.argv[3])) 41 else: 42 advertising_type = AdvertisingType.UNDIRECTED_CONNECTABLE_SCANNABLE 43 44 if advertising_type.is_directed: 45 if len(sys.argv) < 5: 46 print('<address> required for directed advertising') 47 return 48 target = Address(sys.argv[4]) 49 else: 50 target = None 51 52 print('<<< connecting to HCI...') 53 async with await open_transport_or_link(sys.argv[2]) as hci_transport: 54 print('<<< connected') 55 56 device = Device.from_config_file_with_hci( 57 sys.argv[1], hci_transport.source, hci_transport.sink 58 ) 59 60 if advertising_type.is_scannable: 61 device.scan_response_data = bytes( 62 AdvertisingData( 63 [ 64 (AdvertisingData.APPEARANCE, struct.pack('<H', 0x0340)), 65 ] 66 ) 67 ) 68 69 await device.power_on() 70 await device.start_advertising(advertising_type=advertising_type, target=target) 71 await hci_transport.source.wait_for_termination() 72 73 74# ----------------------------------------------------------------------------- 75logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper()) 76asyncio.run(main()) 77