###############################################################################
#   @author         :   Mahasri Kalavala
#   @date           :   04/15/2017
#   @package        :   Home Security
#   @description    :   Home Security System Sensors and Automations
###############################################################################
homeassistant:
  customize:
    group.home_security_system:
      order: 7

    alarm_control_panel.home:
      friendly_name: Home Security System
      icon: mdi:security
    sensor.my_alarm_control_panel:
      friendly_name: Home Security System
      icon: mdi:security

###############################################################################
#                _                        _   _
#     /\        | |                      | | (_)
#    /  \  _   _| |_ ___  _ __ ___   __ _| |_ _  ___  _ __  ___
#   / /\ \| | | | __/ _ \| '_ ` _ \ / _` | __| |/ _ \| '_ \/ __|
#  / ____ \ |_| | || (_) | | | | | | (_| | |_| | (_) | | | \__ \
# /_/    \_\__,_|\__\___/|_| |_| |_|\__,_|\__|_|\___/|_| |_|___/
#
###############################################################################

automation:
  ###############################################################################
  # Leeo light - color indication of Home Security System
  # BLUE for Secured (Home and Away), and RED for OFF or Trigerred
  ###############################################################################
  - alias: Home Security Status Xiaomi Color
    initial_state: true
    trigger:
      platform: state
      entity_id: alarm_control_panel.home
    condition:
      - condition: template
        value_template: "{% if trigger.from_state %} True {% else %} False {% endif %}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') != 'unknown' }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') | trim != '' }}"
    action:
      - service_template: >
          {% if states('alarm_control_panel.home') == "armed_home" %}
            script.xiaomi_blue
          {% elif states('alarm_control_panel.home') == "armed_away" %}
            script.xiaomi_green
          {% elif states('alarm_control_panel.home') == "triggered" %}
            script.xiaomi_red
          {% elif states('alarm_control_panel.home') == "disarmed" %}
            script.xiaomi_red
          {% endif %}

