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
22
23from bumble.device import Device
24from bumble.transport import open_transport_or_link
25
26
27# -----------------------------------------------------------------------------
28async def main() -> None:
29    if len(sys.argv) < 3:
30        print(
31            'Usage: run_connect_and_encrypt.py <device-config> <transport-spec> '
32            '<bluetooth-address>'
33        )
34        print(
35            'example: run_connect_and_encrypt.py device1.json usb:0 E1:CA:72:48:C4:E8'
36        )
37        return
38
39    print('<<< connecting to HCI...')
40    async with await open_transport_or_link(sys.argv[2]) as hci_transport:
41        print('<<< connected')
42
43        # Create a device
44        device = Device.from_config_file_with_hci(
45            sys.argv[1], hci_transport.source, hci_transport.sink
46        )
47        await device.power_on()
48
49        # Connect to the peer
50        target_address = sys.argv[3]
51        print(f'=== Connecting to {target_address}...')
52        connection = await device.connect(target_address)
53        print('=== Connected')
54        print('*** Encrypting...')
55        try:
56            await connection.encrypt()
57        except Exception as error:
58            print(f'!!! Encryption failed: {error}')
59            return
60
61        await hci_transport.source.wait_for_termination()
62
63
64# -----------------------------------------------------------------------------
65logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper())
66asyncio.run(main())
67