Get lambda id() component name from variable

Is it possible to get the component name in a lambda id() expression from a variable?

# This...
- lambda: |-
    id(sht_dewpoint).update();
# ...should become this...
- lambda: |-
    std::string comp_name = "sht_dewpoint";
    id(comp_name).update();

The motiviation for my question is to loop over multiple components. The names of the components would be provided as a list in a substitution string.

You can’t pass a string to id. The preprocessor uses it to convert it to C++ format sht_dewpoint->update().

Components do not have a string name representation. So, if you want to execute a function on a component based on a string name: don’t see a way how this can be done.

But… components can have 1 or more sensors, each sensor has a name. If you want to execute a function on specific sensors: you can get the list of sensors through App. Below sample code to print all sensor names. You can modify it to get the sensor based on a string name.

auto sensors = App.get_sensors();
for(unsigned int i = 0; i < sensors.size(); i++) 
  ESP_LOGD("app", "Sensor: %s", sensors[i]->get_name().c_str());

Do note that there is a getter for each type of sensor. For binary sensors, need to use get_binary_sensors(). For text sensors, use get_text_sensors()

I saw a similar-ish Q on Discord recently.

There was some undocumented ways to use script parameters (which I don’t fully understand;).

Might be worth looking into.

Edit: Reading the OP again, I think I’m off topic. Whoops. I’ll leave it here anyway.

Hi Jörg,

I think I am in the same situation as you, need to loop over many sensors and I need to dinamically assign XX as string in “id(XX)”.

Did you finally get it work?
Thanks!

Hi @ckxsmart,

I have followed your code and I can get the name of the sensors, but I don’t know how can we acces to the state of each sensor with the recovered names instead of the id() method.

Any hint?
Thanks!

Try sensors[i]->state