#:########################################################################################:#
# TITLE: ENTRANCE SPOT PERSON DETECTION
# PACKAGE: entrance_spot_person_detection.yaml
#:########################################################################################:#
# PURPOSE:
# - Turn on the entrance illumination when a configured motion/visitor/presence source
#   becomes active.
# - Temporarily force the illumination ramp number to 1 second for fast response.
# - Restore the original ramp value after the sequence completes.
# - Restart the timing whenever any configured trigger entity activates again.
#
# HOW THIS PACKAGE IS STRUCTURED:
# - Trigger entities are stored in groups for easy future maintenance.
# - The automation listens for state_changed events and checks whether the changed
#   entity is a member of one of those groups.
# - This avoids the limitation of group-state triggers, which would not retrigger
#   if the group was already active from an earlier sensor.
#
# TO ADD MORE TRIGGERS LATER:
# - Add more binary sensors under:
#     group.entrance_spot_person_detection_binary_sensors
# - Add more device trackers under:
#     group.entrance_spot_person_detection_device_trackers
#
# DEVICE TRACKER NOTE:
# - Device trackers often indicate presence using the state "home".
# - If a tracker uses a different detected/present state, change the
#   tracker_active_state value below.
#:########################################################################################:#

group:
  entrance_spot_person_detection_binary_sensors:
    name: Entrance Spot Person Detection Binary Sensors
    entities:
      #- binary_sensor.esp_entmulti_outside_entrance_multisensor_moving_target
      - binary_sensor.view_road_front_door_visitor
      #- binary_sensor.view_road_front_door_motion
      - binary_sensor.view_road_front_door_person

  entrance_spot_person_detection_device_trackers:
    name: Entrance Spot Person Detection Device Trackers
    entities:
      - device_tracker.byd_atto3_ibeacon_bur4c2a_bermuda_tracker

input_number:
  entrance_spot_person_detection_saved_ramp:
    name: Entrance Spot Person Detection Saved Ramp
    min: 0
    max: 720
    step: 1
    mode: box
    icon: mdi:timer-cog

input_boolean:
  entrance_spot_person_detection_ramp_saved:
    name: Entrance Spot Person Detection Ramp Saved
    icon: mdi:content-save-check

automation:
  - alias: Entrance Spot Person Detection
    id: entrance_spot_person_detection
    description: >
      Turn on the front entranceway doorbell illumination when a configured binary
      sensor or device tracker activates. Temporarily force the ramp to 1 second,
      then restore the previous ramp setting after the sequence completes.
    mode: restart
    trigger:
      # Listen for all entity state changes, then filter below so we only respond
      # to configured sensors/trackers becoming active.
      - platform: event
        event_type: state_changed

    variables:
      # Easy-edit entities.
      light_switch_entity: switch.front_entranceway_led_light_controls_doorbell_illumination
      ramp_number_entity: number.front_entranceway_led_light_controls_doorbell_illumination_ramp

      # Easy-edit groups.
      binary_sensor_group_entity: group.entrance_spot_person_detection_binary_sensors
      device_tracker_group_entity: group.entrance_spot_person_detection_device_trackers

      # Easy-edit active states.
      binary_sensor_active_state: "on"
      tracker_active_state: "home"

      # State-change details from the event trigger.
      changed_entity_id: "{{ trigger.event.data.entity_id if trigger.event.data is defined else none }}"
      old_state_value: >
        {{ trigger.event.data.old_state.state if trigger.event.data.old_state is not none else none }}
      new_state_value: >
        {{ trigger.event.data.new_state.state if trigger.event.data.new_state is not none else none }}

      # Members of the configured groups.
      binary_sensor_entities: >
        {{ state_attr(binary_sensor_group_entity, 'entity_id') | default([], true) }}
      device_tracker_entities: >
        {{ state_attr(device_tracker_group_entity, 'entity_id') | default([], true) }}

      # Trigger logic.
      binary_sensor_triggered: >
        {{
          changed_entity_id in binary_sensor_entities
          and old_state_value != binary_sensor_active_state
          and new_state_value == binary_sensor_active_state
        }}

      device_tracker_triggered: >
        {{
          changed_entity_id in device_tracker_entities
          and old_state_value != tracker_active_state
          and new_state_value == tracker_active_state
        }}

    condition:
      # Only continue if the changed entity is one of our configured trigger entities
      # and it has transitioned into its active/detected state.
      - condition: template
        value_template: >
          {{ binary_sensor_triggered or device_tracker_triggered }}

    action:
      # Save the original ramp value only once per active detection cycle.
      # Because the automation uses restart mode, repeated triggers will restart
      # the sequence without overwriting the original saved ramp value.
      - choose:
          - conditions:
              - condition: state
                entity_id: input_boolean.entrance_spot_person_detection_ramp_saved
                state: "off"
            sequence:
              - service: input_number.set_value
                target:
                  entity_id: input_number.entrance_spot_person_detection_saved_ramp
                data:
                  value: >
                    {{ states(ramp_number_entity) | float(1) }}

              - service: input_boolean.turn_on
                target:
                  entity_id: input_boolean.entrance_spot_person_detection_ramp_saved

      # Force the illumination ramp to 1 second for a fast response.
      - service: number.set_value
        target:
          entity_id: "{{ ramp_number_entity }}"
        data:
          value: 5

      # Turn on the entrance illumination.
      # The controlled device/light logic is expected to turn itself off later.
      - service: switch.turn_on
        target:
          entity_id: "{{ light_switch_entity }}"

      # Hold briefly, then restore the ramp once activity has stopped retriggering
      # the automation for this cycle.
      - delay: "00:00:03"

      # Restore the original ramp value that was active before detection.
      - service: number.set_value
        target:
          entity_id: "{{ ramp_number_entity }}"
        data:
          value: >
            {{ states('input_number.entrance_spot_person_detection_saved_ramp') | float(1) }}

      # Clear the saved-state flag ready for the next fresh trigger cycle.
      - service: input_boolean.turn_off
        target:
          entity_id: input_boolean.entrance_spot_person_detection_ramp_saved

      # Optional tidy reset of the helper value.
      - service: input_number.set_value
        target:
          entity_id: input_number.entrance_spot_person_detection_saved_ramp
        data:
          value: 0
