State restoration with Broadlink switches

I have been using a Broadlink RM pro to control several RF sockets. I didn’t like the fact that they don’t show up as normal switches but show a separate on and off button. Initially I usd something like this:

customize:
  switch.outside_light:
    assumed_state: false

That works but the state resets to off if Home Assistant restarts, which can cause problems if this happens while one of the switches is on. To work around this I have done the following:

Removed all switches from the Broadlink config, so it just looks like this:

switch:
  - platform: broadlink
    host: *.*.*.*
    mac: '**:**:**:**:**:**'

Created a script which takes three parameters (the packet to send to the RM Pro, the entity_id of an input_boolean which will be used to retain the state of the switch, and the state itself - on or off):

broadlink_switch_control:
  sequence:
    - service: switch.broadlink_send_packet_*_*_*_*
      data_template:
        packet:
          '{{ packet }}'
    - service_template: >-
        {% if state %}
          input_boolean.turn_on
        {% else %}
          input_boolean.turn_off
        {% endif %}
      data_template:
        entity_id: "{{ entity_id }}"

Created an input_boolean for each switch (I used the same as the name of the switch).

Created template switches or lights as follows:

- platform: template
    switches:
      outside_light:
        friendly_name: "Outside Light"
        value_template: "{{ is_state('input_boolean.outside_light', 'on') }}"
        turn_on:
          service: script.broadlink_switch_control
          data:
            entity_id: input_boolean.outside_light
            state: on
            packet: 'svcy...AAA'
        turn_off:
          service: script.broadlink_switch_control
          data:
            entity_id: input_boolean.outside_light
            state: off
            packet: 'sj0y...AAA' 

Can anybody think of any way that this can be simplified?

Edit: Corrected to state that there are actually three parameters for the script.

5 Likes

Hi there,

is this still works?

If you are on Home Assistant 0.115, where Broadlink was changed to be configured via the UI, or later the broadlink_switch_control script should be something like this instead:

broadlink_switch_control:
  sequence:
  - service: remote.send_command
    data:
      entity_id: remote.name_of_remote
      command: 'b64:{{ packet }}'
  - service: >-
        {% if state %}
          input_boolean.turn_on
        {% else %}
          input_boolean.turn_off
        {% endif %}
    data:
      entity_id: '{{ entity_id }}'

Replacing remote.name_of_remote with the remote entity created when you setup the Broadlink integration.

Note: This is also using service and data instead of service_template and data_template, as 0.115 also removed the requirement to use the _template suffix