MQTT binary_sensor value_template

Hi, I have an MQTT topic that publishes a number and I want to use this as a motion binary sensor so that if the number is 0 it’s off otherwise it’s on.

So I assume I can use the value_template like so

# Example configuration.yaml entry
binary_sensor:
  - platform: mqtt
    state_topic: "lab_button/cmnd/POWER"
    value_template: "{%if is_state(entity_id,\"on\")-%}OFF{%-else-%}ON{%-endif%}"

I tried this but any message turns it on, I assume that’s because it’s just catching the else condition.

  - name: Camera Person Garage
    platform: mqtt
    state_topic: "frigate/garage/person"
    device_class: motion
    availability_topic: "frigate/available"
    unique_id: "camera_person_garage"
    value_template: "{%if is_state('binary_sensor.camera_person_garage',0)-%}OFF{%-else-%}ON{%-endif%}"

Try this:

binary_sensor:
  - platform: mqtt
    name: "Lab button power"
    state_topic: "lab_button/cmnd/POWER"
    payload_on: 1
    payload_off: 0

Thanks, but the value can go above 1. e.g. if 2 people are detected it will show 2 and that would still be an ON for me.

Ah sorry, I got confused by your example:

Try this:

value_template: '{{ value_json.state | int > 0 }}'

that just comes back and says the motion is clear all the time, it’s not a json value being passed it’s just a raw 0 or 1 or 2 etc so I wonder if that makes a difference. Thanks for looking at this by the way.

If it helps I have a seperate sensor called sensor.garage_person that shows the count, I think my first hurdle was using binary_sensor.camera_person_garage in my config for itself as that should always be on or off and not the number if that makes sense.

Try this:

value_template: '{{ value | int > 0 }}'

That still says it’s clear all the time, what should that return, maybe I need to set payload_on: true for that as well?

Brilliant I did have to add the payload_on and off parts as well but it’s working perfectly now. Thank you very much for your help, I think I need to brush up on a few of the configuration basics now.

  - name: Camera Person Garage
    platform: mqtt
    state_topic: "frigate/garage/person"
    device_class: motion
    availability_topic: "frigate/available"
    unique_id: "camera_person_garage"
    payload_on: true
    payload_off: false
    value_template: '{{ value | int > 0 }}'

1 Like