#templates-archived
1 messages Β· Page 135 of 1
They're stored with the code for the integration because they're specific to the integration.
You're welcome to search for evidence of a binary sensor showing anything other than 'on' or 'off' in the Dev Tools. It doesn't change at all, regardless of your language settings.
You don't have to scroll far back to see a Dutch user's template: #templates-archived message
Platform translation strings are stored as JSON in the home-assistant repository. These files must be located adjacent to the component/platform they belong to.
https://developers.home-assistant.io/docs/internationalization/core/
π€·ββοΈ
Some components and platforms will have strings that need to be localized specifically for that platform. These strings are managed in the core home-assistant repository. The Home Assistant backend will serve strings to the clients based on the loaded components in the running instance.
https://developers.home-assistant.io/docs/internationalization
I don't know what you know that I don't. Please share.
it is true unfortunately
:/
just copy the state dict into your template from the file you linked and use the device_class to pull the translation
I'm having trouble with this Template Sensor. It seems no matter what I have tried to fix it I cant get it to pass the check.
sensors:
living_room_occupied:
value_template: >-
{{ is_state('binary_sensor.front_door_contact', 'on')
or is_state('binary_sensor.living_room_motion_occupancy_north', 'on')
or is_state('binary_sensor.living_room_motion_occupancy_south', 'on')
or states('sensor.living_room_grideye_occupancy_count')|float > 0 }}```
you're not following the syntax from the docs
I'm not?
I looked at the docs
and I have another Template sensor that passes
I'll look again
Wow I wasn't even close
I guess I need to create a template: section and start over
This also explains alot
I don't think you were too far away, you're just using the legacy version
so where did you put that?
there's nothing wrong with the legacy definition - all of mine are that way
I had it in binary_sensors:
I have now moved it to template:
Is that right?
This is what I have now... - binary_sensor: - name: living_room_occupied value_template: >- {{ is_state('binary_sensor.front_door_contact', 'on') or is_state('binary_sensor.living_room_motion_occupancy_north', 'on') or is_state('binary_sensor.living_room_motion_occupancy_south', 'on') or states('sensor.living_room_grideye_occupancy_count')|float > 0 }}
it should have been under binary_sensor:, not binary_sensors:
no, not quite
state: >-
as in the docs
you should really focus on the error, rather than just arbitrarily changing it
Well I cant get the syntax to pass right now so I'm at least trying to do that first
if it doesn't pass, then there's an error. focus on that
Can anyone explain why this template always shows 9 sep instead of the actual data of today (15 sep).
{{ as_timestamp(states('sensor.date')) | timestamp_custom('%-m %b %Y') }}
The sensor.date works fine btw.
Ok that's embarrassing. Thx Rob π
Hi, I am look for some help.
I am trying to compare the current and previous value of a sensor is there a easy we of doing this?
Can I do something like sensor.name-of-sensor. previous.value
What I am trying to achieve is to find out if the sensor has gone up, it which case I would like to add the difference to a another sensor or if it has gone down add the value to an another sensor.
{{ trigger.from_state.state }} <-- previous
{{ trigger.to_state.state }} <-- new
Thanks @rugged laurel I am struggling to understand how to use them.
If I have a sensor called** sensor.kwh** and I want to get the difference between the current and previous values how do I related the** trigger.from_state.state** and** trigger.to_state.state staments**.
I was thinking of using a custom sensor set up in the my configuration.yaml (sorry if I am doing this the wrong way I as still getting head around it)
@arctic jay posted a code wall, it is moved here --> https://hastebin.com/imasisuhow
Anyone can help me?
I have 3 sensor entities (temp, humidity, pressure) from a aqara temperature and humidity sensor. i tried following code, but i got error "Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->balkon_climate->attributes. (See ?, line ?)."
- platform: template
sensors:
balkon_climate:
friendly_name: "Balkon Climate"
device_class: temperature
unit_of_measurement: 'Β°C'
value_template: "{{ states('sensor.temperature_balkon') }}"
attributes:
temperature: "{{ states('sensor.temperature_balkon') }}"
humidity: "{{ states('sensor.humidity_balkon') }}"
pressure: "{{ states('sensor.pressure_balkon') }}"
Looks like you're using a weird mix of old and new template sensor styles. Use the new style: https://www.home-assistant.io/integrations/template/
Mr. @ivory delta are you talking to me? or to arifroni?
use the rest integration, not the rest sensor.
attributes should be attribute_templates]
also, as mono suggested, you should move to the new implementation of template sensors
i will try it, thanks
thanks, it works with attribute_templates. I mixed up with new and old implementations. now I am converting all old implementations to new ones. i noticed, there is no 'friendly_name' in the new implementation. how can I achieve that? For example in this case
template:
- sensor:
- name: hue_toilet_motion_sensor_battery
unit_of_measurement: '%'
state: "{{state_attr('binary_sensor.hue_motion_sensor_1_motion', 'battery_level')}}"
anybody that can offer some wisdom on templating the navigation_path for a tap action in lovelace?
i've been asking in #frontend-archived but maybe it's an issue with my template?
you can't template the frontend
there are custom cards that allow you to template things, but that's it. Only built-in card that can be templated is the markdown card
i have successfully used custom:card-templater before
and am trying now, but it's not doing what i expect, even per the docs for that card
π€·ββοΈ you'd have to post configuration
Hi there again, as @mighty ledge suggested i tried to use rest integration and not rest sensor. I still cannot get the correct value.
Am I using it correctly? can use attributes like this? dataList[2]???
rest:
- resource: https://api.solarmanpv.com/device/v1.0/currentData?appId=XXXXXXXXXXXXXXX&language=en&=
scan_interval: 300
headers:
Authorization: XXXXXXXXXXXXXXXX
Content-Type: application/json
payload: '{ "deviceSn": "XXXXXXXXXXXX"}'
sensor:- name: "TEST SOLAR"
value_template: "OK"
json_attributes:- "deviceType"
- "dataList[19]"
- "dataList[21]"
- name: "TEST SOLAR"
Anyone can confirm this?
json_attributes string | list (optional)
A list of keys to extract values from a JSON dictionary result and then set as sensor attributes.
The key names. Not paths to anything beneath those keys.
You probably need to create multiple sensors instead. States are more useful than attributes anyway.
every dataList[X].value have a value that i need, and the X goes from 1-30. Do i need to create 30 sensores? I will need to get information from the API 30x every 300 seconds... ?
That or create a custom integration π€·ββοΈ
create 30 sensors in the sensor section, all with value_templates that pull the data you want. If you read the documentation instead of following the examples, you'd read that it only performs 1 get to populate all the sensors.
rest:
- ... all your setup junk ...
sensor:
- name: sensor 1
value_template: "{{ value_json.deviceType }}"
- name: sensor 2
value_template: "{{ value_json.dataList[19] }}"
- ... etc ...
Its WORKING! I love you all!! thanks!
sry for my dumb and lazy person
Is there a simple way to have the last word say 'time' when result is 1 and else 'timer'?
state_attr('input_datetime.vaskemaskin_startet', 'timestamp')) |
timestamp_custom('%H') |int }} timer.```
set the result equal to a variable and use almost what you have written in your sentence
Iknow you know how to do this, you've asked questions many times here before
start with the first part. How do you set something to a variable? There's literally hundreds of thousands of examples
start simple, just set something like x equal to 1
I think I found a different way but it might be silly:
state_attr('input_datetime.vaskemaskin_startet', 'timestamp')) |
timestamp_custom('%H') |int == 1%}1 time{% else %}{{ (now().timestamp() -
state_attr('input_datetime.vaskemaskin_startet', 'timestamp')) |
timestamp_custom('%H') |int }} timer. {% endif %}
yep that will work, but if you just learned how to set something, it would be alot smaller. Either way, you do you
But you still meant using if and else? Like so?
state_attr('input_datetime.vaskemaskin_startet', 'timestamp')) |
timestamp_custom('%H') |int %}
Vaskemaskiiinen er nΓ₯ ferdig etter {% if vaskemaskin_timer == 1%}1 time{% else %}{{ vaskemaskin_timer }} timer. {% endif %}```
yah but you can use inline if statements, which is almost word for word what you typed
you said " say 'time' when result is 1 and else 'timer'?"
{{ 'time' if vaskemaskin_timer == 1 else 'timer' }}
literally almost word for word
just sayin π
More concise and easier to read too 
Ah. Thanks!
You got a few i to many in "Vaskemaskiiinen"
It's because of the cloud_say service. For some reason that's the only way it will say it properly. π
Same with tumble dryer (tΓΈrketrommelen) that needs to be spelled 'tΓΈrke-trommelen'. Otherwise it puts in a 'u' instead of 'o'.
trying to figure out a template to give all automations which triggered within x amount of time
any ideas?
What have you tried?
hahahaha π I would just use English in that case
As a hint... seems easy to grab all the automations and run them though rejectattr.
My workaround works just fine. π
How stupid is this template? I mean, is there a better way doing this. π
{% if lights|length == 0 %}
{{ 'Verlichting staat uit' }}
{% elif lights|length == 1 %}
{{ '1 lamp aan' }}
{% elif lights|length == 2 %}
{{ '2 lampen aan' }}
{% elif lights|length == 3 %}
{{ '3 lampen aan' }}
{% endif %}```
To get lamp vs lampen?
Yeah i want to show 1 light on, 2 lights on, etc and if lights off "Lights Off".
But i'm not skilled in this so that's the easiest way i can found for me. π
In your language, how many numbers would use 'lamp'?
One
Right... so that's the only special case to cover.
1 lamp or 2 lampen
An almost identical question was just asked... #templates-archived message
and if you don't care about the object_ids anymore you can pare down your set
drop the map
Haha that's to much for me phnx, i just "stole" your template from yesterday and changed it a bit. π
Maybe i just keeps this because it works and otherwise i will make it worse it think...

