Changing 0/1 to display as on/off

I have a rest sensor (Open Sprinkler) which returns 0 or 1. I’d prefer to display off/on
platform: rest
name: sprinkler1
resource: http://x.x.x.x:8080/js?pw=XXX
value_template: “{{value_json.sn[0]}}”

I tried a template (below), which didn’t work because I don’t know enough about HA, and templates yet
- platform: template
sensors:
sprinkler1_name:
entity_id: sensor.sprinkler1
value_template: “{%if states.sensor.sprinkler1 == ‘1’ %}On{% elif states.sensor.sprinkler1 == ‘0’ %}Off{% endif %}”

Grateful for any suggestions

Please format your code as per the blue banner at the top of the page (you can edit your post to do this).

Try this:

platform: rest
name: sprinkler1
resource: http://x.x.x.x:8080/js?pw=XXX
value_template:>
  {% if value_json.sn[0] | int == 1 %}
    'On'
  {% elif value_json.sn[0] | int == 0 %}
    'Off'
  {% else %}
    'Undefined'
  {% endif %}
1 Like

The values in the template should not be quoted (otherwise I believe the state will contain those quote characters.) Also I’d recommend using the “standard” state of unknown for the third option. So:

sensor:
  platform: rest
  name: sprinkler1
  resource: http://x.x.x.x:8080/js?pw=XXX
  value_template:>
    {% if value_json.sn[0] | int == 1 %}
      On
    {% elif value_json.sn[0] | int == 0 %}
      Off
    {% else %}
      unknown
    {% endif %}

Another option is to use a binary REST sensor instead:

binary_sensor:
  platform: rest
  name: sprinkler1
  resource: http://x.x.x.x:8080/js?pw=XXX
  value_template: "{{ value_json.sn[0] }}"

This will automatically convert "1" to on.

2 Likes

I think your template from your first post should also work but you need to complete your variables:

“states.sensor.sprinkler1” should be “states.sensor.sprinkler1.state”

so:

value_template: “{% if states.sensor.sprinkler1.state == '1' %}On{% elif states.sensor.sprinkler1.state == '0' %}Off{% endif %}”

Also make sure that whatever editor you’re using uses “standard” text-style quotation marks. The ones you posted in your template above weren’t simple text marks. I’m pretty sure the ones you posted will make your code not work.

‘1’ compared to '1'

Many thanks - your binary_sensor option is far simpler

Hi, thanks for the tip I’m using N++

Hi,
how to the inverse mode ?
I have ‘on’, how to display 1 or 0 ?
Is there a +simplest mode of this ?

{% if is_state('sensor.side_door','on') %}1    {% else %}0     {% endif %}

thanks