-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.hh
56 lines (46 loc) · 1.47 KB
/
cli.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#pragma once
#include <map>
class Interface {
public:
void handle_serial() {
if (!Serial.available()) return;
const auto str = Serial.readString().trim();
if (str.length() == 0) return;
// Special case "help"
if (str == "help") {
help();
return;
}
for (const auto& handler : handlers_) {
if (str.startsWith(handler.first)) {
// Assume there is a space at the end of the command
const auto data = str.substring(handler.first.length() + 1);
handler.second.function(data);
return;
}
}
Serial.println("Unknown command found!");
}
void help() const {
Serial.println("Commands: ");
for (const auto& handler : handlers_) {
Serial.print(" - '");
Serial.print(handler.first);
Serial.print("': ");
Serial.println(handler.second.description);
}
Serial.println(" - 'help': shows the list of commands");
}
using HandlerFunction = void(*)(const String&);
void add_handler(const String& command, String description, HandlerFunction function) {
auto& impl = handlers_[command];
impl.function = function;
impl.description = std::move(description);
}
private:
struct HandlerImpl {
HandlerFunction function;
String description;
};
std::map<String, HandlerImpl> handlers_;
};