Smart Heating when no entries in calendar

Hi!
I was trying for many days to automate my smart heater so that it would go on as soon as there are no entries left in my calendar for the rest of the day. So that if I would be ready with school and I am about to drive home my smart heater starts.
I tried setting up a binary_sensor or a value template as an condition. But it did not work.

binary_sensor:
  - platform: template
    sensors:
      schedule_remaining:
        value_template: >
          {% set schedule = states.calendar.my_calendar.attributes.start_time %}
          {% if schedule %}
            {% set remaining = schedule | length %}
            {% if remaining == 0 %}
              off
            {% else %}
              on
            {% endif %}
          {% else %}
            off
          {% endif %}
        device_class: presence
value_template: "{{ (as_timestamp(now().strftime('%Y-%m-%d 23:59:59')) - as_timestamp(state_attr('calendar.your_calendar_entity', 'start_time'))) > 0 }}"

I have some coding experience but I am by no means a professional. Has someone of you solved this problem jet or can solve it?

I do something similar.
I rent out 2 rooms in my home, and have an input boolean that turns on guest mode for each room. Its controlled by a calendar connected to AirBnB, so the boolean is true when the calendar has something in it for that day/time, and off otherwise. You should be able to use this to do what you need.

I didnt need to created a separate binary sensor for this:-

alias: Guest Mode - On/Off (AirBnB)
description: ""
trigger:
  - platform: time_pattern
    hours: /1
condition:
  - condition: state
    entity_id: input_boolean.guest_mode_override_calendar
    state: "off"
action:
  - service: input_boolean.turn_{{states('calendar.rental_control_ensuite_room')}}
    data: {}
    target:
      entity_id: input_boolean.guest_mode_ensuite
  - service: input_boolean.turn_{{states('calendar.rental_control_green_room')}}
    data: {}
    target:
      entity_id: input_boolean.guest_mode_green
mode: single

You dont have to check each hour like I did. You could trigger on a calendar entity change.
The reason I do it this way is because I can override the calendar with another boolean so this makes sure guest mode is always in the right state.

Thanks for your answer. But what if I checked the condition right when I have my break. Then the calendar would be set to Off, even though I still have school that day.
That’s why I wanted to check whether the next appointment is on the next day, i.e. the calendar has no more entries for today.

Hi! Thanks for your help. After a full day of continuously trying geting it to work it now finally does what it is supposed to do. :sweat_smile:
I now created an automation with a tempate condition with the following code:

{% if state_attr('calendar.my_calendar_entity', 'start_time') <= now().strftime("%Y-%m-%d 23:59:59") %}
  false
{% else %}
  true
{% endif %}