Simvik

Command console

Split a command line into words, with quoted arguments, and dispatch it through a command table. A hard embedded C problem (UART), run and graded in the…

hard · UART · uart · console · parsing · function-pointers

A serial debug console receives complete lines (assembling them is a separate job). Write the part that runs them.

tokenize(line, argv, max) splits line in place into words and stores a pointer to each in argv:

  • Words are separated by one or more spaces or tabs. Leading and trailing spaces are ignored.
  • A word that starts with " runs to the next ", may contain spaces, and does not include the quotes. "" is an empty word. The closing quote ends the word.
  • Return the number of words, -1 if a quote is never closed, or -2 if there are more than max words.

console_exec(line) tokenizes with MAX_WORDS and then:

  • prints error: unterminated quote or error: too many words for those failures,
  • does nothing for a blank line,
  • looks the first word up in cmd_table and prints error: unknown command '<word>' if it is not there,
  • prints error: wrong number of arguments for <name> if the number of words after the name is outside min_args to max_args,
  • otherwise calls the command's fn with argc and argv.

Starter code

int tokenize(char *line, char **argv, int max) {
  int n = 0;
  char *p = line;
  while (*p) {
    argv[n++] = p;
    while (*p && *p != ' ') p++;
    if (*p) *p++ = '\0';
  }
  return n;
}

void console_exec(char *line) {
  char *argv[MAX_WORDS];
  int argc = tokenize(line, argv, MAX_WORDS);
  int count;
  const cmd_t *t = cmd_table(&count);
  for (int i = 0; i < count; i++)
    if (strcmp(t[i].name, argv[0]) == 0) t[i].fn(argc, argv);
}

Example tests

Commands, extra spaces, a blank line and an unknown command

run("led on");
run("  echo  a   b ");
run("");
run("   ");
run("reboot now");

Expected output:

led on
echo: a|b
error: unknown command 'reboot'

A quoted argument

run("set name \"Kitchen light\"");

Expected output:

set name=Kitchen light

Learn it first

  • UART · Baud rate, framing, errors, flow control and DMA reception.

More UART problems