How to use regex_findall_index for motion detection CGI

Hello,
I use Dlink camera, When i go to http://192.168.0.22/config/notify.cgi
I have this feedback !

md1=off
mdv1=0
pir=off
input1=off
recording=off
output1=off
speaker=on
speaker_occupied=off
mic=on
mic_muted=off
irled=off
led=on
audio_detected=off
audio_detect_val=58
cameraname=salon_2

I try to add in config.yaml :

sensor:
  - platform: command_line
    name: "test"
    command: curl -k --silent "http://USR:[email protected]/config/notify.cgi"
    value_template: >
      {% set status = value | regex_findall_index('md1=(\d+)') %}
      {%- if status == "off" -%}
        None
      {%- elif status == "on" -%}
        Detected
      {% else %}
        Not Determined
      {%- endif -%}
    scan_interval: 3

Th goal is to have the value of md1

Can you help me?

have a good day.

I think you are missing the “after limit” part of the regex.

try this:

{% set status = value | regex_findall_index('md1=(\d+)pir') %}

or maybe:

{% set status = value | regex_findall_index('md1=(\d+)\npir') %}

since I’m not sure how regex deals with newlines.

Thx you, but it don’t work, in the log file, i have this error ;

File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1243, in regex_findall_index
    return re.findall(find, value, flags)[index]
IndexError: list index out of range

sorry,

try this:

{% set status = value | regex_findall_index('md1=(.+)') %}

Great ! it’s better the I have the sensor, but the result is “Not Determined”.
Normally the result is off

the IF structure is good for you?

I don’t have those cameras to test live. I just copied your supplied results from above into the template editor and tested there. And everything worked as expected for me.

Try this:

    value_template: >
      {{ 'None' if 'md1=off' in value else 'Detected' if 'md1=on' in value else 'Not Determined' }}

Yes thx you ! i don’t understand why the code don’t work.
i am confused
I put the code of 123 taras ! and i works fine.

Thanks for your help …

wo thankx you it’s seem to works fine :slight_smile:
I don’t understand why my previous code don’t work. i am confused.

Thanks for your help

The first one failed because it used the wrong pattern. This pattern \d is used for matching numbers (not letters).

This pattern .+ matches anything. The reason why it works in finity’s example is because pattern-matching stops at the first newline so md1=(.+) will only match the first line and return off.

However, I suspect your sensor’s state value contains no newlines (all the data is on one line) so the same pattern will match something very different (the word off and all the characters after it).

A problem I encountered with regex_findall_index is that if it fails to find a match it returns the error you have seen (list index out of range). I feel it should simply return an empty string and not abort with an error.