1"""
2  Copyright (c) 2024, The OpenThread Authors.
3  All rights reserved.
4
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions are met:
7  1. Redistributions of source code must retain the above copyright
8     notice, this list of conditions and the following disclaimer.
9  2. Redistributions in binary form must reproduce the above copyright
10     notice, this list of conditions and the following disclaimer in the
11     documentation and/or other materials provided with the distribution.
12  3. Neither the name of the copyright holder nor the
13     names of its contributors may be used to endorse or promote products
14     derived from this software without specific prior written permission.
15
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  POSSIBILITY OF SUCH DAMAGE.
27"""
28
29import asyncio
30import argparse
31import logging
32import os
33
34from ble.ble_connection_constants import BBTC_SERVICE_UUID, BBTC_TX_CHAR_UUID, \
35    BBTC_RX_CHAR_UUID
36from ble.ble_stream import BleStream
37from ble.ble_stream_secure import BleStreamSecure
38from ble.udp_stream import UdpStream
39from ble import ble_scanner
40from cli.cli import CLI
41from dataset.dataset import ThreadDataset
42from cli.command import CommandResult
43from utils import select_device_by_user_input, quit_with_reason
44
45logger = logging.getLogger(__name__)
46
47
48async def main():
49    logging.basicConfig(level=logging.WARNING)
50
51    parser = argparse.ArgumentParser(description='Device parameters')
52    parser.add_argument('--debug', help='Enable debug logs', action='store_true')
53    parser.add_argument('--info', help='Enable info logs', action='store_true')
54    parser.add_argument('--cert_path', help='Path to certificate chain and key', action='store', default='auth')
55    group = parser.add_mutually_exclusive_group()
56    group.add_argument('--mac', type=str, help='Device MAC address', action='store')
57    group.add_argument('--name', type=str, help='Device name', action='store')
58    group.add_argument('--scan', help='Scan all available devices', action='store_true')
59    group.add_argument('--simulation', help='Connect to simulation node id', action='store')
60    args = parser.parse_args()
61
62    if args.debug:
63        logger.setLevel(logging.DEBUG)
64        logging.getLogger('ble.ble_stream').setLevel(logging.DEBUG)
65        logging.getLogger('ble.ble_stream_secure').setLevel(logging.DEBUG)
66        logging.getLogger('ble.udp_stream').setLevel(logging.DEBUG)
67    elif args.info:
68        logger.setLevel(logging.INFO)
69        logging.getLogger('ble.ble_stream').setLevel(logging.INFO)
70        logging.getLogger('ble.ble_stream_secure').setLevel(logging.INFO)
71        logging.getLogger('ble.udp_stream').setLevel(logging.INFO)
72
73    device = await get_device_by_args(args)
74
75    ble_sstream = None
76
77    if device is not None:
78        print(f'Connecting to {device}')
79        ble_sstream = BleStreamSecure(device)
80        ble_sstream.load_cert(
81            certfile=os.path.join(args.cert_path, 'commissioner_cert.pem'),
82            keyfile=os.path.join(args.cert_path, 'commissioner_key.pem'),
83            cafile=os.path.join(args.cert_path, 'ca_cert.pem'),
84        )
85        logger.info(f"Certificates and key loaded from '{args.cert_path}'")
86
87        print('Setting up secure TLS channel..', end='')
88        try:
89            await ble_sstream.do_handshake()
90            print('\nDone')
91            ble_sstream.log_cert_identities()
92        except Exception as e:
93            print('\nFailed')
94            logger.error(e)
95            ble_sstream.log_cert_identities()
96            quit_with_reason('TLS handshake failure')
97
98    ds = ThreadDataset()
99    cli = CLI(ds, ble_sstream)
100    loop = asyncio.get_running_loop()
101    print('Enter \'help\' to see available commands' ' or \'exit\' to exit the application.')
102    while True:
103        user_input = await loop.run_in_executor(None, lambda: input('> '))
104        if user_input.lower() == 'exit':
105            print('Disconnecting...')
106            if ble_sstream is not None:
107                await ble_sstream.close()
108            break
109        try:
110            result: CommandResult = await cli.evaluate_input(user_input)
111            if result:
112                result.pretty_print()
113        except Exception as e:
114            logger.error(e)
115
116
117async def get_device_by_args(args):
118    device = None
119    if args.mac:
120        device = await ble_scanner.find_first_by_mac(args.mac)
121        device = await BleStream.create(device.address, BBTC_SERVICE_UUID, BBTC_TX_CHAR_UUID, BBTC_RX_CHAR_UUID)
122    elif args.name:
123        device = await ble_scanner.find_first_by_name(args.name)
124        device = await BleStream.create(device.address, BBTC_SERVICE_UUID, BBTC_TX_CHAR_UUID, BBTC_RX_CHAR_UUID)
125    elif args.scan:
126        tcat_devices = await ble_scanner.scan_tcat_devices()
127        device = select_device_by_user_input(tcat_devices)
128        device = await BleStream.create(device.address, BBTC_SERVICE_UUID, BBTC_TX_CHAR_UUID, BBTC_RX_CHAR_UUID)
129    elif args.simulation:
130        device = UdpStream("127.0.0.1", int(args.simulation))
131
132    return device
133
134
135if __name__ == '__main__':
136    try:
137        asyncio.run(main())
138    except asyncio.CancelledError:
139        pass  # device disconnected
140