Converting a string to an int?

I’m trying to play specific tracks in dfplayer using the mqtt client to get track numbers from ha. It works if I specify the payload using multiple topics in the esphome config like this:

mqtt:
  broker: 192....
  username: !secret mqtt_client_user1
  password: !secret mqtt_client_pass1
  on_message:
    - topic: esphome/voice
      payload: 1
      qos: 0
      then:
        - dfplayer.set_volume: 15
        - delay: 150ms
        - dfplayer.play: 1
    - topic: esphome/voice
      payload: 2
      qos: 0
      then:
        - dfplayer.set_volume: 15
        - delay: 150ms
        - dfplayer.play: 2

…but that’s just 2 mp3 files for testing, and the code will become unmanageable when there are many files later on.

So I’m trying to use a lambda to make use of the payload. The problem is mqtt gets strings, and the dfplayer function needs an int. The result is ‘failed to convert’ compiler errors if I don’t do anything to convert:

mqtt:
  broker: 192....
  username: !secret mqtt_client_user1
  password: !secret mqtt_client_pass1
  on_message:
    topic: esphome/voice
    qos: 0
    then:
      - dfplayer.set_volume: 15
      - delay: 150ms
      - dfplayer.play: !lambda return x;

If I try stoi I get ‘not declared in scope’ errors:

      - dfplayer.play: !lambda return std::stoi(x);

I hope it’s just a syntax error, and this is doable. Any advice?

Solved it myself! So looks like the char array from c_str() is the way to go:

      - dfplayer.play: !lambda return atoi(x.c_str());

Now I just need to come up with a bunch of mp3 files and it’s good to go.

5 Likes

can you say how to format lamda command so that text sensor is converterd to number sensor,
what i am doing wrong?

  - platform: template
    name: "O2"
    lambda: |-
      return atoi(id(textsensor).c_str());
    update_interval: 60s