#templates-archived
1 messages Β· Page 69 of 1
you may also be able to use {{ message|default(state_attr('calendar.meals', 'message') , True) }}
wait, what's the diff there? Isn't that also a filter?
yes
but I'm attempting to use state_attr() as the default
default is a filter
it does seem to work
will stick to the if for my understanding given I'm still not familiar with those
{{ message|default(state_attr('sensor.aarlo_battery_level_catbox', 'device_class') , True) }} -> battery
{% set message = "foo" %}
{{ message|default(state_attr('sensor.aarlo_battery_level_catbox', 'device_class') , True) }}
-> foo
@wary yew I converted your message into a file since it's above 15 lines :+1:
No, you're defining variables based off a non-existent state attribute, not the response variable from the service call
I need clarification. Is this what I just typed, that the variable message is wrongly defined?
where you getting agenda from?
agenda is the variable from the service call
service: calendar.get_events
target:
entity_id: calendar.meals
data:
duration:
hours: 24
minutes: 0
seconds: 0
response_variable: agenda
but thtat's the entire list AFAIK
you decided to add state_attr('calendar.meals', 'agenda')
I just want the summary of the second event
when it should just be agenda
nah, that was chatgpt. I get now the mess it got me in...
I just didn't know the syntax to get it myself
which is why we don't allow chatgpt because it doesn't know it's ass from a pancake
the sytnax to get the events would be {{ agenda['calendar.meals'].events[1].summary }}
that's the thing I was looking for
yeah, I saw it, but it didn't have the event index or the piece of info
so I still needed some help for the syntax. That was my problem π¦
and then I wrongly followed the suggested gpt change
thinking he would know xD
Yeah, don't botehr with chatgpt for this service call because it didn't exist when chatgpt was trained
I get it now
so chatgpt makes up what it doesn't know
which is why chatgpt isn't allowed
if it didn't do that, it would probably be a better tool for you
makes sense. In other fields I'm able to discern, but when you're a noob... I feel like any help is good help lol
but yeah, I'll be avoiding it from now on
sorry about the mess
hah
so, if you ask pointed questions about automations, it's pretty good
nah, for me I'm usually just looking for syntax fixes or functions, which is where I'm more clueless about
it's a "I can read" but I can't write kind of thing
ended up working like this in the end {{ iif(message, message, state_attr('calendar.meals', 'message')) }}
just the variable name as condition is a good check for "exists", right?
seems to work at least
any way to search only the 'group' domain? I'm looking for all groups with the prefix 'group.phone*'
yes
{{ states.group|selectattr('object_id', 'match', 'phone')|map(attribute='entity_id')|list }}
hi all!
i am struggling here with the match template...
need to filter all entities that name ".0x" in the suffix.
examples:
sensor.0x00124b002268ea6b_battery
binary_sensor.0x00124b0023420d49_battery_low
number.0xa4c138d2589bb298_maximum_range
this was the best i could do... but did not want to list all the types
|map(attribute='entity_id')|list|join(', ')}}```
see mine
{{ states|selectattr('object_id', 'match', '0x')|map(attribute='entity_id')|list|join(', ') }}
love! π thanks!
btw @mighty ledge, have you guys in the team ever considered adding something like https://www.kapa.ai/ ? I have used it in another Discord from n8n, an automation tool that needed some coding, and it was f*ing amazing tbh. It exclusively uses the projects docs, but it took a massive toll out of community supporters like you. It was also a perfect tool for me since as I said I had plenty of syntax issues and questions. And it was all used from within Discord too. Basically support people only hovered around the threads created by the bot when they were testing it to add some additional info, etc. But the experience for me was amazing.
I could pass it along to the people that matter, looks like it could help
think of removing all the stupid basic questions from people that are actually answered in docs π but answered clearly, with proper sources and all
check it out how they implemented it here: https://discord.gg/n8n
channel bot-help
hope it helps
Well the docs aren't great for templates atm
they are 'ok'
definitely need some love
forums can be used too, and tbh after battling myself, I end up finding out it was in the docs all along. In any case, it's better than nothing!
Is anybody here, who uses a Garagedoor in HomeAssistant@and Homekit?
I am not able to get the status working. Opening is emedetly open without my 19s delay
is that related to a template?
Yes it is
Yeah I try it, but cant copy on the mobile appβ¦. One moment
@proper oak I converted your message into a file since it's above 15 lines :+1:
I don't see any 19s delay there
it's entirely based on the state of input_boolean.garagentor_helfer
Yeah u are right. I will explain, give me a second π
I use a shelly1 with addon a one magnetic switch on the ground. If this switch changed frokmon to off is use an automation to aet the state of this helper to on., because i have tonuse it only fot the upper direction.
My problem is, that I used ioBroker and now I have problems to change my thinking about the coding. Blockly is not yaml π
you still haven't mentioned where this 19s delay is supposed to come from
since that seems to be the crux of your concern
you have an automation that triggers on the switch, and then you delay for 19s and then you turn the input_boolean entity on?
you have an automation that triggers on the switch, and then you delay for 19s and then you turn the input_boolean entity on? Yeah correct
@proper oak I converted your message into a file since it's above 15 lines :+1:
in any case, if your concern is this:
Opening is emedetly open without my 19s delay
then you need investigate that automation, not this template cover
because it is simply reflecting the state of the helper
The delay changed the icon in HomeAssistant, but the translation to Homekit isnt working. I know that HA is also working alone, but I want some parts working from everywhere and there homekit is simple to use (especially to my wife) π
ok, this doesn't sound like any sort of template issue
@inner mesa u are right. But my first template is not working. If i touch the garage door button in Homekit, i can see in the log that open.cover vomes from Homekit to Homeassitant, but the door does nothing. When I delete the conditions for open or close it diesnt make a change
it's a template cover, but the problems that you're describing have nothing to do with the "template" part of that
Any idea where the problem can be? For me it is a little difficult to understand the translation between HomeAssitant and Homekit.
If i touch the garage door button in Homekit, i can see in the log that open.cover vomes from Homekit to Homeassitant, but the door does nothing.
Test the service call manually. Open the switch entity in-> States and switch it on and off to make sure it works
it's just straight-line code, so if you claim to see open_cover being called, but the door isn't opening, then it's that service call
Does anyone here know how to convert command below, to one for zigbee2mqtt to understand? service: zha.issue_zigbee_cluster_command
data:
ieee: 00:0d:6f:00:13:3f:fa:07
cluster_id: 1281
command: 4
command_type: client
cluster_type: out
args: [5, 30, 1, 0]
endpoint_id: 1
in a script/automation if an 'if' has multiple conditions (since it is a list) is it an 'and' or an 'any'?
Hey, I would like to sum the power of all known devices to track "hidden consumers"
currently my test template looks like this:
{% for s in states.sensor %}
{% if s.object_id.endswith('_power') %}
{% set ns.states = ns.states + [ s.state | float ] %}
{% endif %}
{% endfor %}
{{ ns.states | sum | round(2) }}```
And I get the error ``` ValueError: Template error: float got invalid input 'unavailable' when rendering template '{% set ns = namespace(states=[]) %} {% for s in states.sensor %} {% if s.object_id.endswith('_power') %} {% set ns.states = ns.states + [ s.state | float ] %} {% endif %} {% endfor %} {{ ns.states | sum | round(2) }}' but no default was specified```
how can I exclude 'unavailible" values?
You could set a default if the state is not a number
{% set ns.states = ns.states + [ s.state | float(0) ] %}
Wouldn't just | float(0) work?
Even better
so like this?
{% for s in states.sensor %}
{% if s.object_id.endswith('_power') and state.state != 'unavailable' %}
{% set ns.states = ns.states + [ s.state | float(0) ] %}
{% endif %}
{% endfor %}
{{ ns.states | sum | round(2) }}```
i get this:
```'state' is undefined```
meanwhile I tried it differently which seems to work:
{% for state in states.sensor %}
{% if "power" in state.entity_id and state.entity_id.endswith("_power") and state.state != 'unavailable' %}
{% set ns.value = ns.value + state.state | float %}
{% endif %}
{% endfor %}
{{ ns.value }}```
Here your loop item is s but you use both s in the first condition and state in the second
should be both s
good catch!
thats it!
thanks man!
It could also be simplified as:
{{ states.sensor
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('object_id', 'search', '_power$')
| map(attribute= 'state')
| map('float')
| sum }}
I'm on phone don't know if it works...
Sorry for the wrong formatting
@thin spindle I converted your message into a file since it's above 15 lines :+1:
The first is a legacy format part of the sensor integration, the second is part of the new template integration
thanks I just found it googleing around
That would work better for you:
{{ states.sensor
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('device_class', 'eq', 'power')
| map(attribute= 'state')
| map('float')
| sum }}
so the later is the preferred and better way, right?
yep
Assuming all the power sensors have the correct device_class set, but it is at least a more simplified method
is this better in any way other than it seems to be more advanced for my noob brain? π
I would like to exclude one device
state.entity_id != 'sensor.shellyplugs_pv_power'
currently the template that I do understand and works looks like this:
{% for state in states.sensor %}
{% if "power" in state.entity_id and state.entity_id.endswith("_power") and state.entity_id != 'sensor.shellyplugs_pv_power' and state.state != 'unavailable' %}
{% set total_consumer_power.value = total_consumer_power.value + state.state | float %}
{% endif %}
{% endfor %}
{{ total_consumer_power.value }}```
well if there is not really a need to use the template from @frank gale I would just take the one I have and dont waste your time π
I don't think getting the 'power' from an entity_id is a better way to do this
The template I wrote filters all the entities that have 'power' as device_class (that should be the case for the most of your sensors) and sums the numerical states of them
isnt mine doing the same?
and how can I exclude one specific entity from the sum?
I want to calculate the sum of all consumers. My solar system is also included as an entity from type "power", so I want that to be not part of that
Yours looks the entity_id, if you have an entity that ends with power and isn't a power sensor, this will be included in the sum and all the power sensors without 'power' in their entity id will be excluded
It's your choice... Just wanted to simplify your template
Have fun!
ahh... understood.
so yours is better because it doesnt rely on me naming everything correct.
Thanks!
this works btw
this doesnt work
Then they aren't correctly formatted...
looks like this like is not correct:
| selectattr('device_class', 'eq', 'power')
needs to be
selectattr('attributes.device_class', 'eq', 'power')
The line is ok, your entities haven't apparently no device_class
this gives me 2x the value
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'eq', 'power')
| map(attribute= 'state')
| map('float')
| sum }}```
Try adding:
| selectattr('attributes.device_class', 'defined)
before this line
Ahhh yes my bad
attributes.device_class
Sorry
If you got any errors add this line
I do have this {{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'eq', 'power') | map(attribute= 'state') | map('float') | sum }}
this gives me 2x the value that would be correct
and this has an error {{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'defined') | map(attribute= 'state') | map('float') | sum }}
ValueError: Template error: float got invalid input '2024-02-29T05:35:31+00:00' when rendering template '{{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'defined') | map(attribute= 'state') | map('float') | sum }}' but no default was specified
On the second one you should have added the line not remove the other one
How do you know what the correct value should be? I can imagine that not all power sensors have _power at the end
so like this {{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'eq', 'power') | selectattr('attributes.device_class', 'defined') | map(attribute= 'state') | map('float') | sum }} ?
still double the value of what would be right
It seems you have two identical entities
Or double entities indeed
No first the defined one
I know that, because I know my known devices π
I dont know if there are additional sensors inside HA, but I know my devices and what they consume
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power')
| map(attribute= 'state')
| map('float')
| sum }}```
they are applied in order
Ok you know that, but ha should know that also, but apparently it knows you have double entities π
its still 2x the real value
why aren't you making a sensor group?
because you want it to auto generate based on all power entities?
yeah, Im not saying home assitant is wrong on its calculations.. but I know that the value is not right :D:D
yes
my HA is growing fast and I prefer to include this "dynamically"
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power')
| map(attribute= 'entity_id')
| list }}```
What does this return?
it returns this:
@thin spindle I converted your message into a file since it's above 15 lines :+1:
no double entities
you have entities pointing to your phone's power consumption and other things
you should really use a sensor group and select all your power entities that matter. Otherwise this template will require multiple filters from you removing entities that you don't want in the calculation
it'll be the same maitenance as a sensor group where you add things manually. But it will be harder for you to manage because you don't know templates.
ok, now Im getting more to the real value
the template also includes the forecast of the solar production
sensor.power_production_now
without this everything is correct
yep, you have to reject that entity
finally!
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power')
| map(attribute= 'state')
| map('float')
| sum
- states('sensor.power_production_now') | float(0)
- states('sensor.shellyplugs_pv_power') | float(0)
}}```
...
thanks @frank gale @fickle sand and @mighty ledge π π π
You will have more - entities in the future
| rejectattr('entity_id', 'in', ['sensor.power_production_now', 'sensor.shellyplugs_pv_power'])
but not more, that produces power
I am trying to figure out how to sort a list by the attribute state value. The issue I seem to be running into is that the state value is a string and not an int/float. How can I convert the state to an int/float in the sort function? The below example does not sort correctly.
Truncated example:
{% set sorted_list = ns_sensors.values | sort(attribute='state|int', reverse=False) %}
You can't, you need to store the states as numbers in your namespace
@twin compass I converted your message into a file since it's above 15 lines :+1:
you have quotes all over the place for no reason
and not in the correct spot
and you're missing and {% endif %}
and input_number.orderstopprocess isn't declared, assuming you want the state from that entity, which means you should wrap that in states('')
and you have a >- after data
that should be on value if you plan on using multiline notation with your template
the second service you wrote also has incorrect quoting, that will not work. Not sure how it is
if you have a template, your exterior quotes should not match your interior quotes
e.g. "{{ 'something' }}"
ok let me try
Would this be it?
data:
value:
{% if trigger.json["OrdersToProcess"] != "NULL" %}
"{{trigger.json['OrdersToProcess']}}"
{% else %}
"{{states(input_number.orderstoprocess)}}"
{% endif %}
input_number.orderstopprocess is a helper
you need multiline notation, the >-
and you still have quotes all over the place around your ouputs
which arer teh {{ }} lines
and you're missing quotes for the states() function's entity_id
You can test this in the template editor by the way, instead of guessing
use
{% set trigger = {'json':{'OrdersToProcess': 'blah'}} %}
for testing
Thanks so much!! It worked!
If I call the service open.cover or close.cover the garage door is working, but the states. I try a little more and hope it works thanks for your help
Is there an easy way to pull the icon used for an entity? I'm working on a custom card. Passing the entity via a text helper but not sure how to get the icon assigned to that entity
I believe you need to get the entity registry through the WS API, it will be stored in there.
Unless there's a way to get it with templates.... I'm not aware that there is.
We should add entry_attr
{{ state_attr('entity_id', 'icon') }} you mean?
Just tested on Template Editor
Then youβre using something custom
What do you mean by custom? Isn't that working for you?
It only works if the icon is listed as an attribute
2024.2 made a change that removed that attr off most entities
Customize.yaml?
π€·ββοΈ
if you go into
-> States and type "icon" into the attributes field, you don't see any?
Iβm sure there are a bunch, but I do goofy shit in my system
And most of my icons are set through lovelacegen
{{ state_attr('light.coffee_area', 'icon') }} returns None .. expecting something like mdi:light
if you don't see it in
-> States, that's why
Yep. You're correct. So these lights do show the mdi:light in my dashboard but it is not assigned to them. I went in and changed one to explicitly have the mdi:light icon and now I have that available in the attributes. Looks like most of my other sensors all have that icon attribute but not the lights. Weird. I've been running HA since 0.36 so maybe it's a legacy thing and these were never assigned even though they show up correctly.
They are just using the default icon for a light entity
integrations can provide their own default icon for each entity as a property
have been having issues with cover states since 2024.2
Issues with the tuya integration, but i didnβt use it. I use a template only.
hm I see- the issue could just be with covers in general?
gah, how can i store a value for later use .. i want to make a copy of the nordpool today and tomorrow prices as they get moved around/removed etc and messes up all my calculations ..
dont know if its a template question tho ...
hi all. i have a very simple virtual light....but how do i get this assigned to a group?
- platform: template
lights:
alexa_virtual_lights:
friendly_name: "Living Room Lights HA"
turn_on:
turn_off:
set_level:```
(set in configuration.yaml)
Hi,
I want to set up a notification based on a condition and just wanted to check if my template is correct
I use Aqara TRVs for my heating and the current temperature is fed to them by an external aqara temperature sensor. This mostly works stable but sometimes it gets out of sync and then the heater is not action properly. For this cases I want to get notified.
The TRVs temperature is stored in the state attribute current temperature of the climate entity. The external temperature has it's own sensor for the temperature.
I came up with this template, can anyone check briefly if that would work (or tell me how to check myself)?
{% endif %}```
Hello, I have MQTT sensors set up to pull the energy values from my Victron inverter. But every time I restart HA, it temporarily sets them to 0.0 and then to the value read from MQTT:
state_topic: "venus/N/xxx/vebus/289/Energy/OutToInverter"
value_template: "{{ value_json.value | round(2) }}"
device_class: energy
state_class: total_increasing
unit_of_measurement: "kWh"
I tried adding this to the template, but then it always stays unavailable:
availability:
topic: "venus/N/xxx/vebus/289/Energy/OutToInverter"
value_template: "{{ value_json.value | is_number }}"
Any idea why it shortly reverts to 0? I didn't find any default value for round() as it exists for example for float()
Use the same topic in your availability section as for your state topic
As you are checking on the same value
You can check in developer tools > template, but this template is not outputting anything
Thanks. The βno outputβ was exactly my issue on how to test but I didnβt think of a dummy output.
No output should be fine, as I want to use it as Automation condition
if you want to use it in a condition, it should output true or false
You probably want something like:
{{ (state_attr('climate.arbeitszimmer_heizung_links', 'current_temperature') or state_attr('climate.arbeitszimmer_heizung_rechts', 'current_temperature')) != states('sensor.arbeitszimmer_temperatursensor_temperature') | float(0) }}
sorry, didn't obfuscate the id in the second topic, it is the same topic in both templates. I just edited the post above.
ah, I have to set payload_available and payload_not_available respectively?
or do this
availability:
topic: "venus/N/xxx/vebus/289/Energy/OutToInverter"
value_template: "{{ 'online' if value_json.value | is_number else 'offline' }}"
it worked with setting payload_available, but it still sets it to 0 first
I have these entities since December and never had this issue when HA restarted, but I also did not find any changes in 2023.12/2024.01/2024.02 changelogs
just doing a "Reload Manually Configured MQTT Entities" has the same behavior, first a 0, then the real value
{{ states.binary_sensor |
selectattr('attributes.last_tripped_time', 'defined')
}}
this returns binary sensors with None in their last_tripped_time. is that to be expected? is the integration what's setting None or is that a HA default? I'm currently piping it to rejectattr to get rid of the nones but was wondering why that's needed.
yes
difined means "does the attribute exist"
oooh, not "does it have a value." my bad π
yeah, I need that after the selectattr because otherwise it'll error on entities not having that attribute
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_tripped_time'
(which makes sense to me)
right
last q: is friendly name not an attribute?
<template TemplateState(<state binary_sensor.alarm_zone_1=off; last_tripped_time=2024-02-29T17:27:59.635397, zone=1, bypassed=False, open=False, fault=False, alarm=False, tamper=False, low_battery=False, device_class=motion, icon=mdi:motion-sensor, friendly_name=Living room motion @ 2024-02-29T17:28:01.135575-05:00>)>
if i | attr("friendly_name") }} I get
'homeassistant.helpers.template.TemplateState object' has no attribute 'friendly_name'
ah, got it.
attr('entity_id') | state_attr('friendly_name') }}
what is attr('entity_id') supposed to do?
what you want is state_attr('someentity_id', 'friendly_name')
I don't have the entity id at that point
{{ expand(integration_entities('envisalink_new')) |
selectattr('attributes.last_tripped_time','defined') |
rejectattr('attributes.last_tripped_time','none') |
sort(attribute='attributes.last_tripped_time', reverse=true) |
first |
attr('entity_id') |
state_attr('friendly_name')
}}
you can do {{ 'sensor.aarlo_battery_level_catbox'|state_attr('friendly_name') }}
I still don't think it's a thing
{{
expand(integration_entities('envisalink_new')) |
selectattr('attributes.last_tripped_time','defined') |
rejectattr('attributes.last_tripped_time','none') |
sort(attribute='attributes.last_tripped_time', reverse=true) |
first |
state_attr('friendly_name')
}}
this gives me an error
AttributeError: 'TemplateState' object has no attribute 'lower'
but putting attr('entity_id') before the state_attr gets it to work
π€·
{{ states.sensor|selectattr('entity_id', 'search', 'catbox')|map(attribute='attributes.friendly_name')|list|first }}
waits impatiently for petro to prove me wrong
haha
what I have above is how I would get the friendly_name
that error means it's trying to treat the TemplateState object like a string
so you're feeding one of the functions wrong info
oh, it's that state_attr bs you have at the end
lol yeah, I'm trying to get the friendly name
from my... template state object?
state_attr seemed like a good way to get the friendly name, but I needed to pipe it an entity id for it to work
well, when you use first, you chose the first object
yep. I only want the most recently triggered sensor
I would just replace
first |
state_attr('friendly_name')
with
map(attribute='attributes.friendly_name')|list|first
if you put map(attribute='name') before | first you get what you want
will that break my sorting on last triggered?
no
yoiu need the |list in there tho
like rob has
cause it's a generator after you map it
word π
{{
expand(integration_entities('envisalink_new')) |
selectattr('attributes.last_tripped_time','defined') |
rejectattr('attributes.last_tripped_time','none') |
sort(attribute='attributes.last_tripped_time', reverse=true) |
map(attribute='name') |
first
}}
it's just shorter and im lazy
yeah, I guess you don't need |list. |first does it
it's still a generator, but it works
we did it. go team β
we all jumped and did an air high five at the same time, right?
it takes a village to write a template
I learned that I can probably remove some |list filters
sed -i 's/| list//g' .* what could go wrong?
lots
it'll be fine. that's what backups are for!
Thanks, WAI.
I try to push it further. This is my current template:
{{ (state_attr('climate.arbeitszimmer_heizung_links', 'current_temperature') or state_attr('climate.arbeitszimmer_heizung_rechts', 'current_temperature')) != states('sensor.arbeitszimmer_temperatursensor_temperature') | float(0) }}
Within the notification, I would like to take the state attribute friendly name of the climate that made the condition true to know which one to check Is it possible to do that? My current static approach is
β οΈ Heizung {{state_attr('climate.arbeitszimmer_heizung_links', 'friendly_name')}} prΓΌfen.
@steep bloom I converted your message into a file since it's above 15 lines :+1:
@steep bloom I converted your message into a file since it's above 15 lines :+1:
please stop
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.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.
you didn't say what isn't working
entity isn't showing up? entity doesn't work when you try to control it?
your icon_template could result in nothing, which will be a problem
Sorryβ¦Iβm clearly very new to Discord, too
The entity doesnβt even show
Iβm going to try stripping out the icon_template
where did you put all that?
Configuration.yaml
you're also missing the name of the switch
see the example there, specifically the skylight: line
you don't have one of those
and:
To check your configuration use the command for your install method:
do that to check your configuration
Config works. It was the dumb nameβ¦I had it in an earlier version and was struggling with my tabs π THANK YOU!
You can use trigger.to_state.name but that relies on trigger data. You can't see what made this condition true
Hello togehter,
just a, hopefully little, question to you experts here π
I've added a helper card to my dashboard which showing me a power consumption by daily reset.
Any option to shrink the shown amount to 2 decimal places ?
type: entities
entities:
- entity: sensor.heizstab
show_header_toggle: false
state_color: false
title: Heizstab KW/h
Right now its showing:
4,528188 kWh but I want to have like 4,52 kWh
Dont know if I'm righthere in templaes channel oO
If you go to the sensor's details page, you can set the accuracy for many ones
I get a template error I don't quite understand, as I would think I guard against it:
2024-03-01 11:47:42.803 ERROR (MainThread) [custom_components.openhasp] TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '{%- if not is_state('sensor.location_to_location_duration','unknown') %} {{states("sensor.location_to_location_duration")|int | timestamp_custom("%Hh%Mm", false)}} {%- endif %}' but no default was specified') while processing template 'Template<template=({%- if not is_state('sensor.location_to_location_duration','unknown') %} {{states("sensor.location_to_location_duration")|int | timestamp_custom("%Hh%Mm", false)}} {%- endif %}) renders=4>' in entity 'None'
@feral spade no, that doesn't work
is_state() always returns false when the entity doesn't exist (yet)
so not is_state('sensor.not_existing', 'unknown') will return true when the sensor doesn't exist
use {%- if states('sensor.location_to_location_duration') != 'unknown' %} instead, or maybe even better {%- if 'sensor.location_to_location_duration' | has_value %}
thx. Once I actually managed to copy that it works
I'am in the right channel here from my request ?
jorg answered your question
@marsh cairn answered your quest... π
oh dam I'm totaly sorry π¦
Did not recognized it that it was related to me because there was no detail page of this view. but he was talking about the settings of the sensor (in this case a helper) itself.
1000 times thx
why I can't use a template sensor like this in the statistic card?
`
- sensor:
- name: Totale total cost
unit_of_measurement: "β¬"
state: "{{ ((states('sensor.totale_consumi')|float(0)) * (states('input_number.price_per_kwh')|float(0)) ) | round(2) }}"`
- name: Totale total cost
because you don't have the necessary requirements on that entity to generate statistics
what is missing?
device_class, state_class, unique_id
uhm, what kind of device and state class should I use for it?
Well, take a stroll over to the sensor documentation and read through the available device classes and paired unit of measurements
as for state_class, you probably want measurement
yes
yeah, I see, but how can I create a similar utility meter?
have you looked at the utility meter docs?
I mean in the conf, not in the UI
also, if you just attach the cost sensor in the energy dashboard, it will do all the calculations for you
I suggest you head over to #energy-archived for the best path forward
I want to use it in my dashboard graph and not in the energy dashboard
wait, I can create widgets for my own dashboard from the energy one?
I am struggling with apexchart because it doesn't support group by month, so trying to build my own
I know I've said docs a few times now, it would benefit you well if you got comfortable using the documentation
there's a whole dashboard section that shows you all available cards that you can place in your frontend, and a plethora of energy cards
one of them being cost
what kind of doc are you referring to?
the home assistant documents
there's a whole website dedicated to documentation for home assistant
already linked it above
ok, I was thinking that there were a way to configure the widget, but they just use the energy configuration, so for example I cannot group by some time with this card type
but I can replicate the date picker and the bar chart in my own dashboard
my man
the first card option for energy is the energy date picker
add the energy date picker, and the energy card you want, and you'll get monthly
I seriously urge you to read the documentation, don't just skim it
yes, I did it
`type: vertical-stack
cards:
- type: energy-date-selection
- type: energy-usage-graph`
but I dont see how to add also the costs
in the Energy page there is "source" table with the cost column, I don't see it in the card types
It's there, "Energy sources table" (energy-sources-table)
how do you know what attributes etc of sensor that you can template? im trying to set energyscore energy_treshold to a in input_number but failing at it π
developer tools -> states page
suggestions for a card I can use with a Helper Template that identifies lights in my Basement Area that are on? I want to make a slider that controls on the lights that are on, the way you can do in the Hue app. I already made the template.
idk if this is possible
the template:
states.light
| selectattr("state", "eq", "on")
| selectattr('entity_id', 'in', area_entities('Basement'))
| map(attribute='entity_id')
| list
}}
Hey y'all.
Im trying to track my time spent working at my job. I would like to track a) time started, b) time finished and c) hours spent working. I will only "start work" and "end work" once a day (like a normal office job). Im also doing this to visualize the data. Im especially looking forward to seeing at what time i actually show up to the office each day visualized in a nice line graph like those "avg temperature each day" graphs.
Due to the nature of my work, I want to be able to automate start and end time via node-red, as well as having the option of manually entering a time for a day. I would like to use node-red due to too many factors for a simple Homeassistant automation (using geofencing, but also pinging if laptop is in wifi and some other stuff).
My Idea was to use 2 input helpers (input_datetime) for starting time and ending time, setting these via node-red and also having them in the homeassistent dashboard to be able to manually overwrite them. My plan was to then use a time-based-trigger (shortly before midnight) on template sensors to save a) time started, b) time ended and c) time spent working. This way, I would have exactly one datapoint per day and also the ability to have my node-red automations run during the day with me being able to overwrite them by setting the custom input_date in the UI during the evening before the trigger runs shortly before midnight.
The reason im asking for advice are the "input_datetime" entities. It seems to save the state as a string formatted as "hh:mm:ss". Im not sure how I would be able to visualize each datapoint per day via a linegraph down the line. I could make this into a unix-timestamp or take the last_modified timestamp, but then I would have the day as well, when i just need the time. I guess i could also separate the string and multiple hours by 24*60 and minutes by 60 to get the seconds past midnight. But then the charts will look ugly. Any advice?
(Hope this is the right place to ask. Running homeassistent in docker, got hacs set up and working, node-red etc. and all the tech-stack you would expect. Also work on IT...appreciate any inputs)
I'm trying to create a custom date&time sensor for use on a dashboard. I have used the HA date/time integration so I have sensor.time set up already. On the HA website, I got this code as a template for custome sensor. I've only changed a couple of the date/time attributes, nothing else. But when I reload my yaml I'm getting a template error message. Am I doing something wrong here?
https://dpaste.org/MzEze
You're trying to configure two different integrations under the same (unspecified) key. For the date & time sensor, just use the UI Time & Date Helper and delete the YAML configuration. The template sensor needs to be configured under the top-level key template. You have not provided information on what file it is in and/or what key you have configured it under.
I'm not sure I understand (still learning a lot) but here's what I think you're asking. That yaml is in my templates.yaml folder, but I don't know what is meant by 'key'. I also just quickly played with the date/time helper and all that's giving me is 3/1/24 at 12:00am?
The top-level key for your templates.yaml file should automatically be template (unless you did something weird π ), so that is the correct place for the second sensor in your example.
Here's the error log. Does this help narrow it down?
Logger: homeassistant.config
Source: config.py:597
First occurred: 12:40:45 PM (7 occurrences)
Last logged: 1:26:05 PM
Invalid config for 'template' at templates.yaml, line 12: 'platform' is an invalid option for 'template', check: sensor->0->platform Invalid config for 'template' at templates.yaml, line 12: required key 'state' not provided Invalid config for 'template' at templates.yaml, line 13: 'display_options' is an invalid option for 'template', check: sensor->0->display_options
You shouldn't have template: in that file. It goes in configuration.yaml
I have this in config.yaml: "template: !include templates.yaml"
You shouldn't have any platform: lines in that file either
Ok. That's a bit confusing or misleading then, since I copy/pasted that exact code verbatim from the HA website.
What is in the file? And from what website?
Here's the page I'm using as a guide: https://www.home-assistant.io/integrations/time_date/
I copied the code under "Producing your own custom time and date sensor"
Not all sensors are Template sensors. Sensors like Time and Date need to be in a file with sensor as the top-level key.
ok so the first part (with platform) goes in config? then the bottom half in template?
the whole thing can go in configuration.yaml if you don't already have a sensor: or template: tag in there
if you do, then you need to adapt it to your specific case
ok. that's helpful. I think I know what I need to do then. I'll give it a shot. Thanks.
When writing a fan template...is it possible to incorporate the oscillation control into the entity?
Pic shows an example from a different integration of what I'm trying to accomplish. Code is what I have so far but only gives control of speed and on/off
Maybe you need to add oscillating template?
I think I'm getting close but the new date/time entity has a state of 'unavailable'. When I put the as_timestamp code into the template editor I get the following error:
ValueError: Template error: as_timestamp got invalid input '14:41, 2024-03-01' when rendering template '{{ as_timestamp(states('sensor.time_date')) | timestamp_custom('%A %B %-d, %I:%M %p') }}' but no default was specified
Is this where I need a date/time helper?
No
I'm working on the default part right now. I might have it.
Just use {{ (states(xxx)|as_datetime|as_local).strftime('%H:%M') }}
With whatever format string you want
Ok I'm really confused. So I'm building off sensor.time_date. That sensor is showing the correct date and time for my time zone.
When I plug it into here: state: "{{ as_timestamp(states('sensor.time_date'),0) | timestamp_custom('%A %b %d, %I:%M %p') }}" , it's giving me a result of Wednesday Dec 31 at 4pm.
You could use what I gave you
I plugged this into my template editor and got this error: AttributeError: 'NoneType' object has no attribute 'tzinfo'
of course, replacing the xxx's with my sensor
{{ (states('sensor.date_time_iso')|as_datetime|as_local).strftime('%H:%M') }}
same error π
lol idk what to tell you. i promise it's the same
I have a list of entities that I want to select a single one from the list, based on matches. In other words, run match and if it gets no result, try the next match, and so on. Is there a concise way to do this other than if/else if?
Any way to change what the upper and lower bounds of a color temperature for a bulb? I have a bulb that goes from 3000-6000k, and HA thinks it goes from 2000-6500k, which makes something like adaptive lighting display an incorrect color temperature when it updates. The slider functions through the entire range (setting it to 2000 displays 3000, and setting it to 6500 displays 6000, but anything in between is a mystery, I assume it scales by percentage), but I want a way to have the slider display the correct numbers
idk either. not letting me paste a screenshot of mine but it's the same error.
Just to confirm, I have this:
""sensor:
Minimal configuration of the standard time and date sensor
- platform: time_date
display_options:- 'date_time_iso'""
...in my configuration.yaml. I have this:
""- sensor: - name: "Date and time"
state: "{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%A %B %-d, %I:%M %p') }}"
icon: "mdi:calendar-clock"""
...in my template.yaml
- 'date_time_iso'""
I made it work. I ended up using {{ as_timestamp(now()) | timestamp_custom('%A %b %d - %I:%M %p') }}
Thanks for helping point me in the right directions ππΌ
Greetings, I have been playing wit a sensor template to scale an existing sensor.. and it is now working, but there is some existing data that I would like to delete (mistakes were made).. is there a way of removing the historical data/resetting ? I can comment out my definition in the YAMLand then delete the sensor entity, but when I enable my YAML definition the histroical data is still there.
- Is old data cleaned up at all? (if the sensor has been deleted?)
(I suspect that I could change the id of my template for a fresh start.. but I am curious what the process is for old data)
So I want to send a notification when the fire alarm triggers and include what area the entity is tied to. Is this possible using templates?
Chatgpt didn't solve that. :/
I'm getting several errors in the log related to templates:
Error while processing template: Template<template=({% if states('sensor.wiser_lts_heating_demand_guest_bedroom') | float > 0 %} red {% else %} grey {% endif %}) renders=2>
Why would that render a number? I have some issues with the wiser sensors. Might that be the cause? Maybe if the sensor is unavailable that happens?
Yes if the sensor is unavailable or unknown that template will fail because you havenβt provided a default for the float filter. Try float(0) if you want the template to return grey in that case
{{ area_name(trigger.to_state.entity_id) }}
Assuming you are using state trigger for your automation
what about this one:
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=14>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=16>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=18>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=20>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=22>
I also get errors rendering a number.
Share your code
@wary yew Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.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.
Also I believe the renders=22 message is the cumulative number of times the template has been attempted to be rendered. It is not the result of your template.
And if that template is supposed to render a number it certainly does not
Make sure you are trying out your template in the template editor tool.
-> templates
the template works, it returns what I want AFAIK
but I get those errors in the log often
The consumption entity is sent to the round filter and will fail if it is unavailable
Are these source sensors going unavailable often?
yeah, they're from custom integrations and have some bugs often and warnings with api calls. Might be that.
I have a few reported atm, but still ongoing.
just provide a default for the round
your iff is wrong too
under icon
too many )
it's also wrong on badge_icon
and icon_color
wait, no, ignore me
too early
it was working fine tbh
missed the is_state(
anyways, round(2, default='Na')
just noticed @lucid thicket your point, it actually said in the log
homeassistant.exceptions.TemplateError: ValueError: Template error: round got invalid input 'unknown' when rendering template '{{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}' but no default was specified
still throwing me the error. It's weird. The code has the default, but the log doesn't show it.
{{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2, default='Na') }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}
homeassistant.exceptions.TemplateError: ValueError: Template error: round got invalid input 'unknown' when rendering template '{{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}' but no default was specified
Iβm not good with #frontend-archived issues but I think youβll have to make sure any browsers get refreshed, or just reboot ha. Do you have any tablets around the house that display that dashboard constantly?
lemme reboot a second time then
clearing cache too
no tablets or other permanent dashboards, no
hmm yeah, looks like it's not showing up now. Must have been a browser cache then
thanks!!
aaahh, the pleasure of an empty log... so close!
clear your cache and refresh the page on all devices displaying that card
that's the drawback of using frontend cards with the template engine
the frontend holds on to old templates until you refresh the page
no reboot, just refresh
if I do a for a in areas(), the first area is a guid-like number. any idea what it is?
3ebde695493244268f79f03134f255a9
laundry_room
basement
upstairs_bathroom
...snip...
oh it's area IDs
π
is there a shorter/better way of writing this binary sensor template?
{{iif(is_state('binary_sensor.alarm_zone_7', 'on') or is_state('binary_sensor.alarm_zone_8', 'on') or is_state('binary_sensor.alarm_zone_9', 'on') or is_state('binary_sensor.alarm_zone_10', 'on'), "on", "off")}}
using range() or a for loop feels worse?
I guess I could just use a group
Worked perfectly! Thank you!
You can do this:
{{ ['binary_sensor.a', 'binary_sensor.b'] | select('is_state', 'off') | list | count > 0 }}
I love it
{% set slots_unit = "hours" %}
{% set slots_name = "60" %}
{%- if slots_unit == "seconds" -%}
set multiplier = "1"
{%- elif slots_unit == "minutes" -%}
set multiplier = "60"
{%- elif slots_unit == "hours" -%}
set multiplier = "360"
{%- endif -%}
{{ slots_unit }} * {{ slots_name}}
Youβre not actually doing math there and all your numbers are strings, which arenβt able to do math
I'm struggling and could use a push. I am trying to set a timer using assist and want to disect things. If user says 'set timer for 2 hours' I want to take that part, know that 360 hours, then multiply.
@mighty ledge Right. I know my syntax is all wrong but thought if I put this it would be easier than trying to explain in words
Secondly, multiplier wonβt be accessible outside the if statement
Ah okay. So really what I'm wondering is how to do this? I'm really a novice
well, you an just do this
{% set info = {slots_unit: slots_name | int } %}
{{ timedelta(**info) }}
if you want to get a simple timedelta to offset a time
WOW!
Okay, just tried. Not exactly what I need. Here's a couple examples:
Set timer for [60] <seconds> = 60 * 1 = 60
Set timer for [60] <minutes> = 60 * 60 = 360
Set timer for [60] <hours> = 60 *360 = 3600
The resultant value is the timer in seconds and then I am able to past that numerical value over to the timer. Should be a float in case someone says 'one and a half minutes'
no, it's exactly what you need
if you need total seconds out of it...
{{ timedelta(**{slots_unit: slots_name | int}).total_seconds() }}
that's pretty clever
Hey i have this template in a mushroom-template-card. The card gets auto generated with auto-entities.
replaced_entity just writes the name of the entity, not the value. Any ideas? I think I miss something as i'm new to HA and Jinja2
secondary: >
{% set replaced_entity = entity|replace("switch", "sensor")|replace("schalter", "leistung") %}
Leistung: {{replaced_entity}}
fyi your hours calc is wrong
60 * 60 * 24
{% set slots_unit = "hours" %}
{% set slots_name = "60" %}
{% set info = {slots_unit: slots_name | int } %}
{{ timedelta(**info) }}
This returns :
2 days, 12:00:00
What I'm wanting is in time format hh:mm:ss
try the second template I posted.
that will give you the total seconds which you can put into the service call
service: timer.start
target:
entity_id: timer.mytimer
data:
duration: "{{ timedelta(**{slots_unit: slots_name | int}).total_seconds() }}"
although, I migh thave to look up the args that timer accepts
Forget it, I just forgot the "states" so i changed it to {{states(replaced_entity)}} and now it works haha
duration accepts total seconds.
so, that will work
you just have to declar slots_name and slots_unit in a separate variable step
or you can just use the slot directly there
assuming it's slot.name or slot.unit
This is great. I do have one question though:
{% set slots_unit = "minutes" %}
{% set slots_name = "1.5" %}
{{ timedelta(**{slots_unit: slots_name | int}).total_seconds() }}
This returns 60 and not 90
change the int to float
variables are coming from assist so they are actually called trigger.slots.name and trigger.slots.unit but I can't use those in dev tools when testing
you can create a trigger variable to test, similar to what you already did here: #templates-archived message
{% set trigger = {"slots":{"unit":"5", "name":"hours"}} %}
{{ trigger.slots.unit }}
``` -> `5`
i'd be verys surprised if the slots aren't typed
if they are always strings, then that's an odd choice, especially if numbers come through
I am running into an issue with the sentence I created so I think you are right. I think some are predefined and I can't just throw in {units} .. Will ask on #voice-assistants-archived
make sure your predefinition keeps them at hours minutes, and seconds
any deviation (non-plural) will result in that template failing
Right. It's a bit shaky as it is now but a little more logic would sure it up I think. If contains 'seconds' then set to 'second' type of thing
yes but that can be done with a map
Unfortunately I'm just an old guy who knows just enough to be dangerous π
e.g. {% set translation = {'second':'seconds', 'minute': 'minutes', 'hour':'hours'} %}
{% set key = translation.get(trigger.slot.unit) %}
{% set info = {key: trigger.slot.name | float} %}
{{ timedelta(**info).total_seconds() }}
note, you'll have to include all the plurals in the translation dict
you are a champion! Thanks so much for the help
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
This is the YAML config of a trigger based template sensor
Okay, so different question. I have a bunch of sensors that are platform: template is that different than how these are configured? What I'm really wanting to do is create a custom entity that has attributes that I can assign arbitrary names to . Is that possible? I know that if I try as a platform:template type I get errors
platform: template indicates you are using the legacy format, but both in the modern format and in the legacy format you can add attributes to your sensor
Excellent. Thank you!
I've been using HA since the early days and don't keep up with all changes
template:
- sensor:
- name: AssistView_LR
state: "idle"
nightmode: "off"
message: "test"
Just tried adding this to config.yaml but it does not appear in dev tools state after a reboot. Am I missing things totally?
Yes, you aren't following the documentation: https://www.home-assistant.io/integrations/template/#attributes
Got it now. Thank you both
So I am not able to do everything I wanted as two separate variables. I will have one which will look like "10 minute" or "60 seconds" . Can you tell me how I can modify this to work with what you provided? I'm guessing that the space could be used as a separator and assign the first value as one variable and the second value as another variable?
I am using the packages methode for my configuration and Im struggling to get the example code for "Trigger based handling of service response data" https://www.home-assistant.io/integrations/template#trigger-based-handling-of-service-response-data
working.
My config is on my github https://github.com/thedutch-no/homeassistant/tree/main/entities/templates the file is called weather_forecast.yaml
I hope there is someone who can help me getting this working
Can I write my own function so that every automation can use that function directly?
This gives a 404
You can write macros and place them in the custom_templates folder so you can include them
Just checked the url's they work for me, wich one is giving you problems?
yup, user error π
How do you include this folder?
configuration.yaml : packages: !include_dir_named integrations
integrations/templates.yaml: template: !include_dir_list ../entities/templates
Okay, and what is the issue with this weather forecast sensor then?
in the developer tools the sensor.weather_forecast_hourly reports the state as 'unknown'
Did it already trigger?
It should have triggered at 11 CET 53 minutes ago, so it should have a state now
no state, to be sure refreshed the developer tools page
Then there should be something in your logs
found it:
Logger: homeassistant.helpers.script.trigger_update_coordinator
Source: helpers/script.py:1805
First occurred: 10:00:00 (6 occurrences)
Last logged: 11:00:00
Trigger Update Coordinator: Running script requires passing in a context
Trigger Update Coordinator: Error executing script. Error for call_service at pos 1: Weather entity 'weather.home' does not support 'hourly' forecast
There you have it
You need to add a second integration for met.no with the hourly forecast
Or wait until 2024.3
They will be both available in one integration as of then
is it possible to force a trigger instead of waiting a hour?
Add an additional trigger, maybe a state trigger on an input boolean, or an event trigger on a custom event
Got it working now, using openweather instead of met.no
Thanks for your help
Dank je voor je hulp
Takk for hjelpen
You're welcome
Graag gedaan
Ikke nevne det
Hey all... I have a for-me unexpected result from a mqqt template sensor.
Entity sensor.linky_consumption_annual_blue_hc_eur (<class 'homeassistant.components.mqtt.sensor.MqttSensor'>) is using state class 'total_increasing' which is impossible considering device class ('monetary') it is using; expected None or one of 'total'; Please update your configuration if your entity is manually configured, otherwise create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+mqtt%22
why can't a monetary value be total_increasing? This topic is my energy-consumption (total_increasing) x price/kWh
in my view this is still total_increasing (as it will do perpetually....until I die)
is this a bug indeed?
example (I have 6 of them):
- state_topic: myelectricaldata/xxxxxx/consumption/annual/current/thisYear/tempo/BLUE_HC/euro
value_template: "{{ value_json }}"
unique_id: linky_consumption_annual_blue_hc_eur
name: linky consumption annual blue hc eur
icon: mdi:lightning-bolt
device_class: monetary
unit_of_measurement: EUR
state_class: total_increasing
Invalid config for 'binary_sensor'. I am trying to make a yaml for binary sensors. In the configuration yaml I have binary_sensor: !include binary_sensor.yaml and then the binary sensor yaml is - name: freezer_warming2 unique_id: freezer_warming_sensor2 state: > {{ states('sensor.kitchen_freezer_temperature') | int > 20 }} device_class: problem I am getting an error ... Invalid config for 'binary_sensor' at binary_sensor.yaml, line 1: required key 'platform' not provided+ . How to fix?
Just as it says, you didn't include a platform line
You mixed up the old and new formats
Pick one
Franken-YAML 
the head of one format, the tail of another, and no torso

