blueprint:
  name: IKEA Tradfri - ZHA/Z2M - E1766
  description: |
  source_url: https://github.com/EPMatt/awesome-ha-blueprints/blob/main/blueprints/controllers/ikea_e1766/ikea_e1766.yaml
  domain: automation
  homeassistant:
    min_version: 2024.10.0
  input:
    integration:
      name: (Required) Integration
      description: Integration used for connecting the remote with Home Assistant. Select one of the available values.
      selector:
        select:
          options:
            - deCONZ
            - ZHA
            - Zigbee2MQTT
    controller_device:
      name: (deCONZ, ZHA, Zigbee2MQTT Required) Controller Device
      description: The controller device to use for the automation. Choose a value only if the remote is integrated with deCONZ, ZHA, Zigbee2MQTT.
      default: ''
      selector:
        device:
          filter:
            # source: https://www.zigbee2mqtt.io/devices/E1766.html#ikea-e1766
            - integration: mqtt
              manufacturer: IKEA
              model: TRADFRI open/close remote
            # For backwards compatability with z2m 1.x. model_id is added to end of model rather than a seperate attribute in z2m 2.x
            - integration: mqtt
              manufacturer: IKEA
              model: TRADFRI open/close remote (E1766)
            # source: https://github.com/dresden-elektronik/deconz-rest-plugin/wiki/Supported-Devices
            - integration: zha
              manufacturer: IKEA of Sweden
              model: TRADFRI open/close remote
            - integration: deconz
              manufacturer: IKEA of Sweden
              model: TRADFRI open/close remote
          multiple: false
    helper_last_controller_event:
      name: (Required) Helper - Last Controller Event
      description: Input Text used to store the last event fired by the controller. You will need to manually create a text input entity for this, please read the blueprint Additional Notes for more info.
      default: ''
      selector:
        entity:
          domain: input_text
    # inputs for custom actions
    action_button_up_short:
      name: (Optional) Up button short press
      description: Action to run on short up button press.
      default: []
      selector:
        action:
    action_button_up_release:
      name: (Optional) Up button release
      description: Action to run on up button release after long press.
      default: []
      selector:
        action:
    action_button_up_double:
      name: (Optional) (Virtual) Up button double press
      description: Action to run on double up button press.
      default: []
      selector:
        action:
    action_button_down_short:
      name: (Optional) Down button short press
      description: Action to run on short down button press.
      default: []
      selector:
        action:
    action_button_down_release:
      name: (Optional) Down button release
      description: Action to run on down button release after long press.
      default: []
      selector:
        action:
    action_button_down_double:
      name: (Optional) (Virtual) Down button double press
      description: Action to run on double down button press.
      default: []
      selector:
        action:
    # inputs for enabling double press events
    button_up_double_press:
      name: (Optional) Expose up button double press event
      description: Choose whether or not to expose the virtual double press event for the up button. Turn this on if you are providing an action for the up button double press event.
      default: false
      selector:
        boolean:
    button_down_double_press:
      name: (Optional) Expose down button double press event
      description: Choose whether or not to expose the virtual double press event for the down button. Turn this on if you are providing an action for the down button double press event.
      default: false
      selector:
        boolean:
    # helpers used to properly recognize the remote button events
    helper_double_press_delay:
      name: (Optional) Helper - Double Press delay
      description: Max delay between the first and the second button press for the double press event. Provide a value only if you are using a double press action. Increase this value if you notice that the double press action is not triggered properly.
      default: 500
      selector:
        number:
          min: 100
          max: 5000
          unit_of_measurement: milliseconds
          mode: box
          step: 10
    helper_debounce_delay:
      name: (Optional) Helper - Debounce delay
      description:
        Delay used for debouncing RAW controller events, by default set to 0. A value of 0 disables the debouncing feature. Increase this value if you notice custom actions or linked Hooks running multiple times when interacting with the device. When the controller needs to be debounced,
        usually a value of 100 is enough to remove all duplicate events.
      default: 0
      selector:
        number:
          min: 0
          max: 1000
          unit_of_measurement: milliseconds
          mode: box
          step: 10
