###############################################################################
#   @author         :   Mahasri Kalavala
#   @date           :   07/16/2017
#   @package        :   Cameras
#   @description    :   Cameras and the automations
#   @Comment        :   USE AT YOUR RISK!!! I CAN'T GUARANTEE IF IT DOESN'T
#                       WORK IN YOUR ENVIRONMENT!
###############################################################################
homeassistant:

#
# The camera url format in secrets.yaml would look like this:
# frontdoor_camera_url: http://username:password@192.168.xxx.xxx/ISAPI/Streaming/channels/101/picture
#
camera:
  - platform: generic
    name: Frontdoor Camera
    still_image_url: !secret frontdoor_camera_url
    verify_ssl: false
    authentication: digest
    username: !secret camera_username
    password: !secret camera_password

  - platform: generic
    name: Driveway Camera
    still_image_url: !secret driveway_camera_url
    verify_ssl: false
    authentication: digest
    username: !secret camera_username
    password: !secret camera_password

  - platform: generic
    name: Patio Camera
    still_image_url: !secret patio_camera_url
    verify_ssl: false
    authentication: digest
    username: !secret camera_username
    password: !secret camera_password

  - platform: generic
    name: Playarea Camera
    still_image_url: !secret playarea_camera_url
    verify_ssl: false
    authentication: digest
    username: !secret camera_username
    password: !secret camera_password

  - platform: mjpeg
    mjpeg_url: !secret garage_camera_url
    name: Garage Camera

  - platform: mjpeg
    mjpeg_url: !secret kitchen_camera_url
    name: Kitchen Camera

  # - platform: mjpeg
  #   mjpeg_url: !secret frontroom_camera_url
  #   name: Frontroom Camera

  - platform: local_file
    name: Frontdoor Latest Scan
    file_path: "/home/homeassistant/.homeassistant/www/downloads/camera/frontdoor/frontdoor_latest.jpg"
  - platform: local_file
    name: Driveway Latest Scan
    file_path: "/home/homeassistant/.homeassistant/www/downloads/camera/driveway/driveway_latest.jpg"
  - platform: local_file
    name: Patio Latest Scan
    file_path: "/home/homeassistant/.homeassistant/www/downloads/camera/patio/patio_latest.jpg"
  - platform: local_file
    name: Playarea Latest Scan
    file_path: "/home/homeassistant/.homeassistant/www/downloads/camera/playarea/playarea_latest.jpg"
  - platform: local_file
    name: Garage Latest Scan
    file_path: "/home/homeassistant/.homeassistant/www/downloads/camera/garage/garage_latest.jpg"

binary_sensor:
  - platform: hikvision
    name: Frontdoor Camera
    ssl: false
    host: !secret frontdoor_camera_ip
    username: !secret camera_username
    password: !secret camera_password

  - platform: hikvision
    name: Driveway Camera
    ssl: false
    host: !secret driveway_camera_ip
    username: !secret camera_username
    password: !secret camera_password

  - platform: hikvision
    name: Patio Camera
    ssl: false
    host: !secret patio_camera_ip
    username: !secret camera_username
    password: !secret camera_password

  - platform: hikvision
    name: Playarea Camera
    ssl: false
    host: !secret playarea_camera_ip
    username: !secret camera_username
    password: !secret camera_password

image_processing:
  - platform: tensorflow
    scan_interval: 10000
    # confidence: 75
    source:
      - entity_id: camera.frontdoor_camera
      - entity_id: camera.driveway_camera
      - entity_id: camera.patio_camera
      - entity_id: camera.playarea_camera
      - entity_id: camera.garage_camera
    file_out:
      - "/home/homeassistant/.homeassistant/www/downloads/camera/{{- camera_entity.split('.')[1].split('_')[0] -}}/{{ camera_entity.split('.')[1].split('_')[0] }}_latest.jpg"
      - "/home/homeassistant/.homeassistant/www/downloads/camera/{{- camera_entity.split('.')[1].split('_')[0] -}}/{{ camera_entity.split('.')[1].split('_')[0] }}_{{ now().strftime('%Y%m%d_%H%M%S') }}.jpg"
    model:
      graph: /home/homeassistant/.homeassistant/tensorflow/
      # graph: /home/homeassistant/.homeassistant/tensorflow/frozen_inference_graph.pb
    # categories:
    #   - person
    #   - car
    #   - truck

