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 random
22import logging
23
24from bumble.device import Device, Connection
25from bumble.transport import open_transport_or_link
26from bumble.gatt import Service, Characteristic
27
28
29# -----------------------------------------------------------------------------
30class Listener(Device.Listener, Connection.Listener):
31    def __init__(self, device):
32        self.device = device
33
34    def on_connection(self, connection):
35        print(f'=== Connected to {connection}')
36        connection.listener = self
37
38    def on_disconnection(self, reason):
39        print(f'### Disconnected, reason={reason}')
40
41    def on_characteristic_subscription(
42        self, connection, characteristic, notify_enabled, indicate_enabled
43    ):
44        print(
45            f'$$$ Characteristic subscription for handle {characteristic.handle} '
46            f'from {connection}: '
47            f'notify {"enabled" if notify_enabled else "disabled"}, '
48            f'indicate {"enabled" if indicate_enabled else "disabled"}'
49        )
50
51
52# -----------------------------------------------------------------------------
53# Alternative way to listen for subscriptions
54# -----------------------------------------------------------------------------
55def on_my_characteristic_subscription(peer, enabled):
56    print(f'### My characteristic from {peer}: {"enabled" if enabled else "disabled"}')
57
58
59# -----------------------------------------------------------------------------
60async def main() -> None:
61    if len(sys.argv) < 3:
62        print('Usage: run_notifier.py <device-config> <transport-spec>')
63        print('example: run_notifier.py device1.json usb:0')
64        return
65
66    print('<<< connecting to HCI...')
67    async with await open_transport_or_link(sys.argv[2]) as hci_transport:
68        print('<<< connected')
69
70        # Create a device to manage the host
71        device = Device.from_config_file_with_hci(
72            sys.argv[1], hci_transport.source, hci_transport.sink
73        )
74        device.listener = Listener(device)
75
76        # Add a few entries to the device's GATT server
77        characteristic1 = Characteristic(
78            '486F64C6-4B5F-4B3B-8AFF-EDE134A8446A',
79            Characteristic.Properties.READ | Characteristic.Properties.NOTIFY,
80            Characteristic.READABLE,
81            bytes([0x40]),
82        )
83        characteristic2 = Characteristic(
84            '8EBDEBAE-0017-418E-8D3B-3A3809492165',
85            Characteristic.Properties.READ | Characteristic.Properties.INDICATE,
86            Characteristic.READABLE,
87            bytes([0x41]),
88        )
89        characteristic3 = Characteristic(
90            '8EBDEBAE-0017-418E-8D3B-3A3809492165',
91            Characteristic.Properties.READ
92            | Characteristic.Properties.NOTIFY
93            | Characteristic.Properties.INDICATE,
94            Characteristic.READABLE,
95            bytes([0x42]),
96        )
97        characteristic3.on('subscription', on_my_characteristic_subscription)
98        custom_service = Service(
99            '50DB505C-8AC4-4738-8448-3B1D9CC09CC5',
100            [characteristic1, characteristic2, characteristic3],
101        )
102        device.add_services([custom_service])
103
104        # Debug print
105        for attribute in device.gatt_server.attributes:
106            print(attribute)
107
108        # Get things going
109        await device.power_on()
110
111        # Connect to a peer
112        if len(sys.argv) > 3:
113            target_address = sys.argv[3]
114            print(f'=== Connecting to {target_address}...')
115            await device.connect(target_address)
116        else:
117            await device.start_advertising(auto_restart=True)
118
119        while True:
120            await asyncio.sleep(3.0)
121            characteristic1.value = bytes([random.randint(0, 255)])
122            await device.notify_subscribers(characteristic1)
123            characteristic2.value = bytes([random.randint(0, 255)])
124            await device.indicate_subscribers(characteristic2)
125            characteristic3.value = bytes([random.randint(0, 255)])
126            await device.notify_subscribers(characteristic3)
127            await device.indicate_subscribers(characteristic3)
128
129
130# -----------------------------------------------------------------------------
131logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper())
132asyncio.run(main())
133