#templates-archived

1 messages · Page 16 of 1

merry delta
#

yep, template was good, ty for helping me rule that out and find a bigger problem with ring motion integration. my workaround till i ditch ring is virtual switches with alexa routines triggering them. for now

celest plume
#

Question:
I have a sensor that collects this value;

1.84 9

But I want to show this 1.849 ,
How do I remove the (space) between 4 and the 9 ?
When I use this:
value_template: "{{'{:.3f}\x00'.format( value | float )}} "
It keeps the same...

What do I miss.........

Thanks.

glossy viper
#

this: {{ (states.sensor.shopping_list.attributes.incomplete() | list) }} returns error

marble jackal
marble jackal
#

and to get only the names you can use {{ state_attr('sensor.shopping_list', 'incomplete') | map(attribute='name') | list }}

celest plume
glossy viper
#

thank you

lapis lynx
#

I have the following line in the configuration.yaml
template: !include templates.yaml
Then this is my templates.yaml file;
https://pastebin.com/J9kiMEKj

However I get the following error;
Invalid config for [template]: [lights] is an invalid option for [template]. Check: template->lights.
What am I doing wrong?

marble jackal
#

a lot

#

template lights should be under light not under template

#

and the sensors you have there are in the legacy format

#

so they are also incorrect under template

lapis lynx
#

Ah so I've alot of tidying up to do then.. Will it be easy to change to the new format? Feel like my files are a complete mess and need a good tidying up..

plain magnetBOT
marble jackal
#

have a look at the docs 🙂

lapis lynx
#

Thanks, so for my case I'll still have template: !include templates.yaml and then my templates.yaml will start as - sensor ...etc...

Then for lights I'll add in light !include lights.yaml and have similar in that file but for lights?

plain magnetBOT
silent seal
#

You can actually go further 😉

lapis lynx
#

Oh god, this has become way more than I expected..

silent seal
#

Keep it simple to start with, and get fancy later

lapis lynx
#

Think first thing is to update my templates.yaml to have my sensors in the new format, or should that be named sensors.yaml in theory?

silent seal
#

Well, do you only have template sensors, or do you have template binary sensors?

#