input_label:
  current_stream:
    name: Current Stream

# frontdoor_camera_text_overlay_url: http://192.168.xxx.xxx/Video/inputs/channels/1/overlays/text/1
rest_command:
  set_frontdoor_camera_text_left_bottom:
    url: !secret frontdoor_camera_text_overlay_url
    username: !secret camera_username
    password: !secret camera_password
    method: PUT
    content_type: "text/xml"
    payload: >-
      <?xml version="1.0" encoding="UTF-8"?>
      <TextOverlay version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
      <id>1</id><enabled>true</enabled>
      <posX>45</posX><posY>520</posY>
      <message>{{ message }} </message>
      </TextOverlay>

  set_driveway_camera_text_left_bottom:
    url: !secret driveway_camera_text_overlay_url
    username: !secret camera_username
    password: !secret camera_password
    method: PUT
    content_type: "text/xml"
    payload: >-
      <?xml version="1.0" encoding="UTF-8"?>
      <TextOverlay version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
      <id>1</id><enabled>true</enabled>
      <posX>45</posX><posY>520</posY>
      <message>{{ message }} </message>
      </TextOverlay>

  set_patio_camera_text_left_bottom:
    url: !secret patio_camera_text_overlay_url
    username: !secret camera_username
    password: !secret camera_password
    method: PUT
    content_type: "text/xml"
    payload: >-
      <?xml version="1.0" encoding="UTF-8"?>
      <TextOverlay version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
      <id>1</id><enabled>true</enabled>
      <posX>45</posX><posY>520</posY>
      <message>{{ message }} </message>
      </TextOverlay>

  set_playarea_camera_text_left_bottom:
    url: !secret playarea_camera_text_overlay_url
    username: !secret camera_username
    password: !secret camera_password
    method: PUT
    content_type: "text/xml"
    payload: >-
      <?xml version="1.0" encoding="UTF-8"?>
      <TextOverlay version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
      <id>1</id><enabled>true</enabled>
      <posX>45</posX><posY>520</posY>
      <message>{{ message }} </message>
      </TextOverlay>

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