# Automation schema
variables:
  # convert input tags to variables, to be used in templates
  integration: !input integration
  button_up_double_press: !input button_up_double_press
  button_down_double_press: !input button_down_double_press
  helper_last_controller_event: !input helper_last_controller_event
  helper_double_press_delay: !input helper_double_press_delay
  helper_debounce_delay: !input helper_debounce_delay
  # integration id used to select items in the action mapping
  integration_id: '{{ integration | lower }}'
  # adjusted debounce delay so that the resulting double press delay is exactly as specified by the user when running the action, taking also account of debouncing
  # make sure it never goes below the minimum double press delay
  adjusted_double_press_delay: '{{ [helper_double_press_delay - helper_debounce_delay, 100] | max }}'
  # mapping between actions and integrations
  actions_mapping:
    deconz:
      button_up_short: ['1002']
      button_up_release: ['1003']
      button_down_short: ['2002']
      button_down_release: ['2003']
    zha:
      button_up_short: [up_open]
      button_up_release: [stop]
      button_down_short: [down_close]
      button_down_release: [stop]
    zigbee2mqtt:
      # source: https://www.zigbee2mqtt.io/devices/E1766.html#ikea-e1766
      button_up_short: [open]
      button_up_release: [stop]
      button_down_short: [close]
      button_down_release: [stop]
  # pre-choose actions for buttons based on configured integration
  # no need to perform this task at automation runtime
  button_up_short: '{{ actions_mapping[integration_id]["button_up_short"] }}'
  button_up_release: '{{ actions_mapping[integration_id]["button_up_release"] }}'
  button_down_short: '{{ actions_mapping[integration_id]["button_down_short"] }}'
  button_down_release: '{{ actions_mapping[integration_id]["button_down_release"] }}'
  # integrations which need to store the previous press event to determine which button was released
  integrations_with_prev_event_storage: [zha, zigbee2mqtt]
  # build data to send within a controller event
  controller_id: !input controller_device
mode: restart
max_exceeded: silent
triggers:
  # triggers for zigbee2mqtt mqtt device action
  - trigger: device
    domain: mqtt
    device_id: !input controller_device
    type: action
    subtype: open
  - trigger: device
    domain: mqtt
    device_id: !input controller_device
    type: action
    subtype: stop
  - trigger: device
    domain: mqtt
    device_id: !input controller_device
    type: action
    subtype: close
  - trigger: device
    domain: mqtt
    device_id: !input controller_device
    type: action
    subtype: stop
  # triggers for other integrations
  - trigger: event
    event_type:
      - deconz_event
      - zha_event
    event_data:
      device_id: !input controller_device
conditions:
  - condition: and
    conditions:
      # check that the button event is not empty
      - >-
        {%- set trigger_action -%}
        {%- if integration_id == "zigbee2mqtt" -%}
        {{ trigger.payload }}
        {%- elif integration_id == "deconz" -%}
        {{ trigger.event.data.event }}
        {%- elif integration_id == "zha" -%}
        {{ trigger.event.data.command }}{{"_" if trigger.event.data.args|length > 0}}{{ trigger.event.data.args|join("_") }}
        {%- endif -%}
        {%- endset -%}
        {{ trigger_action not in ["","None"] }}
