Help with command_line json sensor

Hi all, I’ve created my own command_line json sensor that uses face_recognition service and compare it with rtsp snapshot from my surveillance camera.

It works properly and it stores also the link of the last snapshot of a face detection.

Now my question is…

is it possible to display the last known status of the sensor instead of unknown when no face is detected?

When I detect a face --> I generate a json output
When I don’t detect a face --> I generate no output

Yes.

Create a template sensor that only updates if the state is not “unknown”. e.g.

- platform: template
  sensors:
    new_sensor:
      value_template: >
        {% if is_state('sensor.your_existing_sensor', 'unknown') %}
          {{ states('sensor.new_sensor') }}
        {% else %}
          {{ states('sensor.your_existing_sensor') }}
        {% endif %}

Thanks for the prompt reply.

This is my original sensor. If I use a template sensor, will it copy all the attributes?

  - platform: command_line
    name: Face Veranda 2
    json_attributes:
      - Faccia1
      - Faccia2
      - Faccia3
      - Faccia4
      - Faccia5
      - Faccia6
      - Faccia7
      - Faccia8
      - Persone
      - FacceTotali
      - Data
      - File
    command: 'python C:\GoogleHome\Python\CameraFaceDetection.py Veranda2 rtsp://admin:[email protected]:14000/tcp/av0_0'
    value_template: '{{ value_json.Stato }}'
    scan_interval: 10
    command_timeout: 120

No, only the state, you didn’t ask about attributes, only the state so that’s all my answer contains.

Got it. What about the attributes? I want to mantain the latest when the status was not unknown

See: https://www.home-assistant.io/integrations/template/#attribute_templates

There’s an example lower down: https://www.home-assistant.io/integrations/template/#add-custom-attributes

Something like this?

attribute_templates:
          faccia1: >-
            {% if is_state('sensor.your_existing_sensor', 'unknown') %}
              {{ state_attr('sensor.new_sensor','faccia1') }}
            {% else %}
              {{ state_attr('sensor.your_existing_sensor','faccia1') }}
            {% endif %}

Yep. You got it (the indentation is usually only 2 spaces though).

Great!!! Thanks a lot!!!

It works like a charm!!! Thanks @tom_l

1 Like

One thing… when I restart HA, the values of the template sensors are lost… is there a way to keep them?

Unfortunately no.