#templates-archived

1 messages · Page 133 of 1

reef onyx
#

I will try with:
sensor:
- name: "Irene Duolingo XP points"
value_template: "{{ value_json.students[0].xp.points }}"
json_attributes_path: $
json_attributes: "{{ value_json.students }}"

#

2021-08-24 22:40:59 WARNING (MainThread) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary

inner mesa
#

I didn't say {{ value_json.students }} for the attributes

reef onyx
#

same error. i make a mirror of the file on my webserver and try it instead

#

and it works

#

hmm

#

i compare the header i use with curl with the packet capture i made on my web server of a request from home assistant

#

looks like i have the same headers in the packet capture as i specify when i run curl

#

only difference in the request is the host and get due to another uri

#

i do a workaround. a cron job at the webserver save the data to a file and home assistant can read it as often i wants 🙂

#

It works. Now i can make an automation that gives my son more internet time on saturdays if he get enough duolingo XP monday to friday 🙂

#

i also get data for my wife 🙂

#

They both need to learn Swedish 😄

ivory delta
reef onyx
#

before this summer i replaced my "ugly" bash scripts that used expect to log on to the firewall to enable and disable my sons internet access on his PC

#

My fortigate have a quite nice API and now i can also see if the firewall policy is on or off so the state is always up to date

#

The plan with duolingo was to extract data from the emails i get when he completes tasks. With the experience from the api call to my firewall I realised that i can get the data via the API. Developere tools in firefox gave me a nice formated one liner in curl

ivory delta
#

API's should always be the preferred way to get data smart

reef onyx
#

to bad i couldn't skip the cron job at the web server

#

i prefer not to have any dependency on other machines for functions

#

Time do do as Tor Johnson said. "Time for go to bed" 😄

fringe temple
#

getting an odd message when trying to check config on a new sensor.template
Invalid config for [sensor.template]: [state] is an invalid option for [sensor.template].

inner mesa
#

sensor.template isn’t a thing. Share the configuration

#

I suspect that you’re mixing up the old and new template sensor formats

fringe temple
#
sensor:
  - platform: template
    sensors:
      my_sensor:
        state: "{{ states('media_player.living_room') }}"
        [...]
inner mesa
#

That’s the old/legacy format, which doesn’t have state:

fringe temple
#

lol well that would explain it

inner mesa
#

There’s a section at the bottom for the legacy format

#

You can use either, but you can’t mix and match in a single definition

fringe temple
#

so the new format is the one which would be represented as

sensor:
  - platform: template
    sensors:
      - name: my_sensor
        state: "{{ states('media_player.living_room') }}"
        [...]
``` ??
inner mesa
#

No

#

Compare with the example in the docs

#

That’s still an unholy mixture of the two

ivory delta
#
  - sensor:
      - name: "Average temperature"```
#

That's your basic structure. It doesn't start with sensor: at the top, and it doesn't have platform: template anywhere at all.

rare sage
#

Daad Day all, Why would this not import my templates.yaml "template: !include_dir_merge_list templates.yaml"

ivory delta
#

Hint: ||templates.yaml isn't a directory||

autumn matrix
#

In C++ you have a map function which maps a range to another range. int percentage = map(300, 500, 0, 100);. This I want to use for my CO2 sensor so that when the value is 400 I can set my mechanical home ventilation system to run at 50%. I can program this in my ESP32 and simple send it to MQTT broker as mechanical_home_ventilation_suggestion but I was wondering if this could also be done in home assistant. Any suggestions? (I'm guessing this is to advanced for automations so thats why i'm asking it here)

mighty ledge
silent barnBOT
autumn matrix
#

Thank you petro. I'll be looking into this

bronze horizon
#

I followed the "JSON Attributes Template Configuration" section of the MQTT sensor docs to extract individual attributes out with a template. It works generally, but any attribute returning a null value generates a TypeError: Object of type LoggingUndefined is not JSON serializable error.

To try and work this out I put {% set var = {"a": null} %}{{ var | tojson }} in the template editor, and got the same error. Is there a way I can properly handle these null values in JSON with a templte?

jagged obsidian
#

what does the json payload look like with null?

bronze horizon
#

It's pretty big, I'll grab a pastebin

#

There are a few other examples, but one of the templates looks like this:

{% if value_json['fsSize']['E:'] is defined %}
        {{ {  'fs': value_json.fs,
        'size': value_json.size,
        'used': value_json.used,
        'available': value_json.available,
        'use': value_json.use } | tojson }}
      {% endif %}

None of fs/size/used/available/use are null , in this case that's the temperature and disksIO attributes.

bronze horizon
#

Probably also worth noting that if I remove the whole json_attributes_template part from the config, the full attributes populate on the sensor, including the null ones.

jagged obsidian
#

you're probably trying to do this

#
{% if value_json['fsSize']['E:'] is defined %}
{% set value = value_json['fsSize']['E:']%}
{ 'fs': {{value.fs}},'size': {{value.size}},'used': {{value.used}},'available': {{value.available}},'use': {{value.use}} }
{% endif %}
bronze horizon
#

Hmm I'm not sure that's it but it did make me realise a huge error I'd made with the json path. This seems to be working:

      {% if value_json['fsSize']['E:'] is defined %}
        {{ {  'fs': value_json['fsSize']['E:']['fs'],
        'size': value_json['fsSize']['E:']['size'],
        'used': value_json['fsSize']['E:']['used'],
        'available': value_json['fsSize']['E:']['available'],
        'use': value_json['fsSize']['E:']['use'] } | tojson }}
      {% endif %}
#

I'm not sure how I got that mixed up with the null attributes...

jagged obsidian
#

yeah it was not it if you need json as the result. you can still replace value_json['fsSize']['E:'] with set

bronze horizon
#

What would be the advantage of that? Just overall neatness of the code?

jagged obsidian
#

yes, and easier editing and multiplying of it

unreal dove
#

Hey guys. How do is evaluate for a single state attribute that is from a list?
Let's say there's two in a list [E8:07:BF:76:E8:F6, 68:E7:C2:20:2F:AA]
And I'm evaluating for if just one is in that list. I'm using this:
{{ is_state_attr('sensor.mealsmob3_bluetooth_connection', 'connected_paired_devices', '68:E7:C2:20:2F:AA') }}
But it only works if the list is size one.

ivory delta
#

You'd use the in operator to check for the presence of an item in a list:
{{ '68:E7:C2:20:2F:AA' in state_attr('sensor.mealsmob3_bluetooth_connection', 'connected_paired_devices') }}

#

D'oh, other way round... lemme edit

#

Like that

unreal dove
#

Sweet! Thank you. I was down the rabbit hole for too long..

ancient lynx
#

Hi everyone. Having a history_stats issue that I can't wrap my head around. It's about setting up the timeframe template, so I hope this is the correct channel to ask it in.

#

I have a sensor that marks someone as sleeping based on some conditions that I have found very reliable. So now I want to set up a history stats sensor that gets the time of sleeping overnight for each day. So obviously I don't want that time to be cut off at midnight and start a new day.

#

I found the Next 4 pm example on the history_stats page:

end: "{{ (now().replace(minute=0,second=0) + timedelta(hours=8)).replace(hour=16) }}"
duration:
    hours: 24

but I can't get my head around what timedelta does. Can someone explain?

inner mesa
#

as in your example, timedelta allows you to add/subtract an offset of the magnitude that you specify

#

add 1 minute, subtract 4 hours, etc.

ancient lynx
#

So if I wanted to do from yesterday at noon to today at noon, I would do {{ (now().replace(minute=0,second=0) + timedelta(hours=12)).replace(hour=12) }}?

#

Or would it just be easier to define an end time in the morning and count back a set amount of hours from there?

inner mesa
#

that's equivalent to noon today if before noon or noon tomorrow if after noon

#

to get noon of yesterday, I would do {{ now().replace(hour=12,minute=0,second=0) - timedelta(days=1) }}

ancient lynx
#

Ah ha. That is a lot simpler. Thank you!

fringe temple
#

when i moved my template sensors to an include, i.e. config.yaml w/ template: !include templates.yaml do i just start listing triggers & sensors or anything special? i had kept the template: key mistakenly...

inner mesa
#

you put everything that would have otherwise gone under template: in the file

wooden sonnet
#

Hi. I have a continuous sensor that has a value from 0.0 to 5.0. I'm trying to figure out a way to know what % of the maximum possible sum of readings over the last 24 hours (5 min interval readings). In other words, 1,440 minutes in a day / 5 minute intervals = 288 intervals. 288 intervals * 5.0 (maximum value of sensor) -> 1,440 again (max possible value for 24 hrs). If the sensor were flat at 2.5 for the past 24 hrs, I'd expect 720/1440 = 0.50. I was about to setup an automation to pull readings and do some arithmetic/store state but figured I'd see if there was anything simper I might have overlooked. I've been playing around with Riemann sum integrals and reading up on history_stats but haven't had any luck implementation-wise.

brisk sonnet
#

Hi all, I am trying to create a sensor that returns a value in hours/minutes from a timestamp and the current time. The timestamp sensor i have is sensor.daves_pc_idle which returns a value of 2021-08-26T12:59:23 I want to use the returned value in an automation and compare it to a set value of say 15 minutes or 1 hour and 10 minutes. Can anyone help with this ?

brisk sonnet
#

I worked it out. - platform: template sensors: daves_pc_idle_time: unit_of_measurement: "m" value_template: >- {{ ((as_timestamp(now()) - (as_timestamp(states('sensor.daves_pc_idle')))) /60) | int }}

fossil venture
#

Dont use a unit, as the sensor will produce results like "7 days 5 minutes and 12 seconds ago"

brisk sonnet
#

Ok. Thanks.

fossil venture
#

Actually it will only return the biggest unit, so for my example it would return "7 days"

edgy umbra
#

Is it possible with a tempate to get the highest temp for today and summary from the weather integration.

ivory delta
#

You're asking that without sharing the data you plan to get it from...

#

.share the data, then maybe we can say if it's possible.

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

floral shuttle
#

