Sync iOS 17 Sleep Alarm to HA

Got it to work but it took longer to implement than expected.

I am in the US and I believe that the ISO formatting is not working for me. I had to change all the adjusted date from ISO to Custom: yyyy-MM-dd HH:mm:ss.

After the change, I no longer have the issue mentioned before with multiple dates showing. I believe that time format in the iPhone is most likely the issue.

Has anyone found a way to subtract some minutes to the alarm time? Maybe @M20Lucas you know how?

Much thanks.

Aha! After some poking around, I figured out what’s going on and why people are getting more than one time entry.

For some reason, iOS is operating on the “Adjusted Date” variable differently when ISO8601 encoding is enabled. It appears to be concatenating the different time operations instead of operating on the variable like you’d expect. The solution is to configure the first two instances of “Adjusted Date” using Date Format = Medium and Time Format = Short.

The formatting must be changed to ISO 8601 when the data is written into the dictionary:

This seems to have fixed my issues! Thanks for putting this together @M20Lucas!

1 Like

Hey all! Thanks a lot for the shortcut and fixing the issues :slight_smile: I got it working after adjusting the date to medium and also after syncing the date/time.

I am however, having one issue and that’s when I create the alarm after midnight, or in the same day I will be waking up. In this case, the shortcut creates a date one day after. Any idea how to add an IF value in there? Thanks a lot!

I use Node-red with the time node!

Try changing this part of the Shortcut from “Tomorrow” to “Today”.

I am facing this also. It seems this automation will disable any health alarm that is not a part of the schedule. Rather dangerous and I almost found this bug the hard way! lol

I’ll play around and see if I can find a solution.

ETA I can’t find a solution. Seems like a bug in the “toggle” function.

Somewhat hilarious that Apple didn’t write a function to just get the current alarm status.

Hi Marcos, I’m not used to work with that, please can you tell me how you do it?

Much thanks.

Works really wel together with this blueprint! Thanks!

Open your Home Assistant instance and show the blueprint import dialog with a specific blueprint pre-filled.

@M20Lucas thank you very much for creating this post and the automation; the Shortcut and HA work very well together. I’d like to expand to the following use case: I have a dimmer light that I want to gradually start a certain amount of minutes before the actual alarm is set.

Basically to subtract a number (20) of minutes from the Adjusted Date:

I’ve checked that the value as calculated in this step is an ISO 8601 Date/Time Format. Unfortunately this adjustment does not propagate to the Date/Time Helper in HA. Does anyone know what goes wrong here? I prefer to do the adjustment already on the iOS side preferably and have an advanced date/time in HA.

For reference, this is the successive config I’ve set up for gradual increase of the brightness:

trigger:
  - platform: time
    at: input_datetime.wekker
action:
  - service: light.turn_on
    metadata: {}
    data:
      transition: 1200
      brightness_pct: 80
    target:
      area_id: bedroom
      entity_id: light.hanging_light_bedroom

Many thanks.

So I fixed this with a solution in HA through implementing a second date/time helper.
Useful thread that helped me in this solution: Input.datetime automation to offset another input.datetime

The config I implemented:

`alias: Time - Update offset for morning routing
description: ""
trigger:
  - platform: state
    entity_id: input_datetime.wekker
condition: []
action:
  - service: input_datetime.set_datetime
    data:
      time: >-
        {{ strptime(states('input_datetime.wekker'), '%H:%M:%S') -
        strptime('30', '%M') }}
    target:
      entity_id: input_datetime.wake_up_light
mode: single`

So, I think this solution have issues. If you change the sleep mode before the alarm goes off on the same day, this will make HA believe the alarm if for tomorrow.

I’m not an expert in IOS Shortcut, so correct me if I’m wrong! Also, when an alarm is skipped for the day, I believe we should get the next alarm day! And if the alarm is not set for everyday (week-end off), this is also a problem with the current implementation.

My suggestion consist to send all the data to HA and use a script to parse, understand, and generate the right alarm time and other variables!
I started this HA Template and I will probably write down a script + share a shortcut once it’s tested but I would like some feedbacks!

