So, the code attached below does work - it’s taken me a while as I’m still new to this, but I’m very happy. At least, up to a point - it seems unnecessarily complicated and I’m wondering if, instead of looping through my data three separate times in jinja templates, I could have done it just once using scripting for the FORs and IFs.
What its doing is reading todays events from an external calendar and then extracting the first start and last end times (but excluding phone appointments) to be used for setting up a custom heating schedule. It’s automated to run just after midnight.
Was there a better way?
Some pseudo code:
Get the Events
For Each Event
Count the Events I care About
Note the first start and last end times
End for
If there are Events I care about
Set the first start and last end times
Set the heating schedule
And the real code:
alias: CheckEvents
sequence:
- service: calendar.get_events
target:
entity_id:
- calendar.xxxx_gmail_com
data:
duration:
hours: 23
response_variable: agenda
- condition:
- condition: template
value_template: >
{% set ns = namespace(mycounter=0) %}
{% for event in agenda["calendar.xxxx_gmail_com"]["events"] %}
{% if event.location != "Phone" %}
{% set ns.mycounter = ns.mycounter + 1 %}
{% endif %}
{% endfor %}
{% if ns.mycounter > 0 %}
{{ true }}
{% else %}
{{ false }}
{% endif %}
- service: input_datetime.set_datetime
data:
timestamp: >-
{% set ns = namespace(firststart = 0, mycounter=0) %}
{% for event in agenda["calendar.xxxx_gmail_com"]["events"] %}
{% if event.location != "Phone" %}
{% if ns.mycounter == 0 %}
{% set ns.firststart = event.start %}
{% endif %}
{% set ns.mycounter = ns.mycounter + 1 %}
{% endif %}
{% endfor %}
{{ as_timestamp(ns.firststart,0) }}
target:
entity_id: input_datetime.treatmentstarts
- service: input_datetime.set_datetime
data:
timestamp: >-
{% set ns = namespace(lastend = 0) %}
{% for event in agenda["calendar.xxxx_gmail_com"]["events"] %}
{% if event.location != "Phone" %}
{% set ns.lastend = event.end %}
{% endif %}
{% endfor %}
{{ as_timestamp(ns.lastend,0) }}
target:
entity_id: input_datetime.treatmentends
- service: script.treatmentspecialset
data: {}
mode: single