Reliable commands

I wondering if HA provides a way to make commands reliable. For example, this is my configuration for an Ethernet I/O board:

  - platform: command_line
    switches:
      relay1:
        command_on: echo -n 11 | nc -q 1 192.168.1.100 6722 
        command_off: echo -n 21 | nc -q 1 192.168.1.100 6722
        command_state: echo -n 00 | nc -q 1 192.168.1.100 6722           
        value_template: "{{ value[0:1] == '1' }}"
        friendly_name: Relay 1

Because I specified the command_state value it is used for feedback - i.e. to change the on/off state according to the actual state of the device.

Sometime, it happens that the command_on (or command_off) is sent, but for any reason the board doesn’t toggle its state. This isn’t a fault of HA, of course! But is there a way to tell HA to retry if the command didn’t work?

If I click on a switch in the page I can manually retry after few seconds, but it’s annoying when it happens in automation.

As far as I’m aware there is no built-in way to do this.

I’ve had similar issues with my Nest devices, so I came up with a way to do this. It’s a bit more complicated than this use case, so here’s the basic idea:

script:
  relay1_turn_on:
    sequence:
      - service: switch.turn_on
        entity_id: switch.relay1
      - service: script.turn_off
        entity_id: script.relay1_check
      - service: script.relay1_check
        data:
          turn_on: true
  relay1_turn_off:
    sequence:
      - service: switch.turn_off
        entity_id: switch.relay1
      - service: script.turn_off
        entity_id: script.relay1_check
      - service: script.relay1_check
        data:
          turn_on: false
  relay1_check:
    sequence:
      - wait_template: >
          {{ is_state('switch.relay1', 'on' if turn_on else 'off') }}
        timeout: '00:00:05'
        continue_on_timeout: 'true'
      - condition: template
        value_template: >
          {{ is_state('switch.relay1', 'off' if turn_on else 'on') }}
      - service_template: >
          {% if turn_on %}
            script.relay1_turn_on
          {% else %}
            script.relay1_turn_off
          {% endif %}

Use one of the first scripts to turn the switch on or off instead of changing the switch directly. You might need to do a bit more to deal with the situation where the relay’s state never changes like it should (e.g., add a counter to the “loop” and stop if it gets too big and maybe send a notification, etc.)

1 Like

Got it. Yes, it gets quite complex soon, while it would be simple enough if handled natively.
Right now I’m going to use this approach only for most important switches. I hope the developers will try to get HA more reliable and begin to use feedbacks to close the control-loop!

1 Like