actions:
  # debouncing - when automation is triggered multiple times, the last automation run is the one which completes execution, due to mode restart
  # therefore previous runs must wait for the debounce delay before executing any other action
  # if the delay expires and the automation is still running it means it's the last run and execution can continue
  - delay:
      milliseconds: !input helper_debounce_delay
  # extract button event from the trigger
  # provide a single string value to check against
  - variables:
      trigger_action: >-
        {%- if integration_id == "zigbee2mqtt" -%}
        {{ trigger.payload }}
        {%- elif integration_id == "deconz" -%}
        {{ trigger.event.data.event }}
        {%- elif integration_id == "zha" -%}
        {{ trigger.event.data.command }}{{"_" if trigger.event.data.args|length > 0}}{{ trigger.event.data.args|join("_") }}
        {%- endif -%}
      deserialized_state: '{{ (states(helper_last_controller_event) | from_json) if helper_last_controller_event is not none and (states(helper_last_controller_event) | regex_match("^\{\s*?((\"a\":\s*?\".*\"|\"t\":\s*?\d+\.\d+)(,\s*?)?){2}\s*?\}$")) else {} }}'
      trigger_delta: '{{ (as_timestamp(now()) - (deserialized_state.t | default(0))) * 1000 }}'
      last_controller_event: '{{ (deserialized_state.a | default("")) }}'
  # update helper
  - action: input_text.set_value
    data:
      entity_id: !input helper_last_controller_event
      value: '{{ {"a":trigger_action,"t":as_timestamp(now())} | to_json }}'
  # choose the sequence to run based on the received button event
  - choose:
      - conditions: '{{ trigger_action | string in button_up_short }}'
        sequence:
          - choose:
              # if double press event is enabled
              - conditions: '{{ button_up_double_press }}'
                sequence:
                  - choose:
                      # if previous event was a short press
                      - conditions: '{{ trigger_action | string == last_controller_event and trigger_delta | int <= helper_double_press_delay | int }}'
                        sequence:
                          # store the double press event in the last controller event helper
                          - action: input_text.set_value
                            data:
                              entity_id: !input helper_last_controller_event
                              value: '{{ {"a":"double_press_up","t":as_timestamp(now())} | to_json }}'
                          # run the double press action
                          # fire the event
                          - event: ahb_controller_event
                            event_data:
                              controller: '{{ controller_id }}'
                              action: button_up_double
                          # run the custom action
                          - choose:
                              - conditions: []
                                sequence: !input action_button_up_double
                    # previous event was not a short press
                    default:
                      # wait for the double press event to occur, within the provided delay
                      # if the second press is received, automation is restarted
                      - delay:
                          milliseconds: '{{ adjusted_double_press_delay }}'
                      # if delay expires, no second press was received, therefore run the short press action
                      # run the short press action
                      # fire the event
                      - event: ahb_controller_event
                        event_data:
                          controller: '{{ controller_id }}'
                          action: button_up_short
                      # run the custom action
                      - choose:
                          - conditions: []
                            sequence: !input action_button_up_short
            # if double press event is disabled run the action for the single short press
            default:
              # fire the event
              - event: ahb_controller_event
                event_data:
                  controller: '{{ controller_id }}'
                  action: button_up_short
              # run the custom action
              - choose:
                  - conditions: []
                    sequence: !input action_button_up_short
      - conditions:
          - '{{ trigger_action | string in button_up_release }}'
          # for integrations which need to store the last controller event, need to check the previous button event, stored in the provided input_text
          - '{{ not integration_id in integrations_with_prev_event_storage or last_controller_event | string in button_up_short }}'
        sequence:
          # fire the event
          - event: ahb_controller_event
            event_data:
              controller: '{{ controller_id }}'
              action: button_up_release
          # run the custom action
          - choose:
              - conditions: []
                sequence: !input action_button_up_release
      - conditions: '{{ trigger_action | string in button_down_short }}'
        sequence:
          - choose:
              # if double press event is enabled
              - conditions: '{{ button_down_double_press }}'
                sequence:
                  - choose:
                      # if previous event was a short press
                      - conditions: '{{ trigger_action | string == last_controller_event and trigger_delta | int <= helper_double_press_delay | int }}'
                        sequence:
                          # store the double press event in the last controller event helper
                          - action: input_text.set_value
                            data:
                              entity_id: !input helper_last_controller_event
                              value: '{{ {"a":"double_press_down","t":as_timestamp(now())} | to_json }}'
                          # run the double press action
                          # fire the event
                          - event: ahb_controller_event
                            event_data:
                              controller: '{{ controller_id }}'
                              action: button_down_double
                          # run the custom action
                          - choose:
                              - conditions: []
                                sequence: !input action_button_down_double
                    # previous event was not a short press
                    default:
                      # wait for the double press event to occur, within the provided delay
                      # if the second press is received, automation is restarted
                      - delay:
                          milliseconds: '{{ adjusted_double_press_delay }}'
                      # if delay expires, no second press was received, therefore run the short press action
                      # run the short press action
                      # fire the event
                      - event: ahb_controller_event
                        event_data:
                          controller: '{{ controller_id }}'
                          action: button_down_short
                      # run the custom action
                      - choose:
                          - conditions: []
                            sequence: !input action_button_down_short
            # if double press event is disabled run the action for the single short press
            default:
              # fire the event
              - event: ahb_controller_event
                event_data:
                  controller: '{{ controller_id }}'
                  action: button_down_short
              # run the custom action
              - choose:
                  - conditions: []
                    sequence: !input action_button_down_short
      - conditions:
          - '{{ trigger_action | string in button_down_release }}'
          # for integrations which need to store the last controller event, need to check the previous button event, stored in the provided input_text
          - '{{ not integration_id in integrations_with_prev_event_storage or last_controller_event | string in button_down_short }}'
        sequence:
          # fire the event
          - event: ahb_controller_event
            event_data:
              controller: '{{ controller_id }}'
              action: button_down_release
          # run the custom action
          - choose:
              - conditions: []
                sequence: !input action_button_down_release