{# INPUTS from IOS #}

  {# This block is not used yet but I beleive we should pass them #}
    {% set allowsSnooze = true %}
    {% set repeats = true %}

  {# This is what I currently use which come from IOS #}
    {% set isEnabled = true %}
    {% set hours = 6 %}
    {% set minutes = 30 %}
    {% set repeatDays = "Wednesday\nMonday\nTuesday\nThursday\nFriday" %}
    {% set IosNow = "2024-03-18T20:07:14-05:30" %}


{# Let's calculate the TZ diff #}
  {# Extract TZ for IOS #}
  {% set iosTZ = (IosNow | as_datetime).strftime('%z') | int %}
  {% set iosMinutesTZ = iosTZ - ((iosTZ / 100) | int) * 40 %}

  {# Extract TZ for HA #}
  {% set haTZ = now().strftime('%z') | int %}
  {% set haMinutesTZ = haTZ - ((haTZ / 100) | int) * 40 %}

  {# Calculate the offset in minutes for IOS to HA #}
  {% set diffTZ = iosMinutesTZ - haMinutesTZ %}


{# Let's set some vairable #}
{% set alarmTimeStr = hours|string + ':' + minutes|string %}
{% set repeatDaysArray = repeatDays.split('\n')%}
{% set ns = namespace(
  alarmDay = today_at(alarmTimeStr) + timedelta(minutes = diffTZ),
  skippedOnce = false,
  foundDay = false,
  skippedAlarm = false,
) %}


{# Does the alarm could be for today? #}
{% if (ns.alarmDay < now()) %}
 {% set ns.alarmDay = ns.alarmDay + timedelta(days = 1) %}
{%endif%}


{# Let's found which day this alarm is #}
{% for _ in range(0, 8) %}
  {% if (not ns.foundDay) %}
    {% if (ns.alarmDay.strftime('%A') not in repeatDaysArray)%}
      {# This day is not in the list, let go to the next day #}
      {% set ns.alarmDay = ns.alarmDay + timedelta(days = 1) %}
    {% elif (not isEnabled and not ns.skippedOnce) %}
      {# This day is in the list, but we need to skip it #}
      {% set ns.skippedOnce = true %}
      {% set ns.skippedAlarm = ns.alarmDay %}
      {% set ns.alarmDay = ns.alarmDay + timedelta(days = 1) %}
    {% else %}
      {# This is the right day! #}
      {% set ns.foundDay = true %}
    {%endif%}
  {%endif%}
{% endfor %}


{# If we didn't found a day, let's just set alarmDay to false #}
{% if (not ns.foundDay) %}
  {% set ns.alarmDay = false %}
{%endif%}


{# Results! #}
foundDay: {{ns.foundDay}}
alarmDay day of the week: {{ns.alarmDay and ns.alarmDay.strftime('%A')}}
alarmDay: {{ns.alarmDay}}
skippedAlarm: {{ns.skippedAlarm}}
skippedOnce: {{ns.skippedOnce}}

Questions for all:

  • Does my concerns on bugs are valid?
  • Does my template seems to work for you? (you could play with the variable in the header!)
  • Does my inputs match your from IOS? (specifically if HA and IOS are not in the same timezone)

Potential downside:

  • When you have different schedule for different days, this is only sending the current schedule. This means that even if I have one schedule for the week and one for the weekend, and we’re Thursday, and we skip the next alarm, HA will compute the next alarm to be Monday! This could be compensate by running the shortcut every day to make sure when the new schedule is active, HA will receive the proper update.
    - I’m not sure if HA and IOS are not in the same timezone, how this will react! (I updated my script with TZ adjustment)

Hi,

Would it be possible to read the ‘bedtime’ in the same way ? I looked through the automation but I could not work it out how to update it.

Thank you,

Really nice shortcut! Thanks for that!
One small point: If I trigger the shortcut past mid-night it will sync not to the next alarm but to the day after. So another if-clause is needed where you say “get strt of day” from tomorrow.

No the bedtime couldn’t be exported from IOS but with an offset it should be able to be calculated!

I think there is few issue with the HA script.
I’m trying to gather multiple inputs and output (actual and expected) to make sure I could debug it and make everything works 100%.
So far, I saw some problem when there is multiple bedtime for multiple days.

If you found any issues, could you share a description of what’s in the IOS app, what’s the input of the script and the output + expected output?

When the script will be dialed in, I will share it through a script blueprint! I will also try to include some offset for bedtime or early alarm automation (eg: 5min before the alarm)

I think the script works well now! I create another post to not confuse bug from two methods: Sync IOS 17 Sleep alarm to HA (take 2)

1 Like

I have the same issue, but can you explain what the fix is that you’re describing?

I had the same problem as you (and others) and thought I’d share my solution. Here is the link to my version of the shortcut.

From my testing this modified version of the shortcut works almost identically to the original version but it allows for setting alarms the same day as well. One caveat to this is that in certain scenarios it can theoretically run twice a day. For example if you wake up at 08:00 and set an alarm intended for tomorrow at 08:30 (before the time has actually passed 08:30), the shortcut will pass an alarm for today at 08:30 which might not be ideal. It might be possible to find a solution to this but for my use this is fine, as setting an alarm is usually the last thing I do but YMMW.

Another quick note, I made this shortcut on iOS 18 but hopefully that won’t affect the functionality on iOS 17.

this seems to have broken recently in one spesific scenario. if you change just the next alarm in the clock app from having no alarm to having an alarm and dont change the whole schedual the pair of toggles will leave it off again. for some reason the second toggle wont turn it back on if the main schedual is for alarm off. not sure when this broke but i now know i ran into it a few weeks ago (didnt realise what it was till now)

(fwiw, im not using your shortcut but i came across the same solution when wrighting my own. might need to find another way to do it till apple fixes this)

Did you or anyone else find a working solution? I noticed this issue this weekend also. Now the shortcut turns off the wake alarm, clearly not what we want. TIA

unfortunatly not. i didnt put too much time into it though since i dont have to do a manual change that often so i turn off the shortcut automation when i do need to