• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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():
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_source, hci_sink):
41        print('<<< connected')
42
43        # Create a device
44        device = Device.from_config_file_with_hci(sys.argv[1], hci_source, hci_sink)
45        await device.power_on()
46
47        # Connect to the peer
48        target_address = sys.argv[3]
49        print(f'=== Connecting to {target_address}...')
50        connection = await device.connect(target_address)
51        print('=== Connected')
52        print('*** Encrypting...')
53        try:
54            await connection.encrypt()
55        except Exception as error:
56            print(f'!!! Encryption failed: {error}')
57            return
58
59        await hci_source.wait_for_termination()
60
61
62# -----------------------------------------------------------------------------
63logging.basicConfig(level=os.environ.get('BUMBLE_LOGLEVEL', 'DEBUG').upper())
64asyncio.run(main())
65