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 readline
30import shlex
31from ble.ble_stream_secure import BleStreamSecure
32from cli.base_commands import (HelpCommand, HelloCommand, CommissionCommand, ThreadStateCommand, ScanCommand)
33from cli.dataset_commands import (DatasetCommand)
34from dataset.dataset import ThreadDataset
35from typing import Optional
36
37
38class CLI:
39
40    def __init__(self, dataset: ThreadDataset, ble_sstream: Optional[BleStreamSecure] = None):
41        self._commands = {
42            'help': HelpCommand(),
43            'hello': HelloCommand(),
44            'commission': CommissionCommand(),
45            'dataset': DatasetCommand(),
46            'thread': ThreadStateCommand(),
47            'scan': ScanCommand(),
48        }
49        self._context = {'ble_sstream': ble_sstream, 'dataset': dataset, 'commands': self._commands}
50        readline.set_completer(self.completer)
51        readline.parse_and_bind('tab: complete')
52
53    def completer(self, text, state):
54        command_pool = self._commands.keys()
55        full_line = readline.get_line_buffer().lstrip()
56        words = full_line.split()
57
58        should_suggest_subcommands = len(words) > 1 or (len(words) == 1 and full_line[-1].isspace())
59        if should_suggest_subcommands:
60            if words[0] not in self._commands.keys():
61                return None
62
63            current_command = self._commands[words[0]]
64            if full_line[-1].isspace():
65                subcommands = words[1:]
66            else:
67                subcommands = words[1:-1]
68            for nextarg in subcommands:
69                if nextarg in current_command._subcommands.keys():
70                    current_command = current_command._subcommands[nextarg]
71                else:
72                    return None
73
74            if len(current_command._subcommands) == 0:
75                return None
76
77            command_pool = current_command._subcommands.keys()
78
79        options = [c for c in command_pool if c.startswith(text)]
80        if state < len(options):
81            return options[state]
82        else:
83            return None
84
85    async def evaluate_input(self, user_input):
86        # do not parse empty commands
87        if not user_input.strip():
88            return
89
90        command_parts = shlex.split(user_input)
91        command = command_parts[0]
92        args = command_parts[1:]
93
94        if command not in self._commands.keys():
95            raise Exception('Invalid command: {}'.format(command))
96
97        return await self._commands[command].execute(args, self._context)
98