Template sensor return unknown

Hello,I’m newbie

I am having problems using a template sensor, It always return unknown. I hope you can help me with this.
I have the following template sensor:

  - platform: template
    sensors:
      p_money:
        value_template: >-
         {% set Sodien = is_state('sensor.san_luong_1') | float %}
         {% if 0 <= Sodien < 50 %}
           {{ Sodien * 1510}}
         {% elif 50 <= Sodien  < 100 %}
           {{ 75500 + (Sodien - 50)*1561 }}
         {% elif 100 <= Sodien  < 200 %}
           {{ 85500 + (Sodien - 50)*1561 }}
         {% elif 200 <= Sodien  < 300 %}
           {{ 334850 + (Sodien - 200)*2282 }}
         {% elif 300 <= Sodien  < 400 %}
           {{ 563050 + (Sodien - 300)*2834 }}
         {% else %}
           {{ 846450 + (Sodien - 400)*2927 }}
         {% endif %}
        unit_of_measurement: 'Đồng' 
        friendly_name: "Tiền điện"

And try this :

  - platform: template
    sensors:
      p_money:
        value_template: >-
         {% if is_state('sensor.san_luong_1') | float > 0 and is_state('sensor.san_luong_1') | float  < 50 %}
           {{ Sodien * 1510}}
         {% elif is_state('sensor.san_luong_1') | float > 50 and is_state('sensor.san_luong_1') | float  < 100 %}
           {{ 75500 + (Sodien - 50)*1561 }}
         {% elif is_state('sensor.san_luong_1') | float > 100 and is_state('sensor.san_luong_1') | float  < 200 %}
           {{ 85500 + (Sodien - 50)*1561 }}
         {% elif is_state('sensor.san_luong_1') | float > 200 and is_state('sensor.san_luong_1') | float  < 300 %}
           {{ 334850 + (Sodien - 200)*2282 }}
         {% elif is_state('sensor.san_luong_1') | float > 300 and is_state('sensor.san_luong_1') | float  < 400 %}
           {{ 563050 + (Sodien - 300)*2834 }}
         {% else %}
           {{ 846450 + (Sodien - 400)*2927 }}
         {% endif %}
        unit_of_measurement: 'Đồng' 
        friendly_name: "Tiền điện"

But it still return " unknown"
The entities for this template sensor are defined here:

  - platform: rest
    name: "Sản lượng 1"
    resource: https://xxxx.xxx.xxx
    value_template: '{{ (value_json.dolan1_sanluong)|round(2) }}'
    scan_interval: 7200
    force_update: true
    unit_of_measurement: '  kWh' 

Tks for help

With is_state you can test for a specific value.


Change
is_state('sensor.san_luong_1')

to

states('sensor.san_luong_1')

in your template.

EDIT: You can easy test your templates in Dev Tools/templates.

it return “unavailable” if use “state”

Here’s an example with a sensor value.

image
it worked , tks so much , nice