Value Template Using Time From Entity Attribute

Trying (and failing) to create a value template to determine whether a ‘target’ was detected within the previous 30s. I’m hoping to use this as a condition within an automation to throttle notifications when a target is detected.

State attributes of the entity are below, the attribute im looking to use is ‘last_target_detection’:

targets:
  - target: person
    confidence: 70
targets_found: []
summary: {}
last_target_detection: 2022-07-08_19-12-09-422790
all_objects:
  - potted plant: 43.717
  - car: 91.79
save_file_folder: /media
save_file_format: jpg
save_timestamped_file: false
always_save_latest_file: true
unit_of_measurement: targets
friendly_name: deepstack_object_ip_camera_north

So far i have the following:

{{ (as_timestamp(now()) -
  as_timestamp(state_attr('image_processing.deepstack_object_ip_camera_north',
              'last_target_detection')
  | default(0)) | int > 30)}}

however this generates the following error in the template editor:

ValueError: Template error: as_timestamp got invalid input '2022-07-08_19-12-09-422790' when rendering template '{{ (as_timestamp(now()) -
  as_timestamp(state_attr('image_processing.deepstack_object_ip_camera_north',
              'last_target_detection')
  | default(0)) | int > 30)}}' but no default was specified

Any suggestions gratefully received.

try this:

{{as_timestamp(now()) - as_timestamp(strptime(state_attr('image_processing.deepstack_object_ip_camera_north', 'last_target_detection'), '%Y-%m-%d_%H-%M-%S-%f')) > 30  }}

strptime takes a string and converts it to a valid datetime object that as_timestamp can use.

Spot on, thank you. One final question, given there is a time delay between starting Home Assistant and the entity attribute reporting a value the following error message is displayed in the logs.

Is there any way to prevent this error message from appearing?

TemplateError('ValueError: Template error: strptime got invalid input 'None' when rendering template '{{as_timestamp(now()) - as_timestamp(strptime(state_attr('image_processing.deepstack_object_ip_camera_north', 'last_target_detection'), '%Y-%m-%d_%H-%M-%S-%f')) < 30 }}' but no default was specified') while processing template 'Template("{{as_timestamp(now()) - as_timestamp(strptime(state_attr('image_processing.deepstack_object_ip_camera_north', 'last_target_detection'), '%Y-%m-%d_%H-%M-%S-%f')) < 30 }}")' for attribute '_attr_native_value' in entity 'sensor.north_target_detected'
{{as_timestamp(now()) - as_timestamp(strptime(state_attr('image_processing.deepstack_object_ip_camera_north', 'last_target_detection'), '%Y-%m-%d_%H-%M-%S-%f', default=0)) > 30  }}

That will eliminate the error but will give a potentially erroneous true result because now() minus 0 will always be greater than 30.

I think in some cases it may be better to accept the error and not allow the template to render than to give a false positive or negative result. Especially if the error is only ever generated at start up.

Thank you - I really appreciate your help with this. I’ve now discovered a further issue. The entity attribute last_target_detection is not generated until an image scan has been run and a target has been detected.

I need the automation to continue even though the value template is throwing an error. Is there a way to ignore value template errors when processing an automation?

post the automation you have now.

See below. Note, i’m currently using a timer workaround instead of the value template. It works, but ideally I would like to use the value template as it would be more CPU efficient given there would be a 30s pause in sending further images to the AI engine once a target had been found. Without this, when movement detected by the camera, images would continue to be sent to the AI engine however notifications would be throttled via the timer. Considerable CPU time would be spent processing images which would never be used in a notification.

alias: >-
  Camera North - (DeepStack:Processing+Notify)
description: >-
  Trigger on motion detected by camera north.

  Perform image processing service call to reset counter state. (counter state records number of targets found in previous image processed)

 *Disabled* Only perform image processing if a target HAS NOT been found in the past 30s

  If target found during counter reset process then stop automation (notify will
  trigger when target detected)

  If no target found then loop while motion is on and there is no target
  detected until either target detected or motion is off.

  If target detected then notify will trigger.
trigger:
  - platform: state
    entity_id:
      - binary_sensor.north_motion
    to: 'on'
    id: Motion
  - platform: event
    event_type: deepstack.object_detected
    event_data:
      name: person
    id: Notify
condition: []
action:
  - choose:
      - conditions:
          - condition: trigger
            id: Motion
          - condition: template
            value_template: >-
              {{as_timestamp(now()) -
              as_timestamp(strptime(state_attr('image_processing.deepstack_object_ip_camera_north',
              'last_target_detection'), '%Y-%m-%d_%H-%M-%S-%f')) > 30  }}
            enabled: false
        sequence:
          - service: image_processing.scan
            data: {}
            target:
              entity_id: image_processing.deepstack_object_ip_camera_north
          - if:
              - condition: numeric_state
                entity_id: image_processing.deepstack_object_ip_camera_north
                above: '0'
            then:
              - stop: ''
            else:
              - repeat:
                  while:
                    - condition: not
                      conditions:
                        - condition: state
                          entity_id: binary_sensor.north_motion
                          state: 'off'
                        - condition: numeric_state
                          entity_id: image_processing.deepstack_object_ip_camera_north
                          above: '0'
                  sequence:
                    - delay:
                        hours: 0
                        minutes: 0
                        seconds: 2
                        milliseconds: 0
                      enabled: false
                    - service: image_processing.scan
                      data: {}
                      target:
                        entity_id: image_processing.deepstack_object_ip_camera_north
      - conditions:
          - condition: trigger
            id: Notify
          - condition: state
            entity_id: timer.camera_north_person_detection_timer
            state: idle
            enabled: true
        sequence:
          - service: notify.cergon
            data:
              message: >-
                Detected {{ trigger.event.data.name }} with confidence {{
                trigger.event.data.confidence }}
              data:
                image: /media/local/deepstack_object_ip_camera_north_latest.jpg
                clickAction: /lovelace-mobile/security
                group: Security
              title: 'ALERT:'
          - service: notify.mobile_app_wall_display
            data:
              message: TTS
              title: ALERT! {{ trigger.event.data.name }} detected at front of house.
          - service: timer.start
            data:
              duration: '00:00:30'
            target:
              entity_id: timer.camera_north_person_detection_timer
            enabled: true
    default: []
mode: parallel

you can try this:

{% if state_attr('image_processing.deepstack_object_ip_camera_north', 'last_target_detection') == None %} 
  true
{% else %}
  {{as_timestamp(now()) - as_timestamp(strptime(state_attr('image_processing.deepstack_object_ip_camera_north', last_target_detection'), '%Y-%m-%d_%H-%M-%S-%f')) > 30  }}
{% endif %}

Perfect, thank you. Automation is working as expected, thank you for all your help.

1 Like