did I miss the change in functionality of this: state: > {% set month = now().strftime('%m') %} {% if month in ['1','3','5','7','8','10','12'] %} 31 {% elif month in ['4','6','9','11'] %} 30 {% else %} {{'29' if states('sensor.year')|int//4 == 0 else '28'}} {% endif %} or is it caused by todays beta 2021.9...

#

apparently we can not use the month numbers without a leading 0 anymore? or use %-m

inner mesa
#

you're doing string comparisons there. what part do you think has changed?

ivory delta
#

This is also a really terrible way to work out leap years:
states('sensor.year')|int//4

#

Suppose you'll be dead before the next time it's wrong though 😂

charred dagger
#

In 79 years? Could happen.

ivory delta
#

Depends where you live, I guess. Life expectancies are heading in the wrong direction in some places.

dreamy sinew
#

now().month is a thing

#

returns an int of the current month

#

now().year does the same for year

#
{{ (now().replace(month=next, day=1) - now().replace(day=1)).days }}```
#

@floral shuttle

#

might have problems at the end of the year though

#
{% set next_month = 1 if n.month == 12 else n.month + 1 %}
{% set next_year = n.year + 1 if next_month == 1 else n.year %}
{{ (n.replace(year=next_year, month=next_month, day=1) - now().replace(day=1)).days }}``` now fixed
#

lol

#

let the thing that actually knows the calendar tell you the days 🙂

floral shuttle
inner mesa
#

You’re comparing against strings that don’t have a leading zero, so I guess the format string tokens might be different?

#

Seems unlikely though

#

%m 09 Month as a zero-padded decimal number.

dreamy sinew
#

Mine doesn't use any strings

#

😛

fossil summit
#

Hi guys, I have a question... what do you use to sum up multiple energy plugs to have a per-room sensor to pass to the utility_meter integration?

#

I have one but it doesnt' work well, when a device goes offline it is counted as "0", so the sensor goes up and down depending on reboots.. causing the utility_meter to misscalculate usage

mighty ledge
#

add an availability template to your entity and it won't go down to zero

tacit arch
#

Hello, I woul like to use Energy tab. I have the power used by the house and the power produced by the solar powerplant. So I should create an entity with differences if above zero (for example, power from the grid should be homepower-solarpower if >0 )
How can I do so?

ivory delta
#

Something like {{ [0, states('sensor.sensor_one') - states('sensor.sensor_two')] | max }} might do it. Just make sure you're doing the subtraction the right way round,.

#

That'll do the difference, even if it's a negative value, but return the largest value from the array each time (0 if the other one went negative).

tacit arch
ivory delta
#

Simple? For Jinja? 😂

#

There are links to the docs (HA and Jinja) in the topic and pins here... but templating is difficult, so there's going to be no simple guide.

tacit arch
#

value_template: "{{ '%0.1f' | format(states('sensor.power_home_energy_today')|float - states('sensor.power_powerplant_energy_today')|float) }}" does, i suppose your idea was to take the bigger value in the array between 0 an the value, it shoul work, is there a syntax error?

winter drift
#

I'm looking to get my tasmota switch set with switchmode 15 to toggle a zigbee light on and off but when the button is pushed i get a tele/lilly_light/SENSOR = {"Time":"2021-08-27T14:45:04","Switch1":"ON"} which im thinking i need a template in my automation to be able to grab the switch1 state, anyone have any ideas?

tacit arch
winter drift
#

when i enter the {} into the payload the automation does not work

tacit arch
dreamy sinew
tacit arch
dreamy sinew
#

need an extra ) after |max

tacit arch
#

yes, found, let's check

pastel moon
#

I would need to create a template that creates a list of entities of types X & Y from what is can find in my scenes files. I need this to supply to the scene snapshotting definition. Is there a good way of doing this, or perhaps a better way?

tacit arch
inner mesa
pastel moon
#

Oh, sorry. types I meant 'light', 'switch' etc

#

This because I have some outlets that are categorized as switches, and would like them as well in the list of light entities

inner mesa
#

those are "domains"

#

the rest of the question is still a bit of a jumble

#

you want a list of entities that are part of scenes?

#

from what is can find in my scenes files

#

?

pastel moon
#

I'll try again, sorry to be vague, not my intention

inner mesa
#

not vague, just hard for me to parse

pastel moon
#

I have a set of scene files. I'd like to extract the entities for select domains from these into a list

inner mesa
#

the fact that you've separated your scene definitions into several files doesn't matter (again)

pastel moon
#

ok, keep forgetting that. I guess i think in terms "file parsing"

inner mesa
#

assuming they're in devtools -> States, you can use expand() to generate the entities

pastel moon
#

Ah, that is interesting, I've seen some talk about expand before, never really got into what it could be used for. Will have a read on that. Thanks! 🙂

inner mesa
#

I couldn't make that work. This is a start: {{ states.scene|map(attribute="attributes.entity_id")|list }}

#

that gives a list of lists of entities and I'm trying to flatten it somehow

#

ha: {{ states.scene|map(attribute="attributes.entity_id")|sum(start=[])|unique|list }}

#

only lights: {{ states.scene|map(attribute="attributes.entity_id")|sum(start=[])|select('match', 'light')|unique|list }}

#

switches and lights: {{ states.scene|map(attribute="attributes.entity_id")|sum(start=[])|select('match', 'switch|light')|unique|list }}

#

I'm done with this: @pastel moon

pastel moon
#

This is so cool! Thanks! Haven't had time to test more than the top one yet, but will be fun. Thank you!!

pastel moon
#

I have now tested a bit and can only get the first line to work. I get UndefinedError: 'mappingproxy object' has no attribute 'entity_id' when trying any of the other ones... I have tried all ways I can think of to break it down but can't seem to get it to work. I did google, but didn't give me a reason for the error (I could understand)

inner mesa
#

they all work for me

#

you pasted exactly that?

#

maybe you have scenes with no entities

pastel moon
#

I do believe you, and am very grateful you helped me with it. Yes, copy & pasted the exact lines

ivory delta
#

I like the |select('match', 'switch|light') smart2

inner mesa
#

I aim to please

pastel moon
#

I will try using another browser, haven't done that yet

inner mesa
#

another browser won't help. post what you're actually using

ivory delta
#

Can confirm Rob's template works. Even created my first ever scene just to test it.

pastel moon
inner mesa
#

I like the sum(start=[]) bit. that was new

ivory delta
#

Yeah, I wondered what that was at first glance. Nice that you can force it to do array concatenation instead of math 😄

#

Every time I think I'm getting good at templates, I see something new.

inner mesa
#

(found via Google search)

inner mesa
pastel moon
#

That's where I started. I get the same error there. That's when I tried to google it...

ivory delta
#

Oh... and match allows proper RegEx? I thought that was missing before?

inner mesa
#

I just copied exactly the script you provided and it worked out of teh box

#

yes, match does regex starting at the beginning and search looks for substrings anywhere

#

added earlier this year

ivory delta
#

Was about to ask why match wasn't letting me query the middle 😅

inner mesa
ivory delta
#

Now when people ask how to 'glob' stuff, I can give them this:
|select('search', '\.tv')

pastel moon
#

I'm stumped.

inner mesa
#

there's no reason that the first one would work and the rest wouldn't with that error

ivory delta
#

It's probably a typo somewhere. As much as I hate pictures of text... share a screenshot of the dev tools with that template and the rendered stuff on the right visible.

pastel moon
#

It throws the error when I add "Sum(start=[])"

ivory delta
#

Sum?

pastel moon
#

sum

ivory delta
#

Ok. Screenshot it please.

pastel moon
ivory delta
#

Make the whole template visible please, even if it means formatting it on multiple lines.

#

Just do a line break before each pipe

inner mesa
pastel moon
inner mesa
#

"limited templates", I think, only apply in triggers

ivory delta
#

I'm just thinking it's being used as a variable in a script... but it's showing the error in Dev Tools too, where full template features should work.

pastel moon
#

I run this on Firefox in Linux. Probably not it either, but something must differ

ivory delta
#

Templates are rendered by the backend.

inner mesa
#

put all the templates in there, starting with the first one

pastel moon
#

in dev tools?

ivory delta
#

It's like one or more of the scenes don't have entities. 🤔

inner mesa
#

right

#

that's what I'm thinking

ivory delta
#

Throw this in your Dev Tools too:
{{ expand(states.scene) | list }}
Let's see the full contents of your scenes.

inner mesa
pastel moon
#

I had an empty scenes.yaml earlier today, but is commented out. I am sure I have restarted since... 🤔 Will do it now just to make sure

ivory delta
#

Haha. I missed that 😄

inner mesa
#

although even that works for me

ivory delta
#

HA version different then?

inner mesa
#

it still has an entity_id: attribute

ivory delta
#

Works on 2021.8.3 for me.

pastel moon
pastel moon
inner mesa
pastel moon
#

A good mystery is always great, but no fun when it seems to work for everybody else...

ivory delta
#

Just upgraded to .8 here and still works.

pastel moon
#

I will try defining one, and one only scene and test with that. Something is not right, question is what. Thanks for the effort guys! I'll post back if I get anywhere

pastel moon
#

Made some progress. Turned out stale entries in the scenes list caused this error for me. Will enable the rest and hope it will continue to work

#

Finally... sigh, took a while to figure that one too. Now I will enjoy the nice pieces of code @inner mesa created earlier. 🙂

kindred tapir
#

is it possible to create a virtual switch that doesn't do anything itself but can be toggled on/off via service and used in automation conditions?

#

suppose an input boolean would work for this purpose

dreamy sinew
#

that is indeed the purpose of that integration

ember hamlet
edgy umbra
#

I'm using the template bellow to show the weather forecast condition (in a custom card...) but it shows the condition in english instead of dutch. In the default weather card it show the condition in dutch. Is there anything i can do or add to the template to show the condition also in dutch in my custom weather card.

#
              'temperature') }}°C <br/> Verwachting is {{
              states('sensor.openweathermap_forecast_condition') }}```
mighty ledge
edgy umbra
#

Any change to explain how to do that.

mighty ledge
#

If you didn't write the custom card, then there's nothing you can do

edgy umbra
#

Oh OK 🙂

#

Going to use another template and translate each condition, only thing i can think about it now that works;

mighty ledge
#

yep, that's about all you can do if the custom card doesn't support translations

#

you can always write up an issue against the custom card to let the dev know he's missing functionality

stark wolf
#

Alright y'all.....I am a total templating newb. Have read through the docs and just cannot figure out how to do a simple sum on two state values. Trying to add two wattage numbers and store that to a new value. Any help appreciated!

sensor.service_entrance_shelly_em_channel_1_power
sensor.service_entrance_shelly_em_channel_2_power

ivory delta
#

{{ state1 | float + state2 | float }}

stark wolf
#

| float converts it to an integer?

ivory delta
#

To a float (decimal). States are strings.

#

Or if you want to do multiple without it getting really long, use filters:
{{ [state1, state2, state3, ...] | float | sum }}

#

And to access the states themselves, sub in the usual function (states('sensor.some_sensor_name'))

stark wolf
#

Perfect. Thank you mono.

dreamy sinew
tawny parcel
ivory delta
#

That looks nothing like the format shown in the docs.

elfin briar
#

Hi everyone! I've made a template that works in the editor, how do I go ahead and make it a sensor in my HA?

#

Quite a rudimentary question, I know, I apologize

#

To my understanding, I just need this?

template:
  - sensor:
      - name: "name"
        state: "{{ code }}"

But it gets messy because I have many lines of code

dreamy sinew
#

state: >- for multi-line

elfin briar
#

and then just paste it all below?

dreamy sinew
#
state: >-
  {%- set foo = 'bar' -%}
  {{ foo }}
elfin briar
#

and then I get a sensor on restart?

dreamy sinew
#

assuming your template and formatting are valid

elfin briar
#

wow that's frickin cool

#

I will let you know in a moment

#

my config just had a stroke

kindred tapir
#

hmm, something strange going on with websocket api, I've subscribed to state changes and when I change the brightness of a light I'm seeing 3 messages through with the brightness level flipping around, first msg goes from 166 -> 87, then 87 165 then 165 -> 87

#

and it does that every time I change the brightness

#

in the end the last msg I recv is correct but sometimes there is a delay so I see my UI flipping around and being incorrect for a second or two

inner mesa
kindred tapir
#

oh I was in other, must have clicked templates at some point.. will move to devs

green lynx
#

hello can anyone help me out with templating?
{{ trigger.event.data.folder}}|regex_replace(find=media/,replace=media/local/,ignorecase=False){{ trigger.event.data.file }}
this is what i have but dont understand very well how to use them =/

inner mesa
#

{{ "/media/"|replace('media','media/local') ~ "file" }}

#

{{ trigger.event.data.folder|replace('media','media/local') ~ trigger.event.data.file }}

#

I don't know what you're doing exactly, but hopefully that points you in the right direction

#

The whole thing is a template, so you shouldn't be splitting it up like you did

#

make sense?

green lynx
#

Yes i see the issue now i will deploy it hopefully it works thank you!

inner mesa
#

the first one is an example that you can play with in devtools -> Templates based on what you're getting from the event

green lynx
#

Haa good idea i can test it there and not get my phone full of failed notifications ja!

green lynx
#

it is almost there but it is clipping the last subfolder i'm getting /media/local/**camerafolder**/**filename.mp4** but it is missing the subfolder of the date could it be because of the replace?

inner mesa
#

Run some tests in dev->template

green lynx
#

got it, just changed, event.data.folder for path and worked

#

now that i have the correct path, i'm getting a message saying failed to load attachment response status code was unacceptable: 404

sudden fractal
#

Is there a way to get a list of devices (or entities) within a given area using a template?

inner mesa
sudden fractal
#

nice!

#

I was taking a look at the source code as well, it looks like area_id is at least partially working in 2021.8.8. Though it looks like in some cases it's an id and some cases it's name.

arctic axle
#

Newbie here, just migrated from SmartThings. Installed button-card and have it working on PC using Vivaldi (chrome). When I open with Vivaldi on my mobile, the Dashboard shows 'custom element not found'. A thorough search turned up <null>

inner mesa
arctic axle
#

Hi Rob, sorry not sure how frontend can help make a custom element show up for a mobile device.

inner mesa
#

well, templates certainly can't 🙂

#

you're talking about the frontend of Home Assistant

#

right?

arctic axle
#

button-card was installed using HACS and is a lovelace custom element. Works fine to create custom button card to set icon, color, animation for device state. When I load the dashboard the card is on with a mobile device running Vivaldi browser, the card shows 'custom element not found'. Makes no sense as mobile is simply running HA through a browser so should work same way regardless of what device browser is running on. Retired IT/programmer so using code editor is a no brainer for me.

ivory delta
#

Makes no sense as mobile is simply running HA through a browser so should work same way regardless of what device browser is running on
Well, no... you're not running HA in any browser, you're accessing a frontend that's being served up (hence Rob pointing you to #frontend-archived ). Also, not all browsers are created equal, much to the chagrin of frontend developers the world over - so it's common for things to work in some and not others.

arctic axle
#

I selected Vivaldi (based on Chrome) because implementation across devices is supposed to be very close to the same. I have now tried running on all popular android browsers: Vivaldi, Chrome, Opera, Firefox and result is the same. The custom element is not getting accessed. It is referenced under Lovelace Dashboards/Resources.

#

Just tried opening another instance on a different tab on my desktop, logging in, and get the same error now. Not sure why it's working on instance where I installed the element but not on any new instance.

#

Issue resolved - had to reinstall button-card in HACS and it changed the resource URL in Lovelace. All working now.

ivory delta
arctic axle
#

After only a few hours of programming custom cards, not up to speed on things like frontend yet but will get there eventually.

lofty ferry
#

I am using the openweathermap integration which provides hourly forecasts and I would like to create a sensor which tells me if it will rain in the next 8 hours (first 8 objects of the forecast list) - how can I acheive this with a template?

#

Anyone have any examples of similar templates?

#

I can loop through the lists fine using this

#
{% for forecast in state_attr('weather.openweathermap', 'forecast') -%}

{%- endfor %}
#

and then forecast.precipitation will give me the number I want to check

inner mesa
#

{{ state_attr('weather.openweathermap', 'forecast')[:8]|selectattr('precipitation', ">", 0)|list|count > 0 }}

clever fable
#

Can anyone tell me how to create a template sensor that will act as a "delta" sensor. My goal is to create a sensor that can tell how much a temp sensor has changed in a given period of time.

ivory delta
#

Templates can't do that. They act on current values, not historic ones.

clever fable
#

Ok thanks

frank gale
#

Hello there!
I want to build a template to return the area_id of an entity. Is it possible?

frank gale
#

That's wonderful!
Thank you very much @fossil venture

#

Did you contributed in that?

fossil venture
#

Ha. No. You can thank raman325 for that addition.

weary pumice
#

Morning everyone, i need some help with a template sensor. I wanted to create battery monitoring for one of my temperature sensors, which have the battery status as an attribute, so i created the following sensor, which unfortunately is always "not available", although the sensor gets updated every 30 min... anybody can tell me why ? --> https://www.hastebin.com/ibihifiyul.yaml

#

Idea was to set the sensor to "not available" if nothing has been reported for 1 hour

fossil venture
#

What does this return in the template editor: {{ (as_timestamp(now())-as_timestamp(states.sensor.kuche_raumtemperatur_3_101.last_updated)) }}

weary pumice
#

Sorry should have mentioned that 😉 Of course i already checked, the value is (currentely) 390.46965289115906, and when i compare it to 3600 it evaluates to "Tru"

#

True

#

So the sensor should be available right?

sleek nova
#

I had issues recently using this way states.sensor.kuche_raumtemperatur_3_101.last_updated

weary pumice
#

Did you solve them somehow or give up;-)

sleek nova
#

I used nodered to solve it

carmine flower
#

Hi All, I am new to templates, any idea why I cannot see the below Item in my entities list?

#

sensor:

  • platform: template
    sensors:

    WLAN AP devices are connected to

    christiaan_ap:
    friendly_name: Christiaan AP

entity_id: binary_sensor.christiaan_ap

value_template: '{{states.device_tracker.christiaan_pixel_5.attributes.ap_mac}}'

  #wlan_ap_device_two:
  #  friendly_name: WLAN AP Device 2
    value_template:  >
      {{ {"12:34:56:78:90:ab": "EG", "12:34:56:78:90:cd": "OG", "12:34:56:78:90:ef": "DG"}[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] | default("N/A") }}
#

(dont know how to paste to hastebin) 😦

#

If I use the template editor I can correctly see the Result I need to see, But I cannot see this as an entity at all

inner mesa
#

don't know?

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

carmine flower
inner mesa
#

there's nothing there

carmine flower
carmine flower
inner mesa
#

it's confusing with the commented-out portions, but it looks like you have two value_template: keys

carmine flower
inner mesa
#

did you run the config check as shown above?

carmine flower
inner mesa
#

and restarted HA?

carmine flower
#

yes feels like 800 times nopw

#

*now

#

wait I ran the full check

#

at it picked up 2 sensor values in my yaml

inner mesa
#

do you see sensor.christiaan_ap in devtools -> States?

#

yeah, you can't do that

carmine flower
#

and all of the sudden it works. Thanks RobC

viscid panther
dreamy sinew
#

don't repeat the light key in your yaml

#

remove the ones from the bottom 2

#
light:
  - platform: group
    name: foo
  - platform: group
    name: foo2
viscid panther
#

That worked perfectly. Thank you. 🖖

unique elm
#

how do you query the value of a number entity rather than a sensor object e.g. I have number.evnex_maximum_current and want to return the value in that entity as part of a template. Do I still use
{{ states('number.evnex_maximum_current')|int)}}?

inner mesa
#

yes, it's just an entity with a state

unique elm
#

@inner mesa Are you in every group 🙂

weary pumice
fossil venture
#

Only around single line templates, and if you do use single line templates make sure the quotes outside the template are different from those inside the template. So like one of these two options: https://www.hastebin.com/equmufitib.yaml

spring blade
#

Hi all template noob here. I am trying to extract key value pairs from a long, nested json string from my solar inverter which I want to push into HA entities.The string is here https://pastebin.com/TJnxHU19 Using the template Developer Tool but not getting past this

{% for key, value in data1.items() %}
{{ data1[key].item }}
{% endfor %}

Result type: string

This template does not listen for any events and will not update automatically.

silent barnBOT
spring blade
#

{% for key, value in data1.items() %}
{{ data1[value].item }}
{% endfor %}
Returns the whole string with error UndefinedError: dict object has no element.

carmine flower
#

Hi Guys, Any Idea why I am getting a TemplateSyntaxError: expected token 'name', got '{' error on the following code?

#

{{ {"74:83:c2:26:75:15": "Office Sales", "e0:63:da:1d:bd:b0": "Back Garden", "78:8a:20:b0:76:81": "Bar", "f0:9f:c2:d6:51:a9": "Home", "fc:ec:da:f3:dd:d3": "Office Tech"}[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] | {"N/A": "N/A", "Unavailable": "N/A"}[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] }}

#

I am testing with the server:8123/developer-tools/template tool

mighty ledge
mighty ledge
ivory delta
#

I don't think the syntax you're trying works. You'll have to split it out like so:

{{ json[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] }}```
#

