Serial Sensor - "Regex" Data

Hi guys, I am a little bit frustrated right now, but let me explain!

at first: If this thread is in the wrong chapter, please move it to the correct one!

I am able to receive data through serial port from sensor, this is working!
Now I want to extract the values from this string via templating.

What I have:
sensor:

  • platform: serial
    serial_port: /dev/ttyUSB0
    name: smartmeter_data
    baudrate: 9600
    bytesize: 7
    parity: E
    stopbits: 1
  • platform: template
    sensors:
    smartmeter_total:
    unit_of_measurement: “kWh”
    value_template: >
    {% if states(‘sensor.smartmeter_data’)|regex_search(“1-0:1.8.0255") %}
    {{ states(‘sensor.smartmeter_data’)|regex_findall_index("((\d
    .\d*))”) | float }}
    {% else %}
    {{ ‘sensor.smartmeter_data’ }}
    {% endif %}

The received string is looking like that:
1-0:0.0.0255(hidden_serialnumber)
1-0:96.1.0
255(hidden_serialnumber)
1-0:1.8.0255(000021kWh)
1-0:2.8.0255(000004kWh)
1-0:96.5.0255(001C0104)
0-0:96.8.0
255(0002DC73)

The result on the dashboard is “unknown” for “smartmeter_total”

What I am doing wrong?

Thanks for your help in advance!

From the FAQ: Format your code


This line in your template doesn’t return the sensor’s value:

{{ 'sensor.smartmeter_data' }}

Change it to this:

{{ states('sensor.smartmeter_data') }}

Reference: Templating - States


In addition, your template’s regex pattern produces more than one matching value.

The float filter cannot process multiple values so it will result in an error (and that’s why the sensor’s value is unknown).

I suggest you try this template:

    value_template: >
      {% set sd = states('sensor.smartmeter_data') %}
      {% if '1-0:1.8.0255' in sd %}
        {{ sd[13:-4] | float(0) }}
      {% else %}
        {{ sd }}
      {% endif %}

Thanks for your suggestion, but its a little bit strange, the result is still “unknown”

Start by posting a properly formatted version of your sensor’s YAML configuration. Without that, we are unable to check it for YAML syntax errors.