#templates-archived
1 messages · Page 43 of 1
Just use the generator with | list | count
argh, you mean {{media_players_active()|list|count}}...
@steel swift I converted your message into a file since it's above 15 lines :+1:
I would suggest to adjust the first sensor so it only gives the power value if the switch is on
then use that sensor in a Riemann Sum Integral (available under Helpers) to convert it to kWh
In any case, you won't be able to create a sensor which you can use in the Energy Dashboard using the old template sensor format, as you can't add the state_class in the old format
Would that help anything, that sensor is reporting. When on/off I must admit though that I am really not sure what the Riemann sum does. The sensors are customized ´´ homeassistant:
customize:
sensor.varmekabel_garderobe_runtime:
state_class: measurement
last_reset: '1970-01-01T00:00:00+00:00'
sensor.varmekabel_garderobe_totalt_forbruk:
device_class: energy
unit_of_measurement: "kWh"
state_class: total_increasing
last_reset: '1970-01-01T00:00:00+00:00'
utility_meter:
varmekabel_garderobe_runtime:
source: switch.varme_garderobe
cycle: hourly´´
if you would just use the new template sensor format, you don't need all this customizations
and you don't need last_reset for both
oh wait, you were already checking if the switch was on
just use that first sensor in the Riemann Sum integral, and you will have kWh as return
in the new format that would be:
template:
- sensor:
- unique_id: power_sensor_varmekabel_garderobe_forbruk
name: "Varmekabel Garderobe Forbruk"
unit_of_measurement: "W"
state: >
{% if is_state('switch.varme_garderobe', 'on') %}
{% set voltage = states('sensor.voltage_phase2_hjemme') | float %}
{% set resistance = 105 %}
{% set power = (voltage * voltage) / resistance %}
{{ power | round(2) }}
{% else %}
0
{% endif %}
device_class: power
state_class: measurement
availability: "{{ 'switch.varme_garderobe' | has_state and 'sensor.voltage_phase2_hjemme' | has_state }}"
just so I understand better, why is that optimal?
Ok, I will try that. Still pretty new in Home Assistant world and try to learn by doing, appreciate all the help I get.
which will result in sensor.varmekabel_garderobe_forbruk based on the name
had my quakes template look like this now: {% set km = states('input_number.quakes_near')|float %} {% set location = states('input_select.quakes_near') %} {% from 'quakes.jinja' import quakes %} {% set ns = namespace(count=0) %} {% for s in quakes().split(',')|reject('eq','')|list if distance(s.entity_id,location) < km %} {% set ns.count = ns.count + 1 %} {% endfor %} {{ns.count}}
because generators don't resolve all items in the collection
when you use | list, you generate all items
the for loop will only generate what it needs
remove the |list
When I set up the riemann sum, I assume I use the integration? Which sum method, left?
You can just set it up under helpers.
I don't expect the sum method really matters here, the power value will be quite stable as the only variable is the voltage (besides the state of the switch)
not sure if this is a template question or something that already exists.
I have a router that will tell me every 5 seconds the current KB/s but not data usage totals. I want to take the values, find the average of the four seconds not reported on based on the value of the two values surrounding them, then calculate the total data used for the entire day.
Is that something I can do with existing helpers, or do i need to come up with some template to do this
Just states unknown so I am probably doing something wrong `` sensor.garderobe_forbruk_varme
Garderobe Forbruk Varme
unknown state_class: total
source: sensor.varmekabel_garderobe_totalt_forbruk
icon: mdi:chart-histogram
friendly_name: Garderobe Forbruk Varme
sensor.varmekabel_garderobe_belastning
Varmekabel Garderobe Forbruk
549.49 unit_of_measurement: W
friendly_name: Varmekabel Garderobe Forbruk ```
Sounds like something for the Riemann Sum Integral helper as well
You are doing something wrong in formatting that post properly 😅
Is that the config for the Riemann Sum Integral? Just set it up in the GUI
Now that was just the info from developer tools, checking out a YT-video now on the riemann sum helper, trying again.
And now it reports 🙂 So then I can add this into energy dashboard. Delete all the leftovers I have done and only keep the sensor in my sensor.yaml?
Gets this in energy dashboard though: Unexpected device class
The following entities do not have the expected device class:
sensor.garderobe_forbruk_varme
your input sensor for the riemann should have device_class: power, and then I believe the riemann sensor will automatically have device_class: energy
if it doesn't I guess you can just add it with customize, or fix the source sensor
Tried something like this but gets: Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->varmekabel_garderobe_belastning->state_class. (See ?, line ?).
You are still using the old format
State class is only supported in the new format
I already mentioned that 🙂
And the new format is " Template: " Tried that, but probably did something wrong again, slow learner.
Can I ask why you added availability?
@steel swift I converted your message into a file since it's above 15 lines :+1:
@steel swift you keep putting in the sensor section
the new style does not go in the sensor section
it goes in configuration.yaml
So I cant have a sensor.yaml?
literaly copy/paste of what thefes wrote
you can, but what thefes wrote goes in configuration.yaml
not sensor.yaml
Ok, see that one. If I choose to have a sensor.yaml, what will the differencies be?
I don'tknow what you're asking
the new template styles goes in configuration.yaml
that's it
there's nothing else to it
it does not go in sensor.yaml and it's contents are meaningless to what thefes wrote
ok, so If I keep my sensor.yaml. It will be for the sensors I already have, and not have converted to the new style.
Thank you, for youre patience, appreciate it.
@steel swift I converted your message into a file since it's above 15 lines :+1:
I have silly question, quite new to HA, I'm designing my dashboard via minimalist theme, but somehow I can't add any custom cards
I add files to custom_cards folder, but they dont get detected
this is a #frontend-archived but you also have to add them via resources.
any idea?
hey everybody!
really struggeling with this organizational thing.
I want to either:
- have multiple yaml files for template sensors (eg. my_computer.yaml,aparment_sensors.yaml,xyz_sensors.yaml) which i could include into configuration.yaml
or
- have custom "headlines" or "brackets" inside the sensors.yaml, for easier navigation (as inside the code.txt)
but here I get the error: Missing property "value_template"
@craggy adder I converted your message into a file since it's above 15 lines :+1:
To avoid it going into error when your source sensors are not available
Thank you 🙂
Had to do some changes on it as it gave error on has state so now it is like this ```availability: "{{ states('switch.varme_garderobe') != 'unavailable' and states('sensor.voltage_phase2_hjemme') != 'unavailable' }}"
is_state() is a thing. could do not is_state() and not is_state()
The function/filter is has_value...
availability: |
{{ has_value('switch.varme_garderobe') and has_value('sensor.voltage_phase2_hjemme')}}
You're getting an error because you're just making things up instead of using the correct configuration format.
For multiple files/folders take a look at Packages (https://www.home-assistant.io/docs/configuration/packages/), it's easy to set up and flexible.
It's indeed has_value instead of has_state
My bad
Re: your number 2 option, just add #comments above your different sections.
No problem, appreciate your help.
Yeah i figured that out, but I cant "bracket" them, to navigate in through them or to collapse them, like:
#sensors
#specific_sensors
#very_specific_sensors1
very_specific_sensor1:
#very_specific_sensors2
#other_sensors
#other_sensors_room1
#other_sensors_room2
it does not work indefinitely, just one Level of "brackets"/comments is possible
is there a preferred extension? there's a whole list of them ..
I use better jinja, not sure if that is the best one
thanks, wil. install. could you please have a look with me here:```
{% set km = states('input_number.quakes_near')|float %}
{% set location = states('input_select.quakes_near') %}
{% from 'quakes.jinja' import quakes %}
{% set ns = namespace(count=0) %}
{% for s in quakes().split(',')|reject('eq','')
if distance(s.entity_id,location) < km %}
{% set ns.count = ns.count + 1 %}
{% endfor %}
{{ns.count}}```
and I am trying to write it in the fomr of {{expand(quakes().split(','))|reject('eq','') |map(attribute='state') |map('int',default=0) |select('<',km) |list|count}} but get stuck with the distance()
or cant I do that without the namespace
What's the result of this quakes macro?
If they are the complete states object, I think you missed the last sentence in this post
https://community.home-assistant.io/t/template-with-custom-templates-import-does-not-update-correctly/581120/10
If they are entity_ids, you need to use map('states') instead of map(attribute='state')
it should return the number of quakes that occur within the distance of the selected range to a selected location
Oh wait, I missed the expand
so if I set the km to 500, and select my phone, wanr me if quakes are within 500km near me
Which you don't need anyway
the expand version was merely c&p of my battery sensor... which is way easier ofc
But quakes() returns a comma separated string with entity_ids right?
yes, the custom_template is:{%- macro quakes() -%} {{- states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','usgs_earthquakes_feed') |map(attribute='entity_id') |list|join(',') -}} {%- endmacro -%}
this was my original pre-macroe jinja template: {% set km = states('input_number.quakes_near')|float %} {% set location = states('input_select.quakes_near') %} {% set ns = namespace(count=0) %} {% for s in states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','usgs_earthquakes_feed') if distance(s.entity_id,location) < km %} {% set ns.count = ns.count + 1 %} {% endfor %} {{ns.count}}
sorry pasted the wrong template..
You don't need both list and join()
heck , I have that in all my custom_templates... ergh, c&p monster, thanks for spotting that
You need to include the reject('eq', '') in the expand()
that is what I posted?
Hey
Ive got the sensor thats giving me
[‘sensor.x_diesel‘, ‘sensor.x_diesel‘, ‘sensor.x_diesel‘]
And i want to get a output in a notification like:
- friendlyname1 value1
- friendlyname2 value2
- friendlyname3 value3
Can somebody help pls?
you would want this: {% set d = expand('sensor.x_diesel1', 'sensor.x_diesel2', 'sensor.x_diesel3') %} {% for x in d %} {{x.name}} : {{x.state}} {% endfor %}
No, the reject() is outside the expand
expand(
quakes().split(',')
) | reject('eq','')
But you don't need to expand it
{{ quakes().split(',')
| reject('eq','')
| map('states')
| map('int',default=0)
| select('<', km)
| list | count
}}```
Also the default to 0 is working against you here, as you are now going to count the ones which are unavailable
Better to default it to km
a yes, that is already much cleaner. what this doesnt do yet, is take into account the if distance(s.entity_id,location) < km %} form the original template
and I cant see how I can do that without the namespace..
same as that I can list the low level batteris like that: {% set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {{batteries().split(',') |reject('eq','') |map('states') |map('int',default=0) |select('<',alert_level) |list|count}} but still require the namescpace to list those: {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in expand(batteries().split(',')) if s.state|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} {%- endfor %} {{- ns.batt_low|join(',')}}
Unfortunately distance() is not available as filter, do you can't use it in map()
1 error on reloading templates: Error validating template result 'unavailable' from template 'Template<template=({{states('sensor.presence_icon')|default('mdi:account-off')}}) renders=5>' for attribute '_attr_icon' in entity sensor.familie_samenvatting validation message 'contains non-whitespace: unavailable' happening on an icon template: icon: > {{states('sensor.presence_icon')|default('mdi:account-off')}}
I've never seen that before though,. I didnt have the default, so hoped setting that would fix the error, but it doesnt. Any ideas what might happen here?
the template for that entity presence_icon is```
sensor:
- unique_id: presence_icon
state: &icon
>
{% set presence = states('zone.home')|int(0) %}
{% set mapper = {0:'mdi:account-off',
1:'mdi:account',
2:'mdi:account-multiple',
3:'mdi:account-multiple-check'} %}
{{mapper.get(presence,'mdi:account-group')}}``` so should be guared againts unknowns itself
unavailable is a valid state, so default does nothing there
yes, confirm. ill take that out again 😉
Reloading templates will render then all unavailable for a short moment
but contains non-whitespace? is that just cryptic for: the template sensor was unavailable?
maybe I should not use another template sensor insiode a template sensors options
icon: >
{{states('sensor.presence_icon') if 'sensor.presence_icon' | has_value else 'mdi:account-off' }}```
I don't see whitespace being relevant here
icon: "unavailable" is invalid
ok, yes Ill use that. would be a pity if I had to recreate that template. otoh, makes me think now: i use it in more places in the config, maybe I should make it availble in the custom_templates as macro.
btw: Error validating template result 'unavailable' from template 'Template<template=({{states('sensor.presence_icon') if 'sensor.presence_icon'|has_value else 'mdi:account-off' }}) renders=5>' for attribute '_attr_icon' in entity sensor.familie_samenvatting validation message 'contains non-whitespace: unavailable'
That should not render unavailable
2 observations: 1) adding the full template in the icon template and reloading fixes the error.
2) when using this in dev templates, reloading templates does not change that for the short moment the templates are unavailable.
most entities restore state now on startup
templates are no execption to that
and knowing your templates, you're probably self referencing
not in this case..
btw, could it be the intensified use of those custom_templates is memory expensive:
+50% isnt minimal...
then it's probably not coming from that 😉
An observed change after a manual change does not directly imply causality when many factors can increase/decrease ram usage
Seems@more than just a correlation tbh. But no hard evidence yet, will need to disable the new additions for that
Thanks for your answer but thats ‚wrong‘, maybe i described it wrong. I got a templete sensor sensor.gasstation and that outputs the 3 cheapest sensors of 12 diesel sensors.
And id wish to trigger an automation that messages me these 3 sensors with their friendly name and their value
Is the list the state of the sensor.gasstation or is it defined in an attribute?
the state is a list of the sensors like: [‚sensor.x_diesel’,‘sensor.x_diesel‘,‘sensor.x_diesel‘]
x is replaced by the actuall adress of the gas stations nearby
A state is always a string so that should either first be transformed to a list type or use it in an attribute that exactly can be any type, including a list
{% set d = expand(states('sensor.gasstation').split(',')|list) %}
{% for x in d %}
{{-x.name-}}: {{x.state}}
{% endfor %}
That doesnt seem to work. Thats the sensor:
value_template: >
{% set sensors = integration_entities('tankerkoenig') %}
{% set ns = namespace(map={}) %}
{% for s in sensors %}
{% set ns.map = dict(ns.map, **{s: states(s)}) %}
{% endfor %}
{{ (ns.map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
put that in an attribute and then use what marius wrote
having that as the state will cause problems for you
You'll be coming here asking us to fix it forever
Sorry dont know how to do this. The template is from RobC
literally copy/paste that template into an attributes template on that template sensor
Im sorry but i still dont know how. Im just not really into templating
it's not templating at that point
it's yaml
you're going to have to try
if you cant figure it out, post what youve tried
but right now you're giving up without doing anything and that's insulting to anyone trying to help you. Because all you're doing is expecting us to do it for you.
Nah im not expecting anything. Im just asking for help, if you dont want to help, thats fine. If you help, im really thankful.
do you know how to copy?
if yes, then do you know how to paste that value somewhere else?
if yes, then all you need to do is add an attributes template to your template senosr by copying and pasting it
here's an example binary_senosr with attribute templates
here's an example of the legacy format (which you're using)
Once you have that setup, we can help you with the tempalte using the attribute you created.
Got the attributes so far, thx
So the sensor gives me the attribute „cheapest“ with the value of sensor.x_diesel, sensor.x_diesel, sensor.x_diesel
{% set d = expand(state_attr('whatever.yoursensorisnamed', 'cheapest')) %}
{% for x in d %}
{{x.name}} : {{x.state}}
{% endfor %}
That works!
If i output this as a notification, how can i show one information per line?
morning , I am looking for any help I can get concerning this template. I have a button card that displays the state of the door and the lock via a sensor template. because I am using sensor templates the standard tap action will not function. I found this tap_action template that Petro had helped someone else with tap_action: action: call-service service: | [[[ return (entity.state === 'locked') ? 'lock.unlock' : 'lock.lock'; ]]] service_data: entity_id: lock.garage_laundry_door_lock_door_lock the problem I think I am having is that in Petro example the entity_id referenced back to the original entity, which is a sensor. Here is the full card http://pastie.org/p/7uWEehpPIHNAcLYHpAO4W4
if that's for custom button card then i believe you'd replace entity.state with entities['lock.garage_laundry_door_lock_door_lock'].state
it's either that or states['lock.garage_laundry_door_lock_door_lock'].state
most likely the second one
And you probably be able to use ‘toggle’ instead of that action template
That will return the entity state, not the entity_id.
petro thanks for your help and patience.
Could you please show me how i can do this?
I am not able to use toggle because the primary entity is a sensor and the tap_action part would default to the primary .
You could still use that if you set the correct entity in the tap config . You can really set anything there.. it’s the power of custom button-card
Check https://github.com/custom-cards/button-card#action. It literally says ‘ any entity_id’
But this really is for #frontend-archived
That's only posssible if your notification service allows it.
IOS does not
Can't answer for andriod
I have a working blueprint that does exactly this on ios, are you sure?
if it's possible, then what was written will work. If it's not possible then what was written will show up as a single line
whitespace is retained in templating
my bad if I am not seeing what you are trying to show me. I did take a look at the github. I did see the action part for the card, but call_service: lock toggle is not an option for me , hence the search for a template. Also are you saying that card templates should be in #frontend-archived only?
so whats the difference between a notification via automation to via blueprint?
Then its possible on ios to do this or am i wrong
without seeing the blueprint.... 🤷♂️
give me a sec
Yes, do t want to be a purist, but this channel is for Jinja templates. #frontend-archived will help you with all JS templates and card configs
got it
This tells nothing, as you provided the notification action yourself when setting up the automation
I think it's about line:
{{"⤵ \n- "}}{{result.sensors|join('\n- ')}}
The automation only says in message: Low batterys in {{sensors}}
and this results in a notification:
Homeassistant
Low batteries in: ⤵️
- sensor1
- sensor2
In your case add this to the outcome in the for loop
{{-x.name-}}: {{x.state}} {{'\n'}}
That works perfectly, thank you so much!
Maybe this is interesting for you too @mighty ledge if you use IOS aswell
hi there, trying to update my HA OS and getting msg that I should move all my sensors that are on configruation.yaml to other yamls
The only sensor i'm not managing to move correctly is this one:
- platform: template
sensors:
any_phone_at_home:
value_template: "{{ is_state('device_tracker.elians_iphone', 'home') or is_state('device_tracker.ofir_phone', 'home') }}"
device_class: presence
should I move it to sensors.yaml or templates.yaml ?
sensor.yaml
https://imgur.com/cGpPhqA
I do get this error when trying to move it to sensors.yaml
by reading https://www.home-assistant.io/integrations/template#device_class I not longer see presence there, what should I use instead to monitor the phones locations for this sensor
if it's a binary sensor, then it would go in binary_sensor.yaml not sensor.yaml
that did the job, thanks mate
@sonic sand I converted your message into a file since it's above 15 lines :+1:
How would I create a virtual sensor that mimics a input_boolean?
the command line stuff is basically:
rather than having:
type: command_line```
you have
```command_line:
sensor:
sensor definitions go here.```
it's mentioned in the breaking changes
- sensor:
name: CPU Temperature
command: "cat /sys/class/thermal/thermal_zone0/temp"
unit_of_measurement: "°F"
value_template: "{{ value | multiply(0.001) | multiply(1.8) | round(1) | float + 32}}"```
like this 🙂
There is absolutely no message that you should split your configuration.
Yeah, that sounds like a poorly-informed human said that
Could someone help?
simplest possible template sensor
I just need a dummy so it cannot be accidentally toggled
template:
- binary_sensor:
- name: my_boolean
state: "{{ states('input_boolean.whatever') }}"
Does this require a HA restart?
do you already have a template: section?
nope
I suppose. Does the name not need quotation marks?
no
I just hope it's a learning opportunity, because it's a really, really simple template
Cannot quick reload all YAML configurations because the configuration is not valid: Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/configuration.yaml", line 47, column 11
The name line
the documentation is here: https://www.home-assistant.io/integrations/template/
Ok, there was a missing column colon
Reloaded yaml but cant seen the sensor anywhere.
sounds like you asked if you needed to restart, I said yes, and then you didn't?
I restart again now.
Ok, working now. Thank you!
Now it´s gone again. WTF
Can I relace on/off by different words on my dashboard?
im trying to change my command line sensor over from the old yaml type to the new type, but im getting an error that seems to be related to using a l iteral scalar
extra keys not allowed @ data['command_line'][0]['command']. Got 'cat /config/.storage/person'
extra keys not allowed @ data['command_line'][0]['name']. Got 'devicetrackers'
extra keys not allowed @ data['command_line'][0]['value_template']. Got "{{((value_json['data']['items']| selectattr('name', 'equalto', 'jack5mikemotown') | first)['device_trackers']|select ('in', integration_entities('mobile_app'))|list)}}". (See /config/configuration.yaml, line 219).```
for this:
``` command: |
echo "$(sed -n '/^{/,/"entries": \[/p' /config/.storage/core.config_entries) $(sed -e 's/^/{/' -e '$ s/,$//' -e 's/,$/},/' /config/.storage/core.config_entries | grep -w "\"domain\"" | sed '$ s/,$//' | awk '!seen[$0]++') ]}}"
how am i supposed to fix this 😅
and yes, i realize the command is horrendous
if i remove the scalar most of the errors go away but then i get
Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/configuration.yaml", line 226, column 51
which is referencing t he : in that line
i might have had bad formatting but, i just went ahead and redid the entire command to be less convouted lmao
command: "jq '.data.entries |= map ({domain: .domain})' /config/.storage/core.config_entries"
prertty sure its fixed now anyways
Hi,
I am trying to calculate the amount of water in a barrel based on the distance from a sensor.
The problem is that to save battery the esp module goes into deep sleep and only sends back values every 10 minutes. This means that the tasmota sensor is in an "unavailable" state most of the time.
How to I retrieve the last numeric value from the sensor and use that in my template?
Hi,
can someone give me a hint how to create statistics from a template senser like this?
sensor:
- platform: template
sensors:
og_bad_floor_local_temperature:
friendly_name: "OG BAD FLOOR local temperature"
unit_of_measurement: "°C"
value_template: "{{ state_attr('climate.og_bad_floor', 'local_temperature') }}"
device_class: temperature
Change to to a non-legacy format template sensor and add a state class
Perfect, thank you! Is there also a way to set the interval of measurment (i picked the "measurment" state class)?
I think there isn't, not that I know of anyway.
You can only control the interval with a time-based trigger template sensor
@sonic sand I converted your message into a file since it's above 15 lines :+1:
@sonic sand I converted your message into a file since it's above 15 lines :+1:
Fixed this error, nevermind 🙂
@sonic sand that's not a command line switch, that's a template switch.
Yeah, I found the command line hidden in the other .yaml file. I thought this error only comes from the main configuriation.yaml file.
the error refers to the integration, not what file it's in
{% set hours = states('input_boolean.hours') | int %}
{% set start = today_at(states('input_datetime.a'))) %}
{{ start <= now() <= start + timedelta(hours=hours) }}
message was deleted but this is the answer
thanks for your effort. I had a similar approach, but some bracket was in the wrong position. Here is my - still to be simplified - approach:
{{ (now() >= today_at(states('input_datetime.zb_charger_uh_charging_delayed_start_at'))) and (now() <= (today_at(states('input_datetime.zb_charger_uh_charging_delayed_start_at')) + timedelta(hours = 8, minutes = 0))) }}
yep, just realize that you don't need to specify minutes
unless you plan on adding minutes as an input
HA performs all the includes an sees that as your configuration. So that includes all the includes 🙂
what is the best/most efficient way to get numerical day of the week
now().strftime('%w')|int is what i use now
{{ now().weekday() }} or {{ now().isoweekday() }}
does it return int or 01, 02 etc
I just googled for 'python day of week'
ha, thanks 😉
cool, my convoluted calculation is now as simple as {{ (now().isoweekday()/10 + 3)|round(0) <= states('sensor.water_hater_power_meter')|float }}
does it cast it to float upon division?
i want to have 3kwh of quota for mon-thur and 4kwh quota for fri-sun
keeps it an int
but then the sensor is float anyway
so what
most languages can handle int vs double/float without problems
np
{{ (now().isoweekday()//10 + 3) <= states('sensor.water_hater_power_meter')|float }}
might need it to be //5
acutally 4
{{ (now().isoweekday()//5 + 3) <= states('sensor.water_hater_power_meter') }} yeah, makes more sense now
👍
awesome, simple and elegant
Hi, I added a entity_picture via customize.yaml. It is working in some cards but I want more control for other cards. This value is not shown in the sensor atributes however, is there a way how I can get to its value ?
This may be something for frontend but I need it in a template...
it'll be an attribute, look in developer tools -> states page
not visible
I would have expected it there to but nope
sensor.flight_tracker_opensky:
entity_picture: /local/pictures/airplane_1.png
is what I have in customize.yaml
and it shows e.g. on th emap card
what do you mean? which one? the sensor or the calculation?
or both
any time you're trying to do math on a string, and all states are strings
you removed the |float
but theres no string to the left
you should put it back
the math returns int
yes, that's the problem
My sensor shows this as attributes
restored: true
friendly_name: Flight Tracker Opensky
supported_features: 0
```
ah, so i |float the right side
like you had earlier
ok, cool, thanks
Sorry rhqq, when I said "most software handles that", I meant comparing ints/doubles, not int and string
no worries, i didnt know the right side would return a string
as my question got scrambled in other discussion 🙂 ... any idea how I can get to the customized attribute?
it should be showing up, if it's not then I'm not sure what to tell you
well... I can only state what I see, usable in e.g. map card, not visble in the sensor itself.
github entry?
probably not
picture_entity always shows up as an attribute unless it was purposely removed in recent times
well. ... I donot know the history, and this is the ONLY customize I have so far so no experience mor ethan this.
did you put it in the correct spot? Is the entity generated with a unique_id?
yes, i.e. I can modify it with icon a.o.
well, your image is coming from the entity config then and you can't customize it via yaml
ok...hmm.... so how can I add a entity_picture to this type of object then?
so if I want a custome picture for a few objects (in this case these are flights) and I want to call upon them in templates (ful path).....any idea?
you can add custom attributes that are not 'entity_picture' that hold the info
ah.... thanks...will dig into that ... 👍
nothing to dig into, just add something after entity_picture that has the same info as entity_picture
in customize.yaml
clear...dig was a bit too much 😃
assuming you're actually including that under homeassistant:
works: THANKS
can I put literal text {% else %} in a template with out it being proccessed as part of the template? I tried " and ' and it didn't help.
no
if you want to comment things, use comment blocks
{# lkdjalfjdsl d #}
see pin 1
I want it to print it though, as literal text.
are you trying to have a template print a template?
then don't put anything around it
templateception
yes.
{% if ... %}
blah
{% else %}
blah2
{% endif %}
if you want to print a template from a template... you have to use {% raw %}.... {% endraw %}
How do I see that my template got added after reloading my configuration?
developer tools -> states
having a calm moment in the config allows me to revisit template select once more. using an input_select for my themes, and an automation using that as trigger, I tried to rewrite that as:```
-
select:
- unique_id: thema_selectie
name: Thema selectie
state: >
{{states('input_select.theme')}}
options: >
{{state_attr('input_select.theme','options')}}
select_option:- service: frontend.set_theme
data:
name: >
{{option}}```
- service: frontend.set_theme
- unique_id: thema_selectie
which works fine as such. But, I still need that input_select for its options. (unless I write those options, which now are created in the UI, in a verbose list probably). Making me wonder if I do this correctly, not seeing the advantage of the selec template...
I have an Aqara temperature sensor which I have set in the UI to use 1 decimal (precision)
In Mushroom I use this code: {{ states('sensor.hal_temperatuur') | replace (".",",") }}. The problem is that it shows 2 decimals precision instead of 1. This is also the case in the developers tools. What do I wrong?
the main problem I have with the template select (same with number) is that the state is not stored, so you need the input_select to resotore the state after a reload.
yes, and its not reliable without this: - unique_id: thema_selectie name: Thema selectie state: > {{states('input_select.theme')}} options: > {{state_attr('input_select.theme','options')}} select_option: - service: frontend.set_theme data: name: > {{option}} - service: input_select.select_option target: entity_id: input_select.theme data: option: '{{option}}'
The advantage is that you don't need an automation
soin the and this is just a replacement for an automation, ut requires all the same parts..
and instead of using the input select to hold your otions, just list your options as an output of options:
or maybe even more, because this was all i the automation:```
- alias: Change current theme
id: change_current_theme
trigger:
platform: state
entity_id: input_select.theme
action:
service: frontend.set_theme
data:
name: >
{{states('input_select.theme')}}```
use {{ states('sensor.hal_temperatuur', rounded=true) | replace (".",",") }}
if it doesn't restore a state, that's a bug
Thanks that works!
I wrote this WTH on it last year
Yeah, but it needs to be written as an issue
all other template entities restore state
Maybe I'll look into it on my freetime
"they could completely replace" would only hold if we could list those options in the UI?
I thought state based template sensors just get re-rendered based on their state template
so a state based template select also does that
currently my input_select options are in UI, but the template select is in yaml only? Or is that because I use yaml mode...
I'd have to double check, it's been a while since I worked on the template integration
basically the bug is that a trigger based select doesn't then
all template entities are yaml only
yes, so listing those is yet another disadvantage
on the other hand it has the potential to make them dynamic, which you don't have in the GUI
if you could list all your themes using a template, you could use a template to define the options
yes, but that would be a moot thing, because the template should be written in yaml too (Ive done that...)
personally, I'd go with the template select entity and hide the input_select
you can also completely remove the input select and just have an input_text
and put all your logic into your template
or a macro
well, not macro a variable
you can select an icon by using the icon key
my_selects.jinja
{% set themes = {
'a': 'Theme name',
'b': 'Theme name 2',
} %}
Then in your template...
{% from 'my_selects.jinja' import themes %}
{{ themes.keys() | list }}
for options
I'll just write out the whole thing
yeah, because im also strugglin with the state: in the case of ditching the input_select.. what do we use for that in the case of only having a select template
- unique_id: thema_selectie
name: Thema selectie
state: >
{{ states('input_text.theme') }}
options: >
{% from 'my_selects.jinja' import themes %}
{{ themes.keys() | list }}
select_option:
- service: frontend.set_theme
data:
name: >
{% from 'my_selects.jinja' import themes %}
{{ themes[option] }}
- service: input_text.set_text
target:
entity_id: input_text.theme
data:
option: "{{ option }}"
(I don't know if set_text is the correct service call, I'll let you look that up)
I'll experiment there. thx. my main issue remaining: if we still need the input_select for the state: of the template select, why not simply use the input_select for all other bits and pieces
my man, no input_select is used, please read the code
an input_text and a select entity
and 1 dictionary as the source for your options
all yaml
(and jinja)
input_text, input_select. we need an extra helper.
about the losing state thing, just to test it again I created this select
- trigger:
- platform: state
entity_id: input_text.test
select:
- unique_id: test_select_1
icon: mdi:test-tube
name: Test Select
options: >
{{ ["A", "B", "C"] }}
state: "{{ trigger.to_state.state }}"
select_option:
- service: input_text.set_value
data:
entity_id: input_text.test
value: "{{ option }}"
doesn't make sense in usability of course, but after setting a value and a template reload it's back to unknown
so, especially since I'm using a trigger based template select, I would expect it to restore the state
yeah, I consider that a bug, espeically if it's using a trigger
I'll write up an issue for it
anyways, using the non-trigger approach will definitely "restore" state because it's resolving the helper entity, which retains the value on restart.
input_text.set_value
You'll need to change the field in data: to value: as well then
comparing all of that with```
- alias: Change current theme
id: change_current_theme
trigger:
platform: state
entity_id: input_select.theme
action:
service: frontend.set_theme
data:
name: >
{{states('input_select.theme')}}``` seems to close in favor of the automation. Especially so since we can set the options of the input_select in the UI, and it is immediate, not requiring a reload custom_templates.
You do whatever you want to do, I personally avoid the UI for all tinkering because it takes 10 years
yes, you have a point there.. yet it has taken me months of moving everything possible to the UI, and I must admit its very adequate, responsive, immediate, and doesnt break. Ive grown to love changing names/icons, heck even entity_ids on the fly, without having to open an editor
all in my yaml is custom or templates. or the odd integration not yet in config entry
and they never will be
So many things would need to happen in the frontend to get templates in the UI
no, that's fine though.
but anything yaml will never be in config_entry
as soon as they move the integrations to the UI, you'll get a config entry
yes, that is cool, and from that moment on we have unique_id's, and we can edit the entities in the UI. just like with template now: Ive taken out all icon/name etc from the yaml, as I can set it in the UI. Themes allow for custom colors per domain, so my custom_ui has decreased with 80%. we even can set show_as, or change units in the UI. really its very nice. My Yaml for templates is nowhere near what is used to be 😉
Template to create sensor of tide height
started a thread, any help appreciated!! thank you 🙂
@floral shuttle I converted your message into a file since it's above 15 lines :+1:
Problem was solved, thanks 🙂 My bad- consequtive writes to same topic created a rush with overwriting data before processing 😦 Problem was:Stuck on getting data from Tasmota to HA. Tasmota sends to MQTT like this:
RESULT = {"SerialReceived":{"Toast":"32"}}but I am having trouble to create a mqtt sensor from it. Is the problem with "" around the 32 data? HA complains:Template variable warning: 'dict object' has no attribute 'Toast' when rendering '{{value_json.SerialReceived.Toast}}'
TheFes, didnt you have some of these translated? its a pain with all of these changing words in Dutch... 😉
aren't you using easy_time?
sure! is that in there too? and the accompanying couter down to dec 31st?
{% from 'easy_time.jinja' import big_time %}
{{ big_time(now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)) }}
`mqtt:
sensor:
- name: 'Magamistoa LG toast'
unique_id: lghvacairtempsleep
state_topic: "tele/tasmota_EE44FC/RESULT"
json_attributes_topic: "tele/tasmota_EE44FC/RESULT"
json_attributes_template: >
{"Toast":{{value}}}
value_template: "{{value_json.SerialReceived.Toast}}`"
that horrific dev tools window.... trying to add the language
ooh, but nice! almost perfect! returning '23 weken, 5 dagen, 14 uren en 52 minuten' were would always say 23 weken, 5 dagen, 14 uur en 52 minuten in Dutch..
can we use Bigtime also for counting down to next new year?:```
{% set Year = now().year +1 %}
{% set newYear = as_timestamp(strptime('01/01/' ~ Year, '%d/%m/%Y')) %}
{% set now = as_timestamp(now().astimezone())%}
{% set New = newYear-now %}
btw given the generic usability of the following, it might be nice for easy_time too?:```
- unique_id: sunset_offset
state: >
{% set nw = now().timestamp() %}
{% set ss = as_timestamp(state_attr('sun.sun','next_setting')) %}
{{'- ' if nw < ss}}{{(nw - ss)|abs|timestamp_custom('%H:%M:%S',false)}}
- unique_id: sunrise_offset
state: >
{% set nw = now().timestamp() %}
{% set ss = as_timestamp(state_attr('sun.sun','next_rising')) %}
{{'- ' if nw < ss}}{{(nw - ss)|abs|timestamp_custom('%H:%M:%S',false)}}
yep!, missed big_relative_time, and had to fiddle a bit to get the new new year in there.. {% from 'easy_time.jinja' import big_relative_time %} {% set year = now().year +1 %} {% set new_year = year~'-01-01 00:00:00' %} {{ big_relative_time(new_year, language='nl') }}
yeah, you're right, should have used uur for both the singular and plural translation
I issued a PR to have it changed 🙂
cool, in my count down to next new year, is there no easy way of replacing the year +1 in {{now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)}}
or would {% set year = now().year +1 %} {{now().replace(year=year,month=1, day=1, hour=0, minute=0, second=0, microsecond=0)}} be shortest
well, its on the big screen every Christmas period...
the template?
well no, the output of that template
I'm sorry, I have no idea what you're asking
is there a reason you need to shorten everything?
ok, sorry for some confusion. First of all this works fine now: {% from 'easy_time.jinja' import big_relative_time %} {% set year = now().year +1 %} {{big_relative_time(now().replace(year=year,month=1, day=1, hour=0, minute=0, second=0, microsecond=0), language='nl')}}
when dealing with your timezone, there's no replacement.
you have to replace all those variables and the year
and is better than my earlier string concatenation in #templates-archived message and outputs over 28 weken, 2 dagen, 8 uren en 26 minuten just perfectly
your earlier one omits TZ but that will work with mystuff
it assumes local
{% from 'easy_time.jinja' import big_relative_time %}
{{ big_relative_time((now().year +1) ~ '-01-01 00:00:00') }}
my other 2 templates were a suggestion to add to easy_time #templates-archived message
except that is not the same. but I will search those example to see if its in there, sorry if I indeed missed that
about the new years count down, they now are all identical , so that is indeed very nice
closest is
{% from 'easy_time.jinja' import time_between %}
{{ time_between(now(), 'sun.sun', attr2='next_setting') }}
yeah, guess the others are fine too, it all depends a bit what your eyes need
having said all of that, the Frontend has evolved since I made those templates with Phil, and using a type: attribute with format: relative isnt so bad either..
it could benefit from the precision of minutes we can show in the templates, but other than that it's quite nice
grr, what am I missing now:```
{% from 'quakes.jinja' import quakes %}
{% set quakes = quakes().split(',')|reject('eq','')|list %}
{% set count = quakes|count %}
{% if count == 0 %} No Quakes registered
{% else %}
{{quakes().split(',')|map(attribute='name')|join(',\n')}}
{% endif %}
throws 'TypeError: 'list' object is not callable'. quakes now returns [ "geo_location.m_4_8_4_km_sse_of_courcon_france" ]
my custom_template for quakes is {%- macro quakes() -%} {{- states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','usgs_earthquakes_feed') |map(attribute='entity_id') |join(',') -}} {%- endmacro -%}
@floral shuttle I converted your message into a file since it's above 15 lines :+1:
this works: {% if count == 0 %} No Quakes registered {% else %} {{quakes|join(',\n')}} {% endif %}
You’re overwriting quakes macro with a variable
Change {% set quakes = to some other variable
a yes, didnt spot that, keen eye!
but,, in the complex namespace, I dont have that: {% set km = states('input_number.quakes_near')|int %} {% set location = states('input_select.quakes_near') %} {% from 'quakes.jinja' import quakes %}{% set ns = namespace(count=0) %} {% for s in quakes().split(',')|reject('eq','') if distance(states[s].entity_id ,location) < km %} {% set ns.count = ns.count + 1 %} {% endfor %} {% if ns.count == 0 %} No Quake to list within {{km}} km {% else %} Quakes near: {% for s in quakes().split(',')|reject('eq','') if distance(states[s].entity_id ,location) < km %} {{- state_attr(s,'friendly_name') -}}: {{states(s)}} km{{', \n' if not loop.last else ''}} {% endfor %} {% endif %}
im struggling t get that saner. its working, and showing the selected quakes on the map, its just that I am positive this can be sanitized.
above is for listing in a markdown, for the map I use this listing: {% set km = states('input_number.quakes_near')|int %} {% set location = states('input_select.quakes_near') %} {% from 'quakes.jinja' import quakes %} {% for s in quakes().split(',')|reject('eq','') if distance(states[s].entity_id ,location) < km %} {{- states[s].entity_id -}}{{',' if not loop.last else ''}} {% endfor %} which is a bit cleaner, but it only has to list the entity_id's
I want to do something like this for hurricanes lol
yah, its working nicely now, though I admit its a bit more complex than what I had before, without using that custom_templates.```
{% set km = states('input_number.quakes_near')|float(0) %}
{% set location = states('input_select.quakes_near') %}
{% for s in states.geo_location
|selectattr('attributes.source','defined')
|selectattr('attributes.source','eq','usgs_earthquakes_feed')
if distance(s.entity_id,location) < km %}
{{- s.entity_id -}}{{',' if not loop.last else ''}}
{% endfor %}
here you go, all that I have..
Hi, trying to read my areas and exclude a few, not going great. This is what I would like to do, can't find what syntax I need for areas
{% set reject_areas = ['bathroom', 'closet'] %}
{{ areas() | reject(reject_areas) | list }}```
I checked the docs, and areas() lists all of them, but how do I exclude some?
try {{ areas()|reject('in', reject_areas)|list}}
what is my best approach for turning a date into a string "Today", "Tomorrow", "Monday" etc
- name: "Living Room Warmed Up"
availability: "{{ states('sensor.living_room_feels_like_temperature') | is_number }}"
state: >
{{ states('sensor.living_room_feels_like_temperature')|float >= 22.0
or state_attr('climate.mitsubishi_hvac','current_temperature')|int >= 23 }}"```
for some reason this won't turn on. - when I put it in the template editor it shows as on
but the sensor won't turn on in HA
Get rid of the last " at the end
great pick up! thanks 🙂
morning guys,
Is there a way to set 2 different scripts depending on the state of the entity?
I will be more specific - I got input.select AC which indicates the status of the device (On / Off).
I want my tablet to be able to turn it off/on with the same button and not have two buttons for each state.
http://pastie.org/p/4HiKG5981SJQOKKpn0JrQZ
I wanna do something that if state equals On then when a click action is performed it will send the 'script.ir_turn_off_bedroom_ac'the and if state is Off it will send the other script of turning it on.
the
Thanks!
With a choose: in your script
There's no other way to do it? like inside this button? because I have many automations with those two scripts already and I don't want to ruin them...
Create an automation that calls one script or the other depending on the state, and use automation.trigger for the service on your button.
like that?
http://pastie.org/p/6ENI6GkS0TxzSCIIMffh69
What trigger/condition should I add to this one before trying to add to the button the automation.trigger you've suggested?
Actually no, I'm dumb, do the exact same thing but with a script, and then call that script from your button.
Let me try that
howdy, got a strange one. i cant test the value of a attribute. see attached
{{ state_attr('sensor.steamdeck_power', 'status') == state_attr('sensor.steamdeck_power', 'status')}}
{{ state_attr('sensor.steamdeck_power', 'status')}}
{{ is_state_attr('sensor.steamdeck_power', 'status', "Charging")}}
{{ is_state_attr('sensor.steamdeck_power', 'status', 'Charging')}}
{{states.sensor.steamdeck_power}}
outputs:
True
Charging
False
False
<template TemplateState(<state sensor.steamdeck_power=94
; battery_present=on, charge_full=5102000
, charge_now=4806000
, level=Normal
, status=Charging
, voltage_min_design=7800000
, voltage_now=8776000
, unit_of_measurement=%, device_class=battery, icon=mdi:battery, friendly_name=Steamdeck Power @ 2023-06-18T00:43:29.931248-07:00>)>
any help" id like to know if its sharging or not
dev tools show:
battery_present: 'on'
charge_full: |
5102000
charge_now: |
4772000
level: |
Normal
status: |
Charging
voltage_min_design: |
7800000
voltage_now: |
8783000
unit_of_measurement: '%'
device_class: battery
icon: mdi:battery
friendly_name: Steamdeck Power
you most likely have to strip the value in the attribute as it looks like it has whitespace.
.strip()
hey so i am trying to create an mqtt sensor to get data from tasmota throught mqtt and i got everything to work but when i try to add "availability_topic" or "availability" to check get the online status the sensor stops working. any help is appreciated. https://pastebin.com/B3HCps5N
Fixed it by pushing payload_available and payload_not_available right under -topic and not availability. Might be a syntax error in the mqtt sensor docs because the way shown in the example at the bottom doesn’t work (at least for me )
I was considering converting my platform: template sensors to the new template format, but I can not see how to carry over the friendly name, having to use the customise.yaml seems a strange way to have to do it, does anyone know, if there is a way to do it more logically. I have quite a lot of template sensors so it will be a big job.
You can change the name in the UI if you give it a unique ID
the name: is the starting point
Shame that is the only way, I will have to sort out a long list to change after I convert all of them. I have loads such as formatted_sunrise which I just want a friendly name of Sunrise.
It seems strange, support for it has been dropped.
it wasn't just dropped willy nilly, long story short is other features that people wanted trumped that... and you couldn't have both features.
basically, a templated friendly name is what caused the conflicts.
I can obviously get around it or just not bother until the powers that be drop support for the old format as they did with the commands and I have to.
it's not going to happen
the discussion has been had about 8394823984 times and there's no way to get object_id back that works with the 'naming convention' built into HA
with the new style
half of it's stupid politics
you can however make a script that builds your customize for you
{% for s in states %}
{%- if s.attributes.friendly_name is defined %}
{{ s.entity_id }}:
friendly_name: {{ s.attributes.friendly_name }}
{%- endfor %}
and now you just need to transfer over and you're done
so make your name equal to your object_id
you can even write a script that does that
Thanks for that. I will write a script in lua to covert the old formats, as I can't write python.
I just looked at lau... never heard of that language, most of that code would run in python with like 2 changes
selling yourself short by not just learning python IMO
I will probably get the hang of it eventually. I started programming in assembler and BASIC in 1980 on a Research machine. So I am about 15 programming languages in at this point.
And of course the correct number of spaces
IDE's do that for you
just hit enter on the keyboard 😉
download VSCode, set your filetype to python, select python as the interpreter, then start writing
Me and Visual Studio code have a love hate relationship, but I have to admit it is good for editing Yaml files.
I have the Home Assistant extension loaded so it makes it easier.
PyCharm > VSCode for python at least
Lol, no way
maybe if you have professional edition
bare bones to bare bones, vscode has way more resources to just setup and run with google at your fingertips
Students get the professional edition for free
And it's a full featured ide, as opposed to VSCode which is a text editor with some fluff imo
lol what? It's full featured... Have you used it before? It has everything, intellisense, auto-complete, linting, annotations, debugging, debug attaching, source-control
I used pycharm for ~6 years and switched to VSCode without looking back, it's no where near a "text editor with fluff". That would be notepad++
I've used it a bit and was underwhelmed, it's possible extensions and stuff add the features I was missing though
You do need to add in the extensions to match the languages you want to use, to get VSCode to work well.
stupid issue, my rhasspy is doing this when im trying to pull the temperature data 'It is <template TemplateState(<state sensor.temperature=26.46; state_class=measurement, unit_of_measurement=°C, device_class=temperature, friendly_name=Temperature @ 2023-06-18T23:11:17.677035+01:00>)> degrees
it looks like you forgot to add .state
or something like that. You'll need to show exactly what you did
that sounds about right
it's just dumping the entire sensor data instead of the state, trying that now
yup\
that fixed it
otherwise, you need to show what you did, not just the bad output
ok
then you should really be doing states('xxx')
i honestly have never messed this before, i just pulled this from the docs to test intent_script: GetTemperature: # Intent type speech: text: We have {{ states.sensor.temperature }} degrees action: service: notify.notify data: message: Hello from an intent!
Can someone help me get my desired output from a template
I have four sensors like this: sensor.daily_energy_offpeak
That have attributes like this:
status: collecting
friendly_name: Off Peak
Only one is collecting at a time, I'd like to display the friendly name of the tariff that is collecting.
I'm doing this at the moment with The tariff period is {{states('select.daily_energy')}} but that state is not formatted like the friendly_name field is.
What does it mean that they're "like this"? Are they all options in that select entity?
if so:
{{ expand(state_attr('select.daily_energy', 'options'))|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='friendly_name')|first }}
they all have the same structure off attributes which incudes status: and friendly_name:
yes they are. was just trying to save text.
sensor.daily_energy_offpeak
sensor.daily_energy_peak
sensor.daily_energy_shoulder
sensor.daily_energy_superoffpeak
alright. I don't know what's in that select entity
what is its state?
you only said "that state is not formatted like the friendly_name field is."
Ah, sorry.
select.daily_energy
icon: mdi:clock-outline
friendly_name: daily_energy```
status: `shoulder`
it's state is changed based on the times that my tariffs change
Basically, for the template, if select.daily_energy is superoffpeak then I'd like to display that name in a print friendly format, like Super Off Peak
I can do this:
The tariff period is
{%- set tariff = states('select.daily_energy') -%}
{% if tariff == 'offpeak' -%}
{{ ' ' }}off peak
{% elif tariff == 'superoffpeak' -%}
{{ ' ' }}super off peak
{% else -%}
{{ ' ' }}{{tariff}}
{% endif %}
But it doesn't feel very smart, I'll need to maintain it if I change tariffs
{% set tariff = states('select.daily_energy').replace('off', ' off ') %}
{{ tariff if tariff == ' off peak' else ' ' ~ tariff }}
oh clever!, I was trying to understand how it works for 'super off peak'. It adds a traileing space too. Always a simple way to skin it.
actually, that's not quite right either
I was trying to unpack this as there's a few functions I haven't used before.
{{expand(state_attr('select.daily_energy', 'options'))}} returns [], not the four options.
yeah, that won't work for you
What are you seeing?
it won't add a leading space for "super off peak"
Ah I see.
what does the ~ do?
concatenates
well there you go.
There's probably a prettier way but {{ ' ' }} will always add a leading space?
but then we'd get two for 'off peak'
My thought was:
Read state of select.daily_energy
set that as 'something'
Than substitute in to sensor.daily_energy_{{something}}
Then use that in state_attr('','')
Not sure if or how we can do the substituting part.
yeah, what I thought was super simple turns out to be a lot of overthinking.
this illustrates what I'm trying to do - but I know that's jsut a print statement.
{% set something = states('select.daily_energy') %}
state_attr('sensor.daily_energy_{{something}}','friendly_name')
you mean this one?
It works.
The original gave hte info, it was just poor formatting on my custom energy dashboard.
More about learning how to template well, rather than the problem at hand.
that comes back to what I provided originally
{% set map = ['offpeak', 'peak', 'shoulder', 'superoffpeak']|map('regex_replace', '^', 'sensor.daily_energy_')|list %}
{{ expand(map)|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='attributes.friendly_name')|list|first }}
I'm just unpacking this at my slow pace ha!
the first line works and produces a map
the second line is giving me an error with the |map filter
{{ expand(map)|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='friendly_name')|first }}
UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'friendly_name'
I'm testing it in /developer-tools/template - assuming that is the right way to do this?
Sure
attributes.friendly_name
Yes, I fixed it
aha, sorry I missed the edit. Wasn't sure what I was trying again! that seems to be working
{% set options = state_attr('select.daily_energy','options') %}
{% set map = options|map('regex_replace', '^', 'sensor.daily_energy_')|list %}
{{ expand(map)|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='attributes.friendly_name')|list|first }}
This is working and if I change or add more tariffs it should continue to work, rather than providing the list? right?
I like it. thanks for your help. Always learning. I will now head off and read about |map filter and regex_replace and how it's used.
Hey,
I'm getting the following error on logs:
http://pastie.org/p/43ADNrPVRA9VTZsxRIwQ0W
sensor.feed_record_timestamp - state in dev tools:
2023-06-18T16:14:51+00:00
the template itself:
http://pastie.org/p/1ZkJHDhB75pIZJcQKUOsB5
Thanks!
Is sensor.feed_is_missing_timestamp working now?
if so, add
availability_template: "{{ 'sensor.feed_record_timestamp' | has_value }}"
Yeah man, it says on state:
2023-06-20T19:14:51+00:00
http://pastie.org/p/6Ji5cCVQTIqm7zUbs9XFWk
like that?
after restarting HA (after adding that availability template, I do get a diff error now)
http://pastie.org/p/3AhIFt7TofRHAHksIslE9f
that one looks fine now
{% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
{{ as_datetime(feed_record.timestamp)|timestamp_local }}
this is the template it errors on, which is not in the code you provided above
just use the same a you did in the code you provided
the availability_template?
{% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
{{ as_local(as_datetime(feed_record.timestamp)) }}
that
which you are using here: http://pastie.org/p/1ZkJHDhB75pIZJcQKUOsB5
I don't know where you are using this {{ as_datetime(feed_record.timestamp)|timestamp_local }} but that's not valid
I'm using it here:
http://pastie.org/p/6iVphhkcirVPkQcEfVsi6C
timestamp_local expects and integer, not a datetime
so I should change line 14, right?
yes
what do you expect as a result there? a datetime like 1970-01-01T01:00:01+01:00?
of a timestamp, like 1687166020.810728
no, because that sensor was actually working
OK, I changed line 14:
http://pastie.org/p/43tkwCEajbkYO9VWsj8Cjp
according what you said here
maybe the sensor wasn't available then for few days because it missed some feeding a week ago and one fish died 😦
well I don't mind how will it look like... I just want to get a notification on if it fed them or not
Result type: string
- platform: template
sensors:
feed_record_result:
value_template: >-
Trueavailability_template: "True"
attribute_templates:
timestamp: >-
2023-06-18 19:14:51+03:00friendly_name: "Automatic Feeder"
device_class: problem
This template listens for the following state changed events:
Entity: switch.hfjh_v2_eadb_fish_tank_2
looks fine now
thats from dev tools
is this a binary sensor?
yeah, you helped me with that btw
ages ago, and you didn't include the binary_sensor part
yeah it was in a diff yaml file
but anyway, the state of this binary sensor will be on or off
http://pastie.org/p/1ZkJHDhB75pIZJcQKUOsB5 why are you creating the first sensor here, and also putting the same information in the attribute of the other sensor
just remove that attribute as you already have another sensor providing the same data
and how do I set a trigger for case the fed time was 2 days ago + 2 hours?
like you are doing
You mean get rid off the
feed_is_missing_timestamp
right?
so what attribute?
http://pastie.org/p/6iVphhkcirVPkQcEfVsi6C I meant you should remove the attribute from this binary sensor
attribute_templates:
timestamp: >-
{%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%}
{% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
{{ as_datetime(feed_record.timestamp)|timestamp_local }}
{%- endif -%}
This part
as your feed_record_result sensor you created here http://pastie.org/p/6iVphhkcirVPkQcEfVsi6C is doing the same thing
is it causing any problems?
ok will remove it right away, so I keep my trigger as it is?
the attribute as you have it now is causing problems
and you were not using it for the feed_is_missing_timestamp sensor, you were using sensor.feed_record_timestamp there
well I'm using those aquarium sensors for two triggers, one is the missing feed as I sent you already.
the second one is this one:
http://pastie.org/p/3654OgIqHtbUAHbrAyikt2
yes, that one is not using template sensors at all
it is using the values directly from the switch
everything does rely on the switch being available though
so if the switch is not available for 2 days, nothing of this works
yeah it's Chinese aquarium so it's not that stable 😦
thanks for help!
one more thing related to templates
I got watchman report thingy and it says i have problem with two groups in my templates.yaml
| group.tvs | unknown | templates.yaml:17 |
| group.temp | unknown | templates.yaml:37
http://pastie.org/p/173YR1Kplyq4oyRV1cimfd
What did I do wrong there?
is this in templates.yaml http://pastie.org/p/173YR1Kplyq4oyRV1cimfd ?
There is nothing wrong probably, but these groups you defined have entities of which HA can not define a group state
so it defines the state as unknown
and in your templates, you are probably using them for expand, to get data from the group members
watchman doesn't understand that, and it sees you are using an entity with unkown as it's state
and it reports that
watchman isn't that smart
oh ok, thanks for the explanation.
is there a smarter addon I can use that scans my yaml files like Watchman?
There's Spook, but according to it's license terms you are not allowed to use it
Alright, thanks man.
I tried to create those groups via the UI in the helpers menu but it has no counter, I just need to count how many entities are within the group and how many of them are on/off state
This is probably really easy.
{{ states.sensor.hvac_operating_mode.last_updated }}
Is 2023-06-19 04:59:07.962340+00:00 while developer tools is
Last updated:
June 19, 2023 at 12:59:07 AM
Why is the template showing 04 and not 00
because that's UTC
use as_local to get it to your local time
but it's pointless if you're just displaying it in the frontend because the frontend handles that for you.
and it's already a datetime object, so as long as you compare it to another TZ aware datetime, it doesn't matter if it's in UTC or local, the comp will work

I'm using this for an automation so I would need as_local. I figured this would be something simple, thank you guys.
no you don't
if you compare it to a local datetime, it compares the times properly
you can compare now() to a last_updated and even perform math and it will work as if it's in your TZ
@silent vector
Oh I would be comparing it to a sensor attribute that's {{ now() | string }}
Is that an attribute of a trigger based template sensor?
Yep
but why is that a string?
that should be a string at all
states.sensor.thermostat_automation_memory.attributes you said to use {{ now{} | string }}
To store time in attributes and access it with that ^
Did it complain about it being a datetime object?
My memory is fuzzy
if it did, then just use utcnow() | string instead
Nope it works without issues
if it doesn't care about datetime objects, then just keep it a DT object
then it doesn't matter
I honestly can't remember
As in comparing the utc | string time to a now() | string should work?
if you're comparing as strings, they both need to be in the same TZ and same format
if you're comparing as datetimes, it doesn't matter
Makes sense thank you
Looking for a way to store the first datetime for when a binary_sensor was triggered today. Is it possible to do that with templates or would I need to rely on an automation to store and reset the value? My point is that I have a history_stats sensor where I want to measure the amount of times a sensor is opened from it's first time and 5 minutes into the future from then.
automation to store the datetime into a input_datetime
best option IMO
I guess and then just reset it every midnight, so two automations it is
or an additional trigger
trigger:
- platform: time
at: "00:00:00"
- platform: state
entity_id: binary_sensor.foo
to: "on"
condition:
- condition: template
value_template: >
{% set last_trigger = this.attributes.last_triggered %}
{{ last_trigger < today_at('00:00:02') if trigger.platform == 'state' or not last_trigger else true }}
action:
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.foo
data:
datetime: "{{ now() }}"
something like that
Hi #templates-archived !
I have a Hue lightstrip (and some other Hue color lights) that unfortunately don't have an available "colorloop" effect. I think the best way to go about adding on this effect would be with a light template. My idea would be to create new light template (e.g. light.strip_template) that has its state and all of its attributes inherited from light.strip, except replace the effect_list_template, effect_template, and set_effect with custom code that adds a "colorloop" effect that calls a colorloop script or automation (how that automation functions is a separate issue). So my question are: Is this a good way to go about my little project? Is there a quick way to have a light template simply inherit all of its attributes and state from a parent light? Also, what does "inclusive" mean in the documentation (e.g. "effect_list_template template (inclusive, default: optimistic)")?
I think you will need to manually set all the values. Then have a script defined to run any effects. If I was doing it, I would write the script first to make sure you can get the effect you want before creating the templated light.
inclusive means it's paired with another field that is required. In that case, its most likely set_effect
i.e. if you don't include that other field, the check config will fail
Also, there is no "quick way" to make it inherit fucntions from another light. You have to painstakingly build it all. 🎉
Thanks guys!
Maybe we'll get a default colorloop effect (and maybe some other fun ones) in a future Hass update, similar to the recent "favorite colors" light feature.
doubtful
All effects are provided by the hardware (or software) that HA talks to. HA does not create any effects.
@spiral grove ^
Yea, I guess this would be more in the realm of an Integration
You can make a color cycle script pretty easily
Yea, I'm not too worried about that part.
I'm just imagining an integration that extends the features of smartlights to include a few things they are physically capable of but don't yet have the software for
alias: cycle colors
variables:
colors:
- [255, 0, 0]
- [0, 255, 0]
- [0, 0, 255]
target_light: >
{{ entity_id | default }}
sequence:
- condition: template
value_template: "{{ target_light is not none }}"
- repeat:
for_each: "{{ colors }}"
sequence:
- service: light.turn_on
target:
entity_id: "{{ target_light }}"
data:
brightness: 255
rgb_color: "{{ repeat.item }}"
- delay: "00:00:05"
You'd need another repeat for indefinitely
That's template light
it just doesn't do anything automatic
I mean, kind of... it's missing the implementation.
And the average user would never take the time
Well an average user isn't going to understand inheritance
Hence, a user-friendly integration.
average users (who've been doing this for years), just make a script with a dropdown
Kind of like how "switch-as" could pretty easily be accomplished with templates
switch as only works because the domains it changes to supports on/off
or some variation of on/off
otherwise, it wouldn't work
lights are very rigid and have many requirements. It would be very doubtful that an integration like this would be built
not to mention, it would be a ton of code, just to get it to mimic another light, but have an extra effect
when you can simply just make a template select that does the same thing or a input_select w/ an automation that does the same thing
Couldn't you make the same argument about the recent "Favorite Colors" feature.
not really
I honestly don't know enough about the backend to say yay or nay
that just extends existing supporting colors into separate buttons
it does not link a dropdown to some script
not to mention, that's all handled by the frontend and the backend has no concept of it
Gotcha.
So, like, hypothetically adding a toggle next to those Favorite Color buttons that cycles through them every 30 seconds would be a much bigger ask?
Disregarding the utility (or lack ther-of) of such a feature
Yes, the frontend doesn't run automations
it simply runs a service when it's told to by the user
Well thanks for taking the time to answer my questions, @mighty ledge ! Much appreciated.
No problemo
hi there just curious what is the best way to add a wake on lan service that i can add to a zigbee based smart button.
# wake_on_lan:
# switch:
# - platform: wake_on_lan
# name: x
# host: x
# mac: x
This is what i have no and it works only to use as a button on my dashboard
but when putting it to my smart button
it gives an error
I don't see any templates here
You probably need #automations-archived to toggle the switch with your smart button
Oh ok thank you
Missing something obvious as a noob. Looking at templates. There seems to be lots of info on syntax and such. What do you use a template for? Do you incorporate them in cards somehow?
Are they card templates? Automation templates?
The demo template produces a string. How do you use it?
I only see space for one in the editor. Is this for testing only & then you cut and past somewhere?
I started down this road of googling how you get HA to use tts to say the weather. Someone advised “use a template,” which seems to be a way to build the speech string. Now, how do I use it in a card or script?
Templates allow you to extract and modify data from entities' states, attributes, and properties. Some custom cards allow templates, but most core cards do not. They can be used in some parts of scripts and automations including variables, template conditions and triggers, as well as in service call actions.
So, they are essentially inline functions or code for building strings?
They can output data types other than strings.
Data structures. Not just strings
Where can you use them? Tried various types of cards with no luck. Scripts?
Going back to link….
The info at the link talks about editing system files. I was just looking for a way to add sensor data to a script or card. This seems more like a developer kind of thing? A little too new to this to go mucking about in the file system. I guess that’s done via ssh and your favorite editor, remembering back to Unix and college days.
I'm trying to create a light group that contains all light entities that are currently on, ignoring groups, and ignoring Fully Kiosk Browser screens. Here's my template that works in Dev Tools
{{ states.light
| rejectattr ('entity_id', 'in', integration_entities('group'))
| rejectattr ('entity_id', 'in', integration_entities('fullykiosk'))
| selectattr( 'state' , 'eq' , 'on' )
| map ( attribute = 'entity_id' )
| list
}}```which returns `['light.bedroom1', 'light.kitchen', 'light.stove', 'light.living_room1', 'light.living_room2', 'light.bedroom2']`
Now, I'm trying to figure out what to do next with it. Is this what I would need to put into configuration.yaml?
light:
- platform: template
light:
all_lights_on:
friendly_name: 'All Lights On'
value_template: "{{ states.light
| rejectattr ('entity_id', 'in', integration_entities('group'))
| rejectattr ('entity_id', 'in', integration_entities('fullykiosk'))
| selectattr( 'state' , 'eq' , 'on' )
| map ( attribute = 'entity_id' )
| list
}}"
I'm confused because when I used to make light groups in YAML (a long time ago), it would be ```yaml
light:
- platform: group
name: All Lights
entities:- light.bedroom1
- more entities follow```
You can't create a group like that
The only way to create a dynamic group is to use group.set
Okay. So, ultimately, I need to create an automation that updates every so often to make the group dynamic and the entities based on the template? Example found:```yaml
sequence:
- service: group.set
data_template:
object_id: my_lights
entities: |
{{ states.light | map(attribute='entity_id') | join(',') }}
mode: single
alias: Create 'my_lights' group for every lights
icon: mdi:lightbulb```
IIRC, group doesn't handle brightness like a light group does. Is there any way to get this to work as a light entity? This is why I used to used the ```light:
- platform: group```method.
That's not a valid thing
You can't just do it differently
And groups actually do handle brightness. It will affect any lights in the group
Try it
It is a valid thing. Just not used any more that it can be configured in the UI. Here's what I used to use. https://i.imgur.com/v1ZiER8.png
Tried with group.set. Only has entity_id, order, auto, icon, and friendly_name.
You should try other things
That's rather cryptic.
not really. brightness:, like you want
not following you
I'm not following you
Make a group, turn it on and specify brightness
That's the point, right?
how does it work if it doesn't have the attribute? (I tested and it does adjust brightness.)
Actually, it only kind of works.
service: homeassistant.turn_on
data:
entity_id: group.whatever
brightness: 100
So it works
Reverts back to "100%" after a couple of seconds. (Brightness slider card.) So it can send the brightness but the group itself doesn't actually retain the value.
That's probably the card
You could try to create a template light
Which is on when any light (excluding groups and kiosk mode) is on
Yes, I suppose they could do that too
He was already doing that here 🙂
Big Slider Card is the one I was testing. Light Card refuses to work with a group. Mushroom Light Card brightness slider disappears when the group is selected. Custom:button-card can't "see"/return brightness of the lights.
Which can all be solved by creating a template light 🙂
https://www.home-assistant.io/integrations/light.template/ might be able to figure out something here. Looks like there is a value_template.
Yes, which should return true or false
That one determines the state of the light (so on or off)
It's all just more complicated than a group, IMO
But, briefly looking over it, it doesn't look like there is an option to define entities.
Right, but the group doesn't work for what I want. I need the attributes of a light entity which a group does not have.
have a template with state: {% set event = '1997-06-20'|as_datetime|as_local %} {% set year = 1 if event.month < now().month or (event.month == now().month and event.day < now().day) else 0 %} {% from 'easy_time.jinja' import count_the_days %} {{count_the_days(event.replace(year=now().year + year)) }} and today it's returning 0, whihc is correct ;-0
now why wont this attribute not return true, or on:```
feest: >
{{states(this.entity_id)|int(default=-1) == 0}}
or using {{this.state}} for that matter. guess I ll just have to use another hard coded template...{{now().strftime('%m-%d') == '06-20'}}
You can define the entities in the service call
does it return true in devtools if you put this at the top of the text field
{% set this = { 'entity_id': 'sensor.your_template_sensor' } %}
and is it a trigger based template sensor, or a state based?
trigger based..... and if I make it a regular binary template, it works as expected.
I am moving to deleting all this variables out of the configs, its just to unreliable
The templates are rendered on trigger, so before the state has been changed
You can add an additional trigger a second later so it will use the new state
They are not unreliable, but they work different than your expectation
the this variable was introduced for self reference. the fact it behaves differently when used in trigger based templates then a verbose template is inconsistent imho. And yes, against expectation..
it's not the this variable what causes this
if you would have used states('sensor.your_sensor') | default(-1) | int == 0 you would have had the same result
what causes is is the fact that the templates for trigger based templates are rendered on the trigger, so before the state change in your state template
so when the attribute template is triggered, your state value is still "1"
yes, and one has to consider that very carefully, and check trickle down. In my config, I have some binaries based on the state of the trigger template, and they would turn on, triggered by:```
template:
- trigger:
- platform: time_pattern
hours: 0
minutes: 0 - platform: homeassistant
event: start - platform: event
event_type: event_template_reloaded``` . Ive moved that to regular template binary,, and now it is immediate, based on the same template trigger from the above trigger...
- platform: time_pattern
- unique_id: count_celebrations
state: >
{{expand(state_attr('binary_sensor.feest_alerts','entity_id'))
|rejectattr('state','in',['unknown','unavailable'])
|selectattr('state','eq','on')
|list|count}}
icon: >
mdi:numeric-{{this.state}}-box
``` is another example...
same thing, this.state is the state before the new state template is rendered. it's like the trigger.from_state.state in an automation
ok. I figured I might also need to guard that icon template so added mdi:numeric-{{this.state|int(default=-1)}}-box and see what happens on reload, it somehow gets a state of 0, and the icon is updated to -1
yes, that's because it changed state from unavailable to 0
so this.state was unavailable
but the state should be 1
the others are template binary_sensors too, so it will be a race on template reload
ah yes, that might be it
the one which should have made it 1 was still unavailable
well, moving it to a regular template fixes it (and yes, also with the this variable)
I have a mqqt sensor that is the cumlative of a week of data (Resets every sunday), I need to see this data for today instead, what would be the best way to do this?
Is it possible to define a binary_sensor that is not a template sensor using configuration.yaml instead of helper entities?
I'd like to have the custom sensor at hand in the scripts, but be able to add a toggle representing it in the UI too
one that saves the state, but has not a template value
oh
yeah...
facepalm. thanks
I appreciate all the work that you put into that template. It definitely puts me on the right track for what I'm trying to accomplish. (Shame it takes so many lines to make it work.) I may try to expand the template so it can also handle RGB and color_temp.
I would like to note a typo on Line 15: level_template: > has an extra space before it.
It is interesting, though, the state does not return to off if all the lights are off. It stays on with the brightness at its last value. Only way that I have been able to reset it has been with a quick reload. https://i.imgur.com/7VlxCD3.gif
I think the problem is... the template sees itself so it is on because it is on... 
It's a light entity, so that might be it
Exclude it from the template
| rejectattr('entity_id', 'eq', this.entity_id)
Now it is working how I was expecting. https://i.imgur.com/kz8JcRd.gif
If I wanted to adjust the brightness of all lights that are currently on, I couldn't adjust brightness for lights.all_lights because it would turn on lights that were off. Now, with the template, I have a lights.all_lights_on entity that can adjust brightness for everything on. (The slider under the All Lights button has its entity set to lights.all_lights_on.)
I am having an MQTT-Sensor that sends out the following JSON Payload: https://gist.github.com/faken/630e8cf7f291283adb321b0ec60afbed I would like to create a sensor that outputs the value of the json attribute: bms_bmsStatus.f32ShowSoc embedded into the 'data' attribute
Can someplease please help me to write the right template for that.
Right now I am having this template code: "{{ value_json.params[1].bms_bmsStatus.f32ShowSoc }}" Which is not working
- condition: template
value_template: >-
{{ '30:DF:17:C1:28:D0' in
state_attr('sensor.pixel_6a_bluetooth_connection','connected_paired_devices')
}}
anything wrong with this, assuming the mac address is correct? doesn't seem to be triggering.
Thanks for this @marble jackal, can this be calculated retrospectively, or is it only for now forward?
It can't calculate retrospectively
Thanks @marble jackal, The issue I have is that the sensor that is populated in HA is already cumaltive by week; I want to split it by day. So if you look at the below, it started at 7.3 at 00:00 and increasd to 12.3 by 00:00 the next day. I need the net of 7.3 and 12 for the day, and reset at 00:00.
The utility meter does that
Just set up a daily utility meter
Based on your weekly sensor
Thank you, let me try that, when I did initially, it seemed to use the first value and sum all other values, meaning the starting balance was wrong.
Correct in saying that they are not deltas (its cumulative) so left that unticked.
Tried this again jumps straight to the cumulative weekly total.
https://ibb.co/C9c0Ybx
Heres the configuration -
https://ibb.co/8YMVppg
I do need some help with rounding sensor values. I would like to round to the values to 100-based values. For example 154 should be rounded to 100 and 444 should be rounded to 400, does somebody how how I can archive this?
Template sensor with a rounding would work.
{{ (states('sensor.original_sensor') | float / 100) | round * 100 }}
You can just do {{ states('sensor.original_sensor') | float | round(-2) }}
Best to ask in #integrations-archived as this is not related to templates
Only noticed now, will do
I'm using a few fixed entity names in the templates, for example an illuminance sensor. Is it possible to define a list of sensors, or a group, in the UI that are pickable? I'd like to ideally pick one sensor from the list so I can reference it then in the templates. I saw there is an input_select integration, so maybe defining the possible options using a template is possible?
Okay I can see there's a set_options service. So an automation that will trigger every once in a while and fill the options using a template will do. I wonder if there's a better way
@deft comet I converted your message into a file since it's above 15 lines :+1:
I keep getting undefined trigger error.
where do you see that?
are you trying to test the automation without letting it trigger?
Home assistant logs
I sent an email, the IMAP integration incremented the count, so it received the email correctly. but I don't see any new sensor/entity. I went to the logs and it showed that error in the logs
what is the actual error you see?
Source: components/imap/coordinator.py:364
Integration: IMAP (documentation, issues)
First occurred: June 20, 2023 at 2:45:34 PM (21 occurrences)
Last logged: 9:25:42 AM
Error rendering imap custom template (Template<template=(template : - trigger : - platform: event event_type : "imap_content" id : "custom_event" event_data : sender : "notifications@alarm.com" sensor : - name : alarmdotcom_armed state : > {% if 'Disarmed' in trigger.event.data["subject"] %} disarmed {% elif 'Armed Stay' in trigger.event.data["subject"] %} armed_stay {% elif 'Armed Away' in trigger.event.data["subject"] %} armed_away {% endif %}) renders=8>) for msgid 18 failed with message: UndefinedError: 'trigger' is undefined```
Each log entry occurs when I receive the email
I think you should remove the space before all the :
I didn't have any space before earlier, and I had the same error. thought perhaps that was the reason.
On the imap integration, there's a field called "Template to create custom event data"
I took an example from here: https://www.home-assistant.io/integrations/imap/
that block of code belongs in configuration.yaml
Im not sure wether this is the right place - but. I have solar panels, and the power-flow-card-plus can tell me the amout of power used in the house...i would like to know how many kwh im sending to the grid as a entity...but as of now I can only see the power producion, grid usage, and battery.. I would like a sensor or something to give me the remaing kwh that I have NOT used myself...
I would like to use it for charging things when I have alot to spare...
it doesn't belong in a field in the UI
Oh I see
Oh that works perfectly! Thank you so much!
I restarted the system and it seems I don't need this sensor automation at all haha. The alarm.com integration is now updating status before the email comes in🤥
Can anyone tell me what Im doing wrong here
{{ states('sensor.al7002022041414_instantaneous_generation') | float(0) - states('sensor.al7002022041414_instantaneous_grid_i_o_total' + 'sensor.al7002022041414_instantaneous_battery_i_o') | float(0) }}
yes, you're adding two strings and then trying to get the state of the resulting string
which is two entity_ids concatenated together
Tried this but I it dosen't seem right:
{% set forbrug = states('sensor.al7002022041414_instantaneous_grid_i_o_total') | float(1) + states('sensor.al7002022041414_instantaneous_battery_i_o') | float(1) %}
{% set produktion = states('sensor.al7002022041414_instantaneous_generation') | float(1) %}
{{ forbrug - produktion }}
is this correct:
- name: "OverUnderForbrug"
state: >
{% set forbrug = states('sensor.al7002022041414_instantaneous_grid_i_o_total') | float(0) + states('sensor.al7002022041414_instantaneous_battery_i_o') | float(0) + states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
{% set produktion = states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
{% set overunderforbrug = produktion - forbrug %}
Would that give me a sensor with the remain kwh
you're not outputting anything
from your last attempt, you swapped the order of your subtraction, but also just assigned a variable rather than outputting the result
This is in my config but returning 02:00 :S
- name: "OverUnderForbrug"
state: >
{% set forbrug = states('sensor.al7002022041414_instantaneous_grid_i_o_total') | float(0) + states('sensor.al7002022041414_instantaneous_battery_i_o') | float(0) + states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
{% set produktion = states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
{% set overunderforbrug = produktion - forbrug %}
{{ overunderforbrug }}
test it in
-> Templates
I have no idea how it could return something with a colon in it
Result type: number
-3580.7440000000006
so no colon
Not when I test it..
perhaps you're looking at the wrong entity, then
sensor.overunderforbrug
OverUnderForbrug
02:00
or perhaps you didn't reload template entities
I was a fool...works now... 😄 Thanks @inner mesa
Hi there!
I want to create template sensor that will calculate sensible temperature based on actual temperature and humidity. I added this into my configuration.yaml:
template:
- sensor:
- name: "Sensible temperature"
state: >
{% set temp = states('sensor.air_monitor_lite_4e4c_temperature') | float %}
{% set hum = states('sensor.air_monitor_lite_4e4c_humidity') | float %}
{{ (temp + 0.3 * hum - 12) | round(1, default=0) }}
But in UI I see Sensible temperature - Unknown. sensor.air_monitor_lite_4e4c_temperature and sensor.air_monitor_lite_4e4c_humidity are shown correctly in UI.
What am I doing wrong?
Put it in
-> Templates
There is works fine
Then you probably didn't reload template entities
I clicked "Restart" -> "Quick reload" and "YAML configuration reloading" -> "All YAML configuration"
Changes nothing
No. But I have few more elements in this sections. Will try to remove them
Works now. Thanks!
Is there a templates FAQ section?
I need a template to use in an automation that will be used as a trigger. (Hope I understand that correctly) . I need to alert if the current temperature attribute is 5 degrees higher than target temperature on an entity of a Nest Thermostat. When I pull up the entity in a history love lace card I can see their values. I don't see them listed under the entity or device.
So you need to create a template sensor, which is based off an attribute of the entity.
The docs are linked in the pinned posts
Or a template trigger
The fun of multiple ways of doing things.
I'd probably go with the first, but that's down to how I thik.
How often do a template evaluate using now()? Nevermind - Found it in the docs.
First thing to do though, is to create your base template.
go to the developer tools, then click on templates. Then you'll want something along the lines of:
{{state_attr("nest device here. something like nest.thermostat or something. I don't have one ", "current temperature")|float +5 }}
get that to the point it's returning the number you think it should be.
Then you need to add to your configuration.yaml, something like
- sensor:
- name: "triggertemperature"
unit_of_measurement: "°C"
state: your_template_goes_here ```
make sure to go to developer tools and click the check configuration button on the yaml page
(I do my editing using the file editor add on, but that's only one of many options.)
if it's good, you can restart (reload might work, but it never does for me 😉 )
then you'll have a new sensor which you can use in an automation.
How can I get a template to evaluate every 15 seconds? The template is using now().second and based on this value a decision is made. The use case is to create a template sensor, and based on its value, True/False, a sensor value will be displayed on a picture elements card.
The aim is to cycle through temp and humidity values on the picture elements card every 15 seconds, or value chosen using an input_number helper.
Thx, but its not an automation, but a conditional card on a picture elements. It only accepts a state, hence using the template sensor. According to the docs now() only evaluates every minute. An example syntax of the conditional card looks like this:```
- type: conditional
conditions:
- entity: binary_sensor.doors_all
state: 'on'
elements:
- type: icon
icon: mdi:door