WTH can't input helpers be read only in UI

Note:

This sensor got it’s own post here. I’ve adjusted it a bit and added the suggestions made in another post in this thread. It’s now also added to the cookbook.

@123
Here you go, an updated version.
You can set a default setting if you want to store the timestamp or not in the default_timestamp attribute of the template sensor, but you can also overrule that setting using set_timestamp: true or set_timestamp: false in the event data

Updated code for the template sensor:

template:
  - trigger:
      - platform: event
        event_type: set_variable
      - platform: event
        event_type: remove_variable
    sensor:
      - unique_id: 4a4c8e53-9e68-4198-9cc5-b336e228ea4d
        name: Variables
        state: Variables
        attributes:
          default_timestamp: true
          variables: >
            {% set current = this.attributes.get('variables', {}) %}
            {% if trigger.event.event_type == 'set_variable' %}
              {% if trigger.event.data.get('set_timestamp', this.attributes.get('default_timestamp', false)) %}
                {% set new = {trigger.event.data.key: {'value': trigger.event.data.value, 'timestamp': now().isoformat()}} %}
              {% else %}
                {% set new = {trigger.event.data.key: trigger.event.data.value} %}
              {% endif %}
              {{ dict(current, **new) }}
            {% elif trigger.event.event_type == 'remove_variable' %}
              {{ dict(current.items() | rejectattr('0', 'eq', trigger.event.data.key)) }}
            {% endif %}

To add a variable (in an automation or script):

action: # for script this is sequence:
  - event: set_variable
    event_data: 
      key: some_test
      value: Some Value
      set_timestamp: false # optional, by default the setting in the sensor will be used, if not added there, the default is false

Result (attributes of sensor.variables):

default_timestamp: true
variables:
  test_without_timestamp: What time is it?
  test_with_timestamp:
    value: I know the time!
    timestamp: '2022-10-02T20:19:41.713241+02:00'
friendly_name: Variables

To remove a variable (in an automation or script):

action: # for script this is sequence:
  - event: remove_variable
    event_data: 
      key: some_test

To get a variable out of the sensor you will have to use templates:

# with timestamp
some_key: "{{ state_attr('sensor.variables', 'variables').variable_key.value }}"

# without timestamp
some_key: "{{ state_attr('sensor.variables', 'variables').variable_key }}"
19 Likes