Get specific value from attribute

Goodmorning all,

I have a custom component that scans for all bluetooth devices in the proximity. All those values are stored in the attribute of a sensor like this:

But now what I want is to create a template sensor that show me the RSSI of a specific mac address. I got it to work but I feel like there must be a more “clean” way to do it. This is wat I got:

{% set x = state_attr('sensor.huiskamer_speaker_bt_devices', 'bt_devices') %}
{% for i in x %}
  {% if i.mac_address == 'd0:11:11:11:11:1' %} 
{{ i.rssi }}
  {% endif %}
{% endfor%}

Any ideas?

Greetings,
Jos Vink

try this

{% set x = state_attr('sensor.huiskamer_speaker_bt_devices', 'bt_devices') | count %}
{% set y = state_attr('sensor.huiskamer_speaker_bt_devices', 'bt_devices') %}
{% for i in range(0,x) %}
{% if y[i].mac_address == 'd0:11:11:11:11:1' %}
{{ y[i].rssi }}
{% endif %}
{% endfor%}

Sorry for the late reply. This works thanks!

Copy-paste the following template into the Template Editor and confirm it reports the desired value (I don’t have the needed entity to test it for you). It should report the rssi value.

{{ state_attr('sensor.huiskamer_speaker_bt_devices', 'bt_devices')
   | selectattr('mac_address', 'eq', 'd0:11:11:11:11:1')
   | map(attribute='rssi') | list | first }}

so this second attribute map(attribute=‘rssi’) is actually embedded of attribute mac_address…?
Would the same logic apply when you go even one (more) attribute - levels deeper?

Copy-paste the following template into the Template Editor and experiment with it:

{% set x = [
  { "name": "John",
    "age": 45,
    "id": 3456 },
  { "name": "Jane",
    "age": 38,
    "id": 1234 },
  { "name": "Sam",
    "age": 27,
    "id": 7890 },
  { "name": "Sue",
    "age": 62,
    "id": 1357 } ] %}

{{ x | selectattr('name', 'eq', 'Jane') | list }}

{{ x | selectattr('name', 'eq', 'Jane')
  | map(attribute='age') | list }}

{{ x | selectattr('name', 'eq', 'Jane')
  | map(attribute='age') | list | first }}

Screenshot

2 Likes

we are very much deviating here but that is not what I meant with my question.
From the OP post assume that “expected profiles”
has another set of (say) 2 sub attributes of which one of them has another 3 sub-attributes.
Does your proposed solution allow to dive into this the same way, iterating whilst searching?

I posted the example so you could experiment with it and find the answer to your question (thereby not hijacking the author’s topic). However, if you want me to answer it, modify the value of the variable x in the manner you want and then I can help you (because I don’t understand the proposed structure of “2 sub-attributes with one having 3 sub-attributes”).

Hi Taras!

This also works! Thanks!