Get a device_id from entity_id

Hi guys,

could you tell me please how to get a device_id from an entity_id?
I have a device that reports a few sensors.
I found a way how to go through entities to read their battery level, but there is no point in reporting a few different entities if they all come from the same device.

Thank you

Somebody posted this link before:

variables:
  haspdevice: !input haspdevice
  haspname: >-
    {%- for entity in device_entities(haspdevice) -%}
      {%- if entity|regex_search("^sensor\.") -%}
        {{- entity|regex_replace(find="^sensor\.", replace="", ignorecase=true)|regex_replace(find="_sensor(?:_\d+|)$", replace="", ignorecase=true) -}}
      {%- endif -%}
    {%- endfor -%}

I can’t say I understand it, but it may give you a starting point

Whaaaaaaaaaaaaaaaat, undocumented method???

Sadly, I don’t think that will work for OP because device_entities requires a device_id to complete. So unless there’s an undocumented method that lists out all device_ids…

EDIT: Just checked the code… no undocumented method for that :frowning:

EDIT2: Although… adding it doesn’t seem to be too hard.

Thank you guys, may be it is possible to get a list of all devices then?
I found group.all_devices mentioned here but it looks like it had been removed a while ago.
Any other ways of getting a list of all devices (in templates)?

I have a template that goes through all states and picks up one that has battery level < XX.
Unfortunately its output is rather “dirty”:

{% set ns = namespace(mdevice=[]) %}
{% for state in states %}
{%- if state_attr(state.entity_id, "battery") != None -%}
{%- if state_attr(state.entity_id, "battery") < 50 -%}
{%- set list2 = state.entity_id.split('.0x')[1].split('_') -%}
{#{ list2 }#}
{#%- ns.mdevice|string + "::" + list2[0] -%#}
{%- if list2[0] not in ns.mdevice -%}
{{- state.attributes['friendly_name'] + ":" + state.attributes['battery']|string + "\n" -}}
{#{- state.entity_id|regex_replace(find="^sensor\.", replace="", ignorecase=true)|regex_replace(find="_sensor(?:_\d+|)$", replace="", ignorecase=true) -}#}
{#{- state.entity_id +"\n" }#}
{%- set ns.mdevice = ns.mdevice + [list2[0]] -%}
{%- endif -%}
{%- endif -%}
{%- endif -%}
{% endfor %}

2021-06-30 10_08_39-Window

I am trying to get rid of those “update available” but I can’t since it is part of a sensor’s friendly_name.

What I would like to have is just " Cabinet wall light dimmer" - as it is shown in HA → “Devices” tab.

here it is:

{{device_id('sensor.mysensor')}}
4 Likes