You're trying to get a value from a dictionary by key name, but you can't just string that syntax on the back of the JSON itself.

mighty ledge
#

the error name but getting { is a specific error related to malformatted yaml.

carmine flower
# mighty ledge You'll need to provide more information, like the configuration of the template,...

No Problem Petro, I have the template defined as such in the configuration.yaml https://www.codepile.net/pile/QlXBqBWw and the state of the attributes.ap_mac is responding with the MAC of the AP it is connected to. Just that sometimes the entity is no longer on the network (becoming "Unavailable" or "N/A" if i take a look at the raw json) So I wanted to transform the template to show N/A for both those scenarios. (I would have used a OR statement on the Condition but I see that is not available)

mighty ledge
#

use the word or

#

| is for filters in jinja, not or

#

your yaml looks fine, so not sure why you're getting 'name', i would assume that error is unrelated to your template.

#

your template should be:

#
{{ {"74:83:c2:26:75:15": "Office Sales", "e0:63:da:1d:bd:b0": "Back Garden", "78:8a:20:b0:76:81": "Bar", "f0:9f:c2:d6:51:a9": "Home", "fc:ec:da:f3:dd:d3": "Office Tech", "Unavailable":"N/A"}.get(state_attr('device_tracker.christiaan_pixel_5','ap_mac'), 'N\A') }}
carmine flower
mighty ledge
#

use what you learn there to access the items that you want.

#

you're data has a combination of lists and dictionaries at each item

#

that last one has a ton of info

spring blade
#

I will be doing some reading up on the links to get my head right with his stuff.

mighty ledge
#

the for loop is iterating through all key value pairs in the top level dictionary. It happens to have 3 key value pairs

spring blade
#

Ok got it. This works {{ data1['data'][0]['dataDict'][8].value }} and is more in line with your last link. When I had tried this before it was without the [0] . Thanks again. Great work.

frank gale
#

Hey! I want an action to trigger after every change on a template (every time the result from the template changes), any smart thought?

#

Every time that changes:
´ {{ states.binary_sensor
| selectattr('state','eq','on')
| selectattr('attributes.device_class','eq','motion')
| rejectattr('entity_id','in',['binary_sensor.yi_movement'])
| map(attribute='entity_id')
| list
| count}}´

dreamy sinew
#

make a template sensor

#

make an automation based on that sensor

frank gale
#

I think I got it... I have already another template sensor that contains something that should contain this other sensor... so I check if the first one is in the second...
Let's see 😉

sonic nimbus
#

hello, in #analytics-archived I asked why my grafana shows for some temperature sensors up-to-time values, and for others dont.

#

basically, if temperature is the same, then it has no additional information from the sensor

#

so basically I want to add horizontal line to my graphs using templates

#

this is the example, can it be done in such manner, when I dont receive any data from my sensor for example 10min, to update value to itself (same value), just to have up-to-time graphs?

ivory delta
#

You wouldn't use templates for that.

#

Templates know what is, they don't guess what should be.

#

You need to fix the issue via integrations.

dreamy sinew
#

Wonder if you could cheese it by subscribing to time.

{{ states('sensor.my_sensor') if n else 0 }}```
#

That'll update it every minute regardless

ivory delta
#

That's beautiful and disgusting at the same time.

sonic nimbus
dreamy sinew
#

no, make a template sensor

#

it'll log the state of the original every minute and whenever the original changes

#

so you'll have updates every minute at the least

edgy umbra
#

Is there a way to add a template to a custom: button-card state to use another entity_picture between certain hours?

#
              - value: mostlycloudy
                entity_picture: /local/weather/cloudy.png
                color: '#B6B6B6' ```
#

This is the one I use now but the problem is that I have two different icons for partly cloudy day and night.

inner mesa
#

It’s JavaScript within the template, so presumably yes

edgy umbra
#

I’m far from good with this so is there any change you can show how to accomplish this.

ivory delta
#

You should at least try it before asking others to do it all for you.

inner mesa
#

There are hits on StackOverflow

ivory delta
#

This is also a #frontend-archived topic, since cards and JS have nothing to do with Jinja templates.

edgy umbra
#

Thanks mono, and I don’t want to be lazy but I have just no idea how to start. 😉

inner mesa
#

A journey of 1000 miles starts with a Google search

ivory delta
#

Well you know how to show one picture. Now you Google how to do a condition in JavaScript... and continue the conversation in #frontend-archived if necessary (after trying for yourself).

#

I didn't know how to do any of this until I Googled stuff. Same goes for my day job as a software engineer... that started with Googling too (and hasn't really stopped if I'm honest).

wide gorge
#

i always wonder how my work would look like without google

mighty ledge
#

Unproductive

#

Or you’d buy books

distant plover
#

I have the following template sensor: value_template: "{{ ((states('sensor.nordpool_kwh_blabla') | float) + (states('input_number.addcost) | float) /100) }}". In Lovelace the history is just a bunch of colors. How do I get a nice graph instead when clicking on the entity? EDIT: Nevermind. Just needed a unit_of_measurement.

floral shuttle
#

re-directed from #beta #beta message I've been looking for a way to template and use the Areas of our devices/entities. Haven't found it though, so please have a look if you can help me out with eg 'All "on" switches in Area Living room'. Only thing with Areas right now I get working in templates is the new {{area_name(trigger.entity_id)}} but not the other way around state_attr('binary_sensor.front_room_sensor_motion','area_name')}} because area is no part of the state.

#

or a notification like: 'Can not turn on Alarm, because Area Livingroom still has 3 switches on (switch x1, switch x2 and switch x3').

