#templates-archived
1 messages · Page 154 of 1
I absolutely do and can't thank you and @silent seal enough for helping to figure this out!
better:
from zoneinfo import ZoneInfo
from datetime import datetime, timezone
import sys
import json
output = {
"datetime": str(datetime.now().astimezone(ZoneInfo(sys.argv[1]))).split('.')[0],
"timezone": sys.argv[1]
}
print(json.dumps(output))
sensor:
- platform: command_line
name: Other Timezone
command: >-
python3 tzconvert.py "{{ state_attr('sensor.robs_iphone_13_geocoded_location', 'Time Zone') }}"
value_template: "{{ value_json.datetime }}"
json_attributes:
- timezone
- now includes the date and the timezone
Altered it a bit to match the needs more:
from datetime import datetime
import sys
import pytz
import json
output = {
"datetime": datetime.now(pytz.timezone(sys.argv[1])).strftime('%a %b %d, %I:%M'),
"timezone": sys.argv[1]
}
print(json.dumps(output))
Hello everyone, could someone please help me figure out a way to send data from a presence sensor into a device tracker?
Basically, through "ESPresense" I've got a presence sensor that outputs either a room name or the words "not_home". Now, I want to use this to track people, but that function only accepts device trackers, which means my sensor won't show up in the dropdown menu.
Now, I figure a simple template could create a binary sensor, to act as a device tracker, which would read "away" when the sensor value is "not_home" and "home" when the sensor value is a room name.
Problem is, I have no idea how to make such a template.
This is actually easier than you think. Give me a second to pull it up
- platform: template # Matthew Home
sensors:
<entity name wanted>:
friendly_name: <friendly name>
value_template: "{% if is_state('<mqtt_room sensor>', '<room>') %}Home{% else %}Away{% endif %}"
- platform: mqtt_room # "Mt_BC"
name: "<mqtt_room sensor>"
device_id: <device ID from mqtt/espresence>
state_topic: espresense/rooms
timeout: 20 # change if you like to suite needs
away_timeout: 270 #change this too asa needed
Two fold process, need to make a sensor to collect from MQTT broker the ESPresece, then template that to read as you need. I use mine just to know if someone is parked in the garage though, so may need to tweek slightly as needed for the rooms part of it
(I use a sensors.yaml, so if you dont you will need to add the sensor: heading to those)
So, way above my skill level.
Thank you very much
The first one goes in the templates.yaml, correct?
Depends how you have your config.yaml set up. I have mine broken out a bit so for me it is sensors.yaml and my config.yaml has sensor: !include sensors.yaml
same way here
the first part isn't working
it keps spitting invalid slug error messages
copy paste exactly what you have filled out
will do, but how do you add those code boxes in discord?
'''sensors:
<entity_name_wanted>: device_tracker.galaxy_watch_4
friendly_name: galaxy_watch_4
value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}" '''
change this
<entity_name_wanted>
to what you want the entity name to be
its backtic btw. usually upper right of the keyboard with ~
well EFF discord for that
entity_name_wanted: device_tracker.galaxy_watch_4
friendly_name: galaxy_watch_4
value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}"```
like this?
Yup. feel free to actually put the name you want there
replace entity name wanted, with an actual name?
- platform: template # Matthew Home
sensors:
matthew_home:
friendly_name: Matthew Home
value_template: "{% if is_state('sensor.mt_bc', 'garage') %}Home{% else %}Away{% endif %}"
that's my dirty config. creates an entity named sensor.matthew_home
device_tracker.galaxy_watch_4:
friendly_name: Galaxy Watch 4
value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}"```
like this?
- platform: template # Galaxy Watch
sensors:
galaxy_watch_4:
friendly_name: Galaxy Watch 4 Presence
value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}"
wait, this template gives a sensor? As in a "sensor.whatever" entity?
correct. ESP presense cant be made into a device tracker, at least not yet. Reason is, it doesnt actually track anything. What it is doing is saying what a device (watch in this case) is connected to.
@lyric socket Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
I already have an espresense sensor, in my entities
I am looking for a way to make a device_tracker.whatever entity and have it so that values from the espresense sensor get copied to that device_tracker entity
and why does it have to be a device tracker?
because I want to track when a person is home or not and the dropdown menu for that will not list or accept anything other than a device_tracker
mhm.
and what are you tracking them for? an automation? or just a lovelace card to say who is or is not home?
both
I don't want some automations running when the relevant person isn't home
and a lovelace card can show me at a glance who is or isn't home.
perfect, then those two chunks of code will get you there.
What you need to do is alter your mindset a bit. Is a device tracker/person entity a lot easy to deal with, by far yes. Best way for that is to have everyone in the house downlaod the HA app on their phone. However, if you are like me and have someone that doesnt want the app, then you got to find new ways to do things.
For me I have a BlueCharm beacon on the persons vehicle (or in your case keys/watch/phone) and when the ESP reports to HA as it being in the garage then I template it to say Home otherwise it says Away. now for an automation that would look something like:
https://pastebin.com/MXS963gR
the referenced entities from the above paste
https://pastebin.com/zLj0yGCD
This can be done with just a template. Running a whole automation, just for that, is wasteful
I already have ESPresense beacons allover the place, looing for bluetooth devices
it works and provides good data
I'd be done, if it wasn't for this one stupid inability to use the sensor in the person device tracker
Thanks for the effort, though.
I'll keep asking around.
I actually had a very similar template, up until a month ago, but I deleted it when it stopped being relevant for its original task.
If I have a dict with multiple keys and corresponding values, can I somehow replace just one value and leave the rest as is?
I can recreate it using the current values, but I was wondering if there is an easier way
Did you try {% set variable.key = new_value %} already?
I don’t know if that will work, but it’s worth a try.
You can't modify data structures like that, but you can use |replace('foo', 'bar') or other filter if you just want to modify a string
Small help required.. cant figure out this one
https://www.home-assistant.io/integrations/switch.command_line/#change-the-icon-when-a-state-changes
What to do when value template is not used?
this does not seem to work
{% if value == true %} mdi:bell
Ah, yes. This seems to work. Only thing is that it stores it as a string.
{% set player = dict(entity_id = 'media_player.beneden_groep', volume_level = 'no volume') %}
{{ player | replace('no volume', 0.25) }}
.share what you have already
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
You can refer to the value of the sensor itself:
icon_template: >
{{ 'mdi:bell' if is_state('switch.cam1_notify', 'on' ) else 'mdi:bell-off' }}
Or
icon_template: >
{{ iif(is_state('switch.cam1_notify', 'on'), 'mdi:bell', 'mdi:bell-off') }}
or you just need to see what the command actually returns and test value against that
Hello, how can I put condition like numeric_state above, below?
for example: conditions: "{{state('sensor.aqua_ariston_current_temperature') < 40}}"
{{ states('sensor.aqua_ariston_current_temperature') | int > 76}} I think this is ok
I am trying to create a script that adjusts HVAC temperature according to the mode. I had this working in my old build but cannot get it working in the new setup. I get "Message malformed: extra keys not allowed @ data['service']" in HASS even though every YAML validator I try says its fine. Any help would be appreciated! Code: https://www.codepile.net/pile/kXWVa0dv
I don't think the problem is in that code
i have a template sensor determining when our shower is in use. where do i define the icon for the sensor? current sensor is setup like this in config.yaml
- platform: template sensors: master_bath_shower_occupied: friendly_name: "Master Bath Shower occupied" value_template: "{{ (states('sensor.temperature_master_bath_humidity')|int - states('sensor.average_humidity_master_bath')|int) > states('input_number.master_bath_humidity_threshold')|int }}"
i was trying this, but got an error that a dictionary value was expected:
- platform: template sensors: master_bath_shower_occupied: friendly_name: "Master Bath Shower occupied" value_template: "{{ (states('sensor.temperature_master_bath_humidity')|int - states('sensor.average_humidity_master_bath')|int) > states('input_number.master_bath_humidity_threshold')|int }}" icon: > {% if states("sensor.master_bath_shower_occupied") == "false" %} mdi:account-cancel {% else %} mdi:account-check {% endif %}
You have to follow the docs
i'm trying. but failing haha
ah i didn't see that "icon_template" in the docs. thank you
was looking at 'icon' under configuration variables
That's from the new format. You're using the legacy format there
the sensor is in legacy format you mean? or the icon
The sensor
oh! should i be doing
template:
- sensor:
etc etc
If you want
ok. i got icon_template working but if i want a static icon i don't seem to be able to define it under this sensor. it just keeps rejecting it. or does it only work with templates?
It's just a string. Should be fine
ah ok great. got it now. thank you!
Can anyone see where my indentation issue is or whatever it may be? am i doing the entire action part wrong?
https://bpa.st/5W7A
You're misunderstanding how templates work there
You can't use templates to surround a set of actions like that. You should look at choose: for that
alright, i'll check out choose. thank you
Does this look better? https://bpa.st/K3NA I'm assuming this will run the tts.google_translate_say only between 7 and 20. but always send the discord message
that'll do it
yo petro. I check that and referenced: https://community.home-assistant.io/t/wait-for-trigger-event-not-being-seen/235368/25 but I still have no joy
that reference has no impact on your script
it's a single script, you aren't running a script in your script
I tried changing service: - service: script.pass_kodi_content_to_other_device to - service: script.turn on but no love
did you even look at the post I made in response? It seems like your'e trying to use your other method, which will not work
you can't pass metadata, so you have to use a single script
or a intermediary object that holds the information
that has nothing to do with it, you need to determine the timing before trying to fix it
moving things around isn't goign to give you any information
look at your script trace, and look at the event times and determine the order
ok let me go back again and try. Sorry I'm just not seeing it. that being said i've learn't a fuckload from your shorthand jinja and yaml. I didn't know you could do shit like this
If you can prove that the event is firing before the wait for trigger (which I think it is), we'll have to make an automation that fires a custom event that passes the file, with a slight delay.
otherwise, it doesn't make sense that it's not triggering, because there's nothing different between the triggers in your automation that you were using before
Thanks 🙂
yes that's the conclusion i came to. But if I use an automation then am I back to the original issue of not being able to pass the a variable to it. Bear with me whilst I test
no
check my response on the forum, my previous no was for your comment about "But if I use an automation then I am back to the original issue"
I have a vibration sensor on my dryer that doesn’t ALWAYS pick up but is mostly consistent for now. I want to take its state, change it to 1/0 instead of True/False, then do a “max value” over the last 10 or so minutes in a sensor. I need some snippet of code to see how you take this true false and make it an INT. Or a smarter way to find out if this sensor hasn’t detected vibration for X minutes.
Sounds like you just to use for: in the trigger
maybe you can use a history_stats sensor?
https://www.home-assistant.io/integrations/history_stats/
you can use the type count and then either compare to 0 or greater than 0
I re-read your comment and if you wanna know when your sensor didn't detect vibration for X minutes, better use type ratio I guess
why do these two templates render differently?
{{ strptime('Sun 2022-03-20 16:29:49 GMT', '%a %Y-%m-%d %H:%M:%S %Z') | relative_time }}
{{ strptime('Mon 2022-03-21 17:36:23 GMT', '%a %Y-%m-%d %H:%M:%S %Z') | relative_time }}
gives
18 hours
2022-03-21 17:36:23-07:00
in the tester
well that is a time in the past for me
17:36:23-07:00 would be 10:36 which was ~25min ago now
and I don't see an error in the log about this either
maybe it's not doing timezones right. If I change the hour to 10, it properly returns the delta string, but if I use 11, it goes back to displaying the time
10:36 being almost an hour ago in my TZ
strptime does not attach a timezone to datetime objects
pfft
it seems relative_time attempts to add a TZ to unTZ'd datetimes
that's the discrepency
so it adds whatever your timezone offset is to your non-tz'd datetime and it ends up being in the future
the one in the past is wrong too
that says '1 day'
it's just that 24 hours is a pretty big window of error that happens to work in your favor
I guess I'm not understanding... I use this template in an "uptime" sensor:
sensor:
- platform: command_line
name: Living Room Monitor Uptime
command: "ssh -o StrictHostKeyChecking=accept-new -i /config/.ssh/id_rsa pi@192.168.1.220 'systemctl show monitor.service --property=ActiveEnterTimestamp --value'"
value_template: >-
Up {{ strptime(value, '%a %Y-%m-%d %H:%M:%S %Z') | relative_time }}
and this works fine for what I need
gives me an actual relative time
but it's not a correct relative time
it's... all relative lol
if I restart the service, the relative time changes to be accurate
right, but it's going to be off by the offset of UTC to whatever TZ you're in
strptime does not attach a timezone to your datetime object
so it's 'unaware' of what TZ it's in
relative_time tries to fix that by adding your local tz to it
even though the string has GMT in it?
problem is I adapted that sensor for a different service on a different host, and the adapted one doesn't work
so one gives me a relative time
and the other gives a timestmp
no, both give you a relative time to a wrong time, one gives you a timestamp because it thinks it's in the future and it doesn't compute time in the future
put this in your template editor, maybe it'll help you understand that you can't avoid this
{% set dt = strptime('Sun 2022-03-20 16:29:49 GMT', '%a %Y-%m-%d %H:%M:%S %Z') %}
{{ dt.tzinfo }}
{% set dt = strptime('Mon 2022-03-21 17:36:23 GMT', '%a %Y-%m-%d %H:%M:%S %Z') %}
{{ dt.tzinfo }}
{{ now().tzinfo }}
ok... so what should I do to work around this?
None, None, Your TZ
I'm not sure how you can work around this
hmm, but what do you mean by this?
did you paste the info into your template editor?
you'll k now what I mean if you did
unfortunately, you need a way to attach utc tz to a datetime
Seems like it should log a warning or error based on invalid input
The input is valid
This is a byproduct of how datetimes work. It’s most certainly a bug in our relative time code
We just need a new filter that’s like as_local but as_utc
relative_time just returns the input when given a future time
Yes, but that’s how it’s designed
Seems no different from other such cases with input that it doesn't handle
so the issue is that because of missing timezones, yesterday is in the past while today is in the future?
or whatever
my first timestamp is in the past but the second one is in the future
It adds local time to your local time, that’s the problem
Because you first local time is timezone-less
If you don’t know code, it’s pointless to try to understand
It’s a gap in the functionality
All you need to know, is that both of your relative times are wrong
well I do know code... I just didn't realize this bug existed
as is the nature of many bugs
I'm a python programmer
just don't deal with timestamps much
Then read up on strptime in the datetime library
There’s many stack overflow pages that cover strptime and it’s inability to assign a tz to the object
what I don't understand is that even with NO timezone, both of those strings are in the past
one works with relative_time (even if it may be innacurate), and one doesn't
Because it’s assigning your tz to the datetime object and it offsets itself by the utc to your tz offset
ok yeah so it's this basically
Google: datetime aware vs naive
You strptime only produces naive
Relative time makes it aware to your tz without changing the time that’s set in it
ok
ok well i figured out why some worked and some didn't
the ones that worked return Tue 2022-03-15 14:18:59 PDT
which, even though the time zone is not factored in by strptime, is still the correct TIME
the host that was returning as GMT had the time zone set wrong on the device
it now reports Mon 2022-03-21 10:36:23 PDT
which is in the past, and works with my template
the hyperion and monitor ones work this way: https://imgur.com/Kijo44r
that "full page" screenshot did something weird with my sidebar but that's fine lol
passed out at 1am again. damn time diff. there was a timeout error from the kodi_call_method_result. gotta go to job#2 will report back tonight.
I am getting an error when trying to use this template to convert a sensor from C to F.
sensors:
- name: "Basement Temp"
unit_of_measurement: "°F"
state:
value_template: {% set t = states('sensor.dining_temp_temperature') | float %}
{{((t)*9/5)+32}}```
2022-03-21 21:29:48 ERROR (MainThread) [homeassistant.components.template] while scanning for the next token
found character '%' that cannot start any token
I changed it to:
sensors:
- name: "Basement Temp"
unit_of_measurement: "°F"
value_template: "{% set t = states('sensor.dining_temp_temperature') | float %}
{{((t)*9/5)+32}}"```
and now get:
Invalid config for [template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', 'Basement Temp'), ('unit_of_measurement', '°F'), ('value_template', "{% set t = states('sensor.dining_temp_temperature') | float %} {{((t)*9/5)+32}}")])]. (See /config/configuration.yaml, line 35).
sensors:
- name: "Basement Temp"
unit_of_measurement: "°F"
state:
value_template: "{% set t = states('sensor.dining_temp_temperature') | float %}{{((t)*9/5)+32}}"```
also same error as above
the template dev tool shows it working fine so I dont understand
change state: to template:
value_template:
dng phone
no that's not right disregard
you need to add %} at the end
value_template: "{% set t = states('sensor.dining_temp_temperature') | float %}{{((t)*9/5)+32}} %}"
sorry
value_template: >
{% set t = states('sensor.dining_temp_temperature') | float %}
{{((t)*9/5)+32}}
bah
HI can someone please explain me how subtraction works in timestamp template? For example in the following case:
{%- if states.vacuum.rockrobo.last_changed -%} {{ (as_timestamp(now()) - as_timestamp(states.vacuum.rockrobo.last_changed)) > 60*10 }} {%- else -%} false {%- endif -%}
what 60*10 means?
timestamp are in seconds. It looks like the template checks if if there has been a state change more then 10 minutes ago (60 seconds * 10)
You couls also use {{ (now() - states.vacuum.rockrobo.last_changed).seconds > 60*10 }}
no need to convert it to timestamps
ty
Hi,
I have a sensor that I want to show in lovelace divided by 1000. Pls suggest what is the right way to do it.
The example below is not correct, but guess it should be something simmilar.
type: entities
entities:
- {{ (states('sensor.valetudo_robot_1_floor_current_statistics_area') | divide (1000) ) }}
Thanks!
if you were to divide on a calculator, what character would you use?
"/" dkesn't work also
States are strings, you can't calculate with strings. You need to convert it to a number first
{{ states('sensor.valetudo_robot_1_floor_current_statistics_area') | float / 1000 }}
but that yaml is suspect. It seems like you're trying to do this in lovelace, which is not possible. You have to make a template sensor.
Or use something like template-entity-row https://github.com/thomasloven/lovelace-template-entity-row
hate to ask but am doing anyway. i am trying to get this to work with my dryer i get this message : Template warning: 'float' got invalid input 'unknown' when rendering template '{% if states("sensor.dryer_power")|float == 0 %} mdi:tumble-dryer-off {% else %} mdi:tumble-dryer {% endif %}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
i have a question, i have a code to monitor my solar panels.
- platform: rest
name: Zonnepanelendagelijks
unit_of_measurement: kWh
resource: http://10.10.11.69/pvi?rName=YieldStatus
value_template: "{{ value_json['yieldDaily'] }}"
device_class: energy
state_class: total_increasing #measurement
When i measure this i get a numer like this 8,6930552 kWh
what do i need to add to my code to only have the last two decimals
im new to home assistant so i really don't know
There's a pinned post about that in this channel
The last two decimals? Like 52 in your example? Or do you want to round it to 2 decimal precision?
Sure you want to keep 8.6, as this would round to 8.7
You could use {{ value_json[yieldDaily] | round(1) }}
The 1 is the number of decimals you want to round it to. So | round(1) will give 8.7 and | round (2) will return 8.69
wow
you are such a hero
i tried this code and it works!
was googling for like an hour
don't know if can ask you this to but also read someting else its a state and gives me the state false
but i would like to see turned on or off
can i put in someting like false = off
You can do something like {{ 'on' if a == b else 'off' }} or even {{ iif(a == b, 'on', 'off') }}
Well depends on what you want to achieve
{{ value_json[yieldDaily] | 'on' if a == b else 'off' }}
im reading this
- platform: rest
name: Zonnepanelenaanofuit
resource: http://10.10.11.69/pvi?rName=InverterStatus
value_template: "{{ value_json['workMode'] }}"
device_class: energy
state_class: measurement
how do you put code in a box like you do in this chat
and workmode is like 1 or 0
no a == b was just an example for a test which can result in either false or true
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
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
value_template: "{{ value_json['workMode'] | 'on' if false == else 'off' }}"
someting like that?
No {{ 'on' if value_json['workMode'] else 'off' }}
Or {{ iif(value_json['workMode'], 'on', 'off') }}
and how does it know what is on or off
i want to know how it works
sorry for being such a noob
I don't know what workMode returns, but according to your earlier posts I assumed it returned true or false
yeah thats correct
- platform: rest
name: Zonnepanelendagelijks
unit_of_measurement: kWh
resource: http://10.10.11.69/pvi?rName=YieldStatus
value_template: "{{ 'on' if value_json['workMode'] else 'off' }}"
device_class: energy
state_class: total_increasing #measurement
thats how i should put it in right
But it it returns 0 or 1 you need {{ 'on' if value_json['workMode'] == 1 else 'off' }} or {{ iif(value_json['workMode'] == 1, 'on', 'off') }}
This will return on or off as state, which makes no sense with the other settings, like state_class and unit_of_measurement
I'm off to bed, but if you have more questions somebody else can maybe answer them later on
HI, I'm trying to build a template sensor with some IFs encapluslated or with If .. AND if ... AND ... if
is this possible ?
Yes, either you want
{% if thingy and other_thingy and yet_another_thingy %}
{{ output }}
{% end if %}
or…
{% if thingy %}
{{ output }}
{% elseif other_thingy %}
{{ other_output }}
…
{% end if %}
Take your pick, indentation highly recommended.
great . wil try .. my objective is to build a Voice_alert_allowed .. having some conditions like after9Am before 10PM on workdays
so not to have the conditions repeated in several automations , it would jsut check the template
That’s a good idea. Make sure to use the Developer Tools to try it out as you go. And check the pins for links to various helpful docs.
Hi @silent seal it's gicing a TemplateSyntacError: tag name expected
'''
{% ((((as_timestamp(strptime((states('input_datetime.end_voice')), "%H:%M:%S"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /60) | int > 0) and (((as_timestamp(strptime((states('input_datetime.start_voice')), "%H:%M:%S"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /60) | int < 0 %} {{ true }} {% end if %}
Make sure to check the documentation for the correct format. The examples above are multi line templates. And if you’re outputting a value rather than a variable you won’t need to wrap it in {{ }}
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
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
well , even without the {{ }} its giving the TemplateSyntaxError: tag name expected
Well, there’s a lot of optimisation that could be done in your template. Let me find a laptop
First of all, make sure you are using a multiline template in the .yaml file.
i'm trying out in the template deve
{% if now() > today_at(states('input_datetime.end_voice')) and now() < today_at(states('input_datetime.end_voice')) %}
true
{% end if %}
That's some guesswork, I'm hoping your xyz_voice helpers are time only.
not really - i need to use the is_timestamp
Why?
it's a input number
But in your template you had input_datetime, those are not numbers
I'm comparing datetimes above, there's a very similar example in the docs...
There's no need to force returning True btw. You can just do something like
{{ x > y }}
``` which will return True or False
Yes, that's a very good point.
..don't know what i'm doing wrong
error : UndefinedError: 'input_datetime' is undefined
'''
{{ now() > today_at(input_datetime.start_voice) and now() < today_at(input_datetime.end_voice) }}
'''
Well my example is pseudocode, not intended to be perfect. It's intended to be put into developer tools and adjusted.
I updated the example to have states('input_datetime.xyz_voice') 😉
A backtick is `
great
now working
{{ now() > today_at( states('input_datetime.start_voice')) and now() < today_at( states('input_datetime.end_voice')) }}
Much simpler, good work
.. can it be like
{{ ( thingy and thingy ) or (thingy and thingy ) }}
?
I've diferent imput select for weekends
Yes, it can. But, I wouldn't do different inputs. I'd use automations to update your inputs to match the day
Then they can handle holidays, you taking a day off work, etc.
good point - i'm already using a workday template for my country holidays
I do that with my alarm clock. It updates every day
but I'm also using a workday offset , as sunday is weekend but kids go to bed as a workday
and on fridays they can be up until later
You can update the end_time at say midday, and the start_time at midnight
ok . but if the automations manages the input_time, i would loose the ability to change it on frontend ..
were you thinking in any performance tradeoff ?
Why would you lose the ability to change it?
Personally I find one variable that is set easier to debug than a series of conditions which depend on a variety of other conditions.
agreed , that's why i'm bulding this voice_alerts_allowed - to not repeat the code
i've got a fairly easy 101 question that I haven't had to do in years so I completely forgot, but how do I customize a binary sensor? I've got a shelly with an input switch for my garage door. ON means closed, OFF means open.. how do I change the output to reflect that?
I will give it a try 😉
I'm trying to create a sensor that shows all the current people home. I've found something online that works and I want to modify it, unfortunately my template skills are non-existent.
When all the people are home this template outputs 1, 2, 3, 4, 5 right now. I would love that it displays 1, 2, 3, 4 and 5. So the last , is always replaced by an and. Would someone be able to help me with this?
{{ person | selectattr('state','eq','on') | map(attribute='attributes.friendly_name') | list | join(', ') }} ```
{% set person = expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | selectattr('state','eq','on') | map(attribute='attributes.friendly_name') %}
{% set last_person = person | last %}
{{ person | reject(last_person) | list | join(', ') }} and {{ last_person }}
That might do it, untested and probably not an efficient approach though
Thanks! But like you expected: TypeError: 'generator' object is not reversible
Yeah, I thought that might be the case. If you pop back tomorrow you might catch someone better than myself at these things. I've been writing too much liquid (which is the Ruby version of Jinja) so my head is definitely in the wrong space
No problem! Thank you for the effort😁
(Tomorrow isn't that long away for context, it's 11pm here!)
Well there you go, just need someone more helpful than me to appear and you're all set! 😛
I will, thanks again 🙂
check the demo template in dev tools, and do something like: {% for light in expand('group.all_lights_only') |selectattr('state','eq','on') -%} {%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%} {{ light.name | lower }} {%- endfor %}. or with person: {% for person in states.person|selectattr('state','eq','home') %} {%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%} {{ person.name }} {%- endfor %} are home. play a bit with the output you'd like, maybe add a Phrase for the are/is, based on count
Hi all! Does anyone know why using a template in a service-call is not working when used with browser_mod/auto-entities? https://pastebin.com/RcmHfPmW
..well. It probably is a way to make it work, but it needs to be coded differently at least. Anyone know why and how?
Glance cards do not support templates.
use config.entity?
notify.mobile_app_{{ recipient }}```
ah...didn't even consider that 🙂 well, that can be changed easily
config.entity will still need to be string-manipulated and thus the same issue arises with the use of template...but if it's the glance-card's fault, I will solve it easily...just haven't considered it before @fossil venture meantioned it
Thank you for the suggestion! I don't know how to properly work with templates yet so not sure how this all combines but I'll try to take a look at it.
well...changed all instances of glance to entities and the template is still not working
it believes the service is '{% set recipient.....'
@silent seal maybe you could help on your suggested solution .. I'm not moving forward 😦
action:
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.start_voice
data:
time: "{% if is_state(\"binary_sensor.workday_sensor\" , 'on' %} 09:30:00 {% else %} 09:00:00 {% endif %}"
Why not use the choose action instead?
🙂 .. you are good 🙂 .. will try that
I am sorry, I only looked at the template, not the card config. you have to use the options the card provides. None of the stock HA cards will allow for that templating. So, you need to do as Tom suggested, use a custom card that does provide or allow templating in services.
maybe this helps: filter: include: - group: group.github_repos_in_use options: tap_action: action: more-info hold_action: | { 'action': 'url', "url_path": "{{state_attr(config.entity,'url')}}" } which is filled by the auto-entities card
but this is more of a #frontend-archived issue
well...I use custom:auto-entities...according to examples given by @charred dagger and others I found online, it should allow customization. Also regarding the templating, just adding a simple button-card to lovelace with the template I pasted, will work fine...as stated, the template works just fine in developer, in script and automations...just not in this nested card-setup I have going on here
that somehow makes me believe that using broweser_mod popup and nested cards has something to do with it...but I am too inexperienced to know and my three days of searching for solutions has gotten me nowhere 😦
as said, you should take it to #frontend-archived because all of the issues you mention are FE related. the template is not very challenging 😉 your card config is. Start with the smallest bit, and work your way up to the bigger picture
I'll do that...thanks for example code, feedback and nudge in the right direction!
worked like a charm .. tested 🙂
I've got it working! Is there any way to make the output in a custom order? Or at least reverse alphabetical?
{%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
{{ person.name }}
{%- endfor %}```
(1 to 5 are actually peoples names but removed them for discord)
using this loop, wont allow you to 'sort'. But I guess you could enter the names in a sorted order in the expand() listing 😉
Did that but it doesn't have any effect 😦
Using the other method I'm able to use sort(reverse = true) for reverse alphabetical order. Isn't there something possible like that with this?
Still, a custom order would be the best but no idea how to tacle that
Are the input_booleans in the order you want the people in?
There isn't really an order right now because I replaced all the real names with 1 to 5
So yes & no
But if you put them in the "right" order in your expand, does it work?
Nope
Well, darn it. Then you'll likely have to build the array manually.
And just checking, this doesn't help?
{% for person in expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | sort(reverse=true, attribute=="name") | selectattr('state','eq','on') %}
{%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
{{ person.name }}
{%- endfor %}
TemplateSyntaxError: invalid syntax for function call expression
Doesn't seem like it. Tried something similar but got errors also
Oh, interesting. You might have to do a
{% set people = expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | sort(reverse=true, attribute=="name") | selectattr('state','eq','on') %}
{% for person in people %}
...
I had a == in there 🤦♀️
{% for person in expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | sort(reverse=true, attribute="name") | selectattr('state','eq','on') %}
{%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
{{ person.name }}
{%- endfor %}
Yay!
Thanks a lot 🙂
No problem, sorry for all the failed attempts 🙂
Not a problem! I have something that works now
I will probably try a custom order in the future, but for now it's bedtime here, 2am
Thanks again 😁
1am for me, I should also sleep! 😂
Otherwise my bedroom will get cold, because past me programmed HA to assume I'm in bed by 1:30am as a sort of punishment if I'm not 🤪
morning... 😉 jut letting you know that the '{% for person in expand('group.all_inside_lights')' format does already order alphabetically, and adding 'sort(reverse=true, attribute="name")' does its job just fine. If it doesnt do that for listed items, you could throw them in a group and expand the group.
another way for the listing, without the loop: {% set lights_on = expand('group.all_inside_lights') |selectattr('state','eq','on')|map(attribute='name')|list %} {% if lights_on|length == 0 %} No lights on. Sleep well.. {% elif lights_on|length == 1 %} The {{lights_on[0]}} light is on. {% elif lights_on|length == 2 %} The {{lights_on[0]}} and {{lights_on[1]}} lights are on. {% else %} The {{lights_on[:-1]|join(', ')}}, and {{lights_on[-1]}} lights are on. {% endif %}
How do I make sure this template is evaluating all 3 entities? The developer tool says it's only listening to weather.home
"{{ (state_attr('weather.home','temperature')) | float(0) < 50 or (state_attr('weather.pirateweather','temperature')) | float(0) < 50 or (state_attr('weather.west_chester','temperature')) | float(0) < 50 }}"
Is the first part (with weather.home) already true? It doesn't evaluate the rest of the template then, so it won't know the entities involved. If the first part is false it will move to the next part
It is the other way around when you use and. It will stop when a part is false and continue to the next part when it is true
Perfect I was wondering if that was the case with and
I have an json rest array where there are multiple keys labeled the same and I am trying to pull all of the same select number of same named keys into the attribute of a rest sensor. I hope that doesn't sound confusing, anyone got any idea how? it would be like title[0], name[0], title[1], name[1], title[2], name[2] and i'm trying to keep them together in order
derp, think I skipped right over one of the examples in the doc that shows how it's done
description: ''
trigger:
- platform: template
value_template: >-
{{ ( now() - states('sensor.thegoat420_lastactive') |
as_datetime).total_seconds() >= 10 }}
condition: []
action:
- service: switch.toggle
what did I do wrong
sensor.thegoat420_lastactive 2022-03-23T14:16:12+00:00
this is how it looks like in DT, and some nice fellow wrote this template for me so that it would trigger after 10seconds of inactivity
for reference, the sensor is a last active sensor for windows detecting when a user made an input.
im basically trying to trigger a fan after pc goes 10sec idle
it will not trigger after 10 seconds of inactivity
it will trigger once per minute at most.
so it will vary between 10 seconds and 1 minute, depending on when the state changed
why, and also how do you know?
because that template will only update when sensor.thegoat420_lastactive updates, and on each minute because the template is using now()
np
ok i am confused as heck now, I thought I figured it out but the rest sensor only pulls the first matching attributes I list. I have a json that comes in like this https://www.codepile.net/pile/GBKOmaBo and I am only trying to fetch 3 items title, releasDate and network but I want all of them and to list them as attributes in order in a sensor. cannot for the life of figure out how to even start if the sensor only pulls one set
you're using a rest sensor?
yea
Hey guys is something wrong with the binary_sensors that relates to updates? UI shows me that i have 3 updates but on Dev tools the entities show that there is no update
sensors : https://imgur.com/a/D1JSjDF
ui : https://imgur.com/2nvvLrL
you're going to want to store the entire result in an attribute
I have resource defines and the attributes, for the value template i just put ok cause i don't want it dumped in the state field
how do you do that?
cause if i list anything in the attributes it seems to only pull the first matching set
well, actually, you'll have to create a rest sensor for each item because the first main item is a list
oh i was so afraid you were gonan say that
where is the json_attributes_template when you need it!
that dosen't even seem logical to even try and do, talking about a dynamic list that could be very short or very long
Yep, probably should start looking at custom integrations that handle this
can you change the device that's outputting it?
no
that codepaste i linked above is all i have to work with
10x
this makes a list of entity_ids: {% set hue_group = 'light.alarm' %} {% set ns = namespace(lights=[]) %} {%- for s in states.light if s.attributes.friendly_name in state_attr(hue_group,'lights') %} {% set ns.lights = ns.lights + [s.entity_id] %} {%- endfor %} {{ns.lights}} and I was trying to do that without namespace, but with a |selectattr('friendly_name','search' ,names) where names would be the 'state_attr(hue_group,'lights')|list'
that yields an empty list though..
what am I missing?
yes, because the hue integration light group has a names list as attribute, and not entity_id.
Not a list of entity_ids?
The first one works, the second doesn't?
And I assume {% set names = state_attr(hue_group, 'lights') %}?
Did you try selectattr('friendly_name', 'in', names)?
yes, yes, and let me try
{% set hue_group = 'light.alarm' %}
{% set names = state_attr(hue_group,'lights') %}
{{states.light|selectattr('friendly_name','in',names )
|map(attribute='entity_id')|list}}``` is []
if I try 'search', is says TypeError: unhashable type: 'set'
{{names}} returns {'Bedside table', 'Dining corner', 'World map', 'Silver cabinet', 'Kist', 'Flash alert', 'Corridor cabinet', 'Frontdoor', 'Kayon'} and thats why I first tested it with {% set names = state_attr(hue_group,'lights')|list %} which makes that a list
no thats the one thing the Hue api does not return, and the Hue integration brings the api into HA, 1 on 1, no manipulations allowed..... so we need to do that with templates in HA.
duh, I was focussing on the wrong error....: {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}} does it. I need 'name' not 'friendly_name'
isnt that odd, needing 2 different attributes in the 2 templates for the same selection?
btw Thomas, making a list and using 'in' works also: {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|list %} {{states.light|selectattr('name','in',names) |map(attribute='entity_id')|list}}
reason for all of this was Id like to create scene on the fly for that light group, without listing all the snapshop_entities verbosely. Seems to be allowed: - service: scene.create data: scene_id: before_flash_alert <<: &flash_entities snapshot_entities: > {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}}
even though it isn't documented we can use templates there... 😉 https://www.home-assistant.io/integrations/scene/#creating-scenes-on-the-fly
anyone have an idea on how to get the number of days of the current ´bimonthly period’ ?
I am able to get the current month but bimonthly makes it a little more difficult
friendly_name is an optional attribute that's mostly being phased out, and using name starts with the name that defaults to what the integration provides, or what the user specified in the UI, or the friendly_name attribute if it exists
What is the current bimonthly period? This month and the next one, this month and the previous one? Or just sets of two? 1 & 2, 3 & 4, 5 & 6, etc
It normally start January so January and February, etc
I thought about finding the bimonthly periods (1-6 periods) but after that?
And my bimonthly bill start somehow the 8 of the first month and finishes the 7 of the second month
Okay, now I know it is about a bill that explains it
Probably your contract started on the 8th.
Yeah and bill is generated the 8
So it starts every 8th day
I would use that as an offset
But that doesn't make a difference for the number of days though
Hold on I’m at work and here I’ll explain in a min why it’s needed
You needed the number of days in the bimonthly period right, if it starts on the 1st of the month or on the 8th that will be exactly the same
Periods are bimonthly but my provider count the number of days in that period for the offpeak rate, ex: the first 40 kwh are off peak but the way they do it is they count ex: 62 days x 40kwh, you get 2542 kWh at off peak then the remaining amount is at a peak rate
Does it make sense? I wrote that super quick
Yes, but again, the start date in the month is not relevant, unless is higher than 28 maybe
But I know a way, but I'm on mobile now, so if nobody else answers within an hour or so, I will provide something
I guess they count the days between the 8 day of the first and the 7th of the second month
Thanks so much, any help is appreciated
I’m just thinking of a logic way of doing it
{% for i in range(0,7) %}
{% set t = now() + timedelta(days=i) %}
{{ t }}
{% endfor %}
This template returns for me:
2022-03-23 19:16:00.001771+01:00
2022-03-24 19:16:00.001934+01:00
2022-03-25 19:16:00.002068+01:00
2022-03-26 19:16:00.002167+01:00
2022-03-27 19:16:00.002260+02:00
2022-03-28 19:16:00.002352+02:00
2022-03-29 19:16:00.002442+02:00
Why is the time zone until Saturday +01:00 and from Sunday goes to +02:00 ?
ok I didn't know that this sunday will be summer time 😛
daylight savings time
This should do it:
{% set m = now().month if now().day >= 8 else now().month - 1 %}
{% set m = 12 if m == 0 else m %}
{% set previous = (now().replace(month = m, day=1) - timedelta(days=1)).day %}
{% set current = 31 if m == 12 else (now().replace(month = m+1, day=1) - timedelta(days=1)).day %}
{% set next = 31 if m in [11, 12] else (now().replace(month = m+2, day=1) - timedelta(days=1)).day %}
{{ current + next if m is odd else previous + current }}
that won't work across years
why not?
But it doesn't, that's why I check if the month is 12.
(and 11 for the next month)
Small edit, as the check is not needed for previous
it will not use m+1 if m == 12 and it will also not use m+1 if m in [ 11, 12 ]
well, I see why I don't think it will work, you're not doing it the way to actually get the correct number of days in the month
you're assuming they are all 31
no, I assume it is 31 when it is december
ah, just a wierd way of doing it
And I also assume the next month will have 31 days when it is November of December
Well, the only month you don't know for sure is February 🙂
Smart, I made a sensor, ill check if this works rn, thanks for the time taken
But this is the best I can come up with, if you have a better approach I'm happy to be learned a lesson Petro 🙂
I love how coding is about being creative
Giving me 61 days
This should count from february 8 to april 7
And it should be 59 if I count right?
You said before it started in January, and then 2 months each time
Hold on
So it is March and April now
Oh, would it work the same if it didnt start in november? How do they calculate this
last bill was:
otherwise you only need to replace odd with even in the last line
doing it rn thanks
honestly, you are saving me a few hours, days of web scraping for this haha, I owe you a beer
no problem!
works perfect, I get 59 as counted
Hey guys! I have a template sensor running which resets itself after a reboot and then go back to the correct number. Issue is this is screwing up the values of my utility sensors. In this case its a gas meter and my gas usage is going from e.g. 0.3 kWh per hour to 2300 kWh Any idea how to keep the numbers after reboot?
probably your source sensor is not available yet, and you use float in your template, causing it to default to 0
add an availabilty_template to check if the source sensor is available to avoid this
@analog crag posted a code wall, it is moved here --> https://hastebin.com/meyacemeru
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Yes. "float" is included.
states('sensor.gasverbrauch') | float this part will default to 0 just after reboot
- platform: template
sensors:
gasverbrauch_kwh:
friendly_name: "Gasverbrauch"
unit_of_measurement: 'kWh'
device_class: "energy"
value_template: "{{ (2302 + states('sensor.gasverbrauch') | float *0.01 * 11.323 * 0.9444) | float | round (2) }}"
attribute_templates:
state_class: total_increasing`
availability_template: "{{ states('sensor.gasverbrauch') | is_number }}"
Ahhhh
this will do, btw, no need to cast a float to a float again
and if you would not have used the legacy template sensor format, you could have added the state_class without using attributes_template
TBH sometimes i dont know what i do 🙂 If it works i´m happy. I dont even know what float means at this point. I´m really far away from templating.
float stand for floating point number, which is basically a number with decimals
int stands for integer, which is a number without decimals
but the last line in my yaml code will make sure your template sensor is unavailable when the source sensor doesn't have a number as it's state
So basically when it's unavailable or not working for another reason
I see. So float and int are defining the type of number. So it´s not a command what to do with this number
I added it and trying it now 🙂
no, but states are always strings (so text) and you can't calculate with text. So you first have to convert it to a number, that is what | float does
got it
and the result of your calculation is already a number, so no need to convert it to a number again
Basically what you wrote before means i can remove the second | float?
yes, correct
Ok cool! Thanks a lot! Also: It worked 🙂 Thank you again! I´m really happy now!
🤷♂️ It just seems easier to use datetime objects instead of if statements
something like
{% set n = today_at().date() %}
{% set t = n.replace(day=8) %}
{% set ns = namespace(dates = [ t.replace(year=n.year - 1, month=12), t.replace(year=n.year + 1, month=2) ]) %}
{% for m in range(2, 14, 2) %}
{% set ns.dates = ns.dates + [ t.replace(month=m) ] %}
{% endfor %}
{% set end = ns.dates | sort | select('>=', n) | first %}
{% set start = ns.dates | sort | select('<=', n) | reverse | first %}
then you can get the cycle, days left, or days in
cylce: {{ (end - start).days }}
days in: {{ (n - start).days }}
days left: {{ (end - n).days }}
there's a ton of different ways to do this
it would be way easier/nicer if we could create dates and if jinja allowed single line for loops like python
Still a lot to learn.. I still get confused by range. The 14 part in this case. It's probably because count starts at 0
And I tested it, 13 would also have worked 🙂
the 2 at the end skips every 2
range(start, end, increment)
Yes, but range(0,3) | list results in [0, 1, 2] and my brain expects [0, 1, 2, 3]
so end kinda seems to be the number of values if start would be 0
Ah yes, start, number to include, rather than start and end
range(6,7) | list results in [ 6 ], and range(6,6) | list in []. So start is as I would expect, while end is not
This is nice!
hi everyone. I want to make a template to close my garage door if left open past midnight. It work, but my trigger is time 00:00 and condition that garage door is open.
I worry that if for whatever reason HA is not available at midnight, when it comes back online (say 00:05), it will not trigger the automation.
What is best way to setup an automation so it triggers any time between say midnight and 5am?
That just sounds like an automation, not a template
Anyway, add a trigger for homeassistant.start and a condition for the time being after midnight
thanks @inner mesa . Was asking in a template as there is no trigger for between 2 times, like there is for condition. But will re-ask in automation, as there may be a time when we come home after midnight and forget to close the garage.
I'm a little confused here... I need a template so that a light turns off if a door was closed, but only if it's been open for at least 1 min. How do I do this? The template is the condition for the automation I have, which is complete, except for I need a template.
Point is that you don't need that kind of trigger, and I do what I described in a number of places. One trigger for a specific time, and others for HA restart, automations reloaded, etc. Then a condition to restrict the times, which as you say, allows for a range
https://bpa.st/EE3Q My automation seems to have stopped working when i removed the "choice" part. The error i'm getting is "Template variable warning: 'dict object' has no attribute 'state' when rendering '{{ value_json.state }}'". I'm unable to run it through dev tools -> templates since it has a trigger. I can't really find anything to do with vlue_json.state, any ideas?
Are you sure it is that automation that is causing the error?
Hi all. Stilo struggling with getting a template to work for a service call from a nested card, but think I am getting closer. In a standard unnested card, I can use service: >{% varmanupulation %}{{ result }}, but in nested card this template is not evaluated. I have however gotten progress using the [[[ var myVar = blah.bleh; return notify.${myVar}; ]]]
Using the first example with curly brackets, I can split my variable string (device_tracker.phone) with string.split(".")[1] to return only (phone)...how do I do this when using [[[ string.MANIPULATE ]]]
Might be a stupid question this, but would really appreciate a nudge here..curly brackets version is YAML code...and [[[ is javascript?
I have error and warning message in the logs for my template sensor. I dont know how I can solve this.
@olive escarp posted a code wall, it is moved here --> https://hastebin.com/uguxefatej
If someone can help it is much appreciated
well it started showing up after i poked at it so i simply assume it's that one. Also it's not working which is another reason i'm thinking that might be it
Okay nevermind i guess. It's not that one. It was due to my zigbee dongle disconnecting....
What is the warning?
And what does this sensor display? I have a similar sensor for my washing machien, and it displays 0:29:00. You can not convert that to a timestamp
If the same applies to your sensor, you can use:
{% set h, m, s = (states('sensor.wasmachine_remain_time')).split(':') %}
{% set min = m ~ ' minuut' if m == '1' else m ~ ' minuten' %}
{{ (h ~ ' uur en ' if h != '0') ~ min }}
Template warning: 'timestamp_custom' got invalid input 'None' when rendering template '{{ as_timestamp(states('sensor.oneplus_arno_next_alarm')) | timestamp_custom('%-H:%M' ,false) }}' but no default was specified. Currently 'timestamp_custom' will return 'None', however this template will fail to render in Home Assistant core 2022.1
That is not related to the code you posted above
it pays to actually read the error, it includes the template that has the error
sorry wrong warning/error
the other templates do not have a default specified for as_timestamp
see the 4th pin in the pins list
Template warning: 'as_timestamp' got invalid input 'unavailable' when rendering template '{{ (as_timestamp(states('sensor.wasmachine_remaining_program_time')) - as_timestamp(utcnow())) | timestamp_custom('%-H:%M' ,false) }}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2022.1
Yep, see the 4th pin in the pins list
But he is using an availability template which should avoid that I guess..
availability: "{{ states('sensor.wasmachine_remaining_program_time') != 'unavailable' }}"
Yah, I think that PR is in now
Ok it is working but i was looking to solve the error/warnings in my log
If the PR solves it that would be great
I did read thru the 4th pin already but it is hard for me to convert the example to my use case
how so? Did you identify the function that's being used that needs the default? If yes, follow the number of comma's and add the default within the ()
if you don't see a comma, that means you only are supplying 1 argument
i.e. you have to add the comma and place the default after the 1st argument
that post is meant to teach you how to add it, not spoon feed you the answer with a copy/paste
function(argument) -> function(argument, default=...)
@olive escarp if you're still struggling, post your attempts and I'll help you fix it.
Oh, I thought that was already fixed a while ago
You mean that the state templates are still rendered when the availability template returns false right?
There was a PR awhile ago to make it not render
I have no idea if it passed and was put in
The availability is working correct
i made a mistake
by heving the old way without the availability and the new way with availabilty
old way being sensor and then platform:template
they both use the same code, the new way just has more configuration avialable
so they will be the same
sorry to have bothered you guys and thanks for the help! although i still not solve it by using the pinned message
the pinned message tries to teach you. If you don't have the "want" to learn how to write a function, you won't like that post. It's hit or miss with everyone.
Hello
I am trying to fetch informations about the actual connected bluetooth device in companion
i try to create a template but i always get a error.
sensor:
- platform: template
sensors:
welches_auto:
friendly_name: "welches Auto"
value.template: "{{ state_attr('sensor.op7_bluetooth_connection','connected_paired_devices') % }}"
any help is welcome
You have a % inside your template
i removed it
and still get : Invalid config for [sensor.template]: [value.template] is an invalid option for [sensor.template]. Check: sensor.template->sensors->welches_auto->value.template. (See ?, line ?).
your yaml is incorrectly spaced
friendly_name and welches_auto should not be in line
same with value.template which should be value_template
thanks mater
mate
after changing value.template -> value_template it seems to work
works like a charm 🙂
Hey guys , i have a sensors (from socket) that counts total energy for a device
in history i can see increasing value everyday
what would be the syntax for braking it into monthly usage ?
use a utility_sensor
looking on a tutorial right now, will update
utility_meter:
electricity_daily_khw:
source: sensor.electricity_energy_kwh
cycle: daily
electricity_monthly_khw:
source: sensor.electricity_energy_kwh
cycle: monthly
like this ?
Looks fine I guess, please format as code next time. And for further questions on this #integrations-archived is the proper channel
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
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
was always curios how to do it, thanks will use from now on
@bronze zinc figured I'd bring the conversation over here since making trigger template sensors is an HA thing rather then a node red one. What you want is essentially this example: https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-binary-sensor. Essentially what happens in this example is when my_event is fired this sensor becomes on and then turns off 5 minutes later. Unless my_event is fired again in which case the 5 min clock restarts.
So to take it your example, by listening to a sensor created like this instead of to the unifi camera events directly you get one state change to on when someone enters the area and then one to off when no one has been detected for 5 minutes and nothing in between. Exactly what you want I believe.
The only thing I'm not sure of is what exactly is your trigger. I don't really know how the unifi cameras work so I'm not sure. I assume its an event? You can use anything in this page to trigger your sensor though: https://www.home-assistant.io/docs/automation/trigger/
ty, I will read through it all when I get home
Hello everyone, i try to get a api from a local device integrated but i cant get it to work.
The call looks like that http://192.168.0.102/INCLUDE/api.cgi?jsonnode=1&jsonparam=I
When i enter the url in the webbrowser or reqbin.com and authenticate with auth-http i get a valid answer that looks like this:
@swift lance posted a code wall, it is moved here --> https://hastebin.com/cavajeyemi
https://pastebin.com/cudUGu5K sorry Mr bot
with {{ value_json.Data.Inputs.0.Value.Value}} in the template dev-tool i get the correct number, e.g 14.1, but i dont know how to use this in a template.
Any help would be appreciated, thanks
this is the part in configuration.yaml
https://pastebin.com/T04tLxHY
(foramtting may be wrong bc i copied them out)
Put this in your rest sensor {{ value_json.Data.Inputs.0.Value.Value }} and you should get 14.1 there. Don't know what you want to do with the template sensor after that
so i want to have multiple sensors from one api call (max 1 per 60s) and in the restfulsensor doc i read that we use json_attributes and template to create multiple attributes from one result.
I added
value_template: "OK"
json_attributes:
- 1
- 2
- 3
- 4
- ... till 14
like here https://www.home-assistant.io/integrations/sensor.rest#fetch-multiple-json-attributes-and-present-them-as-values fairly at the bottom with the
sensor:
- platform: rest
name: room_sensors
resource: http://<address_to_rest_service>
json_attributes:- bedroom1
- bedroom2
- bedroom3
example
i am confused if my json_attributes are correct from 1-14 because the api returns Number : 1 instead of Number1
and if correct how to use this in the template sensor value_template
You can't do that, you can only use dictionary keys as attributes in a rest sensor
So use this:
value_template: "OK"
json_attributes_path: "$.Data"
json_attributes:
- Inputs
Then you do need a template sensor to get the right data out of your rest sensor
attributes:
value_1: "{{ state_attr('sensor.your_rest_sensor', 'Inputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "
value_2: "{{ state_attr('sensor.your_rest_sensor', 'Inputs') | selectattr('Number', 'eq', 2) | map(attribute='Value.Value') | join }} "
so the Inputs work and i get a attribute list with sensor.cmi
Now to get one temperature i use this template sensor
template:
- sensor:
- name: Temperatur Kollektor West
unit_of_measurement: '°C'
attributes:
value_1: "{{ state_attr('sensor.cmi', 'Inputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "
But this spits out an error
Invalid config for [template]: required key not provided @ data['sensor'][0]['state']. Got None. (See /config/configuration.yaml, line 201).
@swift lance posted a code wall, it is moved here --> https://hastebin.com/vufaladufa
okay, so i used
sensor:
- platform: template
instead of
template:
- sensor:
Had to change attributes: to value_template: because it said i cant use attributes with a template sensor.
Tahnk you very much @marble jackal, without your help i couldnt have done it
this is my sensor now:
sensor:
- platform: template
sensors:
temp_kollektor_west:
unique_id: sensor.temp_kollektor_west
device_class: temperature
unit_of_measurement: '°C'
value_template: "{{ state_attr('sensor.cmi', 'Inputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "
Ah sure, with the lecacy template sensor format it is attribute_templates
https://www.home-assistant.io/integrations/template/#attribute_templates
hi kind friends, should this be working?
trigger: platform: template value_template: "{{(states.sensor.cycle_total_kwh.state | float) > (states.cycle_offpeak_kwh.state | float)}}"
Somehow I can not get it to trgger even if sensor.cycle_total_kwh is greater, less, than the other sensor
So bear in mind how template type triggers work:
Template triggers work by evaluating a template when any of the recognized entities change state. The trigger will fire if the state change caused the template to render ‘true’ (a non-zero number or any of the strings true, yes, on, enable) when it was previously ‘false’ (anything else).
So the way it should be working is this:
- Should never trigger if
cycle_total_kwh <= cycle_offpeak_kwh - Should only trigger if a state change makes
cycle_total_kwh > cycle_offpeak_kwhtrue but before that state change this was truecycle_total_kwh <= cycle_offpeak_kwh
It's not as simple as saying it will trigger if one sensor is greater then the other, it should specifically be triggering on the transition only. When the one was not greater then the other and then becomes greater then the other.
Oh so to be triggered it has to be false before it can check if the new state is true?
Yes exactly
thank you! so manually triggering the automation wont change anything
Oh, definitely not. Manually triggering an automation ignores the trigger entirely, it just executes the steps as a script
no that should not be working. states.cycle_offpeak_kwh.state is an invalid state object. You should be using the states method anyways
ask yourself: is cycle_offpeak_kwh a valid entity_id?
sensor.cycle_offpeak_kwh is valid
is that cycle_offpeak_kwh?
yes oh
pretty sure sensor.cycle_offpeak_kwh is not cycle_offpeak_kwh
this is one of the many reasons to stick to the states method over using the states object.
Both are the same, I just did something wrong there
I made a custom sensor doing a calculation
they are not the same
which is sensor.cycle_offpeak_kwh
are you completely glancing over the missing word sensor.?
so should it be states.sensor.cycle_offp
Just noticed that I misstyped it
damn
I did so many do and undo that I probably deleted it
that's why you should use the template editor 😉
It even does autocomplete now
As long as you start with the right thing, which, well, wouldn't have helped you here other than to point out that you were doing the wrong thing
useful
whoops, missed that lol
This will definitely throw errors in your log just after reboot, at least with states('sensor.whatever') you only get warnings (until 2022.1 finally gets shipped 😉 )
If you want to avoid that totally, and be sure the right values are used, use something like:
{% set a, b = states('sensor.whale'), states('sensor.petunia') %}
{{ a | is_number and b | is_number and a | float > b | float }}
@green adder posted a code wall, it is moved here --> https://hastebin.com/waxacizisa
I am struggling to understand why my unique_id values aren't working for a template I am writing. I am trying to make a little binary sensor to combine two other values (The logic here isn't important I can figure that out). I have this code under template in my config:
- binary_sensor:
- name: "Test - Vhia and Nick combined presence"
unique_id: "person_groups_presence_primary"
state: >
... some logic here ...
However the entity in the UI is always called: binary_sensor.vhia_and_nick_combined_presence which looks like a slugified version of the old name (which was Vhia and Nick combined presence). I have tried deleting the entity in the UI but it just appears again immediately with the old name. What am I doing wrong here?
Ideally I would also like to have the block have a unique_id prefix so I don't have to make sure they are all the same for each item in the list but I was struggling to get that to work too
anyone seen this error before?2022-03-25 17:39:32 ERROR (MainThread) [homeassistant.components.template.template_entity] Error validating template result 'unknown' from template 'Template("{{states('sensor.alarm_panel_icon')}}")' for attribute '_attr_icon' in entity switch.security_system validation message 'contains non-whitespace: unknown'
my switch:```
- platform: template
switches:
security_system:
unique_id: switch_security_system
friendly_name: Security system
value_template: >
{{states('alarm_control_panel.ha_rpi4_alarm') in
['armed_away','armed_home','armed_night']}}
icon_template: >
{{states('sensor.alarm_panel_icon')}}```
and the icon_template's entity sensor.alarm_panel_icon: ```
- unique_id: alarm_panel_icon
state: >
{% set panel = states('alarm_control_panel.ha_rpi4_alarm') %}
{% set mapper = {'disarmed':'mdi:shield-check',
'armed_away':'mdi:shield-lock',
'armed_custom_bypass':'mdi:security',
'armed_home':'mdi:shield-home',
'armed_night':'mdi:shield-home',
'arming':'mdi:shield-outline',
'triggered':'mdi:bell-alert'} %}
{{mapper[panel] if panel and panel in mapper else 'mdi:shield-check'}}
its really odd, because the icon it showing just fine, maybe a race condition of sorts?
Maybe you could try moving the check up into where you use the icon instead of or as well as inside the alarm_panel_icon
unique_id doesn't drive the entity_id unless name is missing
and if name is missing the entity_id will be domain.template_<unique_id>
ah I see thanks! Is there a way to specify both entity_id and the human readable name or do I just pick between the two?
You can add friendly_name to attributes
have it slugify the name, and then use the real friendly_name in the attributes
or just adjust it afterwards in the UI
or customize it
in yaml
Yeah, perhaps your alarm_panel_icon hasn't run the first time when it goes to calculate the security_system for the first time. Then it updates once alarm_panel_icon runs and this is why the icon works. I am not sure though. Maybe someone who knows more about this than me can figure it out
will try that, guard the icon template in the template switch.
{{mapper.get(panel, 'mdi:shield-check')}}
The error you're getting is because states('sensor.alarm_panel_icon') isn't known at startup and it isn't an icon.
also, mdi: is common on all those, just move that out
yeah thats easy...
Ok so to get both in yaml I can:
- set
unique_idto control theentity_id - set
friendly_nameinattributes( https://www.home-assistant.io/integrations/template#attributes)
Is that correct?
that might actually solve the error too
let me guard the states('sensor.alarm_panel_icon')
ok I'll use {% set panel = states('alarm_control_panel.ha_rpi4_alarm') %} {% set mapper = {'disarmed':'shield-check', 'armed_away':'shield-lock', 'armed_custom_bypass':'security', 'armed_home':'shield-home', 'armed_night':'shield-home', 'arming':'shield-outline', 'triggered':'bell-alert'} %} mdi:{{mapper.get(panel, 'shield-check')}} first and see what restart gives using the get() in the switch
no matter what, it's now in your entity registry, so just update entity_id in the UI and be done with it
no
put the mdi: in the icon_template
then it would become mdi:unknown, which probably won't fail but won't produce an icon
or just safeguard the icon_template
o right. hmm. I use the sensor.alarm_panel_icon elsewhere too,
then just safeguard it
ok, let my try a few things. thx.
@mighty ledge: Where would I find the source for the docs at https://www.home-assistant.io/integrations/template. I wanted to add a note about the entity_id because that wasn't clear to me
Hi I think i have a working template in developer tools templates but it's not working when i put it in a file called sling.yaml i'm trying to create an offset to a calendar event
is there a pastebin I can use ?
this is the version i'm writing to sling.yaml https://www.codepile.net/pile/ZPj7LVY5
looking at wrong sensor , thanks
There are buttons at the bottom of the page to submit an edit or suggested chagne
Thanks!
this is how entity_id's work in all of home assistant when unique_id and name are an option. I doubt any change you make will go through based on that.
Could we at least link to where that is described from the field in the template docs then?
It's just how the onboarding process works for an entity when name and/or unique_id are supplied
it isn't described anywhere
so that page would need to be made, and then linked to from all the places that use unique_id and name
you're welcome to go down that path if you want
good afternoon. Is there anyway to use a template as a trigger? for example if i wanted any input_boolean "off" to "on" to trigger an automation and have the action from the automation also use a template?
tysm i'm so stupid i missed it.
That won't work for your use case
no matter what, if you have multiple booleans that turn on, the 2nd one will not trigger the automation.
templates need to be false -> true in order to trigger
if it's already true, it won't trigger again
nope that doesn't work either
Create a template sensor with the count of the booleans which are on as state, and a list with the booleans which are on as attribute
i think i see where ur going with this
Trigger on state change, and get the one which triggered it by comparing the from_ state and to_state is the attribute
but it will also trigger from on to off in that case correct?
Add a condition that the to_state must be higher than the from_state
Keep in mind a template sensor like that will only update 1 time per second at most
Also if you use a group and expand?
so i have a related question but not a template question.... is there a way to use an array as a trigger instead of listing each as its own trigger?
Nope, no throttle on expanded groups
I have updated my config to be:
template:
- unique_id: "person_presence_"
sensor:
- unique_id: "test"
attributes:
friendly_name: "Test Presence"
state: >
... logic here ...
which is much closer to what I want. However now have the entity coming out as: sensor.template_person_presence_test. Where does this template_ come from and can I remove it? I tried to have a quick look in components/template/sensor.py but I couldn't easily find where it was being added.
Already told you
right but can I remove that?
Yes, through the ui
but not in yaml?
Already told you that too. You have to supply all three
Name, unique ID, friendly name. Entity Id will be a slugfied name.
That would mean I can't use the prefixing logic if I use name though right? because if name is provided then the unique_id's are not used at all in entity_id generation. Is there a way to get both the prefixing logic and not having it magically add strings to the entity_id?
What?
Just make the name and the unique ID exactly the same. Then use whatever you really want the name to be in the UI the friendly name
So I can use unique_id at the outer layer to prefix all my entities with something (eg in my example above I use "person_presence_"). Then inside my individual items I have just the suffix. If I use name instead then doesn't that mean I need to put the whole name and copy/paste the prefix a bunch of times
Also I would really like to avoid changing things in the UI. I am going to have quite a lot of these things once I get my test one working so I would rather keep it in the config
I think you don’t understand what unique ID does. It’s for the system to know what it is not for the user. A unique ID will be unique across the entire system. Each integration attaches a unique phrase to each unique ID that is unknown to the user
The whole point of adding a unique ID so that you can use it through the UI
So if you don’t want to edit things through the UI, don’t add a unique ID
ok, I will just set name + friendly_name. There is no logic to do the same kind of prefixing that you can with unique_id (both at the top layer and per sensor) for name in the config though right?
I don’t understand what you mean with prefixing. What’s the point?
It literally does nothing
it just means I don't have to copy/paste the entity prefix over and over and possibly typo it
why does it exist for unique_id if it does nothing?
What the hell do you mean entity prefix
This, petro #templates-archived message
I have logical groups of entities which I would like to all have a particular prefix eg for all my people presence ones I want person_presence_<person name>. With unique_id I can specify the person_presence_ once and just use <name> inside each sensor (with unique_id). I was just asking if there was a way to do the same with the entity_id generation
which is why using unique_id seemed appealing for getting the entity_ids that I wanted. but as you said it adds template_ which seems unavoidable
Just use name instead with friendly name
Unique_id is for the system
i feel like htis is beating a dead horse, so your options are:
I understand your comments and what my options are
- name: my_entity_id
unique_id: some_prefix_my_entity_id
attributes:
friendly_name: Some really friendly name
or
- name: some_prefix_my_entity_id
attributes:
friendly_name: Some really friendly name
- will give you
<domain>.my_entity_id2 will give you<domain>.some_prefix_my_entity_id
I was asking if there was something like:
- name: "my_entity_id_prefix_"
sensor:
- name: "suffix"
attributes:
friendly_name: Some really friendly name
That would give me an entity id of my_entity_id_preifx_suffix in the same way that you can for unique_ids
but it seems like the answer is no
i'm not sure what you're expecting out of that
It's just to avoid copy/pasting the same constant in my config multiple times
are you just trying to not repeat the prefix? That isn't possible in all of yaml
how is this yaml specific? The python code reads the same structure for unique_id and is able to combine them with: https://github.com/home-assistant/core/blob/dev/homeassistant/components/template/sensor.py#L147-L148 why could you have the same logic for entity_id?
It just seemed like a cute feature for unique_id so I wondered if the code did the same for entity
that's the unique_id adding the integration prefix for the system.
it's only built into the unique_id, so that the ID is unique across the system incase someone uses the same unqiue_id on 2 separate integrations
it's not a cute feature, unique_id is meant for the system, not users
What you're describing a want for can be done through a device in the UI
but template sensors don't have a device, so you don't get those benefits
If you're referring to the unique_id assigned to the root template level, that is unique to template sensors. If you look in the configuration variables, you'll see that name does not exist at that level. FYI, this would have gone alot smoother if you used the terminology in the documentation instead of talking about a prefix that's in the description of a field.
or a link to what you're talking about would have helped too. Then I wouldn't have gotten frustrated with you repeating this prefix talk without an example.
I guess you did mention it, but you used "outer layer". Sorry.
Yeah, I wasn't sure how to name the two different unique_id fields properly. I am used to python, jinja etc but I don't know all the HA terms well yet
I don’t think there is a proper term for that, I should have picked up on it but I was distracted with other things.
Recipe for frustration. Anyways, sorry. And no, what you want doesn’t exist but it could exist.
no problem, it happens. Thanks for the help anyway, with the descriptions of the 3 fields I now have the entity_ids that I want and I have unset unique_id so the UI isn't allowed to change them (which is also what I want)
Guess this question got lost, but depending on the trigger type you can. You can list multiple entities for a state trigger for example
👍👍
if you really wanted a unique string for every possible combination of an input boolean being on, this would work
{{ states.input_boolean | map(attribute='state') | map(attribute='1') | list | join }}
Appreciate it...just so I understand how does this work?
it maps all input boolean states into a list, then it pulls the second character and makes a string. second character in 'on' is n, second char in off is 'f'. so you'll end up with nnnfnnfnfnnfn
Oh very cool!
Don't you get the same result without casting it to a list first?
I don't remember if join works on a generator
Just tested in dev tools, it does 😀
now just need to commit that to memory
I am building a sensor which abstracts over a manual override, the normal home/away tracking and possibly using other sources to determine if someone is home/away. So far I have this sensor (with some unimportant fields snipped):
- sensor:
- name: "person_nick"
state: >
{% if is_state("input_select.nick_status_override", "Auto") %}
{{ states("person.nick_davies") }}
{% else %}
{{ states("input_select.nick_status_override") }}
{% endif %}
Is there a nice way I can avoid copy/pasting the logic for every person I want to track? Currently they are all the same. I can generate the config file if necessary but I wanted to check if HA already had a way of simplifying this
I also have a similar problem with the input_selects I am using for the override eg I do:
input_select:
nick_status_override:
options: &status_override_options
- Auto
- Unknown
- Home
- Away
vhia_status_override:
options: *status_override_options
... more people here ...
well, this must be it then, no more error: icon_template: > {% if states('sensor.alarm_panel_icon') not in ['unknown','unavailable'] %} {{states('sensor.alarm_panel_icon')}} {% else %} mdi:shield-check {% endif %} feels somewhat clunky, but it gets the job done..
have anyone success with combinde a IKEA curtan, an control it from google home ? (Instead of only using voice )
Im not the biggest code writer 😦
Is there a way to raise an error in a template? I have a condition I know is an invalid config and I would like to crash and tell the user
No, but you can have it output something that you can look for and write a log with a service call. There's no crashing
is there a template way of creating a temperature sensor with the temperature from an hour ago? I know there's a statistics platform, but I'm only just setting up HA and just figuring things out. Its for working our a temperature trend, ie, if 20 an hour ago and 19 now, then the trajectory is negative....and it means I turn heating on earlier than just letting it get to the min value
hmm would it be? https://www.home-assistant.io/integrations/derivative/
ok, that sounds like it might do it all in one thing....thanks I'll have a try
stupidly at the same time, I had a triggered template sensor in my configuration.yaml....
I want to move it to my sensors.yaml, but can'y quite figure out the levels
commented out now, but in configuration.yaml it was:
@untold zodiac posted a code wall, it is moved here --> https://hastebin.com/jugesucaqe
You can't put that in sensors.yaml
has to stay in configuration.yaml?
You could create a templates.yaml and !include that
hi, can I use comments within an array within an template?
set stuff = ["blah", #comment
"blub", #comment
"ding" #comment]
@lyric sun No, you can only use comments outside expressions or statements.
And Jinja comments look like this {# This is a comment #}
You could do this:
{% set blah = 6 %} {# Some comment #}
{% set bluh = 6 %} {# Another comment #}
{% set stuff = [ blah, bluh ] %}
Hey guys, I have this as a sensor attribute data last_goal: 'Elias Lindholm (32) Wrist Shot, assists: Matthew Tkachuk (48), Johnny Gaudreau (55)' I need to just isolate the first name out, Elias Lindholm everything else after and including the (32) I don't need, How could i go about this properly?
last_goal: 'Michael Carcone (1) Wrist Shot, assists: none'
another example.
.split(' (')[0] should give what you want
ty @marble jackal I will try that.
Awesome that worked!
Ty sir!
No problem. It splits the string on ( and takes the first part
Yup kinda understood it, lol.
Now i can have audio callouts for the last scorer for my NHL scoreboard.
you've levelled up 😉
🎉
Trying to set a input_datetime a year into the future, so as to automate Earth Hour procedures; this funky fresh templating isn't doing the trick; any suggestions?
{{ strptime(states('input_datetime.earth_hour_week'), '%Y-%m-%d %H:%:M:%S') + relativedelta(years=1) }}
Maybe this:
{% set d = as_datetime(states('input_datetime.earth_hour_week')) %}
{{ d.replace(year=d.year + 1) }}
Woah, that did it!
Thank you 😊
I have a volume level helper and a service that sends a keypress of 'volume up/down' : 100 max volume, with a step of 2 so that's 50 keypresses total range, is there a way for a template to send the required amount of keypresses according to how I move the slider?
hmm, it would be a template to add/subtract the difference to 'now' and divide that by two, no?
Yes, calculate the difference between the old value and the new value and divide that by 2
how? do you know the template? presses are switch.thegoat420_volumedown and switch.thegoat420_volumeup, sensor is input_number.volume_level
I assume you use an automation with the input_number as trigger?
yes
Why wouldn’t you just use the state of the slider? Auh, key presses 😉
Something like this? https://www.toptal.com/developers/hastebin/ifomutasus.yaml
I have a question regarding using variables in templates and scripts. I've already read the appropriate site but I'm not quite sure on some things.
The example in ( https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts ) shows
data: title: "State change" message: "The light is on!"
and the same but with {{}} in the title and message. My question here is does it have to be "title" and "message" or can it be something else?
Can be whatever you want
Thank you. I've now been playing with this and found that out also 😄
How would I put the variable "streamer" here **Followers**: {{state_attr('sensor.{{streamer}}','followers')}} using this will just ouput None ? I think it tries to search for {{streamer}} but there is none called that way. Yes I recieve the variable when using url: https://www.twitch.tv/{{streamer}}
ah okay I might just need to add two +
Nope doesnt seem to work
ok thanks, I wanted to also generate comments for every line in that array:
https://community.home-assistant.io/t/play-random-album-of-artist-x-on-specific-spotify-connect-device/209473/4?u=thex
but I think its even worse there as its script within a template within a script
You can't add comments with this I guess. You could create a list with a dictionary per link in which you both provide the title and the Spotify URL
mhh ok but that complicates the script, guess it's fine for now
Not sure if I am right here. Is there a way with a sensor template to only set a new value if the sensor is not already having a data for the current day?
I suppose, based on the last_changed property of the template sensor
{{ iif (states.sensor.whatever.last_changed.date() != now().date(), "some_value", states('sensor.whatever')) }}
Maybe I can reframe my question. There is a plug-in and it is getting data from my heating. Whenever I restart HA this plug-in is getting the data and storing it. The value is the same on every request cause it gives the energy consumption of the last whole day. It is in kWh. In a Template Sensor I get that data and divide it by 10 to roughly convert it to m3. What happens now is that also for this template sensor it is having multiple states that day (all with the same value). And the HA energy dashboard calculates all these values and that is wrong. So what I tried to do is that I only store this data in the template sensor if the template sensor is not having data from this day. How could that be solved best?
what I provided seems fine for that
What happens if I had three states on the source sensor and the first was „unavailable“. Then it would lead to the fact that the next state with valid data would not be processed, right?
you can add and states('sensor.whatever') != 'unavailable'
or base the check on the source sensor
Trying to use TheFes's solution to my earth hour issue but having trouble using it in an automation.
- service: input_datetime.set_datetime
'{% set d = as_datetime(states('input_datetime.earth_hour_week')) %}'
data:
datetime: '{{ d.replace(year=d.year + 1) }}'
entity_id: input_datetime.earth_hour_week
Step Details section says: Error: Template rendered invalid service: input_datetime.set_datetime ''
that's bad syntax
you can't set a variable in one template and then use it in another, but there's no reason to do it that way
without paying attention to what you're trying to do:
- service: input_datetime.set_datetime
data:
datetime: >-
{% set d = as_datetime(states('input_datetime.earth_hour_week')) %}
{{ d.replace(year=d.year + 1) }}
entity_id: input_datetime.earth_hour_week
{{ state_attr('weather.kgrr_hourly', forecast')[0].precipitation_probability }}
I finally got this to work in the template editor and it gives me the output I want, but struggling to integrate it into home assistant. How do I go about using this data? I've tried to create a sensor in my configuration.yaml but I'm lost
"integrate" it how? What do you actually want to do?
do you want a template sensor with that as the value?
I've tried to create a sensor in my configuration.yaml but I'm lost
Perhaps sharing what you've done will help
I just want to be able to use that data I'm getting somehow. If I could turn that data into an entity or something.
`sensor:
- platform: template
sensors:
kgrr_hourly:
value_template: "{{ state_attr('weather.kgrr_hourly', forecast')[0].precipitation_probability }}"
friendly_name: Weather Hourly Rain
unit_of_measurement: '%'`
this was one of the things I tried in my config.yaml. Been googling like crazy and can't find the right way to get that working
Or if you know a better way for me to use this data in an automation 😵💫
the only thing wrong with what you posted is that you're missing a quote next to forecast
if you fix that and it's still not working, then please be more specific about what's not working the way you would like
I feel incredibly dumb now thank you rob it’s working now 🤦🏻♂️
Hey all. I am fairly new to all of this, so please tell me if this is a bad way to go about this.
I am trying to set up presence detection based on if the HA app detects if my phone is connected to a certain wifi access point. I have the HA android app all set up and can see it is showing the wifi ID.
I moved on to create a template and while no syntax is being flagged as incorrect, I am not sure it is working, as my presence is still marked as not_home in HA.
configuration.yaml is:
# Text to speech
tts:
- platform: google_translate
automation: !include automations.yaml
script: !include scripts.yaml
group: !include groups.yaml
template: !include templates.yaml```
and templates.yaml
```sensors:
pixel_5_home:
state: >-
{% if states('sensor.pixel_5_wifi_connection') == "WIFI" %}
home
{% else %}
not_home
{% endif %}
name: 'Pixel 5 Home (SSID = WIFI)'```
@tardy basin posted a code wall, it is moved here --> https://hastebin.com/eqaxoyumoz
The HAss companion app has a device tracker. Why are you not using that?
I believe I have that set up? I have "WiFi Connection" enabled under "Sensors" in the companion app
Unless that is something different
Ohh the GPS.
The GPS on my device consistently is wrong so I didnt want to soley rely on that. When I did get it working and set my home location to where it was saying I was, it still had me as not_home.
Are you allowing tracking permissions.
@tardy basin , I would also use the ssid sensor instead of the connection status, as every time you are connected to,WiFi it will show you as home
Yes. I think I have it set up the GPS presence correctly now (was just able to test it) but still would like to make sure that the wifi presence as an added layer
{% if is_state('sensor.your_device_ssid', 'Your_SSID') %}
home
{% else %}
not_home
{% endif %}
Great I will give this a try. Thank you!
Hi,
Pls help me with a template that will show for how long the door is opened based on (binary_sensor.door_contact state), in a format of hh:mm. Thanks!
yes it works thanks a lot! just one thing though, It sometimes skips some steps if the volume change is big. Does the delay have something to do with it maybe?
Could be, maybe make that a little bit longer
Based on your question in #automations-archived that's not what you need 😛
Well I will use it to assign a message. I am not asking the full thing cause understand what to do, just need help with this template.
Thanks 😉
Yes, but you can assign the message in one go
example:
message: >
{% set gate_open = ((now() - states.binary_sensor.door_contact.last_changed).seconds / 60) | int %}
{{ 'Gate just openened' if gate_open < 2 else 'Gate is already open ' ~ gate_open ~ ' minutes' }}
What do you mean?
My idea was to have a message like this message: {{ states('sensor.gate_notify') }}. Make alert repeat every let say 60 min, once opened sensor will be opened, that it will me opened for more than xxxx.
Well, like I have done above 😛
but that will show it in minutes, you can also use a time format
not that good at templates was using such constructions before
- name: "robot_1floor"
state: >
{% if is_state
Thanks!
Or you can use this:
message: >-
{%- set entity = 'binary_sensor.door_contact' %}
{%- set gate_open = (now() - states[entity].last_changed).seconds %}
{%- set open_for = relative_time(states[entity].last_changed) %}
{{ 'Gate just openened' if gate_open < 120 else 'Gate is already open for ' ~ open_for }}
It will not show an exact time, but minutes if minutes are relevant, hours if hours are relevant, days if days are relevant, etc
And you can also do it like that if you want 🙂
Sorry for stupid question.
"message: >-"
What does this mean. Before I was using state: > and then using the value of the sensor to in messages to telegram.
Something like this
message: |
{{"\U0001F916"}} Robot: {{ states('sensor.robot_1floor') }}.
haha you'll like this
the helper triggers the keypresses for volume change via your template and also gets updated by a sensor in order to reflect the volume on the pc. When the sensor updates it triggers the template so it just goes on and on like that
I'm trying to say you don't need a template sensor for this
You can template the message in your alert
so that's why I used message
Ok, googled it, found some examples, have now information to think and experiment. Thanks!
Well, you need to make sure that doesn't happen then 🙂
yeah I know, it's the expected behaviour, I just thought it was neat :p
anyway, the sensor updates the helper because sometimes I change the volume via the pc. Don't really know how to get around this
I expect iif(states.input_number.volume_level.context.user_id) only returns true if you changed the input_number by yourself (by moving the slider) and not when it is updated by the actual volume change
So you cold use the above in a template condition
wow thats nice
and add the following to your automation so you don't get messages about the automation running multiple times
mode: single
max_exceeded: silent
However, that does mean you'll have to wait until your change has been fully processed until you can change the slider again
that's cool, it'll do
cheers!
ok now it doesnt trigger at all, after I added the condition
@stuck remnant It's a template, use "{{ iif(states.input_number.volume_level.context.user_id) }}"
Thx, was fumbling in the dark trying to placate syntax highlighting in VSCode and came up with the wrong answers :S
And if I have several doors that can stay opened at the same time shall I use ...entity1 = 'binary_sensor.door1_contact'... ...entity2 = 'binary_sensor.door2_contact'... , or can leave entity = 'binary_sensor.door1_contact' in one alert and entity = 'binary_sensor.door2_contact' in the other ?
thanks!
Im trying to figure out how to format a state attribute to only show the time rather than the date and the time, my current attempt at the code:
template:
- sensor:
- name: "Next Tram to City"
state: "{{strptime(state_attr('sensor.tram_to_city', 'origin_stop_arrival_time'), '%Y-%m-%d %H:%M') | timestamp_custom('%I:%M %p') }}"
icon: "mdi:tram-side"
Do you have separate alerts per sensor? If so, just replace the endity_id in de template
timestamp_custom needs to be used on a timestamp. You can either use:
"{{ as_timestamp(strptime(state_attr('sensor.tram_to_city', 'origin_stop_arrival_time'), '%Y-%m-%d %H:%M')) | timestamp_custom('%I:%M %p') }}"
or: "{{ strptime(state_attr('sensor.tram_to_city', 'origin_stop_arrival_time'), '%Y-%m-%d %H:%M').strftime('%I:%M %p') }}"
Oh thanks so much! This kinda stuff is pretty new so was a little confused. The first one worked, the second had an error, so happy with it anyway!
Hmm, 2nd one works for me as well, but it the other one works it's probably fine
got it, thanks!
Hi! I'm a super newbie with Home Assistant, I installed it last week. I'm trying to have an entity that is the sum of two entities. From the docs I got that I need to create a template with the operation, I tried the template in the template editor and it works. But I can't figure out where I need to store that template. I know this is really basic, but I've been browsing the docs and looking at youtube videos and can't figure it out :(.
You need to create a template sensor https://www.home-assistant.io/integrations/template/
Do I need to add "template" as an integration? I tried that and it told me that template was not available as an integration
you need to edit the YAML as shown in the docs
Thanks, yes, I've figured that I need to edit the YAML, but still stumbling with the syntax. All the template docs I could find are about how to write the template, not about where to add the YAML code :(.
hi, I don't know what I'm wrong about but this sensor doesn't want to change state, still the same state. https://pastebin.com/UqRRSn9a
I don't see anything inherently wrong with it. Did you reload templates and check the logs?
== 0 isn't ideal tbh. I'd reverse the logic (> 0)
well, yeah. check the template in
-> Templates and make sure that it says what you want, in addition to monitoring the state
in developers tools template working wtf
but no default was specified. Currently 'float' will return '0', however this template will fail to render hmm @inner mesa
what was the actual state?
in HA old state is off, in developers tools working state is Washing
of the sensor that you're trying to convert to a float
I am getting this error "value must be at most 1 for dictionary value @ data['volume_level']. Got None"
service: media_player.volume_set
data: {}
target:
entity_id: media_player.sonos_system
data_template:
volume_level: '{{ states.media_player.sonos_system.attributes.volume_level + 8 }}'
you have both data: and data_template:, and data_template: was deprecated around 2 years ago.
remove the data: line, change data_template to data:, and ensure that the template actually returns what you think it does in
-> Templates
Also, volume_level has to be between 0 and 1, so you'll need to account for that in the template
great - thanks guys 🙂
so I got this to work
service: media_player.volume_set
target:
entity_id: media_player.sonos_system
data:
volume_level: '{{ states.media_player.sonos_system.attributes.volume_level + 0.1 }}'
but when I do it with my tv:
service: media_player.volume_set
target:
entity_id: media_player.living_room_tv_kd_75x8500e
data:
volume_level: >-
{{ states.media_player.living_room_tv_kd_75x8500e.attributes.volume_level + 0.1 }}
for example the tv is set to 41... it then goes to 51 for half a second then goes to 43 for some reason
why would it turn itself down? - is it because the TV is connected to the sonos(first code) via arc
yes that made it work, thank you very much
Hi everyone, tom_l has been helping me with grabbing a list of bus times from a website. I have been able to get the first time, but the website lists anything up to 5 times depending on the time of day. I'd like to grab all available and add them to a card on my dashboard. Here is the code I am using at the moment- platform: rest name: Bus Times json_attributes_path: "$.buses[0]" json_attributes: - route - time - destination resource: https://transperth.maxrumsey.xyz/api/v1/busTimes?stop_number=18418 value_template: "{{ value_json.buses[0].time }}"
How do I specify buses[1-4] even though at night there may only be 1 or 2 or even 0 times available if there a no further buses coming today
How often will this sensor refresh by default?
looks like every 30 seconds https://community.home-assistant.io/t/sensor-platform-rest-scan-interval-system-default/164363/3
Thanks, thats a lot more frequent than I need but will work
For your main question, what would you like to have? A comma seperated list with all the times?
Open to ideas, I was going to put it in an bus times entities card and have each time on a new line, but that would work also
The route # and destination wont change
{{ value_json.buses | map(attribute='time') | join(', ') }} this would give the times
You don't need the attributes then
if its the end of the day and no more buses are available, it will just display nothing?
yes
and no requirement for json_atrributes...?