#
# This automation will trigger when the Home Security System is "Triggered"
# This will send all relevant information - Door Statuses and Camera snapshots around the home
# Meanwhile Home Security Company will be calling and/or dispatching Police over to the house.
# This should give you enough information to have a good conversation with the Home Security System company when not at home

  - alias: Home Security Triggered
    initial_state: true
    trigger:
      platform: state
      entity_id: alarm_control_panel.home
      to: "triggered"
    action:
      - service: script.notify_me
        data_template:
          message: >
            {% set ns = namespace(openDoorCount=0, doorNames="") %}
            {%- set sensors = [
              'binary_sensor.door_window_sensor_158d000424a6d6', 'binary_sensor.door_window_sensor_158d00040ad8fc', 'binary_sensor.door_window_sensor_158d0004880f30',
              'binary_sensor.door_window_sensor_158d000424718f', 'binary_sensor.door_window_sensor_158d0004231f7b', 'binary_sensor.door_window_sensor_158d0004248d5b',
              'binary_sensor.motion_sensor_158d00016c2d0e', 'binary_sensor.motion_sensor_158d00016db6d2', 'binary_sensor.motion_sensor_158d0001a25041',
              'binary_sensor.motion_sensor_158d0001a662fe','binary_sensor.motion_sensor_158d00024e57d3','binary_sensor.motion_sensor_158d00024e57fb',
              'binary_sensor.motion_sensor_158d00024e842c','binary_sensor.motion_sensor_158d00024ee084','binary_sensor.motion_sensor_158d000272bed1',
              'binary_sensor.motion_sensor_158d000272bf48','binary_sensor.motion_sensor_158d000272bfd7','binary_sensor.motion_sensor_158d000464c25a',
              'binary_sensor.motion_sensor_158d00047b6f69'
             ] -%}
            
            {%- for item in sensors  if states(item) == "on" %}
              {% set ns.doorNames = ns.doorNames + state_attr(item, "friendly_name") + (", " if not loop.last else " ")  %}
              {% set ns.openDoorCount = ns.openDoorCount + 1 %}
            {%- endfor %}
            
            Your Home Security System is triggered. {{ "But ALL Doors are CLOSED! Must be a spider on one of the sensor(s) triggered it!"  if ns.openDoorCount == 0 else 'Following sensors are ON currently:' }}
            {{ ns.doorNames }}
            
      - service: camera.snapshot
        data_template:
          entity_id: "camera.frontdoor_camera"
          filename:
            "{{ '/config/www/downloads/camera/frontdoor/frontdoor_' ~
            (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.driveway_camera"
          filename:
            "{{ '/config/www/downloads/camera/driveway/driveway_' ~
            (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.garage"
          filename:
            "{{ '/config/www/downloads/camera/garage/garage_' ~
            (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.patio_camera"
          filename:
            "{{ '/config/www/downloads/camera/patio/patio_' ~
            (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.playarea_camera"
          filename:
            "{{ '/config/www/downloads/camera/playarea/playarea_' ~
            (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"

      - service: notify.telegram
        data_template:
          title: "Camera Snapshots"
          message: "Please check the camera images just to be sure!"
          data:
            photo:
              - file: "{{ '/config/www/downloads/camera/frontdoor/frontdoor_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
                caption: "Front Door"
              - file: "{{ '/config/www/downloads/camera/driveway/driveway_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
                caption: "Driveway"
              - file: "{{ '/config/www/downloads/camera/garage/garage_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
                caption: "Garage"
              - file: "{{ '/config/www/downloads/camera/patio/patio_' ~
                (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
                caption: "Patio"
              - file: "{{ '/config/www/downloads/camera/playarea/playarea_' ~
                (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
                caption: "Playarea"

  ###############################################################################
  # Notify Security System State Change
  ###############################################################################
  - alias: Notify Home Security Status Change
    initial_state: true
    trigger:
      platform: state
      entity_id: alarm_control_panel.home
    condition:
      - condition: template
        value_template: "{{ states('input_boolean.security_system_alerts') == 'on' }}"
      # - condition: template
      #   value_template: >
      #     {%- if state_attr('automation.notify_home_security_status_change', 'last_triggered') -%}
      #       {{ (as_timestamp(now()) - as_timestamp(state_attr('automation.notify_home_security_status_change', 'last_triggered'))) > 90 }}
      #     {%- else -%}
      #       true
      #     {%- endif -%}
    action:
      - service: script.notify_me
        data_template:
          message: >
            {% if states('alarm_control_panel.home') == "armed_home" %}
              Your home is now secured!
            {% elif states('alarm_control_panel.home') == "armed_away" %}
              Your Home Security System is now set to Away mode!
            {% elif states('alarm_control_panel.home') == "triggered" %}
              Attention!: Your Home Security System is triggered! It has been notified to the authorities.
            {% elif states('alarm_control_panel.home') == "disarmed" %}
              Attention!: Your Home Security System is turned OFF.
            {% endif %}
      - service: script.voice_notify
        data_template:
          message: >
            {% if states('alarm_control_panel.home') == "armed_home" %}
              Your home is now secured!
            {% elif states('alarm_control_panel.home') == "armed_away" %}
              Your Home Security System is now set to Away mode!
            {% elif states('alarm_control_panel.home') == "triggered" %}
              Attention!: Your Home Security System is triggered! It has been notified to the authorities.
            {% elif states('alarm_control_panel.home') == "disarmed" %}
              Attention!: Your Home Security System is turned OFF.
            {% endif %}
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') != 'disarmed' }}"
      - service: input_boolean.turn_on
        entity_id: input_boolean.notify_camera_alerts

  ###############################################################################
  # A gentle 10 minute reminder that the Home Security system is OFF
  ###############################################################################
  - alias: Home Security System WatchDog 10 minutes
    trigger:
      - platform: state
        entity_id:
          - alarm_control_panel.home
        to: "disarmed"
        for:
          minutes: 10
    action:
      - service: script.notify_me
        data:
          message: "Home Security System is OFF for more than 10 minutes!"

  ###############################################################################
  # A gentle reminder that the home security is OFF for more than 30 minutes
  ###############################################################################
  - alias: Home Security System WatchDog 30 minutes
    trigger:
      - platform: state
        entity_id:
          - alarm_control_panel.home
        to: "disarmed"
        for:
          minutes: 30
    condition:
      - condition: template
        value_template: "{{ states('input_boolean.security_system_alerts') == 'on' }}"
    action:
      - service: script.notify_me
        data:
          message: "Home Security System is OFF for more than 30 minutes!"

  ###############################################################################
  # When home security system is turned OFF or turned to Home mode from "away"
  # means, someone reached home from outside
  ###############################################################################
  # - alias: Turn ON Thermostat upon reaching home
  #   initial_state: true
  #   trigger:
  #     platform: state
  #     entity_id: alarm_control_panel.home
  #   condition:
  #     - condition: template
  #       value_template: >
  #         {% if trigger.from_state.state == 'armed_away' and
  #               (trigger.to_state.state == 'armed_home' or trigger.to_state.state == 'disarmed') %}
  #           true
  #         {% else %}
  #           false
  #         {% endif %}
  #   action:
  #     - service: climate.set_preset_mode
  #       target:
  #         entity_id: climate.dining_room
  #       data:
  #         preset_mode: "eco"

  ###############################################################################
  # TURN HOME SECURITY SYSTEM ON AT BED TIME
  ###############################################################################
  - alias: Night HomeSecurity On
    initial_state: true
    trigger:
      platform: time_pattern
      minutes: "/5"
      seconds: 00
    condition:
      - condition: template
        value_template: "{{ states('sensor.bedtime_hour')|int == now().hour|int }}"
      - condition: template
        value_template: "{{ states('sensor.bedtime_minute')|int == now().minute|int }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') != 'away' }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'disarmed' }}"
      - condition: template
        value_template: "{{ states('input_boolean.security_system_alerts') == 'on' }}"
    action:
      - service: alarm_control_panel.alarm_arm_home
        data:
          entity_id: alarm_control_panel.home
      - service: script.notify_me
        data:
          message: "It's bedtime, you forgot to turn ON Home Security System. Turned it ON for you."

###############################################################################
# Check for Garage Door Status when Home Security System State changes
###############################################################################
  - alias: Home Security System And Garage Door Check
    initial_state: true
    trigger:
      - platform: time_pattern
        minutes: '/15'
        seconds: 00
    condition:
      condition: and
      conditions:
        - condition: template
          value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
        - condition: or
          conditions:
            - condition: template
              value_template: "{{ states('binary_sensor.door_window_sensor_158d0004231f7b') == 'on' }}"
            - condition: template
              value_template: "{{ states('binary_sensor.door_window_sensor_158d0004248d5b') == 'on' }}"
    action:
      - service: switch.turn_on
        entity_id: switch.garage
  
      - service: script.notify_me
        data_template:
          message: >
            Attention! Your home Security system is set to {{ states('alarm_control_panel.home').split('_')[1] | upper }} mode. BUT THE {% if states('binary_sensor.door_window_sensor_158d0004231f7b') == "on" -%}DOUBLE CAR {%- else  %}SINGLE CAR {% endif %}GARAGE DOOR IS STILL OPEN!
  
      - service: camera.snapshot
        data_template:
          entity_id: "camera.garage"
          filename: "{{ '/config/www/downloads/camera/garage/garage_' ~  (state_attr('automation.home_security_system_and_garage_door_check','last_updated') ~ '').replace('-','_').replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
  
      - service: notify.telegram
        data_template:
          title: "Garage"
          message: "Home Security System is ON, but Garage Doors are OPEN!"
          data:
            photo:
              - file: "{{ '/config/www/downloads/camera/garage/garage_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
                caption: "Garage"
  
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' }}"
  
      - service: script.voice_notify
        data_template:
          message: >
            {%- set doors = "" %}
            {%- if states('binary_sensor.door_window_sensor_158d0004231f7b') == "on"  and states('binary_sensor.door_window_sensor_158d0004248d5b') == "on" %}
              {%- set doors = "Both garage doors" %}
              {%- elif states('binary_sensor.door_window_sensor_158d0004248d5b') == "on"%}
                {%- set doors = state_attr('binary_sensor.door_window_sensor_158d0004248d5b', 'friendly_name') %}
              {%- elif states('binary_sensor.door_window_sensor_158d0004248d5b') == "on" %}
                {%- set doors = state_attr('binary_sensor.door_window_sensor_158d0004231f7b', 'friendly_name') %}
              {%- endif %}
            Attention! Your home Security system is set to {{ states('alarm_control_panel.home').split('_')[1] | upper }} mode.
            BUT the {{ doors }} {{ 'are' if doors.endswith('s') else 'is' }} open.

###############################################################################
# Turn Home Security System ON at sunset time
###############################################################################
# - alias: Turn On Home Security System At Sunset
#   initial_state: true
#   trigger:
#     platform: sun
#     event: sunset
#     offset: '+00:00:00'
#   condition:
#     - condition: state
#       entity_id: alarm_control_panel.home
#       state: 'disarmed'
#   action:
#     - service_template: >-
#         {% if states('binary_sensor.back_door_sensor_sensor') == "off" and
#               states('binary_sensor.aeotec_zw120_door_window_sensor_gen5_sensor')  == "off" and
#               states('binary_sensor.door_window_sensor_158d0004231f7b') == "off" and
#               states('binary_sensor.door_window_sensor_158d0004248d5b') == "off" %}
#           alarm_control_panel.alarm_arm_home
#         {% else %}
#           alarm_control_panel.disarm
#         {% endif %}
#       data:
#         entity_id: alarm_control_panel.home
#     - service: script.voice_notify
#       data_template:
#         message: >
#           {% if states('binary_sensor.back_door_sensor_sensor') == "off" and
#                 states('binary_sensor.aeotec_zw120_door_window_sensor_gen5_sensor')  == "off" and
#                 states('binary_sensor.door_window_sensor_158d0004231f7b') == "off" and
#                 states('binary_sensor.door_window_sensor_158d0004248d5b') == "off" %}
#             It's getting dark outside, and your home security system is now set to HOME mode.
#           {% else %}
#              It is getting dark outside.
#              {%- if states('binary_sensor.back_door_sensor_sensor') == "on" -%}
#                {%- set doors = doors ~ " Back Door" -%}
#              {%- endif -%}
#              {%- if states('binary_sensor.aeotec_zw120_door_window_sensor_gen5_sensor')  == "on" -%}
#                {% if doors | trim != "" %}
#                  {%- set doors = doors ~ " and Front Door" -%}
#                {% else %}
#                  {%- set doors = doors ~ " Front Door" -%}
#                {% endif %}
#              {%- endif -%}
#              {%- if states('binary_sensor.door_window_sensor_158d0004231f7b') == "on" -%}
#                {% if doors | trim != "" %}
#                  {%- set doors = doors ~ " and Two Car Garage Door" -%}
#                {% else %}
#                  {%- set doors = doors ~ " Two Car Garage Door" -%}
#                {% endif %}
#              {%- endif -%}
#              {%- if states('binary_sensor.door_window_sensor_158d0004248d5b') == "on"  -%}
#                {% if doors | trim != "" %}
#                  {%- set doors = doors ~ " and Single Car Garage Door" -%}
#                {% else %}
#                  {%- set doors = doors ~ " Single Car Garage Door" -%}
#                {% endif %}
#              {%- endif -%}
#              Your{{ doors }} {%- if 'and' in doors -%}s are {%- else %} is {%- endif %} open. Home Security System could not be turned on.
#           {% endif %}
#     - service: script.notify_me
#       data_template:
#         message: >
#           {% if states('binary_sensor.back_door_sensor_sensor') == "off" and
#                 states('binary_sensor.aeotec_zw120_door_window_sensor_gen5_sensor')  == "off" and
#                 states('binary_sensor.door_window_sensor_158d0004231f7b') == "off" and
#                 states('binary_sensor.door_window_sensor_158d0004248d5b') == "off" %}
#             It's getting dark outside, and your home security system is now set to HOME mode.
#           {% else %}
#              It is getting dark outside.
#              {%- if states('binary_sensor.back_door_sensor_sensor') == "on" -%}
#                {%- set doors = doors ~ " Back Door" -%}
#              {%- endif -%}
#              {%- if states('binary_sensor.aeotec_zw120_door_window_sensor_gen5_sensor')  == "on" -%}
#                {% if doors | trim != "" %}
#                  {%- set doors = doors ~ " and Front Door" -%}
#                {% else %}
#                  {%- set doors = doors ~ " Front Door" -%}
#                {% endif %}
#              {%- endif -%}
#              {%- if states('binary_sensor.door_window_sensor_158d0004231f7b') == "on" -%}
#                {% if doors | trim != "" %}
#                  {%- set doors = doors ~ " and Two Car Garage Door" -%}
#                {% else %}
#                  {%- set doors = doors ~ " Two Car Garage Door" -%}
#                {% endif %}
#              {%- endif -%}
#              {%- if states('binary_sensor.door_window_sensor_158d0004248d5b') == "on"  -%}
#                {% if doors | trim != "" %}
#                  {%- set doors = doors ~ " and Single Car Garage Door" -%}
#                {% else %}
#                  {%- set doors = doors ~ " Single Car Garage Door" -%}
#                {% endif %}
#              {%- endif -%}
#              Your {{ doors}} {%- if 'and' in doors -%}s are {%- else %} is {%- endif %} open. Home Security System could not be turned on.
#           {% endif %}
