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() -> None:
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_transport:
39        device = Device.from_config_file_with_hci(
40            sys.argv[1], hci_transport.source, hci_transport.sink
41        )
42
43        # Add a Battery Service to the GATT sever
44        battery_service = BatteryService(lambda _: random.randint(0, 100))
45        device.add_service(battery_service)
46
47        # Set the advertising data
48        device.advertising_data = bytes(
49            AdvertisingData(
50                [
51                    (
52                        AdvertisingData.COMPLETE_LOCAL_NAME,
53                        bytes('Bumble Battery', 'utf-8'),
54                    ),
55                    (
56                        AdvertisingData.INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS,
57                        bytes(battery_service.uuid),
58                    ),
59                    (AdvertisingData.APPEARANCE, struct.pack('<H', 0x0340)),
60                ]
61            )
62        )
63
64        # Go!
65        await device.power_on()
66        await device.start_advertising(auto_restart=True)
67
68        # Notify every 3 seconds
69        while True:
70            await asyncio.sleep(3.0)
71            await device.notify_subscribers(
72                battery_service.battery_level_characteristic
73            )
74
75
76# -----------------------------------------------------------------------------
77logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper())
78asyncio.run(main())
79