How convert a string to the value of a const with the same name?

For a domotica project I want to emulate a Bluetooth keyboard. The domotica bridge can sent strings of data to a ESP32… The library has a bunch of key’s declared as const. Like:

const uint8_t KEY_UP_ARROW = 0xDA;
const uint8_t KEY_DOWN_ARROW = 0xD9;
const uint8_t KEY_LEFT_ARROW = 0xD8;
const uint8_t KEY_RIGHT_ARROW = 0xD7;
const uint8_t KEY_BACKSPACE = 0xB2;
const uint8_t KEY_TAB = 0xB3;
const uint8_t KEY_RETURN = 0xB0;
const uint8_t KEY_ESC = 0xB1;
const uint8_t KEY_INSERT = 0xD1;
const uint8_t KEY_DELETE = 0xD4;
const uint8_t KEY_PAGE_UP = 0xD3;
const uint8_t KEY_PAGE_DOWN = 0xD6;
const uint8_t KEY_HOME = 0xD2;
const uint8_t KEY_END = 0xD5;

(And so on…)

How can I convert an incoming string like “KEY_UP_ARROW” to the const? Or do I really need to create long if else solution like this:

if (strcmp(incomingString, "KEY_UP_ARROW")==0) {
    result = KEY_UP_ARROW;
}
else if (strcmp(incomingString, "KEY_DOWN_ARROW")==0) {
    result = KEY_DOWN_ARROW;
}

Surely there must be an more elegant and easier way.

Rather than send a string, you could always just send the key value directly as a single byte and avoid all the compares. Or maybe send the hex value as ascii (e.g. "DA" ) and then convert that to its actual value.

Yes, but I want to keep the user-side (on the Domotica controller) readable and user friendly.

Create an array of structs in progmem to hold the mapping and loop through it to look up the 0xDA value when you have received “KEY_UP_ARROW”.

satoer:
do I really need to create long if else solution
Surely there must be an more elegant and easier way.

A lookup table and 'for' loop.

Thanks. That seems a neater solution.

It's easy to change a bunch of const declarations to lookup array initializers with a text editor:

const uint8_t KEY_UP_ARROW = 0xDA;
const uint8_t KEY_DOWN_ARROW = 0xD9;
const uint8_t KEY_LEFT_ARROW = 0xD8;

Change " = " to "", ":

const uint8_t KEY_UP_ARROW", 0xDA;
const uint8_t KEY_DOWN_ARROW", 0xD9;
const uint8_t KEY_LEFT_ARROW, 0xD8;

Change ";" to "},":

const uint8_t KEY_UP_ARROW", 0xDA},
const uint8_t KEY_DOWN_ARROW", 0xD9},
const uint8_t KEY_LEFT_ARROW, 0xD8},

Change "const uint8_t " to " {"":

  {"KEY_UP_ARROW", 0xDA},
  {"KEY_DOWN_ARROW", 0xD9},
  {"KEY_LEFT_ARROW, 0xD8},

Add some trim around that and you have:

struct {char *name, uint8_t value} LookupTable[] = {
  {"KEY_UP_ARROW", 0xDA},
  {"KEY_DOWN_ARROW", 0xD9},
  {"KEY_LEFT_ARROW, 0xD8},
};