Mapping attribute values to a string

I am looking to map MAC addresses to users, and they are listed in a sensor with an attribute called occupants.

Is there an easy way of doing this?

I was thinking of doing something like

      {% if '57:D5:65:AA:47:6A' in
      state_attr('sensor.landrover_automate','occupants') %}
        bla
      {% else %}
        no known user found
      {% endif %}

in the Lovelace card but it doesn’t support it of course. And if i create a template sensor, i’m not sure how to hold a 1-1 mapping of MAC address to user which i can later reference (probably the best way of doing this).

For reference this sensor looks like:

time: 26 Oct 2022 22:53:46
occupants: >-
  5C:2E:21:B8:68:3D, 67:B1:6E:76:93:32, 88:63:DF:9D:4E:74, 57:D5:65:AA:47:6A,
  D9:06:30:6B:FF:5D, C3:9A:BC:FD:B7:ED, 4E:6F:DB:63:99:35, EE:BA:A2:BD:43:47,
  D0:F6:80:36:B6:6C, 63:6E:FA:EB:79:23, 88:57:1D:93:45:A0, E9:9B:B0:D5:1C:DE,
  20:0C:79:51:A6:00, 34:42:73:51:A6:00, 7C:A6:B0:5D:24:FA, FE:9F:F4:D2:AC:FA,
  F0:27:2D:13:49:1F
bytes_downloaded: '593336'
bytes_uploaded: '2095806'

Any thoughts how one could accomplish this ?

Is occupants an actual list or a list-shaped string…? You can test this by checking the following in the Template tool:

{{ state_attr('sensor.landrover_automate','occupants') | count }}

I get 283 as a result, which i assume is the amount of characters. Not sure what that would make it though.

That means it’s a string, not a true list, so that has to be taken into account… Try the following, mapping your users to their MACs as necessary:

template:
  - sensor:
      - name: Vehicle Occupants
        state: >
          {% set occupants = state_attr('sensor.landrover_automate','occupants') %}
          {% set l = occupants.replace('\n ', '').rsplit(', ') %}
          {% set known_users = {
            'D9:06:30:6B:FF:5D': 'person1',
            'D0:F6:80:36:B6:6C': 'person1',
            '63:6E:FA:EB:79:23': 'person2',
            '88:63:DF:9D:4E:74': 'person3',
            'F0:27:2D:13:49:1F': 'person4'
          } %}

          {% set ns = namespace(in_group=[]) %}
          {% for o in l %}
            {% if o in known_users.keys() %}
              {% set ns.in_group = ns.in_group + [known_users.get(o)] %}
            {% endif %}{% endfor %}
          {{ ns.in_group | unique | join(', ') if ns.in_group != [] else 'No Known Users Found'}}
1 Like

Nice, thank you - let me try and mess around with this.