Binary template sensor - extract an attribute

I have an existing binary sensor created from a template (old format, I know :slight_smile: ).

binary_sensor:
  - platform: template
    sensors:
      sensor_fault:
        friendly_name: "Sensor Fault"
        value_template: >-
          {{ states.sensor  
            | selectattr('attributes.unit_of_measurement', 'defined') 
            | selectattr('attributes.unit_of_measurement', '==', '°C') 
            | selectattr('attributes.sensor_type', 'defined')
            | selectattr('attributes.sensor_type', '==', 'LYWSDCGQ')
            | selectattr('attributes.last_median_of', '<', 5)
            | list | count > 0 }}

This returns true when at least one of the sensors last_median_of value of less than 5.

What I would like to do is extract the friendly names of the sensors that failed the test, into an attribute. I just cannot get the template right to return just the friendly name. Is it possible?

I can return a list of the failed sensors by just removing the count > 0 but I cannot work out how to extract the friendly name.

[<template TemplateState(<state sensor.mi_t_4c65a8d8de98=19.4; state_class=measurement, sensor_type=LYWSDCGQ, mac_address=4C:65:A8:D8:DE:98, median=19.4, mean=19.4, last_median_of=1, rssi=-88, firmware=Xiaomi (MiBeacon V2), last_packet_id=99, battery_level=13, uuid=4C:65:A8:D8:DE:98, unit_of_measurement=°C, device_class=temperature, friendly_name=Catherine Room Temp @ 2022-10-02T13:52:54.202433+01:00>)>]

Copy-paste the following template into the Template Editor and confirm it reports what you want:

          {{ states.sensor  
            | selectattr('attributes.unit_of_measurement', 'defined') 
            | selectattr('attributes.unit_of_measurement', '==', '°C') 
            | selectattr('attributes.sensor_type', 'defined')
            | selectattr('attributes.sensor_type', '==', 'LYWSDCGQ')
            | selectattr('attributes.last_median_of', '<', 5)
            | map(attribute='name')
            | list }}

If you want the result to be a comma-delimited string, use a join filter at the end.

            | list | join(', ') }}
1 Like

Many thanks as ever :grinning_face_with_smiling_eyes:

Can you tell me why it is name rather than friendly_name?

It can be this:

map(attribute='name')

or this:

map(attribute='attributes.friendly_name')
1 Like

Ok, great, many thanks. I thought I’d tried the latter, but many thanks as ever :grinning:

[edit]
@123 (sorry) is it possible to extract more than one attribute?

map(attribute='just one attribute')

1 Like