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"""
28import readline
29import shlex
30from argparse import ArgumentParser
31from ble.ble_stream_secure import BleStreamSecure
32from cli.base_commands import (DisconnectCommand, HelpCommand, HelloCommand, CommissionCommand, DecommissionCommand,
33                               GetDeviceIdCommand, GetPskdHash, GetExtPanIDCommand, GetNetworkNameCommand,
34                               GetProvisioningUrlCommand, PingCommand, GetRandomNumberChallenge, ThreadStateCommand,
35                               ScanCommand, PresentHash)
36from .tlv_commands import TlvCommand
37from cli.dataset_commands import (DatasetCommand)
38from dataset.dataset import ThreadDataset
39from typing import Optional
40
41
42class CLI:
43
44    def __init__(self,
45                 dataset: ThreadDataset,
46                 cmd_args: Optional[ArgumentParser] = None,
47                 ble_sstream: Optional[BleStreamSecure] = None):
48        self._commands = {
49            'help': HelpCommand(),
50            'hello': HelloCommand(),
51            'commission': CommissionCommand(),
52            'decommission': DecommissionCommand(),
53            'disconnect': DisconnectCommand(),
54            'device_id': GetDeviceIdCommand(),
55            'ext_panid': GetExtPanIDCommand(),
56            'provisioning_url': GetProvisioningUrlCommand(),
57            'network_name': GetNetworkNameCommand(),
58            'ping': PingCommand(),
59            'dataset': DatasetCommand(),
60            'thread': ThreadStateCommand(),
61            'scan': ScanCommand(),
62            'random_challenge': GetRandomNumberChallenge(),
63            'present_hash': PresentHash(),
64            'peer_pskd_hash': GetPskdHash(),
65            'tlv': TlvCommand()
66        }
67        self._context = {
68            'ble_sstream': ble_sstream,
69            'dataset': dataset,
70            'commands': self._commands,
71            'cmd_args': cmd_args
72        }
73        readline.set_completer(self.completer)
74        readline.parse_and_bind('tab: complete')
75
76    def completer(self, text, state):
77        command_pool = self._commands.keys()
78        full_line = readline.get_line_buffer().lstrip()
79        words = full_line.split()
80
81        should_suggest_subcommands = len(words) > 1 or (len(words) == 1 and full_line[-1].isspace())
82        if should_suggest_subcommands:
83            if words[0] not in self._commands.keys():
84                return None
85
86            current_command = self._commands[words[0]]
87            if full_line[-1].isspace():
88                subcommands = words[1:]
89            else:
90                subcommands = words[1:-1]
91            for nextarg in subcommands:
92                if nextarg in current_command._subcommands.keys():
93                    current_command = current_command._subcommands[nextarg]
94                else:
95                    return None
96
97            if len(current_command._subcommands) == 0:
98                return None
99
100            command_pool = current_command._subcommands.keys()
101
102        options = [c for c in command_pool if c.startswith(text)]
103        if state < len(options):
104            return options[state]
105        else:
106            return None
107
108    async def evaluate_input(self, user_input):
109        # do not parse empty commands
110        if not user_input.strip():
111            return
112
113        command_parts = shlex.split(user_input)
114        command = command_parts[0]
115        args = command_parts[1:]
116
117        if command not in self._commands.keys():
118            raise Exception('Invalid command: {}'.format(command))
119
120        return await self._commands[command].execute(args, self._context)
121