Hi all, brand new to the world of HA and coding (two weeks in to either), I used the dark arts of youtube, AI and far too much time to try and create an coding solution (if that is what it is called) for my problem.
Basically, I want to try and get a routine to start before a trigger based on the given time that the trigger/ alarm is planned for.
THE VISION -
I want to try and get my heating to turn on in the bedroom 2 hours before my alarm and lights to run a gentle wake up light fade on 1 hour before my first alarm as long as the following criteria are met:
- it is between August and May
- the first alarm of the day only
- as long as the alarm is set between 5am and 9am
- from either my phone or my partners phone
- but ensuring that the person is at home (so ignoring all alarms if the respective phone is not connected to the wifi)
my plan is to run the following code at 2am as a routine and try and use the output times to trigger the heating and lighting as automations. But I have no idea where I can put this code or how to get the times out of the code and into somewhere where I can use them in HA. Am I being completely stupid trying to use this in routines? Any help, and or comments on the actual code would be greatly appreciated.
{% set current_time = now() %}
{% set current_date = current_time.date() %}
{% set current_hour = current_time.hour %}
{% set start_of_august = '08-01' | as_datetime %}
{% set end_of_may = '05-31' | as_datetime %}
{% set alarm_list = [] %}
{# 1. Trigger time is 2 AM #}
{% if current_hour == 2 %}
{% if current_date >= start_of_august.date() and current_date <= end_of_may.date() %}
{# Check if Mike's phone is connected #}
{% if is_state('sensor.mikeys_phone_wi_fi_connection', 'connected') %}
{% set mike_next_alarm = states('sensor.mike_phone_device_next_alarm') %}
{% if mike_next_alarm != 'unavailable' %}
{% set mike_alarm_time = mike_next_alarm | as_datetime %}
{% if mike_alarm_time.hour >= 5 and mike_alarm_time.hour <= 9 %}
{% do alarm_list.append(mike_alarm_time) %}
{% endif %}
{% endif %}
{% endif %}
{# Check if Marita's phone is connected #}
{% if is_state('sensor.marita_phone_wi_fi_connection', 'connected') %}
{% set marita_next_alarm = states('sensor.marita_phone_next_alarm') %}
{% if marita_next_alarm != 'unavailable' %}
{% set marita_alarm_time = marita_next_alarm | as_datetime %}
{% if marita_alarm_time.hour >= 5 and marita_alarm_time.hour <= 9 %}
{% do alarm_list.append(marita_alarm_time) %}
{% endif %}
{% endif %}
{% endif %}
{# Check if alarm list is empty #}
{% if alarm_list | length == 0 %}
{% set first_alarm_time = 'no_alarm_set' %}
{% else %}
{# Find the earliest alarm time from the list #}
{% set first_alarm_time = alarm_list | min %}
{% set first_alarm_time = first_alarm_time.strftime('%H:%M') %}
{% endif %}
{% else %}
{% set first_alarm_time = 'no_alarm_set' %}
{% endif %}
{{ first_alarm_time }}
{% else %}
{# If it's not 2 AM, no action is performed #}
No action triggered at this time.
{% endif %}