# example_6_6_1.yaml
# 是否打开闹钟
input_boolean:
  alarm_clock:
    name: 闹钟
    initial: off
    icon: mdi:alarm

# 闹钟的时间
input_datetime:
  alarm_time:
    name: 时间
    has_time: true
    has_date: false
    initial: 07:00

# 播放的音乐选择
input_select:
  alarm_music:
    name: 音乐
    icon: mdi:music
    options:
      - 卡农
      - I Can Feel It Coming
      - 沧海一声笑

# 播放的文字
input_text:
  alarm_text:
    name: 语音提醒
    initial: 该起床了,该起床了！
    min: 0
    max: 30

# 亮灯时长
input_number:
  alarm_light_duration:
    name: 亮灯提醒（分钟）
    initial: 0
    min: 0
    max: 60
    step: 1

# 自动化每分钟触发
automation:
- alias: Alarm Clock
  initial_state: True
  trigger:
    - platform: time_pattern
      minutes: '/1'
      seconds: 0
  # 判断闹钟是否打开，判断当前时间是否与闹钟时间相同
  condition:
    - condition: state
      entity_id: input_boolean.alarm_clock
      state: 'on'
    - condition: template
      value_template: '{{((as_timestamp(now())|int)|timestamp_custom("%H:%M"))==states.input_datetime.alarm_time.state|truncate(5,False,"",0) }}'
  action:
    # 播放文字语音
    - service: tts.google_say
      entity_id: media_player.vlc
      data_template:
        message: '{{states.input_text.alarm_text.state}}'
    # 打开灯
    - service: light.turn_on
      entity_id: light.gateway_light_7c49eb18e3a7
    # 延时5秒钟
    - delay:
        seconds: 5
    # 等待语音播放结束，最长一分钟
    - wait_template: "{{is_state('media_player.vlc','idle')}}"
      timeout: '00:01:00'
      continue_on_timeout: 'true'
    # 延时5秒钟
    - delay:
        seconds: 5
    # 根据选择项，播放对应的音乐
    - service: media_player.play_media
      data_template:
        entity_id: media_player.vlc
        media_content_type: music
        media_content_id: >
          {% if states.input_select.alarm_music.state=='卡农' %}
            /home/pi/Music/Canon.mp3
          {% elif states.input_select.alarm_music.state=='沧海一声笑' %}
            /home/pi/Music/沧海一声笑.mp3
          {% else %}
            /home/pi/Music/ICanFeelitComing.mp3
          {% endif %}
    # 延时n分钟
    - delay:
        minutes: "{{ states('input_number.alarm_light_duration')|int }}"
    # 关灯
    - service: light.turn_off
      entity_id: light.gateway_light_7c49eb18e3a7

# 将闹钟相关的控制项纳入一个组
group:
  alarm_clock:
    name: 闹钟
    entities:
      input_boolean.alarm_clock, input_datetime.alarm_time, input_text.alarm_text, input_select.alarm_music, input_number.alarm_light_duration

# 定义一个页面组，包含闹钟以及闹钟过程中相关的实体
  alarm_clock_view:
    name: 闹钟
    entities: light.gateway_light_7c49eb18e3a7, media_player.vlc, group.alarm_clock
    view: yes