#templates-archived
1 messages · Page 16 of 1
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.
hi. i have a nice little sensor that exposes items from shopping list, but i want to extract only tha names of incomplete items. http://pastie.org/p/4VAZgNG4EWy7nIVGWE5Nb1 . how can i do that?
this: {{ (states.sensor.shopping_list.attributes.incomplete() | list) }} returns error
{{ '1.84 9' | replace(' ', '') | float }}
you should use state_attr('sensor.shopping_list', 'incomplete')
and to get only the names you can use {{ state_attr('sensor.shopping_list', 'incomplete') | map(attribute='name') | list }}
thanks allot
thank you
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?
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
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..
have a look at the docs 🙂
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?
Here is now to split your configuration into multiple YAML files
You can actually go further 😉
Oh god, this has become way more than I expected..
Keep it simple to start with, and get fancy later
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?
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
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
You can use iif, the immediate if
{{ iif(is_state('binary_sensor.gastezimmer_beschattung_bereit', 'on'), 'bereit', 'gestoppt') }}
thanks, but if I wanted to map more than one state I would still need to chain these, there is no other way right?
I've just got template sensors
Or in some cases, you may find customising the device class gives you what you want.
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') }}
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
that's exactly what I was looking for, it did not occur to me that I can just define variables in templates, thanks!
It's untested, so you will probably need to play with it. But I suspect you can manage it 🙂
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)
Nah, works perfectly :)
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?
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 ?
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 🙂
Why would you want that? It is shown according to the settings in your profile on your Dashbaord
For non-template cards, yes. But my template cards do not localize the values when rendering them to strings
Did you set their device class?
If you set it to be a temperature or similar, I believe it should work 🤔
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
if it is simply to replace it, you can do something like {{ 21.5 | string | replace('.',',') }}
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.
How are you modifying the icon colour? Would it be better to use customisation and do the template for the icon colour in that?
The frontend already does this.
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.
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"
.....
- name: "mylight1"
light templates have not been brought over.
Use the documentation, don't make guesses
Fair, thought they'd have the same format
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
If they are switches, the Switch as X helper is now in the UI
Can i use a template for the "below" value in a numeric state trigger?
This should work shouldnt it?
as a "template condition"
should pass true if the current temp is less than the trigger yeah?
you should convert it to numbers
|float them both yeah?
yeah templatre trigger i worked out 🙂
Hi, when creating a template sensor, are the linked value from the state automatically updated to the template sensor?
``` so this should be solid @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
the other is also a number... or should be?
no, all states are strings
ahhh even if its a device_class temp?
ALL states are strings
kk
yeah i think that comes from when i've been trying to make larger ones and it was easier in my head to seperate things out haha
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
You need to read the template docs
type: custom:mushroom-title-card
title: Hello, entity.state.sun {{ user }} 👋
{{ states('sun.sun') }}
Hello, above_horizon Connor 😅
@short wren I converted your message into a file since it's above 15 lines :+1:
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".
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?
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
On the 3 separate sensors? They are generated from esphome though, can I set a default in the sketch?
It depends on how they became unavailable
Defaults are explained in detail here: <#templates-archived message>
What is the state of the sensors when you are out of reach?
Create two separate triggers and add the entities which should be used on the actions as trigger variabeles
{% 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' }}
When I'm too far away to get a reading it goes unavailable, I'm this case I would still want the lowest of the other sensors to give the relevant room
That's what will happen here
So I can just copy paste your code in place of mine?
You could first test it in developer tools > templates and walk around the house a bit
Brilliant, I'll give it a try, thank you
Seems to be working perfectly so far, it's giving me the room I'm in despite one of the sensors not giving me a value. Perfect, thank you again
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 %}
@short wren I converted your message into a file since it's above 15 lines :+1:
^
I got it working with the above.
Ah, it was not clear to me based oh your previous code that this was your goal
All good 🙂
@late knot I converted your message into a file since it's above 15 lines :+1:
Look for where you have something in a file with value_json['update'], I'd best it's a RESTful integration of a kind
Dear Rosemary,
i try it with grep but i get no result
Where are you searching? It would be in the /config directory most likely.
i do it with
grep -r -i 'value_json['update']' ./
in /config
But where are you when you do that?
in /config ... sorry i forgott it
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
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 %}'
did anyone already "mapped" a value from a CCU energycounter into a template sensor?
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)
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...
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'
Yes, entity_id is not an attribute
In HA terminology, it is in jinja terminology 😅
You can't guard against the attributes. This is more reason for why we need an attributes_template field that's mutually exclusive with json_attributes_path & json_attributes
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.
@celest plume I converted your message into a file since it's above 15 lines :+1:
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...
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}}'```
You forgot, again, to explain the problem/provide the error
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
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 }}"
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.
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.
what is the actual sensor state?
Wednesday 16 November 2022
{{strptime('Wednesday 16 November 2022', '%A %d %B %Y').date() }} -> 2022-11-16
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?
yes my mistake indeed........
thanks for noticed 😉
Stupid google translate
Sorry
Ut r but this bin_date is a variable thats chaning, in not getting this bit
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') }}
- name: "test1"
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?
It doesn't matter. I'm just giving you an example
The point is: add .date()
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
That doesn't answer my questions
Is there an attribute Watt with capital W which has the value you are looking for
No
Is there a way to get a list of all areas?
Thanks, misunderstood it works thanks again 😉
{{ states | map(attribute='entity_id') | map('area_name') | reject('eq', none) | unique | list }}
This entity contains the value what I need. Is there a different way to get it, for further processing
{{ states('sensor.ccu3_sv_svenergycounter_2592_00085a49123456_7') }}
Thanks, I had this but forgot to quote the filter name as the map argument and was getting a confusing error
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
Thanks, I'll try. Where can I get an information when to select state or state_attr? (I got this lines from a YT vid) Even if the source is unitless, Can I define it with an unit the template sensor?
You can do it (and sometimes have to) in other languages, but it's not typical
cough reflection cough
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)
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
right
Well, you use states() if you want the state of the entity, and state_attr() if you want an attribute value
Blue: state
Red: attributes
BTW, you can check out the meta language that the Jinja engine actually executes.
Everytime i use reflection in C# i get confused at the syntax and then I find a way to not use it
to see what it's really doing
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?
first selects the first entity
be warned, you need to provide a default when there is an empty list
there's a way
I'm still don't understand the issue I guess 😅
Maybe if I see the solution of petro
Well it's just a wasted step
{{ ['kitchen', 'bedroom'] | map('area_entities') | list | sum(start=[]) | unique | list }}
probably want to sort that too
just replace the last list with sort
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
that doesn't fix an empty list
{{ states | map(attribute='entity_id') | map('area_name') | reject('eq', none) | unique | map('area_entities') | list | sum(start=[]) }}
All entities which have an area
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
these's are generators, they aren't really lists unless you request the data
Hm that's a good point
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
Yeah I'm just saying it bothers me that there are results when I should have result
which you want 1 big list, so you add the 2 together
Yeah exactly
It doesn't matter, just is inefficient (not that it really matters from a practical standpoint)
ok, so you can add any objects together as long as they can be added
it's not inefficient
sum is being called multiple times, though, right?
Ok so rather it's being called once with an array that is "unnecessarily" large, no?
Yeah I understand that
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
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?
Filters are called with the entire input data structure
I have no idea what you're asking
are you saying you have the exact same entity_id's in your bedroom and your kitchen?
https://i.imgur.com/9ZNiBMM.png Is this the ID that I should use on the "state" ? of a template sensor?
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
what are you trying to do
To get the value from this ID, This is the IoBroker counterpart: https://i.imgur.com/yeI4OGJ.png
So like this:
['kitchen', 'bedroom']
| map('area_entities')
| list
returns a 2d array
"get the value into a template sensor"
Ugh something just happened to my HA instance...must've hit it too hard with templates or something and it's choked up now
and to make it 1d, you use sum(start=[])
and to remove duplicate entity_id's after you make it 1d, you use unique
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
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
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
@rigid chasm I converted your message into a file since it's above 15 lines :+1:
Sorry about that. For some reason I had the idea that each of those nested arrays were exactly the same. That's why I was calling first. But really that isn't even a correct solution
yeah, they won't be the same unless you made a typo and had the same area twice
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
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
I have a general idea, but not specifically how it works in python
it works the same in all languages
And I think I conceptually see what you're saying then if those are generators
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
So it isn't really a list being passed into sum then, it's a generator?
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
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?
An automation with trigger state change of the input helper?
Its the setting of the date/time helper with the current date & time + the minutes selected in the drop down that I'm struggling with as its not something i've done before.
Or is that possible in an automation that I could trigger from the input helper?
Thanks for all the technical details petro
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
Can you post the format of the charge time? A pic of the entity and its attributes in dev tools -> states
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
Ah sorry I thought you said you had a sensor that gave you the charge time
Ahhh no sorry, I'm just creating it now
Are you using a input_datetime with just time?
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)
That could work
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
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
Works perfectly, thank you
No problemo
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
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
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?
Sounds like a statistics sensor
It sure does, thanks @inner mesa !
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)) }}'''
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?
You are comparing a string to a date object. Either add | string to both, or remove it from the first
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.
🫣 yes thanks 😀
if you put them in one yaml file, you can make use of yaml anchors
@marble jackal I converted your message into a file since it's above 15 lines :+1:
whoops, there is a quote wrong there, but I can't edit it anymore 😛
The bot has turned on us
I have the following part of my configuration.yaml http://pastie.org/p/0cb74pNvSN08pKeKRUxKkx and now I want to add a new sensor that should be calculated like this: http://pastie.org/p/6SOk9hFSNCxTo88kyhSkm8
How do I add that to my configuration.yaml based on the current file
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
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()
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?
Thank you very much Fes!
I'll check this out first thing after work 🙂
Because you should not put quotes around the template if you use the multi line format
and you should use backticks to format your texts as code here on discord
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.
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
I signed up right now at pastebin 🙂
awesome worked!
you don't need an account for the websites mentioned here
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.
wrong one
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
yes, but it could be useful in the future :9
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") }}
Sorry
this is the way
Ok ty
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.
yes, thats possible
but are you talkiing about a timestam (the number of seconds passed since 1/1/1970) or about a datetime?
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.
- Store epoch
- 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?
@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:
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
If you want to limit an automation to not let it run if it has already been performed less than 2 hours ago, you can use the built in last_triggered attribute
Ad this as condition:
condition:
- condition: template
value_template: "{{ now() - this.attributes.last_triggered > timedelta(hours=2) if this.attributes.last_triggered else true }}"
Okay I can try that. If it doesn't work the way I need I can pursue the epoch thing then I guess.
{{ state_attr('sensor.lijst_tankerkoenig', 'stations') | map(attribute='id') | list }}
omg are you a template guru ?
I cant thank you enough...
I learn from it......
You were making it far too complex 🙂
yeah I noticed , need to learn i see 😉
I have the following part of my configuration.yaml http://pastie.org/p/0cb74pNvSN08pKeKRUxKkx and now I want to add a new sensor that should be calculated like this: http://pastie.org/p/6SOk9hFSNCxTo88kyhSkm8
How do I add that to my configuration.yaml based on the current file
value_template: >
{% set pris= states('sensor.nordpool_kwh_se3_sek_3_10_0') | float %}
{{(pris)/100}}
or
value_tempate: "{{ states('sensor.nordpool_kwh_se3_sek_3_10_0') | float / 100 }}"
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
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') }}"```
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?
sorry, what kind of cleanup are you trying to do
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 😉
use join(',') instead of list at the end
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
thank you very much @marble jackal and how to you make your code look pretty like that?
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.
damn, I learned now to restart the system core
when you made allot changes 😉
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?
you probably don't need to do that, you can reload most configuration from developer tools > yaml
show your server controls
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
what's the definition of a season here, is it based on months? or the 21st of December for example for Winter?
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
and 21 December is Summer here 😉
{% 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 %}
why even bother with the name, just use that as the Tariff Price
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
also, cheeky pricks think its summer for 5 months.... so they can milk that 49 cents / kWh
Fes, you are a wizard
not anymore this way
I put it into the Template editor and got TemplateSyntaxError: expected token 'end of statement block', got '{'
you didn't put the multiline notation in
no, I forgot %} after defining winter
you must have ninja edited it
jinja-edited
i take this back then
no take backs
What if i take back my take back?
too many take backs for me now...
ok so how does that template then work in an automation?
well that's the thing
and then able to bring the right price into the energy dashboard?
you probably just want to make it output the price instead of the names, and use that as your utility meter sensor
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
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 %}
you could also use it like this, and trigger on state changes to change the select to the corresponding option
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?
depends, If you want to use it for a price sensor for your Energy dashboard, the one resulting in the price will be fine
awesome, cheers. i will give it a go
then would not need so many different sensors and automations.... if that works...
yes I do
so only one
and you use utility meter to split it in 3?
yeah, split the import sensor into the three different tariffs
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
the dynamic price entity being the template sensor?
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
yes
nice to have options
ah yep. 3 different sensors, only one of them is pertinent to these tariffs tho
ohh right
is that how you run it?
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
ohh cool. is it from the energy company?
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?
no, but that is also something for #energy-archived
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)
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?
this datetime is indicates it was 2:00, and that the timezone was GMT+1
Which means it was 1:00 UTC
so your output seems to be the UTC time
Is there some way I can look through all of the different mdi: icons?
Patch notes say which ones are currently added
I would have thought there was some way exposed from within home assistant
There is not. There's a nice Chrome extension, though
Okay, so that part seems to be ok. Then I wonder why the diagram that plots from the same source doesn’t reflect the same thing?
what does the diagram show then?
Actually it’s not entirely clear. I can see that the sensor that was created gives +01:00 and in the template editor it gets +00:00
Share the template you are using
But that actually indicates the result is indeed in UTC
Thanks a lot. I opted for the last option, a sensor for all three prices, popped it open this morning and it’s set as unavailable. 🤦♂️
The post you now reply on doesn't contain different options. It was a 4 step approach 😅
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 ?
Sure
I've tried
"{{((states('sensor.time'))) + ((states('sensor.tmbxxxxxxxxxxxxxx_charging_time_left')))}}"
Not like that
but that does not seem to work not unexpectedly .. 😆
What is the state of this time left sensor
13:15 h
🤬
eg, 32:20 h or 00:40 h
{% set time_left = states('sensor.time_left').split(' ')[0] %}
{% set h, m = time_left.split(':') | map('int') %}
{{ now() + timedelta (hours=h, minutes=m) }}
WOW, thank you soo much
🙇♂️
does the automation use the template sensor we created last night to trigger the change to the utility meter from step 1?
Yes
I’ll see if I can figure it out!
@marble jackal no rush but wondering if you can walk me through the sensor so I can understand it all. I get setting now and the summer and winter months, but lost after that
{% 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 ^
that Petro, trying to understand everything and get the automation to change the price going
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.
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
it should have been 0.2383 at 7am
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)
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
ah right. I did find one that is a starting point I would think, but to be honest, I am not sure
@formal ember I converted your message into a file since it's above 15 lines :+1:
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 ^
testing out now, thanks!
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
No, you need an automation if you want to use the 3 separate sensors created by utility_meter
So you can see by the color which tariff was used
ah, should have read all before replying
haha was gonna say like the one petro wrote for me?
yep
alright will see how it goes tomorrow
for the tariff you can create a separate template sensor like petro did which just shows the active tariff
or you can just assign a static price to in the Energy dashboard for the 3 utility meter sensors
thats the three i have now, automation, the value and the tariff type
I would just use the same template sensor but then resulting in the price instead of the word
that was not working
why not?
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
yeah it just dropped off, came back on at 10pm when off peak started again
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
@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:
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)
and this automation also updates your input_number
that would be why it didnt work
Message malformed: template value should be a string for dictionary value @ data['action'][1]['data']
no, it would just have been peak from 7am to 10pm and never become shoulder
It doesn't like the - in the dict()
what are the action options of the select entity?
its a slider of the price, from 0.2219 - 0.4940 in 0.0001 increments
okay, so without an -
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
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
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
was more thinking after 8.
8pm
should be way more consumption too during the night
i have a dell server running 24/7
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?
yeah, solar generation, import and export
no, all 3 import sensors generated by the utilty meter integration, one for each tariff
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
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)
so i don't think we created entities that produce a kWh value based on the peak
which sensor is added now as an consumption sensor to the dashboard
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
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') }}"```
where are you putting that?
templates.yaml
and how is templates.yaml defined in configuration.yaml?
template: !include templates.yaml
ok, so change value_template to state
Thanks a lot, that did the trick! What's the difference between the two? In the example, they used value_template.
was for sensors: 😄
the example is most likely using the legacy template yaml
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
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
the missing data i think is the inverter turning off 😦
mqtt tempaltes don't have access tot he state machine
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 %}
😭 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!
Or the CT clamp is around the wrong way 🤦♂️
rookie mistake
(I did it too)
Trying to pull the precipitation amount in HA to check if > 0 - Any advice?
{{ is_state_attr('weather.home','forecast')[0].precipitation|float, '0' }}
remove is_, change |float, '0' to > 0
thanks didnt realize i could evaluate to T/F without the _is
Is it possible in an automation to read the state of one device and use it as the target value for another device?
you can do that with entities, not devices.
the line between those is somewhat blurry for me as pretty much every device has entities doesn't it?
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
How to list the states of a device? I want to create a binary sensor template for the HVAC mode of my TRV
are they supported through the UI or do I need to switch to raw yaml?
templates in general are not supported in the UI, you have to switch to yaml for those
ok, that's where I've been getting stuck then... didn't seem supported... will try my hand at the yaml
Does it have more than 1 climate entity? If no, just use the climate entity.
No just one.
ok then, just use the entity
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
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
Yeah online they had something like 'hvacmode.cool', but I don't know if I have that
So how to list the attributes?
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

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
perfect, thank you state_attr appears to do exactly what I want
you can if you want, otherwise you don't have to, it's implied
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
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 ....
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
I guess with this Jinja2 syntax
I recommend cruising through the template docs
is_state_attr checks attributes
is_state checks the state
Already there
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
That's the state
righto
No, that is a list of available states. Just the states('entity') gives me the right string "heat"
So now I have to check that
Yes, got it. Thanks
Sometimes you just need a basic example and where to check that
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
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
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?
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
You could create a template sensor with states | list | count as it's state, and use a state change of that template sensor as a trigger to update the groups
Maybe create one for each domain, then the groups are op to date within a second after the entity is created
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?
post the line
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
"WASTE + FOOD WASTE Friday 18 November"
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
you will likely need to split out those values...
trend sensor?
#automations-archived message @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
trying to parse that thread... thanks
cool, didnt know there was a from and to state
is it that simple? https://pastebin.mozilla.org/WiUOSRjb
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
last link in the first paragraph
Are you just looking for a boolean sensor telling you that you have to do it today?
not this part:
- platform: numeric_state
entity_id: sensor.big_sky_lifts_open_multi
above: 0
you went offscript from the example: https://community.home-assistant.io/t/trigger-automation-when-integer-increases/128098/3
I was hoping for one to tell me it's tomorrow, but essentially
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
I think I can probably live with the annual confusion
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
got it, thanks
see it now, thank you very much!
@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
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
this is the bit that's been eluding me for months - thanks!
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
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
I wish my garbage people had a page I could scrape
they do, but I have to fucking log in
aka, no scrape
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
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
looks like you tried to use a template where it isn't supported
ah, was hoping I could just drop it in
Electrician installed mine! I’ll have to check it today.
Diving into home automation/efficiency has educated me as to just how uneducated a lot of 'installers' really are, it's sad really
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!
I expect that electricians are more concerned with what's code-compliant
Yep, that’s why I diy
Particularly in Australia- our electrical is likely the most highly regulated in the world
which way clamps are supposed to be installed is probably at or below the bottom of the list of things they care about
Although that’s pretty basic surely
Found it - no CT on two of the phases
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') }}
I would say its a first one then but that doesnt seem right
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
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
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"?
yes
then do that 🙂
very true!
only the first one is more complicated
I just copied the wait template from above in my automation and put nots in the front of it haha
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.
yes, the syntax could be changed to actually distribute the "not", but I'd start with trying to simplify it
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.
The fifth, actually
🙂 True. I'm trying to get it into my config but I'mg etting an error.
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
You used the same type of quote inside and out
Heh, woops 🙂
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?
{% set value='binary_sensor.valve_opened_42' %}
{{ value.split('_')[-1] }}
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
Thanks, I'm gonna try it out right now.
Just a short one: can you reload template sensors without restarting HA?
dev tools -> yaml page
Sure, sorry for the dumb question.
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
{% if media_title is not none %}
what's the point of tv_state if you aren't going to use it too?
Ah, I thought it was a string so it'd work as that - will give it a shot!
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.
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
there's a template editor you can use to test things
In the developer section?
yep
I used that and it evaluated to true when I had the code above
Hang, on, let me get a picture
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
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
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).
Either do:
- if: "{{ template }}"
or
- if:
- "{{ template }}"
or
- if:
- condition: template
value_template: "{{ template }}"
What you have now is an incorrect mix of those
@tropic stratus I converted your message into a file since it's above 15 lines :+1:
(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.
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
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.
how is that different from a regular template sensor?
Maybe it's not -- should I be using sensor rather than number? I'm not familiar with the new template sensor configuration.
yes
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.
if you need the set_value functionality that you don't need
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.
is there a way to let a light return to its previous brightness after a motionsensor clears? Without setting a scene?
- motion detected
- save brightness somehow
- turn on light with higher brightness
- motion clears
- 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.
Sure, write the brightness to an input_number and reference it in step 5
once i have written that text i had that brainwave. Im using text helper. will that work?
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?
You can create a scene on the fly for that
but then i HAVE to let the automation run fully in single mode, hence returning to dim again regardless
else when restart in choosen it resaves the scene on wrong value
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
You lost me, but you can always go for the input_helper or input_texr
i think thats a neat way to get what i want
;0
🙂
anyway. bedtime. weltrusten
and thx
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
Or on the trigger in the wait_on_trigger
Thanks, both. I'm going to give this a try. Seems that maybe and will wait... https://community.home-assistant.io/t/help-with-wait-for-trigger-automation/355374/7?u=jumper I want to make sure I'm both home, and in the house before my welcome_home tts automation runs so I can hear it.
Its been fun building a script for the tts engine that reports a number of timely metrics.
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
as I mentioned elsewhere, you're describing an input_datetime
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 {{ }}?
Not like that
{% set controllerx = state_attr('sensor.somesensor', 'controlleridx') %}
{{ states('binary_sensor.' ~ controllerx ~ '_schema') }}
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?
Jinja string concatenation
Thanks!
The links in the channel topic have lots of good info
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
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 😛
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
😄
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 ?
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
This will be the title of my forum thread if I will decide to publicly write about my geniuses
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
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
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 %}
okay so i stored 2 input_datetime in helpers. can i subtract them to get a difference?
yes yes I'm trying to figure that out too! I've been on this for 6 months, it won't work
oh boy, lol
are you trying to get the length of time in the difference? like say "2 hours"
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
{{ 'cloudy' in states('sensor.collingwood_extended_text_0') | lower }}
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
{{ today_at(states('input_datetime.wakeup_time')) - as_timedelta(states('input.datetime.time_difference')) }}
You need to use states() to get the state, see the example above
thx, ill test around with that and see how far i can go
Do you have time only, date only or both in your input datetime
Then you can convert them from string to a datetime using as_datetime
oh that puts it as a string? i missed that lol. yeah then i need to convert it for sure
woops
Do that with both, and you can subtract them
All states in Home Assistant are strings
{{ as_datetime(states('input_datetime.openweathermap_condition_time')) }}
like this
Yep, that will convert it to a datetime
hm. yeah i guess reading the doc on input_datetime, it didnt mention to use as_datetime so thats why i was clueless lol
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
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
{{ (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
oh even better
i didnt know it was that easy
yeah that gives me 50.0
that beats doing .split(':')
split wouldn't work, as you have a timedelta as result. You'd first have to convert it to string then
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
{{ "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) }}
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
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
{{ states('sensor.openweathermap_weather') in [ 'few clouds', 'snow', 'rain' ] }}
Ooo thank you. This is a struggle to relearn lol
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?
Probably depends on the card used, but this is more of a #frontend-archived question
thx..I tried to post there and didnt get an answer...thanks anyway
is there any way to loop thru all my devices that are reporting a battery level and print the values?
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
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?
this is more for #automations-archived but you just simply use the entity_id in the numeric trigger.
Will move
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) }}
how would i do that?
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 %}
thx. ill give that a try
thanks
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?
@amber obsidian I converted your message into a file since it's above 15 lines :+1:
This works but would be just so much easier if could refer to a light directly in light.turn_on.
Hm? Where to give the referal light in turn_on if it's possible?
What do you mean by 'referral light'?
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.
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?
@halcyon sun I converted your message into a file since it's above 15 lines :+1:
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 }}
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
{% set ignore_entities = integration_entities('mobile_app') + ['sensor.id_battery_level', 'sensor.hallway_door_battery', 'sensor.cr_curtains_battery', 'sensor.lr_curtains_battery'] %}
"{{ states('sensor.outside_min_temp') | int('Not Available') }}"
It worked! Thank you so much!
Any idea how I can get a volume value from entity meadia_player.full.range.speakers?
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```
that's becasuse it's a setting of the int() filter
you can't just throw it somewhere in your temlate
oh - so how would I do it for lower, and non-int() filters?
if they are numeric as well you can use float()
like this doesn't make any sense:
Rain: "{{ states('sensor.collingwood_rain_chance_0') ('Not Available')}}"
Rain: "{{ states('sensor.collingwood_rain_chance_0') | float('Not Available')}}
the others are text though
Thank you so much it work
for text iif(states( 'sensor.foo') not in [ 'unavailable', 'unknown'], states('sensor.foo'), 'Not Available')
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
Rain: >
{% set rain = states('sensor.collingwood_rain_chance_0') %}
{{ rain | int ~ '%' if rain | is_number else 'Not Available' }}
amazing -thanks again
{% set minimum = states('sensor.outside_min_temp') °}
{{ minimum | int ~ '°' if minimum | is_number else 'Not Available' }}```
I tried it for this but with "°" and get the error 'TemplateSyntaxError: unexpected char '°' at 72'
I just swapped out the % for °
you're missing a "%"
{% set minimum = states('sensor.outside_min_temp') °}?
or have an extra "°"
@fallow whale I converted your message into a file since it's above 15 lines :+1:
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?
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"
that makes my sensor :unavailable: