Need help to control MQTT Fan using input number automation

I am using the input number and automation to update the slider.
While this works, the MQTT message is sent twice to the switch as the automation updates the slider, then another message is sent out by the front end.
Is there a way this can be avoided.

  • alias: “TestRoom Fan Speed”
    initial_state: true
    hide_entity: true
    trigger:
    platform: state
    entity_id: input_number.testroom_fan_speed
    action:

    • service: mqtt.publish
      data_template:
      topic: “/home/TestRoom/speed_Sub/”
      payload: “{{ states(‘input_number.testroom_fan_speed’) | int }}”
      retain: true
      qos: 0
  • alias: “TestRoom Fan Speed Slider”
    initial_state: false
    hide_entity: true
    trigger:
    platform: mqtt
    topic: “/home/TestRoom/speed/”
    action:

    • service: input_number.set_value
      data_template:
      entity_id: input_number.testroom_fan_speed
      value: “{{ trigger.payload }}”

This is the code I am using.

Thanks in advance.

If you want bidirectional control of that input_number via MQTT, this is the way to do it. It shouldn’t be a big deal publishing the same value to the state topic from 2 devices at the same time.

If you really want to stop it, you’ll have to add a conditional around the state trigger for the input number to only update if the mqtt automation hasn’t been triggered in some amount of time.

- alias: “TestRoom Fan Speed”
  initial_state: true
  hide_entity: true
  trigger:
    platform: state
    entity_id: input_number.testroom_fan_speed
  condition: 
    - condition: template
      # Only trigger if the MQTT automation hasn't been triggered for at least half second.
      # If it has, this update is probably from MQTT, so nothing to do.
      value_template: "{{ as_timestamp(now()) - as_timestamp(state_attr('automation.testroom_fan_speed', 'last_triggered')) > 0.5 }}"
  action:
    - service: mqtt.publish
      data_template:
        topic: “/home/TestRoom/speed_Sub/”
        payload: “{{ states(‘input_number.testroom_fan_speed’) | int }}”
        retain: true
        qos: 0

We now only send the mqtt message if it’s been more than .5 seconds since receiving the mqtt message. Keep in mind, if you now try to update the slider 2 times in half a second…the 2nd one won’t be sent assuming you get an MQTT speed state update from the first one.

You could probably shrink the window there to maybe 0.25, but I feel like we’d be cutting it close in how fast we are processing this trigger.

1 Like

I struggled wit this as well and I think for this example the correct value_template should read

value_template: "{{ as_timestamp(now()) - as_timestamp(state_attr('automation.testroom_fan_speed_slider', 'last_triggered')) > 0.5 }}"
1 Like

Thanks a ton, this worked like a charm. @jocnnor

thanks a ton. @realjax