16static bool isBackspace_(
char receivedChar) {
21static bool isNewline_(
char receivedChar) {
22 return receivedChar ==
'\n' || receivedChar ==
'\r';
28void tokenizeWhitespace(
const std::string& line,
30 std::queue<std::string>& outArgs)
33 while (!outArgs.empty()) {
39 if (token.empty()) {
return;}
40 if (outCmd.empty()) {outCmd = token;}
41 else {outArgs.push(token);}
45 for (
char ch : line) {
46 if (ch ==
' ' || ch ==
'\t') {flush();}
54 while (UART->available() > 0) {
55 const char receivedChar =
static_cast<char>(UART->read());
57 if (isBackspace_(receivedChar)) {
60 }
else if (isNewline_(receivedChar)) {
61 if (lastWasCR_ && receivedChar ==
'\n') {
65 lastWasCR_ = (receivedChar ==
'\r');
69 handleChar_(receivedChar);
74void CommandLine::handleBackspace_() {
75 if (fullLine.empty()) {
return;}
80void CommandLine::handleNewline_() {
83 std::string line = fullLine;
92 std::string cmd = {
""};
93 std::queue<std::string> args = {};
94 tokenizeWhitespace(line, cmd, args);
103void CommandLine::handleChar_(
char receivedChar) {
109 UART->println(
"Buffer overflow, input ignored.");
115 fullLine += receivedChar;
116 UART->print(receivedChar);
121void CommandLine::addCommand(
const std::string& longName,
const std::string& shortName, std::function<
void(std::queue<std::string>, std::string&)> funcPtr) {
122 Command newCommand{ longName, shortName, funcPtr };
123 commands.push_back(newCommand);
129 if (command ==
"help" || command ==
"?") {
134 std::string response;
135 for (
const auto& cmd : commands) {
136 if (cmd.longName == command || cmd.shortName == command) {
138 cmd.funcPtr(arguments, response);
144 UART->println(
"Command not found: " + String(command.c_str()));
145 UART->println(
"Type 'help' or '?' to see available commands.");
149void CommandLine::help(){
150 if (commands.empty()) {
151 UART->
println(
"No commands available.");
156 for (
const auto& cmd : commands) {
157 UART->println(String(cmd.longName.c_str()) +
"<" + String(cmd.shortName.c_str()) +
">");
159 UART->println(
"help<?>");
163void CommandLine::trimSpaces(std::string& str) {
165 size_t start = str.find_first_not_of(
" ");
167 if (start != std::string::npos) {
169 size_t end = str.find_last_not_of(
" ");
170 str = str.substr(start, end - start + 1);
constexpr int COMMAND_CHARS_ASCII_END
constexpr int UART_BUFFER_SIZE
void executeCommand(const std::string &command, std::queue< std::string > arugments)
void addCommand(const std::string &longName, const std::string &shortName, std::function< void(std::queue< std::string > argumentQueue, std::string &)> funcPtr)
CommandLine(Stream *UART)
void println(const T &message)