Problem with lambdas and strings in ESPHome

I wonder if anyone can help me with this.

I am trying to display graphics files on an ePaper device under ESPHome/HA control. The idea is to display a graphic file selected by an integer generated from a sensor in Home Assistant. The graphic files are all named the same, but in numeric sequence, so that graphic01.gif is selected by Int 1 from the sensor, and graphic09.gif is selected by Int 9 from the sensor, etc.

I have produced a lambda which concatenates a string in the following form “graphic0” + string int from sensor + “.gif”. This works fine, and when I output the string result to the logs, it performs exactly as expected. The problem, however, is assigning the string value to the ESP id(my_string) which is needed to select the file and send it to the display.

The following is the part of the code which works perfectly if I comment out the crucial bit, which passes the value back to ESPHome:

image:
  - file: "major-01.gif"
    id: my_image

display:
  - platform: waveshare_epaper
    cs_pin: 5
    dc_pin: 19
    busy_pin: 4
    reset_pin: 12
    model: 2.90in
    full_update_every: 180
    pages:
      - id: tarot1
        lambda: |-
          std::string val = to_string((int)(id(rand_sen).state));
             std::string imagefile = "major-0" + val + ".gif";
             // id(my_image) = imagefile.c_str();
             it.image(0, 0, id(my_image)) ;
          ESP_LOGI("main", "Value of my sensor: %s", val.c_str());
          ESP_LOGI("main", "Value of imagefile: %s", imagefile.c_str());

As I say, the logs display exactly the values I am expecting: the integer returned by the sensor, and the concatenated string which results in major-01.gif, major-09.gif, etc. However, if I remove the comments on the line “id(my_image) = imagefile.c_str();” the compiler produces an error.

src/main.cpp:524:19: error: cannot convert 'const char*' to 'esphome::display::Image*' in assignment
          my_image = imagefile.c_str();
                   ^
*** [/data/epaper2/.pioenvs/epaper2/src/main.cpp.o] Error 1

I have removed the c_str() element, but that does not help. Clearly, the type of string expected by ESPHome is not the same as the string I have generated. Can anybody with greater knowledge of C++ help me out with this?

Many thanks if you can!

1 Like

you can’t dynamically generate id’s in c++ runtime

you’d have to rewrite that code, I would use the switch statement
like

switch(val)
 {
    case 1:
            imgfile = id(imgfile1);
            break;
     case 2:
....

Thanks, Guillermo. I had in fact started off with that approach, but I have a large number of graphics files and I was hoping to find a way of avoiding a brute force way of doing it. I suspected that id’s probably could not be generated in run-time, so thanks for confirming that.

I may be able to find a work-around, perhaps via mqtt.

Thanks again.