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_STATUSfor exactlystatus;CMD_SET_WATERforset water N, where N is only digits and from 10 to 60, after storing N in*value;CMD_RANGEforset water Nwith N only digits but outside 10 to 60 (however many digits);CMD_UNKNOWNfor anything else, includingset waterwith 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
1Out 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 7Learn it first
- UART · Baud rate, framing, errors, flow control and DMA reception.
More UART problems
- Assemble command lines · Collect received characters into lines, with backspace and overflow handled.
- Parse a modem signal report · Validate a +CSQ reply and convert it to dBm.
- Detect the baud rate · Measure a 'U' character's bit times and snap to the nearest standard baud rate.
- Interrupt-driven transmit queue · Queue bytes for the UART and send them from the data-register-empty interrupt.
- Spot OK and ERROR in a modem stream · Feed received characters one at a time and report complete OK or ERROR lines.
- Driver: a polled UART transmitter · Configure a UART from its register map and send bytes without losing any.
- Driver: receive bytes and detect an overrun · Read the UART's receive register without blocking, and report lost bytes.
- Fix: lost bytes are never reported · A receive routine checks the data flag before the overrun flag, so overruns disappear.
- Command console · Split a command line into words, with quoted arguments, and dispatch it through a command table.