Global variables, yet again - automation to store and recover (templated) value

I have read a few threads about global variables. I was not able to work out a feasible solution.

My problem:

  • I have a sensor that lists event dates under an attribute array (which is usually empty but gets an entry when a new event is published);
  • I want to monitor this and raise a notification when a new entry turns up;
  • Do this only once for every new event/date;

I have jinja2 code that parses the sensor and retrieves the datetime that I need. The main idea is to issue a notification then store the value to compare with next time the automation runs so as to trigger the notification only once.

Please advise what is the best way to implement this. I don’t need someone to write the automation for me, just some guidance.

Planned solution 1:

  • Setup an automation that triggers against the sensor attribute changing (or appearing) - may need to use templating to get at the correct value.
  • Compare the value retrieved with the stored one - how? input helper or trigger based template sensor (not sure how to use this or whether it’s even adequate)?
  • If value is new, trigger notification and update “global” variable.

Possible solution 2:

  • Setup a binary sensor that flips to true once there is a new event and it differs from the stored datetime.
    • false when available_events array is empty or when first value is the same as input helper state
    • true when array is not empty and value differs from input helper state
  • Setup an automation based on that sensor becoming true, then update the stored variable, causing the binary sensor to become false.

Sensor attributes (shortened). The array I am after is available_events:

event_types:
  - octopus_energy_all_octoplus_saving_sessions
event_type: octopus_energy_all_octoplus_saving_sessions
account_id: X
available_events: []
joined_events:
  - id: 1163
...
  - id: 1168
    start: "2023-12-12T17:00:00+00:00"
    end: "2023-12-12T18:00:00+00:00"
    rewarded_octopoints: null
friendly_name: Octopus saving session events

Jinja2 code to retrieve first available_events guessing that it will follow the structure of the joined_events array (will be sure when I have a sample). I could use this for both solutions.

{% set available_events=state_attr('event.octopus_energy_X_octoplus_saving_session_events','available_events') -%}
{% if available_events -%}
  {% for ae in available_events -%}
    {% if loop.first and ae is iterable -%}
{{ ae['start'] }}
    {% endif -%}
  {% endfor -%}
{% endif %}

Convert the automation over to a template and use this to calculate the value.