Simvik

TV remote: a table of key actions

Look a key code up in a table and call its action with the device's context. A medium embedded C problem (Function pointers and state machines), run and…

medium · Function pointers and state machines · function-pointers · dispatch-table · context · product

Product: TV remote control (Consumer electronics)

Requirement. The same remote firmware ships with different key layouts for TVs and soundbars, so each model is a table of {key code, action} pairs rather than a long switch.

Find the entry for code in the first n entries of table and call its action with ctx. Return true if an action ran. Return false, doing nothing, if no entry has that code or its action is NULL (a key that exists on the case but does nothing on this model). Key codes are arbitrary numbers, not positions in the table.

Starter code

bool remote_dispatch(const key_entry_t *table, size_t n, uint8_t code, void *ctx) {
  table[code].fn(ctx);
  return true;
}

Example tests

Volume up twice, channel up once

key_entry_t keys[] = { { 0x10, vol_up }, { 0x11, ch_up }, { 0x20, mute } };
tv_t tv = { 5, 1 };
remote_dispatch(keys, 3, 0x10, &tv);
remote_dispatch(keys, 3, 0x10, &tv);
remote_dispatch(keys, 3, 0x11, &tv);
printf("%d %d\n", tv.volume, tv.channel);

Expected output:

7 2

A key this model does not have

key_entry_t keys[] = { { 0x10, vol_up }, { 0x11, ch_up }, { 0x20, mute } };
tv_t tv = { 5, 1 };
int r = remote_dispatch(keys, 3, 0x55, &tv);
printf("%d %d %d\n", r, tv.volume, tv.channel);

Expected output:

0 5 1

Learn it first

More Function pointers and state machines problems