IATkachenko / HA-SleepAsAndroid

Sleep As Android integration for Home Assistant
Apache License 2.0
165 stars 25 forks source link

Add an entity for the next scheduled alarm #68

Open arturbalabanov opened 4 months ago

arturbalabanov commented 4 months ago

Heya, thank you a lot for this integration, it's super useful!

One thing that would be nice to be included is an entity showing the next scheduled alarm which can be added to any dashboard. I just implemented this as a template sensor and works great, here's the YAML code:

template:
  - trigger:
      - platform: mqtt
        topic: SleepAsAndroid/arti_s_pixel  # this value is specific to me and needs to be changed to your topic name
        value_template: "{{ value_json.event }}"
        payload: "alarm_rescheduled"
    action:
      variables:
        alarm_name: >
          {% if 'value2' in trigger.payload_json %}
            {{ trigger.payload_json.value2 }}
          {% else %}
            {{ none }}
          {% endif %}
        trigger_datetime: >
          {% if 'value1' in trigger.payload_json %}
            {{ (trigger.payload_json.value1 | int / 1000) | timestamp_local }}
          {% else %}
            {{ none }}
          {% endif %}
    sensor:
      - name: "SleepAsAndroid Alarm"
        unique_id: "sleep_as_android_alarm"
        device_class: timestamp
        icon: >
          {% if alarm_name is none %}
            mdi:alarm-off
          {% else %}
            mdi:alarm
          {% endif %}
        state: "{{ trigger_datetime | default('No scheduled alarm') }}"
        attributes:
          alarm_name: "{{ alarm_name }}"
          trigger_datetime: "{{ trigger_datetime }}"

Here's an example of a dashboard tile with it:

Screenshot 2024-07-03 at 21 12 21

I've testing this with HAOS 2024.6.4. I'm new to home assistant, so I'm not sure what would be the best way to implement this into the integration but even if it's not a core feature, adding this snippet in the README would help other users who want something similar.

IATkachenko commented 4 months ago

Thanks for the idea! We may create dedicated entity for this.

I'll check SaA doc for stable solution: it looks like we need some special trigger to catch next alarm data.

arturbalabanov commented 3 months ago

Thank you for the prompt response @IATkachenko!

I had to make a small change to the template to fix a bug with disappearing alarms (notably adding payload: "alarm_rescheduled" as I somehow missed this originally) and I haven't found any issues for the last two weeks, so I updated the YAML in my original post for future reference.

Also a small note on the data SleepAsAndroid is sending: value1 and value2 are always referring to the next alarm to be fired (as opposed to the alarm that was just rescheduled). I don't know if this is the desired behaviour but for this usecase it works great and simplifies the logic a lot.