# Security Package

# -----------------------------------------------------------------------------
# Security Device Customization
homeassistant:
  customize_glob:
    "binary_sensor.*_door":
      device_class: door
    "binary_sensor.*_window":
      device_class: window
    binary_sensor.all_doors:
      device_class: door
    binary_sensor.all_windows:
      device_class: window
    binary_sensor.garage_door_open:
      device_class: door

# -----------------------------------------------------------------------------
# Manual Alarm Control Panel
alarm_control_panel:
  - platform: manual
    code: !secret alarm_code
    code_arm_required: false
    arming_time: 30
    delay_time: 20
    trigger_time: 600
    disarm_after_trigger: false
    disarmed:
      trigger_time: 0
    armed_home:
      arming_time: 0
      delay_time: 0

# -----------------------------------------------------------------------------
# Alarm Trigger Source
input_text:
  ha_alarm_trigger:

# -----------------------------------------------------------------------------
# Alarm Settings
input_boolean:
  auto_arm_alarm:
    name: Automatically Arm Alarm on Presence Change
  auto_disarm_alarm:
    name: Automatically Disarm Alarm on Presence Change
  disable_camera_events:
    name: Disable Camera Events

binary_sensor:

# -----------------------------------------------------------------------------
# Doorbell Camera Online State
  - platform: rest
    name: Doorbell Camera Online
    resource: !secret doorbell_camera_rest_url
    authentication: digest
    username: admin
    password: !secret doorbell_camera_password
    params:
      action: getConfig
      name: VSP_PaaS.Online
    value_template: "{{ value.split('=')[1] }}"
    device_class: connectivity

# -----------------------------------------------------------------------------
# Door and Window Groups
  - platform: group
    name: All Doors
    entities:
      - binary_sensor.front_door
      - binary_sensor.laundry_door
      - binary_sensor.living_room_door

  - platform: group
    name: Living Room Window
    entities:
      - binary_sensor.living_room_window_left
      - binary_sensor.living_room_window_right

  - platform: group
    name: All Windows
    entities:
      - binary_sensor.dining_room_front_window
      - binary_sensor.dining_room_side_window
      - binary_sensor.kitchen_left_window
      - binary_sensor.kitchen_right_window
      - binary_sensor.laundry_window
      - binary_sensor.office_window
      - binary_sensor.living_room_window
      - binary_sensor.guest_room_front_window
      - binary_sensor.guest_room_side_window
      - binary_sensor.bathroom_window
      - binary_sensor.bedroom_side_window
      - binary_sensor.bedroom_back_window

  - platform: group
    name: All Motion Sensors
    entities:
      - binary_sensor.entry_sensor_motion
      - binary_sensor.guest_room_sensor_motion
      - binary_sensor.hallway_sensor_motion
      - binary_sensor.office_sensor_motion

template:
  sensor:
    - name: Open Windows/Doors
      unique_id: open_windows_doors
      state: >
        {{ 
          expand(state_attr('binary_sensor.all_doors', 'entity_id') + state_attr('binary_sensor.all_windows', 'entity_id')) 
          | selectattr('state', 'in', ['on']) 
          | map(attribute='attributes.friendly_name') 
          | list | join(', ')
        }}

    - name: Motion Detected
      state: >
        {{
          expand(state_attr('binary_sensor.all_motion_sensors', 'entity_id'))
          | selectattr('state', 'in', ['on'])
          | map(attribute='attributes.friendly_name')
          | list | join(', ')
        }}

  binary_sensor:
    - name: Garage Door Open
      state: "{{ states('binary_sensor.garage_door') }}"
      icon: >-
        {% if is_state('binary_sensor.garage_door', 'on') %}
          mdi:garage-open
        {% else %}
          mdi:garage
        {% endif %}

# -----------------------------------------------------------------------------
# Garage Door Button
input_button:
  garage_door:
    name: Garage Door
    icon: mdi:garage

# -----------------------------------------------------------------------------
# Force Doorbell Online State
shell_command:
  doorbell_camera_set_online: !secret doorbell_camera_online_command

