Sonoff EM Power Attribute - Get a number from string

Hello,

I intend to create a sensor based on several other sensors to sum the total power of home lights.
I’m having problems to get the power data from a Sonoff EM because the power data attribute of this sensor comes in a string and not in a number.


My question is, how can I get only the numeric part from this string?

Thanks in advance.

As long as the unit string isn’t going to change you can use basic string slicing:

state: "{{ (state_attr('switch.x', 'power'))[:-2] }}"

or use split()

state: "{{ (state_attr('switch.x', 'power')).split(" ")[0] }}"

Hello @Didgeridrew,

Thanks for your reply.
And how can I convert the number from the string in a “int” or “float”?
I try to follow this topic, but the result is still a string.

Thanks.

@Andre_Magro In the future please copy/paste your configuration code/templates into the forum post as described in How To Ask a Good Question. It is much easier to inspect than a screenshot and we don’t have to rewrite everything.

By convention, states in Home Assistant are always strings… there is no point in adding a float or int filter to the end of the template. Both triggers and conditions have numeric state variants to handle this.

I’m trying to create a sensor in configuration.yaml based on other ones.

      # Luzes Power
      - name: "Luzes Power"
        unit_of_measurement: "W"
        device_class: power
        state: >
          {% set salacand = states('sensor.gosund_2_wattage') | float %}
          {% set mezanine = {{ state_attr('switch.10009cbb7e', 'power') }}"

          {{ (salacand + mezanine) | float | round(1, default=0) }}

Is not a problem mixing strings with float?

I don’t think you understood my comment. If you create a “Mezanine Power” sensor like in your original example, there is nothing you can do to make the state a number. It will always be a string.

If you want to use it in a template, you would treat it just like you do the Gosund 2 sensor in your “Luzes Power” sensor:

template:
  - sensor:

      # Mezanine Power
      - name: "Mezanine Power"
        unit_of_measurement: "W"
        device_class: power
        state: "{{ (state_attr('switch.x', 'power')).split(' ')[0] }}"

      # Luzes Power
      - name: "Luzes Power"
        unit_of_measurement: "W"
        device_class: power
        state: >
          {% set salacand = states('sensor.gosund_2_wattage') | float(0) %}
          {% set mezanine = states('sensor.mezanine_power') | float(0) %}
          {{ (salacand + mezanine) | round(1, default=0) }}
1 Like

Thanks @Didgeridrew