c++ - 通过 UART 串​​口为 Arduino 交互 shell?

标签 c++ arduino esp8266 arduino-esp8266 platformio

我想通过 UART 串​​口为 Arduino 实现一个交互式 shell,使用纯 C++ OOP 风格的代码。但是我觉得如果在代码中判断用户输入命令的时候if-else判断太多,会有点难看,

所以我想问一下,有什么办法可以避免使用if-else语句吗?例如,

之前:

while(Serial.available())
{
    serialReceive = Serial.readString();// read the incoming data as string
    Serial.println(serialReceive);
}

if(serialReceive.equals("factory-reset"))
{
    MyService::ResetSettings();
}
else if(serialReceive.equals("get-freeheap"))
{
    MyService::PrintFreeHeap();
}
else if(serialReceive.equals("get-version"))
{
    MyService::PrintVersion();
}

之后:

while(Serial.available())
{
    serialReceive = Serial.readString();// read the incoming data as string
    Serial.println(serialReceive);
}

MagicClass::AssignCommand("factory-reset", MyService::ResetSettings);
MagicClass::AssignCommand("get-freeheap", MyService::PrintFreeHeap);
MagicClass::AssignCommand("get-version", MyService::PrintVersion);

最佳答案

您可以有一个数组来存储函数指针以及触发命令的字符串(您可以创建一个结构来存储两者)。

不幸的是,Arduino 不支持 std::vector 类,因此对于我的示例,我将使用 c 类型数组。然而,有一个 Arduino 库为 Arduino 添加了一些 STL 支持 https://github.com/maniacbug/StandardCplusplus (同样对于这个库,您可以使用函数库来使传递函数作为参数更容易)

//struct that stores function to call and trigger word (can actually have spaces and special characters
struct shellCommand_t
{
  //function pointer that accepts functions that look like "void test(){...}"
  void (*f)(void);
  String cmd;
};

//array to store the commands
shellCommand_t* commands;

有了这个,您可以在开始时将命令数组初始化为一个大小,也可以在每次添加命令时调整它的大小,这取决于您的用例。

假设您已经在数组中分配了足够的空间来添加命令的基本函数可能如下所示

int nCommands = 0;
void addCommand(String cmd, void (*f)(void))
{
  shellCommand_t sc;
  sc.cmd = cmd;
  sc.f = f;

  commands[nCommands++] = sc;
}

然后在您的设置函数中,您可以按照与上面类似的方式添加命令

addCommand("test", test);
addCommand("hello world", helloWorld);

最后,在循环函数中,您可以使用 for 循环查看所有命令,检查输入字符串与所有命令字符串的对比。

可以这样调用匹配命令的函数

(*(commands[i].f))();

关于c++ - 通过 UART 串​​口为 Arduino 交互 shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582825/

相关文章:

c++ - 关于 skipws 声明的简单说明

c++ - C++11 中的数组声明和初始化

c++ - 为什么 main() 的参数不是 const 限定的?

检查数组中是否存在char

c - 从 C 套接字上的传入流中提取数据(字符串、字符等)

tcp - Arduino + ESP8266,如何发送连续获取请求?

c++ - 从不在 map2 中的 map1 中查找最大元素

arduino - Telnet 服务器启用客户端线路模式

c++ - 在 arduino 上的类中使用 LiquidCrystal_I2C

esp8266 - 使用 NodeMCU ESP8266 从 DHT22 读取 - DHT 超时