initial commit

This commit is contained in:
proddy
2020-07-05 18:29:08 +02:00
parent 26b201ea2f
commit c5933e8c14
739 changed files with 86566 additions and 20952 deletions

View File

@@ -0,0 +1,166 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <string>
#include <vector>
namespace uuid {
namespace console {
CommandLine::CommandLine(const std::string & line) {
bool string_escape_double = false;
bool string_escape_single = false;
bool char_escape = false;
bool quoted_argument = false;
if (!line.empty()) {
parameters_.emplace_back(std::string{});
}
for (char c : line) {
switch (c) {
case ' ':
if (string_escape_double || string_escape_single) {
if (char_escape) {
parameters_.back().push_back('\\');
char_escape = false;
}
parameters_.back().push_back(' ');
} else if (char_escape) {
parameters_.back().push_back(' ');
char_escape = false;
} else {
// Begin a new argument if the previous
// one is not empty or it was quoted
if (quoted_argument || !parameters_.back().empty()) {
parameters_.emplace_back(std::string{});
}
quoted_argument = false;
}
break;
case '"':
if (char_escape || string_escape_single) {
parameters_.back().push_back('"');
char_escape = false;
} else {
string_escape_double = !string_escape_double;
quoted_argument = true;
}
break;
case '\'':
if (char_escape || string_escape_double) {
parameters_.back().push_back('\'');
char_escape = false;
} else {
string_escape_single = !string_escape_single;
quoted_argument = true;
}
break;
case '\\':
if (char_escape) {
parameters_.back().push_back('\\');
char_escape = false;
} else {
char_escape = true;
}
break;
default:
if (char_escape) {
parameters_.back().push_back('\\');
char_escape = false;
}
parameters_.back().push_back(c);
break;
}
}
if (!parameters_.empty() && parameters_.back().empty() && !quoted_argument) {
parameters_.pop_back();
if (!parameters_.empty()) {
trailing_space = true;
}
}
}
CommandLine::CommandLine(std::initializer_list<const std::vector<std::string>> arguments) {
for (auto & argument : arguments) {
parameters_.insert(parameters_.end(), argument.begin(), argument.end());
}
}
std::string CommandLine::to_string(size_t reserve) const {
std::string line;
size_t escape = escape_parameters_;
line.reserve(reserve);
for (auto & item : parameters_) {
if (!line.empty()) {
line += ' ';
}
if (item.empty()) {
line += '\"';
line += '\"';
goto next;
}
for (char c : item) {
switch (c) {
case ' ':
case '\"':
case '\'':
case '\\':
if (escape > 0) {
line += '\\';
}
break;
}
line += c;
}
next:
if (escape > 0) {
escape--;
}
}
if (trailing_space && !line.empty()) {
line += ' ';
}
return line;
}
void CommandLine::reset() {
parameters_.clear();
escape_all_parameters();
trailing_space = false;
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,550 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a std::copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <Arduino.h>
#include <algorithm>
#include <memory>
#include <map>
#include <set>
#include <string>
#include <vector>
#ifndef __cpp_lib_make_unique
namespace std {
template <typename _Tp, typename... _Args>
inline unique_ptr<_Tp> make_unique(_Args &&... __args) {
return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...));
}
} // namespace std
#endif
namespace uuid {
namespace console {
void Commands::add_command(const flash_string_vector & name, command_function function) {
add_command(0, 0, name, flash_string_vector{}, function, nullptr);
}
void Commands::add_command(const flash_string_vector & name, const flash_string_vector & arguments, command_function function) {
add_command(0, 0, name, arguments, function, nullptr);
}
void Commands::add_command(const flash_string_vector & name,
const flash_string_vector & arguments,
command_function function,
argument_completion_function arg_function) {
add_command(0, 0, name, arguments, function, arg_function);
}
void Commands::add_command(unsigned int context, unsigned int flags, const flash_string_vector & name, command_function function) {
add_command(context, flags, name, flash_string_vector{}, function, nullptr);
}
void Commands::add_command(unsigned int context,
unsigned int flags,
const flash_string_vector & name,
const flash_string_vector & arguments,
command_function function) {
add_command(context, flags, name, arguments, function, nullptr);
}
void Commands::add_command(unsigned int context,
unsigned int flags,
const flash_string_vector & name,
const flash_string_vector & arguments,
command_function function,
argument_completion_function arg_function) {
commands_.emplace(std::piecewise_construct, std::forward_as_tuple(context), std::forward_as_tuple(flags, name, arguments, function, arg_function));
}
// added by proddy
// note we should really iterate and free up the lambda code and any flashstrings
void Commands::remove_all_commands() {
commands_.clear();
}
// added by proddy
// note we should really iterate and free up the lambda code and any flashstrings
void Commands::remove_context_commands(unsigned int context) {
commands_.erase(context);
/*
auto commands = commands_.equal_range(context);
for (auto command_it = commands.first; command_it != commands.second; command_it++) {
shell.printf("Got: ");
for (auto flash_name : command_it->second.name_) {
shell.printf("%s ", read_flash_string(flash_name).c_str());
}
shell.println();
}
size_t nun = commands_.erase(context);
shell.printfln("Erased %d commands", nun);
*/
}
Commands::Execution Commands::execute_command(Shell & shell, CommandLine && command_line) {
auto commands = find_command(shell, command_line);
auto longest = commands.exact.crbegin();
Execution result;
result.error = nullptr;
if (commands.exact.empty()) {
result.error = F("Command not found");
} else if (commands.exact.count(longest->first) == 1) {
auto & command = longest->second;
std::vector<std::string> arguments;
for (auto it = std::next(command_line->cbegin(), command->name_.size()); it != command_line->cend(); it++) {
arguments.push_back(std::move(*it));
}
command_line.reset();
if (commands.partial.upper_bound(longest->first) != commands.partial.end() && !arguments.empty()) {
result.error = F("Command not found");
} else if (arguments.size() < command->minimum_arguments()) {
result.error = F("Not enough arguments for command");
} else if (arguments.size() > command->maximum_arguments()) {
result.error = F("Too many arguments for command");
} else {
command->function_(shell, arguments);
}
} else {
result.error = F("Fatal error (multiple commands found)");
}
return result;
}
bool Commands::find_longest_common_prefix(const std::multimap<size_t, const Command *> & commands, std::vector<std::string> & longest_name) {
size_t component_prefix = 0;
size_t shortest_match = commands.begin()->first;
longest_name.reserve(shortest_match);
{
// Check if any of the commands have a common prefix of components
auto & first = commands.begin()->second->name_;
bool all_match = true;
for (size_t length = 0; all_match && length < shortest_match; length++) {
for (auto command_it = std::next(commands.begin()); command_it != commands.end(); command_it++) {
if (read_flash_string(*std::next(first.begin(), length)) != read_flash_string(*std::next(command_it->second->name_.begin(), length))) {
all_match = false;
break;
}
}
if (all_match) {
component_prefix = length + 1;
}
}
auto name_it = first.begin();
for (size_t i = 0; i < component_prefix; i++) {
longest_name.push_back(std::move(read_flash_string(*name_it)));
name_it++;
}
}
if (component_prefix < shortest_match) {
// Check if the next component has a common substring
auto first = *std::next(commands.begin()->second->name_.begin(), component_prefix);
bool all_match = true;
size_t chars_prefix = 0;
for (size_t length = 0; all_match; length++) {
for (auto command_it = std::next(commands.begin()); command_it != commands.end(); command_it++) {
// This relies on the null terminator character limiting the
// length before it becomes longer than any of the strings
if (pgm_read_byte(reinterpret_cast<PGM_P>(first) + length)
!= pgm_read_byte(reinterpret_cast<PGM_P>(*std::next(command_it->second->name_.begin(), component_prefix)) + length)) {
all_match = false;
break;
}
}
if (all_match) {
chars_prefix = length + 1;
}
}
if (chars_prefix > 0) {
longest_name.push_back(std::move(read_flash_string(first).substr(0, chars_prefix)));
return false;
}
}
return true;
}
std::string Commands::find_longest_common_prefix(const std::vector<std::string> & arguments) {
auto & first = *arguments.begin();
bool all_match = true;
size_t chars_prefix = 0;
for (size_t length = 0; all_match; length++) {
for (auto argument_it = std::next(arguments.begin()); argument_it != arguments.end(); argument_it++) {
// This relies on the null terminator character limiting the
// length before it becomes longer than any of the strings
if (first[length] != (*argument_it)[length]) {
all_match = false;
break;
}
}
if (all_match) {
chars_prefix = length + 1;
}
}
return arguments.begin()->substr(0, chars_prefix);
}
Commands::Completion Commands::complete_command(Shell & shell, const CommandLine & command_line) {
auto commands = find_command(shell, command_line);
Completion result;
auto match = commands.partial.begin();
size_t count;
if (match != commands.partial.end()) {
count = commands.partial.count(match->first);
} else if (!commands.exact.empty()) {
// Use prev() because both iterators must be forwards
match = std::prev(commands.exact.end());
count = commands.exact.count(match->first);
} else {
return result;
}
std::unique_ptr<Command> temp_command;
std::vector<std::string> temp_command_name;
std::multimap<size_t, const Command *>::iterator temp_command_it;
if (commands.partial.size() > 1 && (commands.exact.empty() || command_line.total_size() > commands.exact.begin()->second->name_.size())) {
// There are multiple partial matching commands, find the longest common prefix
bool whole_components = find_longest_common_prefix(commands.partial, temp_command_name);
if (count == 1 && whole_components && temp_command_name.size() == match->first) {
// If the longest common prefix is the same as the single shortest matching command
// then there's no need for a temporary command, but add a trailing space because
// there are longer commands that matched.
temp_command_name.clear();
result.replacement.trailing_space = true;
}
if (!temp_command_name.empty() && command_line.total_size() <= temp_command_name.size()) {
temp_command = std::make_unique<Command>(0, flash_string_vector{}, flash_string_vector{}, nullptr, nullptr);
count = 1;
match = commands.partial.end();
result.replacement.trailing_space = whole_components;
for (auto & name : temp_command_name) {
result.replacement->emplace_back(name);
}
}
}
if (count == 1 && !temp_command) {
// Construct a replacement string for a single matching command
auto & matching_command = match->second;
for (auto & name : matching_command->name_) {
result.replacement->push_back(std::move(read_flash_string(name)));
}
if (command_line.total_size() > result.replacement->size()
&& command_line.total_size() <= matching_command->name_.size() + matching_command->maximum_arguments()) {
// Try to auto-complete arguments
std::vector<std::string> arguments{std::next(command_line->cbegin(), result.replacement->size()), command_line->cend()};
result.replacement->insert(result.replacement->end(), arguments.cbegin(), arguments.cend());
result.replacement.trailing_space = command_line.trailing_space;
auto current_args_count = arguments.size();
std::string last_argument;
if (!command_line.trailing_space) {
// Remove the last argument so that it can be auto-completed
last_argument = std::move(result.replacement->back());
result.replacement->pop_back();
if (!arguments.empty()) {
arguments.pop_back();
current_args_count--;
}
}
auto potential_arguments = matching_command->arg_function_ ? matching_command->arg_function_(shell, arguments) : std::vector<std::string>{};
// Remove arguments that can't match
if (!command_line.trailing_space) {
for (auto it = potential_arguments.begin(); it != potential_arguments.end();) {
if (it->rfind(last_argument, 0) == std::string::npos) {
it = potential_arguments.erase(it);
} else {
it++;
}
}
}
// Auto-complete if there's something present in the last argument
// or the only potential argument is an empty string.
if (!command_line.trailing_space) {
if (potential_arguments.size() == 1) {
if (last_argument == *potential_arguments.begin()) {
if (result.replacement->size() + 1 < matching_command->name_.size() + matching_command->maximum_arguments()) {
// Add a space because this argument is complete and there are more arguments for this command
result.replacement.trailing_space = true;
}
}
last_argument = *potential_arguments.begin();
potential_arguments.clear();
// Remaining help should skip the replaced argument
current_args_count++;
} else if (potential_arguments.size() > 1) {
last_argument = find_longest_common_prefix(potential_arguments);
}
}
// Put the last argument back
if (!command_line.trailing_space) {
result.replacement->push_back(std::move(last_argument));
}
CommandLine remaining_help;
if (!potential_arguments.empty()) {
// Remaining help should skip the suggested argument
current_args_count++;
}
if (current_args_count < matching_command->maximum_arguments()) {
remaining_help.escape_initial_parameters();
for (auto it = std::next(matching_command->arguments_.cbegin(), current_args_count); it != matching_command->arguments_.cend(); it++) {
remaining_help->push_back(std::move(read_flash_string(*it)));
}
}
if (potential_arguments.empty()) {
if (!remaining_help->empty()) {
result.help.push_back(std::move(remaining_help));
}
} else {
for (auto potential_argument : potential_arguments) {
CommandLine help;
help->emplace_back(potential_argument);
if (!remaining_help->empty()) {
help.escape_initial_parameters();
help->insert(help->end(), remaining_help->begin(), remaining_help->end());
}
result.help.push_back(std::move(help));
}
}
} else if (result.replacement->size() < matching_command->name_.size() + matching_command->maximum_arguments()) {
// Add a space because there are more arguments for this command
result.replacement.trailing_space = true;
}
} else if (count > 1 || temp_command) {
// Provide help for all of the potential commands
for (auto command_it = commands.partial.begin(); command_it != commands.partial.end(); command_it++) {
CommandLine help;
auto line_it = command_line->cbegin();
auto flash_name_it = command_it->second->name_.cbegin();
if (temp_command) {
// Skip parts of the command name/line when the longest common prefix was used
size_t skip = temp_command_name.size();
if (!result.replacement.trailing_space) {
skip--;
}
flash_name_it += skip;
while (line_it != command_line->cend()) {
line_it++;
}
}
for (; flash_name_it != command_it->second->name_.cend(); flash_name_it++) {
std::string name = read_flash_string(*flash_name_it);
// Skip parts of the command name that match the command line
if (line_it != command_line->cend()) {
if (name == *line_it++) {
continue;
} else {
line_it = command_line->cend();
}
}
help->emplace_back(name);
}
help.escape_initial_parameters();
for (auto argument : command_it->second->arguments_) {
// Skip parts of the command arguments that exist in the command line
if (line_it != command_line->cend()) {
line_it++;
continue;
}
help->push_back(std::move(read_flash_string(argument)));
}
result.help.push_back(std::move(help));
}
}
if (count > 1 && !commands.exact.empty()) {
// Try to add a space to exact matches
auto longest = commands.exact.crbegin();
if (commands.exact.count(longest->first) == 1) {
for (auto & name : longest->second->name_) {
result.replacement->push_back(std::move(read_flash_string(name)));
}
// Add a space because there are sub-commands for a command that has matched exactly
result.replacement.trailing_space = true;
}
}
// Don't try to shorten the command line or offer an identical replacement
if (command_line.total_size() > result.replacement.total_size() || result.replacement == command_line) {
result.replacement.reset();
}
return result;
}
Commands::Match Commands::find_command(Shell & shell, const CommandLine & command_line) {
Match commands;
auto context_commands = commands_.equal_range(shell.context());
for (auto it = context_commands.first; it != context_commands.second; it++) {
auto & command = it->second;
bool match = true;
bool exact = true;
if (!shell.has_flags(command.flags_)) {
continue;
}
auto name_it = command.name_.cbegin();
auto line_it = command_line->cbegin();
for (; name_it != command.name_.cend() && line_it != command_line->cend(); name_it++, line_it++) {
std::string name = read_flash_string(*name_it);
size_t found = name.rfind(*line_it, 0);
if (found == std::string::npos) {
match = false;
break;
} else if (line_it->length() != name.length()) {
for (auto line_check_it = std::next(line_it); line_check_it != command_line->cend(); line_check_it++) {
if (!line_check_it->empty()) {
// If there's more in the command line then this can't match
match = false;
}
}
if (command_line.trailing_space) {
// If there's a trailing space in the command line then this can't be a partial match
match = false;
}
// Don't check the rest of the command if this is only a partial match
break;
}
}
if (name_it != command.name_.cend()) {
exact = false;
}
if (match) {
if (exact) {
commands.exact.emplace(command.name_.size(), &command);
} else {
commands.partial.emplace(command.name_.size(), &command);
}
}
}
return commands;
}
void Commands::for_each_available_command(Shell & shell, apply_function f) const {
auto commands = commands_.equal_range(shell.context());
for (auto command_it = commands.first; command_it != commands.second; command_it++) {
if (shell.has_flags(command_it->second.flags_)) {
std::vector<std::string> name;
std::vector<std::string> arguments;
name.reserve(command_it->second.name_.size());
for (auto flash_name : command_it->second.name_) {
name.push_back(std::move(read_flash_string(flash_name)));
}
arguments.reserve(command_it->second.arguments_.size());
for (auto flash_argument : command_it->second.arguments_) {
arguments.push_back(std::move(read_flash_string(flash_argument)));
}
f(name, arguments);
}
}
}
Commands::Command::Command(unsigned int flags,
const flash_string_vector name,
const flash_string_vector arguments,
command_function function,
argument_completion_function arg_function)
: flags_(flags)
, name_(name)
, arguments_(arguments)
, function_(function)
, arg_function_(arg_function) {
}
Commands::Command::~Command() {
}
size_t Commands::Command::minimum_arguments() const {
return std::count_if(arguments_.cbegin(), arguments_.cend(), [](const __FlashStringHelper * argument) { return pgm_read_byte(argument) == '<'; });
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,19 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>

View File

@@ -0,0 +1,519 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <Arduino.h>
#include <stdarg.h>
#include <algorithm>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <uuid/common.h>
#include <uuid/log.h>
#ifndef __cpp_lib_make_unique
namespace std {
template <typename _Tp, typename... _Args>
inline unique_ptr<_Tp> make_unique(_Args &&... __args) {
return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...));
}
} // namespace std
#endif
namespace uuid {
namespace console {
// cppcheck-suppress passedByValue
Shell::Shell(std::shared_ptr<Commands> commands, unsigned int context, unsigned int flags)
: commands_(std::move(commands))
, flags_(flags) {
enter_context(context);
}
Shell::~Shell() {
uuid::log::Logger::unregister_handler(this);
}
void Shell::start() {
#ifdef EMSESP_DEBUG
uuid::log::Logger::register_handler(this, uuid::log::Level::DEBUG); // added by proddy
//uuid::log::Logger::register_handler(this, uuid::log::Level::INFO); // added by proddy
#else
uuid::log::Logger::register_handler(this, uuid::log::Level::NOTICE);
#endif
line_buffer_.reserve(maximum_command_line_length_);
display_banner();
display_prompt();
shells_.insert(shared_from_this());
idle_time_ = uuid::get_uptime_ms();
started();
};
void Shell::started() {
}
bool Shell::running() const {
return !stopped_;
}
void Shell::stop() {
if (mode_ == Mode::BLOCKING) {
auto * blocking_data = reinterpret_cast<Shell::BlockingData *>(mode_data_.get());
blocking_data->stop_ = true;
} else {
if (running()) {
stopped_ = true;
stopped();
}
}
}
void Shell::stopped() {
}
bool Shell::exit_context() {
if (context_.size() > 1) {
context_.pop_back();
return true;
} else {
return false;
}
}
void Shell::loop_one() {
if (!running()) {
return;
}
switch (mode_) {
case Mode::NORMAL:
output_logs();
loop_normal();
break;
case Mode::PASSWORD:
output_logs();
loop_password();
break;
case Mode::DELAY:
output_logs();
loop_delay();
break;
case Mode::BLOCKING:
loop_blocking();
break;
}
}
void Shell::loop_normal() {
const int input = read_one_char();
if (input < 0) {
check_idle_timeout();
return;
}
const unsigned char c = input;
switch (c) {
case '\x03':
// Interrupt (^C)
line_buffer_.clear();
println();
prompt_displayed_ = false;
display_prompt();
break;
case '\x04':
// End of transmission (^D)
if (line_buffer_.empty()) {
end_of_transmission();
}
break;
case '\x08':
case '\x7F':
// Backspace (^H)
// Delete (^?)
if (!line_buffer_.empty()) {
erase_characters(1);
line_buffer_.pop_back();
}
break;
case '\x09':
// Tab (^I)
process_completion();
break;
case '\x0A':
// Line feed (^J)
if (previous_ != '\x0D') {
process_command();
}
break;
case '\x0C':
// New page (^L)
erase_current_line();
prompt_displayed_ = false;
display_prompt();
break;
case '\x0D':
// Carriage return (^M)
process_command();
break;
case '\x15':
// Delete line (^U)
erase_current_line();
prompt_displayed_ = false;
line_buffer_.clear();
display_prompt();
break;
case '\x17':
// Delete word (^W)
delete_buffer_word(true);
break;
default:
if (c >= '\x20' && c <= '\x7E') {
// ASCII text
if (line_buffer_.length() < maximum_command_line_length_) {
line_buffer_.push_back(c);
write((uint8_t)c);
}
}
break;
}
previous_ = c;
// This is a hack to let TelnetStream know that command
// execution is complete and that output can be flushed.
available_char();
idle_time_ = uuid::get_uptime_ms();
}
Shell::PasswordData::PasswordData(const __FlashStringHelper * password_prompt, password_function && password_function)
: password_prompt_(password_prompt)
, password_function_(std::move(password_function)) {
}
void Shell::loop_password() {
const int input = read_one_char();
if (input < 0) {
check_idle_timeout();
return;
}
const unsigned char c = input;
switch (c) {
case '\x03':
// Interrupt (^C)
process_password(false);
break;
case '\x08':
case '\x7F':
// Backspace (^H)
// Delete (^?)
if (!line_buffer_.empty()) {
line_buffer_.pop_back();
}
break;
case '\x0A':
// Line feed (^J)
if (previous_ != '\x0D') {
process_password(true);
}
break;
case '\x0C':
// New page (^L)
erase_current_line();
prompt_displayed_ = false;
display_prompt();
break;
case '\x0D':
// Carriage return (^M)
process_password(true);
break;
case '\x15':
// Delete line (^U)
line_buffer_.clear();
break;
case '\x17':
// Delete word (^W)
delete_buffer_word(false);
break;
default:
if (c >= '\x20' && c <= '\x7E') {
// ASCII text
if (line_buffer_.length() < maximum_command_line_length_) {
line_buffer_.push_back(c);
}
}
break;
}
previous_ = c;
// This is a hack to let TelnetStream know that command
// execution is complete and that output can be flushed.
available_char();
idle_time_ = uuid::get_uptime_ms();
}
Shell::DelayData::DelayData(uint64_t delay_time, delay_function && delay_function)
: delay_time_(delay_time)
, delay_function_(std::move(delay_function)) {
}
void Shell::loop_delay() {
auto * delay_data = reinterpret_cast<Shell::DelayData *>(mode_data_.get());
if (uuid::get_uptime_ms() >= delay_data->delay_time_) {
auto function_copy = delay_data->delay_function_;
mode_ = Mode::NORMAL;
mode_data_.reset();
function_copy(*this);
if (running()) {
display_prompt();
}
idle_time_ = uuid::get_uptime_ms();
}
}
Shell::BlockingData::BlockingData(blocking_function && blocking_function)
: blocking_function_(std::move(blocking_function)) {
}
void Shell::loop_blocking() {
auto * blocking_data = reinterpret_cast<Shell::BlockingData *>(mode_data_.get());
/* It is not possible to change mode while executing this function,
* because that would require copying either the std::shared_ptr or
* the std::function on every loop execution (to ensure that the
* function captures aren't destroyed while executing).
*/
if (blocking_data->blocking_function_(*this, blocking_data->stop_)) {
bool stop_pending = blocking_data->stop_;
mode_ = Mode::NORMAL;
mode_data_.reset();
if (stop_pending) {
stop();
}
if (running()) {
display_prompt();
}
idle_time_ = uuid::get_uptime_ms();
}
}
void Shell::enter_password(const __FlashStringHelper * prompt, password_function function) {
if (mode_ == Mode::NORMAL) {
mode_ = Mode::PASSWORD;
mode_data_ = std::make_unique<Shell::PasswordData>(prompt, std::move(function));
}
}
void Shell::delay_for(unsigned long ms, delay_function function) {
delay_until(uuid::get_uptime_ms() + ms, std::move(function));
}
void Shell::delay_until(uint64_t ms, delay_function function) {
if (mode_ == Mode::NORMAL) {
mode_ = Mode::DELAY;
mode_data_ = std::make_unique<Shell::DelayData>(ms, std::move(function));
}
}
void Shell::block_with(blocking_function function) {
if (mode_ == Mode::NORMAL) {
mode_ = Mode::BLOCKING;
mode_data_ = std::make_unique<Shell::BlockingData>(std::move(function));
}
}
void Shell::delete_buffer_word(bool display) {
size_t pos = line_buffer_.find_last_of(' ');
if (pos == std::string::npos) {
line_buffer_.clear();
if (display) {
erase_current_line();
prompt_displayed_ = false;
display_prompt();
}
} else {
if (display) {
erase_characters(line_buffer_.length() - pos);
}
line_buffer_.resize(pos);
}
}
size_t Shell::maximum_command_line_length() const {
return maximum_command_line_length_;
}
void Shell::maximum_command_line_length(size_t length) {
maximum_command_line_length_ = std::max((size_t)1, length);
line_buffer_.reserve(maximum_command_line_length_);
}
void Shell::process_command() {
CommandLine command_line{line_buffer_};
line_buffer_.clear();
println();
prompt_displayed_ = false;
if (!command_line->empty()) {
if (commands_) {
auto execution = commands_->execute_command(*this, std::move(command_line));
if (execution.error != nullptr) {
println(execution.error);
}
} else {
println(F("No commands configured"));
}
}
if (running()) {
display_prompt();
}
::yield();
}
void Shell::process_completion() {
CommandLine command_line{line_buffer_};
if (!command_line->empty() && commands_) {
auto completion = commands_->complete_command(*this, command_line);
bool redisplay = false;
if (!completion.help.empty()) {
println();
redisplay = true;
for (auto & help : completion.help) {
std::string help_line = help.to_string(maximum_command_line_length_);
println(help_line);
}
}
if (!completion.replacement->empty()) {
if (!redisplay) {
erase_current_line();
prompt_displayed_ = false;
redisplay = true;
}
line_buffer_ = completion.replacement.to_string(maximum_command_line_length_);
}
if (redisplay) {
display_prompt();
}
}
::yield();
}
void Shell::process_password(bool completed) {
println();
auto * password_data = reinterpret_cast<Shell::PasswordData *>(mode_data_.get());
auto function_copy = password_data->password_function_;
mode_ = Mode::NORMAL;
mode_data_.reset();
function_copy(*this, completed, line_buffer_);
line_buffer_.clear();
if (running()) {
display_prompt();
}
}
void Shell::invoke_command(const std::string & line) {
if (!line_buffer_.empty()) {
println();
prompt_displayed_ = false;
}
if (!prompt_displayed_) {
display_prompt();
}
line_buffer_ = line;
print(line_buffer_);
process_command();
}
unsigned long Shell::idle_timeout() const {
return idle_timeout_ / 1000;
}
void Shell::idle_timeout(unsigned long timeout) {
idle_timeout_ = (uint64_t)timeout * 1000;
}
void Shell::check_idle_timeout() {
if (idle_timeout_ > 0 && uuid::get_uptime_ms() - idle_time_ >= idle_timeout_) {
println();
stop();
}
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,107 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <Arduino.h>
#include <algorithm>
#include <memory>
#include <string>
#include <uuid/log.h>
namespace uuid {
namespace console {
static const char __pstr__logger_name[] __attribute__((__aligned__(sizeof(int)))) PROGMEM = "shell";
const uuid::log::Logger Shell::logger_{reinterpret_cast<const __FlashStringHelper *>(__pstr__logger_name), uuid::log::Facility::LPR};
Shell::QueuedLogMessage::QueuedLogMessage(unsigned long id, std::shared_ptr<uuid::log::Message> && content)
: id_(id)
, content_(std::move(content)) {
}
void Shell::operator<<(std::shared_ptr<uuid::log::Message> message) {
if (log_messages_.size() >= maximum_log_messages_) {
log_messages_.pop_front();
}
log_messages_.emplace_back(log_message_id_++, std::move(message));
}
uuid::log::Level Shell::log_level() const {
return uuid::log::Logger::get_log_level(this);
}
void Shell::log_level(uuid::log::Level level) {
uuid::log::Logger::register_handler(this, level);
}
size_t Shell::maximum_log_messages() const {
return maximum_log_messages_;
}
void Shell::maximum_log_messages(size_t count) {
maximum_log_messages_ = std::max((size_t)1, count);
while (log_messages_.size() > maximum_log_messages_) {
log_messages_.pop_front();
}
}
void Shell::output_logs() {
if (!log_messages_.empty()) {
if (mode_ != Mode::DELAY) {
erase_current_line();
prompt_displayed_ = false;
}
while (!log_messages_.empty()) {
auto message = std::move(log_messages_.front());
log_messages_.pop_front();
print(uuid::log::format_timestamp_ms(message.content_->uptime_ms, 3));
printf(F(" %c %lu: [%S] "), uuid::log::format_level_char(message.content_->level), message.id_, message.content_->name);
if ((message.content_->level == uuid::log::Level::ERR) || (message.content_->level == uuid::log::Level::WARNING)) {
print(COLOR_RED);
println(message.content_->text);
print(COLOR_RESET);
} else if (message.content_->level == uuid::log::Level::INFO) {
print(COLOR_YELLOW);
println(message.content_->text);
print(COLOR_RESET);
} else if (message.content_->level == uuid::log::Level::DEBUG) {
print(COLOR_CYAN);
println(message.content_->text);
print(COLOR_RESET);
} else {
println(message.content_->text);
}
::yield();
display_prompt();
}
}
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,45 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <memory>
#include <set>
namespace uuid {
namespace console {
std::set<std::shared_ptr<Shell>> Shell::shells_;
void Shell::loop_all() {
for (auto shell = shells_.begin(); shell != shells_.end();) {
shell->get()->loop_one();
// This avoids copying the shared_ptr every time loop_one() is called
if (!shell->get()->running()) {
shell = shells_.erase(shell);
} else {
shell++;
}
}
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,164 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <Arduino.h>
#include <stdarg.h>
#include <string>
namespace uuid {
namespace console {
size_t Shell::print(const std::string & data) {
if (data.empty()) {
return 0;
} else {
return write(reinterpret_cast<const uint8_t *>(data.c_str()), data.length());
}
}
size_t Shell::println(const std::string & data) {
size_t len = print(data);
len += println();
return len;
}
size_t Shell::printf(const char * format, ...) {
va_list ap;
va_start(ap, format);
size_t len = vprintf(format, ap);
va_end(ap);
return len;
}
size_t Shell::printf(const __FlashStringHelper * format, ...) {
va_list ap;
va_start(ap, format);
size_t len = vprintf(format, ap);
va_end(ap);
return len;
}
size_t Shell::printfln(const char * format, ...) {
va_list ap;
va_start(ap, format);
size_t len = vprintf(format, ap);
va_end(ap);
len += println();
return len;
}
size_t Shell::printfln(const __FlashStringHelper * format, ...) {
va_list ap;
va_start(ap, format);
size_t len = vprintf(format, ap);
va_end(ap);
len += println();
return len;
}
size_t Shell::vprintf(const char * format, va_list ap) {
size_t print_len = 0;
va_list copy_ap;
va_copy(copy_ap, ap);
int format_len = ::vsnprintf(nullptr, 0, format, ap);
if (format_len > 0) {
std::string text(static_cast<std::string::size_type>(format_len), '\0');
::vsnprintf(&text[0], text.capacity() + 1, format, copy_ap);
print_len = print(text);
}
va_end(copy_ap);
return print_len;
}
size_t Shell::vprintf(const __FlashStringHelper * format, va_list ap) {
size_t print_len = 0;
va_list copy_ap;
va_copy(copy_ap, ap);
int format_len = ::vsnprintf_P(nullptr, 0, reinterpret_cast<PGM_P>(format), ap);
if (format_len > 0) {
std::string text(static_cast<std::string::size_type>(format_len), '\0');
::vsnprintf_P(&text[0], text.capacity() + 1, reinterpret_cast<PGM_P>(format), copy_ap);
print_len = print(text);
}
va_end(copy_ap);
return print_len;
}
// modified by proddy
void Shell::print_all_available_commands() {
/*
commands_->for_each_available_command(*this, [this](std::vector<std::string> & name, std::vector<std::string> & arguments) {
CommandLine command_line{name, arguments};
command_line.escape_initial_parameters(name.size());
name.clear();
arguments.clear();
println(command_line.to_string(maximum_command_line_length()));
});
*/
// changed by proddy - sort the help commands
std::list<std::string> sorted_cmds;
commands_->for_each_available_command(*this, [&](std::vector<std::string> & name, std::vector<std::string> & arguments) {
CommandLine command_line{name, arguments};
command_line.escape_initial_parameters(name.size());
name.clear();
arguments.clear();
sorted_cmds.push_back(command_line.to_string(maximum_command_line_length()));
});
sorted_cmds.sort();
for (auto & cl : sorted_cmds) {
// print(" ");
println(cl);
}
}
void Shell::erase_current_line() {
print(F("\033[0G\033[K"));
}
void Shell::erase_characters(size_t count) {
print(std::string(count, '\x08'));
print(F("\033[K"));
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,93 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <string>
namespace uuid {
namespace console {
void Shell::display_banner() {
}
std::string Shell::hostname_text() {
return std::string{};
}
std::string Shell::context_text() {
return std::string{};
}
std::string Shell::prompt_prefix() {
return std::string{};
}
std::string Shell::prompt_suffix() {
return std::string{'$'};
}
void Shell::end_of_transmission() {
if (idle_timeout_ > 0) {
println();
stop();
}
}
void Shell::display_prompt() {
switch (mode_) {
case Mode::DELAY:
case Mode::BLOCKING:
break;
case Mode::PASSWORD:
print(reinterpret_cast<Shell::PasswordData *>(mode_data_.get())->password_prompt_);
break;
case Mode::NORMAL:
std::string hostname = hostname_text();
std::string context = context_text();
print(prompt_prefix());
// colors added by proddy
if (!hostname.empty()) {
print(COLOR_BRIGHT_GREEN);
print(COLOR_BOLD_ON);
print(hostname);
print(COLOR_RESET);
print(':');
}
if (!context.empty()) {
print(COLOR_BRIGHT_BLUE);
print(COLOR_BOLD_ON);
print(context);
print(COLOR_RESET);
// print(' ');
}
print(prompt_suffix());
print(' ');
print(line_buffer_);
prompt_displayed_ = true;
break;
}
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,125 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <Arduino.h>
namespace uuid {
namespace console {
int Shell::available() {
if (mode_ == Mode::BLOCKING) {
auto * blocking_data = reinterpret_cast<Shell::BlockingData *>(mode_data_.get());
if (!available_char()) {
return 0;
}
if (blocking_data->consume_line_feed_) {
const int input = peek_one_char();
if (input >= 0) {
const unsigned char c = input;
blocking_data->consume_line_feed_ = false;
if (previous_ == '\x0D' && c == '\x0A') {
// Consume the first LF following a CR
read_one_char();
previous_ = c;
return available();
}
} else {
// The underlying stream has not implemented peek,
// so the next read() could return -1 if LF is
// filtered out.
}
}
return 1;
} else {
return 0;
}
}
int Shell::read() {
if (mode_ == Mode::BLOCKING) {
auto * blocking_data = reinterpret_cast<Shell::BlockingData *>(mode_data_.get());
const int input = read_one_char();
if (input >= 0) {
const unsigned char c = input;
if (blocking_data->consume_line_feed_) {
blocking_data->consume_line_feed_ = false;
if (previous_ == '\x0D' && c == '\x0A') {
// Consume the first LF following a CR
previous_ = c;
return read();
}
}
// Track read characters so that a final CR means we ignore the next LF
previous_ = c;
}
return input;
} else {
return -1;
}
}
int Shell::peek() {
if (mode_ == Mode::BLOCKING) {
auto * blocking_data = reinterpret_cast<Shell::BlockingData *>(mode_data_.get());
const int input = peek_one_char();
if (blocking_data->consume_line_feed_) {
if (input >= 0) {
const unsigned char c = input;
blocking_data->consume_line_feed_ = false;
if (previous_ == '\x0D' && c == '\x0A') {
// Consume the first LF following a CR
read_one_char();
previous_ = c;
return peek();
}
}
}
return input;
} else {
return -1;
}
}
void Shell::flush() {
// This is a pure virtual function in Arduino's Stream class, which
// makes no sense because that class is for input and this is an
// output function. Later versions move it to Print as an empty
// virtual function so this is here for backward compatibility.
}
} // namespace console
} // namespace uuid

View File

@@ -0,0 +1,63 @@
/*
* uuid-console - Microcontroller console shell
* Copyright 2019 Simon Arlott
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uuid/console.h>
#include <Arduino.h>
#include <memory>
#include <string>
namespace uuid {
namespace console {
StreamConsole::StreamConsole(Stream & stream)
: Shell()
, stream_(stream) {
}
// cppcheck-suppress passedByValue
StreamConsole::StreamConsole(std::shared_ptr<Commands> commands, Stream & stream, unsigned int context, unsigned int flags)
: Shell(std::move(commands), context, flags)
, stream_(stream) {
}
size_t StreamConsole::write(uint8_t data) {
return stream_.write(data);
}
size_t StreamConsole::write(const uint8_t * buffer, size_t size) {
return stream_.write(buffer, size);
}
bool StreamConsole::available_char() {
return stream_.available() > 0;
}
int StreamConsole::read_one_char() {
return stream_.read();
}
int StreamConsole::peek_one_char() {
return stream_.peek();
}
} // namespace console
} // namespace uuid

File diff suppressed because it is too large Load Diff