Simvik

Greenhouse: parse a console command

Parse a technician's command line, and refuse anything malformed or out of range. A medium embedded C problem (UART), run and graded in the browser.

medium · UART · parsing · strings · validation · product

Product: Smart greenhouse controller (Agriculture)

Requirement. A technician types commands on the service console. A typo must never change a setting.

line is one command without its line ending. Return:

  • CMD_STATUS for exactly status;
  • CMD_SET_WATER for set water N, where N is only digits and from 10 to 60, after storing N in *value;
  • CMD_RANGE for set water N with N only digits but outside 10 to 60 (however many digits);
  • CMD_UNKNOWN for anything else, including set water with no number or with anything but digits.

Leave *value unchanged unless you return CMD_SET_WATER.

Starter code

int parse_command(const char *line, int *value) {
  if (strcmp(line, "status") == 0) return CMD_STATUS;
  if (strncmp(line, "set water ", 10) == 0) {
    *value = atoi(line + 10);
    return CMD_SET_WATER;
  }
  return CMD_UNKNOWN;
}

Example tests

A setting and a status request

int v = 0;
int r = parse_command("set water 45", &v);
printf("%d %d\n", r, v);
printf("%d\n", parse_command("status", &v));

Expected output:

2 45
1

Out of range is refused and changes nothing

int v = 7;
int r = parse_command("set water 99", &v);
printf("%d %d\n", r, v);

Expected output:

-2 7

Learn it first

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

More UART problems