automation:
  #
  # Scan front door and driveway cameras when motion detected
  # if the garage doors are open, scan garage cameras as well
  #
  - alias: Scan Frontdoor Camera On Motion
    initial_state: true
    trigger:
      - platform: state
        entity_id:
          - binary_sensor.motion_sensor_158d00024ee084
        to: "on"
    action:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - service: script.frontdoor_cam
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_frontdoor_camera
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_driveway_camera
      - condition: template
        value_template: >-
          {% if state_attr('image_processing.tensorflow_frontdoor_camera', 'summary') != None %}
            {% if state_attr('image_processing.tensorflow_frontdoor_camera', 'summary') |count > 0 %}
              true
            {% else %}
              false
            {% endif %}
          {% else %}
            false
          {% endif %}
      - service: script.voice_notify
        data_template:
          message: >-
            {%- set e_id = "image_processing.tensorflow_frontdoor_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the front yard."  }}
            {%- endif -%}
          greeting: "no"
      - service: notify.notify_smtp
        data_template:
          title: 'Front door motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: >
            {%- set e_id = "image_processing.tensorflow_frontdoor_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the front yard on " ~ now().strftime("%d %h %Y, at %I:%M:%S %p") ~ ". Please see the images below." }}
            {% else %}
              Motion detected in the front door on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") }}. Please see the images below.
            {%- endif -%}
          data:
            images:
              - "/home/homeassistant/.homeassistant/www/downloads/camera/frontdoor/frontdoor_latest.jpg"
      - condition: template
        value_template: >
          {% if states('binary_sensor.single_car_garage_door_tilt_sensor_sensor') == "on" or
                states('binary_sensor.two_car_garage_door_tilt_sensor_sensor') == "on" %}
            True
          {% else %}
            False
          {% endif %}
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_garage_camera
  #
  # Scan driveway and frontdoor cameras when motion detected
  # if the garage doors are open, scan garage cameras as well
  #
  - alias: Scan Driveway Camera When Motion
    initial_state: true
    trigger:
      - platform: state
        entity_id:
          - binary_sensor.motion_sensor_158d00024e57fb
        to: "on"
    action:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - service: script.stream2chromecast
        data_template:
          url: !secret driveway_camera_stream_url
          name: "driveway"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_driveway_camera
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_frontdoor_camera
      - condition: template
        value_template: >-
          {% if state_attr('image_processing.tensorflow_driveway_camera', 'summary') != None %}
            {% if state_attr('image_processing.tensorflow_driveway_camera', 'summary') |count > 0 %}
              true
            {% else %}
              false
            {% endif %}
          {% else %}
            false
          {% endif %}
      - service: script.voice_notify
        data_template:
          message: >-
            {%- set e_id = "image_processing.tensorflow_driveway_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the driveway"  }}
            {%- endif -%}
      - service: notify.notify_smtp
        data_template:
          title: 'Driveway motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: >
            {%- set e_id = "image_processing.tensorflow_driveway_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the driveway on " ~ now().strftime("%d %h %Y, at %I:%M:%S %p") ~ ". Please see the images below." }}
            {% else %}
              Motion detected at the driveway on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") }}. Please see the images below.
            {%- endif -%}
          data:
            images:
              - "/home/homeassistant/.homeassistant/www/downloads/camera/driveway/driveway_latest.jpg"
      - condition: template
        value_template: >
          {% if states('binary_sensor.single_car_garage_door_tilt_sensor_sensor') == "on" or
                states('binary_sensor.two_car_garage_door_tilt_sensor_sensor') == "on" %}
            True
          {% else %}
            False
          {% endif %}
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_garage_camera

  #
  # When motion detected in garage, scan garage camera
  # If any of the garage doors are open, scan front door, driveway as well!
  #
  - alias: Scan Garage Camera When Motion
    initial_state: true
    trigger:
      - platform: state
        entity_id:
          - binary_sensor.motion_sensor_158d000272bf48
        to: "on"
    condition:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
    action:
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_garage_camera
      - condition: template
        value_template: >
          {% if states('binary_sensor.single_car_garage_door_tilt_sensor_sensor') == "on" or
                states('binary_sensor.two_car_garage_door_tilt_sensor_sensor') == "on" %}
            True
          {% else %}
            False
          {% endif %}
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_driveway_camera
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_frontdoor_camera
      - condition: template
        value_template: >-
          {% if state_attr('image_processing.tensorflow_garage_camera', 'summary') != None %}
            {% if state_attr('image_processing.tensorflow_garage_camera', 'summary') |count > 0 %}
              true
            {% else %}
              false
            {% endif %}
          {% else %}
            false
          {% endif %}
      - service: script.voice_notify
        data_template:
          message: >-
            {%- set e_id = "image_processing.tensorflow_garage_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the garage."  }}
            {%- endif -%}
      - service: notify.notify_smtp
        data_template:
          title: 'Garage motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: >
            {%- set e_id = "image_processing.tensorflow_garage_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
              {{ " detected in the garage on " ~  now().strftime("%d %h %Y, at %I:%M:%S %p") ~ ". Please see the images below." }}
            {% else %}
              Motion detected in the garage on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") }}. Please see the images below.
            {%- endif -%}
          data:
            images:
              - "/home/homeassistant/.homeassistant/www/downloads/camera/garage/garage_latest.jpg"
  #
  # When motion detected in the backyard, scan both cameras
  #
  - alias: Scan Backyard Camera When Motion
    initial_state: true
    trigger:
      - platform: state
        entity_id:
          - binary_sensor.motion_sensor_158d00024e842c
        to: "on"
    action:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - service: script.stream2chromecast
        data_template:
          url: !secret playarea_camera_stream_url
          name: "backyard"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_patio_camera
      - service: image_processing.scan
        data_template:
          entity_id: image_processing.tensorflow_playarea_camera
      - condition: template
        value_template: >-
          {% if state_attr('image_processing.tensorflow_patio_camera', 'summary') != None %}
            {% if state_attr('image_processing.tensorflow_patio_camera', 'summary') |count > 0 %}
              true
            {% else %}
              false
            {% endif %}
          {% else %}
            false
          {% endif %}
      - service: script.voice_notify
        data_template:
          message: >-
            {%- set e_id = "image_processing.tensorflow_patio_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the backyard."  }}
            {%- endif -%}
      - service: notify.notify_smtp
        data_template:
          title: 'Backyard motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: >
            {%- set e_id = "image_processing.tensorflow_patio_camera" -%}
            {%- if state_attr(e_id, 'summary') -%}
              {%- set count = state_attr(e_id, 'summary') | count -%}
              {%- for x in state_attr(e_id, 'summary') | list -%}
                {%- if loop.first %}{% elif loop.last %}, and {% else %}, {% endif -%}
                {{- state_attr(e_id, 'summary')[x]}} {{ x ~ 's' if state_attr(e_id, 'summary')[x] > 1 else x }}
              {%- endfor -%}
            {{ " detected in the backyard on " ~  now().strftime("%d %h %Y, at %I:%M:%S %p") ~ ". Please see the images below." }}
            {% else %}
              Motion detected in the backyard on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") }}. Please see the images below.
            {%- endif -%}
          data:
            images:
              - "/home/homeassistant/.homeassistant/www/downloads/camera/patio/patio_latest.jpg"
              - "/home/homeassistant/.homeassistant/www/downloads/camera/playarea/playarea_latest.jpg"

  # Before you think this code is crazy, here is an explanation.
  #
  # I have a xiaomi  aqara  PIR   motion  sensor  near  the  front  door, and
  # when it triggers, I capture  photo  from  the  camera,  save  it  locally
  # using  last_triggered  date  and   time  as  filename... then  send  that
  # image to my email as an attacment.
  #
  # In the  action, I have  multiple   services I am calling,  and one service
  # creates  file,  and  I  needed  that   file  name  in  the  second service.
  # Since passing variables/info  between   the  services  within  an  action,
  # is not  possible,  I generate  the file  name  based  on  the automation's
  # last_triggered  date. Since that info is same   across  all  the  services
  # within the automation, I now can access/use the  same file name everywhere!
  #
  # I only  send  iOS notifications when I am home, as my HA is not exposed to
  # Internet, &  I  can't see my camera  unless I login to my vpn on my device.
  # That's why you  see  the condition  right above iOS  notification  service.
  #
  # Make  sure  you add  the path to white_list  in the configuration.yaml file.
  # If front  door is  open, wait  for a  couple  of seconds, before taking pic!
  #

  # I could have combined all the 3 automations into one, but if all the motion
  # sensors are triggered at the same time, the automation would only fire once,
  # and the code gets ugly big and unmanageable. 3 simple automations is better!

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

  - alias: Notify Frontdoor Camera Snapshots
    initial_state: true
    trigger:
      platform: state
      entity_id: binary_sensor.motion_sensor_158d00024ee084
      to: "on"
    condition:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
    action:
      - delay: "{{ '00:00:08' if states('binary_sensor.aeotec_zw120_door_window_sensor_gen5_sensor') == 'on' else '0:0:0' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.frontdoor_camera"
          filename:
            "{{ '/home/homeassistant/.homeassistant/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:
            "{{ '/home/homeassistant/.homeassistant/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_camera"
          filename:
            "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/garage/garage_' ~
            (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: notify.notify_smtp
        data_template:
          title: 'Front door motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: 'Motion detected at the front door on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") -}}. Please see the images below.'
          data:
            images:
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/frontdoor/frontdoor_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/driveway/driveway_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/garage/garage_' ~
                (states.binary_sensor.motion_sensor_158d00024ee084.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - condition: template
        value_template: "{{ states('device_tracker.life360_suresh') == 'home' }}"
      - service: notify.ios_devices
        data_template:
          message: "Check Front Door camera!"
          data:
            push:
              category: camera
            entity_id: "camera.frontdoor_camera"
            attachment:
              url: "{{ states.camera.frontdoor_camera.attributes.entity_picture }}"
              content-type: jpg

  # ###############################################################################
  # #  _____       _
  # # |  __ \     (_)
  # # | |  | |_ __ ___   _______      ____ _ _   _
  # # | |  | | '__| \ \ / / _ \ \ /\ / / _` | | | |
  # # | |__| | |  | |\ V /  __/\ V  V / (_| | |_| |
  # # |_____/|_|  |_| \_/ \___| \_/\_/ \__,_|\__, |
  # #                                         __/ |
  # #                                        |___/
  - alias: Notify Driveway Camera Snapshots
    initial_state: true
    trigger:
      platform: state
      entity_id: binary_sensor.motion_sensor_158d00024e57fb
      to: "on"
    condition:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
    action:
      - service: camera.snapshot
        data_template:
          entity_id: "camera.frontdoor_camera"
          filename:
            "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/frontdoor/frontdoor_' ~
            (states.binary_sensor.motion_sensor_158d00024e57fb.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.driveway_camera"
          filename:
            "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/driveway/driveway_' ~
            (states.binary_sensor.motion_sensor_158d00024e57fb.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: camera.snapshot
        data_template:
          entity_id: "camera.garage_camera"
          filename:
            "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/garage/garage_' ~
            (states.binary_sensor.motion_sensor_158d00024e57fb.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: notify.notify_smtp
        data_template:
          title: 'Driveway motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: 'Motion detected at the Driveway on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") }}. Please see the images below.'
          data:
            images:
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/driveway/driveway_' ~
                (states.binary_sensor.motion_sensor_158d00024e57fb.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/frontdoor/frontdoor_' ~
                (states.binary_sensor.motion_sensor_158d00024e57fb.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/garage/garage_' ~
                (states.binary_sensor.motion_sensor_158d00024e57fb.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - condition: template
        value_template: "{{ states('device_tracker.life360_suresh') == 'home' }}"
      - service: notify.ios_devices
        data_template:
          message: "Check Driveway camera!"
          data:
            push:
              category: camera
            entity_id: "camera.driveway_camera"
            attachment:
              url: "{{ states.camera.driveway_camera.attributes.entity_picture }}"
              content-type: jpg

  # ###############################################################################
  # #  ____             _                        _
  # # |  _ \           | |                      | |
  # # | |_) | __ _  ___| | ___   _  __ _ _ __ __| |
  # # |  _ < / _` |/ __| |/ / | | |/ _` | '__/ _` |
  # # | |_) | (_| | (__|   <| |_| | (_| | | | (_| |
  # # |____/ \__,_|\___|_|\_\\__, |\__,_|_|  \__,_|
  # #                         __/ |
  # #                        |___/
  - alias: Notify Backyard Camera Snapshots
    initial_state: true
    trigger:
      platform: state
      entity_id: binary_sensor.motion_sensor_158d00024e842c
      to: "on"
    condition:
      - condition: template
        value_template: "{{ states('input_boolean.notify_camera_alerts') == 'on' }}"
      - condition: template
        value_template: "{{ states('alarm_control_panel.home') == 'armed_home' or states('alarm_control_panel.home') == 'armed_away' }}"
    action:
      - condition: template
        value_template: >-
          {% if state_attr('image_processing.tensorflow_frontdoor_camera', 'summary') != None %}
            {% if state_attr('image_processing.tensorflow_frontdoor_camera', 'summary') |count > 0 %}
              true
            {% else %}
              false
            {% endif %}
          {% else %}
            false
          {% endif %}
      - service: camera.snapshot
        data_template:
          entity_id: "camera.patio_camera"
          filename:
            "{{ '/home/homeassistant/.homeassistant/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:
            "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/playarea/playarea_' ~
            (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
            .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - service: notify.notify_smtp
        data_template:
          title: 'Backyard motion {{ now().strftime("%d %h %Y, %I:%M:%S %p") }}'
          message: 'Motion detected in the Backyard on {{ now().strftime("%d %h %Y, at %I:%M:%S %p") }}. Please see the images below.'
          data:
            images:
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/patio/patio_' ~
                (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
              - "{{ '/home/homeassistant/.homeassistant/www/downloads/camera/playarea/playarea_' ~
                (states.binary_sensor.motion_sensor_158d00024e842c.last_updated ~ '').replace('-','_')
                .replace(' ', '_').replace(':','_').replace('.','_').replace('+','_') ~ '.jpg' }}"
      - condition: template
        value_template: "{{ states('device_tracker.life360_suresh') == 'home' }}"
      - service: notify.ios_devices
        data_template:
          message: "Check Patio camera!"
          data:
            push:
              category: camera
            entity_id: "camera.patio_camera"
            attachment:
              url: "{{ states.camera.patio_camera.attributes.entity_picture }}"
              content-type: jpg

  ###############################################################################
  #   _______        _      ____                 _
  #  |__   __|      | |    / __ \               | |
  #     | | _____  _| |_  | |  | |_   _____ _ __| | __ _ _   _
  #     | |/ _ \ \/ / __| | |  | \ \ / / _ \ '__| |/ _` | | | |
  #     | |  __/>  <| |_  | |__| |\ V /  __/ |  | | (_| | |_| |
  #     |_|\___/_/\_\\__|  \____/  \_/ \___|_|  |_|\__,_|\__, |
  #                                                       __/ |
  #                                                      |___/
  #
  # Show latest weather information on camera (refresh every 2 minutes), but only
  # do it if the last updated is more than 2 minutes; In case some other automation
  # sets a new text overlay, make sure it stays for at least 2 minutes before
  # replacing with the weather information
  #
  - alias: Show Outdoor Temperature on Camera
    trigger:
      - platform: time_pattern
        minutes: "/2"
    condition:
      - condition: template
        value_template: >
          {% if state_attr('script.frontdoor_camera_text_overlay', 'last_triggered') != None %}
            {{ (as_timestamp(now()) - as_timestamp(
                state_attr('script.frontdoor_camera_text_overlay', 'last_triggered'))) | int > 120 }}
          {% else %}
            true
          {% endif %}
    action:
      - service: script.frontdoor_camera_text_overlay
        data_template:
          text: >
            {{ '* ' if states('alarm_control_panel.home') == 'armed_home' or
                       states('alarm_control_panel.home') == 'armed_away' -}}
            {{- states('sensor.dark_sky_temperature')|int}} °F, Feels like
            {{- ' ' ~ states('sensor.dark_sky_apparent_temperature') |int -}}
      - service: script.driveway_camera_text_overlay
        data_template:
          text: >
            {{ '* ' if states('alarm_control_panel.home') == 'armed_home' or
                       states('alarm_control_panel.home') == 'armed_away' -}}
            {{- states('sensor.dark_sky_temperature')|int}} °F, Feels like
            {{- ' ' ~ states('sensor.dark_sky_apparent_temperature') |int -}}
      - service: script.playarea_camera_text_overlay
        data_template:
          text: >
            {{ '* ' if states('alarm_control_panel.home') == 'armed_home' or
                       states('alarm_control_panel.home') == 'armed_away' -}}
            {{- states('sensor.dark_sky_temperature')|int}} °F, Feels like
            {{- ' ' ~ states('sensor.dark_sky_apparent_temperature') |int -}}
      - service: script.patio_camera_text_overlay
        data_template:
          text: >
            {{ '* ' if states('alarm_control_panel.home') == 'armed_home' or
                       states('alarm_control_panel.home') == 'armed_away' -}}
            {{- states('sensor.dark_sky_temperature')|int}} °F, Feels like
            {{- ' ' ~ states('sensor.dark_sky_apparent_temperature') |int -}}

  ###############################################################################
  #    _____ _                                            _
  #   / ____| |                                          | |
  #  | |    | |__  _ __ ___  _ __ ___   ___  ___ __ _ ___| |_
  #  | |    | '_ \| '__/ _ \| '_ ` _ \ / _ \/ __/ _` / __| __|
  #  | |____| | | | | | (_) | | | | | |  __/ (_| (_| \__ \ |_
  #   \_____|_| |_|_|  \___/|_| |_| |_|\___|\___\__,_|___/\__|
  #
  #
  # Automation to keep Chromecast ON always
  # When chromecase goes into screen saver mode, the status becomes OFF
  # This automation will turn it back on if it is OFF for more than 30 seconds
  - alias: Keep Chromecast On
    trigger:
      - platform: state
        entity_id: media_player.attic_tv
        to: "off"
        for:
          seconds: 30
      - platform: state
        entity_id: media_player.attic_tv
        to: "idle"
        for:
          seconds: 30
    action:
      - service: media_player.turn_on
        entity_id: media_player.attic_tv
      - service: media_player.play_media
        data:
          entity_id: media_player.attic_tv
          media_content_id: !secret frontdoor_camera_stream_url
          media_content_type: video
      - service: input_label.set_value
        data_template:
          entity_id: input_label.current_stream
          value: "frontyard"

  # Motion can be detected anywhere around the house, but the main focus is "Frontyard".
  # By default, the "frontyard" camera stream is played on Chromecast, but when motion
  # detected anywhere  else,  it  changes  the  stream  to  that  corresponding camera.
  # This automation restores back to "default" (frontyard) after 15 seconds!
  #
  - alias: Restore Frontyard Stream
    trigger:
      - platform: time_pattern
        seconds: "/5"
    condition:
      - condition: template
        value_template: "{{ states('input_label.current_stream') != 'frontyard' }}"
      - condition: template
        value_template: "{{ (as_timestamp(now()) -
          as_timestamp(states.input_label.current_stream.last_updated))
          | int > 15 }}"
    action:
      - service: script.frontdoor_cam

  #
  # Every 15 minutes, change stream to alternate view with random cameras
  #
  - alias: Reset Stream On Chromecast
    trigger:
      - platform: time_pattern
        minutes: "/15"
    action:
      - service_template: "script.{{- ['driveway', 'patio', 'playarea'] | random -}}_cam"

script:
  frontdoor_cam:
    sequence:
      - service: script.stream2chromecast
        data_template:
          url: !secret frontdoor_camera_stream_url
          name: "frontyard"
  driveway_cam:
    sequence:
      - service: script.stream2chromecast
        data_template:
          url: !secret driveway_camera_stream_url
          name: "driveway"
  patio_cam:
    sequence:
      - service: script.stream2chromecast
        data_template:
          url: !secret patio_camera_stream_url
          name: "patio"
  playarea_cam:
    sequence:
      - service: script.stream2chromecast
        data_template:
          url: !secret playarea_camera_stream_url
          name: "playarea"
