Need help extracting value of a sensor for automation

Hi,

I have an integration for a water softener that is working well and I see all the values in dashboard. Now I am trying to write an automation that will alert me when the salt level goes below 25%. Here is my automation code:

- id: '1630381254562'
  alias: Ecowater
  description: 'Email when salt level dips below 25%'
  trigger:
  - platform: state
    entity_id: sensor.water_salt_level_2
  condition:
  - condition: state
    entity_id: sensor.water_salt_level_2
    state: '0.25'
    for: 04:00:00
  action:
  - service: notify.emailecowaterlowlevel
    data:
      #message: Water softener salt level is less than 25 percent
      message: |
        Salt level is at {{ states.sensor.water_salt_level_2 }}
      title: Low salt level in water softner
  mode: single

When I manually run the automation, I do get an email but the text looks like:

Salt level is at <template TemplateState(<state sensor.water_salt_level_2=50; friendly_name=Water Salt Level (%) @ 2021-08-30T19:35:50.362908-07:00>)>

I can see that this string contains the correct value i.e 50% but is there a way to clean up the message body?

Try to use this-
{{ states('sensor.water_salt_level_2') }}

Place it in Developer Tools → Template.

- id: '1630381254562'
  alias: Ecowater
  description: 'Email when salt level dips below 25%'
  trigger:
  - platform: numeric_state
    entity_id: sensor.water_salt_level_2
    below: '25'
    for: '04:00:00'
  action:
  - service: notify.emailecowaterlowlevel
    data:
      #message: Water softener salt level is less than 25 percent
      message: >-
        Salt level is at {{ states('sensor.water_salt_level_2') }}%.
      title: Low salt level in water softner
  mode: single

Note that the trigger wont survive HA restart or automation reload. 4 hours is a bit too long in my opinion.

1 Like

Thanks for pointing to template editor, I was not using it and seems like a handy tool to test things!!

Sigh, you beat me to it :slight_smile: I had almost exactly the same thing in my reply. You did change “0.25” to “25”, so the OP would need to see what the state actually is.

1 Like

Yes, I was referencing the state from here. But you are correct, @PanMat should confirm the actual state from Developer Tools → States.

Oh, good catch!

I also noticed that there is a clipboard icon next to each entity for copying its value, can’t believe I was doing things the hard way all these months!

You already have the correct answer, but I thought it’s good to add an explanation. What you got there was a state object (a “thing” that’s a composition of properties and values). If you used states.sensor.water_salt_level_2.state you would get the raw state value on that object. The states function gives you a safe value of that value, which is what one would use almost always. See the states section here.

1 Like

Thanks Pieter, this explains the output I was getting!

1 Like