{{ '{} lamp{} aan'.format(lights|length, 'en' if lights|length > 1 else '') }}
Where will this be placed in the template?
If i do it like this it says "0 lamp aan" but there are "3 lampen aan".
{% if lights|length == 0 %}
{{ 'Verlichting staat uit' }}
{% elif lights|length == 1 %}
{{ '1 lamp aan' }}
{% elif lights|length == 2 %}
{{ '2 lampen aan' }}
{% elif lights|length == 3 %}
{{ '3 lampen aan' }}
{% endif %}```
That isn't supposed to be the first line. It's supposed to replace the numerous ones beneath.
so like i know this isn't right:
{% set automations = states.automation %}
{{ automations | rejectattr('last_triggered', '>', '300') | list }}
how do i get the last triggered from a datetime into a float so i can compare to now? basically
Well that's not going to be testing the last_triggered anyway. You want 'attributes.last_triggered'.
leave them both as datetime objects and compare directly
i want to do something like "all automations that triggered in the last 5 minutes"
so i think i need to do now - 300s and reject anything greater than that
is that not what rejectattr is doing?
Try it yourself. Simplify it so you can see it a step at a time.
well i can see that last_triggered is an attribute of the entities
What does this give you?
{{ expand(states.automation) | map(attribute='last_triggered') | list }}
a bunch of undefined
And how about this?
{{ expand(states.automation) | map(attribute='attributes.last_triggered') | list }}
so if i put attributes.last_triggered i get datetimes
Hence... #templates-archived message
Jinja doesn't know what HA attributes are. You have to tell it where to look...
ok but for example this isn't right syntax: rejectattr(attribute='attributes.last_triggered', '>', now())
No, it's not. What's it telling you?
TemplateSyntaxError: invalid syntax for function call expression lol
you don't need the expand
and this: rejectattr('attributes.last_triggered', '>', now())
gets me TypeError: '>' not supported between instances of 'NoneType' and 'datetime.datetime'
{{ states.automation | map(attribute='attributes.last_triggered') | list }}
because i have a bunch of undefineds in there
Nothing to do with undefined...
If you're using rejectattr('attributes.last_triggered'..., they're not undefined.
You just proved that by using a map to see the values.
seems to me that rejectattr and map have different syntax
what they're looking for is the same.
map, requires you to explain what you want to map
rejectattr and setattr expect attributes, so you don't need attribute=""
so yes, the syntax is different
But you still need 'attributes.', which is what they're disputing.
yes, because that's the attribute
See for yourself, drinfernoo:
{{ states.automation | selectattr('attributes.mode', 'eq', 'parallel') | list }}
Works fine. Syntax isn't the problem.
The comparison is, which is what it's telling you.
in map you'd need attribute='attributes.last_triggered'
in selectattr/rejectattr you just use 'attributes.last_triggered'
ok
the attribute doesn't change between the 2 methods
so i need to figure out the comparison
to do what
not error lol
i want to do something like "all automations that triggered in the last 5 minutes"
^
so like this: {{ states.automation | rejectattr('attributes.last_triggered', '>', (now() | float) - 300) | list }}
but last_triggered is obv not a float
{{ states.automation | rejectattr('attributes.last_triggered', <, now()-timedelta(minutes=5)) | map(attribute='entity_id') | list }}
but you might have to reject missing last_triggereds
{{ states.automation | rejectattr('attributes.last_triggered', '<', now()-timedelta(minutes=5)) | map(attribute='entity_id') | list }}
TypeError: '<' not supported between instances of 'NoneType' and 'datetime.datetime'
yeah umm
{{ states.automation | rejectattr('attributes.last_triggered', 'eq', none) | rejectattr('attributes.last_triggered', '<', now()-timedelta(minutes=5)) | map(attribute='entity_id') | list }}
seems to do it
Just for semantics, I'd suggest going with this:
{{ states.automation | rejectattr('attributes.last_triggered', 'eq', none) | selectattr('attributes.last_triggered', '>', now()-timedelta(minutes=5)) | map(attribute='entity_id') | list }}
The fewer negatives, the better. Easier to understand when you want to read it in a few months.
sounds like a lesson learned the hard way π
We've all struggled with boolean logic at some point, right? I particularly hate nested ternary expressions π€’
I like to think in double negatives
No... I left that the same deliberately. For the first part, you're throwing out the bits you don't want. For the next part, you're keeping the bits you want.
its not never the correct way to do things
ok so... now i'm stuck again on how exactly to use this for what i want
i'm using it in a template filter for custom:auto-entities
but i want to pass options to the entity row as well
which is setting options: ... for include: and exclude: filters
but for a template filter i have to return the whole entity object
So return the objects.
Just don't map the entity ID...
The base form of your 'get every automation from the last X minutes is something like this:
| rejectattr('attributes.last_triggered', 'eq', None)
| selectattr('attributes.last_triggered', 'gt', utcnow()-timedelta(minutes=60))
| list
}}```
Map what you want out of it when you need it. Otherwise, that's just a list of state objects.
(also, bonus points for formatting it to be easy to read π )
I thought there was a way to map that properly with auto entities where it uses the entity_id and it's mapped to properly place it in the object
well i mean it gives me the entity ids which is fine
I can't remember tho because I haven't used that in like 2 years, ditched it for lovelace_gen
but like for example:
filter:
include:
- domain: light
state: "on" # Remember that "on" and "off" are magic in yaml, and must always be quoted
options:
tap_action:
action: toggle
that is an example FROM github
not mine
but i need to pass the options: block as well
and template: filter doesn't support that
so i think my template needs to include all those options?
frick idk
maybe that's something i should take to #frontend-archived now
You're looking at the wrong bit of the docs, but yes... go to #frontend-archived
pretty sure you just apply that filter after your entity_id filter
What does it output?
nothing... testing in template editor and a bit sutck
well, i shouldn't say nothing
It'll tell you what's wrong...
doesn't show any entities in the card
Put it in the Dev Tools. Tell us what it shows.
it tells me
TemplateSyntaxError: unexpected '%'
Right. Because you have a template inside a template. That's invalid.
ok
I have no idea what you think you're referring to with config.entity either.
Nor do I know what you're trying to do with having a | inside a string.
And the | before an object for tap_action? 
Now you have strings that span multiple lines, rather than multiline templates...
But if it works...
ah well didn't change anything
i had used | because of
something
idr
type: custom:auto-entities
card:
type: entities
filter:
template: |
{% for light in states.light %}
{% if light.state == "on" %}
{{ light.entity_id}},
{% endif %}
{% endfor %}
that
from auto entities docs
actually when i changed it to >, it changed it back to | when i saved
this is the output inside dev tools: https://www.hastebin.com/iwavavebat.json
Make sure that when you test it in dev-templates it says "Result type: list"
ohhh it's counting all my commas as a new list item
That requires some trickery with quotes and stuff. This works, for example: {%- set ids = states.automation | map(attribute='entity_id') | list -%} [ {% for id in ids -%} { "entity": "{{id}}", "secondary_info": "last-changed", }, {%- endfor %} ]
And since the results you want includes templates, you also need {% raw %} {% endraw %} in some places.
π° π³οΈ
so raw/endraw should basically go around any of my "inner" templates?
around the whole thing or around each line?
inside or outside of quotes?
And then there's the newlines...
[
{% for id in ids -%}
{
"type": "custom:template-entity-row",
"state_color": "true",
"secondary": "{%raw%}{%- if state_attr(id, 'last_triggered') -%}{{ relative_time(state_attr(id, 'last_triggered')) }} ago{%- else -%}Never triggered{%- endif -%}{%endraw%}",
"state": "{%raw%}{%- if state_attr(id, 'current') == 0 -%}Not Running{%- else -%}{{ state_attr(id, 'current') }} Running{%- endif -%}{%endraw%}",
"tap_action": {
"action": "navigate",
"navigation_path": "/config/automation/trace/{{ id.split('.')[1] }}"
}
},
{%- endfor %}
]```
hmm ok lemme see
This bit is magic.
actually ended up not needing the raw/endraw or removing newlines
it was the quotes around my tap_action json
simply removing those made it resolve as a string
and my card works π
can I sort that list by last-triggered?
seems auto entities sort doesn't work with template filter either
@blazing burrow When using Discord's Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
You have to change this every time (thank the Discord devs for that).
yeah I clicked it too fast π¨
If you want to sort, sort before you start looping.
There's a Jinja filter for sort.
There's a reason we have pins for the common questions π
Filters are powerful once you understand how to combine them.
hoi, i need a tiny bit of help
state: "{{((states('sensor.lux_ups_time') | float + states('sensor.caitlyn_ups_time') | float ))}}"
If i put / 6000 at the end will it actually divide the whole thing of do i need to do something different?
If you just add it to the end, it'll divide the last number.
Try it in
-> templates
You need to wrap them in parentheses to ensure the division happens last.
but just putting the / 6000 after brackets should work? HAS has many times screwd my brain process before
Try it and see
as helpfull as that may be some come here to get a quick and simple answer...not "try a billion times and see what works" ^.^
Thanks for the help @ivory delta
Did you get it figured out?
yep just the brackets as you said ^.^
Sigh. You can try something like that in much less time than it takes to post in
-> Templates. Thatβs my point
βWhat will it do if I do this?β Are easily answered there
but once someone has asked you can probably answer them in a normal way rather than say to find it out the hard way....idk at least that would be more helpful in my opinion(if not helpful than at least nice and polite), Thanks for all the help and ima hop out till i need something again
also how do i use an entity from a template in the energy thini?
Got a qq here. I have a value template that I'm trying to figure out with a water sensor. I've been racking my brain with this one but the sensor in HA always reports Unknown. Even though the entity is reporting a 0
sensors:
laundry_room_wet_sensor:
friendly_name: "Laundry Room Water"
value_template: >-
{% if is_state('number.basement_water_sensor_basic', 255) %}
wet
{% elif is_state('number.basement_water_sensor_basic', 0) %}
dry
{% else %}
n/a
{% endif %}```
I'm sure I'm missing something dumb
yes I've tested this out in the developer tools with success so I'm not sure whats missing in transit
States are strings and youβre comparing the state to a number
Itβs confusing. The state of a number.xx entity is a string
ok so wrap the 255 in single ticks
lol all I wanna know is if the hoses on the washer bust
and of course turn off the water if that happens
neighbor had that happen to them and ever since I've been like I need to automate this
ok so got that in there now but the template entity still reports it as Unknown even though thats not one of my values
Correction it just changed over to n/a
and I can confirm that the device is reporting in the 255
2021-09-15 23:36:21.255 INFO ZWAVE: Node 41: value updated: 32-0-currentValue 0 => 255``` from zwavejs logs
and I can see the number entity in HA change to 255 but the template will not update
hopefully a quick one for someone:
I've got an input_datetime helper set to 05:15, but {{ (state_attr('input_datetime.climate_start','timestamp')) | timestamp_custom('%I:%M %p') }} gives me 03:15 PM
developer tools output:
editable: true
has_date: false
has_time: true
hour: 5
minute: 15
second: 0
timestamp: 18900
friendly_name: Climate Start
I'm sure there's something I'm missing, but what...?
for those having a similar issue, timestamp_custom is assuming the input is UTC and offsetting for local time (timestamp_custom(format_string, local_time=True)) so doing timestamp_custom('%I:%M %p', False) gives me the correct output of 05:15 AM
<<< Read the docs!
Hi guys, How could I pull light color value to variable, so I can use it for something else in automation later on? I tried below way (and few modifications with and without quoting), but it is not working. I get "Message malformed: extra keys not allowed @ data['variables']
platform: state entity_id: light.lampkidsroom_1 variables: color_name: > {% states.light.lampkidsroom_1.attributes.rgb_color }
thx
Yes, I know that. I am not skilled with codding, but I'm "swimming" when have right syntax :)
You mean that in action: I should use state rgb attribute directly?
I canβt really figure out what youβre trying to do there. If you want to use the value of an attribute as data to a service call, then you just use {{ state_attr(βlight.lampkidsroom1β, βrgb_colorβ) }}
Yes, I want to use rgb value of one bulb to set that rgb value on another bulb with service call light.turn_on
Will try with your propose above
Right, so you do it that way
Thx
Hello all. I have a question. I created statistics for a sensor, and then I want to get the statistics attribute for this sensor to use in automation. But for some reason the attribute is constantly "unknown"
`- platform: statistics
name: "CO2_white_stat"
entity_id: sensor.CO2_white
- platform: template
sensors:
co2whitechange:
friendly_name: "CO2 white change"
value_template: "{{ state_attr('sensor.CO2_white', 'change') }}"`
use in UI sensor co2whitechange does not output number
but on the main sensor I get all the statistics data, they are collected and displayed, but I cannot take one attribute separately
Please tell me what I did wrong?)
You are using the wrong entity id, the stats sensor should be this according to what you have posted (taken from the name): ```
value_template: "{{ state_attr('sensor.co2_white_stat', 'change') }}"
Also entity ids never have capital letters.
Also, also you probably don't need a template sensor for this. Numeric state triggers and conditions can access attributes.
thank you dear friend!!!
It helped me a lot and I understood everything at once)
Hello, I have a sensor on home power consumption, not on the meter, so I should use a template to create a new energy sensor
I need something like
if ( consumed power > produced power )
return consumed power - produced power
else
return 0
could you help me? Thanks
{% set diff = states('sensor.consumed_power')|float - states('sensor.produced_power')|float %}
{{ diff if diff > 0 else 0 }}
replace those 2 sensors with your actual sensors
thanks!
surely my fault, but Error loading /config/configuration.yaml: while scanning for the next token
found character '%' that cannot start any token
in "/config/configuration.yaml", line 123, column 26
sensor:
- platform: template
sensors:
power_taken_grid:
friendly_name: Energia Prelevata Rete
value_template: {% set diff = states('sensor.power_home_energy_power')|float -
states('sensor.power_powerplant_energy_power')|float %}
{{ diff if diff > 0 else 0 }}
device_class: energy
unit_of_measurement: "kW"
Either have your template on a single line and wrap it with quotes, or use multi-line templates.
thanks!
Greetings! .. I am in process of converting my mqtt fans to the new method for using speeds and I am following the information in the following post (At least I think I am anyway! π ) : https://community.home-assistant.io/t/how-to-using-the-ifan03-ifan02-running-tasmota-on-mqtt-with-the-newest-updates-to-the-fan-control-models-after-ha-v2021-3-x/297736
here is the link to the config yaml I am using.
@mellow pulsar posted a code wall, it is moved here --> https://hastebin.com/nukidubusi
I believe I have only modified the name, and the states names to reflect changes for my HA instance.
I am getting the following error when trying to start ..
The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while parsing a block mapping in "/config/configuration.yaml", line 1, column 1 expected <block end>, but found '-' in "/config/configuration.yaml", line 692, column 1
692 in my config yaml is at the end of the section above for a different entity and it is ok.
help! π
can someone help me with this 'template'
Game: [[ if(sensor.lich_XXXX.attributes.game == null, "") ]]
i want that "null" should be clear, but when its not "null" it should show the state
Result is this for now:
Game: [[ Template matching failed: if(sensor.lich_5769.attributes.game == null, "") ]]
ok i changed that
That doesn't look like Jinja.
how can i make it better ?
Well... what is it? It's not Jinja. Are you trying to write JavaScript for a #frontend-archived card?
i think so
.share the whole thing
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://hastebin.com/ (sometimes may not allow you to save)
Please don't use Pastebin, since it can randomly add spaces to the main view.
So that's quite clearly a card... and you're lost. You want #frontend-archived
hmpf
posted this value_template {{value|round(2) if value < 2500 else 2500}} in #devs_zwave-archived as a possible but hacky way to protect my mqtt sensors in Ha from hysterical spikes. I know you say prevent sh*t from the source, but there's no way. So will test this for some time. Just asking here if this template could be written with other jinja tools/function/filter to set a ceiling value?
also, to prevent a spike from lets say 200000kWh while it needs to be 34 kWh ( I kid you not) Id consider a value_template to check if the new value is smaller than +10%, and if not, remain with the old value. Would this do: {% if value > states(entity_id) * 1.1 %} {{ states(entity_id) | round(2) }} {% else %} {{ value | round(2)}} {% endif %}
And what if there's a genuine reason for an increase greater than 10%?
I dont think that will ever happen on a kWh sensor, but maybe I could set it a bit higher
final question, and this might be the most difficult, are negative dents of the same size on the kWh sensors. I could simply use value < states(entity_id) * 1.1 or another number, but would need to take a true reset into account. Maybe exclude the value == 0 situation?
I still think you're overthinking it. What's the highest legitimate value you've seen, and have any spikes been less than that?
well, yes, its a bit weird but right now I see a kWh sensor which should grow from 847 onward, had a dent to 0.7 this morning and shortly after that returned to 847+..likewise I have the mentioned spike from 32.25 to 167804.41 back to normal 32,34 ... so yeah these are pretty wide ranged issues...
btw the first one would be {{min(value|round(2), 2500)}}? nice!
Personally, I'd do it the other way round. Pipe a list into the filter... but same thing.
If the spikes are always crazy big numbers, the 10% increase thing in unnecessary. Stick with picking the smaller of two numbers, where one is your upper limit.
Hi guys. Trying to understand how to use a for loop, but I fail to make it return entity_id's. What am I missing? ```
- service: script.turn_on
data_template:
entity_id: ['script.hallway', 'script.kitchen', 'script.living_room']
entity_id: >
[{%- for room in ['hallway', 'kitchen', 'living-room'] -%}
script.{{ room }}
{% endfor %}]```
the commented out line works, and does what I want. I'd like the loop to do that as well, but....
Itβs curious syntax
I saw it in the chat some time ago and thought I'd save it for later...
You saw that?
An example using this technique. So basically, the loop needs another syntax?
I have of course added my entities to it, but other than that just left out an if statement I don't need
one way:
{% set rooms = ["foo", "bar", "blah"] %}
{% for room in rooms -%}
script.{{room}}{{", " if not loop.last }}
{%- endfor %}
-> script.foo, script.bar, script.blah
I don't think you can embed a template in square brackets to form a list like that
Oh! Thank you. No, the trace just printed the whole thing, so did not get interpreted correctly. Will test your code π
ooh, even better:
{{ ["foo", "blah"]|map('regex_replace', '^', "script.")|list|join(', ') }}
I like that a lot
Works very nice! Thanks! π
that last one is very sexy
I'll try that too, agree, like the compact syntax π
-> script.foo, script.blah
Perfect! I use this a lot, so will be very useful! Thanks π
sorry for the tag, but this was long way up... what do you mean there?
btw having terrible type error issues with the entity_id templates on mqtt, I cant get them to work. so I tested the example template https://www.home-assistant.io/integrations/sensor.mqtt/#usage-of-entity_id-in-the-template and even that throws TypeError: can't multiply sequence by non-int of type 'float' Is that bugged?
can only get a working template if I float states(entity_id) which makes that 0 in case of unknown. So basically useless....
If states(entity_id) | float * 0.1 return 0 then your state was either 0 or nullish and then it would make perfect sense.
yes, but the state wasnt 0 or nullish... I am trying to do this {% set old = states(entity_id) %} {% set new = value %} {% if old == 0 and new < 2 %} {{new}} {% elif new > old * 1.5 or (new < old and value != 0) %} {{old}} {% else %} {{new}} {% endif %}
I never used entity_id in mqtt sensors, so I don't know how or if they work
I thought that's how I have to explain the example in the mqtt docs
What is your old value?
Not sure... the one before the current π
Pretty sure that var doesnβt exist
yes, that is what I was beginning to wonder about too, it is explicitly noted in the docs though as being available https://www.home-assistant.io/integrations/sensor.mqtt/#value_template
As I read that example, states(entity_id) is kind of a from_state and value is the to_state .. kind of
I was able to use the example template on a temp entity, and noticed it was unavailable at first, but after an update started to show. however, when using even {% set old = states(entity_id) %} {{old}} on my energy sensors (which have updated while I waited) they remain unavailable after mqtt reload, and unknown upon HA restart.
yeah.... because the old state on startup is unkonwn and it'll never update if you only provide the old state, which is always unknown...
was just experimenting with {% if old == None %} {{new}}
but new doesn't exist
but that remains unknown too.... new is value
and you're missing the endif
{% set new = value %}
{% if old == None %} {{new}}
{% elif old == 0 and new < 2 %} {{new}}
{% elif new > old * 1.5 or
(new < old and new != 0) %}
{{old}}
{% else %} {{new}}
{% endif %}```
well, you never cast old to a float
{{ [1,1000] | min }} # returns 1
I just prefer pipes over functions.
Still the same filter, just a different style of writing it.
ok let me try that
yes thats tricky, ran into trouble floating before, all templates remained 0 π
why aren't you just using filter?
getting '>' not supported between instances of 'str' and 'float' if I use the |float on old... {% set old = states(entity_id) %} {% set new = value %} {% if old == None %} {{new}} {% elif old == 0 and new < 2 %} {{new}} {% elif new > old|float * 1.5 or (new < old and new != 0) %} {{old}} {% else %} {{new}} {% endif %}
value is also a string
filter: because a) that smoothes out the errors I like to ignore instead and b) needs yet another entity... Id hoped to do it all in the mqtt sensor config
if I use new = value|round(2), would new still be a string?
it should be a float at that point
you should really just use the outlier filter
or range
if those don't get you what you want, make a FR for a range calc that acts like outlier
outlier with a radius of 2 is very close to what you want but the band moves with the value.
thanks, Ill have a go at that. Meanwhile I tried this in template editor {% set old = states(entity_id) %} {% set new = value|round(2) %} {% if old is not none %} {% if old == 0 and new < 2 %} {{new}} {% elif new > old * 1.5 or (new < old and new != 0) %} {{old}} {% else %} {{new}} {% endif %} {% else %} {{new}} {% endif %} which seems to behave well
but in the mqtt value_template it yields Unavailable....
ofc I replace the values in the opening set's with test values
like this {% set old = 0 %} {% set new = 1 %} {% if old is not none %} {% if old == 0 and new < 2 %} {{1}} {% elif new > old * 1.5 or (new < old and new != 0) %} {{2}} {% else %} {{3}} {% endif %} {% else %} {{4}} {% endif %}
figure out which is causing the problem
new or old
by hardcoding new or old and keeping the other the value it's supposed to be
Or using outlier π
no, that would be too easy
at this point, I'd want to figure out where the fuck up is in the template
test for existence needs to be {% if states(entity_id) not in ['unknown','unavailable'] %}
at least that gets me past the initial test, and routes me to the correct endpoint in the template. Now I still need to test that with real life value, and see if an 'old' value is seen and compared to a new value, the actual latest mqtt value
{% set new = value|round(2) %}
{% if states(entity_id) in ['unknown','unavailable'] %} {{new}}
{% else %}
{% set old = states(entity_id)|float %}
{% if old == 0.0 and new < 2 %} {{new}}
{% elif new > old * 1.5 or
(new < old and new != 0) %}
{{old}}
{% else %} {{new}}
{% endif %}
{% endif %}
maybe I need to use new != 0.0 in the elif, not sure yet...
for now, I see the Energy sensors update their value and get a value at reload, so those bits of the template fare well. must yet experience a downward dip, or reset to 0 to see if they survive ;-0
all in all I have capped my power sensors to the max rate limit of their documented range and guarded the energy sensors for these ridiculous spikes and dips. I feel the current 'dumb' energy integration really should be doing all of that, by implementing these heuristics.
if in configuration file I create a sensor, when I delete it from the file, it will survive? If I create another sensor with same id/name, will be a new sensor? I'm going banana
@tacit arch posted a code wall, it is moved here --> https://hastebin.com/rowokehiro
I have this in configuration
https://hastebin.com/rowokehiro
sensor.power_taken_grid appears name Not available
they are using the same unique_id
Not so unique then π
Generate UUID's for your unique ID's, then you don't have to remember which ones you've used before.
Never trust a human to come up with anything unique or random.
I supposed a unique id of an existing entity, if I delete the entity I delete the id no?
I should do it on the db?
I don't know what you're asking. I can tell you, you should have 2 different unique_id's there. Not the same one.
unique_id: power_taken_grid
unique_id: power_given_grid
are different
ah i didn't notice that, it looked the same at a glance
so you need to rephrase your question because I'm having a hard time understanding what you're asking
I can't understand why all this doesn't work, after a reboot sensor.power_taken_grid became unavailable and can't delete it. before I used the same name/id for another sensor, not more present. could this be the cause? If yes, how can I delete all data of a entity/sensor when deleted?
it's faded
screenshot?
does the sensor say "read only" on the entities list page?
no, only "this entity is unavailable
anyways, what you can do is rename the entity_id on that one (the one you can't delete), then find the new one that's being created and rename that to the old entity_id that you want.
AH, nevermind
i see your issue
ok, but usually how I delete all data associated to an entity?
don't know, maybe are stored on db even if the entity have been deleted?
no, you have a bad configuration, look at the arrows
I'm an idiot
hahaha, we've all done it
thanks
np
I spent 3 hours this morning
trying to find a bug in my code
and it was a spelling error. in the word actual. I spelled it actaul
so, definitely been there
ok, the entity now it's normal, I've to wait tomorrow to test if all works as I hope
thanks
I have bit of a trouble with entities, they by default show as value based etc.. power meter and instead of text history I have value based one. Any idea how I can modify entity to correct this?
Hello! Anyone know how to call sqlite query from template?
You don't, templates don't make service calls.
You can possibly use templates with the SQL sensor though - the sensor makes the SQL call, the template would just describe what call to make.
are you talking about history graphs?
Yes somehow https://ibb.co/fMb4KJK take look at pic, history graph wants to graph value but this is text based entity
Is it some parameter or something how how I can correct this?; perhaps through template? I have also open issue with integration developer more details here https://github.com/JoDehli/PyLoxone/issues/86
It has a unit of measurement
Itβs not explicitly configured, can I somehow enforce βnoneβ to fix this?
You can customize it
But itβs probably worth it just making a template boolean because itβs not really a sensor
Any idea how to customize it? To get rid of this unit thingy?
Hi, how can I get the sum of multiple entities' states in a template? without listing them one by one
the entites are in numerical order name_1, name_2, name_3 etc so is there a way I can match them by regex name_\d and then get the sum with like a .sum() operation?
{{ states|selectattr('entity_id', 'match', 'input_number..*temp')|map(attribute='state')|map('int')|list|sum }}
for instance
@shell pine
You'll want to escape the first period in that: 'input_number\..*temp
it works as-is
Although the first would work because . will match any character, including the period π
yes
It's just somewhat redundant.
well, that's true. I could just leave it out entirely
I think I had the same discussion recently - getting a sense of deja vu
search is always from the start of the string, right? I think I prefer match, even when I might be after the first part of a string, just so I don't have to remember two different tests.
Oops, other way round.
anyway, I've contribute my required "interesting template of the day", so I guess it's time for a beer
could be trouble, considering that it's only 2:30pm and I'm in my second week of a new job
It's Friday afternoon, no-one expects you to do any work.
thanks
i have some fields defined in a script, but I don't see the fields UI when calling it from an automation\script
all i see is a data: field
whoops... didn't add a selector for the fields. it's working now
entity_id: counter.button3
value_template: xxx modulo 4 == 0 xxx``` Is there a way to test if counter.button3 % 4 == 0
platform: template
value_template: "{{ states('counter.button3')|int % 4 == 0 }}"
My template won't round, what am I missing? {{ states('sensor.panel_total_kwh_cost') | float + 0.82 | round(2) }}
Put it in the template editor. Your results will be .82 so more than likely it is rounding but the rest of your template is wrong.
Thanks
Then I could make this two template sensors to get the wanted result. Is there a way to do this in one template?
Quick maffs
Thanks!
Hello All. I'm having trouble with a template for the Emulated Kasa integration. I'm getting the following config invalid message after I input a template for the dimmer:
light.bedroom_1_bedroom_main_lights (its second from bottom). Attached is a link to debian...https://paste.debian.net/1212261. Can anyone point me in the right direction on where I'm screwing up? Thank you.
Invalid config for [emulated_kasa]: expected float for dictionary value @ data['emulated_kasa']['entities']['light.bedroom_1_bedroom_main_lights']['power']. Got "{{ (state_attr(βlight.bedroom_1_bedroom_main_lights', 'brightness')|float/255|float)*72.0}}". (See /config/configuration.yaml, line 26).
you have fancy quotes in there. Never copy/paste from a forum post if the code is unformatted
your single quotes should be '
not the fancy ones
i'm sorry, newbie here...what are the fancy ones? --> { & }?
β
should they be removed, or replaced with "
read previous post
use normal quotes
not quite
now you're using the same quotes inside and outside
which will break the parser
so only have them on the outside?
as you can see from the color-coding in your link
also no
I'm not sure what you're doing there, but something like this:
light.bedroom_1_bedroom_main_lights:
name: "Bedroom 1 Lights Current Consumption"
power: "{{ (state_attr('light.bedroom_1_bedroom_main_lights', 'brightness')|float/255)*72.0}}"
thanks you, RobC!
You're the man. I appreciate all your help...not just now...be also in the past.
I am trying to parse some nested JSON MQTT messages from a Tasmota sensor and nothing seems to work. Here is the message:
{"Time":"2021-09-18T11:43:28","MAX31865-0":{"Temperature":64.19,"Resistance":1069.72,"Error":0},"TempUnit":"F"}
I have tried:
value_template: "{{ value_json[['MAX31865-0'][0]['Temperature']] }}"
value_template: "{{ value_json.MAX31865-0.Temperature }}"
value_template: "{{ value_json['MAX31865-0'].Temperature }}"
I'm getting a value of Unknown
{% set data = {"Time":"2021-09-18T11:43:28","MAX31865-0":{"Temperature":64.19,"Resistance":1069.72,"Error":0},"TempUnit":"F"} %}
{{ data['MAX31865-0'].Temperature }}
-> 64.19
- platform: mqtt
name: "Wine Cellar Bottle Temperature"
state_topic: "tele/wine_cellar_2/Sensor"
unit_of_measurement: "Β°F"
value_template: "{{ value_json['MAX31865-0'].Temperature }}"
look in your logs for the error
I don't see any errors in the log. I see that it works in the template tool.
has the sensor gotten a new value?
I'm watching the sensor with MQTT.fx and its updating every 10 sec for debugging. I see an error:
Template variable warning: 'list object' has no attribute 'Temperature' when rendering ''
I don't understand what I posted wasn't correct. Is that a list of one item?
Your json does not have a list, yet the error claims it is a list
Tasmota supports (3) MAX81865 but there is only one connected.
I tried this with no change:
value_template: "{{ data['MAX31865-0'][0].Temperature }}"
well that won't work
data is just what I called the variable that I used for your data
sorry I accidently pasted from the template tool
- service: persistent_notification.create
data:
message: "{{ value_json }}"
add that to your action to see what it's actually getting
Pardon my noobiness but I am just defining sensors at this point. Can I add that to the sensor definition?
oh, sorry. then just use value_template: "{{ value_json }}"
HI everybody. I'm just struggling with this single-line-templatecondition:
- condition: "{{ state_attr('cover.bedroomshutter', 'current_position') < 9 }}"
it's producing the following error:
ERROR:homeassistant.config:Invalid config for [automation]: Unexpected value for condition: '{{ state_attr('cover.bedroomshutter', 'current_position') < 9 }}'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['condition'][1]. Got None. (See /home/homeassistant/.homeassistant/configuration.yaml, line 58).
Funny thing: The same in the "classic-format" is working:
- condition: template value_template: > {{ state_attr('cover.bedroomshutter', 'current_position') < 9 }}
How do I concatenate a character and MQTT value in YAML?
this is what I am trying to do:
unit_of_measurement: "Β°{{ value_json['MAX31865-0'].TempUnit }}"
that doesn't work?
it returns:
64.19 Β°{{ value_json['MAX31865-0'].TempUnit }}
oh, you can't have a dynamic unit_of_measurement
really?
I am still curious how I can combine the character and MQTT value together in YAML.
you can't generate a dynamic unit_of_measurement
what you're doing would probably work fine if you did it where it is allowed
where is it allowed?
many places
in service:, in a data: block, or wherever the docs say it is
unit_of_measurement string (optional)
Defines the units of measurement of the sensor, if any.
"string"
compare and contrast with:
value_template template (optional)
Defines a template to extract the value. Available variables: entity_id. The entity_id can be used to reference the entityβs attributes.
"template"
ok I have a lot of reading to do
I am trying to set up a MQTT automation trigger and I can't get it to trigger.
https://www.codepile.net/pile/e9jXxopb
Your quotes in the condition are broken
First, you have two sets of quotes surrounding the template and second you need to mix the quotes inside and outside
I tried using the visual editor and that what came out as YAML
like this?
value_template: "{{ trigger.payload == 'lockhouse' }}"
Yes
it still wont trigger
Follow the debugging tips in #automations-archived . Look at the trace
@inner mesa thank you
@grand merlin posted a code wall, it is moved here --> https://hastebin.com/sasevagipe
Hi! not sure that the right place for my post but I'm using node red for presence notificaiton (using this code)
https://hastebin.com/oxaruceqir.json
the screenshot attached to the notification don't work at all but that because of CloudFlare access I think...
anyway how can I add this to my template so when I click on the notification, I actually open another app (UniFi Protect)
actions:
https://hastebin.com/jiqukapuni.yaml
I tried this https://hastebin.com/duvigehone.json but that doesnt work
Ok so I don't think I can have both screenshot and link to a another app.... (the screenshot doesnt ever work anyway) so this seems to work https://hastebin.com/atobayixom.json
It's not, this channel is for templates. You'd want #integrations-archived
thanks
I have a template condition like this: ```condition:
- condition: template
value_template: '{{ trigger.json.key == ''goodvalue'' }}'``` is it possible to access the secrets.yaml? I want to have ''goodvalue'' be "!secret api_key" as it can be done in configuration.yaml
I found this hack - but I don't like it -> https://community.home-assistant.io/t/how-to-get-the-secret-value-into-template/270600/5
Does anyone know whether Home Assistant publishes the total number of devices for a given integration as an entity? Or do I need to create a template for that?
Specifically, I'd like to keep track of the total number of Zwave devices in my network.
You would need a template. This is the one I use:
- platform: template
sensors:
zwave_status:
value_template: "{{states|selectattr('entity_id', 'search', 'node_status')|selectattr('state', 'in', 'alive, asleep')|list|count}}/{{states|selectattr('entity_id', 'search', 'node_status')|list|count}}"
friendly_name: ZWave Node Status
Am I crazy or is there no way to create Templates via the UI?
Templates aren't a standalone thing. You use them in other things.
You wouldn't 'create a template' in the UI.
What are you trying to do?
Was just working on this actually. You can put a template in the markdown card in Lovelace.
The goal is to create an automation that tracks the total number of Zwave devices and send a notification when that value drops below a specific number.
What is it with everyone tagging on replies tonight?
@willow belfry When using Discord's Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
You have to change this every time (thank the Discord devs for that).
If you want to add a template to an automation, there's nothing stopping you doing that. You can enter templates via the automations UI.
π
this is really cool, been looking for a 'contains' filter since forever, and this comes really close. Not 100% clear on the workings though. eg using {{ expand('group.z_wave_switches')|selectattr('entity_id', 'match', '.freezer*') |map(attribute='entity_id')|list}} on a group that contains 2 switches with that phrase, the template returns [].
I seem to have to add the domain like selectattr('entity_id', 'match', 'switch.freezer*') to have it return those 2 switches. is that expected behavior?
Yes... match vs search.
it gets even stranger, with selectattr('entity_id', 'match', 'switch.f*') it lists all switches... including many that dont use the 'f' at all
Yes... because that's what you told it to find.
If you're going to use RegEx, learn how to use RegEx
βswitch.f*β matches switches that start with zero or more f characters
Thereβs general and understandable confusion between normal globbing and regex
and why would selectattr('entity_id', 'search', '.fre*') result in ```[
"switch.freezer_bijkeuken",
"switch.freezer_garage",
"switch.front_room"
]
because the search is looking for 0 or more e'? in this case 0...
Because you're telling it to find 'any character, followed by f, followed by r, followed by e zero or more times'
Put your pattern into regex101 and it'll break it down for you.
Ok, I see.
What youβre using * for requires β.*β
The funny thing about solving a problem with RegEx is that you now have two problems.
Try this as your search term for me?
^(.+)+$
yes, and they don't have t be concatenated, but have to be in that order?
Yes... you wrote it in that order.
it lists all entities
Seriously... if you want to use RegEx, learn RegEx. It's powerful but it's complicated... and there's no easy way to figure out what it does other than reading a proper guide.
You could give thousands of examples here and ask us what they do, and still be no better at it. You need to understand the syntax... which regex101 also teaches.
Once you know the syntax... it's easy to come up with patterns of your own.
Itβs great if you donβt care about Speed
There's this simple RegEx that tons of software uses:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Marius, itβs not something youβll learn quick
for my usage now, Ill use something like 'daystart' and its pretty unlikely it will find anything other than containing that phrase π
Even as a somewhat-capable developer, it took a long time for RegEx to 'click' for me.
Ya
Well, the prt that had to click was the reading the documentation and understanding it
Kinda happens in stages too:
- learn to read basic patterns
- learn to write basic patterns
- learn when to use those patterns instead of other programmatic approaches
- learn more complex patterns
- repeat
Those online testers are awesome for learning g it
Practise too, like doing RegEx crosswords π https://regexcrossword.com/
Boss: are you playing games again?
Me: nope, practising my RegEx skills.
i like/use it to auto create lists with entities, so I can use those in a group, by simply copying that, (since we can no longer do that in the dev states, because of the listed friendly names)
Tbh tho, Iβll still just Google crap that other people do then add/remove what I need
This is the way.
may I ask a final one before I go retreat an study all that... 'freez*power' in dev states returns all entities I need, but no matter what I try in the regex template, it returns an empty list..
again, "*" represents 0 or more of the previous character. Is that what you want?
0 or more z characters, in that case
And I'll repeat... use regex101 to figure it out.
Get your pattern right before you try applying it somewhere.
yes, I want it to find all entities with the words freezer and power, and anything in between those 2. But ill need to dig further to get the pattern right
And you'd know what to do if you bothered reading the guidance on regex101 and used it as a playground to test your pattern against potential matches.
I will, believe me. For now, I have found the replacement for my much desired 'contains' filter!
hello, has anyone got an example of a time arithmetic template? I'm looking to find the hours and minutes from current time to 12:30am.
so far i've got two lines, but I dont think they're compatible in this form
{{ as_timestamp(strptime("12:30", "%I:%M")) }}```
kinda a pain the ass because it cross the date boundary
either it will, or it won't, so you need to be careful
I could quite happily get whatever value it is to midnight and then add 30 mins
and if it's between midnight and 12:30...
then, i'll be in bed and wont look π
{{ now().replace(hour=23, minute=59, second=59) - now() }}
it's for a quick reference on a dashboard so i can set the dishwasher delay to be in the cheap energy window, which starts at 12:30am
I hate this, but it works:
{% set delta = now().replace(hour=23, minute=59, second=59) - now() %}
{% set hours = (delta.total_seconds()/3600)|float %}
{% set minutes = (hours % 1) * 60 %}
{{ hours|int ~ ":" ~ minutes|int }}
yes. I was hoping that I could just do delta.hour and delta.minute
as you can with a datetime, but can't with a timedelta
I hate this ever so slightly less:
{% set delta = ((now().replace(hour=23, minute=59, second=59) - now())|string).split(":") %}
{{ delta[0] ~ ":" ~ delta[1] }}
I don't see how
ok, i just thought it might be related π€·ββοΈ
{% set delta = (((now().replace(hour=0, minute=30, second=0) + timedelta(days=1 if not (0 <= now().hour < 1 and now().minute < 30) else 0)) - now())|string).split(':') %}
{{ delta[0] ~ ":" ~ delta[1] }}
that takes care of the day split
very good work! thank you!
{% set delta = ((now().replace(hour=0, minute=30, second=0) + timedelta(days=1 if now().strftime('%H:%M') > '00:30' else 0) - now())|string).split(':') %}
{{ "%s:%s"|format(delta[0], delta[1]) }}
not sure if it's getting better, or just different
This isn't even its final form.
{% set delta = ((now().replace(hour=0, minute=30, second=0) + timedelta(days=(now().strftime('%H:%M') <= '00:30')|int) - now())|string).split(':') %}
{{ "%s:%s"|format(delta[0], delta[1]) }}
too many parentheses
Hi!
I am just starting to explore templating in more detaild and had a syntax question for the folks here.
I have multiple template sensor lines in my config.yaml, and I am not sure if that is the most efficient way to write it.
The code is working.
- platform: template
sensors:
left_garage_status:- platform: template
sensors:
car_status:
- platform: template
The question is whether I include only one -platform: template and then nest the sensurs under that. Or perhaps one -platform: template and sensors, and then nest everything under that.
It doesnβt matter
If you wanted to simplify how would you?
Okay, meaning could I have one template and one sensor and nest everything under it?
Thank you!
e.g.:
- platform: template
sensors:
sensor#1 YAML.....
sensor#2 YAML.....
Okay, thank you.
Good morning i use the platform teleinfo and i would like to perform some calculations with the input data i did setup the lambda like this but βunavailableβ is not recognized somebody-may help me?
- platform: template
name: "Conso du jour HC Blue"
id: today_hc_blue_consumption
unit_of_measurement: "Wh"
icon: mdi:moon-waning-crescent
update_interval: 3600s
lambda: !lambda |-
if (id(edf_hcjb), unavailable) {unavailable;} else {return ( (id(edf_hcjb).state-id(yesterday_hc_blue_consumption).state) / 1000);}
Home Assistant has no lambda option. Are you talking about ESPHome? If so:
ESPHome is a system to control your ESP8266/ESP32, with a native integration for Home Assistant.
You can find their documentation here, and get help with ESPHome itself here in the #diy-archived channel (#integrations-archived for the Home Assistant side integration with it). They also have their own Discord server too.
Yes Esphome
Then there are better places to ask listed in that bot message.
I want to trigger a script only if two conditions are met. Something seems to be troubleseome here
script:
...
sequence:
- service: >
{% if is_state('binary_sensor.dark_inside', 'on') and is_state('light.lys_grunnbelysning', 'off') %}
script.lys_grunnbelysning_on
{% endif %}
Put it in a condtion instead of a service call
You will end up with an empty service call this way, if the conditions are not met, and that will give errors
I need to continue after this π
then use a choose:
Ah!
So if these two conditions ar met as one choose: statemennt and tha last (now a condition) as the second choose: , then?
- do something
- choose:
- conditions: "{{ is_state() and is_state() }}"
sequence:
- call service
- do something else```
sequence:
- choose:
- conditions: "{{ is_state('binary_sensor.dark_inside', 'on') and is_state('light.lys_grunnbelysning', 'off') }}"
sequence:
- service: script.lys_grunnebelysning_on
- service: whatever
``` but thomas was faster
but thomas was faster
I cheated
and thank you @marble jackal
Would end up like this, then ?
script:
someone_coming_home:
alias: '[House] - Someone coming home'
sequence:
- choose:
- conditions: "{{ is_state('binary_sensor.dark_inside', 'on') and is_state('light.lys_grunnbelysning', 'off') }}"
sequence:
- service: script.lys_grunnebelysning_on
- condition: template ## Continue only if one adult came home
value_template: "{{ is_state('person.pal', 'home') or is_state('person.eva', 'home') }}"
- service: script.adults_coming_home
Hassbot does not like it but I can't see anything wrong with it.
Hassbot never liked comments, I think. ```yaml
Perfectly valid yaml
a:
- 1
- 2
Or maybe it does.
What we see now is valid, what @silent barn reacted to was not, the post was edited.
Right. Good eye.
Trying to setup a quick light automation ahead of traveling to simulate presence. Was thinking of using the On_off schedule template but it needs a specific time, I'd like to specify "sunset" as the ON trigger and a specific time for the OFF. I assume this can be done in the YAML, can I use the sun.sun next_dusk: '2021-09-21T17:44:06.631221+00:00' attribute somehow?
Or just use the sunset trigger... but see #automations-archived for that.
im trying to implement a delay based on an input_number (in minutes) {{ states("input_number.minutes") | int }} the value is 35 delay: '{{ states("input_number.minutes") | multiply(60) | int }}' gives me 2100 - what is the coreect template i would beed to set the delay for minutes? multiply(1000) | multiply(60) correct?
{{ states("input_number.minutes") | int * 60 }}
thanks
Worked like a charm!
is this the correct format for an if statement to convert 1 and 2 to Source A and B? value_template: >- {% if is_state( (value | int) , '1') %} Source A {% else %} Source B {% endif %}
not like that - you're using value where an entity_id should be, converting the value to an int and then comparing with a string
it can be done more compactly like this:
value_template: "{{ 'Source A' if value == '1' else 'Source B' }}"
without knowing where value is coming from or what it's type is, of course
it's an SNMP sensor: ```sensor:
- platform: snmp
name: HomeLab ATS Selected Source
host: IP
community: public
baseoid: 1.3.6.1.4.1.318.1.1.8.5.1.2.0
value_template: "{{ 'Source A' if value == '1' else 'Source B' }}"
it's still unclear what type value will be
but you can try that, or use value_template: "{{ 'Source A' if value == 1 else 'Source B' }}" if it comes in as an int
ok. you have some examples
going to try it now
thanks, that worked
Hi all. Is it possible to manually fire off an event? Specifically, entering a zone? I want to test my templating for when someone enters the zone then it will pass trigger.id to condition and I want the condition to verify certain things for each user. I've tried changing the person's state from not_home to home or to the name of one of the zones, but no luck.
you can definitely do that from
-> States
"entering a zone" is no different from the state of a device_tracker changing to the name of a zone
Ok so to expand on that, what is the state it should be in?
what trigger are you using?
Oh, wait, the state should just be the zone, right?
State: wba
or state: burns
right?
if you're just changing the device_tracker yes
person.myname
but that depends on what trigger you're using for the zone triggering
Enters zone
please post it
hmm it wont let me upload as a file, I'll try pastebin or is a screen shot ok?
Can see if that works
well, your syntax is wrong for sure
{% if trigger.id == 'triggerjimbob' %}
but, to test those zone triggers, you need to force the state change on person
so set the device_tracker state to equal the zone friendly name
and that should propagate to your person
is_state( only gets an entities state. Trigger is not an entity
I'm getting repeat errors, that I don't understand. Does this mean the sensor doesn't have a state defined?
How do I do formatting again?
3 backticks
Logger: homeassistant.helpers.template
Source: helpers/template.py:1496
First occurred: September 20, 2021, 1:50:58 PM (2591 occurrences)
Last logged: 9:00:02 AM
Template variable error: 'state' is undefined when rendering '{{ state('sensor.power_home_123_1d')|float}}'
it's states() not state()
Thank you!
np
So I just need to change it to states?
- name: "Total Power Usage"
state_class: total_increasing
unit_of_measurement: kWh
device_class: energy
state: >
{{ state('sensor.power_home_123_1d')|float}}
yep
Awesome
although, what you're doing is pointless
Why is that?
because you aren't performing math on the state, so all you're doing is replicating the state into another entity
if you need to add or change attributes to your existing entity, use customization
Oh, I think I was doing that while my source entity wasn't updated to a total increasing yet.
but I think the latest update fixed that.
I'll delete the sensor. Thanks for the reminder.
Anyone have experience creating something to display power usage of something outside of the energy dashboard?
I want to see if it's worth running my miner based on power usage or not.
So I think I need to create two sensors then a third one to do the math for the total
one for off peak and one for peak
I said power usage, but I meant power cost.
I guess the part I don't understand is if it will store the data correctly
Hello there,
I have these two sensors where in the templates tab it shows them as I wish, that is, one per line.
If, however, later when I create the entity card it shows it to me immediately, do you know why it can be?
Hello all, its been a few years since ive been in the HA stuff.. had a good amount of stuff configured back in 18, then deployed, came home and my box was dead, and no backups, and decided just to go Hubitat, but now ive decided to come back.. anyhow I cant remember for the life of me how to create a binary sensor from my locks. Example I just want an entity card to show lock status but not interactive.
sensors:
front_door_status:
friendly_name: Front Door
icon_template: >
{% if is_state('lock.front_door','locked') %} mdi:door
{% else %} mdi:door-open
{% endif %}```
`{{ (states('sensor.unauto')) }}
{{ 'Linea' + ((states('sensor.unauto')).split('LΓnea')[1]) + 'Linea' + ((states('sensor.unauto')).split('LΓnea')[2]) }}`
and output is:
LΓnea L92 4 minutos
LΓnea L91 8 minutos
LΓnea L92 17 minutos
LΓnea L62 19 minutos
LΓnea L91 23 minutos
LΓnea L62 39 minutos
LΓnea L92 54 minutos
Linea L92 4 minutos
Linea L91 8 minutos
but the sensor then shows it to me in a row, without a line break
Line L92 3 minutes Line L91 6 minutes
How are the images inserted in discord?
imgur
whitespace carrage returns are removed from states
if you want to display that, use markdown card
ok, i will try it
just copy the same template that you have for the icon, but return on or off. Put it under the value_template field
Indeed it shows it well, but I imagine that here you can not put icons and others
thanks, now just to remember where i put it .lol
In value_template field. Look at the examples in the docs
oh yea I think i got that , I have to go digging to remember whereei put in my yamls..lol its been a while. but ill get it all sorted.
sensors:
front_door_status:
friendly_name: Front Door
value_template: >
{% if is_state('front_door_lock','on') %} ```
I was doing this on a blank Viscual code from as much memory as I could .
though these days the memory is shot
got it π
π There are a few things broken in there..
Anyone have a pointer as to why I'm getting TypeError: first argument must be string or compiled pattern when doing something like {% set inputs = states.input_boolean %} {% if inputs | list | count > 0 %} {{ inputs | map(attribute='entity_id')|join(',')}} {% endif %}
What does inputs evaluate to on the third line?
It should be the DomainStates for inputs_boolean, no?
As I'm uidnerstanding the templates, I saying give me all input_booleans as inputs. If there are more than 0 then map the entity_ids and join them with ,
The actual logic will be filtering down the input_booleans, but I was just trying super basic for testing.
I'm not asking what you think it does. I'm asking you what it actually does.
Find out what the output of inputs is on the third line.
my automation aint working... the trace shows Error: In 'template' condition: AttributeError: 'mappingproxy' object has no attribute 'lower' however i don't see where i call "lower":
- condition: template
value_template: >-
{{ is_state_attr(trigger.event.data.new_state.attributes, "icon",
"mdi:memory") }}```
for reference
- platform: event
event_type: state_changed
event_data:
entity_id: sensor.memory_use_percent
The first argument to is_state_attr is an entity_id
oh, ok so i should just access trigger.event.data.new_state.attributes directly?
Ah. Sorry, brain was in work teaching mode. It does return the DomainStates <template DomainStates('input_boolean')> which if I pipe to the mapattribute it returns the Generator.
if your goal is to get the icon attribute, then trigger.event.data.new_state.attributes.icon
ok, and i guess i need to guard against new_state then being None
if you want to do the same test, then just use trigger.event.data.entity_id as the first parameter
So everything seems like it should be fine. It's just....not when it's inside of the if. Outside it seems to work just fine. π€
add |list to something that returns a generator to see the elements
right but that would always be the new state, so i cant do that if i want to reference the old state?
so how would i do that with trigger.event.data.entity_id and is_state_attr?
that all seems overly complicated. why can't you just use a state trigger?
i was under the impression it wouldn't fire when only attributes change?
incorrect
ok, i was mislead by the docs then
it says it does in like the first paragraph of the docs
ah, misread that sentence
If only entity_id is given, the trigger will fire for all state changes, even if only state attributes change.****
right, i misread it as it wouldn't do it if only attribs change, silly brain
np, it's not intuitive
well, it certainly could do with a lot more consolidation of the docs and a lot more relevant examples
open source, so yeah i know π
that said, i must admit the new automation ui has improved massively since last time i fooled around, which is great
hi, I am trying to integrate a switch, and I think what I need is to make a template
the device has a URL to switch on, another to switch off, and a third URL to get the state, which retirns a small piece of html
I took a look at REST, but it seems to be all based on json
I just need a few pointers to get started
also, each board can have up to 6 switches, but I just want to get 1 working to start
maybe I dont even need a template I am not sure
the only variable really is the IP address, and the button number
there are other URLs for setting a timer and so on but I can add those in later
@inner mesa ok, that seems to work, cheers!
ideally I would jst enter the IP address and the automation would figure out the number of buttons
it also supports MQTT, so if that would be a better option, I could use that, though it seems a bit more complicated to get started with, but in future it might be the way to go
to set the state it is something like sending PUT to http://ip_address/avtion/button=1&state=1|0
1 or 0
and to read the state, something like send a GET to http://ip_addr/read?button=1
that would be enough to get me started
just not sure how to write that in a template
you don't use a template
ah OK
templates don't do anything - they manipulate data that already exists in the HA state machien
I see, so what would I use instead ?
something like this, perhaps: https://www.home-assistant.io/integrations/switch.command_line/
using curl
it is not
how is it a template?
the only mention of a template is interpreting the output of the status call
well OK, its a config script
templates aren't just "virtual things of any sort" - it's a technical term for Jinja
it's not a script either
but I dont want to have to edit the config file each time I add a new switch
that's your option
I just want to put in the ip address and give it a name
eh ?
cant I add something like a switch class ?
seems a very awkward way of doing things
there's no place in the UI to just put an IP address and have it behave you've described
what you're doing is a very custom thing
well to me it would make sense
normally, there would be an integration that would do the work and expose the switch
make a switch template with name and ip address as variables
that's just not the way HA works
have it show a UI where I can ipnuyt those values, and then the template would add it to the config
you can create a command line switch, as I linked
I mean that is how I would do it
an integration could certainly be written to do exactly that, it just doesn't exist
that I'm aware of, at least. it's not a native thing
well yes I am hoping to make a HACS integration from this
it would be fairly easy to do that
OK, I mean right now Iam just testing...proof of concept if you like
thanks...just getting started with this, its a bit hard to know where to start
so thanks for that
#devs_core-archived can answer questions
thanks a lot !
so for now I should just start with edit the config and put in the command line bits right ?
I thenk that will add the device automatically ?
after a restart ?
~check first
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
but yes, it will create a switch entity
OK, and then - sorry if it is abit off topic, but there was no example there to read a state back in teh commandline docs
ahh no
it has a check, value == 1
so what I need is actually something like a grep
that's what the state command line is for and the value_template
a template can do a regex search
and even that part is optional π
π
that isn't necessary any more, in the GUI, you can just go to Configuration / Server Controls and click on Check Configuration
that is incorrect
which just told me I shouldn't use Tabs in scripts
that's why the first sentence is this:
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
ah I see
sorry my eyesight isnt what it used to be
too many hours of staring at hi resolution monitros I guess
my typing skills are also on the decline....as you can see
shoddy keyboards are partly to blame for that, hard to find a decent one these days
yikes ! config check is failing
it's looking for /root/.homeassistant
which is non existent
the instructions are totally cryptic "If your container name is something other than homeassistant, change that part in the examples below."
I have no idea what the container name is, or even if it is running in a container
it says in Info "docker: true" so I guess it must be, no idea whatthe name is though
If you're using Docker, you named the container. Unless you're using something shitty like Portainer to do it for you.
Im using odroid