# -----------------------------------------------------------------------------
# Security Scripts
script:
  pause_camera_events:
    alias: Pause Exterior Camera Event Detection
    sequence:
      - service: mqtt.publish
        data:
          topic: frigate/backyard/detect/set
          payload: 'OFF'
      - service: mqtt.publish
        data:
          topic: frigate/doorbell/detect/set
          payload: 'OFF'

  resume_camera_events:
    alias: Resume Exterior Camera Event Detection
    sequence:
      - service: mqtt.publish
        data:
          topic: frigate/backyard/detect/set
          payload: 'ON'
      - service: mqtt.publish
        data:
          topic: frigate/doorbell/detect/set
          payload: 'ON'

  auto_resume_camera_events:
    alias: Auto Resume Camera Events
    fields:
      minutes:
        name: Minutes
        description: "The amount of time to wait before resuming detection"
        default: 60
        selector:
          number:
            min: 0
            max: 240
            step: 10
            unit_of_measurement: minutes
            mode: slider
    mode: restart
    sequence:
      - delay:
          minutes: "{{ minutes }}"
      - service: input_boolean.turn_off
        target:
          entity_id: input_boolean.disable_camera_events
      - service: script.resume_camera_events

# -----------------------------------------------------------------------------
# Security Automations
automation:
  - alias: Run Garage Door
    trigger:
      - platform: state
        entity_id: input_button.garage_door
    action:
      - service: switch.turn_on
        target:
          entity_id: switch.garage_door_relay_1

  - alias: Auto-Arm Alarm
    trigger:
      - platform: state
        entity_id: sensor.house_presence_status
        to: Away
    condition: "{{ is_state('input_boolean.auto_arm_alarm', 'on') }}"
    action:
      - service: alarm_control_panel.alarm_arm_away
        target:
          entity_id: alarm_control_panel.ha_alarm
        data:
          code: !secret alarm_code

  - alias: Auto-Disarm Alarm
    trigger:
      - platform: state
        entity_id: sensor.house_presence_status
        to: Just Arrived
    condition: "{{ is_state('input_boolean.auto_disarm_alarm', 'on') }}"
    action:
      - service: alarm_control_panel.alarm_disarm
        target:
          entity_id: alarm_control_panel.ha_alarm
        data:
          code: !secret alarm_code

  - alias: Notify on Alarm Arm/Disarm
    trigger:
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: disarmed
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: armed_home
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: armed_away
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: armed_night
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: armed_vacation
    action:
      - service: notify.security
        data:
          message: >
            {% 
              set person = states.person
                |selectattr('attributes.user_id', 'eq', trigger.to_state.context.user_id)
                |first|default({'attributes':{'friendly_name':'Automation'}})
            %}Alarm changed to {{
              trigger.to_state.state|replace('_', ' ')|title
            }} by {{
              person.attributes.friendly_name
            }}

  - alias: Reset Alarm Trigger on Disarm
    trigger:
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: 'disarmed'
    action:
      - service: input_text.set_value
        target:
          entity_id: input_text.ha_alarm_trigger
        data:
          value: ""

  - alias: Notify on Alarm Triggered
    trigger:
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        to: 'triggered'
    action:
      - service: notify.security
        data:
          message: Alarm triggered by {{ states('input_text.ha_alarm_trigger') }}

  - alias: Trigger Alarm on Window or Door Open
    trigger:
      - platform: state
        entity_id: binary_sensor.all_doors
        to: 'on'
      - platform: state
        entity_id: binary_sensor.all_windows
        to: 'on'
    condition:
      condition: state
      entity_id: alarm_control_panel.ha_alarm
      state:
        - 'armed_away'
        - 'armed_home'
        - 'armed_vacation'
    action:
      - service: input_text.set_value
        target:
          entity_id: input_text.ha_alarm_trigger
        data:
          value: "{{ states('sensor.open_windows_doors') }}"

      - service: alarm_control_panel.alarm_trigger
        target:
          entity_id: alarm_control_panel.ha_alarm

  - alias: Trigger Alarm on Motion
    trigger:
      - platform: state
        entity_id: binary_sensor.all_motion_sensors
        to: 'on'
    condition:
      condition: state
      entity_id: alarm_control_panel.ha_alarm
      state:
        - 'armed_away'
        - 'armed_vacation'
    action:
      - service: input_text.set_value
        target:
          entity_id: input_text.ha_alarm_trigger
        data:
          value: "{{ states('sensor.motion_detected') }}"

      - service: alarm_control_panel.alarm_trigger
        target:
          entity_id: alarm_control_panel.ha_alarm

  - alias: Trigger Alarm on Garage Door Open
    trigger:
      - platform: state
        entity_id: binary_sensor.garage_door
        to: 'on'
    condition:
      condition: state
      entity_id: alarm_control_panel.ha_alarm
      state:
        - 'armed_away'
        - 'armed_vacation'
    action:
      - service: input_text.set_value
        target:
          entity_id: input_text.ha_alarm_trigger
        data:
          value: Garage Door

      - service: alarm_control_panel.alarm_trigger
        target:
          entity_id: alarm_control_panel.ha_alarm

  - alias: Pause Camera Event Detection
    trigger:
      - platform: state
        entity_id: input_boolean.disable_camera_events
        to: 'on'
    action:
      - service: script.pause_camera_events
      - service: script.turn_on
        target:
          entity_id: script.auto_resume_camera_events
        data:
          variables:
            minutes: 60

  - alias: Resume Camera Event Detection
    trigger:
      - platform: state
        entity_id: input_boolean.disable_camera_events
        to: 'off'
    action:
      - service: script.turn_off
        target:
          entity_id: script.auto_resume_camera_events
      - service: script.resume_camera_events

  - alias: Pause Doorbell Event Detection on Arrival or Departure
    trigger:
      - platform: state
        entity_id: person.jpk
        to: 'home'
      - platform: state
        entity_id: person.jen
        to: 'home'
      - platform: state
        entity_id: binary_sensor.front_door
        to: 'on'
    condition:
      condition: state
      entity_id: input_boolean.disable_camera_events
      state: 'off'
    mode: restart
    action:
      - service: mqtt.publish
        data:
          topic: frigate/doorbell/detect/set
          payload: 'OFF'
      - delay: 300
      - service: mqtt.publish
        data:
          topic: frigate/doorbell/detect/set
          payload: 'ON'

  - alias: Pause Backyard Event Detection when Garage Door Open
    trigger:
      - platform: state
        entity_id: binary_sensor.garage_door
        to: 'on'
    condition:
      condition: state
      entity_id: alarm_control_panel.ha_alarm
      state: disarmed
    mode: restart
    action:
      - service: mqtt.publish
        data:
          topic: frigate/backyard/detect/set
          payload: 'OFF'

  - alias: Start Backyard Event Detection when Garage Door Closes
    trigger:
      - platform: state
        entity_id: binary_sensor.garage_door
        to: 'off'
      - platform: state
        entity_id: alarm_control_panel.ha_alarm
        not_to: disarmed
    condition:
      condition: state
      entity_id: input_boolean.disable_camera_events
      state: 'off'
    mode: restart
    action:
      - delay: 60
      - service: mqtt.publish
        data:
          topic: frigate/backyard/detect/set
          payload: 'ON'

  - alias: Reset Doorbell Camera Online Mode
    trigger:
      - platform: state
        entity_id: binary_sensor.doorbell_camera_online
        to: 'off'
      - platform: homeassistant
        event: start
    action:
      - service: shell_command.doorbell_camera_set_online

  - alias: Frigate Event Notification
    trigger:
      - platform: mqtt
        topic: frigate/events
        payload: new
        value_template: "{{ value_json.type }}"
    condition:
      - condition: template
        value_template: "{{ trigger.payload_json.after.has_clip }}"
    action:
      - service: notify.security
        data:
          message: "A {{ trigger.payload_json.after.label }} detected on {{ trigger.payload_json.after.camera|title }} camera"
          data:
            image: "/api/frigate/notifications/{{ trigger.payload_json.after.id }}/thumbnail.jpg"
            clickAction: "https://hass.kraussnet.com/api/frigate/notifications/{{ trigger.payload_json.after.id }}/clip.mp4"
            ttl: 0
            priority: high
            tag: "{{ trigger.payload_json.after.id }}"
            when: "{{ trigger.payload_json.after.start_time|int }}"
            actions:
              - action: URI
                title: View Clip
                uri: "https://hass.kraussnet.com/api/frigate/notifications/{{ trigger.payload_json.after.id }}/clip.mp4"
              - action: URI
                title: View Snapshot
                uri: "https://hass.kraussnet.com/api/frigate/notifications/{{ trigger.payload_json.after.id }}/snapshot.jpg"

      - if:
          - condition: template
            value_template: >-
              {{ trigger.payload_json.after.label|lower == 'person' }}
          
        then:
          - service: persistent_notification.create
            data:
              notification_id: "camera-{{ trigger.payload_json.after.id }}"
              title: "A {{ trigger.payload_json.after.label }} detected on {{ trigger.payload_json.after.camera|title }} camera"
              message: >-
                ![image](/api/frigate/notifications/{{ trigger.payload_json.after.id }}/snapshot.jpg)
                [View Clip](/api/frigate/notifications/{{ trigger.payload_json.after.id }}/clip.mp4)