ivory delta
#

area_name?

#

I don't see that in the docs and it doesn't work on 2021.8

#

Oh, you're asking how to use #beta stuff in the main support channels... yeah, nope.

#

From the looks of the conversation, that isn't even going to make it into 2021.9, so come back and ask in October.

inner mesa
#

that's a new PR that was still open the last time I looked

ivory delta
#

Until that gets merged and released, the next best thing is to customise your entities with attributes that denote the 'area' they're in, and use that attribute in templates instead.

#

More work, but I haven't seen a better workaround.

#

Another alternative would be to name all your entities so they can be searched via RegEx for a room/area.

#

But yeah, no support for unreleased / #beta features in here.

frank gale
frank gale
inner mesa
#

he wants a list of entities in that area, which is only available via a PR that's still open and not included in 2021.9

frank gale
#

Yes, you're right he did wrote that 😛

ivory delta
#

Thanks for the tag, but I'm aware what he was asking 😉

ivory delta
marble jackal
#

Isn't it possible to create a for loop and check the area for each entity and put them in a list if they match the area you need?

dreamy sinew
#

would be pretty clunky

inner mesa
#

probably

#

I tend to lose interest as soon as I can't solve a problem with a clever set of filters 🙂

#

once it goes to a for loop, I look for a different problem to solve

dreamy sinew
#

{{ states.sensor|map(attribute='entity_id')|map('area_name')|reject('eq', None)|list }}

#

good news, area_name is a filter

inner mesa
#

ohai

#

I played with it but didn't come up with that particular incantation

dreamy sinew
#

doesn't answer the question though

inner mesa
#

right, you lose the object and can't select based on the state or get back to the entities

dreamy sinew
#

have to do all of your state filtering before-hand

#

could make it generic instead of counts

#
{{ "Unable to comply. {} {} entities active".format(', '.join(areas), 'have' if areas|length > 1 else 'has') if areas|length > 0 else "ok" }}```
inner mesa
#

still, the goal was to end up with a list of entities to turn off, and I still can't work out how one might do that

jagged obsidian
#

i really need to learn to use the map filter

dreamy sinew
#

map is amazing

jagged obsidian
#

i notice from all your examples

dreamy sinew
#

that above example has both uses of that filter. You can either select an attribute to use (supports dot walking) or you can apply a filter against all items

#

actually, this could work. you can call homeassistant.turn_off with an area_id

inner mesa
#

yeah, I mentioned that. he wants to only target the ones that are on for some reason

#

that's where this started

dreamy sinew
#
service: homeassistant.turn_off
target:
  area_id: >-
    {{ states.binary_sensor|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|map('area_id')|reject('eq', None)|unique|list }}
#

but i don't think we can get to the state of the area itself

#

since i don't think it has one

dreamy sinew
#

ah

#

then use a group

#

and the state of that group

#

i still haven't found a good use of areas

#

could probably just call light.turn_off and switch.turn_off with that same template for area_id

#

assuming that field accepts templates

floral shuttle
#

hi, back again... thanks for all the efforts. we must conclude what I hoped that would be possible, and shouldnt be too odd to want, simply isn't available yet. Ive explored what phnx tries to do, but they are all workarounds really. And, for now, don't get where we want the (use of) Areas to take us.

ivory delta
#

So try again in October.

floral shuttle
#

a group as substitute for Area, or as Mono suggested, add a customized attribute for zone (which indeed would be the best option currently) are both substitutes for whats to come in 2021.10 hopefully..

ivory delta
#

This is what I do for things in a room:

{{ states | selectattr('attributes.room', 'equalto', 'study') | map(attribute='entity_id') | list }}```
#

At least it lets you filter before you map.

floral shuttle
#

yep, thats what I meant above, thanks

#

still dont see the obvious I was steered at in #beta though...

ivory delta
#

I think they were just kicking you out because it's not related to this beta. It'll be in the next one.

floral shuttle
#

no, they wouldnt.... 😉

ivory delta
#

I guess you can extend my template if you're doing it in automations:
{{ states | selectattr('attributes.room', 'equalto', trigger.entity_id.attributes.room) | map(attribute='entity_id') | list }}

#

But then you'd have to double up on attributes and areas 🤦‍♂️

#

Meh. Lemme edit...

#

I've probably mucked that up but you get the idea.

floral shuttle
#

exactly, doing it right now, is a mess... but yes, I get it, been customizing against better judgement of certain dev's for 4 years now, getting where HA wont go..

floral shuttle
violet flower
#

im trying to print out the duration that a job ran using a custom template.
This is what I have so far

