解析具有各种字段的消息,然后根据字段执行 运行 命令的最佳方法是什么?

What is the best way to parse message with various fields, and then run commands based on the fields?

所以现在我定义了一个如下所示的结构:

typedef struct rec_msg {
    uint8_t unit[4];
    uint8_t subdevice[4];
    uint8_t command[4];
    uint16_t  data[3];
    uint16_t  msg_id[1];
} rec_msg;

...我想读取结构中的字符数组,然后 运行 基于它们的命令。现在我正在这样做,而且似乎会有一种更简洁的方法来做到这一点。

 if (strncmp((const char *)message->unit, "blah", 3) == 0)
  {
    if (strncmp((const char *)message->subdevice, "syr", 3) == 0) 
    {
      if (strncmp((const char *)message->command, "rem", 3) == 0)
      {
        // run some command
      }
      else if (strncmp((const char *)message->command, "dis", 3) == 0)
      {
        // run some command
      }
      else
      {
        DEBUG_PRINT("Message contains an improper command name");
      }
    }
    else if (strncmp((const char *)message->subdevice, "rot", 3) == 0)
    {
      if (strncmp((const char *)message->command, "rem", 3) == 0)
      {
        // run some command
      }
      else if (strncmp((const char *)message->command, "dis", 3) == 0) 
      {
        // run some command
      }
      else
      {
        DEBUG_PRINT("Message contains an improper command name");
      }
    }
    else
    {
      DEBUG_PRINT("Message contains an improper subdevice name");
    }
  }
  else
  {
    DEBUG_PRINT("Message contains the wrong unit name");
  }
}

不要为一般问题编写明确的代码,而是将任务分解为多个步骤。伪代码如下。

对于 3 组字符串中的每一组,将匹配的文本转换为数字。建议具有相应枚举的字符串数组。 (下面显示 2 个)

enum unit_index {
  unit_blah,
  unit_N
};

const char *unit_string[unit_N] = {
  "blah"
};

enum subdevice_index {
  subdevice_syr,
  subdevice_rot,
  subdevice_N
};

const char *subdevice_string[subdevice_N] = {
  "syr"
  "rot"
};

查找匹配索引

unit_index unit = find_index(message->unit, unit_string, unit_N);
if (unit >= unit_N) {
  DEBUG_PRINT("Message contains the wrong unit name");
  return FAIL;
}

subdevice_index subdevice = find_index(message->subdevice, subdevice_string, subdevice_N);
if (subdevice >= subdevice_N) {
  DEBUG_PRINT("Message contains the wrong subdevice name");
  return FAIL;
}

// similar for command

现在代码有 3 个索引对应于 3 个文本字段。

创建 table 个索引和相应的命令

typedef struct {
  enum unit_index       unit;
  enum subdevice_index  subdevice;
  enum command_index    command;
  int (*func)();
} index2func;

index2func[] = {
  { unit_blah, subdevice_syr, command_dis, command_blah_syr_dis },
  { unit_blah, subdevice_rot, command_dis, command_blah_rot_dis },
  ...
  { unit_blah, subdevice_rpt, command_rem, command_blah_rot_rem }
};

遍历 table 一组匹配的索引并执行命令。