MQTT-publish based on/off switch which relies on MQTT-subscribe JSON encoded numeric value

I have a MQTT standing desk which publishes a JSON encoded blob containing the current height as an integer value (ranging from 400 to 6000). Another MQTT namespace sets the value back to the device, but is fuzzy (e.g. set to 4000 the device motors might spin to 4050).

The value published by desk is similar to: {"height":340}

I wish to create an on/off button which executes when the device advises that the integer value is above 2000. I have scripts ‘mqqt_standing_desk_down’ and ‘mqqt_standing_desk_up’ which work correctly, and a sensor which correctly displays the numeric value in the UI:

sensor:
  platform: mqtt
  state_topic: 'positionUpdate'
  force_update: true
  name: StandingDeskSensor
  value_template: "{{ value_json['height'] }}"

How can I add a button which is ON when the value of StandingDeskSensor is greater than 2000, which toggles the scripts to raise / lower the desk? I have so far only achieved a button which always thinks it’s off and will only ever raise (but not lower ) the desk.

Thanks!

With a template sensor? Like:

  - platform: template
    name: "DeskUP"
    value_template: >-
        {{ states('sensor.StandingDeskSensor') >= 2000 }}

This will evaluate every time StandingDeskSensor changes, and return on if true and off for everything else.

By the way - don’t trust my syntax, have a read of template binary sensors :slight_smile:

You will then need to integrate that sensor with a suitable automation if you want to control the desk.

Or maybe better still use a Template switch:

But however you do it templates are the answer.

Thanks, I was almost on the right track as it were but the binary sensor syntax you linked got me there. The final solution was:

switch:
  - platform: template
    switches:
      deskup:
        value_template: >-
          {{ states('sensor.StandingDeskSensor')|float >= 2000 }}
        turn_on:
          service: script.mqqt_standing_desk_up
        turn_off:
          service: script.mqqt_standing_desk_down

Interesting that explicit casting needs to occur, without the |float the that would always evaluate as false, but it’s fixed now irrespective of what the cause was :slight_smile:

The state value of all entities is a string. If you want to use it in a numeric comparison, you will have to convert the string value to either integer or float.

One more thing, all entity names are always in lower case. Check Developer Tools > States and you will see that there is a sensor.standingdesksensor and not a sensor.StandingDeskSensor as referenced in your value_template.

Hah! - I have been caught with that before - which is why I advised to check my syntax. :blush: