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 22import random 23import struct 24 25from bumble.core import AdvertisingData 26from bumble.device import Device 27from bumble.transport import open_transport_or_link 28from bumble.profiles.battery_service import BatteryService 29 30 31# ----------------------------------------------------------------------------- 32async def main(): 33 if len(sys.argv) != 3: 34 print('Usage: python battery_server.py <device-config> <transport-spec>') 35 print('example: python battery_server.py device1.json usb:0') 36 return 37 38 async with await open_transport_or_link(sys.argv[2]) as (hci_source, hci_sink): 39 device = Device.from_config_file_with_hci(sys.argv[1], hci_source, hci_sink) 40 41 # Add a Battery Service to the GATT sever 42 battery_service = BatteryService(lambda _: random.randint(0, 100)) 43 device.add_service(battery_service) 44 45 # Set the advertising data 46 device.advertising_data = bytes( 47 AdvertisingData( 48 [ 49 ( 50 AdvertisingData.COMPLETE_LOCAL_NAME, 51 bytes('Bumble Battery', 'utf-8'), 52 ), 53 ( 54 AdvertisingData.INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 55 bytes(battery_service.uuid), 56 ), 57 (AdvertisingData.APPEARANCE, struct.pack('<H', 0x0340)), 58 ] 59 ) 60 ) 61 62 # Go! 63 await device.power_on() 64 await device.start_advertising(auto_restart=True) 65 66 # Notify every 3 seconds 67 while True: 68 await asyncio.sleep(3.0) 69 await device.notify_subscribers( 70 battery_service.battery_level_characteristic 71 ) 72 73 74# ----------------------------------------------------------------------------- 75logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper()) 76asyncio.run(main()) 77