I read that integration template document until Iβm blue in the face and I canβt figure out what Iβm supposed to add.
as I said, you're mixing up the two formats
if you want to stick with the legacy format: https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
I suggest reading from teh top of that page, though
If it is in binary_sensor:, it is the old legacy format (and needs the platform defined).
If it is in template:, it is the new recommended format.
I only just started doing HA and I don't know the old format and the new format. I just copied stuff and changed a few words. I copied it directly off of that document.
OK, so I need to delete the binary sensor yaml file and put everything in the template yaml
Meaning the top level of the config
so you put sensors and binary sensors all in the template Yaml file
If you just want the answer:
template:
- binary_sensor:
- name: freezer_warming2
state: "{{ states('sensor.kitchen_freezer_temperature') | int > 20 }}"
unique_id: freezer_warming_sensor2
put that in configuration.yaml
I thought the idea was to put all of this in separate files, so it was easier to find
you can if you want
you cannot put that under binary_sensor: because it doesn't belong there
that's why I was putting it in the binary sensor why yaml file
but it is a binary sensor, so why would it not go in the binary sensor file?
sorry I'm being really dense I don't mean to be stupid
you're also welcome to read the link above that shows how to use the legacy format, which does belong under binary_sensor:
but then you need to write it properly for that format
like I said, I don't know the old format so I'd rather just use the new stuff. And it sounds like what you're telling me is everything goes in the template and forget the whole idea of putting it in the separate binary sensor file.
thank you very much for being patient with me! I appreciate it. I think I got it working.
Is there a way to check a variables value to see if it contains numerals or if it contains alphabetic characters? I'm wanting to check "10" and "minutes" to know which is the number and which is a word describing the units
The is_number filter/test
DId some searching but not seeing this. Is the concept to try and convert string to int and if it gives error you can assume it does not contain only numbers?
All searching starts here: https://www.home-assistant.io/docs/configuration/templating/
Many examples
{% set x = '20 minutes' %}
{% set unit = x.split()|reject('is_number')|first %} {{unit}}
{% set qnty = x.split()|select('is_number')|first %} {{qnty}}
Thank you both for the help
{{ trigger.event == 'enter' }} is correct?
For Zone trigger
no need add {{ trigger.event.data == 'enter' }} or {{ trigger.event.state == 'enter' }}
I often use conditionals {{ trigger.to_state.state != trigger.from_state.state }}
Is it accurate?
I'm not sure but it still works
Do i can change from {{ trigger.to_state.state != trigger.from_state.state }} to {{ trigger.to_state != trigger.from_state }}
As you can see in the linked docs, trigger.event will either be "leave" or "enter"
For a platform: zone trigger that is
So not trigger.event.data
thanks
in the linked docs is trigger.from_state and trigger.to_state
But i find many guidline templates is trigger.to_state.state and trigger.from_state.state
So which one is correct?
trigger.to_state will be the entire state object of the entity that caused the trigger
The state will be one of the objects of the state object
So trigger.to_state.state will give you the new state of the entity which caused the trigger
Thank you very much
@marble jackal I moved to #templates-archived .
What should I put on the template to do the tricky stuff on sending actionable notification depend on the person that enters the home zone? How complicated is that gonna be? also is it harder to create an option that if Robot Vacuum hasn't cleaned for 3 days it will send us an actionable notification that asks if he can run even tho' there's people in the home zone and they haven't left (together) for 3 straight days?
That's wife requirements hehe π
[http://pastie.org/p/0UUZHQpF6iVK8M8Em4HcZl]
Thanks for helping and I appreciate that very much!
- name: chore_drying
state: >-
{% if states('input_boolean.dryer') == 'on' and states.input_boolean.dryer.last_changed|float < (as_timestamp(now()) - 180) %}Drying{% else %}Idle{%endif%}
attributes:
finish_time: ''
attention_time: '{{ (as_timestamp(now()) - states.sensor.chore_drying.attributes.finish_time) | timestamp_custom("%H:%M:%S", false)}}'
needs_attention: 'off'
Here's a template sensor I'm working on. When drying finishes I set the finish_time with the as_timestamp(now()) from a python script that can set that attribute. I know that the attention_time is only updated once every 30/60 seconds but when it does I lose the value in finish_time and attention_time shows as null. Am I going about this all wrong?
the themplates are wrong
{% if is_state('input_boolean.dryer', 'on') and states.input_boolean.dryer.last_changed < now() - timedelta(minutes=3) %}Drying{% else %}Idle{%endif%}
and
{{ now() - state_attr('sensor.chore_drying', 'finish_time') }}
but keep in mind, you have to ensure finish_time has a valid datetime
Also, don't use the python set attribute script... just move finish time to its own trigger-based sensor.
Thanks for sure. Truth be told this just got moved from the old sensor definition over to the modern template format so I guess syntax changed or is different. That bit has worked for years.
Thanks for the tip. I have not looked into this. I am really doing some things out of the proper way but I'm terrible about finding the 'right' way to do things and lack of time to devote doesn't help either.
not sure how it did, states.input_boolean.dryer.last_changed|float will never work
it's never been valid syntax
states.input_boolean.dryer.last_changed is valid, and |float is valid, but combining the two will always result in an error
especially without a default for float
and it's gone
Hoped I was quick enough. My problem was that I had what I needed commented out. Will take a break after I get this going.
- name: chore_drying
state: >-
{% if is_state('input_boolean.dryer', 'on') and states.input_boolean.dryer.last_changed < now() - timedelta(minutes=3) %}Drying{% else %}Idle{%endif%}
attributes:
finish_time: 0
attention_time: >-
{{ now() - state_attr('sensor.chore_drying', 'finish_time') }}
needs_attention: 'off'
Here's what I have now. State does not change when I toggle input_boolean.dryer on or offand attention_time does not show up in attributes.
I'm forcing finish_time to 0 which I thought would satisfy what you mentioned above but I suppose it doesn't
I'm not positive of what that value should look like. Is it unix time format?
I'm not understanding the question. On HA restart this needs to have a value correct? If so, what value can I use as a place holder? Is this impacting the state change from input_boolen.dryer from being evaluated?
it's impacting attention_time
that can't calculate if finish_time doesn't have a valid datetime
and in general, there's nothing that's going to make finish_time change
so what's the use of finish_time, if you're using something goofy to set finish time, you're not using HA or it's attributes properly
and all you'll be doing is causing yourself pain
(like this)
At this point, I think it would be better to describe your whole goal instead of focusing on this small single template
Thank you for your continued patience. I am coming from a place where I know what I'd like to accomplish but not sure how to go about doing it.
For this case, I had a template sensor in the old format that was used to determine if my dryer was 'idle' or 'drying'.
Now I am wanting to extend this so that I can know how long it has been since the sensor went from 'drying' to 'idle' so that I can use that value to send a reminder to action taking out the clothes and/or displaying this on my dashboard.
I already get notifications when the state changes as mentioned but I'd like to know if it's been hours since it was taken care of. I have this set for both washer and dryer with washer more critical to get into the dryer on time.
These are going to be simple template entities
utilize the built-ins that HA offers
for example, a template sensor that knows the time the input_boolean was turned on
template:
- trigger:
- platform: state
entity_id: input_boolean.xyz
to: 'on'
sensor:
- name: Last on
state: "{{ now() }}"
device_class: timestamp
put that anywhere in your UI and it will be translated to the last time it ran, i.e. 15 min ago
you can do the same for when it turns off
then just build automations off that
or if you want a notification if it was turned off 3 hours ago, completely avoid the template and use a trigger
in your automation
Understood. I was trying to consolidate things rather than have a lot of different 'helpers'
- platform: state
entity_id: input_boolean.xyz
from: 'off'
to: 'on'
for:
hours: 3
you don't need helpers, you can probably do all this without helpers, but it seem slike you're stuck in the past
HA has changed alot
start using the new stuff
if you want to display something in a dashboard, you will need helpers
notifications though, most likely no helpers needed. Just an automation
When I said helpers I meant more that what you are suggesting is a separate entity helping rather than included in the attributes.
and that's what I'm saying, you'll need these things to display them on the dashboard
HA has changed alot
Yeah, this is a good thing but does mean learning new stuff. I'm good with it for sure but a bit difficult when I'm not tracking everything that has changed. I'll get there.
attributes do not allow for translations
states do
i.e. more helpers
less attributes
Understood and thanks again. I will rethink/rework my approach.
you need something like this:
trigger:
- platform: state
entity_id:
- person.a
- person.b
to: home
condition: state condition vacuum is running
variables:
notify_mapper: # should match the persons from the trigger
person.a: notify.mobile_phone_foo
person.b: notify.mobile_phone_bar
action:
- service: "{{ notify_mapper[trigger.entity_id }}"
data:
message: Watch out for the vacuum robot
in jinja is it possible to select all values in an list that is greater than a given value ?
or do i need to do a for loop and count then myself? π
Ah, sure it might be but i could not find a single example on it and been searching for 10mins π either i suck at google or its not very common π
any idea of doing a range between two float numbers with a step of say 0.1 ? π
This error started popping in my log lately, even when these templates have existed for a few months.
https://dpaste.org/5WHch
Looking at the comon one among the errors there is no single common sensor causing this. I think the culprit is when calling the last_changed value on any of the sensors. The errors show up when rebooting HA. They don't seem to occur again later.
Can you help me debug the issue?
I recall reading in the docs that using states.sensor... could cause issues when booting and the sensor was not still available. This seems something like that, but unsure. Anyway, there's no other way AFAIK to get the last-changed value. Also it never showed up before, not sure why now.
{% set my_test_json = {'artists': [], 'albums': [], 'tracks': [{'item_id': '4VywXu6umkIQ2OS0m1I79y', 'provider': 'spotify', 'name': 'Better Together', 'uri': 'spotify://track/4VywXu6umkIQ2OS0m1I79y', 'external_ids': [['isrc', 'USMC60400027']], 'media_type': 'track', 'duration': 207, 'artists': [{'item_id': '3GBPw9NK25X1Wt2OUvOwY3', 'provider': 'spotify', 'name': 'Jack Johnson', 'version': '', 'sort_name': 'jack johnson', 'uri': 'spotify://artist/3GBPw9NK25X1Wt2OUvOwY3', 'external_ids': [], 'media_type': 'artist'}], 'album': {'item_id': '7tTc46dNdE6GGuiQsssWxo', 'provider': 'spotify', 'name': 'In Between Dreams', 'version': '', 'sort_name': 'in between dreams', 'uri': 'spotify://album/7tTc46dNdE6GGuiQsssWxo', 'external_ids': [], 'media_type': 'album', 'year': 2005, 'artists': [{'item_id': '3GBPw9NK25X1Wt2OUvOwY3', 'provider': 'spotify', 'name': 'Jack Johnson', 'version': '', 'sort_name': 'jack johnson', 'uri': 'spotify://artist/3GBPw9NK25X1Wt2OUvOwY3', 'external_ids': [], 'media_type': 'artist'}], 'album_type': 'album'}}], 'playlists': [], 'radio': []} %}
{{ my_test_json['tracks'] }}
Can someone tell me how I can structure the template response to grab the 'uri' value from within 'tracks'
I'm able to pull 'tracks' but don't know how to index to grab 'uri' within
or {{ my_test_json['tracks']|map(attribute='uri')|list }} if there's more than one
^
perfect. Thanks to you both
Why can I not get these template sensors to work? https://pastebin.com/v631RDrv
They don't show up as entities
Fortunately it does and haven't had problems until tonight
I suggest re-reading the template sensor docs
I just switched the templates back to the templates.yaml file with the include
It's just a mishmash of old and new formats
Your indentation of packages: is wrong, so I'm curious what it does with that
I had to indent that because it threw an error when I had it indented like the rest
You mixed up that with this; https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
So now I have to put - sensor before each of them?
It is a list, and you need to follow that format. And then you switched formats halfway through
Why if I copy and paste those into developer tools template does it work fine?
Because it doesn't care at all about the YAML format
That fixed it plus adding the - sensor before each one
Thank you @inner mesa!
Now to get this thing counting how many times my sump pump runs
You don't need - sensor: before each one
Here's an example of multiple sensors: https://www.home-assistant.io/integrations/template/#state-based-sensor-changing-the-unit-of-measurement-of-another-sensor
You are correct again. Fixed that. I think I have my sump pump tracker going too. It's running way too much
sweet! thanks man!!
Is there any way to implement that inside the other automation or do they have to be separated from each other? also, where can I put the other option instead of just a message? I wanted it to have 2 options [actionable notification that will have Continue to clean or Return to dock - up to person's choice ofc]
--
In the first automation I got the template
{{ (this.attributes.last_triggered | default(0 | as_datetime, true) | as_local).date() != now().date() }}
I'm trying to set the this to the vacuum entity (which have no attribute of last_triggered) and it gives me an error in dev tools of 'vacuum' is undefined
I also tried to change the entity to sensor.roborock_s8_pro_ultra_last_clean_begin which has a state of timestamp, it gives an error of 'sensor' is undefined
{{ (states('sensor.roborock_s8_pro_ultra_last_clean_begin') | as_datetime(as_datetime(0)) | as_local).date() != now().date() }}
this only works on 2034.2 or higher
returns true now π
so if it's true the condition pass right?
yes
so why is it not triggering the automation? after changing to the right template in the condition part
http://pastie.org/p/7kSPkmZxBIIx2QxgbwZZzn
zone.home state shows 0
and
template returns true on Developer Tools.
the state has to change form above or equal to 1 to below 1
there has to be a state change
change it to 1 in devtools states, then change it back to 0 and wait 45 minutes
also, if you make a change to the automation in this 45 minute period (or restart HA), it won't trigger anymore
Oh got it, thanks man!
It works perfectly!
now how can I approach the 2nd feature of my automation to do an actionable notification to a person when enters zone.home
that will will have 2 options Continue to clean or Return to dock - up to the person's choice on the actionable notification
there is a good example on actionable notifications in the companion docs
Does anyone know of an easy way to calculate variance in jinja from a list of numbers?
make each variable as you loop
with namespace
no different then any other equation
yeah, I saw that one, but how do I separate it for each person who enters the home zone? that's where I'm stuck at.
I use a macro for variance:
{% macro variance(values=[], is_pop=false) %}
{%- if values is not list %}Values must be in the form of a list.{%- else %}
{%- set p = 1 if not is_pop else 0 %}
{%- set l = values|select('is_number')|map('float', 0)|list %}
{%- set m = l|average %}
{%- set n = l|count %}
{%- set ns = namespace( z = []) %}
{%- for L in l %}{% set ns.z = ns.z + [(L - m)**2]%}{%endfor%}
{%- set var = ((ns.z|sum)/(n-p))|round(3, 0) %}
{{- var }}{%- endif %}{%- endmacro %}
this is where numpy would be great
but man would it suck to integrate numpy into jinja
Awesome that worked
What is is_pop for?
oh population?
seeing that it's the denominator in the equation, yes it would seem it's is_population
and it's 0 or 1, so it reduces n by 1
or 0
Sounds good
['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding']
I've got this array coming in as a response variable. I would like to do a find/replace for the single quote character but I cannot figure out how to do this. I know some other times in other instances I've been able to use ' or "'" type thing but can't get those to work with templating.
To be clear when I'm showing these on my card the values are showing with the single quotes and I'm trying to get rid of them.
{{ ['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding'] | join(', ') }}
Perfect! Only one other thing. Can you tell me how to limit the list to the first or last 10 items?
first 10:
{{ ['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding'][:10] | join(', ') }}
last 10
{{ ['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding'][-10:] | join(', ') }}
Thanks for your patience. I said that was the last thing but this has broken a different part. I was doing a substitution for the separator and replacing it with a line break:
"{{ shopping_response['items'][-10] |regex_replace(find=',', replace='<br />')| join(', ')}}"
So what I'm wanting is the output to show the first/last 10 items but have each start on a new line. I'm not sure how to accomplish that now
I got it
join it with <br /> instead of a comma
haha... so much easier. I'm getting closed to finished. Thanks again for the help and patience
hmm, in sensors etc im using attributes for different things that belongs to the same sensor... but in those attributes they can reference other attributes in the same sensor .. is that bad practice? like "sensorname.price_max" checks the max "sensorname.prices | max" for example
if it works, it's not bad practice
bad practice with templates & template entities is using an automation to set attributes via some weird python script
if you post everything involved in what you think is bad practice, we may be able to simplify your process.
was thinking mostly cause im getting template errors in the logs that its a None Object, but it all still works so i guess its when the template is loaded something is "calculated" to early
seems to be when i reload the templates it happends π
yes, that means there is room for improvement
For some reason I get error
Error rendering data template: UndefinedError: 'values' is undefined
again.
http://pastie.org/p/78uZbQeM4A5Vglg7G5BB0K
It worked perfectly on Sunday. [and since June 2023]
I've run into a problem today which I could solve somehow, but I will ask, if someone can explain me, why this had happened and if I can solve it in another (better way).
In a decluttering-card I calculate several time the battery charge percentage:
card:
type: custom:mushroom-template-card
secondary: >
{% set level = calcBatteryLevel %}
icon: >
{% set level = calcBatteryLevel %}
icon_color: >
{% set level = calcBatteryLevel %}
Then upon the level I display different text, icon and or color.
If I use the variable "level" in every case (like above), on one HASS it works, on another one i.e. the icon had not the color I specified, t was gray:
Using different variable names, like "txt_level", "icn_level", "col_level" it works.
Why does this happen? Can I calculate the level once?
each template is independent, they don't share a scope
I don't really understand that use case - you're just assigning a variable and not using it anywhere
I understood, that each template is independent. "calcBatteryLevel" is a funktion like this:
{% set bat_level = ((states('[[entity]]') | int - '[[lower-limit]]'|int) / ('[[upper-limit]]' | int - '[[lower-limit]]'|int) *100) | round(0) %}
Having this expression in the template several times, the icon_color does not work on one HASS but on the other one.
The code is the same in both.
And sure, I have further a bunch if if-statements, I only wouldn't post them here.
is that psudeo code? That's not valid jinja
if you want to reuse jinja code, use custom_templates
Guess it's meant to be used with decluttering card
doesn't decluttering card us JS?
Yes it does
then it's definitely not going to work
No, it is not pseudo code, I only wouldn't post all the code, since it is a lot.
And yes, it is decluttering-card and it works, I'm working in yaml-mode, not UI-mode.
My problem was, that it didn't work when I use everywhere the same variable "level", but it works using a a different in the cases.
#frontend-archived is more suited for help with templating in decluttering card
well, after reviewing the documentation for decluttering card, you won't even be able to use custom_templates to solve this
so, your only option is to copy/paste
cluttering card in this situation
I have no problemn with copy/paste the equation, my problem was, why the variables have to have different names.
Btw, I've tried this withis the decluttering-card:
secondary: >
{% from 'test.jinja' import battery_level %}
{{ battery_level('[[entity]]') + ' %' }}
with the macro:
{% macro battery_level(entity_id) %}
{% set level = ((states(entity_id) | int - 2800) / (3600 - 2800) *100) | round(0) %}
{{ level }}
{% endmacro %}
and it works.
bumping this, still need help
states.binary_sensor.stairs_motion_sensor_occupancy doesn't exist in the state machine
error probably only occurs on startup
if the template is in the frontend, consider moving it to the backend.
how is that done? Never done that before.
Template sensors, they donβt persist through startups like the frontend will
you mean creating a sensor that returns the value of the last_change of the sensor I want and using that in the dashboard instead?
Yeah thatβs one way
cool. When you have a minute, if you can explain alternatives for me to learn, I'd appreciate it
Experimenting with templates I often phase the challenge that the value of a state changes to something which throws an error in the template. Even worse this might happen anytime later an that makes debugging very difficult. Is there any way to test templates with all kind of different states, unlike letting me change the values manually by hand one-by-one?
I also came up with the idea that it might be very helpful if a mouse-hover-popup could be added to the template editor, so that one can see the current value of a state keeping placing the mouse over an entity. If you think that sounds nice, I would formulate a feature request on github
a list and a loop...
use developer tools -> template tab
use {% set value = states('xxxx.xxx') %} in your actual template, but when you test replace it with {% set value = 'whatever you want to test' %}
it's a good idea, but feature requests go on the forums.
Thanks I will do so.
Hi! I am looking for a solution how I could make a sensor that would monitor the calendar entity as shown below, I would like to get the data in the order of the events which are more recent first and for the next 7 days. The current code displays the next event for each calendar separately, which can be several months apart and there can be multiple events within the same calendar within 7 days. ```yaml
Start at: {{ state_attr("calendar.prazniki_v_sloveniji","start_time")}} {{ state_attr("calendar.prazniki_v_sloveniji","message")}}
Start at: {{ state_attr("calendar.krscanski_prazniki","start_time")}} {{ state_attr("calendar.krscanski_prazniki","message")}}
Start at: {{ state_attr("calendar.pravoslavni_prazniki","start_time")}} {{ state_attr("calendar.pravoslavni_prazniki","message")}}
Start at: {{ state_attr("calendar.zodiac","start_time")}} {{ state_attr("calendar.zodiac","message")}}
Start at: {{ state_attr("calendar.f1","start_time")}} {{ state_attr("calendar.f1","message")}}
Start at: {{ state_attr("calendar.moto_gp","start_time")}} {{ state_attr("calendar.moto_gp","message")}}
Start at: {{ state_attr("calendar.odvoz_odpadkov","start_time")}} {{ state_attr("calendar.odvoz_odpadkov","message")}}
Start at: {{ state_attr("calendar.dom","start_time")}} {{ state_attr("calendar.dom","message")}}
Start at: {{ state_attr("calendar.robert","start_time")}} {{ state_attr("calendar.robert","message")}}
You will need to use a trigger-based template sensor with the calendar.get_events service.
Would you be so kind as to write/describe to me in more detail how to do it.
Thanks for the answer. I have to apologize to you because I still don't understand where I have to add this? sensors.yaml, binary_sensors.yaml, automations.yaml etc?
It needs to go either directly in your configuration.yaml or in a file that is merged with the top-level key template...
Look in your configuration.yaml to see if you have a line like template: !include some_file.yaml, if you do, put it in the named file.
Thanks.
I'm sorry. Should this be: https://www.home-assistant.io/integrations/template/
Please clarify what you're asking by that...
I realized that this is obviously different than sensor.yaml or binary_sensor.yaml
@hybrid halo I converted your message into a file since it's above 15 lines :+1:
What makes you think you did something wrong?
If I look at sensor.multical_72_hour_agenda in HA under Developer Tools, it returns state: unknown?
The values will not populate until a trigger fires.
If you want to manually make it to populate, you need to add a trigger that you can control.
I would like to be able to call something like this from the floor plan tab and have it interact with the SVG text field.
Maybe if you have time you should look at https://community.home-assistant.io/t/share-your-floorplan/21315/792 because there are also pictures attached for easier representation.
That seems like a #frontend-archived question.
Ok thanks.
@open vapor I converted your message into a file since it's above 15 lines :+1:
Just get rid of the single quotes so you are using the variable
... selectattr('entity_id', 'in', area_entities(area)) ...
oh, I tried this option, but left the single quotes.π€¦ββοΈ thanks again, it worked
when you can @mighty ledge
all the alternatives involve template sensors of some sort
there's endless template entites you can come up with, so alternatives are not really discussable
I've gone down that route but I don't think I'm doing it right. I'm getting even more errors than before. Here are the 3 created sensors.
- platform: template
sensors:
front_door_last_changed:
value_template: >-
{{ relative_time(states.binary_sensor.front_door_contact.last_changed) }}
back_door_last_changed:
value_template: >-
{{ relative_time(states.binary_sensor.back_door_contact.last_changed) }}
side_door_last_changed:
value_template: >-
{{ relative_time(states.binary_sensor.side_door_contact.last_changed) }}
Here the errors: https://file.coffee/u/diZginQRNsicAuEa-S6I6.png
teh first error is the only one related to those templates
the other errors are still your frontend
oh right, checking them now, mb
you'll have to add availability tempates to those template sensors
availability_template: "{{ 'binary_sensor.back_door_contact' | has_value }}"
is it possible to make the following "less then"?
hours: 0
minutes: 0
seconds: 0```
so person detected, but for LESS then 2 minutes.
the usual is 2 or more.
only with templates
if it's a condition, you can use 'not' to get less than
because for is technically greater than or equal to
go into the UI for your automation, search not in the condition area
I don't have the yaml memorized
a single log error left after fixing the templates, I'm so happy π π π π π π
@scenic verge I converted your message into a file since it's above 15 lines :+1:
would this work @mighty ledge ? so trigger automation if condition is true, but same condition is not true....for 2 mins.
I believe it would
thanks!
Hello, I have made a helper a sensor that calculates the realtime power used by taking the sum of solar generation (e.g. 1000 watts) and the amount that my meter measures going back to the grid (e.g. -800 watts) resulting in a use by my home of 200 watts. however, at night times the helper sensor goes to 'unknown' as the transformer shuts off and the generation sensor becomes unavailable. what would be the easiest way to fix this problem? thanks for any insights :)
feel like im on the right track, but probably loads of syntax mistakes?
sensor.pv_power * sensor.p1_meter_power
{% else %}
sensor.p1_meter_power
{% endif %}```
definitely some odd choices
hey I never used this before :-) this already better I think?
{% set current_power = states('sensor.p1_meter_power') %}
{% if is_number(states('solar_power')) %}
{{ solar_power + current_power }}
{% else %}
{{ current_power }}
{% endif %}```
all states are strings, so you need |float to convert them to numeric values if you want to perform math on them, optionally also providing a default like |float(0)
otherwise, yes, that's a better attempt
Thank you. I tried the above template and it seems to be working without using | float. Some type conversion happening somewhere I guess
I have a rgb strip and i have connected it using dynalite integration. Can somebody please help me in making a template which can combine the channels created as lights to be a single rgb light in home assistant
It will add the strings together, so "101" + "202" = "101202"
As long as the first one is "0" the result will look correct
Ah I didn't think of that. Would've looked interesting tomorrow. Changed it now.
Trying to make a template to display the amount of specified lights and switch entities as lights on. Here is what I currently have that is not working
{% set light_states = states.light | selectattr('entity_id', 'in', entities) | selectattr('state', 'eq', 'on') | list %}
{% set switch_states = states.switch | selectattr('entity_id', 'in', entities') | selectattr('state', 'eq', 'on') | list %}
{% set count = light_states | length + switch_states | length %}
Lights {{ count }} on```
You have a stray ' in the set switch_states statement, but you can do it easier just selecting with the is_state
test:
{% set entities = ['light.aidan_s_bedroom_light', 'light.monitor_ambilight', 'light.3d_printer_light', 'switch.power_strip_socket_1', 'switch.garage_lights', 'switch.chicken_coop_socket_1'] %}
{% set count = entities | select('is_state', 'on') | list | count %}
Lights {{ count }} on
I am using the Mushroom Template card to display some information about my dishwasher. There is a sensor that keeps track of when the cycle will be complete.
I'm trying to display that in the format of something like in x minutes
I am using this as the template value:
{{ states('sensor.dishwasher_dishwasher_completion_time') | relative_time }}
However, it's still displaying it in the datetime format
2024-03-07 05:51:28+00:00
The relative_time filter/function only works on times in the past
You can try this macro from thefes: https://community.home-assistant.io/t/relative-time-plus/635274
Perhaps a dumb question, but I'm trying to figure out what's going on with my very simple dusk to dawn helper sensor. {{states('sensor.sun_solar_elevation') < '-6' }} bounces between states around sunset and sunrise. Any idea why or how I could solve this?
This is the logbook
Turned on
7:11:30 PM - 4 hours ago
Turned off
6:46:04 PM - 5 hours ago
Turned on
6:16:34 PM - 5 hours ago
Turned off
6:48:49 AM - 17 hours ago
Turned on
6:19:27 AM - 17 hours ago
Turned off
5:58:40 AM - 17 hours ago
States are strings
And comparing a string with a string like that is guaranteed to not be what you want
Ah, ok. Makes sense. Will revise. Thank you.
{{states('sensor.sun_solar_elevation')|float(0) < -6 }}
Or you can use state_attr('sun.sun', 'elevation') < -6
You don't need the other sensor and attributes retain their types
Even better. Thanks a bunch!!!
Thanks!
That's something for #frontend-archived
thank
Hey
For some reason I get error
Error rendering data template: UndefinedError: 'values' is undefined
again.
http://pastie.org/p/76KwieEATeY0juFXu1m4Go
It worked perfectly on Sunday. [and since June 2023]
can you check in the trace where that error comes from
well it was one day ago, and state of aquarium is changing every hour.. so it's gone;
I can try manually feed them just for the trace hold on
probably this would solve it
- alias: Check if the values are correct
condition: template
value_template: >
{{
values is defined and values.value is defined and values.timestamp is defined
and not (values.value == 'unknown' and values.timestamp == 'unknown')
}}
at least avoid the error message π
still
Error running action Error rendering data template: UndefinedError: 'values' is undefined
are you running it manually?
how do you mean?
can you send the json download of the trace?
conditions are not checked if you trigger it manually, so changing a condition won't solve it if you run it manually
you pasted the entire condition as template in the condition
you now have:
- alias: Check if the values are correct
condition: template
value_template: >
- alias: Check if the values are correct
condition: template
value_template: >
{{
values is defined and values.value is defined and values.timestamp is defined
and not (values.value == 'unknown' and values.timestamp == 'unknown')
}}
you can just change anything in that attribute in devtools > states to trigger the automation again
oh i haven't slept tonight that's for sure, just fixed it. sorry
let me try to trigger again now
Thanks It's working now π
also got a question related to the Robot Vacuum automation you helped me with template there.
http://pastie.org/p/5Q7jBoOIKmEQD2XZhF5gcl
It is changing the value to true after midnight (by date) right?
so that's why I have set up that condition is time after 10:30AM, but it will have to re-trigger itself to make it run, no?
With that condition it will start cleaning after 10:30 when everybody has left the house for 45 minutes
if the vacuum didn't clean earlier that day
Yeah, but will it work at 10:30AM, when lets say we both left the house at 1AM?
or should we enter zone and leave it again to make it work?
yes
that will work
not specifically at 10:30 AM though
it will trigger when you leave the house
yeah because of the 45 minutes check, right?
not at 10:30, that is not a trigger
yeah yeah I know
Wife asked for a feature to this automation to send actionable notification if vacuum hasn't cleaned for 3 days, how can I approaches that to make it work in your opinion?
Thanks for helping man!
what should be the trigger then? At a certain time? When it has exactly been 3 days? Something else?
well I got sensor.roborock_s8_pro_ultra_last_clean_begin sensor which shows timestamp of the last clean time, I thought of using that as a starter
yes, so you want to get a notification exactly 3 days after that date?
which could be any time of the day
EDIT:
No, let's set it to 12PM.
by the way, I have tried to put the same fishing fed telegram notification automation in my Room Automation (I know you not gonna like this idea.. but I wanted to group all of them in one automation) and it's not sending the telegram photo...
This is the json of the traces - (The specific automation is called there 13 / line 1399
http://pastie.org/p/3rzfzdH4DID9jeXCFw1fIl
I guess it's has to do something with the variables.
you are making it way to complex if you combine them all
I know.... but having 98 automations it's hard for my OCD π¦
you need to move the creation of the variable, and the check if it has valid data in the section for that specific message
Move it to be under the then part?
http://pastie.org/p/2c543yv9C9Bef3TKK5o7U6
I tried to do that, but nothing changed.
The conditions are disabled so don't mind them^
those wait templates don't make sense, there is nothing to wait on
and they are already checked in the conditions (if you would enable tthose)
Yeah, so where should I move the creation of the variable you mentioned?
Okay it's working, I added the variables to the bottom of the automation yaml.
Thanks @marble jackal .
Now is there a chance you can help me with the Vacuum thingy we talked about earlier?
trigger:
- platform: time
at: your desired time
condtion:
- condition: template
value_template: "{{ now() - states('sensor.vacuum_last_time_whatever') | as_datetime | as_local > timedelta(days=3) }}"
action:
- send actionable notification according the example in the companion app docs
Thanks!
Is it recommended to put it in a diffrent automation or can I put it on the same one and use IF triggerd by ...?
whatever you want. Combining automations adds additional complexity and the only advantage is that your list of automations is shorter
Thanks dude!
is getting the trigger of a device trigger the same as an entity trigger?
I.e., ```
{{ trigger.to_state.attributes.friendly_name }}
depends on the device
some device triggers are state based, some device triggers are event based
this one... is based on a "diagnostic binary sensor"
thank you π
{{ trigger.to_state.name }} would work as well
oh nice
Good afternoon all. Is this the best place if I'm looking for assistance with some yaml code? Relatively beginner HA user, have only ever really used the GUI for most of my stuff up until this point.
Depends on what you want to do in YAML. This channel is mainly for jinja2 templates that can be used within yaml. But if you want to configure an integration with yaml #integrations-archived can help you and so does #frontend-archived for all dashboard-related stuff.
I think Jinja comes into play here? I'm trying to get a button to use call service Number: Set to set a speaker entities volume to either 0 or 100 when pressed, and only those values.
show_name: true show_icon: true type: button tap_action: action: call-service service: number.set_value data: value: '0' target: entity_id: number.tapoc111_speaker_volume entity: number.tapoc111_speaker_volume show_state: true icon_height: 50px hold_action: action: none
This works to set the speaker to 0 if it's at 100. I don't know how to continue the logic to do the inverse. Not sure where to read up on this. This is new waters for me.
The default HA button-card does not support templating
So your best bet is to let a script handle the logic and call that script
If you need help with that we can move to #frontend-archived or #automations-archived although it can be setup by the gui from the script editor
Thank you! Need to step away for a bit but I'll jump in those channels shortly!
hey there, i want to create a sensor wich calculate the value kb/sec to MB/sec
i have this code:
- platform: template sensors: total_bandwidth: friendly_name: 'Total bandwidth Upload NAS1' value_template: "{{ state_attr('sensor.nas1_upload_durchsatz') / 1000 }}" unit_of_measurement: "Mbps"
but the sensor is not available. Can someone help me whtas wrong?
all states are strings
you need to convert it to a number first to be able to divide it by 1000
Just curious, why are you doing this? HA does this by default
in sensor.nas1_upload_durchsatz settings, change the units to Mbps
yes, but in then it will only change the Unit, not calculate the valur from kbs to mbs
No
it will convert the value too