How to find a sensor in a location and get its value using templates

To respond to an intent, I need the value of one sensor at a certain location. I created a filter for this, but when I put it in a template states(’ '), it doesn’t seem to work.

{{ 
  states.sensor
  |selectattr('attributes.device_class', 'eq', 'carbon_dioxide')
  |selectattr('entity_id', 'in', area_entities('hall'))
  |map(attribute='entity_id')
  |first
}}

area will be a variable value

Can you please help me out? What would be the correct syntax?

Why would you do that? You already have access to the state object, there’s no benefit in rendering the entity ID and running it through an additional function… just map the state. Make sure to select for device class being defined, and that your Area name matches (spelling, capitalization, etc).

{{ 
  states.sensor
  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class', 'eq', 'carbon_dioxide')
  | selectattr('entity_id', 'in', area_entities('hall'))
  | map(attribute='state')
  | first
}}

Thank you for your help. I had assumed something similar, but I failed due to a lack of basic knowledge.

There is another question. Is there a filter to select the max (or min) value instead of the first one if there are several devices in the area?

Yes.

You could try it out in the Developer Tools > Template, where there are handy links to the documentation where you can find the list of builtin Jinja filters:

https://jinja.palletsprojects.com/en/latest/templates/#list-of-builtin-filters

OK, I found the answer. Tnx.

Then could you tell me what the practical meaning of the filter is “selectattr(‘attributes.device_class’, ‘defined’)”.
Doesn’t it duplicate the next one, in which we sort devices by a specific class?
Would it be correct to delete this part of the code?

No. Not all sensors have a device class assigned to them, if you don’t first select for sensor’s that do, your second selection filter can fail due to error when it iterates over an object that doesn’t looking for the value carbon_dioxide.

1 Like