#templates-archived
1 messages · Page 103 of 1
Yes, I had that at one point, so as long as wed is anywhere it will trigger
in the description that is
I should have tried that, thank you!
that works for me even with a stray newline
lets see if it works
hum... still something is off...
{{ is_state('calendar.ouachita_hills_academy', 'on') and in_state_attr('calendar.ouachita_hills_academy','description', 'wed') }}
lol, that's not how that works 🙂
look at my example above
you seem to have made something up
a quick example that I just tested on my system: {{ 'Re' in state_attr('calendar.garbage_collection', 'message') }}
Could someone help me with a command_line ?, I need to pass the data from a dict / JSON to a template
@pale python posted a code wall, it is moved here --> https://paste.ubuntu.com/p/XBtwSS7PSy/
@pale python are you restarting? Also, why are you even creating the template sensor. They are 100% pointless, you can just place the booleans inside the group.
I know,...It's not the real case... I will modify and repost the code. Gimme some minutes
But the point is...why if I use an if-then-else template on sensor templates and I put them in a group, the group state is Unknown ?
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
because those aren't on/off home/not home states
it's not going to propagate states that groups can't be
groups just work on states groups understand
yes...thanks
I missed this
because those aren't on/off home/not home states
@mighty ledge
Hi! I've been looking around for ages, and trying to get this to work.. but i have had little to no success. (also noob here)
My custom sensor output only shows "true" or "false" but I managed to get the "raw" data by using {{states.sensor.kvbdep_245}}. This provides me with a dynamic list which auto updates with the next tram from the station. The data output is as follows:
<template state sensor.kvbdep_245=True; stationname=Subbelrather Strasse, departures=[{'line_id': 143, 'direction': 'Lövenich', 'wait_time': '0'}, {'line_id': 13, 'direction': 'Holweide', 'wait_time': '3'}.... etc
What I am trying to do, is get data from a sensor and present it in a sentence: "The next tram to Am Buzweilerhof will depart in [....] minutes.
Could anyone help me?
Where do you want to display it? In a card in lovelace ?
You can create a card with this template :
I want to display it as a state-lable over a picture elements card
The next tram to Am Buzweilerhof will depart in {{ states.sensor.kvbdep_245.attributes.departures[0].wait_time}} minutes.
That gets me in the right direction, but that only gives the time of the next departure, and not the specific tram
you want to display the line_id? or get the time of a specific line_id?
not sur I understand
if you want the wait_time of the line 143 for instance you could do something like (to be tested):
The next tram to Am Buzweilerhof will depart in {%- for i in states.sensor.kvbdep_245.attributes.departures -%} {%- if i.line_id == 143 -%} {{i.wait_time}} {%- endif -%} {%- endfor -%} minutes.
Îm looking for the time of a specific line_id, which would be the wait_time of the line.
@thorny snow
{% set desired_tram = 143 %}
{% set selected = state_attr('sensor.kvbdep_245', 'departures') | selectattr('line_id', 'eq', desired_tram) | list | first %}
The next tram to Am Buzweilerhof will depart in {{ selected.wait_time}} minutes.
or {{ (states.sensor.kvbdep_245.attributes.departures | selectattr('line_id', 'eq', 143)|first).wait_time }}
for safety you should probably use this instead:
{% set desired_tram = 143 %}
{% set selected = state_attr('sensor.kvbdep_245', 'departures') | selectattr('line_id', 'eq', desired_tram) | list %}
{% if selected | count == 1 %}
The next tram to Am Buzweilerhof will depart in {{ selected[0].wait_time }} minutes.
{% else %}
There is no tram.
{% endif %}
Thank you very much. @deft timber and @mighty ledge those both work flawlessly.
I am trying to format an email in HTML, and include state information in it. Is a template the best way to do this? I usually use Node Red but I haven't figured out how to make it happen there either. Does anyone have an example of how to do this?
That's my issue, I don't even know where to start 🤔
well, you need to figure out what/how you're going to send the email first.
Most integrations read emails, I can't think of any that send emails.
I was planning on sending it using a node in Node Red, I can format the HTML and send the email, but I can't figure out how to include the state information. So far I haven't been able to get any assistance in the Node Red channel so I thought I would look at doing it in yaml and templates
Well I just dug around a bit, and I see there is an smtp integration that will allow you to send them as 'notifications'
Either way, need to know the service to form the html and it'll need to be an automation
also, if you want to grab info from a sensor to put in HTML, just use the templates to grab data... I.e. {{ states('sensor.xxx') }}
Seems my Google-Fu failed me, thanks for pointing me in this direction. I'll give it a go ...
I'm trying to setup up an automation to alert me for each state of my alarm. This is what I have so far - and it works, but it says "Home Alarm as changed from disarmed to armed_away". I'd like to be able to "customize" the text - something like "Home Alarm has changed from disarmed to away"
alias: Alarm Test
trigger:
- platform: state
entity_id: alarm_control_panel.ring_alarm
action:
- service: notify.mobile_app_my_iphone
data:
data:
push:
message: Home Alarm changed from {{ trigger.from_state.state }} to {{ trigger.to_state.state }}!
title: Attention!```
Home Alarm changed from {{ trigger.from_state.state.replace('armed_','') }} to {{ trigger.to_state.state.replace('armed_','') }}!
thanks! is there any easy way to capitalize the letters? AWAY instead of away?
or even change words altogether?
Home Alarm changed from {{ trigger.from_state.state.replace('armed_','').upper() }} to {{ trigger.to_state.state.replace('armed_','').upper() }}!
that was fast, thanks! what about changing words altogether? Entry Delay instead of pending?
it'd be a more complex template but nothing too crazy. i wouldn't have time to make it until possibly sometime tonight though
if nothing else i'm sure someone else could chime in
oh, ok. no problem. Do you know of anything I could read up on to attempt? I was reading this, but I didn't see anything else complex. https://www.home-assistant.io/docs/automation/templating/
Home Alarm changed from {{ map.get(trigger.from_state.state, "UNKNOWN") to map.get(trigger.to_state.state, "UNKNOWN) }}!```
where the armed phrases are the raw states
where does {%- set map.... go in relation to the message?
like this: message: {%- set map = {"armed_phrase_one": "MY CHANGE 1", "armed_phrase_two": "MY CHANGE 2"} -%} Home Alarm changed from {{ map.get(trigger.from_state.state, "UNKNOWN") to map.get(trigger.to_state.state, "UNKNOWN) }}!
Yup
I keep getting missed comma between flow collection entries at line 340, column 17: line 340 is message: {%- set map.......
Oh. message: >-
Hey guys, I have just updated HA to 0.115 and as a result I am getting an error when starting up, indicating customizer cannot be loaded. I had installed customizer as AFAIK it was the only way to do template base global customization. Has anyone run into this?
@dreamy sinew haha! I just figured that out as you responded. Got it working, thanks!
This is showing as deprecated:
\ float < 75 %}\n cover.close_cover\n{% else %}\n timer.start\n{% endif %}"```
What did I miss?
You upgrade to 115?
So: - service: "{% if states('sensor.bathroom_humidity_sensor_humidity') |\ \ float < 75 %}\n cover.close_cover\n{% else %}\n timer.start\n{% endif %}"
Gotta keep the support folks busy with something. If it’s not telling people to add _template, it’s telling people to remove it 🙂
Yup
yeah that worked 😦
I'd consider making that a multiline template too @winged dirge
I prefer this style it's harder to read.
Not sure if this has been brought up:
now we can replace data_template with data, but if my template uses trigger (because this script is in an automation), the new way doesn't work.
HA'd complain:
jinja2.exceptions.UndefinedError: 'trigger' is undefined
Scoping problem. Script won't have access
@dreamy sinew No it's not a script, it's the action script of an automation, let me share a code snippet.
- alias: Occupancy Notifier
trigger:
- entity_id: input_boolean.X_present, input_boolean.Y_present
platform: state
action:
- service: notify.telegram_to_X
data_template:
message: "
{% if trigger.to_state.state == 'on' %}
🏡 {{ trigger.to_state.name }} is Home.
{% endif %}"
If I replace data_template with data, it won't work, HA'd complain:
jinja2.exceptions.UndefinedError: 'trigger' is undefined
And you have actually upgraded?
Yes, this works for me like a charm:
- alias: Garage Door Checker
trigger:
- minutes: /15
platform: time_pattern
condition: "{{ states.cover.opengarage_a80.state != 'closed' }}"
action:
service: notify.telegram_to_X
data:
message: Garage Door is {{states.cover.opengarage_a80.state|upper}}!!!
See I replaced data_template with data
I r seen someone else do that already and it worked. How are you testing this?
And you’re letting it trigger and not just hitting ‘execute’?
Okay, I hope it's my issue, let me dig a little.
@inner mesa dang it, you might be right
My bad guys, I'm glad it was my stupidity, not a common issue
Okay. You’ll need an else there, too, or it’ll complain. Or a condition before it
Okay. You’ll need an else there, too, or it’ll complain. Or a condition before it
@inner mesa I removed some details, my full code works
Thanks for the headup
Ok, np
@astral wren: an update on yesterday's issue converting a number of hours to formatted string:
value_template: >
{% if states("sensor.history_stats")| float > 24 %}
{{ states("sensor.history_stats")| round(0) }}:{{ (states("sensor.history_stats")|float - states("sensor.history_stats")| round(0)) | multiply(3600) | timestamp_custom("%M", false) }}
{% else %}
{{ states("sensor.history_stats") | float | multiply(3600) | timestamp_custom("%-H:%M", false) }}
{% endif %}
otherwise, if sensor.history_stats is 25, then timestamp_custom just shows the number of hours, which is 1 and you'd have to add %d to show a number of days (also 1) and if the sensor had a number of hours over a month, you'd have to add %m to see the number of months...
Do i need to remove these entity_idaslo? ```sensor:
- platform: template
sensors:
last_alexa:
entity_id:
- media_player.henning_s_echo
- media_player.henning_s_echo_show
- media_player.henning_s_echo_dot
value_template: >
{{ states.media_player | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}```
Hi! Yesterday I got some help with one of my sensors. We got it to work but now I need to integrate the "direction" of the tram into the variables. I got it to work in the template developer but the configuration check keeps throwing an error. I'm new at programming.. so help would be appreciated!
- platform: template sensors: kvb_buzweilerhof: friendly_name: "Departures to Am Buzweilerhof" value_template: > {% set desired_tram = 5 %} {% set selected = state_attr('sensor.kvbdep_245', 'departures') | selectattr('line_id', 'eq', desired_tram) | selectattr('direction', 'eq', 'Am Butzweilerhof') | list %} {% if selected[0].direction == "Am Butzweilerhof" %} The next tram to Am Buzweilerhof will depart in {{ selected[0].wait_time }} minutes. {% else %} no trams lol. {% endif %}
What's the error?
(I would replace if selected[0].direction == "Am Butzweilerhof" by {% if selected|length > 0 %}. I think that you will have an error evaluating selected[0] if the list is empty)
I'm not sure why it didn't catch the first time; but I now have it up and running!
Thanks again for your help @deft timber 🙂
Apologies as I'm not sure if this is the right place in the Discord to post this - I have a template sensor where the value template is:
value_template: >-
{{((as_timestamp(strptime(states('sensor.date'), '%d.%m.%Y'))-state_attr('input_datetime.softener_salt', 'timestamp')) /60/1440) | int}}
In Dev Tools > Template I'm currently getting 15 but the state of the template sensor itself is "# #15 15", what am I doing wrong?
Ignore me, I've just worked it out. I tried to comment out some old lines with # (to keep them in case recent changes broke) and they're being included in the output - I didn't realise it'd actually include the #
@obsidian cypress templates include all strings in between the code. The proper way to comment in a template is to wrap the line like this {# blah blah #}
@acoustic ridge the entity_id field is no longer needed in 0.115. Your template sensor will still work.
Thanks @mighty ledge! Makes sense ☺️
Hi, I'm using sensor.random_sensor in my automation, but it doesn't update that frequently. Like every 30 seconds. Can this be faster?
I access the value in a template with '{{states("sensor.random_sensor")}}'
Can you change the scan_interval?
This sensor evaluate properly in the template editor and worked until I updated to 115.0 yesterday. I can't find any breaking changes that would cause the state to be unknown now. Any ideas? corrected_voltage: unit_of_measurement: V value_template: "{{ (((state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean')) * 6) | float + ((states('sensor.realtime_solar_gen') | float - states('sensor.realtime_consumption') | float)* -1 / ((state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean')) * 6) | float) * 0.00378739327871000214178624973228) }} "
@karmic oar Cant find that in the docs. Don't think it is there for the random sensor
Your corrected_voltage, can't you break it down in the template editor?
It works in the template editor. No issues at all.
Are there any log entries which me help you?
None
So in the States, you find your sensor.corrected_voltage and it has a state unknown
@faint salmon all sensors on an interval accept the scan_interval field even if the docs don’t say it
@faint salmon all sensors on an interval accept the scan_interval field even if the docs don’t say it
@mighty ledge I'll give it a try
@mighty ledge You made my weekend a better one 😉 Thanks It worked!
Hey, folks. Since updating to 0.115, it doesn’t seem like any of my time or date-based template sensors are updating.
The new Template dev tool says they do not “listen for any state changed events and will not update automatically”.
Is this a known issue?
Ok, next question. I have a Xiaomi cube and I want to use it to change the brightness of a light by turning it. How do I get the value of the degrees in my automation action? I tried state_attr("trigger.event.data","relative_degrees") but that didn't work
"event_type": "zha_event", "data": { "device_ieee": "xx:xx:xx:xx:xx:xx:XX", "unique_id": "xx:xx:xx:xx:xx:xx:XX", "endpoint_id": 3, "cluster_id": 12, "command": "rotate_left", "args": { "relative_degrees": 91.25999450683594 }
So the zha_event is my trigger, that works fine, just how to get the degrees value is my issue
@sleek coral posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ZVt5XXsC4P/
aw it moved my whole message. sorry
I want the entity's attribute to be like
- key1: value1
key2: value2
...
- key1: value1
but it becomes a string, i.e. data: [{'key1': 'value1', 'key2': ...
@wet lodge Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Thanks again.
And FYI - I think the code wall tip was meant for someone else.
Nah, that was it helps if you share code 😉
Hard to diagnose problems with only it doesn't work and no context
(except in this case, where I'm guessing my guess was on target)
It was.
That has caught a lot of folks out
That doesn’t surprise me... As releases get bigger - and release notes with them - it gets easier and easier for smaller notes like this to get missed. And I suspect that’s a common function that a lot of people use.
Yeah, when we notice we steer folks towards the date/time sensor for that kind of thing, but it's a pain to use that way
Just did a search. I have it in 40 places in my config.
🤦♂️
115 exposes timedelta() now
Is this the reason why I get 'the entity_id option is deprecated, please remove it from your configuration'? And how do I fix it if so? https://pastebin.com/0w8yrJZm
It's in the breaking changes of 115
Yeah, that's what I read. But I don't understand how to remove/fix it 🙂
There is a link in the breaking changes that gives you options https://www.home-assistant.io/integrations/binary_sensor.template/#working-without-entities
Hmm... too complicated 🙂
🤷 that's the way it is now
Got the template I linked from a package. Don't understand how it works so it's especially hard to rewrite it.
Remove the entity_id line and make an automation that updates the entity state based on time_pattern
I don't have to touch the lines like this one |rejectattr('entity_id','in',state_attr('group.ignored_entities', 'entity_id')) ?
no, you don't change the template at all
Well that certainly helps
So basically remove the entity_id: sensor.time line and add an automation like this? ``` trigger:
- platform: time_pattern
minutes: '1'
condition: []
action: - service: homeassistant.update_entity
data: {}
entity_id: sensor.utilgjengelige_entiteter```
minutes: '/1'
What's the difference? I made it in the UI.
# Matches every hour at 5 minutes past whole
minutes: 5
# You can also match on interval. This will match every 5 minutes
minutes: "/5"
(to save you from having to read the docs 😛 )
That template iterates all states. You don’t need anything to update it. You can just remove the entity id field.
Nice. Thanks.
Then I guess I don't need the - platform: time_date in configuration.yaml anymore either.
hello, i need some help. the RF bridge is passing a code to an mqtt. The code is in a json message. I need to extract that code and if it matches with the code that i'm "looking for" i would make some action. The problem is that i don't understand how MQTT Trigger will know to compare the message and the "payload" that i'm expecting
Here i only see that it has payload option https://www.home-assistant.io/docs/automation/trigger/#mqtt-trigger
sshould i use value_template and compare it somehow?
https://www.home-assistant.io/docs/automation/templating/#mqtt, but you still haven't provided anything about that JSON you keep referring to
@arctic sorrel here it is: {"Time":"2020-09-18T18:29:03","RfReceived":{"Sync":9900,"Low":320,"High":960,"Data":"213AA2","RfKey":"None"}}
@fading plank Generally, don't tag people to ask for help - it comes across as bad manners, you’re demanding somebody answers you. It’s different if you’re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please don’t DM (direct message) people asking for help. It also comes across as demanding, and means that others can’t learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).
obviously i need the Data
value_template: "{{ value_json.RfReceived.Data }}"
aaa, so it's possible to make direct comparison
aaa
if you only said that before man 😦
Well, if only you'd actually answered the question I kept asking
:(:(
We're good here, but we can't read minds
Be easy on me
Please, give me your "buy me a coffe" link
It's on my GitHub, but don't feel you need to
Despite my grumpy nature, I'm here to help
Hey all
i have problems using float it gives me error i didnt have last days in the "template training developper tool"
i was wondering if i'm missing something or if it's related to updates
do you have same kind of problems ?
yes indeed
Today is the day for I have a thing that doesn't work
What are you doing, what do you get, what do you expect?
my question was do you have guys general problems due to update, but i'll come with more precise question 🙂
Then, no
well, i'm creating a sensor who gives a medium value from 3 other sensors, it's working, but i don't get de round() to work, the result still have lot of decimals
medium_temperature:
friendly_name: 'medium of temperatures'
value_template: >-
{{ (float(states.sensor.thermohygro5_temperature.state) + float(states.sensor.thermohygro4_temperature_2.state) + float(states.sensor.thermohygro3_temperature.state)) / 3 | round(1) }}
this is the result in the developper tool :
medium_temperature:
friendly_name: 'medium of temperatures'
value_template: >-
27.933333333333334
question : what is the correct syntax to have a 1 decimal number as result ?
Your template is only rounding that 3
BODMAS 😉
You need more parens
i did my best
Your best was good 👏
i don't know if you realise the time you all save me every time i'm stuck with my own ignorance 😍
well it's a lot
at least 7 probably
and it's kind of magic because sometime i just write the question and find the answer before anyone answers

The best way to learn something is to explain it to someone else, and the best way to solve a problem is often to write it out 🙂
So in the States, you find your
sensor.corrected_voltageand it has a stateunknown
@faint salmon Yes! I don't know why.
i'm having trouble with Template Light's set_color method. I am trying {{ h }}, {{ s }} but they are both None when it fires. the samples do not work for me even, any tips? 🙂
@karmic oar I really think you need to start from the beginning. Start small, check the state and you might know when it breaks. But I agree the syntax is good.
Figured it out (#templates-archived message) It's trigger.event.data.args.relative_degrees
I have updated to 115 version, but have now templates error, some of them: https://pastebin.com/iHz4a0Sa and my template: https://pastebin.com/1b9r01NJ , I am bad and templates and not understand what should I change?
Looks like you are using attributes that do not exist. Could you check in the State tab the attributes of stikalo_moja_soba for instance?
@deft timber thank you, have restarted 2 times and it is ok now😳
This is a bit of a niche use-case but can I somehow check if a jinja2 helper exists?
How would I parse a response like tele/zfbridge/SENSOR {"ZbReceived":{"0xFA4C":{"Device":"0xFA4C","Name":"Osseliecht","Power":0,"Endpoint":1,"LinkQuality":55}}} ? value_template: "{{ value_json['ZbReceived']['0xFA4C']['Power'] }} " doesnt seem to work to parse the state
sorry if this is the wrong channel 🤔
Hi can anyone please help with the following error invalid config for [script]: invalid template (TemplateSyntaxError: expected token ',', got 'volume_level') for dictionary value
Invalid config for [script]: invalid template (TemplateSyntaxError: expected token ',', got 'volume_level') for dictionary value @ data['script']['1589123276952']['sequence'][0]['data']. Got OrderedDict([('entity_id', 'var.alexa_living_room_volume'), ('value_template', "{{state_attr('media_player.living_show, 'volume_level')|float}}")]). (See /config/configuration.yaml, line 87).
The config was fine until updated to latest version
'media_player.living_show -> 'media_player.living_show'
@rugged laurel Thank you I've found and corrected it now, for some reason the config check never showed the error nor did i get a script error in notifications until this version
I try a sensor which is displaying the remaining days to a calendar event. But my if-else isn't working with my day calculating. When I set the bday parameter to 0 or 1 it is working. Someone knows where my problem in my "remaining day calculating" is?
{% set bday = (( as_timestamp(state_attr('calendar.contacts', 'start_time')) - as_timestamp(now()) ) / (3600*24) ) | round(0, "ceil") %}
{% if bday == "1"%} if
{% elif bday == "0"%} dummy
{% else %} else
{% endif%}{{bday}}
hi everyone I have this error
WARNING (MainThread) [homeassistant.components.template.sensor] The 'entity_id' option is deprecated, please remove it from your configuration
- platform: template sensors: simple_date: friendly_name: "Data" entity_id: sensor.time value_template: "{{ as_timestamp(now()) | timestamp_custom('%d/%m/%Y') }}"
I deleted entity id but now the time is no longer updated how can I solve?
@random wing posted a code wall, it is moved here --> https://paste.ubuntu.com/p/s2sDNxZ8s8/
@random wing Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
nobody?
nobody?
@south monolith it got deleted by the HassBot
https://paste.ubuntu.com/p/ytvpCdBQC4/ Look here
@south monolith it got deleted by the HassBot
https://paste.ubuntu.com/p/ytvpCdBQC4/ Look here
@random wingit works thanks!
Is someone able to take a quick look at my templating for my input_boolean? I just want to disable the ability to toggle the input boolean's state is 'on'
https://pastebin.com/QLsj4zgw
What happens is that I'm unable to toggle it even if it's state is set to 'off'
that's not the right template format for the custom button card
Ah okay, I see now... I need to create a separate template for this button and then add it in. Thank you!
np. basically, it uses javascript and [[[ ]]]
It seems like I need to add it into my ui-lovelace.yaml/raw config? That seems like an odd place to me, but oh well lol
it's no different from what you were doing before when adding the wrong kind of template
just use the right format
True true. Yeah, it was pretty simple to add
Sweet, it worked! Though, and this is just personal preference, but I wish it didn't ONLY work with javascript for the templating. Seems like this could be more difficult for others. But it does work great!
my output is to long.
Might know how I can limit the number of sings to 254 ?
! truncate
string[0:254]
or string[:254]
Hey pros, any idea why my template is returning the state: "unknown".
I was working fine before.
temp_living:
value_template: '{{ ((float(states.sensor.temperature_living.state)) - (float(states.sensor.outside_temperature.state))) | round(2) }}'
Both sensors are returning the correct states
works for me for my sensors
did you try it in
-> Templates?
it's not really best practice, though. (states('sensor.temperature_living')|float - states('sensor.outside_temperature')|float)|round(2) would be more conventional
@inner mesa I'm getting this error: https://imgur.com/a/05yF2t9
please no partial images of text
looks like you missed a paren or something
I could have, too. But this works fine for me:
{{ (states('sensor.wirelesstag_refrigerator_temperature')|float - states('sensor.wirelesstag_master_bedroom_temperature')|float) | round(2) }}
as a value_template:?
in
-> Templates. But no reason why it wouldn't work in a template sensor
did you try it in
-> Templates?
Haven't used it before, I'll try
It's giving me 0.0 there, and it should be around -6 now
then your sensors aren't giving you what you thought
or you're using the wrong names, or soemthing
anyway, get it working there
I have my first sensor on 23.7 and my other one on 16.1. Triple checked the names and states.
🤷
negative value = unknown?
does it say "unknown" in
-> Templates?
get it working there
check each sensor there
@inner mesa thanks alot for sticking with me but no success: If you want to check out these 3 screenshots. Something doesn't add up
https://imgur.com/a/rNmqYRT
nevermind
it works now
had a .sensor too much after correcting everything 🙂
thanks alot
I was about to ask what was wrong there
So after 2 server restarts, sensor.temp_living still returns unknown. (While it works in
-> Templates)
temp_living:
value_template: "{{ (states('sensor.temperature_living')|float - states('sensor.outside_temperature')|float) | round(2) }}"
Is the entity ID right?
Just try
{{ states('sensor.temperature_living') }}
``` (and similar for the other entity)
what's the rest of that sensor definition?
Yea, I've done this in the screenshots a bit higher. But it seems to be working now. 5 minutes after home assistant being back up completely
Does it need time to update? I thought it was realtime
I guess so. thanks alot though!
np. you can give them a default if you want them not to be "unknown" at first, or if they're from MQTT (for instance), you can retain the values
I'll check it out. Thanks.
hello :)
I don't know if i should post here or in integration, but i am having issue with the light.template integration
https://www.home-assistant.io/integrations/light.template/ seam to give jinja var like {{ brightness }} and {{ h }} to use in the service, but i can't make it work. i always get python error like voluptuous.error.MultipleInvalid: expected int for dictionary value @ data['brightness']
Does someone have a working exemple ?
https://paste.ubuntu.com/p/QNprWPpvnM/
hi... is there a way to reference the previous value of a sensor in a template?
previous as in back in time, or the value before the automation was triggerd ?
back in time.
ah, i was hoping trigger.from_state.state would be enought ....
usecase; i'm trying to make a sensor that extracts the forecast of tomorrom from met.no, but i want to reference the 'old' version of it - so that i basically get today's forcast
i don't think there is something from the loger, but i know you can query data from the influxdb recorder, but to what extend ...
I guess i could make an automation that triggers when met.no forecast changes and then store the from_state.state?
i don't know met.no, but the weather integration i use will provide me with more data that i get in the state...
so it would work, but you may be limited
which one are you using?
😉
@sinful bison I don't see brightness defined for line 20, you look to have it as level_template on line 5
thank's @brisk temple, my issue was that i didnt .. use ... data_template ...
and i am ashame of it
brightness was provided by the integration itself
i won't upgrade for now, waiting for some bugfix first and then removing /merging some of my custom component
@sinful bison are you in 0.115? If not, you need to use data_template instead of data.
yea i know, but i copy pasted from the doc, without thinking, and i forgot about it
thank's
good day everyone
i am trying to use the new timedelta() function in an automation
can somebody help me with that?
I'm an idiot with git, but it doesn't look like that PR (adding timedelta) has been released yet and I don't see it in the release notes or docs
:))
documentation seems to be a bit of an improvement area everywhere IT guys are working 🙂
it's in dev, so presumably will make it to 0.116
there's still a way to do what you want, it's just more complicated. do a search on the forum
that is what I spend my afternoon on 🙂
it's not too hard. this provides a timestamp of one minute ago: {{ (now().timestamp() - 60)|timestamp_local }}
for time: doesn't work
time: '{{ now().strftime(''%H:%M:%S'') }}' that was your input which works great
so actually the target is to have an automation that if Time 1 is change, set Time 2 to Time 1 - Variable
hello everyone what am I wrong in your opinion? it does not return any value to me
- platform: time_date display_options: - 'time_date'
- platform: template sensors: custom_date_time_ita: friendly_name: "Ora e Data" icon_template: mdi:calendar-clock value_template: "{{ as_timestamp(states('sensor.time_date')) | timestamp_custom('%H:%M, %d-%m-%Y', true) }}"
the problem are in a template
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
you need to use sensor.date_time_iso and have configured that in the time_date platform
or reformat the time/date string
you need to use
sensor.date_time_isoand have configured that in thetime_dateplatform
@inner mesa it's working thanks!
I've got a sensor that, seemingly randomly, becomes "unknown" and then stays that way for an indefinite period of time. Template evaluates perfectly in the template editor. corrected_voltage: unit_of_measurement: V value_template: "{{ ((state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean')) * 6) + (((states('sensor.pwr_avail')|float|abs) / (state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean') * 6)) * 0.00378739327871000214178624973228) | round(2) }}"
got a lot of potential string math going on in there
gotta |float any states() or state_attr() calls
looks like you got your parens right for order of operation enforcement though
Again, works great.
Always has... and the template editor shows it evaluating properly. 115 installed and suddenly it's unknown for random periods of time
Though I do see this
@karmic oar posted a code wall, it is moved here --> https://paste.ubuntu.com/p/TbypD8kzgW/
there's potential divide by 0 issues if some of those aren't available
yep, that's another potential result
Hmm... I suppose that could be an issue, but they'd be 0 during a reboot only momentarily and I've been running this for probably 9 months now
cast them all to float and they'll eval to 0.0 when they come back as None
just have to be careful with your divide
chances are those are failing too but it bails at the first issue
I think I used to have them as floats. Just changed it yesterday trying to fix this. I'll go add it back in real quick
Well now that I've done that it's upset about there being a zero
I see where this is going with being able to reload templates without rebooting, but something has changed to a point where my templates aren't working now
your template as written can't handle missing sensors/attributes
you've been lucky so far that the problem didn't manifest, but now it does
Well, I designed it that way.
so now you gotta fix it ¯_(ツ)_/¯
I had some issues arise when something dropped offline or didn't report
So I wrote the templates in a way that allow HA to continue and pick back up when it was good again
yep, and things changed in the backend and the solution you have will no-longer work
divide by 0 is a show stopper
going to need to re-write this to bail safely
1 step forward, 2 steps back
{% if base > 0 %}
{{ ((base + (states('sensor.pwr_avail')|float|abs) / base) * 0.00378739327871000214178624973228) | round(2) }}
{% else %}
{{ "Unknown" }}
{% endif %}```
And here I thught my yaml was finally going to shrink
question. my automation has the user_id in the event data. I want to turn that back into the username of the person. is there a template way to do that?
i don't think so. you would need to make your own map and access that way
i figured it out. it's a bit groody, but it works
p.attributes.user_id==trigger.event.context.user_id
%}{{p.attributes.friendly_name }}{%endfor%}
thats a smart template @warm needle !
{{person.attributes.friendly_name }}```
for the cross post
still grody but no loop
had to split because it didn't like dot-walking or .get() or even |attr() to get down to friendly_name after |first
I'm using the custom flex-table-card in order to show some json data (from a RESTful sensor) as a table and that works great. I also have some sensor-data/manual data I want to put into a custom template sensor and present as a table, but is there a way to store the attributes in a similar pattern as the restful sensor does? If I inspect the attribute values I see nested YAML(?), but when I make a custom template sensor I see the data as an array or list and flex-table-card doesn't seem to accept that :/
hm.. seems like going python is the only solution, seemed to work
hey, I'm not sure if I'm missing something. Is it possible to use templates in the automation trigger for: / minutes: field? Everything I've tried so far returns a syntax error.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Here are the details: https://paste.ubuntu.com/p/93gWTwFcj6/
based on the documentation, I'm going to try it without the hours/minutes/seconds being broken up as the ui editor does.
Wrap the template in double quotes
I'm trying to convert b to Mb in a template. I've got "{{ states('sensor.arris_sbg10_router_b_sent') | (float / 10**6) | round(1) }}" If I don't put the float in () it doesn't round, but if I do, I get an error "expected token 'name', got '(') for dictionary value"
.share the full thing please
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Hi all, I am using a value_template in a sensor, and I am getting the error : TypeError: unsupported operand type(s) for -: 'str' and 'str'
The operands are decimal values . When I do the template, I did not specify the data type as it wasn't needed prior to .115.. Does .115 now require them to be defined specifically now?
no changes there that I'm aware of. states are always strings, and need to be converted/filtered to numbers (int/float) if you want to compare them (</>/etc.) or perform math operations on them
it's possible that it's just calling out more existing issues, but it's likely that it wasn't working properly before
but I'm just guessing without the actual template
here is what i have currently, that was working....
value_template: "{{ state_attr('sensor.statswdaccx', 'max_value') - state_attr('sensor.statswdaccx', 'min_value') }}"
do i then need to convert it to this:
value_template: "{{ state_attr('sensor.statswdaccx', 'max_value')|float - state_attr('sensor.statswdaccx', 'min_value')|float }}"
just making sure i have the right syntax
yes, that should work. try it in
-> Templates
HI, after upgrade to 0.115 (now 0.115.2) entity_id is deprecated in templates. I have 1 sensor which calculate days from specific date, but it does not work anymore. Should I use again entity_id: sensor.time or do automation to call update entity ?
- platform: template
sensors:
left?:
value_template: "{{ (( as_timestamp(now()) - as_timestamp(strptime('29.8.2020 13:30', '%d.%m.%Y %H:%M')) ) / 86400 ) | int }}"
# entity_id: sensor.time
icon_template: "mdi:timer-outline"
unit_of_measurement: "Days"
no, because using entity_id is deprecated
I believe you can use states('sensor.date_time_iso') in place of now()
assuming that you set that up in the time_date integration
please explain "assuming that you set that up in the time_date integration" . It is configured in sensors/date_template.yaml file
I can't see such a time_date integration in config panel
yes, I have this integration enabled and configured manually,
if you have sensor.time, you probably already did
ok, I'll try to change now()
so, if you have - 'date_time_iso' there, then use that as I described
try it in
-> States and make sure that it gives you the right answer
yes, it is working, Should I replace now() in automations too or it does not matter ?
Hi All - I'm coming up to speed on all the capabilities and options of automations/scripts et al. I just discovered the "choice" entry allowing me to combine several conditions into one automation. My task at hand is a 4 rocker-button X10 (yeah, X10 - but the wireless stuff is not bad!) which transmits (eg.) A1 ON/OFF for top button, A2 ON/OFF for next button etc. I've installed the w800rf32 integration and it appears to be working fine.
So now I want to deal with those buttons in one automation - at first it seemed i had to create an automation for each button and each state (rocker on/off).
Choose seems to help with that - a choice for each button - but it seems I still need to create a condition for ON and a condition for OFF. Is there not a way to simple pass the state of the "trigger" to the thing I want to control?
i.e someone presses A1 ON. I would want to just pass whatever A1 stste just changed to to the light etc that I want to control.
Am I missing a point here?
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
There's the docs to have a read through
You can do things like:
- service: >
{% if trigger.to_state.state == 'ON' %}
switch.turn_on
{% else %}
switch.turn_off
{% endif %}
There's much shorter ways of doing that, but longhand is a good starting point
Been reading those. I must have missed where I can pass automation trigger info to a template
First link above
Also, HA is case sensitive, ON and on and On are three different things
sigh. How do you jnow which your particular device/entity needs? Look at logs?
Well, to know the state of any entity, look at
-> States
That's your truth table for HA
got it.
For what service that's linked to the domain, such as switch
I am using a template as an automation trigger which should only trigger when one temperature sensor is above the other one but unfortunately it also triggers a lot of times when it shouldn't. does anyone have any idea what could be wrong?
{{ states('sensor.studiobrick_temperature')|int > states('sensor.gym_temperature')|int }}
Thanks, I see what's the problem. Guess I have to exclude values 0 in my template then. any idea how to do that?
Oh I think just using values 0 as a condition in the automation will work!
I’m trying to convert an input number into an automation I’m doing. There are two ways that I can see going about it, first is to have the input number and then create a template sensor that multiplies the value of it by 60 so that I can reference the number of seconds in the automation...
My other idea is to have the time formatted version using a template of the input number, however I’m having an issue.
{{"00:0" + states('input_number.hallway_timer') + ":00"}} becomes 00:02.0:00 due to the input number having a decimal place. I want to pipe the input number to an integer but I get an error in the dev tools template section when trying this {{"00:0" + states('input_number.hallway_timer') |int + ":00"}}
Any suggestions?
{{ "00:{}:00”.format(states('input_number.hallway_timer')) }}
{{ "00:{}:00”.format(states('input_number.hallway_timer')) }}
@dreamy sinew I wasn’t aware of that formatting method, so thank you! To get the input number to an integer I slightly changed your answer, but wouldn’t have got there without you!
{{ "00:{}:00”.format(states('input_number.hallway_timer')|int) }}
Since you're making it an integer I think you can add 0 padding
Just too much if a pain to type out on mobile
That’s cool dude, thank you! I need to read up on my Jinja as there’s clearly a lot more to it!
Hi, just looking for some help with a template for my RF blind. I control this with a Broadlink RM Pro and since HA V115 it stopped working. This is code I think is correct but it still isn't working. Any help would be a appreciated please.
Might be better off in #integrations-archived I think. No jinja logic there
What is the best way to get the next occurrence of a certain appointment in a calendar?
Does anyone know if I can can use <= for smaller than or equal to with home assistant templating?
Yes
great, thanks
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
How can i change the Output from "2020-09-20T13:27:09.681681+00:00" to a Timer?
is that the finish time?
Yes
and where is it coming from?
This is a sensor for my washing machine over the Home Connect integrations
create a time_date sensor and then create a template sensor that evals the two
OK, i will give this a shot. Thanks
I created the date_time sensor, but i cant figure out how to evals the two sensors
I'm trying to implement a control for my innovelli led bar. The switch is expecting the brightness value to be one of 0%, 10%, 20% etc. I cannot see a way to accomplish this using the default MQTT light schema outlined here https://www.home-assistant.io/integrations/light.mqtt/#default-schema.
I have this working using the template schema, but I cannot implement the RGB portion using that schema because it doesn't support RGB commands on a separate topic.
Any help would be greatly appreciated!~
is it not zwave?
yeah i'm using zwave2mqtt
okay thanks
so are you suggesting that it's not possible to do what i want currently?
i could look into submitting a pr to add functionality to the mqtt templating if that's the case
i have no idea, i don't have that device nor do i use that integration
i'm just talking about the mqtt light templatnig
but, since you're using zwave, you really should consider the ozw integration as it is much more likely to handle this properly
i have everything setup with zwave2mqtt because i'm using a pi in the middle of my house
it seems like zwave2mqtt is doing something funky with that device
ozw supports that flow
is there a way to set a variable while inside a for loop?
I don’t think so...
for example ``` {%- set found=false -%}
{%- for value in textList -%}
{%- if key in value -%}
{%- set found= true -%}
It won’t work that way
Yeah.. is there a way to find out if my value has ever been found?
I am trying to get it to print false if the key value was never found in the list. Then print the keyCode if it is found in the list and is valid and then print invalid if it is not a valid keyCode..
I know I am shoving a lot in to that variable..
I have most of it working just cant get it to print out false if nothing is found.
{%- for value in description -%}
{%- if search in value-%}
{%- set code = (value.split(":", 2))[1] -%}
{%- set code = (code | regex_replace("[^0-9]*", "")) -%}
{%- if (code | length < 4) or (code | length > 8) -%}
Invalid
{%- else -%}
{%- for number in code -%}
{{number}}
{%- endfor -%}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
I need something at the end of the for loop that could tell me if I have ever found a key code.
search = "K:"
Why not simply {% if search in description %} ? Is the for really needed ?
ah ok, forget my question
well that might work. If i did that first.
need to do namespacing
With macro ?
`{% macro isInList(search) %}
{%- set description = ['Jeff', 'K:34333'] -%}
{%- for value in description -%}
{%- if search in value-%}
{{ true }}
{%- endif -%}
{%- endfor -%}
{%endmacro%}
{% if isInList("K:") %}
found it
{%else%}
did not found it
{%endif%}`
{% set ns = namespace(found=false) %}
{% for v in temp if "foo" in v %}
{{v}}
{% set ns.found=True %}
{% endfor %}
{{ ns.found }}```
looks like the for ... if ... would be useful to you too
might need to share the full thing though. where is search coming from?
from the macro parameter, it appears. but since you can't have global scope, that's not very useful
I dont think it is the prettiest but I got it to work.
@void steeple posted a code wall, it is moved here --> https://paste.ubuntu.com/p/bmWtbf9t8Q/
I am trying to take keycodes out of a google calendar so that I can send it to the zwave lock when the event starts and then remove it from the zwave lock when the event ends.
I am trying to automate my vacation property 🙂
This way all I have to do is create a new event in the google calendar where I set K:923923 in the description and it will extract it.
ok, you can slim it a bit by doing {% for value in description if search in value %}
looks like you're doing that lookup twice though?
I am which I know is not the most efficient but I had to do that because it is the limitation of Jinja
i don't think that would be the result of a limitation
oh, you're using that to set false
use the namespace example from above
Does namespace make it a global variable?
definitely available to anything in the macro, haven't tested beyond that
might be truly global
(to the scope of the template)
I think the reason why you can not set variables inside of a for loop is because it is rolling back the memory heap
no, its namespacing
anything inside the loop is scoped to the loop
all {% set %} commands are limited to the scope of the loop
Right that make sense. I was trying to do something like a set found = true if the key code was actually found in the loop.
I will try it with the namespace
yep, so define that namespace and you can then set ns.your_var = <whatever>
that would improve the BigO of the macro.
probably don't need the macro at all at that point
it isn't hurting anything though
right, you're defining a macro to call exactly once 🙂
That seems to work as well. Thank you for your help.
{%- set ns = namespace(found=false) %}
{%- for value in description if 'K:' in value -%}
{%- set ns.found = true -%}
{%- set code = (value.split(":", 2))[1] -%}
{%- set code = (code | regex_replace("[^0-9]*", "")) -%}
{{ code if 4 < code | length < 8 else "Invalid }}
{%- endfor -%}
{{ false if not ns.found }}```
one more reduction
that is much cleaner then what I had written thanks!
you could combine those 2 code sets but splitting into 2 lines makes each line not as long so i can appreciate that
give it a shot to see if it works. i don't have the input data so i can't be sure
I ran it through all of the test inputs and it worked well..
Thank you again. Its interesting to see how much more simplistic it can be.
pretty complex but easy to read.
Name-spacing, filtered for loop, and in-line if statements
also "between" comparisons
you might want <= for both of those
if 4 and 8 are valid numbers
oh, bonus, this protects against unknown
This is from a script that requires input data brightness, to_state, color_temp and transition.
- service: "{{ 'light.turn_' + to_state }}"
data: >-
{% if to_state == "on" %}
brightness: "{{ brightness }}"
color_temp: "{{ color_temp }}"
{% fi %}
transition: "{{ transition }}"
entity_id: light.outside_bathroom
I can't get it to work and get this error.
Invalid config for [script]: expected dict for dictionary value @ data['script']['hallway_bedroom_to_livingroom']['sequence'][0]['choose'][0]['sequence'][0]['data']. Got '{% if to_state == "on" %}\n brightness: "{{ brightness }}"\n color_temp: "{{ color_temp }}"\n{% fi %} transition: "{{ transition }}" entity_id: light.outside_bathroom' expected dict for dictionary value @ data['script']['hallway_bedroom_to_livingroom']['sequence'][0]['default'][0]['data']. Got '{% if to_state == "on" %}\n brightness: "{{ brightness }}"\n color_temp: "{{ color_temp }}"\n{% fi %} transition: "{{ transition }}" entity_id: light.hallway'. (See /config/configuration.yaml, line 42).
it's hard to tell from that unformatted mess 🙂
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
to start, the service is light.turn_on, and your template will produce something like light.turnon if you're just passing in on
<keep trying 🙂 >)
{% fi %} should be {% endif %}
recommend consulting templating docs
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
@inner mesa discord messed it up. Better in paste link above. endif is a good lead 🙂 I'm testing now
you may not be able to group two tags together within a single template as you've done with "brightness" and "color_temp"
dunno
ok :/ What the heck ? 🙂
"entrence" is spelled wrong, but maybe?
and if you're just doing the same thing to a bunch of entities, you can just list them like this:
"entrence" is spelled wrong, but maybe?
@inner mesa it's by design 😉
fix_scene_states:
# mode: parallel
sequence:
- entity_id:
- script.fix_fr_scene
- script.fix_mbr_scene
- script.fix_kit_scene
service: script.turn_on
in other words, you have multiple, identical blocks when a single one with a list of entities should suffice, I think
i don't know if you can change brightness
anyway, there's much to chew on there...
How do fe find the date fiffrence from 2 dates?
{{ (states.sensor.last_reading_taken_date.state) - (states.sensor.due_date.state) }} Not working
Hey guys, I’m trying to create a switch from a template that calls two service calls for on and two different ones for off. I’m using this template, which works with a single service call for each, but how would I go about with the formatting to add a second one? https://www.home-assistant.io/integrations/switch.template/#toggle-switch
Like https://community.home-assistant.io/t/days-between-2-dates/28739
@inner mesa{{ ((states.sensor.last_reading_taken_date.state)) - (as_timestamp(now())) }}i gerunkown errorcan u help
That’s not what the post says and is different from the original dates you were trying to subtract
ya ok, but my sensor.last_reading_taken_date is pooled from electricity company server. So i want to subratct that from todays date
I dont see attribute end_time for my sensor
i am having a real hard time with templates. I originally wanted to take the data from my JSON API as a 'state' but i hit the 255 char limit, so i had to put it as an attribute.. now im struggling on extracting the data is a decent way from the attributes.. https://imgur.com/a/tA6ddrh
i am basically wanting to be able to display information from each of the 'routes'
perhaps with each 'route' as its own sensor?
what do you want to display exactly?
Here is a template to display the name of the route
{%- for f in states.sensor.bayislandsguide.attributes.route -%} {{f.name}}, {%- endfor -%}
i want to be able to display the name of the route, and the 'departstime'
Well this should make it:
{%- for f in states.sensor.bayislandsguide.attributes.route -%} {{f.name}}: {{f.departstime}}, {%- endfor -%}
i will give it a try, thanks.
ok, so that is showing the info i want.. ill try to work out what else i need from here
i think my end goal should be to make 2 sensors, which i can then display in the UI
unless i am doing something wrong?
No you don’t. It really depends on what you want to do
i just feel like i am doing things in way too many steps
basically, there is the URL: https://api.bayislandsinfo.com/index.php?view=signage-ferryplanner&key=g3klsprM&from=russell&to=redland
and i want to display 2 items.. "4:30AM Direct to Redland Bay" and "7:20PM via all islands" or whatever
i am currently using the 'rest' integration to fetch the data
I would just make a custom component for it instead, should be doable with around ~50 lines
that was my original thought.. but i am very new to all of this
of course, there is also the 'gtfs' integration, but its not giving correct data
it seems to show 'No more departures' when I know there are.
I have this sensor giving me avg of 2 temperatures
value_template: '{{ (float(states.sensor.wohnzimmer_motion_1_temperature.state) + float(states.sensor.wohnzimmer_motion_2_temperature.state)) / 2 | round(2) }}'
unit_of_measurement: °C```
Is there a better way to do this?
Seems like it only updates if one of those 2 sensors changes values
well, the average is no different if the values have not changed.. so there is no need to update
seems to be solved by using https://www.home-assistant.io/integrations/min_max/ with type 'median'
@coarse tiger https://www.home-assistant.io/integrations/min_max/
if you don't want to do that:
wohnzimmer_sensor_avg:
value_template: ->
{%-set sensors = [float(states.sensor.wohnzimmer_motion_1_temperature.state), float(states.sensor.wohnzimmer_motion_2_temperature.state)] | map('float') -%}
{{ sensors | sum / sensors|reject('eq', '0.0')|list|length }}
unit_of_measurement: °C
this is abusing the fact that {{ "NaN"|float }} evals to 0.0
Hi all how would I got about creating a template sensor to output text based on two values?
entity_id - sensor.bme680_static_iaq_accuracy
ie
i want an output based on between 0 & 1
different out based on between 1 & 2
and so on
what if the value is equal to 0, 1, or 2?
value_template: >
{% set val = states('sensor.bme680_static_iaq_accuracy') | float %}
{% if val <= 1 %}
One
{% elif val <= 2 %}
Two
...
{% else %}
One million
{% endif %}
Thanks, will give that a go
Can anyone tell me if there is a state_not you can use in the wait templates?
@mental charm
"{{ not is_state('sensor.whatever', 'something') }}"
That will work for a wait template?
Just wanna make sure because in the dev tools template area it doesn't show as true or false
Yep, use it all the time
It should show true or false...what are you trying and what does it say?
{{ not_is_state('media_player.living_room_speaker', 'playing') }}
I'm working on a template sensor. I have a capacitance soil sensor that gives me readings between ~500 and 1000 that corresponds to 100% wet and 0% wet. I've got the formula sorted, moisture% = 200 - (0.2*soil_sensor). That will take my analog signal and give me a 0-100% moisture reading which is what I want. There will be more work later to limit it to no lower than 0% and not higher than 100% but I digress. Been playing with the templating tool and I got the math working but I'm not sure how to insert the entity into the formula.
My formula is: {{200 -(0.2*X)}} When I change X to a number between 500 and 1000, I get a good result. What I need to have in there in place of X is my entity which is: sensor.soil_sensor_analog_a0. Simply adding it like that didn't work, not putting it in quotes. I know I'm overlooking something fundamental but I just can't figure it out.
{{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0')) }}
That's giving me "unknown error".
But I think I get what I was missing. Perhaps it's a formatting thing at this point.
Are you sure that sensor id is correct?
oh you might need to cast it to a number first. Try {{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0') | float) }}
All states are strings, even if they disguise themselves otherwise sometimes
And I'll need to keep it a number if I want to do my comparisons as well. My template sensor will have an if > 100 then cap the value at 100, andif lower than 0, cap at 0, elseif it's just the value.
This is what I ended up with:
{{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0') | float) |round }}
I can't seem to simply put the above into an if/then statement.
if {{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0') | float) |round }} > 100
Do I need to be using is_state or something else for a comparison?
What are you trying to accomplish?
Might be worth reviewing the docs for the templating language
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
It was just the formatting, I included the {{ }} by mistake
Yep, been reading the Jinja stuff. It's a steep learning curve for me though. Working through it slowly 🙂
What are you trying to accomplish?
It's an imperfect template sensor conversion. I have an analog sensor that gives me values between 500 and 1000. I'm converting it to a percentage but if it goes above 1000 or below 500 I get a percentage above 100 or a negative number. So I was making an if/then statement to limit it to 100 if it went above 100 and to 0 if it was below zero. That way I alays get a value between 0-100. The Jinja formatting and logic isn't easy for an old fart like myself. Got it working finally though. Thanks to the help here and a lot of trial and error with the templating tool.
That template tester is probably my most used feature
I was thinking what it would have been like to try and figure this all out in my config file and rebooting each time 😮
Yeah...
Could someone improve upon or advise if what is below is possible Within my automation which cycles through different WLED effects, can i under the data template, for each effect, set is timing, brightness and intensity etc and pallet https://paste.ubuntu.com/p/QTgpNs2GSk/
I may have found a bug (or am stupid). I was just adjusting an elaborate template sensor. this template refers to another template sensor. after I was done adjusting it, I used the new 'reload template entities' feature. after reloading, the template sensor entity showed unavailable. In the logs I am seeing ''None' has no attribute 'state'' for any template entities that refer to another template, or 'Template loop detected while processing event' for some of them. All my template entities are showing unavailable if they refer to another template. When I put them in the template tool, they render correctly. If I restart home assistant, everything works correctly. Is this expected behavior for the new reload function for template entities?
yeah many of mine do
maybe that is just so rare that it wasn't considered. im just confused why restarting doesn't have this problem when the reloader does
i moved them around to test that, no difference. one of them is the very last elif in the list
oh wait what list do you mean
in the config.yaml
in the actual yaml docs?
yeah
ohhh
probably need all the deps to load before the things that call them
damn yeah so this is a me problem
its a huge guess
gonna be a bitch to fix that since i use packages and they are all spread out. but i bet you are right
oh gross
the config has gotten away from me lol
Hi All, I've been using HA for 18 months now and I am loving it. I have always managed to find answers on forums/Internet on how to do what I needed but this time I am struggling.
I'm trying to create a binary template referencing two lux sensors in an OR configuration but cannot for the life of me get it to work.
value_template: >-
{{ states('sensor.hall_lux')|float < 5
or state("sensor.study_lux')|float < 5 }}
Any ideas??
You’re missing the ‘s’ in ‘states’ in the second one
And you have a double quote where a single quote should be
Hi all, I have 4 sensor entities to get ink levels and a 5th to get status of my printer. When my printer is on, I have the ink levels like this :
https://ibb.co/LtbQxpD
When my printer is off :
https://ibb.co/9TDPHc4
I'd like to get the last ink levels with normal color drop icon when printer is off
and the update ink levels with personalised ink color (black, yellow, magenta, cyan) drop icon when printer is on
I looked around templates and icon_color with custom UI but without success
Thanks for you help
@sinful ridge "{% set forecast = state_attr('weather.home', 'forecast') or [] %}{{ forecast[0].get('temperature') if forecast}}"
OK, I'll give it a try. Thanks.
The above didn't seem to make any difference.
I was playing around and tried this:
{{ state_attr('weather.home', 'forecast') }}
Which gave me the full forecast array:
https://paste.ubuntu.com/p/5N6bTPbvqy/
What's the formatting to pull specific data out of that array? forecast[1].temperature doesn't pull the temperature for the 1st forecasted day. I get "None" as the result.
If what I gave you does not work, you are using it wrong, or the entity/attribute does not exsist
I don't doubt I'm using it wrong. I simply copy/pasted it directly into the templating tool. It gave no output.
Then the entity or attribute does not exsist, for me it display a temperature
From the forecast array, I can see the data I need. I just don't know how to pull that one specific bit of data.
Arrgh! Type-o
It works!
Thank you.
Hi guys, can someone help me translating a curl command in platform: rest config?
The curl command is: curl -H "X-User-id:xxxx” -H "X-User-hash:xxxx” https://data.uradmonitor.com/api/v1/devices/<SysID>/all/60
I've tried with - platform: rest
resource: "https://data.uradmonitor.com/api/v1/devices/<SysID>/all/60"
headers:
"X-User-id": “xxxx”
"X-User-hash": “xxxx”
but it is not working
thanks
What do you mean by 'not working'? You have the logs?
the value I get for that specific sensor is null
the entire rest entity is like this:
- platform: rest
resource: "https://data.uradmonitor.com/api/v1/devices/<SysID>/all/60"
headers:
"X-User-id": “xxxx”
"X-User-hash": “xxxx”
scan_interval: 60
name: uRad_Cloud_Noise
value_template: '{{ value_json.data.noise }}'
unit_of_measurement: "dB"
any reason why you have '#' before all the lines? everything is commented ?!
In my current config I've commented the lines as they are not working
Not sure X-User-id & X-User-hash should be between quotes
(header are not in quotes in the example https://www.home-assistant.io/integrations/rest/)
would be valid if everything was wrapped in {} but yeah
bad mix of json and yaml there
when running the curl command I get the following results:
before you paste, you should use a code sharing site
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
[{"time":1600956088,"latitude":44.xxxx,”longitude":29.xxxxxx,”altitude":100,"timelocal":4080,"temperature":28.5,"pressure":100072,"humidity":70.599999999999994,"voc":44942,"noise":45,"co2":878,"ch2o":183,"o3":20,"pm1":277,"pm25":369,"pm10":580}]
and I want to extract all these values: temp, humidity, etc
Try {{ value_json[0].noise }} instead of {{ value_json.data.noise }}
removed the quotes ... no errors when checking the config but the value is still unknown
@deft timber it works!
thanks a lot man
now, for each value I want to extract I need to create a separate entity or it is possible to get all the values in one shot?
either you create a rest sensor for each of your measures (temp, humidity, ...) or you create just one a put all the info you want in the attributes
I think I'll create a sensor for each value as you can guess I have no clue when coding :))
Never tested it but this could work, the value of the sensor would be the temp; and humidity, temp & noise would be in the attributes of the sensor:
value_template: {{ value_json[0].temp }} json_attributes: - humidity - temp - noise json_attributes_path: $.[0]
@deft timber it works a per your indication
temperature: 28.75
pressure: 100079
humidity: 69.6
voc: 48703
noise: 42
co2: 880
ch2o: 172
o3: 20
pm1: 159
pm25: 205
pm10: 299
I'll keep each entity separate as I want to graph the values over time for each value
thanks again for your help
if you want to split to different entities, its better to have one sensor for the rest call and do the rest in template sensors pulling from those attributes
otherwise you're going to spam the hell out of that endpoint
@dreamy sinew I have no Idea how to achieve this...
`sensor:
- platform: template
sensors:
urad_noise:
value_template: {{states.sensor.urad_cloud_noise.attributes.noise}}
unit_of_measurement: dB`
i'd use the state_attr() notation for that
if the template sensor starts up before the rest sensor does you'd throw an exception with the other method
so how value_template: {{states.sensor.urad_cloud_noise.attributes.noise}} would look like using state_attr()?
if you click the link i posted there's an example
please don't get mad at me ... I have no coding skills
state_attr('sensor.urad_cloud_noise', 'temp')
Well I changed my template sensor 3 different times
Now I have the old names in history
(I really tried searching, so I'm so sorry🙈)
🙏
You could manually edit the DB but I doubt that's worth it
I'll put up with it for a while
I'd probably edit it, I have too much to do
With other aspects of my life. Wish I could just screw off everything and really focus on HA
I setup a template sensor for the temp to automate my heater, I was using YR temp before that.
Since the fan.mqtt integration requires some work, I need a template which returns a json string
{{{"fanSpeed": "value_json.fanSpeed"}}}
this sadly doesn't work :/
nvm I'm just very stupid
{"fanSpeed":"{{valueJson.fanSpeed}}"}
Hello, maybe someone have a small fix. Since 0.115 this template does not work anymore. The value_template part still works, but the rest...
- platform: template
sensors:
wz_temp_mean:
value_template: >
{{ ( ( (float(states.sensor.wohnzimmer_multisensor_temperature_air.state))
+ (float(states.sensor.ht_livingroom_temperature.state))
+ (float(states.sensor.ht_diningroom_temperature.state)) ) / 3 )
| round(1) }}
unit_of_measurement: °C
Had a look into the docs, but this should be still the right syntax.
Hello all, i want to use my next phone alarm as trigger! i set alarm time on 07:30. See picture https://i.imgur.com/i4QIGlA.png . How can i set that time as trigger? i dont have the same alarm time everyday.
i cant get the attributes of the state with ; "{{ state_attr('sensor.marcus_p30_next_alarm', 'Local Time') }}"
this works but that time is wrong : {{ states('sensor.marcus_p30_next_alarm') }}
@river blade , I don't understand why you have the 'state' at the end. It shoud be states.sensor.wohnzimmer_multisensor_temperature_air (or states('sensor.wohnzimmer_multisensor_temperature_air')
@silver pewter , didn't Tinkerer help you with that yesterday in #automations-archived and recommended you to use an input_datetime for that purpose?
This works but it it get the wrong time: https://hastebin.com/ejusepucuz.bash
like you see on the imgur link, right time is under "Local Time" and state showing 2h wrong
or is it right but it showing time as 12h clock am/pm ? i need 24h clock xD
@deft timber sry bad english 😛
@silver pewter , didn't Tinkerer help you with that yesterday in #automations-archived and recommended you to use an input_datetime for that purpose?
@deft timber No. That .state ist required at then end of entity. Otherwise it does not work.
When i att this to the automation : datetime: "{{ state_attr('sensor.marcus_p30_next_alarm', 'Local Time') }}"
it doesent work
but it gets the right time in template under developer tools
Oh. That seems a much better option. Thanks for the recommendation!
@teqqyde do you know what is wrong with my template?
I think it is a problem with the timezone
okok, i have this in my docker compose:
volumes:
- /etc/localtime:/etc/localtime:ro
- /etc/TZ:/etc/timezone:ro
environment:
- TZ=Europe/Stockholm
I have to look into it
thx for answering me 🙂
The time is right in ha, like loogbook. strange 😛
Hi, guys!
Can some of you bright coders here, shed some light on this service_template, which I cannot get to work...
It is part of an action: in an automation
- service_template: "{% if states.sensor.planter_urtehage_fukt.state < '25' %} script.vanning_terrasse_og_urtehage_tidsstyrt"
What am I missing?
Don’t you miss the {% endif %} statement ?
Don’t you miss the {% endif %} statement ?
@deft timber I´ve tried that too, and over multiple lines... This do not compile
{%- if states.sensor.planter_urtehage_fukt.state|int < '25' -%} script.vanning_terrasse_og_urtehage_tidsstyrt {%- endif -%}
Neither do
- service_template: >-
{% if states.sensor.planter_urtehage_fukt.state < '25' %}
script.vanning_terrasse_og_urtehage_tidsstyrt
{% endif %}
I don't understand why you have the 'state' at the end. It shoud be
states.sensor.wohnzimmer_multisensor_temperature_air(orstates('sensor.wohnzimmer_multisensor_temperature_air')
@deft timber this is not correct,states.sensor.wohnzimmer_multisensor_temperature_air.stateis valid. However, the second method in your message is preferred.
@earnest cosmos Remove the quotes around '25'. You're making 25 a string when you put it in quotes. Also if that sensor is above 25 that automation will print an error about a missing service (and it might not continue past that action, but I'm not sure about that)
@deft timber Keeping the multi line version?
You also need the | int that you had originally. Finally, states('sensor.planter_urtehage_fukt') | int would be better
Can you share the entire automation? There might be a better way of accomplishing what you're trying to do
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Yes @buoyant pine , I noticed my error 🙂 one moment of distraction 😉
Hello, im trying to get a Template that shows the Time left unitl my Washingmaschine is finished.
Output of {{ states('sensor.waschmaschine_remaining_program_time') }} is 2020-09-25T14:12:19.957394+00:00
This is also not my TimeZone it is the UTC Timezone.
How do i get this to show something like "2h Remaining" or "02:20:12" (hh:mm:ss)?
I think you could use timestamp_local
I have a value_template: "{{ state_attr('sensor.utomhus_framsida_temperature', 'lastUpdated') | timestamp_local }}"that works fine
or use something like this:
{{ as_timestamp(strptime(states.binary_sensor.status_smoke_sensor_0.last_updated | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f')) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
but I you should do the calculation first in UTC and change format last
I have a
value_template: "{{ state_attr('sensor.utomhus_framsida_temperature', 'lastUpdated') | timestamp_local }}"that works fine
or use something like this:{{ as_timestamp(strptime(states.binary_sensor.status_smoke_sensor_0.last_updated | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f')) | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
@waxen rune This is giving me the same Timezone as before.
which of them?
@earnest cosmos posted a code wall, it is moved here --> https://paste.ubuntu.com/p/wTsDDc8wtg/
Can you share the entire automation? There might be a better way of accomplishing what you're trying to do
@buoyant pine
This automation is controlling irrigation, and made to schedule start at set hours, and in conditions whereyr_precipitationis below the threshold.
My aim is to trigger a script for this, where each script is (so far) set for two irrigation sections.
script:
vanning_terrasse_og_urtehage_tidsstyrt:
sequence:
- service: homeassistant.turn_on
entity_id:
- switch.vanning_terrasse_og_urtehage
... and some notifications and stuff left out here.
@earnest cosmos posted a code wall, it is moved here --> https://paste.ubuntu.com/p/3DsbTgyKM7/
automation:
- alias: '[Vanning] Daglig tidsstyrt'
trigger:
- platform: time
at: '04:00:00'
- platform: time
at: '12:00:00'
- platform: time
at: '18:00:00'
condition:
- condition: template ## there will be no more that 0,5 mm precipitation for the next hour
value_template: "{{ states.sensor.yr_precipitation.state < '0.5'}}"
action:
- service: script.vanning_lavendel_og_pottedrypp_trapp_tidsstyrt
- service_template: "{% if states.sensor.planter_urtehage_fukt.state < 25 %} script.vanning_terrasse_og_urtehage_tidsstyrt {% endif %}"
Sorry for the mess, guys 🙂 @buoyant pine
Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
Please read the rules--over 15 lines and you should use pastebin or similar. Keeps it cleaner for those on mobile @earnest cosmos
Anyway, just use a numeric state condition between those two actions checking if that sensor is below 25
Anyway, just use a numeric state condition between those two actions checking if that sensor is below 25
@buoyant pine Could you explain?
There wiill be more than just one sensor to check, and more than one areas to irrigate 🙂
Hi guys, how can I work around the new template handling since 0.115 no longer uses entity_id as a template update trigger? I've got this template:
{{ is_state('sensor.netatmo_camera_garage_movement', 'movement') and as_timestamp(now()) - as_timestamp(state_attr('sensor.netatmo_camera_garage_movement', 'time_fired')) <= states('input_number.netatmo_events_cooldown_time') | int }}
Before I had a sensor in the entity_id section that would trigger the update every few seconds, since 0.115 I can't do this anymore. The sensor get's stuck with true whereas before it would update after every few seconds and reevaluate the template.
I believe you just have to add this to the top of your template:
{% set foo = states('sensor.date_time') %}
Or whatever entity you used to use
The template just needs to somehow reference an updating entity
Even if it doesn't use it
Ok, I gues that would work, if anyone has a less "dirty" approach that would be apprechiated 🙂 Otherwise I'll stick with that. Thanks @autumn hearth
I'm pretty sure that was the recommended approach by the folks who made it. It's in the WTH thread
I guess I also could replace the now() with a sensor that represents the current time anyways.
👌
Yes
The entity_id section was perfect for that but this also works 🙂
The entity_id section was also a "dirty" approach though. The goods of the change definitely outweigh the bads in this instance
But yeah, definitely feels funky 🙂
Yeah for this particular template I'd prefer the old way 😛 But thanks again 🙂
Hey there, has anyone used 'eventsensor' before?
I'm trying to capture an event output into a sensor but unsure how to set this up with eventsensor ... Here is the output of the event ... https://pastebin.com/utEteVb0
Got it working!
anyone using the circadian lighting integration?
i'm trying to use some of it's values in an automation via a template, but not working out
in particular, this in my yaml: brightness: {{ states('sensor.circadian_values') }}
gets turned into:
brightness:
'[object Object]':
when i save it
action:
- service: light.turn_on
data:
entity_id: light.bedroom
brightness:
'[object Object]':
apparently hassbot likes formatted code lol
it likes properly formatted yaml
ohh ok
What is the current state of the entity?
from the template editor:
brightness: {{ states('sensor.circadian_values') }}
kelvin: {{ state_attr('sensor.circadian_values', 'colortemp') }}
brightness: 97.32123802347765
kelvin: 5419.63714070433
those same lines render the "empty" object above when i save the automation that way
You mean the UI automation editor? Have you tried editing the yaml file directly?
yeah, it i put that in there it crashes the ui editor lol
You should also be wrapping the template in quotes brightness: "{{ states('sensor.circadian_values') }}"
think that did it 👍
What am I doing wrong here? sensor: !include_dir_merge_list sensors/
finn_activity_goal.yaml
friendly_name: "Finn Activity Goal"
icon_template: mdi:trophy-outline
value_template: '{{ state_attr("device_tracker.whistle_finn", "activity_goal") }}'
unit_of_measurement: "minutes"
Invalid config for [sensor.template]: [friendly_name] is an invalid option for [sensor.template]. Check: sensor.template->friendly_name. (See ?, line ?).
from the docs
friendly_name string(optional)
Name to use in the frontend.
where? none of my other sensor templates have it
the name comes from the file name
I don’t do what you’re doing, but it certainly doesn’t follow the example
that's because there is no example for !include_dir_merge_list
Ok
@latent kiln Rob is saying you're missing sensors: in the third line of the first example on the page he linked above (as well as the sensor name below that line)
Well, third line excluding the comment
sensor:
- platform: template
sensors: <==== this line
solar_angle: <==== also this line
@buoyant pine yeah that worked, rob was correct as well. weird that my other template sensors don't have those lines and work
What other template sensors?
The only part of the config for integrations that's affected by splitting up the config is the integration line (sensor: at the top in this case). The rest of the config stays the same
anybody know which github I would post an issue with the template reloader? just /core?
core
Can anyone help with correct syntax: I want to show brithness of my lamp (data.new_state.attributes.brightness) but i dont know how to write it in this context: [[[ return (states['light.lampa_baksida'].state) ]]]
When using multiple ´service_template´s in an action: Will the entire action sequence stop if one ´service_template´ evaluate false?
action:
- service_template: "{% if states.sensor.planter_urtehage_fukt.state < '25' %} script.vanning_terrasse_og_urtehage_tidsstyrt {% endif %}"
- service_template: "{% if states.sensor.planter_lavendel_fukt.state < '20' %} script.vanning_lavendel_og_pottedrypp_trapp_tidsstyrt {% endif %}"
Trying to get TTS working with home mini but no luck. Any idea why? https://i.imgur.com/g6shdVj.png
@earnest cosmos What you’ve written will fail if the conditions are false because you aren’t providing a service in that case. It looks like you want a ‘choose:’ block: https://www.home-assistant.io/docs/scripts/#choose-a-group-of-actions
@worldly cypress you don't need to put 'data:' in the data of the service developer tool. just put entity_id: and message: in line.
@zinc goblet need to see what you are trying to do. first off it should be curly braces {} not brackets [].
.share the config you are trying to get to work
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
That’s from a custom button card or similar and they also cross posted in #frontend-archived (the right place)
ah. i don't go over there much ha
@earnest cosmos. It looks like you want a ‘choose:’ block: https://www.home-assistant.io/docs/scripts/#choose-a-group-of-actions
@inner mesa I am aiming at starting several scripts if each condition is met. Each of the scripts is starting if the soil moisture is below the thresholds for each plant.
A choose: can do that
A different and perhaps better solution is simply to add the condition to the beginning of each script and then just call them normally. The condition can determine whether watering is required for that plant and only continue if it is
@earnest cosmos
yeah that's definitely better
A different and perhaps better solution is simply to add the condition to the beginning of each script and then just call them normally. continue if it is
@inner mesa true. Good idea 💡
Thanks
Hello everyone,
I'd like to write a template to know which light is on of all my lights... Help please?
Gents, is there a way of creating a function so I don’t have to write the same code over? For example, to convert Celsius to Fahrenheit the formula is: f = (x * 9 / 5) + 32. How could I create a function and use that in an automation?
@lyric snow there's an example here: https://community.home-assistant.io/t/how-to-survive-without-the-all-groups/165742
Gents, is there a way of creating a function so I don’t have to write the same code over? For example, to convert Celsius to Fahrenheit the formula is:
f = (x * 9 / 5) + 32. How could I create a function and use that in an automation?
@sly thistle
https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts
but then how does he get it back to the automation?
maybe have the script write it to an input_*
or fire custom event
sounds like more work than just putting in the equation
yeah
can setup a template sensor to convert it, then just reference that
maybe a template inside input_text.c_to_f
then use it in automation as
data: >-
{{input_text.c_to_f}}```
i'm not sure if this would work
you can set the system unit Developer Tools -> General and in sensors if you set the unit_of_measurement: it will auto convert
Something so simple shouldn’t be so complicated to implement :/
Just switch to using Python through AppDaemon 😉
Is it possible to add template sensors through the ui at all?
No
Hey all, is there any easy way to convert a sensor that represents bytes into mb? I essentially want to create a sensor that represents the result of computing: <input sensor> / 1,048,576 From reading the docs i'm assuming that this will involve HomeAssistant's templating language, or possibly filters?
Could it be something as simple as this:
- platform: template
sensors:
network_mb_sent:
value_template: "{{ sensor.unifi_dream_machine_b_sent / 1048576 }}"
Where sensor.unifi_dream_machine_b_sent is a pre-existing entity i want to transform the value of?
Or is this correct format:
- platform: template
sensors:
network_mb_sent:
value_template: "{{ state(sensor.unifi_dream_machine_b_sent) | float / 1048576 }}"
there ya go
sorta
- platform: template
sensors:
network_mb_sent:
value_template: "{{ states('sensor.unifi_dream_machine_b_sent') | float / 1048576 }}"
test in
-> Templates
Thank you! I would have totally missed the quote marks
In the developer tools templates section is get the message "This template listens for all state changed events." with this test:
- platform: template
sensors:
network_mb_sent:
value_template: "{{ state('sensor.unifi_dream_machine_b_sent') | float / 1048576 | float(2) }}"
But as far as i can tell this should work fine?
- platform: template
sensors:
network_mb_sent:
value_template: "{{ (states('sensor.unifi_dream_machine_b_sent') | float / 1048576) | round(2)}}"
that's probably what you want
🙂 You're totally right. Thank you! I feel a bit embarrassed that i actually posted that mistake, but super grateful you pointed it out to me 🙂
np, it's easy to miss
the other main thing I fixed is to round the result of the calculation, rather than just the divisor
I see that now - (<thing> | float / <int>) | round(2) I've never really used this templating language before. Thanks for the guidance!
is it possible to make a template sensor that does not display any icon?
that's a #frontend-archived question
template sensors by themselves don't display anything
it seems that if i leave out icon_template altogether it gets the eyeball icon
again, that's a matter of what's displaying it
which is a card, which is a #frontend-archived thing
you'd need to either configure the card not to display an icon, or change the icon, or choose another card that lets you do what you want
the basic sensor card doesn't appear to let you not display an icon, but others do (like the custom button card)
I'll try that, thanks.
n00b question: Have a thermostat which has "humidity" available as an attribute. How do I get this to be able to use it in automations and in Lovelace?
1st I want to display the value in lovelace
2nd - I'd like to control a fan to switch on when the humidity is over a certain value
you need to decide on a card and the docs will tell you how to display attributes (if they can)
the docs show you how to use a numeric_state trigger with an attribute: https://www.home-assistant.io/docs/automation/trigger/
hello, how can I check in the value_template if the message was a string that's possible to convert to int (I.e. '100') or it's a json object (i.e. {"Time":"1970-01-02T18:54:59","Shutter1":{"Position":100,"Direction":0,"Target":100}})
try {{ state_attr('sensor.sensor1', 'Shutter1')['Target'] is string }}
hmm probably not an attribute for you
{{ states('sensor.sensor1')['Shutter']['Target'] is string }} maybe
I've figured it out,
{% if value|int(-1) != -1 %}
{{ value|int }}
{% elif ('Shutter1' in value_json and 'Position' in value_json.Shutter1.Position) %}
{{ value_json.Shutter1.Position }}
{% endif %}
is it possible to create a device_tracker entity from restful data?
there's only sensor and binary_sensor in Restful integration, but i was wondering if its possible to template a device_tracker
@elder moon there is a workaround to do that. you can make an mqtt device tracker and use the restful data to publish an mqtt topic which would change the state of the device tracker.
essentially the same thing as a template device_tracker, just an extra step.
no straight up template device_tracker is possible though, at least as of the last time I tried (and discovered the workaround)
thanks Barbados
do you know if there's a ready made solution for a linux service which would fetch rest data and translate it to mqtt
?
not sure. if you already have the integration set up in HA you could just use an automation though
ah an automation which sends data to mqtt and then use mqtt device_tracker?
correct
feels awkward but this can work 🙂
it is janky but works fine once you have it set up
too bad i missed WTH month with this
lol yeah, template device trackers do seem like a WTH
Moving my question here:
any python gurus, to help me optimize this block to one-liner, map + filter functions?
{% set nowTime = now() %}
{% set lights_on = expand('group.lights') | selectattr('state', 'eq', 'on') %}
{% set lights_count = 0 %}
{% for light in lights_on if as_timestamp(nowTime) - as_timestamp(light.last_changed) > (10 * 60) -%}
{% set lights_count = lights_count + 1 %}
{%- endfor %}
{{ lights_count }}```
{{ states.light|selectattr('state','equalto','on')|list|length }}
i cant get to wrap my head around how to template a sensor so it shows the delta of a timestamp to the current time, it would be great if someone could help me out, The sensor holds the finishing time of my dishwasher (2020-09-27T16:35:10.038563+00:00) and i want to have a sensor who shows the remaining running time in minutes
The professional in me got frustrated with having to put my home assistant base URL in the yaml repeatedly (re: discussion in #frontend-archived ).
From what I've read, concatenating secrets in templates does not work.
I found a bash script I can use to grep the secrets out of the secrets.yaml... but haven't been able to wrap my mind around how to properly call that from a template yet, with a variable of which secret to call.
Does anyone happen to have a working example of such?
(of course, if there is a way to more properly call the internal or external URL as configured in home assistant already, rather than storing it in a secret as well, I'm all ears!)
A common way to do this is to add the thing you want as an attribute to an entity using customize.
So if you have yaml homeassistant: customize: sensor.my_sensor: #or just anything that EXISTS, could be e.g. sun.sun my_secret: !secret my_secret
you can then use jinja {{ state_attr('sensor.my_sensor', 'my_secret') + "/rest_or_url_or_whatever" }}
Of course it won't be secret anymore, though.
Only not in the logs I suppose. For sharing config etc. it's still secret. Thanks!
huh.
This template evaluates OK in the browser's template developer tool.
{{states('input_text.exhabaseurl') + "hassio/dashboard"}}
When I put it in the yaml it fails :(
invalid key: "OrderedDict([('states('input_text.exhabaseurl') + "hassio/dashboard"', None)])"
the alert: https://paste.ubuntu.com/p/sZDn7hKzsQ/
(Yes - I figured I could use an input_text rather than tacking it onto a sensor meant for other things)
Just put the text after the template
huh.
This template evaluates OK in the browser's template developer tool.
{{states('input_text.exhabaseurl') }} "hassio/dashboard"
Maybe without the quotes
Yep. That's yaml biting you again. { indicates the start of a map.
If it starts with text and then goes into a template, it works fine
Yep, best not to rely on the interpretation and just be explicit
url: "{{states('input_text.exhabaseurl') + 'hassio/dashboard' }}" this is the result which passes ha core check. Great!
Thank you
Hello. Does anyone know why this template worked before and updated the time alone, and now it doesn't work?
https://paste.ubuntu.com/p/gcWCcwbQgY/
im trying to do a bunch of Restful sensors, but the Rest API requires a valid Auth Token and this one can be obtained only by another Rest request but its only valid for 8 hours. Is templating such sensors possible in HA?
{{ states.light|selectattr('state','equalto','on')|list|length }}
@brisk temple This is missing the conditional which I am unable to convert to single line solution.
i reckon that i would need an input_text sensor which holds the current api token for use in Restful sensors
@elder moon might be better off with a custom component in that situation
what am i missing here.. something simple im sure
sensors:
last_motion:
friendly_name: 'Last Motion'
icon_template: 'mdi:motion-sensor'
value_template: >
{%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
{% for pir in pirs %}
{% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
{{ pir.name }}
{% endif %}
{% endfor %}```
template message just says "This template listens for all state changed events."
hmm maybe the last update changed they way my templates work because another one of my template is broke. 😕
sensors:
main_level_avg_temp:
friendly_name: "Average House Temp"
device_class: 'temperature'
unit_of_measurement: '°F'
value_template: >-
{% set sensors = [
states('sensor.living_area_temperature')|float,
states('sensor.master_bedroom_temperature')|float,
states('sensor.kitchen_temperature')|float,
states('sensor.kids_room_temperature')|float
]
%}
{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
@topaz walrus what error are you getting in your logs? or what is it not doing that it should be?
and also are any of those sensor entities in the template template sensors themselves? and if so, did you use the 'reload template entities' button?
Nothing in my logs, just checking them in the “template checker” thing under developer tools.
But looking at the change log there is some type of breaking change to templates. I honestly just don’t understand what changed.
nothing that would affect templates that were already working. the changes to templates were mostly that you don't need to put 'data_template' anymore to use templates in scripts and automations
template sensors should be fine. thats why I asked if any of the sensors referenced in the template you shared are template sensors. there is an open issue about that as it relates to the new template reloader
but if there's nothing in your logs then it probably isn't that.
Hi all! i need help to modify a template sensor :
medium_temperature:
friendly_name: 'medium of temperatures'
value_template: >-
{{ ((float(states.sensor.thermohygro5_temperature.state) + float(states.sensor.thermohygro4_temperature_2.state) + float(states.sensor.thermohygro3_temperature.state)) / 3) | round(1) }}
unit_of_measurement: '°C'
Here is the problem :
when one sensor.thermohygro*_temperature is not working the medium don't give any result
Here is my question :
how can i modify the template to avoid using a "not working sensor" in the calculation
is there a good way to get the timestamp of the last time an entity's state changed?
@dusky bane , did you try using the min/max sensor? https://www.home-assistant.io/integrations/min_max/
@marble needle yes there is: states.domain.entity_id.attributes.last_changed (ex: states.sensor.my_sensor.attributes.last_changed)
ah cool, it's used in examples but not explicitly described
Has there been some recent changes to templates? I've got a few template sensors that show as "unknown" but in dev tools they render correctly?
@marble needle Correctionstates.domain.entity_id.last_changed without the 'attributes'
thank you @deft timber i didnt know about that i'll try it
@violet oyster I’m not sure then. They were working and now they stopped. 😕 like I said if I throw them in the template checker it just says "This template listens for all state changed events."
@deft timber it's working, very direct solution, perfect thank you very much
👍
Anyone know whats wrong here?
sensors:
last_motion:
friendly_name: 'Last Motion'
icon_template: 'mdi:motion-sensor'
value_template: >
{%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
{% for pir in pirs %}
{% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
{{ pir.name }}
{% endif %}
{% endfor %}
I'm trying to create a sensor for a device's bandwidth on my network using the difference in total data transferred divided by a certain amount of time. Anyone have a sample of something i can look at that is similar to that?
EXAMPLE: at 21:00:00 the device had transmitted 100MB, at 21:00:30, the device had transmitted 200MB. So the device transmitted 100MB/30seconds or 3.33MB/s (average)
I think I could create the arithmetic part of the sensor, but I don't know how to grab values at t=0s and t=30s and use them in the template.
Hi I am working on a interactive floorplan using Picture Elements card.
About state_image, it was like from those example I can recall an entity and then base on its condition, let's say "on"/"off", to show a image overlay.
Is it possible if I can have two conditions?
Let's say,
if light A is on, light B is off, show picture A
else if light A is off, light B is on, show picture B
else if light A is on, light B is on, show picture C
else show transparent.png
is it possible?
Thanks
Seems like a #frontend-archived question
I copy&paste overthere then