I started out with just templates.yaml, and then went to templates/sensors.yaml (and the same with binary_sensors, and now I do templates/sensors/my_id_for_sensor.yaml

split pivot
#

Is there an easy way to map states to text without doing a bunch of if else?
I currently have this: {% if is_state("binary_sensor.gastezimmer_beschattung_bereit", "on") -%}bereit{%- else -%}gestoppt{%- endif %} and was wondering if there is a jinja filter I can just give a mapping of states to text to simplify this

silent seal
#

You can use iif, the immediate if

#
{{ iif(is_state('binary_sensor.gastezimmer_beschattung_bereit', 'on'), 'bereit', 'gestoppt') }}
split pivot
#

thanks, but if I wanted to map more than one state I would still need to chain these, there is no other way right?

lapis lynx
silent seal
#

What you might be able to do is define a dictionary and just get the value for the key.

# pseudocode
{% set my_words = {"on": "bereit", "off": "gestoppt", "unavailable": "nicht verfügbar"} %}
{{ my_words[state('binary_sensor.gastezimmer_beschattung_bereit') }}
silent seal
# lapis lynx I've just got template sensors

Then, I would start with a folder called templates and put a file in there called sensors 🙂
I believe you'll use !include_dir_named in that:

template: !include_dir_named templates
split pivot
#

that's exactly what I was looking for, it did not occur to me that I can just define variables in templates, thanks!

silent seal
#

If I've screwed it up RobC, Petro or TheFes may be around later to give you more pointers 😄

#

(Or someone else, lots of folks do try and help out in here)

split pivot
#

Nah, works perfectly :)

tepid moth
#

hi guys, i want to set generic thermostat. and in away mode use value from equation. let say outdoor temperature +5. how can i achieve that?

split pivot
#

Is it possible to format an entity state in a template in a locale aware way? As in replace the decimal point with a , if the frontend locale is German? Something like {{ states(sensor.temperature) | localize() }} to get 21,5 instead of 21.5 ?

silent seal
#

Quick Jinja tip: if you are using this | something_or_other then you are calling the function something_or_other on this (so it's the same as something_or_other(this).

#

But localisation like that is not something you'd do with a template. I don't believe the ,, . swap is something supported right now—though there may be an open request for it in the forums with recent dev commentary on 🙂

marble jackal
#

Why would you want that? It is shown according to the settings in your profile on your Dashbaord

split pivot
#

For non-template cards, yes. But my template cards do not localize the values when rendering them to strings

silent seal
#

Did you set their device class?

#

If you set it to be a temperature or similar, I believe it should work 🤔

split pivot
#

I'm not talking about template entites, I'm writing the template in a lovelace card because I want to modify icon color based on states and also show the state differently. In that case the value is always with, e.g., a decimal point

marble jackal
#

if it is simply to replace it, you can do something like {{ 21.5 | string | replace('.',',') }}

split pivot
#

Yes, that would be the easy, cheap and also wrong way because then when someone else opens the dashboard in english, it's wrong for them.

#

If it's not possible currently then it's fine, I can live with it.

silent seal
#

How are you modifying the icon colour? Would it be better to use customisation and do the template for the icon colour in that?

mighty ledge
#

don't use template cards, make a template sensor. Otherwise you have to build the logic using something that has access to translations.

#

the Jinja templates do not have access to that, some JS templates do.

lapis lynx
#

Managed to bring my sensor templaters to use the modern way. Now I need to figure out how exactly to do a light template. Does this become;
configuration.yaml;
light: !include lights.yaml

lights.yaml;

  • lights
    • name: "mylight1"
      .....
mighty ledge
#

light templates have not been brought over.

#

Use the documentation, don't make guesses

lapis lynx
#

Fair, thought they'd have the same format

marble jackal
#

there is a link to the template light docs on the page I provided earlier

#

If they would have been converted to a new format, it would have been stated there

silent seal
#

If they are switches, the Switch as X helper is now in the UI

unreal beacon
#

Can i use a template for the "below" value in a numeric state trigger?

unreal beacon
#

This should work shouldnt it?
as a "template condition"

#

should pass true if the current temp is less than the trigger yeah?

marble jackal
#

you should convert it to numbers

unreal beacon
#

|float them both yeah?

marble jackal
#

but this would be a template tirgger, not a numeric state trigger

#

yes

unreal beacon
#

yeah templatre trigger i worked out 🙂

ember saffron
#

Hi, when creating a template sensor, are the linked value from the state automatically updated to the template sensor?

unreal beacon
#
``` so this should be solid @marble jackal
marble jackal
#

a bit overdone with the paranthesis
{{ state_attr('climate.spa_thermostat','current_temperature') < state('sensor.spa_trigger') | float }}

#

actually you don't need the float on the first one, that will already be a number

unreal beacon
#

the other is also a number... or should be?

marble jackal
#

no, all states are strings

unreal beacon
#

ahhh even if its a device_class temp?

marble jackal
#

ALL states are strings

unreal beacon
#

kk

unreal beacon
sacred ridge
#

Hello I’m using Mushroom cards I’m trying to make it so that it says Good morning, {{user}} the user bit currently works but the rest doesn’t

inner mesa
#

What 'rest'?

#

Saying what's working and glossing over what doesn't won't help you 🙂

sacred ridge
#

Hello, entity.state.sun {{ user }} 👋

#

That’s what I have

inner mesa
#

You need to read the template docs

sacred ridge
#

type: custom:mushroom-title-card
title: Hello, entity.state.sun {{ user }} 👋

marble jackal
#

Hello, above_horizon Connor 😅

inner mesa
#

I don't judge

#

The heart wants what it wants

plain magnetBOT
#

@short wren I converted your message into a file since it's above 15 lines :+1:

short wren
#

On HA 2022.11.1. Wondering what's wrong with my entity_id template and if perhaps I could write this cleaner with less duplicated "code".

lyric hatch
#

Hey all, I have a template sensor that gives me the room my phone is in based from the lowest number of 3 sensors, the sensor works until one of the sensors is unavailable then it fails, anyway I can solve this?

inner mesa
#

Provide a default with float(0), or whatever you want the default to be

#

Maybe a big number so it won't be the lowest

lyric hatch
#

On the 3 separate sensors? They are generated from esphome though, can I set a default in the sketch?

inner mesa
#

It depends on how they became unavailable

marble jackal
#

What is the state of the sensors when you are out of reach?

marble jackal
marble jackal
# lyric hatch Hey all, I have a template sensor that gives me the room my phone is in based fr...
{% set sensors = ["sensor.sam_living_room_distance", "sensor.sam_bedroom_distance", "sensor.sam_kitchen_distance"] %} 
{% set ns = namespace(min=99999, room='') %}
{% for item in expand(sensors) | selectattr('state', 'is_number') %}
  {% if item.state | float < ns.min %}
    {% set ns.min = item.state | float %}
    {% set ns.room = item.object_id | replace('sam_', '') | replace('_distance', '') | replace('_', ' ') | title %}
  {% endif %}
{% endfor %}
{{ ns.room if ns.room else 'Not Home' }}
lyric hatch
marble jackal
#

That's what will happen here

lyric hatch
marble jackal
#

You could first test it in developer tools > templates and walk around the house a bit

lyric hatch
lyric hatch
marble jackal
#

BTW if you would give the sensors the corresponding room as name, you can replace {% set ns.room = item.object_id | replace('sam_', '') | replace('_distance', '') | replace('_', ' ') | title %} with {% set ns.room = item.name %}

plain magnetBOT
#

@short wren I converted your message into a file since it's above 15 lines :+1:

short wren
marble jackal
#

Ah, it was not clear to me based oh your previous code that this was your goal

short wren
#

All good 🙂

plain magnetBOT
#

@late knot I converted your message into a file since it's above 15 lines :+1:

silent seal
#

Look for where you have something in a file with value_json['update'], I'd best it's a RESTful integration of a kind

late knot
silent seal
#

Where are you searching? It would be in the /config directory most likely.

late knot
silent seal
#

But where are you when you do that?

late knot
silent seal
#

Did you install some kind of integration to tell you when there are updates or similar?

#

And have you tried increasing the log levels?

#
logger:
  logs:
    homeassistant.helpers.template: debug
late knot
#

special intigrations ... no
i try it with increasing the log level

#

no chance i only get the warning

2022-11-15 23:23:36.530 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'installed_version' when rendering '{{ value_json['update']['installed_version'] }}'
2022-11-15 23:23:36.530 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'installed_version' when rendering '{% if value_json['update']['state'] == "available" %}{{ 'newer' }}{% else %}{{ value_json['update']['installed_version'] }}{% endif %}'

ember saffron
#

did anyone already "mapped" a value from a CCU energycounter into a template sensor?

unreal merlin
#

Howdy 🙂
I'm having a hard time with a template sensor: it stops working after a while.
Here's what I've got:
template: - sensor: - name: "Plex Usage" state: "{{ expand(integration_entities('plex'))|selectattr('state', 'in', ['paused', 'playing'])|list|count }}"

This works fine when I reload my template entities, but only for so long.
Debugging this (when the issue occurs) it seems that:

  • Running this in template editor will still show the correct count
  • The state however will not change for the template sensor (so UI won't update either).
#

The purpose of this is to conserve energy and put plex into sleep when not in use.
In this suspended state, integration_entities('plex') returns an empty list, which is counted 0, so that ideally is functioning as it should.

#

but still, after a while it seems that this template sensor goes titsup and won't update its values until I reload templates.
Any hints on how can I debug this further to understand what's happening? (for now I'm crawling the logs hoping it turns up anything useful)

floral shuttle
#

took me a while, but I have to get back to this. on a time when no 'tomorrow' data is available (hour 24 t0 48) this {{(value_json|default(['default']*48))[24]['TariffUsage']|float(0) + states('sensor.prijsopslag_energie')|float(0)}} etc still causes the error 2022-11-16 10:19:12.578 WARNING (MainThread) [custom_components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary for all of the sensors

#

full sensor yaml:```
- name: Energieprijs uur 24
value_template: >
{{(value_json|default(['default']*48))[24]['TariffUsage']|float(0) +
states('sensor.prijsopslag_energie')|float(0)}}
json_attributes_path: "$[24]"
json_attributes: *attributes

#

wouldn't the json_attributes_path: "$[24]" cause issues too? I mean there's no such thing at that time?

#

Yes, I guess its been that all the time, because, I can use the earlier default (and leave out the attributes) {{(value_json|default(['default']))[24]['TariffUsage']|float(0) + states('sensor.prijsopslag_energie')|float(0)}} on those sensors without it returning an error. So, I need to guard the attributes...

pine belfry
#

hello, any clue why this returns undefined as the entity_id ?

#

{{ states.binary_sensor | selectattr('attributes.device_class', 'defined') |
selectattr('attributes.device_class', '==', 'window') |
map(attribute='attributes.entity_id') |list}}

#

i guess because im stupid, the mapping should be attribute='entity_id'

marble jackal
#

Yes, entity_id is not an attribute

#

In HA terminology, it is in jinja terminology 😅

mighty ledge
floral shuttle
#

is there some discussion on the matter in dev world?

#

it would already help if the error message would distinguish between the state template and attributes.

mighty ledge
#

no

#

not that I know of

plain magnetBOT
#

@celest plume I converted your message into a file since it's above 15 lines :+1:

charred dagger
#

It could be that you have translated (?) lngto length and rad to wheel.

#

Also, the German word for fuel is "sprit"??

#

That's the Swedish word for hard booze, which... kind of works...

inner mesa
#

Ha

#

Automatic website translation doesn't work well with REST parameters 🙂

open coral
#

hello! I am trying to get this template to fire on an automation but its not working. any help appreciated!

    service: light.turn_on
    entity_id: light.1st_floor_tv_lights
    data:
      brightness: '{{states.light.1st_floor_tv_lights.attributes.brightness + 10}}'```
arctic sorrel
#

You forgot, again, to explain the problem/provide the error

open coral
#

sorry. the error is:
Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][0]['data']. Got None. (See /config/configuration.yaml, line 45). 

#

im trying to get an automation where when I push a button, the brightness of lights.1st_floor_tv_lights increases by 10

inner mesa
#

I don't think it likes that your object_id starts with a number

#

you should use this anyway:

#

brightness: "{{ state_attr('light.1st_floor_tv_lights', 'brightness') + 10 }}"

amber obsidian
#

Funny. Just opened the channel to ask if that can be done like that. Or kind of. I'm using off_brightness for attr when turning lights on. But thanks!

#

Just to clarify: I'm setting off_brightness with other triggers and this way the light goes on with right brightness.

vast juniper
#

Guys, how to set up template using strptime to display 2022-11-16? I have "{{strptime(states('sensor.bin_date'), '%A %d %B %Y') }}" its prints "2022-11-16 00:00:00" how to get rid of the hours min and sec? Everything i try it errors me.

inner mesa
#

what is the actual sensor state?

vast juniper
#

Wednesday 16 November 2022

inner mesa
#

{{strptime('Wednesday 16 November 2022', '%A %d %B %Y').date() }} -> 2022-11-16

ember saffron
#

Hi, I’m new to HA and I have a question about the template sensor. When I add a template sensor it appear in the gui but when get it updated with a value? Always when the source changes?

inner mesa
#

In general, yes

#

I think@that's in the docs

celest plume
vast juniper
ember saffron
#

Can anyone check whats wrong with my first template sensor? It would be awesome

#

template:

  • sensor:
    • name: "test1"
      unit_of_measurement: "W"
      device_class: "power"
      state_class: "measurement"
      state: >
      {{ state_attr('sensor.ccu3_sv_svenergycounter_2592_00085a49123456_7','Watt') }}
marble jackal
#

Are you sure the value you need is in that attribute?

#

And if so, check in developer tools > states of the attribute key isn't watt?

inner mesa
#

The point is: add .date()

ember saffron
#

I've modified the ID of the Entitiy for security reasony, but yes it should be (of course as I've understood it correctly to use this ID)

#

from the dev tools, then look for the entity and then under the (I)

#

also there the unit_of_measurement: is unitless

marble jackal
#

That doesn't answer my questions

#

Is there an attribute Watt with capital W which has the value you are looking for

ember saffron
#

No

marble jackal
#

Are you not looking for the state of the sensor

#

Then that is your problem

atomic blade
#

Is there a way to get a list of all areas?

vast juniper
marble jackal
ember saffron
#

This entity contains the value what I need. Is there a different way to get it, for further processing

marble jackal
#

{{ states('sensor.ccu3_sv_svenergycounter_2592_00085a49123456_7') }}

atomic blade
inner mesa
#

That's one of the things that can easily be confusing about Jinja. It's one of the few times in many languages when you pass a string that represents an executable thing

ember saffron
inner mesa
#

You can do it (and sometimes have to) in other languages, but it's not typical

inner mesa
#

I was amazed the first time I realized that I could construct a function name from string manipulation and call the thing

#

(coming from embedded C)

mighty ledge
#

the drawback is that it's slow

#

if you can get away without using it, it's better

#

but sometimes you can;t

#

pretty sure that jinja uses function pointers for that, so it's not actually reflection

#

but calling a function by name as a string typically means that the code is using reflection to get the function in some way

inner mesa
#

right

marble jackal
#

Blue: state
Red: attributes

inner mesa
#

BTW, you can check out the meta language that the Jinja engine actually executes.

mighty ledge
#

Everytime i use reflection in C# i get confused at the syntax and then I find a way to not use it

inner mesa
#

to see what it's really doing

atomic blade
#

Is there a better way of doing this without needing the first at the end?

['kitchen', 'bedroom']
| map('area_entities')
| list
| first
#

To build on what I had before, I'm trying to get a list of all entities with an area. Maybe there's a better way to do that?

mighty ledge
#

first selects the first entity

#

be warned, you need to provide a default when there is an empty list

atomic blade
#

Well my problem is more with the map I guess than the first

#

There's no reduce lol

mighty ledge
#

there's a way

marble jackal
#

I'm still don't understand the issue I guess 😅

#

Maybe if I see the solution of petro

atomic blade
#

Well it's just a wasted step

mighty ledge
#
 {{ ['kitchen', 'bedroom'] | map('area_entities') | list | sum(start=[]) | unique | list }}
#

probably want to sort that too

#

just replace the last list with sort

atomic blade
#

This is really just to fix the problem of an empty list, though, right? That's a cool trick I'll have to remember. But I was more looking for reduce-like behavior so I don't wind up with a list at all

mighty ledge
#

that doesn't fix an empty list

marble jackal
#

{{ states | map(attribute='entity_id') | map('area_name') | reject('eq', none) | unique | map('area_entities') | list | sum(start=[]) }}
All entities which have an area

atomic blade
#

Oh ok I kinda see. I mean behind the scenes it still is creating that list of lists all containing the same entity id's though, right?

#

I think just knowing that bothers me haha

mighty ledge
#

these's are generators, they aren't really lists unless you request the data

atomic blade
#

Hm that's a good point

mighty ledge
#

the sum(start=[]) is simply adding your results together

#

i.e. when you use ['kitchen', 'bedroom'] | map('area_entities') you end up with 2 lists of entities

atomic blade
#

Yeah I'm just saying it bothers me that there are results when I should have result

mighty ledge
#

which you want 1 big list, so you add the 2 together

atomic blade
#

It doesn't matter, just is inefficient (not that it really matters from a practical standpoint)

mighty ledge
#

ok, so you can add any objects together as long as they can be added

#

it's not inefficient

atomic blade
#

sum is being called multiple times, though, right?

mighty ledge
#

no

#

it's being called once

#

do you understand the order of operations in code?

atomic blade
#

Ok so rather it's being called once with an array that is "unnecessarily" large, no?

#

Yeah I understand that

mighty ledge
#

if you have 4 lists and you call sum on them, it's adding the 4 lists together

#

[ ['a'], ['b'], ['c'], ['d'] ] | sum(start=[]) | list -> ['a','b','c','d']

#

which is the same as ['a'] + ['b'] + ['c'] + ['d']

#

doesn't matter how many items are in the lists, the output is the same

#

string concatenation is the same

#

any object that can be iterated is the same

atomic blade
#

Just to make sure we're on the same page with what the data looks like, without the sum I end up with a list of identical lists. Being identical in that they each have all the same entity_id's?

inner mesa
#

Filters are called with the entire input data structure

mighty ledge
#

are you saying you have the exact same entity_id's in your bedroom and your kitchen?

ember saffron
mighty ledge
#

I can understand if you have overlap. That's what the unique is for. It keeps only unique strings and removes duplicates

#

that's why that's executed last

ember saffron
atomic blade
ember saffron
#

"get the value into a template sensor"

atomic blade
#

Ugh something just happened to my HA instance...must've hit it too hard with templates or something and it's choked up now

mighty ledge
#

and to remove duplicate entity_id's after you make it 1d, you use unique

atomic blade
#

Right but what I saw at least in that 2d array looked something like this:

[
  ['entity1', 'entity2'],
  ['entity1', 'entity2']
]
#

Wait now that I write it out I think I see where I was interpreting it wrong

#

Not sure how I arrived at that either tbh lol

mighty ledge
#

with your example, sum(start=[]) will return ['entity1', 'entity2','entity1', 'entity2'] and then unique would return ['entity1', 'entity2']

#

then you probably want a sort cause unique mangles the order of things

atomic blade
#

No sorry I think we were on different pages cuz I was assuming something about the structure of data that was incorrect. And you probably didn't catch on because, well, it didn't make sense. Not sure how I arrived there either.

#

Maybe. Let me wait for HA to come back up so I can play in dev tools

#

Somehow the demo template is back lol

plain magnetBOT
#

@rigid chasm I converted your message into a file since it's above 15 lines :+1:

atomic blade
mighty ledge
#

yeah, they won't be the same unless you made a typo and had the same area twice

atomic blade
#

Circling back to the technical aspect of it though, I think it's still inefficient, though not for why I was saying before. Isn't sum still having to traverse the whole list? Theoretically you shouldn't ever need a 2d array in memory

mighty ledge
#

and this goes back to generators

#

tbh, I think you need to brush up on how and what generators are and lambdas

#

they all use the same tech

#

which is that they don't resolve unless they are explicitly accessed

atomic blade
#

I have a general idea, but not specifically how it works in python

mighty ledge
#

it works the same in all languages

atomic blade
#

And I think I conceptually see what you're saying then if those are generators

mighty ledge
#

it yields the result when it's needed

#

all list traversing filters are generators

#

aside from expand

#

and sort

#

and possibly unique nope, it's a generator

atomic blade
#

So it isn't really a list being passed into sum then, it's a generator?

mighty ledge
#

it's only summing when the value is needed

#

you have 5 generators in a row, only the information that comes out at the end is what was accessed

gusty pulsar
#

Hi Guys, what would be the best way to take a value (in minutes, e.g. 60) from a drop down and add it to the current date & time to set a date/time helper with that value?

dry narwhal
gusty pulsar
atomic blade
mighty ledge
gusty pulsar
# mighty ledge Can you explain your endgoal

Of course, what I'm trying to achieve is automating an EV Charger.

When an EV is connected to the charger, it will check the drop down for how many minutes of charging are required, then at a set time it will start charging for the number of minutes selected from the drop down.

I can handle the charger side of things no problem

mighty ledge
#

Can you post the format of the charge time? A pic of the entity and its attributes in dev tools -> states

gusty pulsar
#

I've not created it yet so I can tailor it to how works best, my idea was a drop down helper in 15 minute intervals

mighty ledge
#

Ah sorry I thought you said you had a sensor that gave you the charge time

gusty pulsar
#

Ahhh no sorry, I'm just creating it now

mighty ledge
#

Are you using a input_datetime with just time?

gusty pulsar
#

I suppose a timer helper could be used and trigger the automation to stop charging once the timer finishes?

At the minute I've set it up with date and time because I could foresee an issue with one day ending and another starting as the charging time will pretty much always start at 11:30pm (but not always)

mighty ledge
#

What about a slider?

#

In number of minutes

gusty pulsar
#

That could work

mighty ledge
#

ok, so

#

make a template sensor

#
template:
- binary_sensor:
  - name: Charge
    state: >
      {% set start =  today_at(states('input_datetime.time')) %}
      {% set duration = states('input_number.charge_time') | int(0) %}
      {% set end = start + timedelta(minutes=duration) %}
      {{ start <= now() <= end }}
#

however, things might get odd if you cross midnight

#

might be worth it to start at midnight instead of 11:30pm

#

otherwise the template will get a bit hairy

#

but anyways, it's a binary sensor, so making an automation is simple, just start charging when it goes on, then stop charging when it goes off

gusty pulsar
#

That is really helpful, thanks so much for that.

I can start it at midnight no problem, the charge time is usually 2hrs 30 minutes and my time of use tariff is a 6 hrs cheap electric window.

Genuinely really appreciate that, ill start creating it now

gusty pulsar
mighty ledge
dapper aurora
#

Trying to test a template and this is_state_attr is not working - not sure why
When i evaluate for the attribute I put this into the is_state_attr
{{state_attr('light.atom919','rgb_color') }}

{{ is_state_attr('light.atom','rgb_color',' (255, 0, 0)') }}
However the is_state is evaluating to false

silent seal
#

You're missing a quote before the start of the brackets around the RGB values

#
{{ is_state_attr('light.atom', 'rgb_color', '(255, 0, 0)') }}

Or rather, you had a space inside the quotes

floral steeple
#

Hello! Can somebody point to me in the right direction to make a sensor that averages the value of another sensor but for only the last 10 minutes?

inner mesa
#

Sounds like a statistics sensor

floral steeple
#

It sure does, thanks @inner mesa !

vast juniper
#

Guys, it does me heading now, what I'm doing wrong, I trying to compare tomorrow day with bin collection day, both prints theme same but if I compare them prints that are not equal. '''{{ (now().date() + timedelta(days=1)) | string ==
strptime(states('sensor.bin_collection_3rd_span_date'), '%A %d %B %Y').date()}}

{{strptime(states('sensor.bin_collection_3rd_span_date'), '%A %d %B %Y').date()}}
{{(now().date() + timedelta(days=1)) }}'''

clear mist
#

hey guys, i'm trying to make a chip card for my dashboard using a template card, but for some reason i can't put in a new line?
http://pastie.org/p/6PCNttcZIx3S07tz5qamB9
this code works in the developer tools->template section (spits out the temperature with the forecast beneath it on a new line), but for some reason in the chip template card, it's only on one line? am i missing something, or can chips not do multi line stuff?

marble jackal
wispy path
#

Is there any way to create multiple template entities by using a parent template?

Goal is to extend/enhance an integration that provides door and window sensors as "switch" entities and "off" means they are in an open state. There are separate sensors for sensing proper opening and tilt opening, but entity_id partially matches for both.
The idea is to combine two of these separate sensors per window into a 3-state sensor entity that has the cover device class, without having to define ~20 or so template entities.

marble jackal
plain magnetBOT
#

@marble jackal I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

whoops, there is a quote wrong there, but I can't edit it anymore 😛

jagged obsidian
#

The bot has turned on us

astral axle
ember saffron
#

Hi, I've tried something and the suggestions from TheFes, but I dont get the updated values from my source entity into my template sensor. I've made a small picture with code: https://i.imgur.com/v3uMf4Y.png

#

I hope somebody sees my issue why the sensors are not getting updated

marble jackal
#

Don't post pictures of text, if I would want to correct something I would have to type it all over

#

but anyway, you need to use states(), not state()

vast juniper
#

Im still fighting with this templating issue. in developer tools this reads 'True'
''' '{{ (now().date() + timedelta(days=1)) == strptime(states('sensor.bin_collection_3rd_span_date'), '%A %d %B %Y').date() }}' '''

In configuration file under binory_sensor template it reads 'False'
''' - platform: template
sensors:
waste_bin_collection_day_tomorrow_3rd:
friendly_name: "Waste Bin Collection Tomorrow 3rd"
value_template: >-
'{{ (now().date() + timedelta(days=1)) == strptime(states('sensor.bin_collection_3rd_span_date'), '%A %d %B %Y').date() }}' '''
Its a same line copied across but reads diferent results why?

wispy path
marble jackal
#

and you should use backticks to format your texts as code here on discord

plain magnetBOT
#

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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

marble jackal
#

BTW, if you want to use quotes around your template (in the sinle line notation) make sure to use different quotes as you use inside your template

#

now you are using single quotes inside the template, so you should use double quotes outside the template

ember saffron
#

awesome worked!

marble jackal
plain magnetBOT
#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

marble jackal
#

wrong one

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

ember saffron
#

yes, but it could be useful in the future :9

silent flicker
#

Hello - https://i.imgur.com/G9pkb2l.png - I am trying to figure out how to get this state to display in my TEMPLATE without success. I tried

states.('sensor.openweathermap_condition')
#

well maybe i got it. is this the best way?

{{ states("sensor.openweathermap_condition") }}
silent flicker
#

You don't happen to know if it's possible to do math with timestamps? As in, taking two timestamps and subtracting them to figure out how much time has gone by.

marble jackal
#

yes, thats possible

#

but are you talkiing about a timestam (the number of seconds passed since 1/1/1970) or about a datetime?

silent flicker
#

I wanted to store the time when I ran an automation then the next time it ran, subtract it to see if 2 hours has gone by, for example

#

The idea is to prevent repetitive TTS events by limiting it to once every 2 hours by checking the time.

#

I could do epoch.... Is that possible?

#

That'd be easier then.

#
  1. Store epoch
  2. Reference it again and subtract it from old epoch. Then figure out how many hours that is.

Question is, how easy is it to obtain epoch to store it in a Helper?

plain magnetBOT
#

@celest plume I converted your message into a file since it's above 15 lines :+1:

#

@celest plume I converted your message into a file since it's above 15 lines :+1:

celest plume
#

Now I want to have a printed list of the state_attr object "id"

When I put in development templates.

{{ ['sensor.lijst_tankerkoenig'] | map('state_attr', 'stations') | list }}
#

I get printout of the the unique ID "stations"

[[{'id': '9be31084-fc9a-45a9-a198-31c469851006', 'name': 'Shell Selfkant Sittarder Str. 42', 'brand': 'Shell', 'street': 'Sittarder Str.', 'place': 'Selfkant', 'lat': 51.014235, 'lng': 5.901075, 'dist': 7.8, 'diesel': 1.979, 'e5': 1.949, 'e10': 1.889, 'isOpen': True, 'houseNumber': '42', 'postCode': 52538}, {'id': 'eabe4d46-f7c1-4192-92c5-4b5e02bd339f', 'name': 'Esso Tankstelle', 'brand': 'ESSO', 'street': 'SITTARDER STR. 59', 'place': 'SELFKANT', 'lat': 51.014555, 'lng': 5.902493, 'dist': 7.9, 'diesel': 1.979, 'e5': 1.949, 'e10': 1.889, 'isOpen': True, 'houseNumber': '', 'postCode': 52538}, {'id': '005056a9-779e-1ed9-8483-ceb40dd64399', 'name': 'star Tankstelle', 'brand': 'STAR', 'street': 'Landstraße', 'place': 'Selfkant', 'lat': 50.995313, 'lng': 5.923923, 'dist': 8, 'diesel': 1.959, 'e5': 1.939, 'e10': 1.879, 'isOpen': True, 'houseNumber': '4', 'postCode': 52538}, {'id': '90d06430-885a-4ef2-9e6e-b55080f9eb14', 'name': 'Shell Selfkant-Suesterseel Suestrastr. 63', 'brand': 'Shell', 'street': 'Suestrastr.', 'place': 'Selfkant-Suesterseel', 'lat': 50.996571, 'lng': 5.937555, 'dist': 8.9, 'diesel': 1.969, 'e5': 1.989, 'e10': 1.929, 'isOpen': True, 'houseNumber': '63', 'postCode': 52538}]]
#

But when I ad the object 'id' to it ..

{{ ['sensor.lijst_tankerkoenig'] | map('state_attr', 'stations', 'id') | list }}

I get a error

TypeError: state_attr() takes 3 positional arguments but 4 were given

Tried to google the error but allot noice to filter 😉
Perhaps someone can help me in here......
I keep searching myself also for the solution

Thanks again

marble jackal
#

Ad this as condition:

#
condition:
  - condition: template
    value_template: "{{ now() - this.attributes.last_triggered > timedelta(hours=2) if this.attributes.last_triggered else true }}"
silent flicker
#

Okay I can try that. If it doesn't work the way I need I can pursue the epoch thing then I guess.

marble jackal
celest plume
#

omg are you a template guru ?
I cant thank you enough...
I learn from it......

marble jackal
#

You were making it far too complex 🙂

celest plume
#

yeah I noticed , need to learn i see 😉

astral axle
marble jackal
#

BTW, you should also add default to the float filter (eg float(default=0)) to avoid errors when the sensor is not available, eg during startup

#

or add an availability template to the sensor

astral axle
#

Thank you, and how do I incorporate that into my configuration.yaml?
Do I add it as a second platform: template? (how do I make the code look as nice as you did in the message?)

sensor:
  - platform: systemmonitor
    resources:
      - type: memory_use_percent
      - type: memory_free
      - type: processor_use

  - platform: template
    sensors:
      temperature:
        friendly_name: "Gästrum temperatur"
        unit_of_measurement: '°c'
        value_template: "{{ state_attr('climate.mill_oil', 'current_temperature') }}"```
celest plume
#

try this...

  - platform: template
    sensors:
      temperature:
        friendly_name: "Gästrum temperatur"
        unit_of_measurement: '°c'
        value_template: >-
          "{{ state_attr('climate.mill_oil', 'current_temperature') }}"
#

i'm a newbie.... so better to wait for @marble jackal

#

The code worked perfectly.
Can I put inside a kind of filter directly or do I need to make a sensor first?

marble jackal
#

sorry, what kind of cleanup are you trying to do

celest plume
#

from

['9be31084-fc9a-45a9-a198-31c469851006', 'eabe4d46-f7c1-4192-92c5-4b5e02bd339f', '005056a9-779e-1ed9-8483-ceb40dd64399', '90d06430-885a-4ef2-9e6e-b55080f9eb14']

to

9be31084-fc9a-45a9-a198-31c469851006,eabe4d46-f7c1-4192-92c5-4b5e02bd339f,005056a9-779e-1ed9-8483-ceb40dd64399,90d06430-885a-4ef2-9e6e-b55080f9eb14

So remove all accept the , between the values

To use as variable inside other Sensor 😉

marble jackal
celest plume
#

ok wow......

#

I cant find this sollutions on the net that fast

#

🙂

marble jackal
#

you can add it as a second sensor:

  - platform: template
    sensors:
      temperature:
        friendly_name: "Gästrum temperatur"
        unit_of_measurement: '°c'
        value_template: "{{ state_attr('climate.mill_oil', 'current_temperature') }}" 
      your_new_sensor: #replace with something more relevant
        friendly_name: "Some name" #replace with something more relevant
        unit_of_measurement: 'whales' #replace with something more relevant
        value_template: "{{ 'bla' }}" #replace with something more relevant
astral axle
#

thank you very much @marble jackal and how to you make your code look pretty like that?

plain magnetBOT
#

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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

celest plume
#

damn, I learned now to restart the system core
when you made allot changes 😉

formal ember
#

hi all. i am absolutely lost. i am trying to make an automation that switches energy tariffs based on time of day and season. I found one here that kind of hits it, but I need an additional season and additional tariff. https://community.home-assistant.io/t/power-tarrif-configuration-by-season-and-time/384819/2?u=beasthouse

My energy is metered as per Residential Customers - Seasonal Time of Use Definitions at this link - so needs Summer, Winter and Shoulder seasons, as well as Peak, Offpeak and Shoulder Tariffs switching dependant on those seasons https://www.ausgrid.com.au/Your-energy-use/Meters/Time-of-use-pricing

Any absolute template wizards able to assist?

marble jackal
plain magnetBOT
celest plume
#

Well I did, But sometimes it produces to much sensors...
When I restart the core... all work ok... suddenly

#

I also use the ' C' button to reload

marble jackal
formal ember
#

Summer = 1 Nov - 31 Mar inclusive
Winter = 1 June - 31 Aug inclusive

During these months there is 3 tariffs, Peak, Off-Peak and Shoulder

All other times there is Off-Peak and Shoulder

#

Summer

Off-Peak 10pm-7am
Shoulder 7am-2pm and 8pm-10pm
Peak 2pm-8pm

Winter

Off-Peak 10pm-7am
Shoulder 7am-5pm
Peak 5pm-10pm

All other times

Off-Peak 10pm-7am
Shoulder 7am-10pm

#

I have created a utility_sensor that has the three tariffs and there is a select entity for it, not sure if that is much use though?

#
- sensor:
    - name: "Tariff Price"
      unique_id: 468b81e7-1026-45d8-84c8-ced58a2ffeb5
      unit_of_measurement: AUD
      state: >
            {% if is_state('utility_meter.monthly_energy', 'peak') %}
                {{ 0.4940 }}
            {% elif is_state('utility_meter.monthly_energy', 'shoulder') %}
                {{ 0.2383 }}
            {% elif is_state('utility_meter.monthly_energy', 'offpeak') %}
                {{ 0.2219 }}
            {% endif %}

Created this too for the different tariffs

formal ember
marble jackal
#
{% set now = now() %}
{% set summer = [ 11, 12, 1, 2, 3] %}
{% set winter = [ 6, 7, 8 ] %}
{% if today_at('07:00') < now < today_at('22:00') %}
  {% if (now().month in summer and today_at('07:00') < now < today_at('22:00'))
      or (now().month in winter and today_at('17:00') < now < today_at('22:00'))
  %}
    Peak
  {% else %}
    Shoulder
  {% endif %}
{% else %}
  Off-Peak
{% endif %}
mighty ledge
#

why even bother with the name, just use that as the Tariff Price

marble jackal
#

okay, good point 🙂

#

theoretically there could be an issue with the template above if it starts rendering at 21:59:59.999 or something similar and then ends up as none

formal ember
#

also, cheeky pricks think its summer for 5 months.... so they can milk that 49 cents / kWh

marble jackal
#

not anymore this way

formal ember
#

I put it into the Template editor and got TemplateSyntaxError: expected token 'end of statement block', got '{'

mighty ledge
#

you didn't put the multiline notation in

marble jackal
#

no, I forgot %} after defining winter

mighty ledge
#

you must have ninja edited it

marble jackal
#

jinja-edited

formal ember
mighty ledge
#

no take backs

formal ember
#

What if i take back my take back?

mighty ledge
#

you can't because no take backs

#

it supersedes taking back

formal ember
#

too many take backs for me now...

#

ok so how does that template then work in an automation?

mighty ledge
#

well that's the thing

formal ember
#

and then able to bring the right price into the energy dashboard?

mighty ledge
#

you probably just want to make it output the price instead of the names, and use that as your utility meter sensor

formal ember
#

slowly getting pieces of the puzzle identified, yet to put them together

#

oh

mighty ledge
#

then again, I don't use utility meter so I coudl be wrong on how it behaves

#

I should probably put that on my list of things to play with

formal ember
#
 state: >
        {% set now = now() %}
        {% set summer = [ 11, 12, 1, 2, 3] %}
        {% set winter = [ 6, 7, 8 ] %}
        {% if today_at('07:00') < now < today_at('22:00') %}
          {% if (now().month in summer and today_at('07:00') < now < today_at('22:00'))
              or (now().month in winter and today_at('17:00') < now < today_at('22:00'))
          %}
            0.4940
          {% else %}
            0.2383
          {% endif %}
        {% else %}
          0.2219
        {% endif %}
marble jackal
#

you could also use it like this, and trigger on state changes to change the select to the corresponding option

formal ember
#

so like that

#

any benefit to either option?

hexed laurel
#

Hello all I am not good with templates at all. Is there is there a way to return place or address in a attribute of an entities card depending on if the "place" of life360 is null?

marble jackal
#

depends, If you want to use it for a price sensor for your Energy dashboard, the one resulting in the price will be fine

formal ember
marble jackal
#

wait

#

Do you have one sensor providing you with your energy usage?

formal ember
#

then would not need so many different sensors and automations.... if that works...

#

yes I do

marble jackal
#

so only one

formal ember
#

my import sensor?

#

well

#

import sensor
export sensor
solar generation sensor

marble jackal
#

and you use utility meter to split it in 3?

formal ember
#

yeah, split the import sensor into the three different tariffs

marble jackal
#

Well, basically, you can use either the singe one consumption entity for the Energy dashboard, and use a dynamic price entity to get the right costs shown

formal ember
marble jackal
#

or you use the utility_meter, to spit in in 3 seperate sensors, and use that for the Energy Dashboard, and use fixed prices per energy rate

formal ember
#

nice to have options

marble jackal
#

if you use 3 different sensors, you cal also see which tariff was used

#

like this

formal ember
#

ah yep. 3 different sensors, only one of them is pertinent to these tariffs tho

#

ohh right

marble jackal
#

there is a slight color difference

#

you will have 3 (in summer and winter)

formal ember
#

is that how you run it?

marble jackal
#

no, my energy meter already provides two different sensors for peak and off-peak, so I don't need to use utility meter for that

formal ember
#

ohh cool. is it from the energy company?

marble jackal
#

yes, it's a smart meter

#

BRB

formal ember
#

i got one of those, but no way to tap into it or anything, so had the solar smart meter installed

#

whenever you get back (i am gonna head to bed soon) - is there a way to somehow include the daily connection fee to your energy dashboard? or record the daily cost somehow another way?

marble jackal
#

But anyway, what you can do

  • create the utility meter config with the 3 different rates (I think you already have that now)
  • create the template sensor to determine the right tariff for the time of day
  • create an automation to select the corresponding option in the select entity created by the utility meter integration
  • use the 3 separate sensors for the Energy dashboard, and add the corresponding price to each sensor (or also create the template sensor with the price, and use that sensor for all 3)
ashen pecan
#

Hi!
I have a template that outputs a datetime as follows: 2022-11-17T02:00:00+01:00, it is formatted with isoformat().
When i try to print this as a label in a custom button i get the time as 01:00:00, shouldn’t this become 03:00:00?

marble jackal
#

this datetime is indicates it was 2:00, and that the timezone was GMT+1

#

Which means it was 1:00 UTC

marble jackal
cold ibex
#

Is there some way I can look through all of the different mdi: icons?

dull burrow
#

Patch notes say which ones are currently added

cold ibex
#

I would have thought there was some way exposed from within home assistant

inner mesa
#

There is not. There's a nice Chrome extension, though

ashen pecan
marble jackal
#

what does the diagram show then?

ashen pecan
marble jackal
#

Share the template you are using

#

But that actually indicates the result is indeed in UTC

ashen pecan
formal ember
marble jackal
#

The post you now reply on doesn't contain different options. It was a 4 step approach 😅

sturdy juniper
#

I have a sensor that shows charging time left for our EV
Is there a way I can create a template sensor that calculates current time + charging time left to show expected finishing time ?

marble jackal
#

Sure

sturdy juniper
#

I've tried
"{{((states('sensor.time'))) + ((states('sensor.tmbxxxxxxxxxxxxxx_charging_time_left')))}}"

marble jackal
#

Not like that

sturdy juniper
#

but that does not seem to work not unexpectedly .. 😆

marble jackal
#

What is the state of this time left sensor

sturdy juniper
#

13:15 h

marble jackal
#

Okay, like that, including the h

#

And what if it's less then an hour?

sturdy juniper
#

hmm, not sure

#

gimme a sec

#

allways like that, also when its 24hrs+

sturdy juniper
#

eg, 32:20 h or 00:40 h

marble jackal
#
{% set time_left = states('sensor.time_left').split(' ')[0] %}
{% set h, m = time_left.split(':') | map('int') %}
{{ now() + timedelta (hours=h, minutes=m) }}
sturdy juniper
#

🙇‍♂️

formal ember
marble jackal
#

Yes

formal ember
#

I’ll see if I can figure it out!

formal ember
mighty ledge
#

{% set now = now() %} -> get current time
{% set summer = [ 11, 12, 1, 2, 3] %} -> Make a list of months by their number
{% set winter = [ 6, 7, 8 ] %} -> make a list of months by their number
{% if (now().month in summer and today_at('07:00') < now < today_at('22:00') if today_at('07:00') < now < today_at('22:00') %} -> If the time is between 7 am and 10 pm
{% if (now().month in summer and today_at('07:00') < now < today_at('22:00')) -> if this is a summer month and we are between 7am and 10pm
or (now().month in winter and today_at('17:00') < now < today_at('22:00')) -> Or if this is a winter month and we are between 5pm and 10 pm
%} -> end the previous if statement
0.4940 -> output 0.4940
{% else %} -> otherwise
0.2383 -> output 0.2383
{% endif %} -> end the matching if
{% else %} -> if we arent between 7am and 10pm
0.2219 -> output 0.2219
{% endif %} -> end the matching if

#

@formal ember ^

formal ember
#

that Petro, trying to understand everything and get the automation to change the price going

mighty ledge
#

if you read the code, it reads almost exactly like what I'm saying

#

there is no automation to change the price

#

it will change the price depending on the minute of the day

#

it's a template that self calculates

#

no automation needed.

formal ember
#

oh? thought Fes said I had to

#

It has not worked too well today - the tariff stayed at the rightprice until 7am this morning, great. then it went to 0/unavailable - then at 10pm this evening (23 mins ago) it kicked back in to the offpeak price

mighty ledge
#

it should have been 0.2383 at 7am

formal ember
#

yeah, it did not change, just disappeared, from what I can see in the history of the entity anyway]

#

and my figures for today are too cheap to believe (thats what made me do some digging)

mighty ledge
#

hmm, it looks like you will need an automation

#

they force you to have an automation change the times of day, you can't feed it a sensor

#

I'd have to look into utility meter more

#

I'm not getting enough info out of the documentation

formal ember
#

ah right. I did find one that is a starting point I would think, but to be honest, I am not sure

plain magnetBOT
#

@formal ember I converted your message into a file since it's above 15 lines :+1:

formal ember
#

woops

#

but i think my tariffs are a bit more complicated that this guys was

mighty ledge
#

if you have to use the select, then you'd want to go back to the original template that hadd the words

#
 state: >
        {% set now = now() %}
        {% set summer = [ 11, 12, 1, 2, 3] %}
        {% set winter = [ 6, 7, 8 ] %}
        {% if today_at('07:00') < now < today_at('22:00') %}
          {% if (now().month in summer and today_at('07:00') < now < today_at('22:00'))
              or (now().month in winter and today_at('17:00') < now < today_at('22:00'))
          %}
            peak
          {% else %}
            shoulder
          {% endif %}
        {% else %}
          off-peak
        {% endif %}
#

then your automation woudl just be

#
alias: Set Electricity Tariff
description: ''
trigger:
- platform: state
  entity_id: sensor.electricity_tarriff
  not_to:
  - unavailable
  - unknown
action:
- service: select.select_option
  target:
    entity_id: select.electricity_imported_power_daily
  data:
    option: "{{ trigger.to_state.state }}"
#

@formal ember ^

formal ember
#

testing out now, thanks!

formal ember
#

alright and which entity should I be using in the energy dashboard for price? input_number.electricity_tariff?

#

so confused i really should clean up the other entities i created haha

marble jackal
#

So you can see by the color which tariff was used

#

ah, should have read all before replying

formal ember
#

haha was gonna say like the one petro wrote for me?

marble jackal
#

yep

formal ember
#

alright will see how it goes tomorrow

marble jackal
#

for the tariff you can create a separate template sensor like petro did which just shows the active tariff

formal ember
marble jackal
#

or you can just assign a static price to in the Energy dashboard for the 3 utility meter sensors

formal ember
#

thats the three i have now, automation, the value and the tariff type

marble jackal
#

I would just use the same template sensor but then resulting in the price instead of the word

formal ember
#

that was not working

marble jackal
#

why not?

mighty ledge
#

I don't know enough about utility meter to suggest a proper route

#

he was claiming that it went to 0/unavail @ 7am

#

which i'm not sure how that's possible looking at the code

formal ember
#

yeah it just dropped off, came back on at 10pm when off peak started again

marble jackal
#

isn't shoulder starting at 10pm?

#

I also don't see a reason why that would happen

#

well, you can also use the input_number and add it to the automation

formal ember
#

nah shoulder is like 8-10pm

plain magnetBOT
#

@marble jackal I converted your message into a file since it's above 15 lines :+1:

#

@marble jackal I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

whoops, forgot to remove some text:

{% set now = now() %}
{% set summer = [ 11, 12, 1, 2, 3] %}
{% set winter = [ 6, 7, 8 ] %}
{% if today_at('07:00') < now < today_at('22:00') %}
  {% if (now().month in summer and today_at('14:00') < now < today_at('20:00'))
      or (now().month in winter and today_at('17:00') < now < today_at('22:00'))
  %}
    peak
  {% else %}
    shoulder
  {% endif %}
{% else %}
  off-peak
{% endif %}
#

this one has the correct time for peak in summer, the other one didn't (forgot to adjust it)

marble jackal
formal ember
formal ember
marble jackal
marble jackal
#

what are the action options of the select entity?

formal ember
#

its a slider of the price, from 0.2219 - 0.4940 in 0.0001 increments

marble jackal
#

no

#

the select entity, not the input_number

formal ember
#

ah from utility_meter entity?

marble jackal
#

okay, so without an -

formal ember
#

ah got it haha

#

how can I test it?

marble jackal
#

in that case, remove the - from the template in for the input_number (so off-peak becomes offpeak) and also remove it in the template sensor

formal ember
#

done

#

off topic for this channel but seems as soon as the solar cuts off, the import export also just disappears in the dashboard https://imgur.com/b9xEaGM

marble jackal
#

reloading template sensors should proably trigger the automation

#

I don't see a relation between the solar production and the missing data for consumption in that screenshot

#

from 6 - 9 there is production, but no consumption

formal ember
#

8pm

#

should be way more consumption too during the night

#

i have a dell server running 24/7

marble jackal
#

I see that there is an issue here, but I don't see a relation with the solar production

#

did you add all 3 utility meter sensors to the Dashboard?

formal ember
#

yeah, solar generation, import and export

marble jackal
#

no, all 3 import sensors generated by the utilty meter integration, one for each tariff

formal ember
#

oh no...

#

I used Use an entity with current price

marble jackal
#

I 'm not talking about price

#

I'm talking about the entities providing the kWh values

#

the utility_meter integration provides 3 sensors, one for each tariff

formal ember
#

oh....

#

and add each as an import sensor?

marble jackal
#

correct

#

because only the relevant one based on this select entity will acutally increase

#

if the select is set to eg shoulder, the peak and offpeak sensors will not change, but the shoulder one will (if you consume energy that is)

formal ember
#

so i don't think we created entities that produce a kWh value based on the peak

marble jackal
#

which sensor is added now as an consumption sensor to the dashboard

formal ember
#

just the one from my inverter

#
daily_energy:
  source: sensor.solaredge_m1_imported_kwh
  cycle: daily
  tariffs:
    - peak
    - offpeak
    - shoulder
#

thats what I set up in utility_meter

#

so if i add those, say sensor.daily_energy_offpeak, what cost do I use to track?

#

static price i guess

thorny snow
#

Hi, I'm trying to add a sensor to get the temperature from the climate entity, but it's not showing up. Any ideas what I'm missing? Very new to this, so sorry if it's a stupid question

  - name: "thermostaat_temperatuur"
    unit_of_measurement: '°C'
    value_template: "{{ state_attr('climate.vaillant_vsmart_07_00_00_1b_48_36', 'current_temperature') }}"```
mighty ledge
#

where are you putting that?

thorny snow
mighty ledge
#

and how is templates.yaml defined in configuration.yaml?

thorny snow
mighty ledge
#

ok, so change value_template to state

thorny snow
#

Thanks a lot, that did the trick! What's the difference between the two? In the example, they used value_template.

lethal locust
#

was for sensors: 😄

mighty ledge
marble jackal
# formal ember static price i guess

a static price per sensor, the input_number, the price according to the template sensor (if it would work). That doesn't really matter actually

young shadow
#

Hi!
Please help me set up an mqtt binary sensor: ```yaml

  • state_topic: "akos-notebook/display-connected"
    payload_on: "true"
    payload_off: "false"
    name: Akos external display
    value_template: "{% if is_state('binary_sensor.akos_notebook','on') %}{{ value }}{% else %}false{% endif %}"```
    if the notebook is on, then take the payload on the mqtt topic (can be true/false) and use it as the sensor's state, if the notebook is not on, then be false, so off.
#

the problem is that the sensor doesn't turn off if the notebook is off

formal ember
mighty ledge
#

you need to make a template binary sensor using the values from notebook being on and display connected

#
- state_topic: "akos-notebook/display-connected"
  payload_on: "true"
  payload_off: "false"
  name: Akos Display Connected
  value_template: "{{ value }}"

and

template:
- binary_sensor:
  - name: Akos External Display
    state: "{{ if is_state('binary_sensor.akos_notebook','on') %}{{ states('binary_sensor.akos_display_connected') }}{% else %}false{% endif %}
young shadow
#

😭 that's what I wanted to avoid, I wanted to keep it in a single sensor. But as I see I will have to go wit a template.. thanks for the hint!

formal ember
mighty ledge
#

(I did it too)

dapper aurora
#

Trying to pull the precipitation amount in HA to check if > 0 - Any advice?

{{ is_state_attr('weather.home','forecast')[0].precipitation|float, '0' }}

mighty ledge
#

remove is_, change |float, '0' to > 0

dapper aurora
formal wave
#

Is it possible in an automation to read the state of one device and use it as the target value for another device?

mighty ledge
formal wave
#

the line between those is somewhat blurry for me as pretty much every device has entities doesn't it?

mighty ledge
#

Yes, every device has entities

#

device actions do not support templates, and that's a requirement to do something like this

#

call service supports templates

warm elbow
#

How to list the states of a device? I want to create a binary sensor template for the HVAC mode of my TRV

formal wave
mighty ledge
#

templates in general are not supported in the UI, you have to switch to yaml for those

formal wave
#

ok, that's where I've been getting stuck then... didn't seem supported... will try my hand at the yaml

mighty ledge
mighty ledge
#

ok then, just use the entity

warm elbow
#

Like this?

template:
  - sensor:
    - name: Heizung Wohnzimmer an
      state: "{{ state_attr{'climate.thermostat_wohnzimmer_zha' 
}}}"
#

I don't see thow this will give me a binary sensor

mighty ledge
#

well, you have to build the logic

#

you're using state_attr but you aren't providing an attribute

#

you're not using () for the function, you're using {}

#

you're also creating a sensor and not a binary_sensor

warm elbow
#

Yeah online they had something like 'hvacmode.cool', but I don't know if I have that

#

So how to list the attributes?

mighty ledge
#

you have to find out what your climate device supports by looking at the attributes when it's in the mode you're looking for

#

develop tools -> states

warm elbow
#

Ah yes

#

Didn't know that

#

Here

hvac_modes: off, heat
min_temp: 5
max_temp: 30
current_temperature: 23.7
temperature: 30
system_mode: [<SystemMode.Heat: 4>]/heat
occupied_heating_setpoint: 3000
friendly_name: Thermostat Wohnzimmer
supported_features: 1
#

Guess system_mode is what I'm looking for

formal wave
#

perfect, thank you state_attr appears to do exactly what I want

warm elbow
#

But it's a string

#

Do I have to work with an if clause now?

mighty ledge
#

you can if you want, otherwise you don't have to, it's implied

warm elbow
#

Doesn't work though. I have this now

template:
  - sensor:
    - name: Heizung Wohnzimmer an
      state: "{{ states('climate.thermostat_wohnzimmer_zha') }}"
    - name: Heizung Schlafzimmer an
      state: "{{ states('climate.thermostat_schlafzimmer_zha') }}"
    - name: Heizung Badezimmer an
      state: "{{ states('climate.thermostat_badezimmer_zha') }}"

It doesn't give me a binary sensor though

#

I want to plot this in Grafana, so I guess strings won't work

mighty ledge
#

becaues you're putting it in the sensor section. Also, binary sensors require true/false responses. You should be checking the state vs a value you expect it to be

#

when I said it was implied, I meant you don't have to write if ....

warm elbow
#

So what do I have to write.? I don't get it

#

I would I assume I would have to strip the "heat" from the system_mode somehow and evaluate that

mighty ledge
#

how do you check an attribute is a value?

#

how do you check a state is a value?

warm elbow
#

I guess with this Jinja2 syntax

mighty ledge
#

I recommend cruising through the template docs

#

is_state_attr checks attributes

#

is_state checks the state

warm elbow
#

Already there

mighty ledge
#

you can see what current attributes are by getting them by using state_attr

#

fyi hvac_mode is most likely the attribute you want.

#

well apparently you don't have that, which is odd

inner mesa
#

That's the state

mighty ledge
#

righto

warm elbow
#

So now I have to check that

#

Yes, got it. Thanks

#

Sometimes you just need a basic example and where to check that

mighty ledge
#

the doc's have those basic examples

#

there's an entire page and section dedicated to states, state_attr, is_state, and is_state_attr

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

young shadow
#

I would like to create a template sensor, and it's value should be a sum of other numeric sensors, and they should be selected by a regular expression, so if new sensors pop up, they would be added to the sum template sensor too.

Is this possible? Or is there a better way?

mighty ledge
#

I usually create an oldschool group via an automation with group.set on startup (you can also just run the actions of the automation). Then use that group with expand in your template sensor.

#

There's no 'new entity added' event, so there's no way to detect when a new entity is added. So you basically have to rely on a periodic update or manual update

marble jackal
mighty ledge
#

that's trottled though

#

I like to have instant updates

#

but yes, I get ya

marble jackal
#

Maybe create one for each domain, then the groups are op to date within a second after the entity is created

fading bear
#

Hello all, I've got a scrape sensor which gives me the name and date of the next bin collection, and I'm trying to turn it into a sensor (or two) which I can automate from. I've looked into this a few times and never managed to work out how to correctly translate the line of text i have into actual times/statuses. Anyone able to give me a hand?

ivory harbor
#

I'm trying to write a template for an automation to see if a sensor's numeric value increases (by any amount) and Im rather stuck

fading bear
#

so ideally i'd like a sensor which tells me which bin (which can just be text) but i'd like the date to actually be something i can interact with, so an actual datetime

ivory harbor
inner mesa
ivory harbor
#

I'm not the best and templating, but I believe you can treat that text as an array and then parse it out. For example the first element [0] is WASTE

ivory harbor
#

cool, didnt know there was a from and to state

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

inner mesa
#

last link in the first paragraph

mighty ledge
inner mesa
#

not this part:

fading bear
mighty ledge
#

so the difficulty is that your string doesn't have a year

#

and as stupid as that sounds, you can make this work, but if you happen to be on a separate year from when you have to take out the trash, it's not going to work

fading bear
#

I think I can probably live with the annual confusion

mighty ledge
#

and 'detecting that' will be a pita

#

ok

#

@fading bear this is for the date

#
{% set value = states('sensor.scrape') %}
{% set date = value.split(' ')[-3:] | join(' ') ~ now().year %}
{% set date = strptime(date, '%A %d %B%Y', default=today_at()) | as_local %}
{{ date }}
#

{{ states('sensor.scrape').split(' ')[:-3] | join(' ') }}

#

for the other half

ivory harbor
ivory harbor
mighty ledge
#

@fading bear I wouldn't recommend doing the calc in the scrape sensor because you'd have to scrape twice as much

#

make template sensors

fading bear
#

yeah i planned to make two template sensors which reference the original scrape

#

so we've basically chopped out the date, added the current year on the end, and then turned it into a time, displaying it as local time

fading bear
ivory harbor
#

i also wonder if the webpage you are scraping has any kind of 'last updated' field where you could scrape year and then join it

fading bear
#

it's a UK council webpage, the less it is relied on the better

#

I'm genuinely shocked every week to find that the scrape still works at all

mighty ledge
#

I wish my garbage people had a page I could scrape

#

they do, but I have to fucking log in

#

aka, no scrape

fading bear
#

yeah my local council is ok for this, the URL you go to never changes

#

i tried to do it for someone else but their URL has to contain the current date and time just to get the page to load

ivory harbor
#

one more template question ... I'm trying to use the value of a sensor as the max for a gauge ... I'm using max: {{ states('sensor.big_sky_acres_total') | int }} but that throws an error

#

We support (number) but received ({"[object Object]":null})

#

in the template editor that returns the right number

inner mesa
#

looks like you tried to use a template where it isn't supported

ivory harbor
#

ah, was hoping I could just drop it in

formal ember
fading bear
formal ember
#

He did say it’s the first time he’d installed one. He spent the day prior reading about the system and was very knowledgeable- I guess everyone makes mistakes!

inner mesa
#

I expect that electricians are more concerned with what's code-compliant

formal ember
inner mesa
#

which way clamps are supposed to be installed is probably at or below the bottom of the list of things they care about

formal ember
#

Although that’s pretty basic surely

formal ember
#

Found it - no CT on two of the phases

sacred sparrow
#

if I want NOT for each one can I just do:
{{ not is_state('climate.mitsubishi_hvac', 'off') or is_state('binary_sensor.living_room_warmed_up', 'on') or is_state('light.bathroom_lights_main','on') or is_state('light.shower_lights_smartplug', 'on') }}
or do I have to put "not" for everyone:
{{ not is_state('climate.mitsubishi_hvac', 'off') or not is_state('binary_sensor.living_room_warmed_up', 'on') or not is_state('light.bathroom_lights_main','on') or not is_state('light.shower_lights_smartplug', 'on') }}

inner mesa
#

just read it like a sentence

#

no need to overthink it

sacred sparrow
#

I would say its a first one then but that doesnt seem right

inner mesa
#

you're right, it doesn't

#

there's nothing about that syntax that says that it distributes to the others as you showed in the second

#

if you just want to check for the opposite, then just do that rather than negating the result

#

A binary_sensor can only be "on" or "off"

#

same with a light

#

unless you're trying to catch "unavailable" or something. like that

#

generally, if the logic seems overly complex, it's often needlessly complex

sacred sparrow
#

is there another way to check for the opposite

#

{{ not is_state('climate.mitsubishi_hvac', 'off') or not is_state('binary_sensor.living_room_warmed_up', 'on') or not is_state('light.bathroom_lights_main','on') or not is_state('light.shower_lights_smartplug', 'on') }} is the one that works

#

I don't know how to make it less complex

inner mesa
#

get rid of all but the first "not" and just check for the thing you actually care about

#

what are you trying to achieve with not is_state('light.shower_lights_smartplug', 'on')?

#

to see if it's "off"?

sacred sparrow
#

yes

inner mesa
#

then do that 🙂

sacred sparrow
#

very true!

inner mesa
#

only the first one is more complicated

sacred sparrow
#

I just copied the wait template from above in my automation and put nots in the front of it haha

fossil venture
#

There's also a boolean law that may simplify things. Not A or Not B or Not C == Not(A and B and C)

#

That's from memory though. So look it up to confirm.

inner mesa
#

yes, the syntax could be changed to actually distribute the "not", but I'd start with trying to simplify it

sage aurora
#

How can I get the specific forecasted temperature in 4 hours? I am trying {{ states.weather.gatineau_hourly_forecast[1] }} in the developer console, I get UndefinedError: homeassistant.helpers.template.TemplateState object has no element 1. This is my data : https://pastebin.com/rYYNR6bS

#

Ah, got it going with {{ state_attr('weather.gatineau_hourly_forecast', 'forecast')[4] }}

#

For 4th element.

inner mesa
#

The fifth, actually

sage aurora
#

value_template: '{{ state_attr('weather.gatineau_hourly_forecast', 'forecast')[4] }}'

#
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 95, column 7
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 96, column 30
inner mesa
#

You used the same type of quote inside and out

sage aurora
#

Heh, woops 🙂

thorny snow
#

I'm not sure this is doable in a template, but I'd like to extract a number from a string, like I want to get "42" from "binary_sensor.valve_opened_42". Could you give me a hint on this?

marble jackal
thorny snow
#

Very elegant, thanks a lot!

#

Can I use it as a filter?

marble jackal
#

If it's not always the last part, but there is always just one part with a number you can also use

{% set value='binary_sensor.valve_opened_42' %}
{{ value.split('_') | select('is_number') | first }}
#

You can't use split as a filter

thorny snow
#

Thanks, I'm gonna try it out right now.

#

Just a short one: can you reload template sensors without restarting HA?

mighty ledge
#

dev tools -> yaml page

thorny snow
#

Sure, sorry for the dumb question.

clear mist
#

Hey guys, what am I doing wrong with the automation?

http://pastie.org/p/4mMzS2bXolcSLz3EIpKE9L

I'm trying to get the attribute value of media_player.tv_google_cast and if 'media_title' is not none, it should send me a notification

Unfortunately for some reason this doesn't work when it's an automation - there's no trace or anything for it, but when I do the the code in the {% %} bits in the developer template section, it evaluates to true?

Sorry if this is basic, I've never used this before for automations

mighty ledge
#

{% if media_title is not none %}

#

what's the point of tv_state if you aren't going to use it too?

clear mist
#

Ah, I thought it was a string so it'd work as that - will give it a shot!

mighty ledge
#

also, that will only trigger when the template changes from false to true. If you get new media, it will not trigger again if media is already there.

clear mist
#

And I want to do an and statement for tv_state but it wasn't working so was trying to figure out where things weren't working

mighty ledge
#

there's a template editor you can use to test things

clear mist
#

In the developer section?

mighty ledge
#

yep

clear mist
#

I used that and it evaluated to true when I had the code above

#

Hang, on, let me get a picture

mighty ledge
#

well yeah, but you didn't check when it was none 😉

#

the template will always tell y ou the outcome, it's up to the user to set the states on the objects to test the template in all scenarios

#

just because it's true during 1 test doesn't mean it works when the state has other values

clear mist
#

Ahhh, good point!

#

Thanks, that solved it!

#

I had the developer template section open when stuff was playing so it happened to be true anyway

sonic nimbus
#

why I cantr use template conditions with if-then

sequence:
  - if:
      - alias: "If frontdoor is unlocked"
        condition: > 
          "{{door == 'frontdoor' or door = 'all' and is_state('lock.nuki_front_door_lock', 'unlocked')}}"
    then:
      - alias: "Then lock frontdoor!"
        service: lock.lock
        target:
          entity_id: lock.nuki_front_door_lock
#

Ihave this error: Invalid config for [script]: Expected a dictionary @ data['sequence'][0]['choose'][2]['conditions'][0]. Got None Unexpected value for condition: '{{is_state('lock.nuki_front_door_lock', 'locked')}}'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone, a list of conditions or a valid template @ data['sequence'][0]['choose'][2]['sequence'][1]. Got None Unexpected value for condition: '{{is_state('lock.nuki_front_door_lock', 'unlocked')}}'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone, a list of conditions or a valid template @ data['sequence'][0]['choose'][2]['sequence'][0]. Got None. (See /config/configuration.yaml, line 63).

marble jackal
plain magnetBOT
#

@tropic stratus I converted your message into a file since it's above 15 lines :+1:

tropic stratus
#

(repost of last, long line that sums up the issue): The problem is that I need a set_value field, but the documentation is pretty vague on this point. It's required, but I have no particular actions I would want to take, and the documentation doesn't have an example.

marble jackal
#

The set_value is what will happen if you change the number entity

#

If you don't want that, an input_number might make more sense

tropic stratus
#

As in, create an Input Number, and then have an automation that calls set_value to 0 or 1 every time the binary sensor changes to 'on' or 'off'?

#

Seems kinda heavyweight, so I must be missing something.

#

Maybe not heavyweight, but circuitous?

#

I'm trying to get a numerical 0/1 representation of a binary sensor, so I can do averages.

inner mesa
#

how is that different from a regular template sensor?

tropic stratus
#

Maybe it's not -- should I be using sensor rather than number? I'm not familiar with the new template sensor configuration.

inner mesa
#

yes

tropic stratus
#

Ah. Thanks.

#

I am confused about what number is for, then -- but, perhaps I'll wait on that and see if it becomes need-to-know.

inner mesa
#

if you need the set_value functionality that you don't need

tropic stratus
#

Ah. ..which is effectively a function for munging the input to something based on the input, or for cleaning up the data, etc.

#

Makes sense.

In any case, thanks, using a regular sensor works for this purpose, as you said.

acoustic arch
#

is there a way to let a light return to its previous brightness after a motionsensor clears? Without setting a scene?

#
  1. motion detected
  2. save brightness somehow
  3. turn on light with higher brightness
  4. motion clears
  5. turn on ligh with previous brightness
#

whenever i use a scene i HAVE to set it to single run. Doing restart it will resave the scene at higher brightness rendering it useless.

buoyant pine
#

Sure, write the brightness to an input_number and reference it in step 5

acoustic arch
#

once i have written that text i had that brainwave. Im using text helper. will that work?

dusty hawk
#

I need a template that evaluates true upon the change in state of one sensor following the change in state of another sensor. Here's the idea (I know following is not a keyword):
{{ is_state("binary_sensor.indoor_motion", "on") -following- is_state("binary_sensor.at_home", "on") }}
Is there a way to do this?

marble jackal
plain magnetBOT
acoustic arch
#

else when restart in choosen it resaves the scene on wrong value

marble jackal
#

You don't need restart

#

Use a wait (for trigger) to wait for the motion to clear

acoustic arch
#

but when it clears it starts a delay due to motionsensor not reacting.

#

then when returning in that timeframe its already too late and light turning dim

#

and no refire of motion

marble jackal
#

You lost me, but you can always go for the input_helper or input_texr

acoustic arch
#

i think thats a neat way to get what i want

#

;0

#

🙂

#

anyway. bedtime. weltrusten

#

and thx

silent seal
#

Why not add a delay on the trigger?

#
automation:
  trigger:
    - platform: state
      entity_id:
        - binary_sensor.fuzzyduck_motion
      # Optional
      from: "on"
      to: "off"
      for:
        hours: 0
        minutes: 3
        seconds: 0
marble jackal
#

Or on the trigger in the wait_on_trigger

dusty hawk
dusty hawk
#

Its been fun building a script for the tts engine that reports a number of timely metrics.

silent flicker
# marble jackal Ad this as condition:

i think based on my needs. i need to store the time in a helper and reference it later to do some math with it. is that possible to do? i figure i would need something other than just storing now() to a Helper

inner mesa
#

as I mentioned elsewhere, you're describing an input_datetime

hollow mortar
#

I would like to do this, but it wont work:

{% set controllerx = state_attr('sensor.somesensor', 'controlleridx') %}
{{ states('binary_sensor.{{ controllerx }}_schema') }}
#

Does anyone know how to put {{ }} inside of {{ }}?

inner mesa
#

Not like that

#
{% set controllerx = state_attr('sensor.somesensor', 'controlleridx') %}
{{ states('binary_sensor.' ~ controllerx ~ '_schema') }}
hollow mortar
# inner mesa Not like that

Thanks! Was googling alot and couldnt find anything remote like what you wrote. Can you tell me a phrase so I can google more on this?

fickle kettle
#

Jinja string concatenation

hollow mortar
#

Thanks!

inner mesa
#

The links in the channel topic have lots of good info

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

hollow mortar
#

Yes I can see now, because I learned a new english (or programming) word "concatenate" 😛

#

I was googling like "{{ inside {{, curly inside curly, expression inside expression, nesting {{/curly/expressions" and most was rubish, other that would be maybe correct for me said not to do it... Like dont use inner {{ }}. Well whatever 😛 thanks for helping me, im really grateful and saving stuff like this to my own docs 😛

#

I have alot of sensors in my central heating system that are repeating and after 2 weeks of even more templating sensors, lovelace cards and stuff its getting quite stupid to catch myself on typos because of so much repeating sensors. Thats why Im now trying to make "grand daddy sensors" that will have attributes inside so I can "concatenate all sensors" or "group similar together" by changing only one string instead of 10s 😛

inner mesa
#

You fell into the trap of going straight to what you thought was the solution, rather than searching for what you actually wanted to do

hollow mortar
#

😄

#

Its working but after some time when I will forget how I did it, it will be easier to start from scratch then to learn this mess

#

Im now quickly googling "home assistant concatenate sensors" and cant find anything similar what im doing yet.

#

Or I am a genius after 2 weeks of templating or making even a bigger mess (which I doubt, it will be genius after its done)

#

Do you understand what Im trying to do, do you have anything similar in your setup or how did you tackle "problem" like this @inner mesa ?

inner mesa
#

You don't concatenate sensors, you're just forming a string that will be the sensor entity_id

#

Anyway, it sounds like you just want a template sensor

hollow mortar
#

Yes Im doing a "daddy template sensor"

#

"The main one for each branch on a tree"

hollow mortar
digital iris
#

I'm lost, hopefully someone can help. I need a template that subtracts 30 min from a time helper. Essentially, if the time helper is 7:00am, then the template will output 6:30am. Believe me when I say I have tried every help article out there about this topic. Seemingly so simple, but I have been racking at this for months.

#

I am tired, frustrated, and sad lol

#

if anyone can offer some wisdom or insight in this matter it would be greatly appreciated

sacred sparrow
#

how can I make it true if 'sensor.collingwood_extended_text_0' contains the word "cloudy"

#

I have

#

{{ 'cloudy' in states('sensor.collingwood_extended_text_0') }}

#

but its case sensitive

rare karma
#

I have a template sensor which I have to convert the power state from. Now, the template works but it's a hardcoded value it returns. Is there any way to have these On/Off values translated as if it's a default entity state? When using a binary sensor it gets the right on/off state, but it doesn't capitalize the first letter...

#

sensor:

  • platform: template
    sensors:
    kookplaat:
    friendly_name: Kookplaat
    value_template: >-
    {% if states('sensor.siemens_ex977lxv5e_68a40e7ca0c2_bsh_common_setting_powerstate') == 'BSH.Common.EnumType.PowerState.On' %}
    Aan
    {% else %}
    Uit
    {% endif %}
silent flicker
digital iris
silent flicker
#

oh boy, lol

#

are you trying to get the length of time in the difference? like say "2 hours"

digital iris
#

the opposite actually. I want to input a time difference like "2 hours" and have it subtract that from one time helper and add to another.

Example:
Input Wakeup time - 9:00am
Input Time difference subtraction - 30 min
Output Lights on time - 8:30am

marble jackal
silent flicker
#

if i have time in

input_datetime.openweathermap_condition_time

how do i mess around with it in TEMPLATE? i tried to put

{{ input_datetime.openweathermap_condition_time }}

but it didnt show me the timestamp

marble jackal
marble jackal
silent flicker
#

thx, ill test around with that and see how far i can go

marble jackal
#

Do you have time only, date only or both in your input datetime

silent flicker
#

if youre referring to me. i have date and time

#

ex: November 20, 2022 at 2:00 AM

marble jackal
#

Then you can convert them from string to a datetime using as_datetime

silent flicker
#

oh that puts it as a string? i missed that lol. yeah then i need to convert it for sure

#

woops

marble jackal
#

Do that with both, and you can subtract them

#

All states in Home Assistant are strings

silent flicker
#
{{ as_datetime(states('input_datetime.openweathermap_condition_time')) }}

like this

marble jackal
#

Yep, that will convert it to a datetime

silent flicker
#

hm. yeah i guess reading the doc on input_datetime, it didnt mention to use as_datetime so thats why i was clueless lol

marble jackal
#

Without timezone information though, so if you want to compare it to now() you need to add as_local as well

#

The docs don't cover using them in templates

silent flicker
#

oh. okay im starting to catch on. sorry its 6am for me ive been trying to crack this lol

#

okay so i did this:

{{ as_datetime(states('input_datetime.openweathermap_condition_time_2')) - as_datetime(states('input_datetime.openweathermap_condition_time'))}}

and it gives me the output

2:00:00

is there a way to make it always stay in hours? because if its more than a day, it will add make it

2 days, 2:00:00
#

i'd much prefer it so be 50 hours instead of 2 days, 2:00:00

#

then im sure i could do some sort of split with 50:00:00 to only get the 50 in a variable, then i could use that in a math calculation

marble jackal
#

{{ (as_datetime(states('input_datetime.openweathermap_condition_time_2')) - as_datetime(states('input_datetime.openweathermap_condition_time'))).total_seconds() }} will give the number of seconds, you can convert that to hours by dividing it with 3600

silent flicker
#

oh even better

#

i didnt know it was that easy

#

yeah that gives me 50.0

#

that beats doing .split(':')

marble jackal
#

split wouldn't work, as you have a timedelta as result. You'd first have to convert it to string then

silent flicker
#

and then convert away from a string if i want to see if its greater or less than a number too lol

#

yeah thats annoying

#

is there a command to tell what type of value something is? like to test if its a string, int, float, datetime

#

i know you can in other languages

marble jackal
#

{{ "whale" is string }}

#

If you want to check if the result subtracting two datetime objects is above a certain value, you can compare it to another timedelta:
{{ datetime1 - datetime2 > timedelta(hours=50) }}

silent flicker
#

ahh i see

#

ty

#

woohoo finally

{{ ((as_local(now())- as_local(as_datetime(states('input_datetime.openweathermap_condition_time')))).total_seconds())/3600 }}

definitely not confusing

silent flicker
#

is there an easy way to test a state for multiple ORs?

if:
  - condition: state
    entity_id: sensor.openweathermap_weather
    state: few clouds OR snow OR rain
marble jackal
#

{{ states('sensor.openweathermap_weather') in [ 'few clouds', 'snow', 'rain' ] }}

silent flicker
#

Ooo thank you. This is a struggle to relearn lol

steep temple
#

Is it possible to style a piece of text based on the results of a template condition? For example .... {% if states.binary_sensor.somesensor.state is defined %} somesensor is HERE! {% else %} <style="color:red;">somesensor is NOT HERE!</style> {% endif %} I know this is not the correct method to do this it's just an example of what I'd like to do. Is this possible?

marble jackal
steep temple
steep temple
#

is there any way to loop thru all my devices that are reporting a battery level and print the values?

inner mesa
#

There's not really a consistent method of reporting that. It's easy to output the state of every entity with an entity_id that contains battery_level

zenith rain
#

I have an automation that makes some calculation and saves a value (number) within an input number helper. How can I use that value within a second automation in a numeric state trigger below or above value?

mighty ledge
zenith rain
#

Will move

lime shell
#

Hello everyone, so i've created a template it's working now the only problem is that i can't use it on the energy tab because it's not listed, am i missing something?

Template code.

- platform: template
  sensors:
    solar_total_energy:
      icon_template: mdi:solar-power
      unit_of_measurement: KWh
      device_class: power
      friendly_name: Solar Total Energy
      unique_id: solar_total_energy
      value_template: >-
        {{ states('sensor.solar_energy_total_energy')|float(0) - states('sensor.house_energy_total_energy')|float(0) }}
inner mesa
inner mesa
#

something like:

{% set entities = states.sensor|selectattr('entity_id', 'search', 'battery_level')|rejectattr('state', 'eq', 'unknown') %}
{% for entity in entities -%}
  {{ entity.name ~ ': ' ~ entity.state ~ '%' }}
{% endfor %}
ember saffron
#

thanks

amber obsidian
#

Is there not a way to call light.turn_on using another light as parameters? I'm thinking when I have some lights on and turning more lights on. Would be nice for these new lights to turn on with same settings than the others.

#

Would work like hs_color: "{{ state_attr('light.oh_light_group_tv', 'hs_color') }}" but this is off if color_mode is color_temp. Would need to check first color_mode as condition? As one cannot use if sentences outside of the attribute to be set?

plain magnetBOT
#

@amber obsidian I converted your message into a file since it's above 15 lines :+1:

amber obsidian
#

This works but would be just so much easier if could refer to a light directly in light.turn_on.

inner mesa
#

You are?

#

I don't know exactly you claim isn't possible

amber obsidian
#

Hm? Where to give the referal light in turn_on if it's possible?

inner mesa
#

What do you mean by 'referral light'?

amber obsidian
#

I mean I'm turning one light on and would like to get all the parameters for that from another light that is already on.

halcyon sun
#

Hi Guys, i'm new in making template, i found this template online, but i would like to exclude all sensor from the Mobile App Integration, is it possible?

plain magnetBOT
#

@halcyon sun I converted your message into a file since it's above 15 lines :+1:

sacred sparrow
#

I am getting a "expected string" error:

- binary_sensor:
    - name: "Current Weather"
      state: >
        {{ not is_state('sensor.collingwood_short_text_0', 'unavailable') and
        not is_state('sensor.outside_home_feels_like_temperature', 'unavailable') and
        not is_state('sensor.outside_min_temp', 'unavailable') and
        }}
      attributes:
        Forecast: {{ states('sensor.collingwood_short_text_0') | lower }}
        Temperature: {{ states('sensor.outside_home_feels_like_temperature') |int }}
        Minimum: {{ states('sensor.outside_min_temp')|int }}
inner mesa
#

Rule #1

#

Surround single line templates in quotes

sacred sparrow
#

this is why I shouldnt code at 7am on a Monday morning 😄

#

Currently "Minimum: "{{ states('sensor.outside_min_temp') | int }}"" is unknown - how can I make it "Not Available" if its unknown/unavailable?

#

because its not showing up as anattribute when its unknown/unavailable

marble jackal
marble jackal
digital iris
#

It worked! Thank you so much!

#

Any idea how I can get a volume value from entity meadia_player.full.range.speakers?

sacred sparrow
# marble jackal `"{{ states('sensor.outside_min_temp') | int('Not Available') }}"`

that worked great but it doesnt seem to work for the other sensors:

      attributes:
        Forecast: "{{ states('sensor.collingwood_short_text_0') | lower('Not Available') }}"
        Temperature: "{{ states('sensor.outside_home_feels_like_temperature') | int('Not Available') }}"
        Minimum: "{{ states('sensor.outside_min_temp') | int('Not Available') }}"
        Maximum: "{{ states('sensor.collingwood_temp_max_0') | int('Not Available') }}"
        Rain: "{{ states('sensor.collingwood_rain_chance_0') ('Not Available')}}"
        Pollen Count: "{{ states('sensor.melbourne_pollen_count') ('Not Available')}}"
        UV Index: "{{ states('sensor.collingwood_uv_category_0') ('Not Available')}}"
#

I am getting "null" on most:

Temperature: 5
Minimum: Not Available
Maximum: 14
Rain: null
Pollen Count: null
UV Index: null
friendly_name: Current Weather```
marble jackal
#

that's becasuse it's a setting of the int() filter

#

you can't just throw it somewhere in your temlate

sacred sparrow
#

oh - so how would I do it for lower, and non-int() filters?

marble jackal
#

if they are numeric as well you can use float()

inner mesa
#

like this doesn't make any sense:
Rain: "{{ states('sensor.collingwood_rain_chance_0') ('Not Available')}}"

sacred sparrow
#

Rain: "{{ states('sensor.collingwood_rain_chance_0') | float('Not Available')}}

#

the others are text though

marble jackal
#

for text iif(states( 'sensor.foo') not in [ 'unavailable', 'unknown'], states('sensor.foo'), 'Not Available')

sacred sparrow
#

ah gotcha. thanks 🙂

#

Rain: "{{ states('sensor.collingwood_rain_chance_0') | int('Not Available') }}%"
This works but when its not an int it says 'Not Available%' is there a way to only show the percent sign when its an int

marble jackal
#
Rain: >
  {% set rain = states('sensor.collingwood_rain_chance_0') %}
  {{ rain | int ~ '%' if rain | is_number else 'Not Available' }}
sacred sparrow
#

amazing -thanks again

sacred sparrow
#

I just swapped out the % for °

inner mesa
#

you're missing a "%"

#

{% set minimum = states('sensor.outside_min_temp') °}?

#

or have an extra "°"

plain magnetBOT
#

@fallow whale I converted your message into a file since it's above 15 lines :+1:

sacred sparrow
#

that worked - thanks 🙂 last thing:

    - name: "Current Weather"
      state: >
        {{ not is_state('sensor.collingwood_short_text_0', 'unavailable') or not is_state('sensor.collingwood_short_text_0', 'unknown') and
        not is_state('sensor.outside_home_feels_like_temperature', 'unavailable') or not is_state('sensor.outside_home_feels_like_temperature', 'unknown') and
        not is_state('sensor.outside_min_temp', 'unavailable') or not is_state('sensor.outside_min_temp', 'unknown') and
        not is_state('sensor.collingwood_temp_max_0', 'unavailable') or not is_state('sensor.collingwood_temp_max_0', 'unknown') and
        not is_state('sensor.collingwood_rain_chance_0', 'unavailable') or not is_state('sensor.collingwood_rain_chance_0', 'unknown') and
        not is_state('sensor.melbourne_pollen_count', 'unavailable') or not is_state('sensor.melbourne_pollen_count', 'unknown') and
        not is_state('sensor.collingwood_uv_category_0', 'unavailable') or not is_state('sensor.collingwood_uv_category_0', 'unknown')
        }}

sensor.outside_min_temp is unknown and it still is showing my binary sensor state as 'on'

#

is there a better way to the whole state section?

inner mesa
#

yes, there's a better way

#

all those "or" statements aren't what you want

#

if any are true, the result is true

#

{{ expand(['sensor.collingwood_short_text_0', 'sensor.outside_home_feels_like_temperature', 'sensor.outside_min_temp', 'sensor.collingwood_temp_max_0', 'sensor.collingwood_rain_chance_0', 'sensor.melbourne_pollen_count', 'sensor.collingwood_uv_category_0'])|rejectattr('state', 'in' ['unavailable', 'unknown'])|list|length > 0 }}

#

assuming that your goal is for it to be "on" if any of those aren't "unavailable" or "unknown"

sacred sparrow
#

that makes my sensor :unavailable: