#templates-archived
1 messages Β· Page 89 of 1
I guess you can't cross a build if it's not built though
LOL I laugh at me enough for everyone
HE WAS WRONG ABOUT SOMETHING INSIGNIFICANT!
BURN HIM
egrish is serious business
are you guys ok?
i'm doing great, what about you?
is anyone?
we should do this stay-at-home thing every year
i think we're all a bit nuts these days
minus the pandemic obvi
my fiancee is slowly losing her mind but i'm loving it
π€
i'm doing 100% of the work for 100% of the pay. am i doing something wrong?
yeah, same shit different day for me for the most part
or maybe 100% of the work for 110% of the pay since i'm saving on commuting costs
i'm 100% work from home normally
eh. more like 101% of the pay
I have to remote work unless there's an "emergency" and I have to go onsite
but 90% of my job is onsite
i'm onsite all the time so working from home full time has been a nice change
strange, but nice
i'm 100% work from home normally
@dreamy sinew youβve been saving on day care huh? π
People spend ton of money when they have to work away from home
nah, we send her to daycare
can't really work and watch the kid at the same time
without failing at both
lol. I hear you!
[Solved!]
Hey there!
TL;DR: How can I use a variable inside of a variable? For example {{ states.{{ target }}.state }}
I'm stuck! I think I know why it doesn't work but I don't know how to work around it.
I want to call the following script with the variables index: 1 and target: 12_23_34_45_56_67.
So far, I only got it working with the MAC-Address fixed, not as a variable.
description: 'Updates any device vban IP'
sequence:
- service: shell_command.vban_sendtext_crixpc
data_template:
command: "vban.outstream[{{ index }}].ip={{ state_attr('device_tracker.12_23_34_45_56_67', 'ip') }}"```
This works. It takes the `ip` attribute of `device_tracker.12_23_34_45_56_67` and outputs `vban.outstream[1].ip=192.168.2.120` as expected, works flawlessly. BUT
when I try to swap the MAC-Address with {{ target }}, ```command: "vban.outstream[1].ip={{ state_attr('device_tracker.{{ target }}', 'ip') }}"```
it stops working. I guess that's kinda obvious since that's a variable inside a variable and that somehow doesn't work. But how can I go around this?
Wow, the solution is simpler than I would have allowed myself to think: don't use any braces at all! π
command: "vban.outstream[1].ip={{ state_attr('device_tracker.' + target, 'ip') }}" works
I'm trying to fix a script conraining a templates tts component. I hat this up an running bus since quite some time it did stop workin. Any idea on what I'm doing wrong? ```leave_home_test:
alias: Leave Home Test
sequence:
- service: tts.google_translate_say
data_template:
entity_id: media_player.arbeitszimmer
language: de
message: "{states('sensor.tts_ww_az')}}"
need two braces at the beginning ({{)
oO you're right, will give it a try
thnx
sorry for the dumb question but when do I have to use ' and when "
if i just copy '{{ states(''sensor.tts_ww_az'')}}' into the template section of lovelace it does not work
if I do '{{ states("sensor.tts_ww_az")}}' it is ok for lovelace but my script still isnt working
single line templates need to wrapped in quotes and you need to be careful about using single and double quotes
youll want to do double on the outside and single quotes inside or vice versa
your first example isnt valid since it only uses single quotes
some helpful pointers here: https://www.home-assistant.io/docs/automation/templating/#important-template-rules
thanks for your help! so i should go with this right: ``` leave_home_test:
alias: Leave Home Test
sequence:
- service: tts.google_translate_say
data_template:
entity_id: media_player.arbeitszimmer
language: de
message: "{{states('sensor.tts_ww_az')}}" ```
yup
Can someone tell me what is wrong with this? I'm going crazy. The image I am trying to attach is not being found by the discord script. ```action:
- data_template:
message: Robert recognised with probability {{ trigger.event.data.confidence
}} percent
target:- '126567519145295872'
data:
images:- "/config/webcamface.jpg"
service: notify.discord
- "/config/webcamface.jpg"
- '126567519145295872'
Log Details (WARNING)
Logger: homeassistant.components.discord.notify
Source: components/discord/notify.py:69
Integration: discord (documentation, issues)
First occurred: 11:34:32 PM (3 occurrences)
Last logged: 11:36:51 PM
Image not found: /config/webcamface.jpg
Image not found: /usr/local/config/webcamface.jpg```
In the docker terminal: /config # ls -l total 485736 -rw-r--r-- 1 root root 3341 Apr 9 23:56 automations.yaml -rw-r--r-- 1 root root 1184 Apr 9 21:08 configuration.yaml drwxr-xr-x 1 root root 0 Apr 6 11:32 deps -rw-r--r-- 1 root root 0 Apr 6 11:32 groups.yaml -rw-r--r-- 1 root root 7939 Apr 9 23:36 home-assistant.log -rw-r--r-- 1 root root 497299456 Apr 10 00:01 home-assistant_v2.db -rw-r--r-- 1 root root 32768 Apr 10 00:01 home-assistant_v2.db-shm -rw-r--r-- 1 root root 0 Apr 10 00:01 home-assistant_v2.db-wal -rw-r--r-- 1 root root 0 Apr 6 11:32 scenes.yaml -rw-r--r-- 1 root root 0 Apr 6 11:32 scripts.yaml -rw-r--r-- 1 root root 161 Apr 6 11:32 secrets.yaml drwxr-xr-x 1 root root 4356 Apr 9 21:58 tts -rwxrwxrwx 1 1000 users 40365 Apr 9 22:10 webcamface.jpg
@near marsh the permissions are off for that file atleast which would probably explain it
I seen that after I sent it. It did a chown root:root webcamface.jpg
still the same issue
-rwxrwxrwx 1 root root 40365 Apr 9 22:10 webcamface.jpg
@near marsh pack the imagae in another folder and whitelist that folder in the configuration
homeassistant:
time_zone: Europe/Vienna
packages: !include_dir_named packages
whitelist_external_dirs:
- /config/imagerec/
also jump into the container(?) and do a realpath webcamface.jpg
Hey peeps,
I like the thought behind this automation.
https://community.home-assistant.io/t/which-is-the-best-way-to-build-a-room-presence-detection-system/164944/19?u=rkor
But it seems very troublesome to have 3 automations for each motion sensor/room
I'd like the lights to turn on when motion is detected, run for certain time and then turn off only if there's been no motion detected for the last X time...
Trouble as I have it now is that the light turns off even if we're still in the room
The other trick is, say there's still motion being detected, how do we restart the automation countdown to check for motion again in X amount of time?
Now I feel really silly! I have done that automation in other parts of the house long ago and have forgotten π€¦
Thanks man
Hi guys, is there an easy way to check if my current time (e.g. "16:44") is between two other times? What would you recommend for checking if the current time is between two input_datetimes?
so, this works: {{ now() <= now() <= now() }}
so might be able to do
{{ state_attr('input_datetime.time1', 'timestamp') <= now()|as_timestamp() <= state_attr('input_datetime.time2', 'timestamp') }}
My script:
water_a_zone:
alias: Innaffia una zona
sequence:
- service: shell_command.run_netro
data_template:
zona: >
{{zona}}
minuti: >
{{minuti}}
My shell_command
run_netro: python C:\GoogleHome\Python\NetroRun.py "{{zona}}" "{{minuti}}"
Why I cannot read the parameters?
Nerd @dreamy sinew π€
@lunar osprey To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
@lunar osprey windows venv? That would be _here be dragons _ anyway, don't expect anything to work as intended
Is the syntax correct?
Tediore, let me try in this way
2020-04-10 16:50:01 ERROR (MainThread) [homeassistant.components.shell_command] Error running command: python C:\GoogleHome\Python\NetroRun.py {{zona}} {{minuti}}, return code: 2
are you calling the script?
- service: script.water_a_zone
data:
zona: zone_1
minuti: 60
or whatever parameters you want
The script is called, but I see {{zona}} instead of the value
Lovelace:
- type: button
entity: sensor.centralina_irrigazione
style:
left: 17%
top: 37%
#--iron-icon-height: 30px
#--iron-icon-width: 30px
icon: 'mdi:radio'
tap_action:
action: call-service
service: script.water_a_zone
service_data:
zona: 1
minuti: 5
And in script:
water_a_zone:
alias: Innaffia una zona
sequence:
- service: shell_command.run_netro
data_template:
zona_val: >
{{zona}}
minuti_val: >
{{minuti}}
for the third time:
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
please format your blobs
formatting is super important in yaml and if you don't use it weird stuff happens
@dreamy sinew Thx, I'll try that out tight now
Pls check it in pastebin
I tried
it's the same
I can't see the values of the parameters
in the log of the run execution
your script indentation is a little wacky
What's wrong with it?
not using two spaces consistently
I don't think this is the issue for the problem I have
Ok, so the timestamp for one of my input_datetimes is 5400, But the timestamp for now() is 1586530883.486388, can I subtract the timestamp of the current day at midnight to get to a comparable value? Basically I'm trying to have two input_datetime fields that act as an automatic arm and disarm time for when my alarm should be armed each day, and being input_datetime fields I can adjust them via the UI
5400 seesm wrong
could just add a time sensor to your config and compare HH:MM strings for the time sensor and the input_datetime
and yeah, 5400 ain't right
oh, because its time without a date
It's a time only input_datetime, set tho 5:30 am
oh right lol
Yes π
it starts getting a lot more obnoxious to work with at that level
@buoyant pine any idea about my issue?
I'm open for doing things differently
@lunar osprey config check come back ok?
Before I had the time hardcoded into the automation
if you can get away with flat hours its easier but adding in minutes is a pain
@buoyant pine what do you mean?
also maybe try:
water_a_zone:
alias: Innaffia una zona
sequence:
- service: shell_command.run_netro
data_template:
zona_val: "{{zona}}"
minuti_val: "{{minuti}}"
does the configuration check come back ok
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
@analog remnant @dreamy sinew what about this: https://discordapp.com/channels/330944238910963714/672223497736421388/698187183663874188
mm maybe
does the configuration check come back ok @lunar osprey
I thought you could check in the condition if the current hour is between those of the two variables, if yes, just check the minutes as a bonus, is that wat you're thinking?
only error is when I try to execute the script tapping the button
how ecatly to wrote in my script, in part of data_template, that entity_id should be the one who invoked that script?
sequence:
service: light.turn_on
data_template:
entity_id: light.livingroom_go_color_greywall ```
for now I have 4 scripts which are doing same thing, just entity_id is different
maybe like entity_id: "{{device}}"?
What do you guys think? https://pastebin.com/n22JDSFb Not tested yet...
flip the <= in your first minute check
and make the first condition type an and
you can remove the last condition as that case is already accounted for in the hour + min checks
@buoyant pine any idea?
Why flip it? If it were 1:45 am and the alarm was set to be armed from 1:30, in order to pass the condition, 45 (now) must be greater than 30(start input_time)?
Or am I thinking wrong here?
oh, no you're right
@lunar osprey no clue, sorry. still haven't heard back from you about the config check
I replied
I don't have errors in the log
when I start HA
I think this is what you mean, right? @buoyant pine
Also, I think I can't remove the last condition, the first two conditions are just to handle the hours where the hour is either the exact hour of my start or end hour, if I would remove it I had to change the hour check from == to >= and <=, but that would mess up the minute checks
I'll give it a try, let's see if it works π
oh, yeah. sorry. time stuff hurts my brain
No problem, I'm happy you guys are sticking with me and my stupid problems π
@warm isle That worked perfectly! Thank you!
Can anyone please help me, to get this working?
trigger:
- platform: template
value_template: "{{ (as_timestamp(now()) == state_attr('input_datetime.aufwachlicht', 'timestamp')) }}"
it'll probably never actually match exactly
Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'trigger' is undefined
data_template:
title: >
"{{ trigger.to_state.attributes.friendly_name }}"
message: "{{ device }}"```
I just want to catch which entity has called the script
Are you actually providing the script with the variables trigger and device? Could you share the whole script?
@sonic nimbus scripts donβt have access to the trigger object. Only automations do.
If you put that service in an automation, it should work. If you want to call a script from automation, you can pass data from automation to scripts.
Anyone can help on this? https://community.home-assistant.io/t/issue-with-command-line-parameters-in-windows/185531
I donβt think you shared the whole code. Actual script code is missing.
Hello. My whole frontend is displaying temperature in Celsius. However, I do have a DIY temperature sensor for my pool that I want to display in Farenheit. It is right now reporting in Celsius.. How can I alter that one sensor to display in Farenheit without changing all the other units
you don't
Home Assistant uses either imperial or metric
I was thinking perhaps there was a way of taking the value returned by the sensor and converting it to F and display the resulting value.
@thorny snow C * 2 + 30? π€·πΌββοΈ
@oak rampart posted a code wall, it is moved here --> https://paste.ubuntu.com/p/cRBKPBcHjw/
@oak rampart posted a code wall, it is moved here --> https://paste.ubuntu.com/p/tPfkf4xtrY/
.rule6 @oak rampart
@oak rampart Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, codewalls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
Not once,but twice...
Same text, both times. Somebody's not paying attention π€
Are you asking how to write an automation to match the fan speed to the input select @oak rampart ?
yes
Your action section would be
action:
- service: fan.set_speed
data_template:
entity_id: fan.xiaomi_miio_device
speed: "{{ states('input_select.skorost_day') }}"
``` The trigger would be a simple state trigger on `input_select.skorost_day` with no `to` or `from`
are you able to get it to work if you give hard coded values for zona and minuti? Try calling from a simple automation
the timestamp_customer() function shown on https://www.home-assistant.io/docs/configuration/templating/#time is said to convert a UNIX epoch into a string. the local_time=True parameter I can pass to it, what does it do ... tell the function to show whatever that timestamp is, in the local timezone?
Yep
I think there is a problem in the device_class=timestamp rendering. But still processing data.
@rare panther with values in shell_command yes... with template no...
Not sure if this is the problem but ypu can try with directly giving the '{{zona}}' in the same line and not with >
Also put the shell command in ' '
I tried also using zona_val: 2
it's not working...
I added in the shell command single quotes
or double quotes
it doesn't seem to recognize the template
I'm on Windows
I added some logs into the shell_command
rendered_args=C:\GoogleHome\Python\NetroRun.py 1 5
args=C:\GoogleHome\Python\NetroRun.py {{zona_val}} {{minuti_val}}
so seems I can see the parameters
Do I need to put a return code in the file NetroRun.py?
If I use values in shell_command instead of template, the automation with HA works...
prog=python
cmd=python C:\GoogleHome\Python\NetroRun.py {{zona_val}} {{minuti_val}}
rendered_args --> I can see the parameters....!!!!
I think this is the problem...
shlex.split(s, comments=False, posix=True)
Split the string s using shell-like syntax. If comments is False (the default), the parsing of comments in the given string will be disabled (setting the commenters attribute of the shlex instance to the empty string). This function operates in POSIX mode by default, but uses non-POSIX mode if the posix argument is false.
Note Since the split() function instantiates a shlex instance, passing None for s will read the string to split from standard input.
I'm creating camera snapshots and saving them with a filename like: 'mycamera_{{ now().strftime("%Y%m%d-%H%M%S") }}.jpg'
this works. It produces files like 'mycamera_20200411-184630.jpg' which is what I need, but I'm trying to send the image using 'notify.mobile_app' and the image: attribute doesn't like the format. Anyone know of a way to use a template when sending notifications to the mobile app?
I tried that without succeeding. I went with saving two pics, one with the templated name and one like "camera_01.jpg" that always gets overwritten. Not what I really wanted, but works great.
Do you know where the pics are stored in Home Assistant (previoulsy known as Hass.io) and if they are accessible?
I have plenty of room, but sooner or later I'll want to clear out the old copies, but I can't find them π
They're stored wherever you're saving them π€·
The default might be your config folder, but I'm assuming you've looked there
how to split string by last underscore
%}
{{entity.split('.')[1]}} #livingroom_abovetv_stripled_all_switcher```
I want just to be livingroom_abovetv_stripled_all
Jinja Template Designer Documentation
For more examples and samples, visit see this page
how can I use only object_id without domain in states for templating?
platform: state
to: 'on'
entity_id:
- binary_sensor.livingroom_abovetv_stripled_all_switcher
- binary_sensor.bedroom_wall_ledstrip_switcher
action:
- service_template: persistent_notification.create
data_template:
title: "{{trigger.state.object_id}}"
message: "N1"```
this doesnt work - title
oh, I found its a "{{trigger.to_state.object_id}}"

https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
Worth taking the time to read the docs π
thanks @abstract kelp
Im just exercising in templates section..trying to read friendly name of some entity
{{states("binary_sensor.livingroom_abovetv_stripled_all_switcher")}}
this returns state off or on
Yes
but I cant find in docs how to return friendly name
like {{states("binary_sensor.livingroom_abovetv_stripled_all_switcher", "name")}}
yep that's it {{state_attr("binary_sensor.livingroom_abovetv_stripled_all_switcher", "friendly_name")}}
π
tnx
but if I would to get state.object_id without domain?
{{ states.binary_sensor.livingroom_abovetv_stripled_all_switcher.object_id }}?
yes, I just found exact syntax
and another question π
if I have binary_sensor.livingroom_abovetv_stripled_all_switcher what is the best way to trim _switcher at the end?
I use [:-9] on my [object_id]
like 9 chars remove at the end
is there some better approach?
Depends on what your goal here is - why you're doing that
It may be easier to change the entity ID π
well, I setup my naming convention, that my some binary_sensors switches has that suffix _switcher and my lights (ledstrip) doesnt have that suffix
so basically trigger: platform: state to: 'on' entity_id: - binary_sensor.livingroom_abovetv_stripled_all_switcher - binary_sensor.bedroom_wall_ledstrip_switcher action: - service_template: persistent_notification.create data_template: title: "{{trigger.to_state.object_id[:-9]}}" message: "N1"
just imagine instead off persistent notifications that I called service light.toggle
Change the entity ID then?
and my entity_id would be like {{trigger.to_state.object_id[:-9]}}
you mean to call all my switches like binary_sensor.livingroom_abovetv_stripled_all
?
No
but maybe is gonna be confusing
how can i set my switch button to return to "off" automatically but not to run anything at this time?
i mean, i tap on the switch - it goes on and running my script, but it stays "on"
Hi! I have some custom switches based in command_line, they are all doing SSH checks every minute or so.
Is there any way to group all these switches, use only a single command_state and different value_template for checking status?
@ornate pecan posted a code wall, it is moved here --> https://paste.ubuntu.com/p/rCH3sgmK9N/
part of the code is https://paste.ubuntu.com/p/KrDyy6yWvG/
@ornate pecan not sure if you can do that... that's the switch definition, and not automation or script code...
unless there is a template command_line switch that lets you do it, it may not be possible!
I already though it was not an available option π©
when i set up a mqtt dimmer what values are required for it to work?
The ones marked Required, plus those relevant to whatever you're doing (in this case, sounds like brightness)
template question: this formula {{ states.light|selectattr("state", "equalto", "on")|list|length }} will count all lights that are "on", can/how can i add another criteria to it so that it will not count my light groups, identified by a ~~variable ~~ attribute "is_deconz_group":"true"
Hmmm.....it seems that it wont count the groups at all with this template {{ states.light|selectattr("is_deconz_group", "equalto", "true")|list|length }}
Solved: {{ states.light|selectattr('state', 'eq', 'on')|rejectattr('attributes.is_deconz_group')|list|length }}
Would this work? https://hastebin.com/cohegisile.rb
It's endif not end if
Is that the only problem?
Probably
Let's try it
Wait how do I trigger the script
With automations there is automation.trigger
is there something like that with scripts because there isn't a script.trigger
if i just call script.what will it trigger it
That's what I said
Try it from
-> Services π
Any service you see listed there you can call
All scripts show up as service calls, as well as being entities
The only script services that show are script.turn_on/off/toggle
And when I call script.turn_off with the entity_id: script.menu-button-tv, it says Failed to call service script/turn_on. not a valid value for dictionary value @ data['entity_id']
I tried with underscores too
If you use the UI to create the script, it will have a numeric name
If you didn't use the UI, you have to reload the scripts
After a command line config check
Ah ok
If the script doesn't show in
-> States it doesn't yet exist
Do I have to restart hass?
Ah ok
https://hastebin.com/fukucozonu.php I have that in my scripts.yaml file and when I reload scripts it says there is an error with the script integration...
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
Hey, I try to convert a 1024 bit value to a % vaule. But the Round option in the template isn't rounding. What I am doing wrong?
{{ states('sensor.wetterstation_analog_a0') | float/1024*100 | round(1) }}
have you tried it in the template tester?
yes
{{ (states('sensor.wetterstation_analog_a0') | float/1024*100) | round(1) }}
worked thx. But why I need that single ) there?
Here in this example, there worked without it, so that isn't working too? https://www.home-assistant.io/docs/configuration/templating/#priority-of-operators
its not a single
@dreamy sinew Ah, now I get it! Thanks! π€ͺ
hi, is it possible to use a template that checks the last state of an entity to be included as a condition in an automation?
hi, is it possible to use a template that checks the last state of an entity to be included as a condition in an automation?
@rancid copper you mean something like this? https://www.home-assistant.io/docs/automation/condition/
thanks yes...but just the state on/off
and the last state, not the state in this moment
Hi everybody, I would like to have a variable (energy consumption) to a daily value and reset that at midnight. Any idea on how to best achieve that ?
That's it!
{{relative_time(strptime("2019","%Y"))}
Shouldn't this work?
Or do I misunderstand the docs. https://www.home-assistant.io/docs/configuration/templating/#time
Hey All, I'm trying to reformat a sensor that is bringing me "Amps" from my power usage.. A couple of things i want to do.. But first thing is to format the input correct from the MQTT values.. Have tried a few value_template's but none seem to work i get no value, unknown etc..
here is my sensor - - platform: mqtt
name: "Power-Current3"
state_topic: "mport3/sensor/port3/mFiCS"
unit_of_measurement: "Amps"
icon: mdi:current-ac
i need to multiple that value by 100 to get the real value..
actually ! finally figured it out after about 15 google attempts... (Still learning HA and that..) had to create a sensor template with the expression from the original entity
Or is it some other way to get relative time in the lovelace markup card from input_datetime. last_changed works. but not the state. try to wrap it in strptime to get a datetime object but thrown an error.
Hi Friends, got a question with message template message: '{{now().strftime("%b %d, %Y %I:%M%p")}} Tank will be Empty, On the Bore motor' issue that the the now() time variable gets refreshed everytime if the alert repeats. Therefore I lost track on original 1st time the alert triggered.
How should I change the template to pickup 1st time the alert triggered data and use that for consecutive messages
I am thinking like, may be have variable that updates 1st time and then for consecutive runs call the same variable
{{ states.alert.whatever.last_changed.strftime("%b %d, %Y %I:%M%p") }}
I use relative time to get how long the alert has been active for, like https://github.com/DubhAd/Home-AssistantConfig/blob/master/alerts/garage_door_l.yaml
Thanks Tinker, your the life saver for me always π btw, Side note I got the ubuntu battery command line working. Its perfect.
No worries
Hi, I'm new and I'm trying to understand how it works if else, for example if entity1 = X do entity2 ON, otherwise OFF
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
Have you read the templating docs yet?
how can I do?
yes, but I can't understand
I would like to start with a simple thing so that I understand how it works
action:
- service_template: >-
{% if is_state('sensor.whatever','X') %}
switch.turn_on
{% else %}
switch.turn_off
{% endif %}
entity_id: switch.two
That's the long form - you can significantly simplify that
Testing in
-> Services is the way to go π
π
- service: input_boolean.turn_on
a boolean entity called mode
You define the service as input_boolean.turn_on
No it's not
If it was, it'd be input_boolean.mode
That is an entity
Also, either service or service_template
Finally ON isn't a service
So, the only valid line there was the first one π
Oh, and entity1 also isn't an entity
and the state of it is highly unlikely to be ON
I get it
how can I use the if with state_attr?
{% if is_state_attr('sensor.kipper','smoked','lightly') %}
It's just an if statement
@arctic sorrel thanks to your help I'm learning, I have implemented some functions that allow me to restore the thermostat state, because when it turns off and on again it always goes into "heating". https://paste.ubuntu.com/p/svqywqP6dw/
However, I can't integrate the template that allows me before turning off the air conditioner to activate an input_boolean so that it can understand the previous state of the thermostat, I have tried various templates but I really can't
Two things
- Service not value
- What if it's not in cool mode?
- service_template: >-
{% if is_state("climate.terina", "cool") %}
input_boolean.turn_on
{% else %}
input_boolean.turn_off
{% endif %}
entity_id: input_boolean.terina_mod
You got that sort of right later on, but not at line 21
Same for the hvac mode, needs an else
I don't care, I only care if it's cold, so then it comes back on in heating
i have tried many times with this code but it doesn't work
You don't care
The system does
Any time you have if you need else if you don't want errors and things stopping
ahahah
If you don't want it turned on at all, don't turn it on...
so I can't use an if without an else
Sure you can, if you don't mind HA throwing errors
More to the point, ...
- data_template:
hvac_mode: >-
{% if is_state("input_boolean.terina_mod", "on") %}
cool
{% endif %}
So, the mode if that is off is ... undefined
Computers are like toddlers, or end users, you can't assume they can think for themselves. You have to tell them exactly what to do
That's pretty much the same thing I say when someone complains about YAML being "picky about indentation" lol
ok, i can add here else "heat"

You have to tell it what do to when you tell it to do something
You can't leave it hanging
I have no idea what you're doing any more
So, you only want it to operate when cooling?
ahah
You have spent some time banging the rocks together and scattering confusion
i want if thermostat is in "cool" mode boolean "on"
No
The XY problem is asking about your attempted solution rather than your actual problem. This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
You want this logic to only operate when cooling? Or also when heating?
with both
yes but I think the problem is that the template does not actually read the state of the thermostat so it doesn't work

Paste the whole template into
-> Templates
As I explained before
{% if is_state("climate.terina", "cool") %}
input_boolean.turn_on
{% else %}
input_boolean.turn_off
{% endif %}
i see
i try dosen't work
i know
How about being a little more descriptive
{{ states('climate.terina') }}
``` Paste that into the Templates screen and _copy and paste_ the output
i see cool
So what was the output from
{% if is_state("climate.terina", "cool") %}
input_boolean.turn_on
{% else %}
input_boolean.turn_off
{% endif %}
``` then?
when i open the window the boolean dosen't turn on
ok
i don't read your question before...but thanks...you have always been available and kind
i see input_boolean.turn_off
I was with my 9 month old daughter in my arms and I let you imagine
Sorry
Well, if you want help, it needs you to pay attention. If you're splitting your attention, you're wasting our time, that we're giving up for free to help you
This is also why I asked you to copy and paste, rather than just say what you think you see
you're right, I apologize again
Let's try again then, one last time...
{{ states('climate.terina') }}
{{ is_state('climate.terina','cool') }}
Put that in Templates
copy and paste the output
Don't retype a damn thing
cool, true
Right, then... that doesn't explain what you got before
{{ states('climate.terina') }}
{{ is_state('climate.terina','cool') }}
{% if is_state("climate.terina", "cool") %}
input_boolean.turn_on
{% else %}
input_boolean.turn_off
{% endif %}
Try that
cool
True
input_boolean.turn_on
Ah, copy and paste at last
Or better typing
No idea why you were getting the turn off before π€·
ok
Either:
- You weren't
- The state of the entity wasn't
cool
If it doesn't work, turn the logger to info and it will log more in the log file
ok thanks again
Also, if it doesn't work, configure https://www.home-assistant.io/integrations/file
Then you can log a lot of details as things happen, and it's going to be much easier to help you
ok
Well, you'll only get help if you explain the problem π
π thanks π it's about delay
I need to make to things and i don't understand how can i do with delay
So first it's to make a binary sensor motion like this : ( if motion 1 = on or motion 2 = on then binary sensor = on for 30 minutes )
I test with this:
hmm i make a code tag ?
Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
Up to 12 lines, in channel. Above, using a code share site
Yes i saw it but i'm really tired π¦
motion_salon:
friendly_name: "Mouvement salon"
device_class: motion
delay_on:
minutes: 30
value_template: >-
{{ is_state('binary_sensor.motion_sensor_158d000165fe6f', 'on')
and is_state('binary_sensor.motion_sensor_158d0001a24b54', 'on') }}
But i don't know if it's really work like i want :/
I think you wanted delay_off
i think too but i don't really understand how the both work... :/
The on delay is:
The amount of time the template state must be met before this sensor will switch to on.
Off delay:
The amount of time the template state must be not met before this sensor will switch to off.
As you said:
So first it's to make a binary sensor motion like this : ( if motion 1 = on or motion 2 = on then binary sensor = on for 30 minutes )
So, you want it to delay the off for 30 minutes
ok delay the off it's clear !
Of course, you also said or but coded for and π€
omg
Yes i remember why i do this
Ok i will test for delay off
do you know if the delay start at binary sensor changed to on, or at last motion 1 or 2 changed to on ?
The day for off starts when the template is no longer true
So, when the last sensor turns off if an or, or both if and
And it's the reason why i don't know how it not relevent for my test
OKKK Really thanks
ok so i take that. And just for me, if i explain delay_off like, delay the off for... do you think delay_on: it's for delay the on for... ?
can you explain more delay_on ?
The amount of time the template state must be met before this sensor will switch to on.
That's what the docs say
So, when the template is true, that's the amount of time it has to stay true before the sensor will turn on
hmm
Maybe you only care if there's been 30 minutes of motion
for the moment, i try to understand it because i just do lot of test with one input boolean. And all my test don't work.
Without knowing what you were doing... π€·
lol
I just want to check if i understand delay. So just for test i make that:
test_delay:
delay_on:
minutes: 30
value_template: "{{is_state('input_boolean.bouton_test', 'on')}}"```
x(
Back tick π
Next to 1οΈβ£ usually
That won't turn on until the boolean has been on for 30 minutes
ok so i test
test_delay: delay_on: minutes: 30 value_template: "{{is_state('input_boolean.bouton_test', 'on')}}"```
@sick haven ok i get skill
That won't turn on until the boolean has been on for 30 minutes
@arctic sorrel It's work !!
π
I try to make every test ever today ...
π’
π
i note that !!
Ok and for my last thing, i just want your point of view ("point of view" is understandable?)
I have trackers on my phone and wife's phone. So i want to make (if trackers off then alarm = armed_away).
But my wife turn off here phone at night, so i want to make a template like: (if trackers off and houses door last changed > 30 minute then alarm = armed_away else alarm = arme_home) do you thinks it's a good stuff for an alarm ?
That's pretty much what I do, so yes π
I use the door sensors to work out whether people could be away, and track their actual state with booleans, rather than the trackers
wait i translate xD
https://blog.ceard.tech/2020/04/presence-detection-one-last-time.html if you want the full technical details
oh wow it's too late i take this in my fav !!
It's really what i want to do. Make a binary sensor for movement on house, and this can't turn off if door is open and tracker on for 30minute. after that, if trackers off, so alarm can get armed home
I use the door sensors to work out whether people could be away, and track their actual state with booleans, rather than the trackers
@arctic sorrel
That looks reasonable
thanks for your think !!
soon i want to work out with camera
maybe just with body recognize
but only i ve a pi
and open cv don't work π¦
i need a todo list :/
Ok so it's enough for tonight. Thanks for your help !!
Whats a quick way to list entity_id that contains specific text
I tried {{ states.sensor|list | map(attribute='entity_id') | reject('ne','node_up') | join(', ') }} but the reject filer is obviously wrong
@arctic sorrel Doing a / between 2 templated staes
π
Would that be ```{{ (states('sensor.condensation_kwh_may_5148') | float }} /{{ states('sensor.energy_kwh_may_5172') | float) | round(1) }}
there are plenty of other people who can answer that question lol
shh
Mkay
{{ (states('sensor.foo') | float / states('sensor.bar') | float) | round(1) }}
Ty β€οΈ
@buoyant pine I'll ping you nexttime
@buoyant pine
Still error :/
i try the same but with some other sensor i have
{{ (states('sensor.desktop_4f930au_amd_ryzen_5_2600_powers_cpu_core_1') | float / states('sensor.desktop_4f930au_amd_ryzen_5_2600_powers_cpu_core_2') | float) | round(1) }}
what does
{{ states('sensor.desktop_4f930au_amd_ryzen_5_2600_powers_cpu_core_1') }}
``` and
{{ states('sensor.desktop_4f930au_amd_ryzen_5_2600_powers_cpu_core_2') }}
Error rendering template: TemplateSyntaxError: unexpected '}', expected ')'
Because you missed a thing
But
what about
{{ states('sensor.desktop_4f930au_amd_ryzen_5_2600_powers_cpu_core_1') | float }}
maybe it doesn't like the comma. try
{{ states('sensor.desktop_4f930au_amd_ryzen_5_2600_powers_cpu_core_1').replace(',','.') | float }}
yup, it doesn't like the comma which i suppose makes sense
My code actually is: but I want to add a time check too:
{% if now().days == Giovedi %} <b>Ciao</b> {{'\U0001F611'}}
{% else %} <b>Errore giorno</b> {{'\U0001F974'}}
{% endif %}
How can I add now.time too as check before run βIFβ?
{% if now().days == Giovedi and now().hour <= 10 %}
{% if now().days == Giovedi and now().hour <= 10 %}
@arctic sorrel I tried to put this:
{% if now().days == Sabato and now().hour >= 16 %} </br><b>Spuntino Mirko</b></br></br> Macedonia 200gr</br></br><b>Spuntino Elisa</b></br></br>Macedonia 200gr
{% elif now().days == Sabato and now().hour >= 18 %} </br><b>Cena Mirko</b></br></br> Pomodorini 200gr</br>Olio 15gr</br>Fiocchi 200gr</br>Frutta 100gr</br>Pane 100gr</br></br><b>Cena Elisa</b></br></br>Pomodorini 150gr</br>Olio 10gr</br>Fiocchi 200gr</br>Pane 60gr</br>Frutta 100gr
{% else %} <b>Errore</b> {{'\U0001F974'}}
{% endif %}
but even if today is not "sabato", the text show anyway. What's the error?
You need to simplify that while testing so it's easier for people to help
{% if now().days == Sabato and now().hour >= 16 %} EARLIER
{% elif now().days == Sabato and now().hour >= 18 %} LATER
{% else %} ERROR
{% endif %}
Try that in
-> Templates
Day: {{ now().days }}
Hour: {{ now().hour }}
{% if now().days == Sabato and now().hour >= 16 %} EARLIER
{% elif now().days == Sabato and now().hour >= 18 %} LATER
{% else %} ERROR
{% endif %}
``` for some debug data
The problem is that seems the code check only date or time, and not date and time together @arctic sorrel
~irc @tranquil dome
@tranquil dome Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
I can't see what you see, but if you posted the above, it does both checks
That's how and works
I have a couple MQTT lights, and in Node-Red I am putting in the following, but the transition time does not do anything. Can someone let me know what I may be doing wrong.
{
"white_value": 250,
"transition": 30
}
It seems that doesn't work now.days
That's on my sensor.yaml:
day:
entity_id: sensor.date
value_template: >
{% set days = ["Lunedi", "Martedi", "Mercoledi", "Giovedi", "Venerdi", "Sabato", "Domenica"] %}
{{ days[now().weekday()] }}
Share the result from the last code I pasted - copy and paste the output please
Day:
Hour: 19
EARLIER
Well, looks like now().days isn't producing any output π
yeah i see, what can be the problem?
Maybe it'll be less broken if you use your custom sensor
That's on my sensor.yaml:
day: entity_id: sensor.date value_template: > {% set days = ["Lunedi", "Martedi", "Mercoledi", "Giovedi", "Venerdi", "Sabato", "Domenica"] %} {{ days[now().weekday()] }}
@tranquil dome that's the code on my sensor.yaml
Which isn't what you've been using in your template
What does
{{ states('sensor.day') }}
``` show?
What does
{{ states('sensor.day') }} ``` show?
Yes, show the exactly date now
So, how can i change the code for let "IF" check the states.sensor.day?
Day: {{ states('sensor.day') }}
Hour: {{ now().hour }}
{% if states('sensor.day') == Sabato and now().hour >= 16 %} EARLIER
{% elif states('sensor.day') == Sabato and now().hour >= 18 %} LATER
{% else %} ERROR
{% endif %}
``` π€·
right, the day isn't matching your check
i changed the date from the code
obviously
I put "Giovedi" as day
Day: {{ states('sensor.day') }}
Hour: {{ now().hour }}
{% if states('sensor.day') == Giovedi and now().hour >= 7 %} </br><b>Colazione Mirko</b></br></br> Latte 200gr</br>Biscotti int. 30gr</br><b>Colazione Elisa</b></br></br>Latte 200gr</br>Biscotti int. 30gr
{% elif states('sensor.day') == Giovedi and now().hour >= 9 %} </br><b>Spuntino/Pranzo Mirko</b></br></br>Toast Misto 100gr</br>Pane 100gr</br>Crudo 50gr</br>Formaggio 50gr</br>Succo 200gr</br><b>Colazione Elisa</b></br></br>Latte 200gr</br>Biscotti int. 30gr
{% elif states('sensor.day') == Giovedi and now().hour >= 10 %} </br><b>Spuntino/Pranzo Mirko</b></br></br>Toast Misto 100gr</br>Pane 100gr</br>Crudo 50gr</br>Formaggio 50gr</br>Succo 200gr</br><b>Spuntino Elisa</b></br></br>Fette biscottate 20gr</br>Marmellata 20gr
{% elif states('sensor.day') == Giovedi and now().hour >= 12 %} </br><b>Spuntino/Pranzo Mirko</b></br></br>Toast Misto 100gr</br>Pane 100gr</br>Crudo 50gr</br>Formaggio 50gr</br>Succo 200gr</br><b>Pranzo Elisa</b></br></br>Pasta pomodoro 70gr</br>Olio 10gr</br>Crudo 70gr</br>Frutta 150gr
{% elif states('sensor.day') == Giovedi and now().hour >= 16 %} </br><b>Spuntino Mirko</b></br></br>Barretta 25gr</br></br><b>Spuntino Elisa</b></br></br>Barretta 25gr
{% elif states('sensor.day') == Giovedi and now().hour >= 18 %} </br><b>Cena Mirko</b></br></br>Insalata 200gr</br>Olio 20gr</br>Pollo 170gr</br>Frutta 150gr</br>Pane 100gr</br></br><b>Cena Elisa</b></br></br>Insalata 150gr</br>Olio 15gr</br>Pollo 150gr</br>Frutta 150gr</br>Pane 70gr
{% else %} <b>Errore</b> {{'\U0001F974'}}
{% endif %}
Found the solution: {% if is_state("sensor.day", "Giovedi")
But the problem is, the check for hour. that print the wrong thing based on time:
Check here what i mean: https://postimg.cc/7J01YMcy
Should this work? {{ relative_time(states.vacuum.xiaomi_vacuum_cleaner.clean_stop) }}
Or this {{ relative_time(state_attr('vacuum.xiaomi_vacuum_cleaner', 'clean_stop')) }}
-> Templates and try it out
I did. It did not work. But I figured it out.
I have a template sensor, like this:
value_template: "{{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'clean_stop') }}"```
And then I can put this `{{ relative_time(states.sensor.vacuum_time_last_run.last_updated) }}` into Templates and get the relative time. Yay!
Have tried this some time ago, but was not able to make it work then.
this has prolly been answered before but i can't find it or only get old hits from 2018, so it might have changed... i have a even increasing sensor with khw values that i would like to see consumption per day and i'm trying to use a statistics templata for this but i'm not usre if that's the way to do it, another possible solution might be a history sensor, not sure.
ah! thanks
Would you guys know how i can compare 2 dates and lets say the current date in more than the last changed day by a full day - to display something
- platform: template
sensors:
unraiddock_last_run:
friendly_name: "Dockers"
entity_id: input_boolean.dockerscriptcheck
value_template: '{{as_timestamp(states.input_boolean.dockerscriptcheck.last_changed) | timestamp_custom("%A %d-%b-%y, %H:%M:%S") }}'
this displays the date and time of the last changed - but now i want to compare the day and if the day moves on to lets say Sat
I've got a sensor (time to work) which gives a duration. I can show that duration on my tileboard with:
value: '&sensor.werk.attributes.duration'
The only problem is that I want to round of the duration. So I used a value template for it. But I can't get it to work. The sensor has an attribute with duration.
13.716666666666667```
Added this to the sensor:
```value_template: '{{ value.duration | round(1) }}'```
try {{ state_attr('sensor.werk', 'duration') | float | round(1) }}
any ideas on how i would see if its been 24 hours
{{as_timestamp(now()) | timestamp_custom("%A %d-%b-%y, %H:%M:%S") }} > {{as_timestamp(states.input_boolean.dockerscriptcheck.last_changed) | timestamp_custom("%A %d-%b-%y, %H:%M:%S") }}
from Now to the last.changed time?
I'd check the number of seconds difference
60 (seconds) * 60 (minutes) * 24 (hours) is the difference you're after (taking into account that it may not test right on the second
Hey guys, I need a little help with a value_template validation for a binary_sensor, the json is "status":"enabled" and I am trying to use is_state but I can't get the value json correctly, I am trying this way:value_template: '{{ is_state("value_json.status", "enabled") }}' Clearly I am doing something wrong but I am not sure how to "intercept" that value, any idea?
Is that an attribute of the binary sensor, or what?
Binary sensors are after all only on/off
no, I want to define true/false of the binary sensor
I know, that's why I need to "replace" the enabled to "on"
Ok, well, where is the JSON coming from?
pi-hole
rest api call
I thought that having an is_state matching the value_json.status might return true/false and work with the binary sensor, no?
is_state works with state objects
oh.. makes sense π
Pretty sure that's even explained in the docs π€· might not be though
Jinja π
Found a solution, for anyone interested: value_template: {% if value_json.status == 'enabled' %} true {% else %} false {% endif %}
Thanks @arctic sorrel π
ahj
I thought I did try that :/
that was literally the first thing I tried.. I must have misspelled something without noticing
So I am using the binary_sensor.updater entity to display on my lovelace ui whether there is an update is available. Currently is just shows as On if an update is available, or Off if Home Assistant is up to date. How would I replace these with better terms in lovelace (i.e. On = Update available & Off = Up to date)?
It is in an entities card.
Front end doesn't support templates
So what should I do if I wanted to make the output of the update sensor more readable?
You could probably make a template sensor to make a new entity
Okay, I didn't know that was a thing. Thanks!
For icon_template, am I just able to specify an icon, or does it have to be in the form of a template?
If you just want an icon, why use a template?
Then ... don't define an icon template, just an icon
oh so the sensor works with all standard attributes, plus the ones specifically listed in the documentation?
okay
Any clue why the following doesn't work?
value_template: >-
{% if is_state('binary_sensor.updater', 'true') %}
Update available
{$ else %}
Up to date
{% endif %}
So if the value isn't true, then it should be Up to date, right?
Look at that else line
{% if is_state('binary_sensor.updater', 'on') %}
Update available
{% else %}
Up to date
{% endif %}
That works
{{ "Update available" if is_state('binary_sensor.updater', 'on') else "Up to date" }}
``` is the compact version
ok
thank you
I got this error Invalid config for [sensor.template]: [icon] is an invalid option for [sensor.template].
I thought you said that i could just add an icon?
This is the yaml:```yaml
ha_updates:
friendly_name: "Updates"
icon: mdi:update
@arctic sorrel
~irc @naive gust
@naive gust Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
βοΈ @naive gust
sorry -- matter of habit
Bad habit π
ahhhh
okay
I need an entity ID to do that, but I can't see an option for that in the template integration docs
i do
ahh okay
Basically, what the docs say π
they say three separate things lol
Because there's many things you can do
yeah
Hi
i need help with bolean input, i create virtual switch and i want to have momentary switch, something like push button but without toggle option. any idea?
There's no such concept in HA, what's your goal though?
There may be other ways to achieve this
now i create an automation which call action input boolean to turn of when it appear to be on
its any easier way to do this ?
Do you simply want a button in the UI you can push?
Script
Button card
tap_action
Put all the actions in the script
Have a button card that runs the script with the tap_action
Heck, you probably don't even need the action
Hey all
I've been developing a Healthcare IoT solution for a while now and the core functionality of the application has primarily moved to the MQTT Broker and Automations.
I was curious, does anyone know of a modular service/application/component that serves the same functionality as Automations?
Ideally, a piece of software that listens to a MQTT Channel (would be cool if it had a REST Server too!), allows me to transform the payload (have grown to like Jinja2) and then I can shoot it off with an mqtt.publish
Now that I'm thinking of it, it might be Node-Red?
You could ask the #node-red-archived folks
Hi everyone, first post
How can I display a webpage that requires a username and password login to access the page? I have had success showing a webpage without login using the webpage card, but I am unsure what to add to the code for the login process to happen automatically
If the website requires basic authentication (IE: it pops up a dialog asking for user/pass) then you can pass the user/password via the URL like http:// user : pass @www.domain.com/ (just remove the spaces)
seems discord reformats the url so you cant see what I typed. Let me try that again
hmm doesnt seem to like that. I've used similar for camera streams and it worked well, but not for this page. I can interact with the dialog box and login through the webpage card once it show up....which was my second choice. Thanks LispWarez for the input
i don't think templates is the right place for this question
maybe #frontend-archived can help
hi! i want to create a template sensor is just for the interval between the last and second time a boolean sensor was triggered
so the new sensor should be the time between those
so every time the boolean is triggered this other sensor update with the new interval
if that makes sense?
@ebon yoke You could try something like this: as_timestamp(states.sensor.sensor_name.last_changed) to get the change of the other sensor and now().timestamp() for the currently changed sensor. And calculate difference between them. You can see some examples of playing with time in my switcher sensors, it is different from what you need but there is time difference there. See the Auto Off sensor. https://github.com/dmatik/homeassistant-config/blob/master/homeassistant/config/entities/sensors/sensors_switcher_webapi.yaml
Hi guys, I actually have a question of my own. I write a lot of templates, mostly sensors. Now some of them are really complicated, and I have to reboot every time to check if some change is working. Is there any tool you guys are using for templates development to be able to check and/or even debug to speed up the process? Thanks in advance.
> Templates is probably what you looking for
I need a bit of help..
I set up a scrape sensor that scrapes either 'low' 'moderate' 'high' or 'very high' and would like to template this to 1 through 4 for both graphing and automation use.. anyone who can get me started in the right direction ?
{% set c = {"low": 0, "moderate": 1} %} {{c[value]}}
Do templates work for the image value in the picture entity in lovelace?
That's a #frontend-archived question, but genreally no
Hello I am struggeling to remove decimals from my sensor through a template. What is wrong with: value_template: "{{ ((states.sensor.ruud_s_tesla_s_range_sensor) | float) | int }}"
states.sensor.ruud_s_tesla_s_range_sensor isn't what you want π
Try it in
-> Templates
You wanted
states('sensor.ruud_s_tesla_s_range_sensor')
Thanks Tinkerer.. now have: value_template: "{{ (states.('sensor.ruud_s_tesla_s_range_sensor') | float) | int }}" but HA still does not like it...
All I am trying to do is to make the sensor an "int" as the card does not allow decimal setting...
Look again, what you have is not what Tinkerer said
Always test in the Templates menu
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
You "may" also want to read those
Thanks works now! I see I had a typo when I tried your suggestion.. π Ok, need to figure out how that testing works but sounds good.
Another Templating question: I would like to have a sensor calculate the daily total and then reset. That works fine with the energy sensors under utility_meter. Can I add any sensor there to calculate a daily total ?
~templating @sonic nimbus
@sonic nimbus https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
thanks @arctic sorrel
My new preformulated question shiuld be like service_template: > {% if states('sensor.temperature') | float > 15 %} switch.turn_on {% else %} switch.turn_off {% endif %} entity_id: switch.ac
Yup
I get it, like a variable that I put to entity_id:
you replace switch.ac with the template that produces the entity you want
so, in these if blocks I should add that variable that I will be set later for entity_id
No
entity_id: >-
{% if states('sensor.temperature') | float > 15 %}
switch.ac
{% else %}
switch.dc
{% endif %}
You're going to have errors in your log, and the automation will stop at that point
No further actions in that script/automation will happen
Well, if you've no further actions, it's not the end of the world
ok π
Need help again: I would like to calaculate the sum of a sensor and reset to zero every day. Works perfect with Energy sensors under 'utility_meter'. Does NOT work woith non-energy sensors..
I installed a theme through HACS but it doesnt show up in my choice for themes
#frontend-archived @bitter lagoon that has absolutely nothing to do with templates
oh
I have a binary sensor template Iβm trying to work with and I just canβt find examples of how to work an and statement in with a !=
binary_sensor:
- platform: template
sensors:
someone_home:
friendly_name: "Someone Home"
device_class: presence
value_template: >-
{{ (is_state('person.matt_yette', 'home') and states.sensor.matts_iphone_x_ssid != "V1rus")
or (is_state('person.brittany', 'home') and states.sensor.brittanys_iphone_x_ssid != "V1rus") }}
The ssid != doesnβt seem to be making an impact
Basically if Iβm βhomeβ as far as GPS goes, but if Iβm on a neighbors SSID, I want it to flip this sensor false
The βis_stateβ doesnβt seem to have a βis_not_stateβ option
Both person objects are βhomeβ, but both iPhones are on the V1rus SSId. So I would think it would return false?
@dreamy ember use the same is_state() method for the sensors too but put not first
So βhomeβ) and not is_state(....blah ??
(Truncating beginning and end )
Thank you will try Tediore!
whats wrong with this template to display time.{{ now().strftime(''%I %M %p'') }}
i get this error :Error rendering template: TemplateSyntaxError: expected token ',', got 'string'
{{ now().strftime("%I %M %p") }}
``` or
{{ now().strftime('%I %M %p') }}
but you probably want
{{ now().strftime('%I:%M %p') }}
{% set door_last_changed = states.binary_sensor.spare_bedroom_door.last_changed %}
{% set motion_last_changed = states.binary_sensor.spare_bedroom_motion.last_changed %}
{% set closed_door_motion = (door_last_changed - motion_last_changed).total_seconds() %}
{% if is_state('binary_sensor.spare_bedroom_door', "closed") and
closed_door_motion > 1 %}
Occupied
{%- else -%}
Unoccupied
{%- endif %}
should this not print Occupied if there is motion after the door closes?
oh wait.. I think I see where I stuffed up
turns out I don't...
does the template editor update at all? or is it stuck in time :/
plus I changed it to < 0 because I thought that was the problem
Guys, what's wrong with the following template? {{ states('sensor.efw_stats').split(';')[0] }} It displays correctly in dev tools but throws an error in the config file
it's almost always a matter of how you put it in the config file.. is that the entirety of the template?
Damn, forgot the "" π
is it a sensor?
thanks
it is a mqtt based sensor of CPU idle time. It gets a value in % e.g. '90%'. I would like to express it as cpu usage, but somehow cannot subtract it from 100%.
you need to cast it to an int I think
both of them.. otherwise they're just text
so rip off the % and cast it to int
right! "{{100-(states('sensor.efw_stats').split(';')[2].split('%')[0]|float)}}"
double split did the job π
thanks!
was this the sort of thing you're doing?
{% set stats = '90%' %}
{{ 100 - (stats.split('%')[0]|float) }}%
surprised that idle states don't come in as well.. usually on linux systems they give you EVERYTHING
I had compound data in the payload that I had to extract using split, thus the double split
@edgy dirge both will work π
You can use single or double quotes but not two single quotes
@thorny snow oh I figured that.. I just simplified it for the purposes of clarity.. I need to start doing more templates as I've forgotten way too much :/
@restive flume you might need to convert the last_changed objects to a number before doing math, and closed should be off
off!! crap.. I forgot that!
it's a datetime delta so the math is fine. but I think I messed up the state
yes.. that was it.. Thank you π
will need a bunch more rules to do it properly.. ie opening the door should make it unoccupied..
shouldn't this work
entity_id: light.wled_kitchen_undercabinets
effect: 'Solid'
rgb_color: >-
{% if is_state("sensor.ha_nuc_house_mode_state", "Home") %}
[235,200,145]
{% elif is_state("sensor.ha_nuc_house_mode_state", "Evening Time") %}
[255,190,0]
{% else %}
[255,190,0]
{% endif %}
It doesn't, because those are now strings...
strings.. jinja is all strings
@weary jasper or do this:
rgb_color:
- {{ }}
- {{ }}
- {{ }}
Template the three colors
Looks like your elif is redundant so you could do an inline if check in those templates
well i would except i have already done three of them ....why you so late π€£
Eh, remember for the future I guess lol
hey guys! need some help with a template sensor i created
- platform: template
sensors:
upstairs_cooling_time:
value_template: "{{ state_attr('sensor.ac_usage_today_upstairs', 'value').split('M')[0] | int }}"
``` maybe
3.5 years, give or take
You just need to work through the template problem
As we've no idea what you see, it's hard to help
HI guys. I just integrated my withings scale. on the templating part I made the changes and put it in my sensor folder, but it doesn't convert the Kg to Lbs. I hit check config and got no errors
@silk owl posted a code wall, it is moved here --> https://paste.ubuntu.com/p/MMqrQ2T2Z6/
Sorry, I am very new to this and trying to get some help. I am trying to setup a template to notify me when my abode alarm gets triggered that tells me the "event_name". For example I would like to have "Basement Window Perimeter Alarm Activated" when the above event is seen.
That'd be https://www.home-assistant.io/docs/automation/trigger/#event-trigger on abode_alarm then with the following action:
- service: notify.your_notifier_here
data_template:
message: "{{ trigger.event.data.event_name }}"
``` @silk owl
https://www.home-assistant.io/docs/configuration/templating/#time @gray wharf - you want the timestamp_* filters
Hello Guys, given a timestamp, how do i convert it to date_time object in templates?
oopsy
No, not oopsy, templates π
cant find something that takes the unix timestamp and converts it to datetime object.
parses a string based on a format and returns a datetime object
π€
LoL
nah i won't do that. π
but even if I could use strptime there is no format that tages the timestamp in unix elapsed time from epoch
hmm timestamp_custom looks like a solution
There's a bunch of ways you can do this...
Whatever this really is, since you didn't tell us π
Sorry, i want to get the relative time to the next sunrise
If you've got the next sunrise, then the relative time filter is for you
You may have some tweaking to do, since it's designed for past things, but ... eh
I tried -> {{ relative_time(states.sun.sun.attributes.next_rising) }}
but since next_rising is "string" and relative_time takes "datetime" it won't work
Also I wanted to subtract 40minutes to the next sunrise
still no luck π¦
{{
strptime
(
(
as_timestamp(states.sun.sun.attributes.next_rising) +
(states.input_number.sprinkler_sunsetrise_offset.state |int * 60)
)
| timestamp_custom("%a, %d %b %Y %H:%M:%S +0000"),
"%a, %d %b %Y %H:%M:%S +0000"
)
}}
this returns -> 2020-04-21 05:13:22
which is, by documentation a valid datetimeobject.
If i wrap that in a relative_time then i get "unknown error blabla"
while, ofc, relative_time(now()) works
Did you spot the part where relative_time is only for the past π
It's going to be tricky
You need to have a template that provides a datetime that's as far in the past as your target time is in the future
That's not hard, just fiddly
isnt it possible for me to write my own filter?
Well... yes, but...
Here's an example of a custom filter, and some overhead... https://github.com/thomasloven/hass-lovelace_gen/blob/master/custom_components/lovelace_gen/__init__.py#L15-L16
If that did only adding the filter, I'd say you'd need about 2/3 of that still.
And this method is not guaranteed to work with backend configuration.
Hello,
Question, I have a template sensor that in home assistant has a state to an https link. This link is from an image, it changes over time.
Now I would like to assign this to a photo card is this possible ?
I've already tried
- type: picture-entity style: | ha-card { padding: 8px; background-color: var(--dwains-theme-primary); } entity: sensor.steam_76561198016698912 image: "${states['sensor.steam_game1_image'].state}"
Well, card stuff belongs in #frontend-archived
Pretty sure you've got limited template support there though
What am I missing here?
This:
{{ states('sensor.phoscon_last_update_date') }}
{{ is_state('sensor.phoscon_last_update_date', '2020-03-09') }}
gives:
2020-03-09
False
Expected to be True.
Probably the first returns a datetime object, not a string
How can I read type of object?
The sensor is from the scrape integration, so should be a string.
Now it works. I just rebooted so dont know what was wrong π
I have a question https://pastebin.com/0sdP2GTj
how to combine these two automations into one?
triger numeric_state needs to be like dynamic?
I mean this is working very well, just Im curious how to shrink it into one automation (template probably)
Very roughly ... https://paste.ubuntu.com/p/hsthpJHxyp/
Hi Friends, I am trying to set a binary sensor on based on the timestamps of a switch entity.
But its not working as expected
I am sure that template conditions are good and working as I tested that on developer template
I think I am making mistake on setting binary sensor and using condition on it
Should I add something to set the binary sensor ON ?
a binary sensor can only be on or off
you're also missing - platform: template in your config
(unless that's just missing from your paste for some reason)
Thanks Tediore for your response, yeah thats copy paste mistake.
so in my case, how to on the sensor if my condtion matches
Instead of Tank_full_in_last_10_mins how to set on ?
replace your if line with this:
{{ is_state("switch.bore_tanks", "off") and last_bore_full_time_in_min < 10 }}
and remove everything below that
Thanks Tediore, trying that
Thanks @buoyant pine . Its working perfectly.
I got a false positive here, since restarted the HA its considering the bore-on switch time as last time HA came up
I thought HA would retain original switch state change time, is that not case ?
any thoughts to get original switch last_changed time because its considering HA restart time as last changed ?
Thanks in advance
never-mind, I got answer from https://community.home-assistant.io/t/a-state-timestamp-that-is-not-affected-by-ha-restarts/115822/5
Thanks guys
Hello Tediore, if your still on. I got another interesting behaviour. Noticed that binary_sensor is not turning off even after 10 mins crossed.
π
But If I run the condition check in developer tools, it showing false
Very roughly ... https://paste.ubuntu.com/p/hsthpJHxyp/
@arctic sorrel thanks
~share @oak lava
@oak lava Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs.
Show us what you've got π
Somebody didn't read the templating docs π
Templates with now() do not update when the time changes
{% set last_bore_full_time = (as_timestamp(now()) - as_timestamp(states.switch.bore_tanks.last_changed)) %}
{% set last_bore_full_time_in_min = ((last_bore_full_time / 60)) | int %}
{{ is_state("switch.bore_tanks", "off") and last_bore_full_time_in_min < 10 }}
``` That only updates when `switch.bore_tanks` changes state
oops, sorry
You'd need to use https://www.home-assistant.io/integrations/time_date
okay, do you mean I should call this integration and then instead of now, I should call sensor.time on that template ?
Yes, replace now() with one of those
For instance, if you're using sensor.time
{% set last_bore_full_time = (as_timestamp(states.sensor.time.last_changed) - as_timestamp(states.switch.bore_tanks.last_changed)) %}
cool, trying that. Thanks Tinkerer. I do read the template docs for buliding this code. but didn't note the important point properly π Thanks for letting me know.
To be fair, like many warnings it's only obvious in hindsight
This won't work, right? Including a secret as a substring?
- platform: command_line
command: curl -sL !secret backyard_still 2>&1 | md5sum | cut -d ' ' -f 1
name: backyard md5
scan_interval: 300
trying to detect "stuck" video streams
Nope, won't work, you need to put the whole thing in the secret
That's what I thought, thanks
Yes, replace
now()with one of those
@arctic sorrel Thanks its working perfectly now π
Trying to create a binary sensor that will show the state of a garage door (open/closed) and a momentary switch will toggle it. This is what I came up with but it's not working: https://paste.ubuntu.com/p/zKMgk5mQGx/
The error I get is: invalid config for sensor
This is returning "None", what do i have wrong?
{{ as_timestamp(states.sensor.date_time.state) | timestamp_custom('%-I:%M %P') }}
I assumed I needed a binary switch and then in an automation I will create will do the toggling of that binary switch between open and closed.
The indentation is correct, just not in the pastebin
That should be a binary sensor, not a sensor π
Also, if you set the device class the icon will change automatically
The value template is wrong though, it's not a template
garage_door_status:
friendly_name: "Garage Door Status"
device_class: garage_door
value_template: '{{ SOME ACTUAL TEMPLATE HERE }}'
2020-04-20 09:18:29 ERROR (MainThread) [homeassistant.components.sensor] command_line: Error on device update!
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 324, in _async_add_entity
await entity.async_device_update(warning=False)
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 476, in async_device_update
await self.hass.async_add_executor_job(self.update)
File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/homeassistant/homeassistant/components/command_line/sensor.py", line 101, in update
self.data.update()
File "/usr/src/homeassistant/homeassistant/components/command_line/sensor.py", line 180, in update
self.value = return_value.strip().decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 33: invalid start byte
My secret backyard_md5: 'curl -sL http://view:viewpassword@localhost:7001/ec2/cameraThumbnail?cameraId=0eb24232-d7d5-60d3-3bdc-d499b3fdcd0f&time=now 2>&1 | md5sum | cut -d '' '' -f 1'
Do I maybe need to escape something?
That should be a binary sensor, not a sensor π
@arctic sorrel Ha, yeah, that's a pretty fundamental mistake.
-> Customizing