{% set secs = (trigger.to_state.last_changed - trigger.from_state.last_changed) -%}
{% set days = secs//8640 -%}
{% set hours = (secs - days*86400)//3600 -%}
{% set minutes = (secs - days*86400 - hours*3600)//60 -%}
Job ran for {{hours | int}} hours {{minutes | int}} minutes

It feels a bit verbose, is there a more concise way of doing it?

inner mesa
#

{{ relative_time(states.switch.fr_table_lamp.last_changed) }} -> 30 minutes

unique elm
#

Hi everyone, simple question this time. I just want to transfer the value I have calculated (stored in sensor.calculated_sp) into an existing entity (number.evnex_maximum_current). But all templates seem to be about creating a new entity, here I don't need a new entity, I just want to copy values between existing entities. How do I do this please

violet flower
ivory delta
unique elm
#

How often does the automation do this? Just once? Or do I need to set an automation that repeats every minute to update the result of the calculation?

ivory delta
#

That depends what you're actually trying to achieve 🤷‍♂️

unique elm
#

The updated available power from my solar arrives every minute (from SolaX) I understand in templates that the calculation gets re-triggered when an input variable changes so this updates once per minute. I then want the available power, divided by 230 volts, to be added to the current power limit to my EV. I have this calculation working thanks to @inner mesa

#

So really it is every minute

ivory delta
#

I don't understand where the copying comes in.

unique elm
#

My OCCP based EV charger allows me to write to its internal hardware to set the charge limit to the car. That is a pre-created entity called number.evnex_maximum_current So I need to send the value of my calculation to this entity

ivory delta
unique elm
#

And I can set the automation to run every minute?

ivory delta
unique elm
#
  trigger:
  - platform: time_pattern
    minutes: '/1'
```?
ivory delta
unique elm
#

OK but I was thinking this could be done in a template which is why I started here. I am trying to follow the rules 🙂

ivory delta
#

It's not a template. It's an automation. I thought I'd made that clear already (several times).

#

👋

unique elm
#

Yes you have

fringe temple
#

group lights YAML

unique elm
#

I have installed the new core-2021.9.0 as it better supports the energy page and has new templates. I wanted to create a new number entity. However, even following the guide, I am struggling.

sensor:
  - platform : template
    number:
      - name: "Test for car"
        min: 0
        max: 32
        step: 1```
#

I skipped state and set_value as I don't need them at this stage. First, why does the entity not have a name? The name field looks more like a 'nice name'

#

second, this passes configuration check but fails on restart

inner mesa
#

your space is not in the right place, to start

#

and you have number: under sensor?

#

it's wrong

#

it doesn't follow what was in the blog post

unique elm
#

Where else do you put any entity?

mighty ledge
#

Wrong integration

inner mesa
#
number:
  - name: "test_number"
    state: "{{ states('input_number.test') }}"
    min: 0
    max: 100
    step: 1
    set_value:
      service: input_number.set_value
      target:
        entity_id: input_number.test
      data:
        value: "{{ value }}"
#

under template:

unique elm
#

In configuration.yaml

mighty ledge
#

You’re mixing the old configuration and the new style

inner mesa
mighty ledge
#

You can only use the new style. I.e. platform:template is not the new style

unique elm
#

OK, I actually started with that example page...but it got rejected by configuration check, will try again

mighty ledge
#

Put it under template section with a - in front of number

inner mesa
#

I have template: !include templates.yaml in configuration.yaml, and exactly the content above in templates.yaml

#

I threw it together to test your last issue 🙂

unique elm
#

OK, I assume the input_number.set_value entity is something you also created under sensors, but I will not need, right?

#

I could just create: template: number: - name: "test_number" min: 0 max: 32 step: 1

#

and then I have a variable I can use in my testing

#

Invalid config
The following integrations and platforms could not be set up:

template
Please check your config and logs.

mighty ledge
#

You need the - before number like I said

inner mesa
#

I don't think so

unique elm
#

I tried exactly RobC code and it was accepted and worked

#

it has no - in front of number

#

It does however have a 'state' line

#

can I just use state: {{}}

inner mesa
#

that's not a very interesting entity

unique elm
#

Its a dummy variable I can then use in automations

inner mesa
#

that's an input_number

unique elm
#

So I can use to test the automation that is currently failing

mighty ledge
#

Not sure why without the dash is working

#

It follows the same config as trigger

#

Which requires the dash

unique elm
#

it has to be 'number' in the automation as eventually it writes to a number entity created by OCCP

inner mesa
#

the blog post shows both number: and select: without it

#

a dict vs. a list, in other words

mighty ledge
#

Yes but the whole template section is a list

#

You can’t mix and match

#

It’s a list or a dict

inner mesa
#

I agree that the template sensor docs all show the sensors as a list

unique elm
#

If I remove the 'set value' section it fails to load. Same error message as above

#

All I am really after is a number entity I can write to

inner mesa
#

like I said, input_number

#

those already exist

#

you're trying to use the wrong tool for the job

unique elm
#

Does this mean that the occp writers, who have created a number entity, one that needs to be written to or used with a slider, should have created an input_number entity, noting of course that this is a value they read and write to/from inside the EV Charger?

inner mesa
mighty ledge
#

That would be my guess

inner mesa
mighty ledge
#

It doesn’t make sense otherwise

unique elm
#

In dev tools templates I now have:```
sequence:

  • service: number.set_value
    target:
    entity_id: number.evnex_maximum_current
    data:
    value: "{{ states('sensor.pv_to_car')|int }}"```
mighty ledge
#

Cause it can’t be both a dict and a list, and I 100% treat my config as a list for templates

#

Unless number and select are outside the template section

unique elm
#

This has '19' as the value for data, which is correct, but number.evnex_maximum_current is still reading 32. Do I have to reload this template or in some way restart it?

inner mesa
#

that's up to the integration

mighty ledge
#

So why aren’t you using input_number?

inner mesa
#

saw something shiny and new in the blog 🙂

mighty ledge
#

Ah

inner mesa
#

actually, I think the number entity there is exposed by the integration, as I mentioned above

mighty ledge
#

Well, you can use trigger with number

inner mesa
#

yeah, we went over that earlier

unique elm
#

so why is the sequence I pasted above not writing to the number entity?

inner mesa
#

the integration doesn't like what you're providing, or has an issue

#

it's coming from the integration, right? check your logs

#

where did that number entity come from?

mighty ledge
#

Template that he just made.

unique elm
#

Nope, it can from the OCCP integration

mighty ledge
#

It’s not going to update because the set value doesn’t have a service and the service doesn’t impact the state of the number

inner mesa
#

so check your logs, then, and then docs for the integration

mighty ledge
#

Well disregard my comment then, was based on it being a template number

#

What’s occp, doesn’t come up in the docs, custom?

unique elm
#

I can display this number.evnex_maximum_current on a page, it always shows with a slider. I can drag the slider and the EV charger responds, I can see it reducing its output power to match. I can type into the entity from dev_tools, also works

#

OCCP is a HACS integration

inner mesa
#

have you checked the logs?

mighty ledge
#

You’d have to see if it supports set_value

#

Ocpp you mean

unique elm
#

so being able to write to it and use a slider does not mean I cand set_value?

#

Yes, I turned Russian there for a second, its OCPP

inner mesa
#
    async def async_set_value(self, value):
        """Set new value."""
        num_value = float(value)

        if num_value < self._minimum or num_value > self._maximum:
            raise vol.Invalid(
                f"Invalid value for {self.entity_id}: {value} (range {self._minimum} - {self._maximum})"
            )

#

so...check your logs

unique elm
#

Two warnings in logs, both about set last_reset being deprecated

mighty ledge
#

It supports it, just checked code

inner mesa
#

it's up there

unique elm
#

I also set " custom_components.ocpp: debug" under logger in configuration.yam;

#

so nothing in the logs

inner mesa
unique elm
#

I can see my code running in dev tools templates. Every minute or so the 'value' changes to 17 or 18 or 19 based on my solar cells. But nothing is going into number.evnex_maximum_current

mighty ledge
#

There’s no messages in the function that log anything so the logs will be useless

inner mesa
#

replace the template with 5 and see what happens

#

or 42, or some sane value

unique elm
#

Yes, it was a string last time because the entity did not even exist. Its only created when the EV charger cycles up, which only happens when a car is plugged in that needs charging

inner mesa
#

ok, but I think you're still claiming that you can set it in dev tools, but not in the automation

mighty ledge
#

Setting things in dev tools is not the same

unique elm
#

no, when it did not exist it said 'unknown' in dev tools

#

of course it existed as an entity, since entities never die, you have to delete them

#

ooohh, I put 5 as the value instead of the number.evnex_maximum_current and now I have a message that says "This template does not listen for any events and will not update automatically"

#

so how do I get the sequence to run every time sensor.pv_to_car changes?

inner mesa
#

not what I meant

#
sequence:
  - service: number.set_value
    target:
      entity_id: number.evnex_maximum_current
    data:
      value: 5
unique elm
#

That is exactly what I have

inner mesa
#

I put 5 as the value instead of the number.evnex_maximum_current

#

that's not how I read that, but ok

#

anyway, does that set the number to 5? feel free to pick a better number

unique elm
#

no

inner mesa
#

alright, you clearly have a mystery to solve

#

probably better taken up with the author of that integration

unique elm
#

I was thinking, this is a value both read from and written to OCPP. Does that make trouble? for example does HA see that the value it has in HA is not the same as OCPP so overwites it?

#

Though under that basis you could never write to a read/write register in any external device...

inner mesa
#

that, also, is a question for the author of that integration

unique elm
#

Luckily I know the author who put in the EVNEX charger personally

inner mesa
#

go buy them a beer

unique elm
#

👍

inner mesa
#

I have nothing that exposes a number entity, and the one that I created as per the blog post works fine for reading and writing

unique elm
#

the key is "AttributeError: 'Number' object has no attribute 'min_value'"

#

This is what number.evnex_maximum_current does have: initial: 32 editable: true min: 0 max: 32 step: 1 mode: slider unit_of_measurement: A friendly_name: evnex.Maximum_Current icon: mdi:ev-station

inner mesa
#

When you talk to the dev, tell them that this seems to be wrong: class Number(InputNumber):

unique elm
#

OK, have done so and also put it on the issues list on github

floral shuttle
# dreamy sinew ```yaml service: homeassistant.turn_off target: area_id: >- {{ states.bina...

getting back to this: {{ states.binary_sensor|selectattr('state', 'eq', 'off') |map(attribute='entity_id')|map('area_id')|reject('eq', None)|unique|list }} please educate me on what I am seeing being returned: [ "51721157e7d0491abbffa49c9b069e7e", "df21e517d2624b49a682041fe632cddc", "b36ceff2389e4b189f528ede60ad291f", "c52f1c47fd9111eaa95e2bc99216c855", "stookhok" ] seems to be a list of area_id's, of which only one has been named by me, and the others are system generated?

#

do all devices have a system generated area_id until the user sets one? and, for the template at hand, can we filter out those?

#

wait... I discovered core.area_registry and the above numbers are id's for user set Area's. changing the template to ```{{ states.binary_sensor|selectattr('state', 'eq', 'off')|map(attribute='entity_id')|map('area_name')|reject('eq', None)|unique|list }}

#

but now the question is why do a few of the area's have name/id sets like: { "name": "Garden terrace", "id": "garden_terrace" }, { "name": "Garden backyard", "id": "garden_backyard" }, where others are system generated like: { "name": "Corridor", "id": "3b2a49ef6eef476ab8873510626542ac" }, { "name": "Dining room", "id": "93c3a87cc88945cdbdc859fc2495804f" },

floral shuttle
#

listing all available areas: {{ states |map(attribute='entity_id')|map('area_name')|reject('eq', None)|unique|list }} 😉

#

no way to template that directly? but this is a small enough hack..

mighty ledge
floral shuttle
#

well, a workaround then. opposed to using something like {{areas|list}} if areas would have been available directly, we now have to go via the entities that have an Area set

marble jackal
ivory delta
floral shuttle
floral shuttle
mighty ledge
#

if it's old vrs new, then it's 'very old vs new'. I created my areas in january and they all have area_id's that match area_name, but lowercase and using underscore

floral shuttle
mighty ledge
#

i'm not sure why that's a question though

#

who cares about the id

#

it's an identifier

#

it's meant for code

#

not for humans

floral shuttle
#

because it was suggested in a template yesterday, I started having a look to study that. And when noticed, tried to understand and make sense of it

mighty ledge
#

what were you going to use the area_id for if it was suggested to use it?

floral shuttle
mighty ledge
#

ok, and that would work, so what's all the fuss about the output?

floral shuttle
floral shuttle
#

Mono's suggestions comes closest, to add an attribute as customization with an area name and template on that attribute

mighty ledge
#

how so, that service will turn off all devices in that area id that are on

#

unless the intention is to only target specific entity types

ivory delta
#

All devices, not just devices of a certain domain.

floral shuttle
#

My goal was to turn off switches in let's say area 'Living room'. (remember we hadn't noticed the slugified id's yet, only working with the system generated)

mighty ledge
#

use namespace and you can get the list now

floral shuttle
#

was trying this:```{{ states.switch|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|map('area_id')|select('eq', 'Living')|list }}

mighty ledge
#
{% set ns = namespace(entities=[]) %}
{% for s in states.switch | selectattr('state','eq','on') %}
  {% if area_name(s.entity_id) == 'Living Room' %}
    {% set ns.entities = ns.entities + [ s.entity_id ] %}
  {% endif %}
{% endfor %}
{{ ns.entities }}
#

using map will not work because it changes the object to the mapped value.

#

after area_entities is added...

{{ states.switch | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
#

just as ugly.

#

so, it's not like it'll be any better

#

or

floral shuttle
#

thanks Petro, appreciated. Your template doenst work though, [] result

strange geode
#

Ive got a rest sensor that give me some data,
But in the json attributes is shows text like <br> </>

  • how can i excludes that in my sensor text ??
mighty ledge
#

more efficient

{{ expand(area_entities('Living Room')) | selectattr('domain','eq','switch') | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
mighty ledge
floral shuttle
#

namespace template gives me an empty list. 2021.9

mighty ledge
#

then you're using the wrong area name or state

strange geode
#

Value from json file: "description": "HERE THE INPUT TESXT <br /> <br />WILL BE SHOWN.",

  • platform: template
    sensors:
    sensor:
    friendly_name_template: "Sensor name"
    value_template: >
    {{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description + ' / ' + state_attr("sensor.sensor","properties").lastModified }}

In the .description it shows <br /> <br />
i want to exclued that letter in the sensor so it wont show <br /> <br />

mighty ledge
#

@strange geode that's html

#

are you sure that should be a rest sensor?

strange geode
#
  • platform: rest
    name: Sensor name
    json_attributes_path: "$.features[0]"
    json_attributes:
#

This is my rest sensor that creates info...

  • from that i use a template sensor like the first i wrote...
#

Value from my rest sensor is: "description": "HERE THE INPUT TESXT <br /> <br />WILL BE SHOWN.",

  • But in this i would like to hide : <br /> <br />

in this value_template
{{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description + ' / ' + state_attr("sensor.sensor","properties").lastModified }}

mighty ledge
#

then just use .replace('<br /> <br />', '')

floral shuttle
mighty ledge
#

works fine for me

strange geode
mighty ledge
#

yep, but without the space between n and .

strange geode
#

Okay so like this, sorry havent tried it before 😛
{{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description.replace('<br /> <br />', '') + ' / ' + state_attr("sensor.sensor","properties").lastModified }}

mighty ledge
#

just test it in the template tester

strange geode
#

Just did and it work thank u!

Is it possible to set Title name from a sensor with notify?

kindred arrow
#

Hey guys, I need your help, I wish to make something like this, like putting another layout of logical operator in parentheses
{% if is_state('sun.sun' ,'below_horizon') and {if is_state('light.allhome' ,'on') or (not if is_state('input_select.maeva_home' ,'Inside') and is_state('input_select.tom_home' ,'Inside'))) %}
Simplier:
{.. and (.. and ..)
how can I?

mighty ledge
kindred arrow
#

Arg, i might did a mistake then, thank youu, I'll come back later when I'll find it

mighty ledge
#

You used if twice for some reason

kindred arrow
mighty ledge
#

If ( … and ( … and … )

kindred arrow
#

That was simple as that 😮‍💨

stable wagon
#

Hi Guys, can somebody help me? I'm trying to write a template sensor, which shows the "Grid-uptake" of power. So I wanted the sensor to subtract the energy produced with the solar panels from the total energy consumption of the house.

This is what I tried:
value_template: >- {% set verbrauch = states.sensor.stromverbrauch_haus_gesamt_geglattet_taglich|float %} {% set produktion = states.sensor.stromproduktion_photovoltaik_taglich|float %} {{ (verbrauch - produktion)|round(1) }}

#

But I get always zero

dreamy sinew
#

because you are casting the object to a float which will always be 0

#

use states('sensor.whatever')|float

stable wagon
#

thank you so much !! I'll try this

#

It works! I don't fully understand why, but it does 🙂

dreamy sinew
#

states.domain.entity is the entity object, not a state

#

NaN|float will always -> 0.0

inner mesa
stable wagon
#

Thanks a lot. will study this. One more:
`type: entity
entity: sensor.total_energy_uptake_grid
style: |

  • {
    --primary-text-color:
    {% if states("sensor.total_energy_uptake_grid")|float > 0 }
    Green;
    {% else %}
    OrangeRed;
    {% endif %};
    }`
    Did I miss something. Want a green value if the value of the sensor is positive
mighty ledge
#

too may ;

#

that question doesn't make sense

#

templates update themselves

#

templates do not know state history

#

you'll need an input number and you'll have to store the lowest number in that input number for it to persist alltime, so this would be an automation

stable wagon
#

okay thats right, deleted a few ; 🙂
`type: entity
entity: sensor.total_energy_uptake_grid
style: |

  • {
    --primary-text-color:
    {% if states("sensor.total_energy_uptake_grid")|float > 0 }
    Green
    {% else %}
    OrangeRed
    {% endif %};
    }`
#

Is it possible, that my condition is wrong

thorny snow
#

How can i get the maximum value of a sensor alltime?

#

so no max_age

ivory delta
#

Not with a template. They're based on current values only.

#

Integrations have access to historic data.

thorny snow
silent barnBOT
#

@primal canyon When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

ivory delta
#

And no, that sounds silly. You'd use either an automation or an integration to achieve that.

inner mesa
#

Whenever the trigger fires, all related entities will re-render and it will have access to the trigger data in the templates.

#

a trigger-based template sensor could probably do it

ivory delta
#

Or a utility meter or SQL sensor 🤷‍♂️

nocturne chasm
#

Does this look correct?

{{ ((trigger.event.data.type == 6 ) and ( trigger.event.data.event == 6 ) and ( trigger.event.data.event_label == 'Keypad unlock operation') and ( trigger.event.data.parameters.userId == [1, 2, 3, 4, 5] )) }}
ivory delta
#

It looks well-formed if that's what you're asking.

#

No need for the outer parentheses though. The ands will work without the whole statement being wrapped.

#

You could probably get rid of all of the parentheses if you wanted, since equality is going to be checked first.

nocturne chasm
#

Thanks….I struggle with setting variables in the template manager…knowing it is close will get me started.

mighty ledge
#

Don't do that again. Thanks.

mortal ruin
#

Could someone help me figure out why my sensor isn't picking up a state?

#

I think my template is setup wrong

#
  • trigger:
    sensor:
    • name: "Tariff Price"
      unit_of_measurement: USD
      state: >
      {% if is_state('utility_meter.monthly_energy', 'peak') %}
      {{ 0.11951 }}
      {% elif is_state('utility_meter.monthly_energy', 'offpeak') %}
      {{ 0.11229 }}
      {% endif %}
#

I'm referencing it using the following line in my config file

#

template: !include templates.yaml

#

the sensor shows up as an entity in developer tools

#

but the state isn't populating.

#

utility_meter.monthly_energy says offpeak

#

so that's working.

inner mesa
#

please format your code

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

inner mesa
#

it looks like you have a trigger: with no actual trigger

#

and that means that it will never update

mortal ruin
#

that would make sense.

#

I was just following a video

inner mesa
#

that's the kiss of death

mortal ruin
#

but he didn't have that either. 😕

inner mesa
#

following the docs > following some rando video

#

Trigger-based entities do not automatically update when states referenced in the templates change. This functionality can be added back by defining a state trigger for each entity that you want to trigger updates.

mortal ruin
#

So it sounds like I just need to get rid of the trigger

inner mesa
#

remove that line

#

and put a "-" on the sensor: line

mortal ruin
#

That fixed it

#

thank you so much!

#

well, the price still isn't showing up in my energy dashboard, but now at least the sensor.tariff_price is populating correctly.

river blade
#

Hi. I have a template like this

- platform: template
  sensors:
    tesla_charing_at_home:
      value_template: >
        {% if is_state('device_tracker.tesla_location', 'home') %}
        {{ (states('sensor.tesla_charger_power') | float)}}
        {% else %}
        {% endif %}

But the corresponding sensor is a state sensor not with values like it should. How could i fix this?

#

I like to fill the sensor.tesla_charging_at_home if the car location is at 'home' from the sensor.tesla_charger_power sensor.

inner mesa
#

You can’t just have an empty else like that

#

Please rephrase your first sentence? It doesn’t make sense

river blade
#

Ok, with the else i can fix.

#

The "tesla.charging_at_home" sensor contains in the frontend just the state like on/off not the value with an graph.

#

I cannot upload an image to visualize this.

inner mesa
#

it sounds like you put that under binary_sensor: instead of sensor:

river blade
#

It sounds, bit it is not. Its in the same folder like my other energy sensors i crated from plugs or other hardware.

#

Is something like that possible to do? Maybe HA is not captable to fill a sensor with a sensor value.

inner mesa
#

what is the entity_id?

#

is it really sensor.tesla_charging_at_home?

river blade
#

you mean in the frontend?

inner mesa
#

are you really getting on/off, or something else?

#

if you're getting values and they're just not displayed in a graph, then you need to add a unit_of_measurement

river blade
river blade
#

Also tried this.

inner mesa
#

you need to let the old data flush out, or purge that entity

river blade
#

Oh sorry. tried device_class

#

Just as sec.

inner mesa
#

unit_of_measurement string (optional, default: None)
Defines the units of measurement of the sensor, if any. This will also influence the graphical presentation in the history visualization as a continuous value. Sensors with missing unit_of_measurement are showing as discrete values.

river blade
#

Thx. the unit_of_measurement did the trick!

small hazel
inner mesa
#

What does?

ivory delta
#

It does

inner mesa
#

I hate that thing. It’s always so vague

ivory delta
small hazel
#

any idea of those which is most appropriate for a gas meter?

ivory delta
#

🤷‍♂️

#

What are you trying to do?

small hazel
#

I have an RTL-SDR that reads my power and gas meters to mqtt topics of readings/$DEVICEID/meter_reading and I'm trying to get those values into HA as sensors with the appropriate unit of measurement

#

maybe just leave it blank?

ivory delta
#

You've described what you've already done, not what you're trying to do next.

small hazel
#

probably so, I started out in here because I needed to convert the number to a different value using templates, but I'm pretty sure I figured that out with just a / 100

stable wagon
#

guys, just a quick question:
i want a template to report true if a entity value is >0. Is this condition right:?
{% if states("sensor.total_energy_uptake_grid")|float > 0 }

ivory delta
#

Close... your braces are wrong.

#

You want {{ }} around it.

charred dagger
#

No. For an if block you want {% %}

#

With the % it should be correct

ivory delta
#

I think they just want the test...

#

to report true if a entity value is >0

inner mesa
#

‘Report’ would imply removing the if and using {{ }}

charred dagger
#

Oh, right. Sorry. You're right.

ivory delta
#

It happens occasionally 😅

charred dagger
#

Do that instead

stable wagon
#

thank you the 2nd percentage char did the job!

ivory delta
#

I don't think it did...

stable wagon
#

it is an if clause for a custom format of the value in lovelace

#

value should be formatted green if greater than zero and red if less 🙂

charred dagger
#

So a bit of term confusion then. Glad things worked out.

stable wagon
#

Of course 🙂 I'm a newbie ^^

charred dagger
#

we all are...

nocturne chasm
#

Ok, what am I doing wrong?

{% set trigger = {
   "event.data.type": 6,
   "event.data.event": 6,
   "event.data.event_label":"Keypad unlock operation",
   "event.data.parameters.userId": 1
  }
%}

{{ (trigger.event.data.type == 6 ) and ( trigger.event.data.event == 6 ) and ( trigger.event.data.event_label == 'Keypad unlock operation') and ( trigger.event.data.parameters.userId == 1 ) }}
ivory delta
#

The first half isn't structured correctly. You're defining a dictionary with 4 keys, each of which are a quoted string.

nocturne chasm
#

UndefinedError: 'dict object' has no attribute 'event'

ivory delta
#
  "event": {
    "data": {
      "type": 6,
      "event": 6,
      "event_label":"Keypad unlock operation",
      "parameters": {
        "userId": 1
      }
    }
  }
}
%}```
nocturne chasm
#

Auh....ok

ivory delta
#

Assuming the second half is correct, it expects a structure like that.

nocturne chasm
#

that makes sense

ivory delta
#

Dot notation works for accessing nested properties of objects... but dots in key names don't denote nesting.

nocturne chasm
#

so when I set trigger.event.data.parameters.userId == 1 is evaluates as true

#

but when I set trigger.event.data.parameters.userId == [1, 2, 3, 4, 5, 6] it evaluates as false

#

I should be able to list a dict like that correct? or is it taking the comma as part of the dict?

inner mesa
#

Did you want ‘in’ instead of ==?

#

That’s certainly false as is

nocturne chasm
#

auh, hold on

#

noice

#

thank you

charred dagger
#

Only for accessing, though.

ivory delta
#

🤯

#

First and last are equivalent anyway, it's the middle one that's weird.

#

And I guess that's just because the state object holds references in both places.

inner mesa
#

Like it has a key that’s a dotted string?

#

Truly hacky

charred dagger
inner mesa
#

Well, it helps with Jinja filters, so I’m onboard. They’re my favorite

ivory delta
#

| replace('u', '')

idle ivy
#

Hi All

#

I'm either not understanding total_increasing state_class or something might not be configured correctly. I am integrating into my unfi setup and am looking at tracking total traffic for some users however unifi works on sessions so the traffic will keep increasing until the user disconnects. One they reconnect it starts at 0 again. I'm looking for a way to have an ever increasing value in HA. So I configured the following:

- name: "Edward - Pixel 5 Total Traffic"
  unique_id: sensor.edward_pixel_5_total_traffic
  state: >
    {{float(states('sensor.edward_pixel5_rx')) + float(states('sensor.edward_pixel5_tx')) }}
  unit_of_measurement: "MB"
  state_class: total_increasing

However when I look at the sensor value it seems to be going back to 0 instead of continuously aggregating. Herewith is a screenshot of the sensor values: https://imgur.com/a/BvvDUTz

earnest cosmos
#

Hi, guys!
Just need to get this confirmed, as something is wrong, not running what´s after this condition even when group.family is not__home

- condition: template     ## Continue only if nobody is home
  value_template: "{{ is_state('group.family', 'not_home') }}"

I want all services listet after this condition to be run if condition evaluates true. Is the condition correct, then?

waxen rune
#

The template looks fine to me. Have you tested it in dev tools so you're certain it works as expected?

If so, is your automation syntax correct? https://www.home-assistant.io/docs/scripts/conditions/#template-condition

From the examples:
conditions: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}" or

condition:
  condition: template
  value_template: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}"
earnest cosmos
#

the shorthand - conditions: "{{ is_state('group.family', 'not_home') }}" evaluates with error:

Invalid config for [script]: [conditions] is an invalid option for [script]. Check: script->sequence->2->conditions. (See ?, line ?)
mighty ledge
#
- "{{ }}"
charred dagger
#

That example in the documentation should probably say condition: {{ (state_attr... without the plural...

#

...maybe...

waxen rune
#

Yeah, you're right Thomas. I tried conditions as the docs says. Didn't work.
So I guess it is a combination of wrong docs and the incorrect leading dash before condition (see petros's post).

Anyway, this works:

- id: '1630331287319'
  alias: TEST
  trigger:
  - platform: state
    entity_id: switch.<...>
  condition: "{{ is_state('switch.<...>', 'on') }}"
  action:
  - service: notify.<...>
mighty ledge
#

or

#
- id: '1630331287319'
  alias: TEST
  trigger:
  - platform: state
    entity_id: switch.<...>
  condition: 
  - "{{ is_state('switch.<...>', 'on') }}"
  action:
  - service: notify.<...>
idle ivy
mortal ruin
#

Would you use a template to create an entity that has a numerical value of of two entities states combined?

#

or would you do that another way?

#

I want to see the true cost of my mining rig in the dashboard. I use two plugs though. So I can see one at a time, but I'd like to see them both.

#

Same for a server I have dual PSUs on.

#

I guess creating a custom entity would be best? Is that possible?

mortal ruin
#

This is my first attempt.

#
      state_class: measurement
      unit_of_measurement: kWh
      device_class: energy
      state: >
                {{ state('sensor.emporia_power_plug_3_123_1d + sensor.emporia_power_plug_4_123_1d') }}
#

I feel like I'm so close.

dreamy sinew
#

{{ states('sensor.emporia_power_plug_4_123_1d')|float + states('sensor.emporia_power_plug_3_123_1d')|float }}

mortal ruin
#

Testing, thank you

#

so the trick is states plural, and converting them to floats?

#

IT'S WORKING!

#

Thank you so much!

#

Hmm I can't add it to the indvidual devices space in the energy dashboard 😕

dreamy sinew
#

and you need to call states() for each entity

fiery mirage
#

Is there a graceful way to get the value of a sensor from a specific time (in the past) without using a SQL query into homeassistant_v2.db? I’m after trying to get a value of a sensor from 3 days ago, so I can calculate the 3-day delta of it in a template. Seems like a common use case, but reading some stuff of it not being available and needing SQL. Have things changed with the introduction of long term stats?

dreamy sinew
#

there is a history stats sensor

#

but beyond that i haven't paid attention

fiery mirage
dreamy sinew
#

gotcha, no idea then

hearty mica
#

super dumb question that has stumped me... when creating a template that uses "Entity" I am able to use [[[ return entity.entity_id ]]]

#

How can I use something similar when using "Entities"

inner mesa
#

that's for custom button card?

#

if so, it doesn't support entities

hearty mica
#

I am trying to use custom switch-popup-card

#

wait no you're right.. This wont work then.. Thanks

analog remnant
#

Hello guys, a few months back there was a really helpful message about using "map", I'm trying to map different fans speeds of my fan (off, low, medium, ...) to the actual fan_modes that the fan-entity accepts. I'd like to use map to "translate" my off, low, ...-values to those that the fan accepts. Can anyone help me finding the example or help me otherwise?

karmic prism
#

hi i'm trying to pull 3 values from a rest call and https://hastebin.com/ejutobuzug.yaml nearly works home assistant says my config is good i get 3 sensors but the values are unknown i think there should be 4 but ... i'm new to this it was a win to finally get it to validate

ivory delta
#

What's the value of sensor.csensor right now?

#

And all of the attributes.

karmic prism
ivory delta
#

Ok. And you're doing it wrong anyway. Remember when you first asked about this and I asked if the order of the entries was always the same?

#

That's because you don't have keys to access the data with. You have to access the list of items based on their position.

#

Nothing you're trying to do with the JSON attributes will work. You need 3 separate sensors, like I suggested the first time round.

#

You were given the working code for the first one. Tweak it for the other two.

karmic prism
ivory delta
#

Yes, three like that.

karmic prism
#

I put all 3 as the state of c sensor the problem is how to break them out or set them as attributes of csensor

edgy umbra
#

Anyone can help me to get a between time? I want to only show this icon between 22:00 and 06:00 🙂

#
              [[[ 
                if (states["weather.openweathermap"].state == "sunny" && states["sensor.time"].state < '17:00' ) return '/local/weather/Sunny.svg';
              ]]]```
ivory delta
ivory delta
grand merlin
#

I'm trying to bypass login for a google nest nest (IP 192.168.1.2) and limit this to the google nest hub user , would that work, and would other user still be able to login (same subnet and other subnet)

#

auth_providers:
- type: trusted_networks
trusted_networks:
- 192.168.1.2 -- client IP / no sub
trusted_users:
192.168.1.2: !secret gcastuser
allow_bypass_login: true
- type: homeassistant

pastel moon
#

Trying this out in dev tools ```
{% set trace = ['motion-off', 'motion-on', 'manual'] %}
{{ 'motion-off' not in trace }}

#

Is there a contains clause perhaps? Searched for it but had no luck

ivory delta
#

First, filter so you only have the items from the original list that match the RegEx pattern /motion/, then work out the length of the new list and assert that it's 0.

pastel moon
#

Fantastic, works nicely! Thanks @ivory delta !

autumn matrix
#

I'm trying to change my lighting based on the state of my apple tv when watching a netflix movie.
For this I want to use media_title. I can distinguish if its a serie or a movie based on the media_title attribute.
Namely series will start with S1: E1 and movies won't.

So in other programming languages I would use a regular expression which goes something like this /^(?!S[1-9]:)/gm. Which matches only if media_title does not start with S1-9:.

My question is. How can I do this with templates in combination with automation. I can choose NOT as a condition but don't know who to use a regular expression there?

  - condition: not
    conditions:
      - condition: state
        entity_id: media_player.woonkamer
        attribute: media_title
        state: 'S([1-9]):'
inner mesa
#

you don't

#

there's nothing in the docs that says you can use a regex there

#

you would need to use a template condition

autumn matrix
#

I was hoping I could do something with templates but not sure how

#

Ok thank you for confirming atleast I should look any futher in the regular expression support for the condition section

#

any hint on were to look regarding templates?

inner mesa
#

something like "{{ not state_attr('media_player.woonkamer', 'media_title') is search('S([1-9]):') }}"

autumn matrix
#

ah... is was looking at an if statement like
{% if regex_search(states.media_player_woonkamer.attributes.media_title, '^S([1-9]):', ignorecase=TRUE) %} {% endif %}

inner mesa
#

that's not a very useful "if" statement

#

in any case, you just need a boolean, which my expression produces

autumn matrix
#

I see

inner mesa
#

yours uses a different command and has more characters and doesn't actually return anything 🙂

autumn matrix
#

true.. its good to know a boolean is needed 🙂

#

and I can also confirm it works. Awesome!

karmic prism
ivory delta
#

That's not going to happen. HA could handle thousands of them 🤷‍♂️

novel widget
#

i just created a template sensor - which is just working out the average of the three values they return. ive restarted HA and as well as the state being the average i expected, it includes median, mean, last value and other stuff and has the calculator average - does HA just automagically treat them as statistics sensors or something because ive performed arithmetic with the sensor values?

ivory delta
#

statistics sensors
Statistics or long-term statistics? The latter is a concept introduced recently with the energy feature.

novel widget
#

i didnt think i had created either

#
  • platform: template
    sensors:
    house_temperature:
    friendly_name: "House Temperature"
    value_template: >-
    {%- set var = (states('sensor.living_room_temperature') |
    float) + (states('sensor.kitchen_thermometer_temperature') | float) +
    (states('sensor.upstairs_thermometer_temperature') | float) -%}
    {{ (var/3) | round(1) }}
ivory delta
#

The former is a type of sensor you'd define. The latter is a 'feature' you'd get depending on certain characteristics of a sensor.

#

What are you trying to achieve?

novel widget
#

just a simple average - i dont have a problem i just was surprised that the above sensor provided more than just the single average instead it provided additional attributes

#

i.e.

#

count_sensors: 3
max_value: 18
max_entity_id: sensor.kitchen_thermometer_temperature
mean: 17.82
median: 17.75
min_value: 17.7
min_entity_id: sensor.upstairs_thermometer_temperature
last: 17.7
last_entity_id: sensor.upstairs_thermometer_temperature
unit_of_measurement: °C
friendly_name: house_temperature
icon: mdi:calculator

ivory delta
#

What you're seeing is normal based on what you've described. Ignore the attributes you're not interested in.

kindred arrow
#

Hello! I wish to count all active automation, with attributes "current" != 0
I tried {{ expand(states.automation) | selectattr('current', 'ne', '0') | list | count }} but it doesn't seem to work, how would you guys do for that? Thank you for the help!

ivory delta
#

What doesn't work? What's it doing?

kindred arrow
#

It's like the "current" attribute doesnt exist, because it gives me my number of automations

mental path
#

I am trying to modify a template, so I can check on a value being > 100 as opposed to being exactly 255 for instance.. can I modify this line somehow?

#

value_template: "{{ is_state('sensor.vision_zg8101_garage_door_detector_alarm_level', '255') }}"

ivory delta
#

Two changes:
{{ expand(states.automation) | selectattr('attributes.current', 'ne', 0) | list | count }}

mental path
#

(hi all - happy LDW!)

ivory delta
#

You weren't targeting the right attribute, and you need to compare against a number.

ivory delta
#

selectattr doesn't only look at attributes of a HA entity. It's a Jinja filter, so you have to be more specific about what to look for - Jinja means something different by attributes.

mental path
#

This template stuff is black magic.. 🙂

ivory delta
#

Gah, messed up the formatting 🤦‍♂️ All good now.

mental path
#

Thanks !! I'll try it - trying to fix garagedoor logic 🙂

#

Ah thats useful thanks.. is thats whats consider a limited template when its in a cover for instanc?

#

*instance

#

so for the icon template I could use it as this? :

#

icon_template: >-
{% if states('sensor.sensor.aqarav2_angle_x') > 70 %}
mdi:garage-open
{% else %}
mdi:garage
{% endif %}

#

(aqaraV2 is sensor telling me the angle of the garage door

inner mesa
#

states are strings

#

{% if states('sensor.sensor.aqarav2_angle_x')|float > 70 %}

mental path
#

the |float converts the string to a float to compate with the 70?

inner mesa
#

yes

mental path
#

Hmm I think I have the value template wrong ? Is this right? Its showing unavailable

silent barnBOT
inner mesa
#

you don't have what I gave you

#

you also need it in the value_template

#

for the same reason

mental path
#

duh, ok how about this - value_template: "{{ if states('sensor.sensor.aqarav2_angle_x')|float > 70 }}"

inner mesa
#

now you added an unnecessary "if"

mental path
#

ah ok its different in the value template vs below? looks valid now at least, thanks!

#

makes sense.. top one resolves to a true false, below the true false renders the two icons.. ok i think i have it .. sorta.. thanks again 🙂

#

its not working though - sensor.aqarav2_angle_x does change from 2 to 72 when the door is opened, but the ui card doesnt change.. shows closed icon still 😦

silent barnBOT
#

Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).

Please take the time now to review all of the rules and references in #rules.

inner mesa
#

does the state change as expected in devtools -> States?

#

for the icon, just use device_class: garage as shown in the docs

mental path
#

ok let me check in states - i was checking in zigbee2mqtt

#

state for sensor.aqarav2_angle_x changes as expected 2 and 72 for closed and open respectively- history on the cover shows 'closed' all times even after a few up/downs. When i go to settings for the cover i have this message though "This entity ("cover.garage_door_2") does not have a unique ID, therefore its settings cannot be managed from the UI"

inner mesa
#

no idea

#

hopefully you restarted HA or reloaded template entities

mental path
#

yeah restarted every change

#

thanks - i'll mess around with it. but the template looks good now? i put in device class instead of the conditional icon as well

#

is there a way to see waht value_template: "{{ states('sensor.sensor.aqarav2_angle_x')|float > 70 }}" evaluates to ? or even just the sensor.sensor.aqarav2_angle_x')|float part?

ivory delta
#

Yeah, put it into the Dev Tools under Templates.

mental path
#

So {{ states('sensor.sensor.aqarav2_angle_x')|float > 70 }} evaluates to false in dev tools while sensor.aqarav2_angle_x is 72 in states.. thats odd

inner mesa
#

oh, this is wrong: sensor.sensor.aqarav2_angle_x

#

you have two "sensor." in there

#

in both parts

#

@mental path

kindred arrow
#

Hello, it's me again, I wish to make a list of "home" entities inside of a group like this, can you please help me out?

{% if is_state(state.entity_id, 'home') %}
🔺{{ state.entity_id }}
{%- endfor %}```
#

The group name is group.needs_multiprise_bureau

#

I successfully did it with an expand like this, but that's not how I want it to
🔺{{ expand('group.needs_multiprise_bureau') | selectattr('state', 'eq', 'home') | map(attribute='entity_id') | list | join('\n- ') }}

inner mesa
#

how do you want it?

#

your first "for" loop doesn't make sense - scripts have a state of on or off, not "home"

kindred arrow
#

Like this kinda:
🔺device_tracker.pc1
🔺device_tracker.pc2

inner mesa
#

what is that triangle?

kindred arrow
#

Yeah yeah I know for the "script" I just took that loop for the example, and the 🔺 is the an emoji that I use for the lists, instead of -

inner mesa
#

why?

#

you want a real list?

#

with "-"?

kindred arrow
#

It's not about the emoji aha, that doesnt matter, I just don't know how to list entities in group ^^

inner mesa
#

ok, just a weird thing

kindred arrow
#

I have a group named group.needs_multiprise_bureau and I would like to list all entities with state "home" that's all :p

inner mesa
#

So you just want a list out of it? Isn't a comma-separated list enough?

#

that's easy